feat: 웹이 앱(웹뷰 셸) 안인지 알아보고 앱 브리지로 구글 로그인·위치·공유를 처리 — user agent NalssigakApp/ 로 감지, 공유 이미지는 JPEG 로 줄여 전달, 앱 안에서는 설치 배너 숨김 (GA app_launch android_app, app_bridge_error, platform android_app)
This commit is contained in:
1 parent
c8287b4bf3
commit
2a94ebe85b
9 files changed
+204
-19
No files matched your search
@@ -30,7 +30,7 @@ import {
|
||||
} from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||
import { AuthProvider, ReportReason, type CommentData, type Factor, type ResAuth, type ResCommentList, type ResIndexDetail } from '@nalssigak/shared/api/client/types.gen'
|
||||
import { track } from '../lib/analytics'
|
||||
import { IS_TOSS, tossLogin, tossShare } from '../lib/platform'
|
||||
import { appShare, IS_APP, IS_TOSS, tossLogin, tossShare } from '../lib/platform'
|
||||
import { cx } from '../lib/utils'
|
||||
import { useAuth } from './authContext'
|
||||
import { ago, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from '@nalssigak/shared/lib'
|
||||
@@ -694,6 +694,29 @@ function ShareSheet({ share }: { share: SharePayload }) {
|
||||
)
|
||||
return
|
||||
}
|
||||
if (IS_APP) {
|
||||
// 앱 웹뷰는 navigator.share 가 없어, 이미지를 줄여 앱에 넘기고 앱의 공유창으로 보낸다. 링크도 복사해 둔다
|
||||
const copied = navigator.clipboard?.writeText(url).then(
|
||||
() => true,
|
||||
(e: unknown) => {
|
||||
console.error('[share] copy link', e)
|
||||
return false
|
||||
},
|
||||
)
|
||||
appShare(image.blob, file.name, share.title).then(
|
||||
async () => {
|
||||
setToast((await copied) ? '보냈어요. 링크도 복사해 뒀어요' : '보냈어요')
|
||||
track('share', { content_type: 'image', item_id: share.title, method: 'share_sheet', ratio: SHARE_SIZES[size].ratio })
|
||||
reward()
|
||||
},
|
||||
(e: unknown) => {
|
||||
console.error('[share] app', e)
|
||||
track('app_bridge_error', { action: 'share' })
|
||||
setToast('보내지 못했어요. 한 번 더 눌러 주세요')
|
||||
},
|
||||
)
|
||||
return
|
||||
}
|
||||
if (navigator.canShare?.({ files: [file], text, url })) {
|
||||
const copied = navigator.clipboard?.writeText(url).then(
|
||||
() => true,
|
||||
|
||||
@@ -2,13 +2,15 @@ import { useMutation, useQuery } from '@tanstack/react-query'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { authConfigOptions, googleLoginMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||
import type { ResAuth } from '@nalssigak/shared/api/client/types.gen'
|
||||
import { track } from '../lib/analytics'
|
||||
import { appGoogleLogin, IS_APP } from '../lib/platform'
|
||||
import { cx } from '../lib/utils'
|
||||
import { loadGoogle } from './googleScript'
|
||||
import { SHEET_OPEN_MS } from './lib'
|
||||
import { Skel } from './ui'
|
||||
|
||||
/** 구글로 계속하기 버튼. 서버에 클라이언트 ID가 없으면 아무것도 그리지 않는다 */
|
||||
export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) => void; onFail: () => void }) {
|
||||
/** 구글로 계속하기 버튼(웹). 서버에 클라이언트 ID가 없으면 아무것도 그리지 않는다 */
|
||||
function WebGoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) => void; onFail: () => void }) {
|
||||
const config = useQuery({ ...authConfigOptions(), staleTime: Infinity })
|
||||
const clientId = config.data?.google_client_id
|
||||
const login = useMutation(googleLoginMutation())
|
||||
@@ -66,3 +68,50 @@ export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) =>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 앱 안 웹뷰는 구글 웹 로그인이 막혀 있어, 앱의 구글 계정 선택창으로 ID 토큰을 받아 같은 서버 로그인에 보낸다 */
|
||||
function AppGoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) => void; onFail: () => void }) {
|
||||
const config = useQuery({ ...authConfigOptions(), staleTime: Infinity })
|
||||
const clientId = config.data?.google_client_id
|
||||
const login = useMutation(googleLoginMutation())
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [broken, setBroken] = useState(false)
|
||||
|
||||
const press = async () => {
|
||||
if (!clientId || busy) return
|
||||
setBroken(false)
|
||||
setBusy(true)
|
||||
try {
|
||||
const res = await appGoogleLogin(clientId)
|
||||
// 사용자가 계정 선택창을 닫음
|
||||
if (!res) return
|
||||
login.mutate({ body: { credential: res.idToken } }, { onSuccess: (r) => onResult(r), onError: () => onFail() })
|
||||
} catch (e) {
|
||||
console.error('[google] app login', e)
|
||||
track('app_bridge_error', { action: 'google_login' })
|
||||
setBroken(true)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (config.isPending) return <Skel shape className="mx-auto h-[44px] w-full max-w-[400px] rounded-full" />
|
||||
if (!clientId) return null
|
||||
const pendingLogin = busy || login.isPending
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={press}
|
||||
disabled={pendingLogin}
|
||||
className="mx-auto h-[44px] w-full max-w-[400px] cursor-pointer rounded-full border-[1.5px] border-(--line) bg-white text-[15px] font-extrabold text-[#28304a] disabled:opacity-60"
|
||||
>
|
||||
{pendingLogin ? '구글로 로그인 중…' : '구글로 계속하기'}
|
||||
</button>
|
||||
{broken && <p className="m-0 text-center text-[13px] font-bold text-(--ink3)">구글 로그인을 하지 못했어요. 잠시 뒤에 다시 해 주세요.</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 구글로 계속하기 버튼. 앱 안에서는 앱의 구글 로그인, 그 밖에서는 구글 웹 버튼 */
|
||||
export const GoogleButton = IS_APP ? AppGoogleButton : WebGoogleButton
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useSyncExternalStore } from 'react'
|
||||
import { track } from '../lib/analytics'
|
||||
import { IS_APP } from '../lib/platform'
|
||||
import { useSheet } from './sheetContext'
|
||||
|
||||
type InstallPromptEvent = Event & { prompt: () => Promise<void>; userChoice: Promise<{ outcome: 'accepted' | 'dismissed' }> }
|
||||
@@ -27,10 +28,10 @@ if (typeof window !== 'undefined') {
|
||||
|
||||
export type Platform = 'standalone' | 'inapp' | 'ios' | 'android' | 'other'
|
||||
|
||||
/** 지금 이 기기에서 홈 화면 추가를 어떻게 안내할지 */
|
||||
/** 지금 이 기기에서 홈 화면 추가를 어떻게 안내할지. 날씨각 앱 안이면 이미 설치한 것이라 standalone */
|
||||
export function platform(): Platform {
|
||||
const ua = navigator.userAgent
|
||||
if (window.matchMedia('(display-mode: standalone)').matches || (navigator as Navigator & { standalone?: boolean }).standalone) return 'standalone'
|
||||
if (IS_APP || window.matchMedia('(display-mode: standalone)').matches || (navigator as Navigator & { standalone?: boolean }).standalone) return 'standalone'
|
||||
if (/KAKAOTALK|Instagram|FBAN|FBAV|NAVER\(inapp|; wv\)|Line\//i.test(ua)) return 'inapp'
|
||||
if (/iPhone|iPad|iPod/.test(ua) || (/Macintosh/.test(ua) && navigator.maxTouchPoints > 1)) return 'ios'
|
||||
if (/Android/.test(ua)) return 'android'
|
||||
|
||||
@@ -4,7 +4,7 @@ import regionPages from '../../seo/region.json'
|
||||
import { nearestRegion } from '@nalssigak/shared/api/client/sdk.gen'
|
||||
import type { RegionData } from '@nalssigak/shared/api/client/types.gen'
|
||||
import { track } from '../lib/analytics'
|
||||
import { IS_TOSS, tossLocation } from '../lib/platform'
|
||||
import { appLocation, IS_APP, IS_TOSS, tossLocation } from '../lib/platform'
|
||||
import { DEFAULT_REGION, ownPage, pageOf, RegionContext, type LocateStatus } from './regionContext'
|
||||
|
||||
const KEY = 'nalssigak.b.region'
|
||||
@@ -50,7 +50,7 @@ export function RegionProvider({ children }: { children: ReactNode }) {
|
||||
const [chosen, setRegionState] = useState<RegionData>(() => (page ? regionIn(page, stored) : (stored ?? DEFAULT_REGION)))
|
||||
// 앱 안에서 다른 지역 페이지로 옮겨 가면 그 지역으로
|
||||
const region = page && !page.regions.some((g) => g.code === chosen.code) ? regionIn(page, stored) : chosen
|
||||
const canLocate = IS_TOSS || (typeof navigator !== 'undefined' && 'geolocation' in navigator)
|
||||
const canLocate = IS_TOSS || IS_APP || (typeof navigator !== 'undefined' && 'geolocation' in navigator)
|
||||
const [locateStatus, setLocateStatus] = useState<LocateStatus>(!landing && (!stored || IS_TOSS) && canLocate ? 'locating' : 'idle')
|
||||
|
||||
// 지역 페이지에서 고르면 주소도 그 지역 페이지로 바꿔, 공유한 링크가 보던 화면과 같게 한다
|
||||
@@ -72,15 +72,17 @@ export function RegionProvider({ children }: { children: ReactNode }) {
|
||||
})
|
||||
.catch(() => !quiet && setLocateStatus('error'))
|
||||
}
|
||||
if (IS_TOSS) {
|
||||
tossLocation(ask).then(
|
||||
// 토스·앱은 웹 위치 대신 호스트(토스 SDK·앱)에 위치를 묻는다
|
||||
if (IS_TOSS || IS_APP) {
|
||||
;(IS_TOSS ? tossLocation(ask) : appLocation(ask)).then(
|
||||
(loc) => {
|
||||
if (loc === null) setLocateStatus('idle')
|
||||
else if (loc === 'denied') setLocateStatus(quiet ? 'idle' : 'denied')
|
||||
else fromCoords(loc.lat, loc.lon)
|
||||
},
|
||||
(e: unknown) => {
|
||||
console.error('[region] toss location', e)
|
||||
console.error('[region] host location', e)
|
||||
if (IS_APP) track('app_bridge_error', { action: 'location' })
|
||||
setLocateStatus(quiet ? 'idle' : 'error')
|
||||
},
|
||||
)
|
||||
@@ -120,12 +122,18 @@ export function RegionProvider({ children }: { children: ReactNode }) {
|
||||
}
|
||||
// 지역 페이지로 들어오면 그 지역을 보여 준다. 구로 나뉜 시는 위치를 이미 허용했고 그 시 안에 있으면 지금 있는 구로
|
||||
if (landing.regions.length < 2) return
|
||||
const adopt = (r: RegionData) => {
|
||||
if (pageRef.current === landing && landing.regions.some((g) => g.code === r.code)) setRegionState(r)
|
||||
}
|
||||
// 앱은 웹의 위치 권한 상태를 알 수 없어, 앱이 이미 허용한 경우에만(ask=false) 앱에 위치를 묻는다
|
||||
if (IS_APP) {
|
||||
findNearest(adopt, true, false)
|
||||
return
|
||||
}
|
||||
navigator.permissions?.query({ name: 'geolocation' })
|
||||
.then((s) => {
|
||||
if (s.state !== 'granted') return
|
||||
findNearest((r) => {
|
||||
if (pageRef.current === landing && landing.regions.some((g) => g.code === r.code)) setRegionState(r)
|
||||
}, true)
|
||||
findNearest(adopt, true)
|
||||
})
|
||||
.catch((e) => console.warn('위치 권한 상태를 읽지 못함', e))
|
||||
}, [canLocate, landing, stored, findNearest, setRegion])
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
/** 웹/앱인토스 차이를 모으는 곳. 토스 SDK 는 토스 빌드(`vite build --mode toss`)에서만 불러온다 */
|
||||
/** 웹/앱인토스/날씨각 안드로이드 앱(웹뷰) 차이를 모으는 곳. 토스 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 가 번들에 들어가지 않는다
|
||||
@@ -45,3 +50,93 @@ export async function tossLocation(ask: boolean): Promise<TossLocation | 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)
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import './api/setup'
|
||||
import App from './App.tsx'
|
||||
import './b/install'
|
||||
import { track } from './lib/analytics'
|
||||
import { APP_VERSION, IS_APP } from './lib/platform'
|
||||
|
||||
// index.html 의 첫 화면이 멈췄을 때 앱 파일까지는 실행됐는지 가르는 표시
|
||||
;(window as Window & { __appStarted?: boolean }).__appStarted = true
|
||||
@@ -25,7 +26,8 @@ const queryClient: QueryClient = new QueryClient({
|
||||
if (import.meta.env.PROD && 'serviceWorker' in navigator) {
|
||||
navigator.serviceWorker.register('/sw.js').catch((e: unknown) => console.error('[sw] register', e))
|
||||
}
|
||||
if (window.matchMedia('(display-mode: standalone)').matches || (navigator as Navigator & { standalone?: boolean }).standalone) track('app_launch', { mode: 'standalone' })
|
||||
if (IS_APP) track('app_launch', { mode: 'android_app', version: APP_VERSION })
|
||||
else if (window.matchMedia('(display-mode: standalone)').matches || (navigator as Navigator & { standalone?: boolean }).standalone) track('app_launch', { mode: 'standalone' })
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
|
||||
Reference in new issue
Block a user