feat: 앱을 날씨각 웹(weather.o2o.kr)을 띄우는 웹뷰 셸로 전환 (안드로이드) — 전체 화면 웹뷰·뒤로 가기·실패 화면, 구글 로그인·위치·공유 브리지, 앱 링크(assetlinks·인텐트 필터)·nalssigak:// 링크 열기, 안전 영역은 웹이 처리하도록 패딩 없음. 푸시·iOS 는 제외, expo-file-system 추가

This commit is contained in:
skkim committed 2026-11-13 13:45:57 +09:00
1 parent 2a94ebe85b
commit a228fcf560
8 files changed
+288 -46

No files matched your search

@@ -0,0 +1,10 @@
[
{
"relation": ["delegate_permission/common.handle_all_urls"],
"target": {
"namespace": "android_app",
"package_name": "kr.o2o.nalssigak",
"sha256_cert_fingerprints": ["A8:AB:9E:E2:CF:BA:38:22:91:4D:82:4C:C2:50:AB:2A:85:2E:42:9C:0C:E3:D5:5F:AE:0C:C1:DE:60:95:07:DF"]
}
}
]
+8
View File
@@ -22,6 +22,14 @@
"monochromeImage": "./assets/images/android-icon-monochrome.png"
},
"predictiveBackGestureEnabled": false,
"intentFilters": [
{
"action": "VIEW",
"autoVerify": true,
"data": [{ "scheme": "https", "host": "weather.o2o.kr" }],
"category": ["BROWSABLE", "DEFAULT"]
}
],
"permissions": [
"android.permission.ACCESS_COARSE_LOCATION"
],
+1
View File
@@ -13,6 +13,7 @@
"expo": "~57.0.28",
"expo-constants": "~57.0.21",
"expo-device": "~57.0.2",
"expo-file-system": "~57.0.7",
"expo-font": "~57.0.4",
"expo-glass-effect": "~57.0.4",
"expo-image": "~57.0.5",
+8
View File
@@ -0,0 +1,8 @@
/**
* 들어오는 링크(nalssigak://…, https://weather.o2o.kr/…)를 Expo Router 경로로 읽지 않고 항상 '/' 로 돌린다.
* 안 그러면 사이트 주소(/today/…)가 앱 경로로 읽혀 'Unmatched Route' 화면이 셸을 덮는다.
* 링크는 웹 셸(components/web-shell.tsx)이 Linking 으로 직접 받아 웹뷰에서 연다.
*/
export function redirectSystemPath() {
return '/';
}
+17 -46
View File
@@ -1,59 +1,30 @@
import '@/lib/api';
import { BagelFatOne_400Regular } from '@expo-google-fonts/bagel-fat-one';
import { GowunBatang_400Regular } from '@expo-google-fonts/gowun-batang';
import { Jua_400Regular, useFonts } from '@expo-google-fonts/jua';
import { QueryClientProvider } from '@tanstack/react-query';
import { Stack } from 'expo-router';
import * as SplashScreen from 'expo-splash-screen';
import { StatusBar } from 'expo-status-bar';
import { useEffect } from 'react';
import { View } from 'react-native';
import { useCallback, useEffect } from 'react';
import '@/global.css';
import { SkyBg } from '@/components/sky-bg';
import { FirstLoad } from '@/components/first-load';
import { SheetProvider } from '@/components/sheets';
import { AuthProvider } from '@/lib/auth';
import { LevelWatcher } from '@/lib/level';
import { queryClient } from '@/lib/query-client';
import { RegionProvider } from '@/lib/region';
import { SkyProvider, useSky } from '@/lib/sky';
import { WebShell } from '@/components/web-shell';
SplashScreen.preventAutoHideAsync();
function Shell() {
const { kind } = useSky();
return (
<View className="flex-1">
<SkyBg />
<StatusBar style={kind === 'night' ? 'light' : 'dark'} />
{/* 탭 묶음 위에 사주·게임 같은 탭 밖 화면이 쌓인다. 하늘 배경이 비치게 화면 바탕은 투명 */}
<Stack screenOptions={{ headerShown: false, contentStyle: { backgroundColor: 'transparent' } }}>
<Stack.Screen name="(tabs)" />
</Stack>
<FirstLoad />
</View>
);
}
/** 웹이 뜨지 않아도 시작 화면에 갇히지 않게 하는 최대 대기 시간 */
const SPLASH_MAX_MS = 8000;
/** 앱은 날씨각 웹을 띄우는 껍데기 하나뿐이다. 화면 이동은 모두 웹이 한다 */
export default function RootLayout() {
const [loaded, error] = useFonts({ Jua_400Regular, BagelFatOne_400Regular, GowunBatang_400Regular });
const hideSplash = useCallback(() => {
SplashScreen.hideAsync().catch((e: unknown) => console.warn('[splash] 숨기지 못함', e));
}, []);
useEffect(() => {
if (loaded || error) SplashScreen.hideAsync();
}, [loaded, error]);
if (!loaded && !error) return null;
const t = setTimeout(hideSplash, SPLASH_MAX_MS);
return () => clearTimeout(t);
}, [hideSplash]);
return (
<QueryClientProvider client={queryClient}>
<SkyProvider>
<AuthProvider>
<RegionProvider>
<SheetProvider>
<LevelWatcher />
<Shell />
</SheetProvider>
</RegionProvider>
</AuthProvider>
</SkyProvider>
</QueryClientProvider>
<>
<StatusBar style="dark" />
<WebShell onReady={hideSplash} />
</>
);
}
+135
View File
@@ -0,0 +1,135 @@
import Constants from 'expo-constants';
import { useCallback, useEffect, useRef, useState } from 'react';
import { ActivityIndicator, BackHandler, Linking, Pressable, View } from 'react-native';
import { WebView, type WebViewMessageEvent, type WebViewNavigation } from 'react-native-webview';
import { Text } from '@/components/text';
import { SITE_URL } from '@/lib/site';
import { handleRequest, parseRequest, replyScript } from '@/lib/web-bridge';
const SITE_ORIGIN = new URL(SITE_URL).origin;
/** 웹 첫 화면(하늘색)과 맞춰, 웹이 뜨기 전에 흰 화면이 비치지 않게 한다 */
const BG = '#d6ebff';
/** 웹이 앱 안인지 알아보는 표시. 웹뷰 기본 user agent 뒤에 붙는다 (예: NalssigakApp/1.1.0) */
const APP_UA = `NalssigakApp/${Constants.expoConfig?.version ?? '0'}`;
/** 앱 링크(https://weather.o2o.kr/…)와 앱 주소(nalssigak://today/…)를 사이트 주소로 바꾼다. 날씨각 주소가 아니면 null */
function toSiteUrl(link: string): string | null {
const scheme = /^nalssigak:\/\/(.*)$/.exec(link);
const url = scheme ? `${SITE_URL}/${scheme[1]}` : link;
try {
return new URL(url).origin === SITE_ORIGIN ? url : null;
} catch {
return null;
}
}
function LoadFailed({ onRetry }: { onRetry: () => void }) {
return (
<View className="absolute inset-0 items-center justify-center px-6" style={{ backgroundColor: BG }}>
<Text className="text-center text-[15px] font-bold text-ink2">날씨를 불러오지 못했어요. 인터넷 연결을 확인하고 다시 시도해 주세요.</Text>
<Pressable onPress={onRetry} accessibilityRole="button" className="mt-5 rounded-full bg-white px-6 py-3">
<Text className="text-[15px] font-extrabold text-[#28304a]">다시 불러오기</Text>
</Pressable>
</View>
);
}
/**
* 날씨각 웹(weather.o2o.kr)을 전체 화면으로 띄우는 앱 껍데기.
* 화면은 모두 웹이 그리고, 앱은 뒤로 가기·불러오기 실패 화면만 맡는다.
* 웹뷰는 상태바·내비게이션 바 아래까지 꽉 채운다: 웹이 env(safe-area-inset-*)로 위아래 여백을 직접 두므로 앱이 또 패딩을 주면 이중 여백이 생긴다.
* 날씨각 사이트 밖 주소(tel:, mailto:, 다른 사이트)는 웹뷰 라이브러리가 휴대폰 앱·브라우저로 넘긴다 (originWhitelist).
*/
export function WebShell({ onReady }: { onReady: () => void }) {
const webView = useRef<WebView>(null);
const canGoBack = useRef(false);
const ready = useRef(false);
// 불러오기 실패·웹뷰 프로세스 종료 뒤 다시 시도하려고 웹뷰를 새로 띄운다
const [attempt, setAttempt] = useState(0);
// 링크로 열렸으면 그 주소로, 아니면 홈으로 시작한다. 첫 주소를 알기 전에는 웹뷰를 띄우지 않는다
const [startUri, setStartUri] = useState<string | null>(null);
// 웹이 한 번 뜨거나(성공·실패) 앱 시작 화면을 걷는다
const markReady = useCallback(() => {
if (ready.current) return;
ready.current = true;
onReady();
}, [onReady]);
// 웹 안에서 이동한 기록이 있으면 안드로이드 뒤로 가기는 앱을 닫지 않고 웹 뒤로 간다
useEffect(() => {
const sub = BackHandler.addEventListener('hardwareBackPress', () => {
if (!canGoBack.current) return false;
webView.current?.goBack();
return true;
});
return () => sub.remove();
}, []);
useEffect(() => {
let alive = true;
Linking.getInitialURL().then(
(link) => alive && setStartUri((link && toSiteUrl(link)) ?? SITE_URL),
(e: unknown) => {
console.warn('[shell] 처음 링크를 읽지 못함', e);
if (alive) setStartUri(SITE_URL);
},
);
// 앱이 떠 있는 동안 링크를 누르면 지금 화면에서 그 주소로 옮겨 간다
const sub = Linking.addEventListener('url', ({ url }) => {
const target = toSiteUrl(url);
if (target) webView.current?.injectJavaScript(`location.assign(${JSON.stringify(target)}); true;`);
});
return () => {
alive = false;
sub.remove();
};
}, []);
const retry = useCallback(() => setAttempt((n) => n + 1), []);
const onNavigationStateChange = useCallback((nav: WebViewNavigation) => {
canGoBack.current = nav.canGoBack;
}, []);
// 날씨각 사이트에서 온 요청만 처리한다 (다른 주소의 페이지가 로그인 같은 네이티브 기능을 부르지 못하게)
const onMessage = useCallback((e: WebViewMessageEvent) => {
let origin: string;
try {
origin = new URL(e.nativeEvent.url).origin;
} catch {
return;
}
if (origin !== SITE_ORIGIN) return;
const req = parseRequest(e.nativeEvent.data);
if (!req) return;
void handleRequest(req).then((reply) => webView.current?.injectJavaScript(replyScript(reply)));
}, []);
return (
<View className="flex-1" style={{ backgroundColor: BG }}>
{startUri && (
<WebView
key={attempt}
ref={webView}
source={{ uri: startUri }}
originWhitelist={[SITE_ORIGIN]}
applicationNameForUserAgent={APP_UA}
onNavigationStateChange={onNavigationStateChange}
onMessage={onMessage}
onLoadEnd={markReady}
onRenderProcessGone={retry}
renderError={() => <LoadFailed onRetry={retry} />}
renderLoading={() => <ActivityIndicator style={{ position: 'absolute', top: '45%', alignSelf: 'center' }} />}
startInLoadingState
setSupportMultipleWindows={false}
overScrollMode="never"
bounces={false}
style={{ backgroundColor: BG }}
/>
)}
</View>
);
}
+108
View File
@@ -0,0 +1,108 @@
import { GoogleSignin, isErrorWithCode, isSuccessResponse, statusCodes } from '@react-native-google-signin/google-signin';
import { File, Paths } from 'expo-file-system';
import * as Location from 'expo-location';
import * as Sharing from 'expo-sharing';
/**
* 웹(frontend/src/lib/platform.ts)이 앱에 시키는 일.
* 웹 → 앱: window.ReactNativeWebView.postMessage(JSON {id, type, payload})
* 앱 → 웹: window.__nalssigakReply({id, ok, data | error}) (replyScript)
* 메시지 형식을 바꿀 때는 이미 설치된 앱(옛 셸)이 깨지지 않게 type 을 새로 만든다.
*/
type Request = { id: number; type: string; payload: unknown };
export type Reply = { id: number; ok: boolean; data?: unknown; error?: string };
/** 웹이 보낸 문자열을 요청으로 읽는다. 형식이 다르면 null (날씨각 웹이 보낸 게 아닌 메시지) */
export function parseRequest(raw: string): Request | null {
try {
const v: unknown = JSON.parse(raw);
if (typeof v !== 'object' || v === null) return null;
const { id, type, payload } = v as Record<string, unknown>;
return typeof id === 'number' && typeof type === 'string' ? { id, type, payload } : null;
} catch {
// JSON 이 아닌 메시지는 이 브리지 것이 아니니 무시한다
return null;
}
}
/** 구글 계정 선택창 → ID 토큰. 사용자가 닫으면 null */
async function googleLogin(payload: unknown) {
const clientId = (payload as { clientId?: unknown } | null)?.clientId;
if (typeof clientId !== 'string' || !clientId) throw new Error('clientId 가 없어요');
GoogleSignin.configure({ webClientId: clientId });
await GoogleSignin.hasPlayServices({ showPlayServicesUpdateDialog: true });
try {
const res = await GoogleSignin.signIn();
if (!isSuccessResponse(res)) return null;
if (!res.data.idToken) throw new Error('구글이 ID 토큰을 주지 않았어요');
return { idToken: res.data.idToken };
} catch (e) {
if (isErrorWithCode(e) && e.code === statusCodes.SIGN_IN_CANCELLED) return null;
throw e;
}
}
/** 위치를 못 잡으면(실내·에뮬레이터) 끝없이 기다리지 않게 10초에 끊는다 */
function withTimeout<T>(p: Promise<T>, ms: number): Promise<T> {
return Promise.race([p, new Promise<never>((_, reject) => setTimeout(() => reject(new Error('위치 찾기 시간 초과')), ms))]);
}
/**
* 지금 위치. ask 면 권한이 없을 때 권한 창을 띄우고, 거부하면 'denied'.
* ask 가 아니면 이미 허용한 경우에만 읽고, 아니면 null (권한 창 없이 조용히 넘어감).
* 웹뷰의 navigator.geolocation 은 앱이 막아 둔 정밀 위치(FINE) 때문에 권한 창이 안 떠서 앱이 대신 읽는다.
*/
async function location(payload: unknown) {
const ask = (payload as { ask?: unknown } | null)?.ask === true;
let permission = await Location.getForegroundPermissionsAsync();
if (!permission.granted && ask && permission.canAskAgain) permission = await Location.requestForegroundPermissionsAsync();
if (!permission.granted) return ask ? 'denied' : null;
const pos = (await Location.getLastKnownPositionAsync({ maxAge: 600_000 })) ?? (await withTimeout(Location.getCurrentPositionAsync({ accuracy: Location.Accuracy.Balanced }), 10_000));
return { lat: pos.coords.latitude, lon: pos.coords.longitude };
}
/** 웹이 넘기는 공유 이미지(base64)의 상한. 웹이 700KB 안팎으로 줄여 보내지만, 이상한 요청이 메모리를 먹지 않게 막는다 */
const SHARE_MAX_BASE64 = 6_000_000;
const SHARE_MIME = ['image/jpeg', 'image/png'];
/** 직전 공유 이미지. 공유창이 닫힌 뒤에도 받는 앱이 파일을 읽을 수 있어서, 다음 공유 때 지운다 */
let lastShared: File | null = null;
/** 웹이 넘긴 이미지를 캐시 폴더에 파일로 저장해 휴대폰 공유창을 띄운다. 공유창이 닫히면 true */
async function share(payload: unknown) {
const { data, mimeType, fileName, title } = (payload ?? {}) as Record<string, unknown>;
if (typeof data !== 'string' || !data || data.length > SHARE_MAX_BASE64) throw new Error('공유할 이미지가 올바르지 않아요');
if (typeof mimeType !== 'string' || !SHARE_MIME.includes(mimeType)) throw new Error('지원하지 않는 이미지 형식이에요');
if (!(await Sharing.isAvailableAsync())) throw new Error('이 기기에서는 공유할 수 없어요');
// 웹이 준 이름은 경로 문자를 걷어 내고 쓴다
const safeName = String(typeof fileName === 'string' ? fileName : 'share.jpg').replace(/[^\w.-]/g, '_').slice(-60);
if (lastShared?.exists) lastShared.delete();
const file = new File(Paths.cache, `share-${Date.now()}-${safeName}`);
lastShared = file;
file.create({ overwrite: true });
file.write(data, { encoding: 'base64' });
await Sharing.shareAsync(file.uri, { mimeType, dialogTitle: typeof title === 'string' ? title : undefined });
return true;
}
const handlers: Record<string, (payload: unknown) => Promise<unknown>> = {
googleLogin,
location,
share,
};
/** 요청 하나를 처리해 웹에 돌려줄 답을 만든다. 모르는 type 이나 실패는 ok: false */
export async function handleRequest(req: Request): Promise<Reply> {
const handler = handlers[req.type];
if (!handler) return { id: req.id, ok: false, error: `모르는 요청: ${req.type}` };
try {
return { id: req.id, ok: true, data: await handler(req.payload) };
} catch (e) {
console.warn('[bridge]', req.type, e);
return { id: req.id, ok: false, error: e instanceof Error ? e.message : String(e) };
}
}
/** 답을 웹 페이지 안에서 실행할 스크립트로 만든다 */
export const replyScript = (reply: Reply) => `window.__nalssigakReply && window.__nalssigakReply(${JSON.stringify(reply)}); true;`;
+1
View File
@@ -51,6 +51,7 @@
"expo": "~57.0.28",
"expo-constants": "~57.0.21",
"expo-device": "~57.0.2",
"expo-file-system": "~57.0.7",
"expo-font": "~57.0.4",
"expo-glass-effect": "~57.0.4",
"expo-image": "~57.0.5",