stat.js 13.2 KB
Newer Older
M
mehaotian 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
const PagesJson = require('uni-pages?{"type":"style"}').default
const statConfig = require('uni-stat-config').default || require('uni-stat-config');
import {
  getUuid,
  getSgin,
  getSplicing,
  getPackName,
  getPlatformName,
  getVersion,
  getChannel,
  getScene,
  getTime,
  getFirstVisitTime,
  getLastVisitTime,
  setPageResidenceTime,
  getPageResidenceTime,
  getTotalVisitCount,
  GetEncodeURIComponentOptions,
  getFirstTime,
  getLastTime,
  getResidenceTime,
  getPageRoute,
  getRoute,
  getPageTypes,
  calibration
} from './parameter';

import {
  STAT_URL,
  STAT_VERSION,
  STAT_H5_URL,
  OPERATING_TIME
} from './config';

const resultOptions = uni.getSystemInfoSync();

class Util {
  constructor() {
    this.self = '';
    this._retry = 0;
    this._platform = '';
    this._query = {};
    this._navigationBarTitle = {
      config: '',
      page: '',
      report: '',
      lt: ''
    }
    this._operatingTime = 0;
    this._reportingRequestData = {
      '1': [],
      '11': []
    };
    this.__prevent_triggering = false

    this.__licationHide = false;
    this.__licationShow = false;
    this._lastPageRoute = '';
    this.statData = {
      uuid: getUuid(),
      ut: getPlatformName(),
      mpn: getPackName(),
      ak: statConfig.appid,
      usv: STAT_VERSION,
      v: getVersion(),
      ch: getChannel(),
      cn: '',
      pn: '',
      ct: '',
      t: getTime(),
      tt: '',
      p: resultOptions.platform === 'android' ? 'a' : 'i',
      brand: resultOptions.brand || '',
      md: resultOptions.model,
      sv: resultOptions.system.replace(/(Android|iOS)\s/, ''),
      mpsdk: resultOptions.SDKVersion || '',
      mpv: resultOptions.version || '',
      lang: resultOptions.language,
      pr: resultOptions.pixelRatio,
      ww: resultOptions.windowWidth,
      wh: resultOptions.windowHeight,
      sw: resultOptions.screenWidth,
      sh: resultOptions.screenHeight
    }

  }

  _applicationShow() {
    if (this.__licationHide) {
      getLastTime();
      const time = getResidenceTime('app');
      if (time.overtime) {
        let options = {
          path: this._lastPageRoute,
          scene: this.statData.sc
        }
        this._sendReportRequest(options);
      }
      this.__licationHide = false;
    }
  }

  _applicationHide(self, type) {

    this.__licationHide = true;
    getLastTime();
    const time = getResidenceTime();
    getFirstTime();
109
    const route = getPageRoute(this);
M
mehaotian 已提交
110
    this._sendHideRequest({
111
      urlref: route,
M
mehaotian 已提交
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
      urlref_ts: time.residenceTime
    }, type)
  }

  _pageShow() {
    const route = getPageRoute(this);
    const routepath = getRoute(this);
    this._navigationBarTitle.config = PagesJson &&
      PagesJson.pages[routepath] &&
      PagesJson.pages[routepath].titleNView &&
      PagesJson.pages[routepath].titleNView.titleText ||
      PagesJson &&
      PagesJson.pages[routepath] &&
      PagesJson.pages[routepath].navigationBarTitleText || '';

    if (this.__licationShow) {
      getFirstTime();
      this.__licationShow = false;
      // console.log('这是 onLauch 之后执行的第一次 pageShow ,为下次记录时间做准备');
      this._lastPageRoute = route;
      return;
    }

    getLastTime();
    this._lastPageRoute = route
    const time = getResidenceTime('page');
    if (time.overtime) {
      let options = {
        path: this._lastPageRoute,
        scene: this.statData.sc
      };
      this._sendReportRequest(options);
    }
    getFirstTime();
  }

  _pageHide() {
    if (!this.__licationHide) {
      getLastTime();
      const time = getResidenceTime('page');
      this._sendPageRequest({
        url: this._lastPageRoute,
        urlref: this._lastPageRoute,
        urlref_ts: time.residenceTime
      });
      this._navigationBarTitle = {
        config: '',
        page: '',
        report: '',
        lt: ''
      };
      return;
    }
  }

  _login() {
    this._sendEventRequest({
      key: 'login'
    }, 0)
  }

  _share() {
    this._sendEventRequest({
      key: 'share'
    }, 0)
  }
  _payment(key) {
    this._sendEventRequest({
      key
    }, 0)
  }
  _sendReportRequest(options) {
184

M
mehaotian 已提交
185 186 187
    this._navigationBarTitle.lt = '1';
    let query = options.query && JSON.stringify(options.query) !== '{}' ? '?' + JSON.stringify(options.query) : '';
    this.statData.lt = '1';
188
    this.statData.url = (options.path + query) || '';
M
mehaotian 已提交
189 190 191 192 193
    this.statData.t = getTime();
    this.statData.sc = getScene(options.scene);
    this.statData.fvts = getFirstVisitTime();
    this.statData.lvts = getLastVisitTime();
    this.statData.tvc = getTotalVisitCount();
194 195 196 197 198
    if (getPlatformName() === 'n') {
      this.getProperty();
    } else {
      this.getNetworkInfo();
    }
M
mehaotian 已提交
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
  }

