/** * 任务上报 */ import { context } from '@/common/context'; import { TaskTracker, TaskPoint } from '@/common/report/task-track'; import { EventEmitter, getApiHost, isBoolean } from '@jolibox/common'; import { innerFetch as fetch } from '../network'; import { applyNative } from '@jolibox/native-bridge'; import type { Track } from '.'; import type { TrackEvent } from '@jolibox/types'; import { getGlobalStorage, setGlobalStorage } from '../api/storage'; import { canIUseNative } from '@/native/utils/can-iuse-native'; const REPORT_FIRST_OPEN_GAME = 'REPORT_FIRST_OPEN_GAME'; type NativeTaskPointEvent = | 'OpenGame' | 'CloseGame' | 'LevelFinished' | 'TaskFinished' | 'LevelUpgrade' | 'HistoryUserLevel' | 'HistoryUserScore' | 'UseGameItem' | 'GameTaskEvent'; export type NativeTaskPoint = { event: NativeTaskPointEvent; params: Record; }; export class NativeTaskTracker extends TaskTracker { private gameId: string; private sessionId: string; private track: Track; private taskUrl: string; private started = false; constructor(track: Track, eventEmitter: EventEmitter<{ visible: [boolean] }>, interval?: number) { super(eventEmitter, interval); this.gameId = context.mpId; this.sessionId = context.sessionId; this.track = track; this.taskUrl = getApiHost(context.testMode) + '/api/base/app-event'; } async reporter(point: TaskPoint): Promise { const { event, params, extraParams } = point; const reportBody = { eventType: event, gameInfo: { gameId: this.gameId, sessionId: this.sessionId, ...params } }; if (extraParams) { Object.assign(reportBody, extraParams); } const reportTask = this.createTask(reportBody); await reportTask; } async reportToNative(point: NativeTaskPoint) { const { event, params } = point; await applyNative('userTrackAsync', { event: event, params: { ...params }, gameId: this.gameId }); } tracker(event: TrackEvent, info: Record | null = null) { this.track(event, info); } start(duration?: number) { if (this.started) { console.info('[JoliboxSDK] taskTrakcer has started'); return; } super.start(duration); this.tryReportOpenGamePlus(); this.started = true; } private tryReportOpenGamePlus() { getGlobalStorage(REPORT_FIRST_OPEN_GAME).then((res) => { if (isBoolean(res.data) && res.data) { this.tracker('OpenGame_2Plus'); } setGlobalStorage(REPORT_FIRST_OPEN_GAME, true); }); } private createTask(reportBody: { eventType: string; gameInfo: { gameId: string; sessionId: string; }; }) { if (canIUseNative('sendServerEventAsync')) { return applyNative('sendServerEventAsync', { payload: reportBody }); } return context.platform === 'android' ? fetch(`/api/base/app-event`, { method: 'POST', data: reportBody }) : applyNative('trackAppEventAsync', { url: this.taskUrl, body: JSON.stringify(reportBody) }); } }