feat: 完成 Q 群組 — APP(React Native + Expo)
新增 apps/mobile:Expo Router 檔案系統路由(同 Next.js App Router 的 心智模型),底部四分頁(聊天/角色/日常/設定)皆為真實 API 串接(/chat、 /tachie、/characters、/schedule、/health、/push)。聊天分頁完整重用 H/O 群組已驗證過的對話+表情查詢節奏。立繪暫以依情緒 magnitude 調整 透明度的色塊佔位(PixiJS 是瀏覽器 DOM/Canvas API,未移植到 React Native,需要 react-native-skia 等原生繪圖套件才能重現分層合成,超出 本群組範圍)。 新增 apps/api/src/push/:PushProvider 抽象(第三次套用 F-1/P-4 的 Provider 模式),MockPushProvider 供測試、ExpoPushProvider 是可直接 打真實 HTTP 請求的完整實作(Expo 推播匿名發送不需金鑰,不像 LLM/TTS 需要另外挑供應商待人工確認)。PushToken/PushNotificationLog 記錄裝置 註冊與每次推播嘗試。J 群組 TaskTriggerService 觸發時會嘗試推播給 使用者已註冊裝置,用觸發訊息本身當推播內容。 本環境沒有 Android/iOS 模擬器,改用 `expo start --web` + playwright-core (同 O 群組手法)驅動無頭瀏覽器驗證四分頁切換、真實 API 串接、聊天 完整往返、推播按鈕在無裝置環境下的優雅降級——不是原生 APP 的完整驗證, 但驗證了畫面邏輯與 API 契約層。過程中發現並修正 CORS 設定只放行網頁版 origin、擋掉 Expo 網頁版請求的問題(永久修正:新增 localhost:8081 白名單, 不影響原生 APP,原生環境沒有 CORS 限制)。 Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5
parent
0e9401b891
commit
5da8b3a63e
@@ -16,6 +16,7 @@ import { CanonModule } from "./canon/canon.module.js";
|
||||
import { EpilogueModule } from "./epilogue/epilogue.module.js";
|
||||
import { TachieModule } from "./tachie/tachie.module.js";
|
||||
import { VoiceModule } from "./voice/voice.module.js";
|
||||
import { PushModule } from "./push/push.module.js";
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -35,6 +36,7 @@ import { VoiceModule } from "./voice/voice.module.js";
|
||||
EpilogueModule,
|
||||
TachieModule,
|
||||
VoiceModule,
|
||||
PushModule,
|
||||
],
|
||||
controllers: [HealthController],
|
||||
})
|
||||
|
||||
@@ -6,7 +6,9 @@ import { AppModule } from "./app.module.js";
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule, { logger: false });
|
||||
app.enableCors({ origin: process.env.WEB_ORIGIN ?? "http://localhost:3100" });
|
||||
// Q-1:8081 是 `expo start --web` 的預設埠——APP 在真機/模擬器上不受 CORS 限制(原生環境沒有這個瀏覽器機制),
|
||||
// 只有用瀏覽器跑 Expo 的網頁版時才需要放行,開發環境固定加這個來源即可。
|
||||
app.enableCors({ origin: [process.env.WEB_ORIGIN ?? "http://localhost:3100", "http://localhost:8081"] });
|
||||
const port = Number(process.env.PORT ?? 3001);
|
||||
await app.listen(port);
|
||||
log("啟動", "INF", `api 服務已啟動,監聽埠 ${port}`);
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import type { PushProvider, PushMessage, PushSendResult } from "./push-provider.js";
|
||||
|
||||
const EXPO_PUSH_ENDPOINT = "https://exp.host/--/api/v2/push/send";
|
||||
|
||||
interface ExpoPushResponse {
|
||||
data?: { status?: string; message?: string };
|
||||
}
|
||||
|
||||
// Q-3 真實推播供應商:Expo 的推播 API 是「React Native + Expo」這個技術選型本身自帶的服務
|
||||
// (不像 LLM/TTS 需要另外挑一家外部供應商待人工確認),基本匿名發送不需要金鑰,所以這裡直接
|
||||
// 實作真正會打出去的 HTTP 呼叫——沒有真實裝置 token 時,Expo 端會回報 token 無效,屬於預期行為,
|
||||
// 不是這個 Provider 本身沒做完。
|
||||
@Injectable()
|
||||
export class ExpoPushProvider implements PushProvider {
|
||||
async send(message: PushMessage): Promise<PushSendResult> {
|
||||
try {
|
||||
const res = await fetch(EXPO_PUSH_ENDPOINT, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
||||
body: JSON.stringify({ to: message.token, title: message.title, body: message.body, data: message.data ?? {} }),
|
||||
});
|
||||
const payload = (await res.json().catch(() => null)) as ExpoPushResponse | null;
|
||||
const ticket = payload?.data;
|
||||
if (!res.ok || ticket?.status === "error") {
|
||||
return { success: false, errorText: ticket?.message ?? `HTTP ${res.status}` };
|
||||
}
|
||||
return { success: true };
|
||||
} catch (err) {
|
||||
return { success: false, errorText: err instanceof Error ? err.message : String(err) };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import type { PushProvider, PushMessage, PushSendResult } from "./push-provider.js";
|
||||
|
||||
// Q-3 MockPushProvider:不打真的網路請求,只記錄「這次呼叫本身有沒有正確組出訊息」——
|
||||
// 讓推播的節流/記錄/與 J 群組的整合可以在沒有真實裝置與網路的情況下完整測試。
|
||||
@Injectable()
|
||||
export class MockPushProvider implements PushProvider {
|
||||
public readonly sent: PushMessage[] = [];
|
||||
|
||||
async send(message: PushMessage): Promise<PushSendResult> {
|
||||
this.sent.push(message);
|
||||
return { success: true };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Inject, Injectable } from "@nestjs/common";
|
||||
import { PrismaService } from "../prisma/prisma.service.js";
|
||||
import { PushTokenService } from "./push-token.service.js";
|
||||
import { PUSH_PROVIDER, type PushProvider } from "./push-provider.js";
|
||||
|
||||
export interface SendToUserResult {
|
||||
attempted: number;
|
||||
succeeded: number;
|
||||
}
|
||||
|
||||
// Q-3 推播通知:提醒觸發(J 群組)、角色主動訊息、鎖屏通知都走這個服務——同一個使用者可能有
|
||||
// 多台裝置,逐一送出並各自留一筆記錄(成功或失敗皆記),方便之後追查「提醒有沒有真的送達」。
|
||||
@Injectable()
|
||||
export class PushNotificationService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly pushToken: PushTokenService,
|
||||
@Inject(PUSH_PROVIDER) private readonly provider: PushProvider,
|
||||
) {}
|
||||
|
||||
async sendToUser(userId: string, title: string, body: string, data?: Record<string, unknown>): Promise<SendToUserResult> {
|
||||
const tokens = await this.pushToken.listForUser(userId);
|
||||
let succeeded = 0;
|
||||
for (const { token } of tokens) {
|
||||
const result = await this.provider.send({ token, title, body, data });
|
||||
await this.prisma.client.pushNotificationLog.create({
|
||||
data: { userId, title, body, success: result.success, errorText: result.errorText },
|
||||
});
|
||||
if (result.success) {
|
||||
succeeded += 1;
|
||||
}
|
||||
}
|
||||
return { attempted: tokens.length, succeeded };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
export interface PushMessage {
|
||||
token: string;
|
||||
title: string;
|
||||
body: string;
|
||||
data?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface PushSendResult {
|
||||
success: boolean;
|
||||
errorText?: string;
|
||||
}
|
||||
|
||||
// Q-3 PushProvider 抽象:同一個模式的第三次套用(F-1 LLMProvider/P-4 TTSProvider),
|
||||
// 切換 Provider 不動呼叫端任何一行。
|
||||
export interface PushProvider {
|
||||
send(message: PushMessage): Promise<PushSendResult>;
|
||||
}
|
||||
|
||||
export const PUSH_PROVIDER = Symbol("PUSH_PROVIDER");
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { PrismaService } from "../prisma/prisma.service.js";
|
||||
|
||||
// Q-3 裝置推播 token 註冊:同一個 token 重複註冊(例如 APP 重新啟動)視為更新,不會產生重複紀錄。
|
||||
@Injectable()
|
||||
export class PushTokenService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async register(userId: string, token: string, platform: string) {
|
||||
return this.prisma.client.pushToken.upsert({
|
||||
where: { token },
|
||||
update: { userId, platform },
|
||||
create: { userId, token, platform },
|
||||
});
|
||||
}
|
||||
|
||||
async listForUser(userId: string) {
|
||||
return this.prisma.client.pushToken.findMany({ where: { userId } });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { Body, Controller, Post } from "@nestjs/common";
|
||||
import { PushTokenService } from "./push-token.service.js";
|
||||
import { PushNotificationService } from "./push-notification.service.js";
|
||||
|
||||
interface RegisterBody {
|
||||
userId: string;
|
||||
token: string;
|
||||
platform: string;
|
||||
}
|
||||
|
||||
interface SendTestBody {
|
||||
userId: string;
|
||||
title: string;
|
||||
body: string;
|
||||
}
|
||||
|
||||
@Controller("push")
|
||||
export class PushController {
|
||||
constructor(
|
||||
private readonly pushToken: PushTokenService,
|
||||
private readonly pushNotification: PushNotificationService,
|
||||
) {}
|
||||
|
||||
@Post("register")
|
||||
async register(@Body() body: RegisterBody) {
|
||||
return this.pushToken.register(body.userId, body.token, body.platform);
|
||||
}
|
||||
|
||||
@Post("send-test")
|
||||
async sendTest(@Body() body: SendTestBody) {
|
||||
return this.pushNotification.sendToUser(body.userId, body.title, body.body);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { log } from "@kokorone/shared";
|
||||
import { PrismaModule } from "../prisma/prisma.module.js";
|
||||
import { PushTokenService } from "./push-token.service.js";
|
||||
import { PushNotificationService } from "./push-notification.service.js";
|
||||
import { MockPushProvider } from "./mock-push-provider.service.js";
|
||||
import { ExpoPushProvider } from "./expo-push-provider.service.js";
|
||||
import { PUSH_PROVIDER } from "./push-provider.js";
|
||||
import { PushController } from "./push.controller.js";
|
||||
|
||||
// Q-3 Provider 切換:PUSH_PROVIDER=mock|expo,預設 mock(同 F-2/P-4 的作法,開發期不依賴外部服務)。
|
||||
function pushProviderFactory(mock: MockPushProvider, expoProvider: ExpoPushProvider) {
|
||||
const providerName = process.env.PUSH_PROVIDER ?? "mock";
|
||||
if (providerName === "expo") {
|
||||
log("啟動", "INF", "PUSH_PROVIDER=expo,推播會真的呼叫 Expo 推播 API(沒有真實裝置 token 時預期會失敗)");
|
||||
return expoProvider;
|
||||
}
|
||||
return mock;
|
||||
}
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule],
|
||||
controllers: [PushController],
|
||||
providers: [
|
||||
PushTokenService,
|
||||
PushNotificationService,
|
||||
MockPushProvider,
|
||||
ExpoPushProvider,
|
||||
{ provide: PUSH_PROVIDER, useFactory: pushProviderFactory, inject: [MockPushProvider, ExpoPushProvider] },
|
||||
],
|
||||
exports: [PushTokenService, PushNotificationService, PUSH_PROVIDER, MockPushProvider],
|
||||
})
|
||||
export class PushModule {}
|
||||
@@ -2,16 +2,20 @@ import { Injectable } from "@nestjs/common";
|
||||
import { PrismaService } from "../prisma/prisma.service.js";
|
||||
import { ScheduleService } from "../schedule/schedule.service.js";
|
||||
import { KeywordMemoryRetriever } from "../memory/memory-retriever.service.js";
|
||||
import { PushNotificationService } from "../push/push-notification.service.js";
|
||||
import { taipeiParts } from "../schedule/time-utils.js";
|
||||
import { buildTriggerMessage } from "./task-performance.js";
|
||||
|
||||
// J-3 觸發演出:任務時間到時,依作息語氣+相關記憶回顧組成訊息;準時觸發是引擎責任,語氣是角色責任。
|
||||
// Q-3:觸發的同一刻也會嘗試推播給使用者的裝置(提醒、她的主動訊息都走這條路)——沒有註冊過
|
||||
// 任何裝置 token 時,PushNotificationService.sendToUser 單純回報 attempted=0,不影響任務本身的觸發。
|
||||
@Injectable()
|
||||
export class TaskTriggerService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly schedule: ScheduleService,
|
||||
private readonly memoryRetriever: KeywordMemoryRetriever,
|
||||
private readonly pushNotification: PushNotificationService,
|
||||
) {}
|
||||
|
||||
async fire(taskId: string, now: Date = new Date()): Promise<string | null> {
|
||||
@@ -46,6 +50,8 @@ export class TaskTriggerService {
|
||||
data: { status: "TRIGGERED", triggeredAt: now, triggerMessage: message },
|
||||
});
|
||||
|
||||
await this.pushNotification.sendToUser(task.userId, "心音 Kokorone", message);
|
||||
|
||||
return message;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { MemoryModule } from "../memory/memory.module.js";
|
||||
import { RelationshipModule } from "../relationship/relationship.module.js";
|
||||
import { EmotionModule } from "../emotion/emotion.module.js";
|
||||
import { ScheduleModule } from "../schedule/schedule.module.js";
|
||||
import { PushModule } from "../push/push.module.js";
|
||||
import { TaskService } from "./task.service.js";
|
||||
import { TaskSchedulerService } from "./task-scheduler.service.js";
|
||||
import { TaskTriggerService } from "./task-trigger.service.js";
|
||||
@@ -13,7 +14,7 @@ import { ProactiveCareService } from "./proactive-care.service.js";
|
||||
import { TaskController } from "./task.controller.js";
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule, MemoryModule, RelationshipModule, EmotionModule, ScheduleModule],
|
||||
imports: [PrismaModule, MemoryModule, RelationshipModule, EmotionModule, ScheduleModule, PushModule],
|
||||
controllers: [TaskController],
|
||||
providers: [
|
||||
TaskService,
|
||||
|
||||
Reference in New Issue
Block a user