  _sendPageRequest(opt) {
    let {
      url,
      urlref,
      urlref_ts
    } = opt;
    this._navigationBarTitle.lt = '11';
    let options = {
      ak: this.statData.ak,
      uuid: this.statData.uuid,
      lt: '11',
      ut: this.statData.ut,
      url,
      tt: this.statData.tt,
      urlref,
      urlref_ts,
      ch: this.statData.ch,
      usv: this.statData.usv,
      t: getTime(),
      p: this.statData.p
    }
222 223 224 225 226 227 228
    if (getPlatformName() === 'n' && this.statData.p === 'a') {
      setTimeout(() => {
        this.request(options);
      }, 200)
      return
    }

M
mehaotian 已提交
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
    this.request(options);
  }

  _sendHideRequest(opt, type) {
    let {
      urlref,
      urlref_ts
    } = opt;
    let options = {
      ak: this.statData.ak,
      uuid: this.statData.uuid,
      lt: '3',
      ut: this.statData.ut,
      urlref,
      urlref_ts,
      ch: this.statData.ch,
      usv: this.statData.usv,
      t: getTime(),
      p: this.statData.p
    }
249 250 251 252 253 254
    if (getPlatformName() === 'n' && this.statData.p === 'a') {
      setTimeout(() => {
        this.request(options, type)
      }, 200)
      return
    }
M
mehaotian 已提交
255 256 257 258 259 260
    this.request(options, type)
  }
  _sendEventRequest({
    key = '',
    value = ""
  } = {}) {
261
    const route = this._lastPageRoute;
M
mehaotian 已提交
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
    let options = {
      ak: this.statData.ak,
      uuid: this.statData.uuid,
      lt: '21',
      ut: this.statData.ut,
      url: route,
      ch: this.statData.ch,
      e_n: key,
      e_v: typeof(value) === 'object' ? JSON.stringify(value) : value.toString(),
      usv: this.statData.usv,
      t: getTime(),
      p: this.statData.p
    }
    this.request(options);
  }

  getNetworkInfo() {
    uni.getNetworkType({
      success: (result) => {
        this.statData.net = result.networkType;
        this.getLocation();
      }
    });
  }

287 288 289 290 291 292 293
  getProperty() {
    plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => {
      this.statData.v = wgtinfo.version || '';
      this.getNetworkInfo();
    });
  }

M
mehaotian 已提交
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
  getLocation() {
    if (statConfig.getLocation) {
      uni.getLocation({
        type: 'wgs84',
        geocode: true,
        success: (result) => {
          if (result.address) {
            this.statData.cn = result.address.country;
            this.statData.pn = result.address.province;
            this.statData.ct = result.address.city;
          }

          this.statData.lat = result.latitude;
          this.statData.lng = result.longitude;
          this.request(this.statData);
        }
      });
    } else {
      this.statData.lat = 0;
      this.statData.lng = 0;
      this.request(this.statData);
    }
  }

  request(data, type) {
    let time = getTime();
    const title = this._navigationBarTitle;
    data.ttn = title.page;
    data.ttpj = title.config;
    data.ttc = title.report;

    let requestData = this._reportingRequestData;
326 327 328
    if (getPlatformName() === 'n') {
      requestData = uni.getStorageSync('__UNI__STAT__DATA') || {}
    }
M
mehaotian 已提交
329
    if (!requestData[data.lt]) {
330 331 332 333 334 335
      requestData[data.lt] = [];
    }
    requestData[data.lt].push(data);

    if (getPlatformName() === 'n') {
      uni.setStorageSync('__UNI__STAT__DATA', requestData)
M
mehaotian 已提交
336 337 338 339
    }
    if (getPageResidenceTime() < OPERATING_TIME && !type) {
      return
    }
340 341 342 343
    let uniStatData = this._reportingRequestData
    if (getPlatformName() === 'n') {
      uniStatData = uni.getStorageSync('__UNI__STAT__DATA')
    }
M
mehaotian 已提交
344 345
    // 时间超过,重新获取时间戳
    setPageResidenceTime();
346 347 348 349 350 351
    let firstArr = [];
    let contentArr = [];
    let lastArr = [];

    for (let i in uniStatData) {
      const rd = uniStatData[i];
M
mehaotian 已提交
352
      rd.forEach((elm) => {
353
        const newData = getSplicing(elm);
M
mehaotian 已提交
354
        if (i === 0) {
355
          firstArr.push(newData);
M
mehaotian 已提交
356
        } else if (i === 3) {
357
          lastArr.push(newData);
M
mehaotian 已提交
358
        } else {
359
          contentArr.push(newData);
M
mehaotian 已提交
360
        }
361
      });
M
mehaotian 已提交
362 363
    }

364
    firstArr.push(...contentArr, ...lastArr);
M
mehaotian 已提交
365 366 367 368
    let optionsData = {
      usv: STAT_VERSION, //统计 SDK 版本号
      t: time, //发送请求时的时间戮
      requests: JSON.stringify(firstArr),
369 370 371 372 373
    };

    this._reportingRequestData = {};
    if (getPlatformName() === 'n') {
      uni.removeStorageSync('__UNI__STAT__DATA')
M
mehaotian 已提交
374 375 376 377 378 379
    }

    if (data.ut === 'h5') {
      this.imageRequest(optionsData)
      return
    }
380

381 382 383 384 385 386 387 388
    uni.request({
      url: STAT_URL,
      method: 'POST',
      // header: {
      //   'content-type': 'application/json' // 默认值
      // },
      data: optionsData,
      success: () => {
M
mehaotian 已提交
389 390 391
        // if (process.env.NODE_ENV === 'development') {
        //   console.log('stat request success');
        // }
392 393 394
      },
      fail: (e) => {
        if (process.env.NODE_ENV === 'development') {
M
mehaotian 已提交
395
          // console.log('stat request fail', e);
396 397 398 399 400 401 402 403
        }
        if (++this._retry < 3) {
          setTimeout(() => {
            this.request(data);
          }, 1000);
        }
      }
    });
404

M
mehaotian 已提交
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
  }
  /**
   * h5 请求
   */
  imageRequest(data) {
    let image = new Image();
    let options = getSgin(GetEncodeURIComponentOptions(data)).options;
    image.src = STAT_H5_URL + '?' + options
  }

  sendEvent(key, value) {
    // 校验 type 参数
    if (calibration(key, value)) return

    if (key === 'title') {
      this._navigationBarTitle.report = value;
      return
    }
    this._sendEventRequest({
      key,
      value: typeof(value) === 'object' ? JSON.stringify(value) : value
    }, 1);
  }
}


