From a228fcf5608d02c23a6b7e1c4ccc402da2884693 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=84=B1=EA=B2=BD?= Date: Fri, 13 Nov 2026 13:45:57 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=EC=95=B1=EC=9D=84=20=EB=82=A0=EC=94=A8?= =?UTF-8?q?=EA=B0=81=20=EC=9B=B9(weather.o2o.kr)=EC=9D=84=20=EB=9D=84?= =?UTF-8?q?=EC=9A=B0=EB=8A=94=20=EC=9B=B9=EB=B7=B0=20=EC=85=B8=EB=A1=9C=20?= =?UTF-8?q?=EC=A0=84=ED=99=98=20(=EC=95=88=EB=93=9C=EB=A1=9C=EC=9D=B4?= =?UTF-8?q?=EB=93=9C)=20=E2=80=94=20=EC=A0=84=EC=B2=B4=20=ED=99=94?= =?UTF-8?q?=EB=A9=B4=20=EC=9B=B9=EB=B7=B0=C2=B7=EB=92=A4=EB=A1=9C=20?= =?UTF-8?q?=EA=B0=80=EA=B8=B0=C2=B7=EC=8B=A4=ED=8C=A8=20=ED=99=94=EB=A9=B4?= =?UTF-8?q?,=20=EA=B5=AC=EA=B8=80=20=EB=A1=9C=EA=B7=B8=EC=9D=B8=C2=B7?= =?UTF-8?q?=EC=9C=84=EC=B9=98=C2=B7=EA=B3=B5=EC=9C=A0=20=EB=B8=8C=EB=A6=AC?= =?UTF-8?q?=EC=A7=80,=20=EC=95=B1=20=EB=A7=81=ED=81=AC(assetlinks=C2=B7?= =?UTF-8?q?=EC=9D=B8=ED=85=90=ED=8A=B8=20=ED=95=84=ED=84=B0)=C2=B7nalssiga?= =?UTF-8?q?k://=20=EB=A7=81=ED=81=AC=20=EC=97=B4=EA=B8=B0,=20=EC=95=88?= =?UTF-8?q?=EC=A0=84=20=EC=98=81=EC=97=AD=EC=9D=80=20=EC=9B=B9=EC=9D=B4=20?= =?UTF-8?q?=EC=B2=98=EB=A6=AC=ED=95=98=EB=8F=84=EB=A1=9D=20=ED=8C=A8?= =?UTF-8?q?=EB=94=A9=20=EC=97=86=EC=9D=8C.=20=ED=91=B8=EC=8B=9C=C2=B7iOS?= =?UTF-8?q?=20=EB=8A=94=20=EC=A0=9C=EC=99=B8,=20expo-file-system=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/public/.well-known/assetlinks.json | 10 ++ mobile/app.json | 8 ++ mobile/package.json | 1 + mobile/src/app/+native-intent.tsx | 8 ++ mobile/src/app/_layout.tsx | 63 +++------ mobile/src/components/web-shell.tsx | 135 ++++++++++++++++++++ mobile/src/lib/web-bridge.ts | 108 ++++++++++++++++ package-lock.json | 1 + 8 files changed, 288 insertions(+), 46 deletions(-) create mode 100644 frontend/public/.well-known/assetlinks.json create mode 100644 mobile/src/app/+native-intent.tsx create mode 100644 mobile/src/components/web-shell.tsx create mode 100644 mobile/src/lib/web-bridge.ts diff --git a/frontend/public/.well-known/assetlinks.json b/frontend/public/.well-known/assetlinks.json new file mode 100644 index 0000000..29261e1 --- /dev/null +++ b/frontend/public/.well-known/assetlinks.json @@ -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"] + } + } +] diff --git a/mobile/app.json b/mobile/app.json index 93437f3..e906f3b 100644 --- a/mobile/app.json +++ b/mobile/app.json @@ -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" ], diff --git a/mobile/package.json b/mobile/package.json index 712a45e..07db5b2 100644 --- a/mobile/package.json +++ b/mobile/package.json @@ -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", diff --git a/mobile/src/app/+native-intent.tsx b/mobile/src/app/+native-intent.tsx new file mode 100644 index 0000000..eb63835 --- /dev/null +++ b/mobile/src/app/+native-intent.tsx @@ -0,0 +1,8 @@ +/** + * 들어오는 링크(nalssigak://…, https://weather.o2o.kr/…)를 Expo Router 경로로 읽지 않고 항상 '/' 로 돌린다. + * 안 그러면 사이트 주소(/today/…)가 앱 경로로 읽혀 'Unmatched Route' 화면이 셸을 덮는다. + * 링크는 웹 셸(components/web-shell.tsx)이 Linking 으로 직접 받아 웹뷰에서 연다. + */ +export function redirectSystemPath() { + return '/'; +} diff --git a/mobile/src/app/_layout.tsx b/mobile/src/app/_layout.tsx index 444dbc4..a07f22d 100644 --- a/mobile/src/app/_layout.tsx +++ b/mobile/src/app/_layout.tsx @@ -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 ( - - - - {/* 탭 묶음 위에 사주·게임 같은 탭 밖 화면이 쌓인다. 하늘 배경이 비치게 화면 바탕은 투명 */} - - - - - - ); -} +/** 웹이 뜨지 않아도 시작 화면에 갇히지 않게 하는 최대 대기 시간 */ +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 ( - - - - - - - - - - - - + <> + + + ); } diff --git a/mobile/src/components/web-shell.tsx b/mobile/src/components/web-shell.tsx new file mode 100644 index 0000000..c0a7f86 --- /dev/null +++ b/mobile/src/components/web-shell.tsx @@ -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 ( + + 날씨를 불러오지 못했어요. 인터넷 연결을 확인하고 다시 시도해 주세요. + + 다시 불러오기 + + + ); +} + +/** + * 날씨각 웹(weather.o2o.kr)을 전체 화면으로 띄우는 앱 껍데기. + * 화면은 모두 웹이 그리고, 앱은 뒤로 가기·불러오기 실패 화면만 맡는다. + * 웹뷰는 상태바·내비게이션 바 아래까지 꽉 채운다: 웹이 env(safe-area-inset-*)로 위아래 여백을 직접 두므로 앱이 또 패딩을 주면 이중 여백이 생긴다. + * 날씨각 사이트 밖 주소(tel:, mailto:, 다른 사이트)는 웹뷰 라이브러리가 휴대폰 앱·브라우저로 넘긴다 (originWhitelist). + */ +export function WebShell({ onReady }: { onReady: () => void }) { + const webView = useRef(null); + const canGoBack = useRef(false); + const ready = useRef(false); + // 불러오기 실패·웹뷰 프로세스 종료 뒤 다시 시도하려고 웹뷰를 새로 띄운다 + const [attempt, setAttempt] = useState(0); + // 링크로 열렸으면 그 주소로, 아니면 홈으로 시작한다. 첫 주소를 알기 전에는 웹뷰를 띄우지 않는다 + const [startUri, setStartUri] = useState(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 ( + + {startUri && ( + } + renderLoading={() => } + startInLoadingState + setSupportMultipleWindows={false} + overScrollMode="never" + bounces={false} + style={{ backgroundColor: BG }} + /> + )} + + ); +} diff --git a/mobile/src/lib/web-bridge.ts b/mobile/src/lib/web-bridge.ts new file mode 100644 index 0000000..a305cf8 --- /dev/null +++ b/mobile/src/lib/web-bridge.ts @@ -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; + 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(p: Promise, ms: number): Promise { + return Promise.race([p, new Promise((_, 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; + 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 Promise> = { + googleLogin, + location, + share, +}; + +/** 요청 하나를 처리해 웹에 돌려줄 답을 만든다. 모르는 type 이나 실패는 ok: false */ +export async function handleRequest(req: Request): Promise { + 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;`; diff --git a/package-lock.json b/package-lock.json index 6f11819..e0a0a74 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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",