tz-content-sdk
Version:
内容中心
668 lines (649 loc) • 23.1 kB
JavaScript
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var LogType;
(function (LogType) {
LogType["T101"] = "101";
LogType["T102"] = "102";
LogType["T103"] = "103";
LogType["T104"] = "104";
LogType["T105"] = "105";
LogType["T111"] = "111";
LogType["T112"] = "112";
LogType["T113"] = "113";
LogType["T121"] = "121";
})(LogType || (LogType = {}));
var SourceFrom;
(function (SourceFrom) {
SourceFrom["YISEN_AJN"] = "YISEN_AJN";
SourceFrom["YISEN_CONTENT_H5"] = "YISEN_CONTENT_H5";
SourceFrom["HEYSHOP_CONSTELLATION_MINI"] = "HEYSHOP_CONSTELLATION_MINI";
})(SourceFrom || (SourceFrom = {}));
function isWX () {
return typeof wx !== "undefined" && wx.getSystemInfo;
}
function isTT () {
return typeof tt !== "undefined" && tt.getSystemInfo;
}
function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response;
}
var error = new Error(response.statusText);
error.response = response;
throw error;
}
var http = (function () {
function http() {
}
http.request = function (method, url, data, token) {
if (isWX()) {
return new Promise(function (resolve, reject) {
wx.request({
url: url,
header: {
"content-type": "application/json",
"X-Open-Api-Token": token,
},
method: method,
data: data,
success: function (res) {
resolve(res.data);
},
fail: function (res) {
reject(res);
},
});
});
}
if (isTT()) {
return new Promise(function (resolve, reject) {
tt.request({
url: url,
header: {
"content-type": "application/json",
"X-Open-Api-Token": token,
},
method: method,
data: data,
success: function (res) {
resolve(res.data);
},
fail: function (res) {
reject(res);
},
});
});
}
var fetchParams = {
headers: {
"content-type": "application/json",
"X-Open-Api-Token": token ? token : "",
},
method: method,
};
if (method === "POST" && data) {
fetchParams.body = JSON.stringify(data);
}
if (method === "GET" && data) {
var paramsArray_1 = [];
Object.keys(data).forEach(function (key) {
return paramsArray_1.push(key + "=" + data[key]);
});
if (url.search(/\?/) === -1) {
url += "?" + paramsArray_1.join("&");
}
else {
url += "&" + paramsArray_1.join("&");
}
}
return fetch(url, fetchParams)
.then(checkStatus)
.then(function (response) { return response.json(); });
};
http.get = function (url, data, token) {
return this.request("GET", url, data, token);
};
http.post = function (url, data, token) {
return this.request("POST", url, data, token);
};
return http;
}());
function randomStr(size) {
if (size === void 0) { size = 16; }
var str = Math.floor(Math.random() * 1e12).toString(16) + Math.floor(Math.random() * 1e12).toString(16);
return str.slice(0, size);
}
var contants = {
LOGURL: "https://dc-logapi-test.tezign.com/log-content/event",
};
var Base = (function () {
function Base(config) {
this.startTime = new Date().getTime();
this.postlossed = false;
this.isScrollBottom = false;
this.logConfig = this.getLogConfig(config);
this.checkRequiredValues(config);
if (this.logConfig.env === "producation") {
contants.LOGURL = "https://tracking.tezign.com/log-content/event";
}
if (this.logConfig.columnId) {
this.getSystemInfo();
}
else {
setTimeout(this.getSystemInfo.bind(this), 500);
}
}
Base.prototype.checkRequiredValues = function (config) {
var sourceFrom = config.sourceFrom, columnId = config.columnId, isShared = config.isShared;
if (!(sourceFrom in SourceFrom)) {
var sourceFromStr = Object.keys(SourceFrom).join(" / ");
console.error("sourceFrom 是枚举值!当前值:", sourceFrom, "。可选枚举字段:", sourceFromStr);
}
if (!isShared && !columnId) {
console.error("columnId 在当前场景下是必传字段!当前值:", columnId);
}
};
Base.prototype.getLogConfig = function (config) {
var env = config.env, openId = config.openId, unionId = config.unionId, userId = config.userId, contentId = config.contentId, sessionId = config.sessionId, character = config.character, columnId = config.columnId, title = config.title, columnName = config.columnName, keyWords = config.keyWords, isShared = config.isShared, sellerId = config.sellerId, sellerName = config.sellerName, department = config.department, sourceFrom = config.sourceFrom;
if (typeof columnId === "undefined" || columnId === null) {
console.warn("columnId 不能为空值");
}
return {
env: env,
openId: openId,
deviceId: userId,
unionId: unionId,
contentId: contentId,
character: character,
columnId: columnId,
sessionId: sessionId || randomStr(),
tenantId: env === "production" ? "t151" : "t1",
title: title,
columnName: columnName,
keyWords: keyWords || null,
isShared: isShared || false,
sellerId: sellerId || null,
sellerName: sellerName || null,
department: department || null,
sourceFrom: sourceFrom,
};
};
Base.prototype.send = function (type, metadata) {
var logConfig = this.logConfig;
var data = __assign(__assign({}, logConfig), { type: type,
metadata: metadata });
var contentIdType = typeof data.contentId;
if (contentIdType !== "number") {
return console.error("contentId 的类型错误,期望是 number 类型,而不是 " +
contentIdType +
" 类型");
}
if (isNaN(data.contentId)) {
return console.error("contentId 不能是 NaN");
}
if (data.columnId) {
http.post("" + contants.LOGURL, data);
}
else {
setTimeout(function () {
http.post("" + contants.LOGURL, __assign(__assign({}, logConfig), { type: type,
metadata: metadata }));
}, 200);
}
if (this.logConfig.env !== "producation") {
console.log("type", type);
console.log("metadata", metadata);
}
};
Base.prototype.upgradeColumnId = function (columnId) {
if (!this.logConfig.columnId && columnId) {
this.logConfig.columnId = columnId;
}
};
Base.prototype.getSystemInfo = function () {
if (isWX()) {
var _this_1 = this;
wx.getSystemInfo({
success: function (res) {
console.log(res);
if (res) {
var SDKVersion = res.SDKVersion, batteryLevel = res.batteryLevel, brand = res.brand, language = res.language, platform = res.platform, screenHeight = res.screenHeight, screenWidth = res.screenWidth, statusBarHeight = res.statusBarHeight, system = res.system, windowHeight = res.windowHeight;
var data = {
SDKVersion: SDKVersion,
batteryLevel: batteryLevel,
brand: brand,
language: language,
platform: platform,
screenHeight: screenHeight,
screenWidth: screenWidth,
statusBarHeight: statusBarHeight,
system: system,
windowHeight: windowHeight,
};
_this_1.mpSystemInfo = data;
_this_1.send(LogType.T121, data);
}
},
});
}
};
return Base;
}());
var Heatmap = (function () {
function Heatmap(config) {
this.scrollContentHeight = -1;
this.preTimeStamp = 0;
this.parts = 50;
this.hiding = false;
this.interval = 350;
this.initTimeStamp = 0;
this.config = config;
this.preTimeStamp = Date.now();
this.initTimeStamp = Date.now();
}
Heatmap.prototype.report = function (scrollTop) {
var _this = this;
var now = Date.now();
var timeDelta = now - this.preTimeStamp;
if (timeDelta < this.interval) {
return;
}
if (now - this.initTimeStamp > 60 * 1000) {
this.interval = 600;
}
var topPercent = Math.max(scrollTop, 0) / this.scrollContentHeight;
var bottomPercent = Math.min(scrollTop + this.config.windowHeight, this.scrollContentHeight);
var partAndTime = [
topPercent,
bottomPercent / this.scrollContentHeight,
].map(function (ele) { return Math.floor(ele * _this.parts); });
this.preTimeStamp = now;
var data = {
duration: timeDelta,
proportion: partAndTime,
partition: this.parts,
};
return data;
};
Heatmap.prototype.handleScrollEvent = function (scrollHeight, scrollTop) {
if (this.hiding) {
return;
}
if (this.scrollContentHeight < 0) {
this.scrollContentHeight = scrollHeight;
}
if (this.config.windowHeight < 0) {
this.getSystemInfo(this.config);
return;
}
var data = this.report(scrollTop);
if (data) {
this.config.reportData(data);
}
};
Heatmap.prototype.getSystemInfo = function (config) {
wx.getSystemInfo({
success: function (res) {
console.log(res);
var windowHeight = res.windowHeight;
config.windowHeight = windowHeight;
},
});
};
Heatmap.prototype.onHide = function () {
this.hiding = true;
};
Heatmap.prototype.onShow = function () {
this.hiding = false;
this.preTimeStamp = Date.now();
};
return Heatmap;
}());
var Secend2 = 2 * 1000;
var Secend5 = 5 * 1000;
var Secend10 = 10 * 1000;
var Secend60 = 60 * 1000;
var Accesstime = (function () {
function Accesstime(config) {
this.timeStamp = 0;
this.duration = 0;
this.timeout = Secend2;
this.timeId = null;
this.config = config;
var timeout = config.timeout, startTime = config.startTime;
if (typeof timeout === "number" && timeout > 2000 && timeout < 20000) {
this.timeout = timeout;
}
this.timeStamp = startTime || Date.now();
this.accumulation = this.accumulation.bind(this);
this.setInterval();
}
Accesstime.prototype.report = function () {
this.config.reportData(this.duration);
return this.duration;
};
Accesstime.prototype.setInterval = function () {
if (typeof this.timeId === "number") {
clearInterval(this.timeId);
}
this.timeId = setInterval(this.accumulation, this.timeout);
};
Accesstime.prototype.accumulation = function () {
var current = Date.now();
this.duration += current - this.timeStamp;
this.timeStamp = current;
if (this.duration > Secend10 && this.timeout < Secend5) {
this.timeout = Secend5;
this.report();
this.timeId && clearInterval(this.timeId);
this.timeId = setInterval(this.accumulation, Secend5);
}
else if (this.duration > Secend60 && this.timeout < Secend10) {
this.timeout = Secend10;
this.report();
this.timeId && clearInterval(this.timeId);
this.timeId = setInterval(this.accumulation, Secend10);
}
else if (this.duration > 600 * 1000 && this.timeId) {
clearInterval(this.timeId);
this.timeId = null;
}
return this.report();
};
Accesstime.prototype.close = function () {
this.accumulation();
if (this.timeId) {
clearInterval(this.timeId);
this.timeId = null;
}
};
Accesstime.prototype.onHide = function () {
this.close();
};
Accesstime.prototype.onShow = function () {
var current = Date.now();
this.timeStamp = current;
this.setInterval();
};
Accesstime.prototype.onUnload = function () {
this.close();
};
return Accesstime;
}());
var Log$1 = (function (_super) {
__extends(Log, _super);
function Log(config) {
var _this = _super.call(this, config) || this;
_this.maxScrollPercent = 0;
_this.clientHeight = config.clientHeight;
_this.scrollTimestamp = Date.now();
_this.contentCreateTime = config.contentCreateTime;
return _this;
}
Log.prototype.event_page_pv = function () {
this.send(LogType.T101, {
sdkVersion: "0.1.23",
});
};
Log.prototype.event_page_access_time = function (timeout) {
var _this = this;
if (this.accesstime) {
return;
}
var startTime = this.startTime;
this.accesstime = new Accesstime({
timeout: timeout,
startTime: startTime,
reportData: function (duration) {
var endTime = new Date().getTime();
var metadata = {
startTime: startTime,
endTime: endTime,
duration: duration,
};
_this.send(LogType.T102, metadata);
if (duration > 10 * 1000) {
_this.event_page_loss_access();
}
},
});
};
Log.prototype.event_page_hotaccess_time = function (scrollHeight, scrollTop) {
var _this = this;
if (this.heatmap) {
this.heatmap.handleScrollEvent(scrollHeight, scrollTop);
return;
}
var windowHeight = this.clientHeight;
this.heatmap = new Heatmap({
windowHeight: windowHeight,
reportData: function (data) {
_this.send(LogType.T103, data);
},
});
};
Log.prototype.event_page_loss_access = function () {
if (!this.postlossed) {
this.send(LogType.T104);
this.postlossed = true;
}
};
Log.prototype.event_page_hide = function () {
this.event_page_loss_access();
if (this.accesstime) {
this.accesstime.onHide();
}
if (this.heatmap) {
this.heatmap.onHide();
}
};
Log.prototype.event_page_show = function () {
this.event_page_loss_access();
if (this.accesstime) {
this.accesstime.onShow();
}
if (this.heatmap) {
this.heatmap.onShow();
}
};
Log.prototype.event_page_send_position = function (scrollHeight, scrollTop) {
if (this.isScrollBottom)
return;
this.event_page_loss_access();
var clientHeight = this.clientHeight;
if (scrollHeight <= clientHeight) {
this.isScrollBottom = true;
this.send(LogType.T105, {
proportion: 1,
});
return;
}
var now = Date.now();
if (now - this.scrollTimestamp < 350) {
return;
}
this.scrollTimestamp = now;
var percent = Math.min(1, (scrollTop + clientHeight) / scrollHeight);
if (percent === 1) {
this.isScrollBottom = true;
}
if (percent > this.maxScrollPercent) {
if (this.logConfig.env !== "producation") {
this.send(LogType.T105, {
proportion: percent,
scrollHeight: scrollHeight,
scrollTop: scrollTop,
});
}
this.send(LogType.T105, {
proportion: percent,
});
this.maxScrollPercent = percent;
}
};
Log.prototype.event_page_unload = function () {
if (this.accesstime) {
this.accesstime.onUnload();
if (this.logConfig.env !== "producation") {
console.log("退出单页,定时器卸载");
}
}
};
Log.prototype.event_page_useful = function () {
this.send(LogType.T111);
this.event_page_loss_access();
};
Log.prototype.event_page_download = function () {
this.send(LogType.T112, {
contentCreateTime: this.contentCreateTime,
});
this.event_page_loss_access();
};
Log.prototype.event_page_share = function () {
this.send(LogType.T113, {
contentCreateTime: this.contentCreateTime,
});
this.event_page_loss_access();
};
Log.SourceFrom = SourceFrom;
return Log;
}(Base));
var storage = {
set: function (key, value) {
try {
if (typeof localStorage !== undefined) {
localStorage.setItem(key, JSON.stringify(value));
}
else if (isWX()) {
wx.setStorageSync(key, value);
}
else if (isTT()) {
tt.setStorageSync(key, value);
}
}
catch (e) { }
},
get: function (key) {
var value;
try {
if (typeof localStorage !== undefined) {
value = localStorage.getItem(key);
if (value)
value = JSON.parse(value);
}
else if (isWX()) {
value = wx.getStorageSync(key);
}
else if (isTT()) {
value = tt.getStorageSync(key);
}
}
catch (e) { }
return value;
},
};
function int2str(number) {
return number.toString(36);
}
function str2int(str) {
return parseInt(str, 36);
}
function getNowStr() {
return int2str(parseInt(Date.now() / 1000));
}
var Options = {
API_ORIGIN: "https://open-api.tezign.com/open-api/v1",
sessionTimeout: 30 * 60,
initData: undefined,
};
var TezignContent$1 = {
_token: storage.get("content_token") ? storage.get("content_token") : "",
getToken: function () {
return this._token.substring(0, this._token.length - 7);
},
init: function (options) {
if (options && options.initData) {
Options.initData = options.initData;
}
if (options && options.sessionTimeout) {
Options.sessionTimeout = options.sessionTimeout;
}
if (!TezignContent$1._token) {
return TezignContent$1.createToken();
}
else {
return TezignContent$1.refreshToken(TezignContent$1._token, Options.sessionTimeout);
}
},
createToken: function () {
return http
.post(Options.API_ORIGIN + "/common/latestnews/generate", Options.initData)
.then(function (res) {
console.log(res.result.token);
TezignContent$1._token = res.result.token + "." + getNowStr();
storage.set("content_token", TezignContent$1._token);
return res.result.token;
});
},
refreshToken: function (session, timeout) {
var idx = session.lastIndexOf(".");
var _pt = str2int(session.substr(idx + 1, 6));
if (Math.round(Date.now() / 1000) - _pt > timeout) {
return TezignContent$1.createToken();
}
else {
return Promise.resolve();
}
},
getContentList: function (params) {
return http.post(Options.API_ORIGIN + "/customized/trend/list", params, TezignContent$1.getToken());
},
getContentItem: function (params) {
return http.get(Options.API_ORIGIN + "/customized/trend/detail", params, TezignContent$1.getToken());
},
getContentLabels: function (params) {
return http.post(Options.API_ORIGIN + "/customized/trend/labelList", params, TezignContent$1.getToken());
},
};
var Log = Log$1;
var TezignContent = TezignContent$1;
var index = {
Log: Log$1,
TezignContent: TezignContent$1,
};
export default index;
export { Log, TezignContent };