class Stat extends Util {
  static getInstance() {
    if (!this.instance) {
      this.instance = new Stat();
    }
    return this.instance;
  }
  constructor() {
    super()
    this.instance = null;
    // 注册拦截器
    if (typeof uni.addInterceptor === 'function') {
      this.addInterceptorInit();
      this.interceptLogin();
      this.interceptShare(true);
      this.interceptRequestPayment();
    }
  }

  addInterceptorInit() {
    let self = this;
    uni.addInterceptor('setNavigationBarTitle', {
      invoke(args) {
        self._navigationBarTitle.page = args.title
      }
    })
  }

  interceptLogin() {
    let self = this;
    uni.addInterceptor('login', {
      complete() {
        self._login();
      }
    })
  }

  interceptShare(type) {
    let self = this;
    if (!type) {
      self._share();
      return
    }
    uni.addInterceptor('share', {
      success() {
        self._share();
      },
      fail() {
        self._share();
      }
    })
  }

  interceptRequestPayment() {
    let self = this;
    uni.addInterceptor('requestPayment', {
      success() {
        self._payment('pay_success');
      },
      fail() {
        self._payment('pay_fail');
      }
    })
  }

  report(options, self) {
    this.self = self;
M
mehaotian 已提交
498 499 500
    // if (process.env.NODE_ENV === 'development') {
    //   console.log('report init');
    // }
M
mehaotian 已提交
501 502 503 504 505 506
    setPageResidenceTime()
    this.__licationShow = true;
    this._sendReportRequest(options, true);
  }

  load(options, self) {
507 508 509 510
    if (!self.$scope && !self.$mp) {
      const page = getCurrentPages()
      self.$scope = page[page.length - 1]
    }
M
mehaotian 已提交
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
    this.self = self;
    this._query = options;
  }

  show(self) {
    this.self = self;
    if (!getPageTypes(self)) {
      this._applicationShow(self);
    }
  }

  ready(self) {
    this.self = self;
    if (getPageTypes(self)) {
      this._pageShow(self);
    }
  }
  hide(self) {
    this.self = self;
    if (getPageTypes(self)) {
      this._pageHide(self);
    } else {
      this._applicationHide(self, true);
    }
  }
  error(em) {
    if (this._platform === 'devtools') {
      if (process.env.NODE_ENV === 'development') {
        console.info('当前运行环境为开发者工具,不上报数据。');
      }
      // return;
    }
    let emVal = ''
    if (!em.message) {
      emVal = JSON.stringify(em)
    } else {
      emVal = em.stack
    }
    let options = {
      ak: this.statData.ak,
      uuid: this.statData.uuid,
      lt: '31',
      ut: this.statData.ut,
      ch: this.statData.ch,
      mpsdk: this.statData.mpsdk,
      mpv: this.statData.mpv,
      v: this.statData.v,
      em: emVal,
      usv: this.statData.usv,
      t: getTime(),
      p: this.statData.p
    }
    this.request(options);
  }
}
export default Stat