import Inject, { RegisterSingleton, ServiceProvider } from "@entity-access/entity-access/dist/di/di.js"; import BasePushService, { IPushPayload, IPushToken } from "../BasePushService.js"; import ForwardPushService from "../forward/ForwardPushService.js"; import DBConfig from "../../DBConfig.js"; import { Notification, Provider} from "@parse/node-apn"; import { globalEnv } from "../../../../common/globalEnv.js"; import { join } from "path"; import ensureDir from "../../../../common/FileApi.js"; import { writeFile } from "fs/promises"; import PushConfig from "../PushConfig.js"; @RegisterSingleton export default class ApnPushService extends BasePushService { @Inject forward: ForwardPushService; config: PushConfig; provider: Provider; protected async initConfig() { using scope = ServiceProvider.createScope(this); const db = scope.resolve(DBConfig); this.config = (await db.getOrCreate(PushConfig, {})).value as PushConfig; if (this.config.apn?.key) { let key = join(globalEnv.tmpDir, "apn", "key"); ensureDir(key); key = join(key, "p8"); await writeFile(key, this.config.apn.key); const { keyId, teamId } = this.config.apn; this.provider = new Provider({ token: { key, keyId, teamId }}); } } protected async pushMessage(token: IPushToken, payload: IPushPayload) { if (!this.provider) { return this.forward.push(token, payload); } const note = new Notification(); const { title, body } = payload; note.alert = { title, body }; await this.provider.send(note, token.deviceToken); } }