Files
o2o-weather/frontend/src/lib/platform.ts
T

143 lines
6.5 KiB
TypeScript

/** 웹/앱인토스/날씨각 안드로이드 앱(웹뷰) 차이를 모으는 곳. 토스 SDK 는 토스 빌드(`vite build --mode toss`)에서만 불러온다 */
export const IS_TOSS = import.meta.env.MODE === 'toss'
/** 날씨각 안드로이드 앱의 웹뷰 안인지. 앱이 user agent 끝에 NalssigakApp/버전을 붙인다 (mobile/src/components/web-shell.tsx) */
const APP_UA = typeof navigator === 'undefined' ? null : /NalssigakApp\/([\w.-]+)/.exec(navigator.userAgent)
export const IS_APP = APP_UA !== null
export const APP_VERSION = APP_UA?.[1] ?? ''
const TOSS_APP = 'intoss://nalssigak'
// 웹 빌드에서는 이 분기가 지워져 SDK 가 번들에 들어가지 않는다
const sdk = () => (import.meta.env.MODE === 'toss' ? import('@apps-in-toss/web-framework') : Promise.reject(new Error('토스 앱 밖에서는 쓸 수 없어요')))
function toBase64(blob: Blob): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onload = () => resolve(String(reader.result).split(',')[1] ?? '')
reader.onerror = () => reject(reader.error)
reader.readAsDataURL(blob)
})
}
/** 토스: 이미지를 기기에 저장하고 토스 앱 링크를 공유창으로 보낸다 */
export async function tossShare(image: Blob, fileName: string, title: string): Promise<'saved' | 'link-only'> {
const { File, Share } = await sdk()
let saved = false
if (File.saveBase64.isSupported()) {
await File.saveBase64({ data: await toBase64(image), fileName, mimeType: image.type })
saved = true
}
const link = await Share.createLink({ path: TOSS_APP })
await Share.sendMessage({ message: `${title} · 날씨각 ${link}` })
return saved ? 'saved' : 'link-only'
}
/** 토스: 토스 로그인 창을 띄우고 서버로 보낼 인가 코드를 받는다 */
export async function tossLogin() {
const { TossAuth } = await sdk()
return TossAuth.login()
}
export type TossLocation = { lat: number; lon: number } | 'denied'
/** 토스: 위치를 읽는다. 권한이 없으면 ask 일 때만 권한 창을 띄운다 */
export async function tossLocation(ask: boolean): Promise<TossLocation | null> {
const { Accuracy, Device } = await sdk()
let status = await Device.getLocation.getPermission()
if (status !== 'allowed' && ask) status = await Device.getLocation.openPermissionDialog()
if (status !== 'allowed') return ask ? 'denied' : null
const { coords } = await Device.getLocation({ accuracy: Accuracy.Balanced })
return { lat: coords.latitude, lon: coords.longitude }
}
/* ---------- 앱 브리지: 웹이 앱(네이티브)에 일을 시키고 답을 받는다 ---------- */
type AppReply = { id: number; ok: boolean; data?: unknown; error?: string }
type Pending = { resolve: (data: unknown) => void; reject: (e: Error) => void; timer: ReturnType<typeof setTimeout> }
declare global {
interface Window {
ReactNativeWebView?: { postMessage: (message: string) => void }
__nalssigakReply?: (reply: AppReply) => void
}
}
const pending = new Map<number, Pending>()
let seq = 0
// 앱이 일을 마치면 이 함수를 불러 답을 넘긴다 (web-shell 의 injectJavaScript)
if (IS_APP) {
window.__nalssigakReply = (reply) => {
const p = pending.get(reply.id)
if (!p) return
pending.delete(reply.id)
clearTimeout(p.timer)
if (reply.ok) p.resolve(reply.data)
else p.reject(new Error(reply.error ?? '앱이 요청을 처리하지 못했어요'))
}
}
/** 앱에 요청 하나를 보내고 답을 기다린다. 앱 밖이거나 timeoutMs 안에 답이 없으면 실패한다 */
function callApp<T>(type: string, payload: unknown, timeoutMs: number): Promise<T> {
const bridge = window.ReactNativeWebView
if (!IS_APP || !bridge) return Promise.reject(new Error('앱 밖에서는 쓸 수 없어요'))
return new Promise<T>((resolve, reject) => {
const id = ++seq
const timer = setTimeout(() => {
pending.delete(id)
reject(new Error(`앱이 ${type} 에 답하지 않아요`))
}, timeoutMs)
pending.set(id, { resolve: (data) => resolve(data as T), reject, timer })
bridge.postMessage(JSON.stringify({ id, type, payload }))
})
}
/** 앱: 구글 계정 선택창을 띄우고 서버로 보낼 ID 토큰을 받는다. 사용자가 닫으면 null */
export function appGoogleLogin(clientId: string): Promise<{ idToken: string } | null> {
return callApp('googleLogin', { clientId }, 180_000)
}
/** 앱으로 넘기는 공유 이미지의 목표 크기(바이트). 브리지 메시지(base64)가 커지면 저사양 폰에서 멈칫하므로 줄여 보낸다 */
const APP_SHARE_TARGET_BYTES = 700_000
const APP_SHARE_QUALITIES = [0.85, 0.72, 0.6, 0.48]
/** PNG 공유 이미지를 JPEG 로 줄인다. 목표 크기 안에 들어오는 가장 높은 품질을 쓰고, 끝까지 크면 가장 작은 것을 쓴다 */
async function shrinkForApp(image: Blob): Promise<Blob> {
const bitmap = await createImageBitmap(image)
try {
const canvas = document.createElement('canvas')
canvas.width = bitmap.width
canvas.height = bitmap.height
const ctx = canvas.getContext('2d')
if (!ctx) throw new Error('canvas 2d context unavailable')
// JPEG 는 투명이 없어 흰 바탕을 깐다 (공유 이미지는 배경을 꽉 채워 보통 보이지 않음)
ctx.fillStyle = '#fff'
ctx.fillRect(0, 0, canvas.width, canvas.height)
ctx.drawImage(bitmap, 0, 0)
let smallest: Blob | null = null
for (const quality of APP_SHARE_QUALITIES) {
const jpeg = await new Promise<Blob>((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('toBlob failed'))), 'image/jpeg', quality))
if (jpeg.size <= APP_SHARE_TARGET_BYTES) return jpeg
if (!smallest || jpeg.size < smallest.size) smallest = jpeg
}
return smallest!
} finally {
bitmap.close()
}
}
export type AppLocation = { lat: number; lon: number } | 'denied'
/** 앱: 지금 위치를 읽는다. ask 면 권한이 없을 때 권한 창을 띄우고, 아니면 이미 허용한 경우에만 읽고 그 밖에는 null */
export function appLocation(ask: boolean): Promise<AppLocation | null> {
return callApp('location', { ask }, 60_000)
}
/** 앱: 이미지를 줄여 넘기고 앱의 공유창을 띄운다. 공유창이 닫히면 true (보냈는지는 앱도 알 수 없다) */
export async function appShare(image: Blob, fileName: string, title: string): Promise<boolean> {
const jpeg = await shrinkForApp(image)
const data = await toBase64(jpeg)
return callApp<boolean>('share', { data, mimeType: jpeg.type, fileName: fileName.replace(/\.\w+$/, '.jpg'), title }, 600_000)
}