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

+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;`;