import { Dimensions } from 'react-native' import { getBrand, getSystemVersion, getDeviceType, getBuildNumber, getVersion, getUserAgent, getCarrier, getDeviceId, getTotalMemory, } from 'react-native-device-info' import { request } from '../utils' import pubsub from '../utils/pubsub' import sha256 from 'crypto-js/sha256' import type { AppBatchUpload } from '../utils/batch' import createAppBatchUpload from '../utils/batch' import type { AppInvokeApiType, AssemblyCollectType, DeviceInfoType, RouteInfo, RouteNavigationState, } from '../interface' import { getAppUuid } from '../utils/pv' export type AppTrackerConfig = { /** * 数据上传的URL 如果不传 使用`process.env.CHUSHU_UPLOAD_HOST` */ uploadUrl: string /** * 应用key 如果不指定,则默认使用`process.env.CHUSHU_AK` */ accesskey: string /** * 是否记录页面访问数据 默认`false` */ pv?: boolean } class Tracker { private uploadUrl: string private userHash: string private deviceInfo: DeviceInfoType private routerInfo: string private accessKey: string private appBatchUpload: AppBatchUpload private pv: boolean private startTime: number public constructor(config: AppTrackerConfig) { this.startTime = Date.now() this.pv = config.pv || false this.accessKey = config.accesskey this.uploadUrl = config.uploadUrl this.appBatchUpload = createAppBatchUpload({ request: this.request.bind(this), batchSize: 10, }) // 订阅存储事件 pubsub.subscribe('ADD', this.addCacheData.bind(this)) // 监听错误 this.listenError() } public setUserHash(id: string) { if ( !this.userHash || (this.userHash && this.userHash !== sha256(String(id)).toString()) ) { const hash = sha256(String(id)).toString() this.userHash = hash this.appBatchUpload.setUserHash(hash) // 由于用户元数据和用户相关 因此一定是在获取到userHash后再初始化获取元数据并立刻上传 this.initDeviceInfo() } } public setRouteInfo(routeState: RouteNavigationState) { function getCurrentRoute(allRoutes: RouteNavigationState): RouteInfo { const tempRoutes = allRoutes.routes[allRoutes.index] if (tempRoutes.state) { return getCurrentRoute(tempRoutes.state) } return { name: tempRoutes.name, params: tempRoutes.params, } } const currentRouteInfo = getCurrentRoute(routeState) let str = '' if (currentRouteInfo?.params) { const routeParamsKeys = Object.keys(currentRouteInfo.params) routeParamsKeys.forEach((item, index) => { const typeStr = Object.prototype.toString.call( currentRouteInfo.params[item], ) str += `${item}=${ typeStr === '[object Object]' || typeStr === '[object Array]' ? JSON.stringify(currentRouteInfo.params[item]) : `${currentRouteInfo.params[item]}` }${index === routeParamsKeys.length - 1 ? '' : '&'}` }) } this.routerInfo = `${currentRouteInfo.name}${str ? `?${str}` : ''}` if (this.pv) { getAppUuid().then(res => { pubsub.publish( 'ADD', { uuid: res, path: currentRouteInfo.name, time: Date.now(), timeStamp: Date.now() - this.startTime, t: 'pv', params: currentRouteInfo.params, }, false, ) }) } } private initDeviceInfo() { const screen = Dimensions.get('screen') this.deviceInfo = { screen: { width: screen.width, height: screen.height, }, t: 'm', ov: getSystemVersion(), b: getBrand(), dt: getDeviceType(), bn: getBuildNumber(), v: getVersion(), di: getDeviceId(), } Promise.all([getUserAgent(), getCarrier(), getTotalMemory()]) .then(res => { this.deviceInfo.ua = res[0] this.deviceInfo.c = res[1] this.deviceInfo.ms = res[2] }) .catch(() => {}) .finally(() => { pubsub.publish('ADD', this.deviceInfo, false) }) } private listenError() { ErrorUtils.setGlobalHandler(err => { pubsub.publish('ADD', { en: err?.name, em: err?.message, es: err?.stack, createTime: new Date().getTime(), t: 'e', }) }) // eslint-disable-next-line @typescript-eslint/no-require-imports require('promise/setimmediate/rejection-tracking').enable({ allRejections: true, onUnhandled: (id: number, err: Error) => { pubsub.publish('ADD', { en: err?.name, em: err?.message, es: err?.stack, createTime: new Date().getTime(), t: 'e', }) }, }) } private request(data: any) { let temp: Record // 添加ak和uh if (Array.isArray(data)) { temp = { data: data.map(item => ({ ...item, uh: this.userHash, })), ak: this.accessKey, } } else { temp = { ...data, uh: this.userHash, ak: this.accessKey, } } return new Promise(resolve => { request(this.uploadUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(temp), }) .then(() => { resolve(true) }) .catch(() => { resolve(false) }) }) } private addCacheData( rawData: AssemblyCollectType, cache?: boolean, callback?: () => void, ) { // 1. 给异常数据添加MetaData和路由信息 const data = this.appendSomeInfo(rawData) this.appBatchUpload.addCache(data, cache, callback) } /** * 给不同的数据添加元数据和路由信息 * @param rawData * @returns */ private appendSomeInfo(rawData: AssemblyCollectType) { const temp = { ...rawData } if (rawData.t === 'e') { temp.d = this.deviceInfo temp.r = this.routerInfo } // 如果API数据有关联异常,则同样需要添加设备信息 if (temp.t === 'api' && (temp as AppInvokeApiType).e?.length) { ;(rawData as AppInvokeApiType).e.forEach(err => { err.d = this.deviceInfo err.r = this.routerInfo }) } return temp } } export default Tracker