| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034 |
- // var window.mode_env = 'development';
- window.mode_env = 'production';
- let API_URL=window.themeConfig.api;
- // if (
- // window.location.href.indexOf('localhost') >= 0 ||
- // window.location.href.indexOf('192.168.1.') >= 0 ||
- // window.location.href.indexOf('192.168.11.') >= 0 ||
- // window.location.href.indexOf('10.10.100.') >= 0 ||
- // window.location.href.indexOf('bigwinga.me') >= 0 ||
- // window.location.href.indexOf('thekongfu.com') >= 0 ||
- // window.location.href.indexOf('kysdkllc.com') >= 0
- // ) {
- // window.mode_env = 'development';
- // } else {
- // window.mode_env = 'production';
- // }
- // 初始化 渠道信息
- var SingletonChannelInfo = (function () {
- // 存储单例实例的变量
- var instance;
- // 初始化实例的函数
- function init(newh2, newh3, newh4) {
- var h2 = newh2 || 'h5';
- var h3 = newh3 || 'web';
- var h4 = newh4 || '';
- return {
- // 公有方法和属性
- h2,
- h3,
- h4
- };
- }
- return {
- // 获取单例的实例的方法
- getInstance: function (...args) {
- if (!instance && args.length > 0) {
- instance = init(...args); // 如果实例不存在,创建它
- }
- if (!instance && args.length === 0) {
- instance = init();
- }
- return instance; // 返回单例实例
- }
- };
- })();
- // function getCookie(key) {
- // const cookie = document.cookie;
- // const cookieArr = cookie.split(";");
- // const cookieObj = {};
- // cookieArr.forEach((item) => {
- // const [key, value] = item.split("=");
- // cookieObj[key.trim()] = value;
- // });
- // return key ? cookieObj[key] : cookieObj;
- // }
- window.hasFixexpire = false;
- function getCookie(key) {
- const cookie = document.cookie;
- const cookieArr = cookie.split(';');
- const cookieObj = {};
- cookieArr.forEach(item => {
- const [k, v] = item.split('=');
- const trimmedKey = k ? k.trim() : '';
- const trimmedValue = v ? v.trim() : '';
- if (trimmedKey && trimmedValue) cookieObj[trimmedKey] = trimmedValue;
- });
- if (!window.hasFixexpire) {
- if (cookieObj['winus_uuid']) {
- setCookie('winus_uuid', cookieObj['winus_uuid']);
- }
- if (cookieObj['us_h5_sourceurl_key']) {
- setCookie('us_h5_sourceurl_key', cookieObj['us_h5_sourceurl_key']);
- }
- window.hasFixexpire = true;
- }
- return key ? cookieObj[key] : cookieObj;
- }
- function setCookie(key, value, expires = 365 * 24 * 60 * 60 * 1000) {
- const date = new Date();
- date.setTime(date.getTime() + expires);
- document.cookie = `${key}=${value};path=/;domain=.${window.location.hostname.split('.').slice(-2).join('.')};expires=${date.toUTCString()};SameSite=None;Secure;`;
- }
- function isInApk() {
- if (!window.android) return false;
- if (!window.android?.getDeviceID || !window.android?.saveUserID) return false;
- return true;
- }
- function getSubscriptionInfo() {
- var installed = isPwaInstall();
- var cacheKey = 'submit_subscription_' + udatadict.channel + '_' + udatadict.userid + '_' + installed;
- return localStorage.getItem(cacheKey) === '1';
- }
- function getSafeReturnUrl(value) {
- if (typeof value !== 'string' || value.trim() === '') return '';
- try {
- var url = new URL(value, window.location.href);
- return url.protocol === 'http:' || url.protocol === 'https:' ? url.href : '';
- } catch (error) {
- return '';
- }
- }
- function getIsPostData() {
- var installed = isPwaInstall();
- var cacheKey = 'submit_subscription_post_' + udatadict.channel + '_' + udatadict.userid + '_' + installed;
- return localStorage.getItem(cacheKey) === '1';
- }
- function setIsPostData() {
- var installed = isPwaInstall();
- var cacheKey = 'submit_subscription_post_' + udatadict.channel + '_' + udatadict.userid + '_' + installed;
- localStorage.setItem(cacheKey, '1');
- }
- // 获取全局唯一标识
- var getUniqueID = (function () {
- // 缓存全局唯一标识
- let __global_unique_ID;
- // 缓存 promise 避免多次执行
- let promiseInProgress = null;
- function resolveUniqueID(resolve, value) {
- let uniqueID = value;
- if (!uniqueID) {
- try {
- uniqueID = getLocalUUID();
- } catch (error) {
- errorpushlog('Failed to create local unique ID:', error);
- }
- }
- if (uniqueID) {
- __global_unique_ID = uniqueID;
- try {
- setCookie('winus_uuid', uniqueID, 604800000);
- } catch (error) {
- errorpushlog('Failed to cache unique ID:', error);
- }
- }
- resolve(uniqueID || '');
- }
- return function () {
- if (__global_unique_ID) {
- return Promise.resolve(__global_unique_ID);
- }
- // 如果已经有全局唯一标识, 直接返回
- var cookie_md5_val = getCookie('winus_uuid');
- // if(!cookie_md5_val){
- // cookie_md5_val=getLocalUUID();
- // if(cookie_md5_val){
- // setCookie('winus_uuid', cookie_md5_val, 604800000);
- // }
- // }
- if (cookie_md5_val) {
- __global_unique_ID = cookie_md5_val;
- return Promise.resolve(__global_unique_ID);
- }
- if (promiseInProgress) {
- return promiseInProgress;
- }
- if (isInApk()) {
- // apk 环境下, 直接返回
- promiseInProgress = new Promise(resolve => {
- let completed = false;
- const finish = deviceId => {
- if (completed) return;
- completed = true;
- clearTimeout(timeoutId);
- resolveUniqueID(resolve, deviceId);
- };
- const timeoutId = setTimeout(() => finish(''), 5000);
- try {
- // IPA 环境
- if (window?.android?.isIpa) {
- // 确保回调函数在调用 getDeviceID 之前就绑定好
- window.android.deviceIdCallback = function (deviceId) {
- finish(deviceId);
- };
- window.android.getDeviceID?.();
- return;
- }
- // 普通 APK 环境
- const deviceId = window?.android?.getDeviceID?.();
- finish(deviceId);
- } catch (error) {
- errorpushlog('Failed to read native device ID:', error);
- finish('');
- }
- });
- return promiseInProgress;
- }
- promiseInProgress = new Promise(function (resolve) {
- var iframe = document.createElement('iframe');
- iframe.src = window.location.protocol + '//cen.greatus777.com/storage';
- // iframe.src = window.location.protocol + '//' + 'dev.winus777.com' + '/storage';
- var iframeOrigin = new URL(iframe.src).origin;
- var timeoutId = null;
- var completed = false;
- function cleanup() {
- if (timeoutId) clearTimeout(timeoutId);
- window.removeEventListener('message', messageHandler);
- if (iframe.parentNode) iframe.parentNode.removeChild(iframe);
- }
- function finish(value) {
- if (completed) return;
- completed = true;
- cleanup();
- resolveUniqueID(resolve, value);
- }
- iframe.style.display = 'none';
- iframe.addEventListener('load', function () {
- iframe.contentWindow?.postMessage('getUniqueID', iframeOrigin);
- }, { once: true });
- iframe.addEventListener('error', function () {
- finish('');
- }, { once: true });
- function messageHandler(event) {
- if (event.origin !== iframeOrigin || event.source !== iframe.contentWindow) return;
- const uniqueID = event.data && typeof event.data === 'object' ? event.data.md5val : '';
- if (uniqueID) finish(uniqueID);
- }
- // 监听 iframe 的消息
- window.addEventListener('message', messageHandler);
- document.body.appendChild(iframe);
- timeoutId = setTimeout(function () {
- finish('');
- }, 8000);
- });
- return promiseInProgress;
- };
- })();
- /**
- * 上报订阅信息
- * @param {*} data
- * {
- * userid: 1, // 用户ID
- * result: 1, // 1 接受 2未接受 3 不支持 4 拒绝
- * machineserial 机器码
- * ish5 0:app(w2a),1:h5(pwa)
- * p_source
- * }
- */
- function uploadSubscription(data) {
- if (+data.ish5 !== 0 && +data.ish5 !== 1) return;
- const ajax = new XMLHttpRequest();
- const callback = data.callback;
- ajax.open('POST', API_URL+"/api/upload_subscribe_state", true);
- ajax.setRequestHeader('Content-Type', 'application/json');
- ajax.onreadystatechange = function () {
- if (ajax.readyState === 4 && ajax.status === 200) {
- setIsPostData();
- }
- callback && callback();
- };
- ajax.onerror = function () {
- callback && callback();
- };
- ajax.send(JSON.stringify(data));
- }
- function isIOS() {
- try {
- let u = navigator.userAgent;
- let isIOS = false;
- // 检查是否包含 iPhone, iPad, iPod 或 Mac OS X (通常Safari在iOS上运行)
- if (/(iPhone|iPad|iPod|iOS)/i.test(u)) {
- isIOS = true;
- }
- // 排除 Android,避免误判
- if (u.indexOf('Android') > -1 || u.indexOf('Adr') > -1) {
- isIOS = false;
- }
- return isIOS
- } catch (t) {
- return false
- }
- }
- function openUrlUseSafari(url = "", isNewTab = true, isBFP = true) {
- if (url == null || url === "") url = window.location.href;
- if (window.BFP != null && window.BFP !== "" && isBFP) {
- if (url.indexOf("?") === -1) url += "?bfp=" + window.BFP;
- else url += "&bfp=" + window.BFP;
- }
- if (isIOS()) {
- const safariUrl = url.startsWith('https')
- ? url.replace('https://', 'x-safari-https://')
- : url.replace('http://', 'x-safari-https://');
- if (isNewTab) {
- window.open(safariUrl, '_blank', 'noopener,noreferrer');
- } else {
- window.location.href = safariUrl;
- }
- }
- }
- function openChrome() {
- var url = window.location.href;
- if (isIOS()) {
- let r = "googlechromes://" + url.replace(/^https?:\/\//, "");
- window.open(r, "_blank", "noopener,noreferrer");
- } else {
- url = url.replace('https://', '');
- url = url.replace('http://', '');
- var newLink =
- 'intent://' + url + '#Intent;scheme=https;action=android.intent.action.VIEW;component=com.android.chrome;end';
- var a = document.getElementById('pwaIFrame');
- if (!a) {
- a = document.createElement('iframe');
- a.id = 'pwaIFrame';
- a.style.width = '0';
- a.style.height = '0';
- a.style.opacity = '0';
- a.name = 'pwaIFrame';
- document.body.appendChild(a);
- }
- a.src = newLink;
- }
- setTimeout(() => {
- if (!document.hidden) {
- uploadSubscription({
- userid: udatadict.userid || '',
- result: 3,
- machineserial: udatadict.machineserial,
- ish5: 1,
- p_source: udatadict.channel
- });
- }
- }, 1000);
- document.body.removeEventListener('click', openChrome);
- }
- // 判断是否在 chrome 浏览器中
- function isInChromeBrowser() {
- return /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
- }
- var pushOfFingerprint = '';
- var udatadict = {};
- var pushLogOpen = true;
- function pushmlog(...args) {
- if (pushLogOpen) {
- console.log('Push log:', ...args);
- }
- }
- function errorpushlog(...args) {
- if (true) {
- console.error('Push error log:', ...args);
- }
- }
- // 将URL Base64编码的字符串转换为Uint8Array
- function urlBase64ToUint8Array(base64String) {
- var padding = '='.repeat((4 - (base64String.length % 4)) % 4);
- var base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
- var rawData = window.atob(base64);
- var outputArray = new Uint8Array(rawData.length);
- for (var i = 0; i < rawData.length; ++i) {
- outputArray[i] = rawData.charCodeAt(i);
- }
- return outputArray;
- }
- // 判断是否在PWA模式下运行
- function isPwaInstall() {
- if (
- window.matchMedia('(display-mode: standalone)').matches ||
- window.navigator.standalone ||
- document.referrer.includes('android-app://')
- ) {
- return 1;
- } else {
- return 0;
- }
- }
- // 获取平台
- function getPlatform() {
- var ua = navigator.userAgent;
- if (ua.match(/Android/i)) {
- return 'Android';
- } else if (ua.match(/iPhone|iPad|iPod/i)) {
- return 'iOS';
- } else {
- return 'Other';
- }
- }
- // 将订阅信息发送到服务器
- function submitSubscription(subscription, channel, userid) {
- // 注意落地页和游戏内的指纹算法保持一致!!!
- var fingerprint = pushOfFingerprint;
- var website = window.location.href;
- // 发送订阅信息到服务器
- // xmlhttprequest
- var xhr = new XMLHttpRequest();
- // 墨西哥订阅地址
- if (window.mode_env === 'development') {
- xhr.open('POST', API_URL + '/api/push_subscribe', true);
- } else {
- xhr.open('POST', API_URL + '/api/push_subscribe', true);
- }
- xhr.setRequestHeader('Content-Type', 'application/json');
- var contentData = {
- fingerprint: fingerprint,
- userid: userid, // 如果有用户登录,可以传用户ID
- subscibe_info: JSON.stringify(subscription),
- channel: channel,
- web_site: website,
- platform: getPlatform(),
- installed: isPwaInstall()
- };
- xhr.onreadystatechange = function () {
- if (xhr.readyState === 4 && xhr.status === 200) {
- pushmlog('Subscription info sent to server:', xhr.responseText);
- var installed = isPwaInstall();
- var cacheKey = 'submit_subscription_' + channel + '_' + userid + '_' + installed;
- localStorage.setItem(cacheKey, '1');
- }
- };
- xhr.onerror = function () {
- errorpushlog('Failed to send subscription info');
- };
- xhr.send(JSON.stringify(contentData));
- }
- // 埋点日志
- function recordEvent(eventName, channel, remark, userid) {
- var info = SingletonChannelInfo.getInstance();
- var h2 = info.h2;
- var h3 = info.h3;
- var h4 = info.h4 || channel;
- var host = 'us_' + h2 + '_' + h3 + '_' + h4;
- var url =
- API_URL + '/api/weblog?host=' + host + '&act=' + eventName + '&remark=' + remark + '&orderid=' + userid;
- var xhr = new XMLHttpRequest();
- xhr.open('GET', url, true);
- xhr.send();
- }
- // 请求用户授权订阅推送通知
- function requestNotificationPermission(registration, channel, userid, machineserial, ish5) {
- // 检查浏览器是否支持Notification API
- if ('Notification' in window) {
- // 请求授权
- Notification.requestPermission().then(function (permission) {
- if (permission === 'granted') {
- pushmlog('User has authorized push notifications');
- recordEvent('push_permission', channel, 'allow', userid);
- // 注册Service Worker
- return registration.pushManager
- .subscribe({
- userVisibleOnly: true,
- applicationServerKey: urlBase64ToUint8Array(
- 'BEKE0qlrGMp-XyUHppeFMscDiJg-sL98jr4b51glbvicHnD69oNZ9JiLHKIQ9_3K0ImSZlo0Ggw-RE3FxYOUwJo'
- )
- })
- .then(function (subscription) {
- var saveSubScription = JSON.stringify(subscription);
- localStorage.setItem('subscription', saveSubScription);
- pushmlog('User has subscribed to push notifications:', subscription);
- // 将订阅信息发送到服务器
- submitSubscription(subscription, channel, userid);
- uploadSubscription({
- userid: userid || '',
- result: 1,
- machineserial,
- ish5,
- p_source: channel,
- callback: function () {
- if (+ish5 === 1 || +ish5 === 0) {
- // 如果是H5游戏, 则打开网址
- if (+ish5 === 1) {
- if (udatadict.returnurl) {
- setTimeout(() => {
- window.location.href = udatadict.returnurl;
- }, 1000);
- }
- } else {
- // 打开游戏
- const div = document.createElement('div');
- div.style =
- 'position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.5); z-index: 9999;';
- div.innerHTML = `<div
- style="padding: 6px 10px; border-radius: 4px; background: rgba(89, 92, 115, 0.65); position: absolute; left: 50%;transform: translateX(-50%); color: #fff;font-size: 14px;top: 10%;">
- Go back to the game
- </div>`;
- document.body.appendChild(div);
- setTimeout(function () {
- document.body.removeChild(div);
- }, 3000);
- }
- }
- }
- });
- })
- .catch(function (error) {
- errorpushlog('Failed to subscribe to push notifications:', error);
- });
- } else if (permission === 'denied') {
- pushmlog('User denied push notifications', userid, machineserial, ish5, channel);
- recordEvent('push_permission', channel, 'deny', userid);
- uploadSubscription({
- userid: userid || '',
- result: 4,
- machineserial,
- ish5,
- p_source: channel,
- callback: function () {
- if (+ish5 === 1 || +ish5 === 0) {
- // 如果是H5游戏, 则打开网址
- if (+ish5 === 1) {
- if (udatadict.returnurl) {
- setTimeout(() => {
- window.location.href = udatadict.returnurl;
- }, 1000);
- }
- } else {
- // 打开游戏
- const div = document.createElement('div');
- div.style =
- 'position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.5); z-index: 9999;';
- div.innerHTML = `<div
- style="padding: 6px 10px; border-radius: 4px; background: rgba(89, 92, 115, 0.65); position: absolute; left: 50%;transform: translateX(-50%); color: #fff;font-size: 14px;top: 10%;">
- Go back to the game
- </div>`;
- document.body.appendChild(div);
- setTimeout(function () {
- document.body.removeChild(div);
- }, 3000);
- }
- }
- }
- });
- } else {
- pushmlog('User has not decided whether to authorize push notifications');
- uploadSubscription({
- userid: userid || '',
- result: 2,
- machineserial,
- ish5,
- p_source: channel,
- callback: function () {
- if (+ish5 === 1 || +ish5 === 0) {
- // 如果是H5游戏, 则打开网址
- if (+ish5 === 1) {
- if (udatadict.returnurl) {
- setTimeout(() => {
- window.location.href = udatadict.returnurl;
- }, 1000);
- }
- } else {
- // 打开游戏
- const div = document.createElement('div');
- div.style =
- 'position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.5); z-index: 9999;';
- div.innerHTML = `<div
- style="padding: 6px 10px; border-radius: 4px; background: rgba(89, 92, 115, 0.65); position: absolute; left: 50%;transform: translateX(-50%); color: #fff;font-size: 14px;top: 10%;">
- Go back to the game
- </div>`;
- document.body.appendChild(div);
- setTimeout(function () {
- document.body.removeChild(div);
- }, 3000);
- }
- }
- }
- });
- recordEvent('push_permission', channel, 'pending', userid);
- }
- }).catch(function (error) {
- errorpushlog('Failed to request notification permission:', error);
- });
- }
- }
- var isCheckingPushPermission = false; // 如果正在检查推送权限, 则不再检查, 避免在未收到结果前再次调用,会有多个订阅上报
- /**
- * 外部调用 检查推送权限
- * @param {string} channel 渠道标识
- * @param {number} userid 用户ID
- * @param {string} machineserial 机器码
- * @param {number} type 0:app(w2a),1:h5(pwa)
- * @param {object} options 其他参数
- * */
- function checkPushPermission(channel, userid, machineserial, type, options) {
- var returnurl = options && options.returnurl;
- var endCallback = options && options.endCallback;
- try {
- if (userid == null) {
- userid = 0;
- }
- if (channel == null) {
- channel = 'default';
- }
- getUniqueID().then(fingerprint => {
- pushOfFingerprint = fingerprint; // 先记录下来
- // 如果有连续调用, 那么只记录最后一次的 udatadict
- udatadict.userid = userid;
- udatadict.channel = channel;
- udatadict.fingerprint = fingerprint;
- udatadict.machineserial = machineserial;
- udatadict.type = type;
- udatadict.returnurl = getSafeReturnUrl(returnurl);
- // 保存到 localstorage
- localStorage.setItem('pushudatadict', JSON.stringify(udatadict));
- if ('serviceWorker' in navigator)
- navigator.serviceWorker.ready
- .then(function (registration) {
- if (isCheckingPushPermission) {
- return;
- }
- isCheckingPushPermission = true;
- // 检查是否支持service worker
- if (!registration?.pushManager) {
- isCheckingPushPermission = false;
- !isInApk() &&
- setTimeout(() => {
- document.body.addEventListener('click', openChrome);
- }, 500);
- errorpushlog('registration or pushManager is undefined');
- return;
- }
- var installed = isPwaInstall();
- var cacheKey = 'submit_subscription_' + udatadict.channel + '_' + udatadict.userid + '_' + installed;
- return registration.pushManager.getSubscription().then(function (subscription) {
- isCheckingPushPermission = false; // 已经有结果了
- if (subscription) {
- var subscriptionOld = localStorage.getItem('subscription');
- endCallback && endCallback('subscription');
- // 用户已经订阅推送通知
- pushmlog('User has already subscribed to push notifications');
- // 判断 当前渠道+当前用户 是否已经上报过授权. 如果未上报过, 则上报一次
- var cacheValue = localStorage.getItem(cacheKey);
- if (cacheValue && subscriptionOld && subscriptionOld === JSON.stringify(subscription)) {
- pushmlog('User has already reported subscription info');
- return;
- }
- recordEvent('push_permission', udatadict.channel, 'update', udatadict.userid);
- localStorage.setItem('subscription', JSON.stringify(subscription)); // 更新
- submitSubscription(subscription, udatadict.channel, udatadict.userid); // 已经授权过就再上报一次 如果未上报
- const ispost = getIsPostData();
- if (!ispost) {
- uploadSubscription({
- userid: udatadict.userid || '',
- result: 1,
- machineserial: udatadict.machineserial,
- ish5: udatadict.type,
- p_source: udatadict.channel
- });
- }
- return;
- } else {
- // 用户尚未订阅推送通知
- pushmlog('User has not yet subscribed to push notifications');
- localStorage.removeItem(cacheKey);
- // 判断 通知状态
- if (Notification.permission === 'denied') {
- endCallback && endCallback('denied');
- const ispost = getIsPostData();
- if (!ispost) {
- uploadSubscription({
- userid: udatadict.userid || '',
- result: 4,
- machineserial: udatadict.machineserial,
- ish5: udatadict.type,
- p_source: udatadict.channel
- });
- }
- pushmlog('User has already denied push notifications');
- } else {
- endCallback && endCallback('pending');
- // 状态是授权或者用户未决定, 但是拿不到订阅信息, 重新请求授权
- requestNotificationPermission(registration, udatadict.channel, udatadict.userid, machineserial, type);
- }
- }
- }).catch(function (error) {
- isCheckingPushPermission = false;
- errorpushlog('Failed to read push subscription:', error);
- });
- })
- .catch(e => {
- isCheckingPushPermission = false;
- errorpushlog('Service worker readiness failed:', e);
- });
- });
- } catch (error) {
- errorpushlog('Failed to check push permission:', error);
- isCheckingPushPermission = false;
- }
- }
- // 外部调用。每次
- function checkAlive(userid, vippoint, channel, score) {
- try {
- if (udatadict.fingerprint === undefined || udatadict.fingerprint === null) {
- var udatadictstr = localStorage.getItem('pushudatadict');
- if (udatadictstr) {
- udatadict = JSON.parse(udatadictstr);
- }
- if (udatadict.fingerprint === undefined || udatadict.fingerprint === null) {
- errorpushlog('udatadict.fingerprint is undefined');
- return;
- }
- }
- if (userid === undefined || userid === null) {
- errorpushlog('userid is undefined');
- return;
- }
- // 1 小时最多上报一次
- var isInstalled = isPwaInstall();
- var reportkey = 'lastreporttime_' + userid + '_' + channel + '_' + isInstalled;
- var lastreporttime = localStorage.getItem(reportkey);
- var now = new Date().getTime();
- if (lastreporttime) {
- var last = parseInt(lastreporttime);
- if (now - last < 1000 * 60 * 60) {
- return;
- }
- }
- localStorage.setItem(reportkey, now);
- // 请求用户活跃接口
- var xhr = new XMLHttpRequest();
- xhr.open('POST', 'https://pushme.us3slot77.com/alive', true);
- xhr.setRequestHeader('Content-Type', 'application/json');
- var contentData = {
- userid: userid,
- vippoint: vippoint,
- channel: channel,
- fingerprint: udatadict.fingerprint,
- installed: isInstalled,
- platform: getPlatform(),
- score: score,
- client_active_time: new Date().toISOString()
- };
- xhr.send(JSON.stringify(contentData));
- xhr.onreadystatechange = function () {
- if (xhr.readyState === 4 && xhr.status === 200) {
- pushmlog('User activity info sent to server:', xhr.responseText);
- }
- };
- } catch (error) {
- errorpushlog('Failed to check user activity:', error);
- }
- }
- //简单加密
- const encrypt = (str, pwd) => {
- if (str === '') {
- return '';
- }
- str = encodeURIComponent(str);
- if (!pwd || pwd === '') {
- pwd = 'xbd4jl';
- }
- pwd = encodeURIComponent(pwd);
- if (pwd === '' || pwd.length <= 0) {
- return '';
- }
- var prand = '';
- for (var i = 0, len = pwd.length; i < len; i += 1) {
- prand += pwd.charCodeAt(i).toString();
- }
- var sPos = Math.floor(prand.length / 5);
- var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos * 2) + prand.charAt(sPos * 3) +
- prand.charAt(sPos * 4) + prand.charAt(sPos * 5));
- var incr = Math.ceil(pwd.length / 2);
- var modu = Math.pow(2, 31) - 1;
- if (mult < 2) {
- return '';
- }
- var salt = Math.round(Math.random() * 1000000000) % 100000000;
- prand += salt;
- while (prand.length > 10) {
- let left = prand;
- let num = 0;
- while (left.length > 0) {
- let temp = parseInt(left.substring(0, 10));
- num = num + temp;
- left = left.substring(10, left.length);
- }
- prand = num.toString();
- }
- prand = (mult * prand + incr) % modu;
- var encChr = '';
- var encStr = '';
- for (var strIndex = 0, strLength = str.length; strIndex < strLength; strIndex += 1) {
- encChr = parseInt(str.charCodeAt(strIndex) ^ Math.floor((prand / modu) * 255));
- if (encChr < 16) {
- encStr += '0' + encChr.toString(16);
- } else {
- encStr += encChr.toString(16);
- }
- prand = (mult * prand + incr) % modu;
- }
- salt = salt.toString(16);
- while (salt.length < 8) {
- salt = "0" + salt;
- }
- encStr += salt;
- return encStr;
- }
- //简单解密
- const decrypt = (str, pwd) => {
- if (str === '') {
- return '';
- }
- if (!pwd || pwd === '') {
- pwd = 'xbd4jl';
- }
- pwd = encodeURIComponent(pwd);
- if (str === undefined || str === null || str.length < 8) {
- return '';
- }
- if (pwd === undefined || pwd === null || pwd.length <= 0) {
- return '';
- }
- var prand = '';
- for (var i = 0, len = pwd.length; i < len; i += 1) {
- prand += pwd.charCodeAt(i).toString();
- }
- var sPos = Math.floor(prand.length / 5);
- // console.log(prand.length+"sPos____"+sPos+"prand"+prand);
- var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos * 2) + prand.charAt(sPos * 3) +
- prand.charAt(sPos * 4) + prand.charAt(sPos * 5));
- var incr = Math.round(pwd.length / 2);
- var modu = Math.pow(2, 31) - 1;
- var salt = parseInt(str.substring(str.length - 8, str.length), 16);
- str = str.substring(0, str.length - 8);
- // console.log("prand"+prand);
- prand += salt;
- // console.log("prand"+prand);
- while (prand.length > 10) {
- let left = prand;
- let num = 0;
- while (left.length > 0) {
- let temp = parseInt(left.substring(0, 10));
- num = num + temp;
- left = left.substring(10, left.length);
- }
- prand = num.toString();
- }
- // console.log("prand"+prand);
- prand = (mult * prand + incr) % modu;
- var encChr = '';
- var encStr = '';
- for (var strIndex = 0, strLength = str.length; strIndex < strLength; strIndex += 2) {
- encChr = parseInt(parseInt(str.substring(strIndex, strIndex + 2), 16) ^ Math.floor((prand / modu) * 255));
- encStr += String.fromCharCode(encChr);
- prand = (mult * prand + incr) % modu;
- }
- return decodeURIComponent(encStr);
- }
- const LOCAL_VISTOR_ID = "LOCAL_VISTOR_ID";
- const head = "a6072637";
- const isenc = true;
- const localStorageGet = (key, defaultValue = "") => {
- let value = localStorage.getItem(key);
- if (value == null) value = defaultValue;
- else {
- if (value.startsWith(head)) {
- try {
- value = decrypt(value.substring(head.length));
- }
- catch (err) {
- //如果出错返回空
- value = "";
- }
- }
- }
- return value;
- }
- const localStorageSet = (key, value) => {
- if (isenc) {
- if (value != null && value !== "") {
- if (typeof value !== "string") value = value.toString();
- try {
- value = head + encrypt(value);
- }
- catch (err) { }
- }
- }
- localStorage.setItem(key, value);
- }
- const localStorageRemove = (key) => {
- localStorage.removeItem(key);
- }
- const getLocalUUID = () => {
- let bfp=localStorageGet(LOCAL_VISTOR_ID, "");
- if(!bfp){
- localStorageSet(LOCAL_VISTOR_ID, generateUUIDv7());
- bfp=localStorageGet(LOCAL_VISTOR_ID, "")
- }
- return bfp;
- }
- let params={}
- let urlParams=new URLSearchParams(window.location.search)
- for (const [key, value] of urlParams.entries()) {
- params[key] = value
- }
- const LOCAL_ACTIVITY_C = "LOCAL_ACTIVITY_C";
- const DEFAULT_CHANNEL = "100";
- function ProcessChannel() {
- let storedChannel = localStorageGet(LOCAL_ACTIVITY_C, "");
- let channelFromUrl = params["c"] || "";
- let finalChannel = channelFromUrl || storedChannel || DEFAULT_CHANNEL;
- // 保存渠道号(如有变化)
- if (finalChannel && finalChannel !== storedChannel) {
- localStorageSet(LOCAL_ACTIVITY_C, finalChannel);
- }
- window.APKCHSource = finalChannel;
- window.channel = finalChannel;
- }/**
- * 生成 UUID v7 (基于时间排序)
- * 格式: 48位时间戳 | 4位版本(7) | 12位随机数 | 2位变体(10) | 62位随机数
- */
- function generateUUIDv7() {
- const bytes = new Uint8Array(16);
- // 1. 填充随机数 (16 字节)
- crypto.getRandomValues(bytes);
- // 2. 写入 48 位毫秒时间戳 (大端序)
- const now = Date.now();
- bytes[0] = (now / 0x10000000000) & 0xff;
- bytes[1] = (now / 0x100000000) & 0xff;
- bytes[2] = (now / 0x1000000) & 0xff;
- bytes[3] = (now / 0x10000) & 0xff;
- bytes[4] = (now / 0x100) & 0xff;
- bytes[5] = now & 0xff;
- // 3. 设置版本号 (Version 7)
- // 清除前 4 位并设为 0111 (0x70)
- bytes[6] = (bytes[6] & 0x0f) | 0x70;
- // 4. 设置变体号 (Variant 10xx)
- // 清除前 2 位并设为 10 (0x80)
- bytes[8] = (bytes[8] & 0x3f) | 0x80;
- // 5. 转换为 8-4-4-4-12 字符串格式
- return Array.from(bytes)
- .map((b, i) => {
- let s = b.toString(16).padStart(2, '0');
- // 在特定位置添加连字符
- if (i === 3 || i === 5 || i === 7 || i === 9) return s + '-';
- return s;
- })
- .join('');
- }
- // Public API consumed by the standalone PWA pages and native shells.
- Object.assign(window, {
- getSubscriptionInfo,
- openUrlUseSafari,
- isInChromeBrowser,
- checkPushPermission,
- checkAlive,
- localStorageRemove,
- ProcessChannel
- });
- if (isIOS()) {
- window.location.href = window.location.origin + '/' + window.location.search;
- }
|