diff --git a/Proxy.list b/Proxy.list
index 33dfdd4..354956a 100644
--- a/Proxy.list
+++ b/Proxy.list
@@ -1,11 +1,2 @@
-# > 18mag
-DOMAIN,18mag.net
-# > 中国移动
-DOMAIN,clientaccess.10086.cn
-# > da
-DOMAIN,deviantart.com
-# > plex
-DOMAIN,downloads.plex.tv
-DOMAIN,metadata-static.plex.tv
-DOMAIN,metadata.provider.plex.tv
-DOMAIN,meta.plex.tv
+DOMAIN,ql.lowking.pro
+DOMAIN,newdy2.smjc.top
diff --git a/README.MD b/README.MD
index e82514c..4ffe29a 100644
--- a/README.MD
+++ b/README.MD
@@ -42,7 +42,6 @@
🟢
### Scriptable
-
🔴
🟢
## 许可
diff --git a/README_en.MD b/README_en.MD
index b4bcd33..837aa94 100644
--- a/README_en.MD
+++ b/README_en.MD
@@ -42,7 +42,6 @@
🟢
### Scriptable
-
🔴
🟢
## LICENSE
diff --git a/Scriptable/10000.js b/Scriptable/10000.js
index bafd999..a52dbed 100644
--- a/Scriptable/10000.js
+++ b/Scriptable/10000.js
@@ -547,7 +547,8 @@ const renderWebView = async () => {
}
}
-let isLimited = await lk.checkLimit()
+const isLimited = lk.isLimited
+lk.log(isLimited)
if (config.runsInWidget) {
lk.log('在小组件运行')
await main(isLimited)
@@ -557,5 +558,5 @@ if (config.runsInWidget) {
await lk.handleOperations(enter)
}
//ScriptableToolKit-start
-function ScriptableToolKit(scriptName,scriptId,options){return new class{constructor(scriptName,scriptId,options){this.isLimited=false;this.checkLimit();this.local=FileManager.local();this.icloud=FileManager.iCloud();this.curDateCache=this.local.joinPath(this.local.documentsDirectory(),"curDateCache");this.options=options;this.tgEscapeCharMapping={"&":"&"};this.userAgent=`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.2 Safari/605.1.15`;this.prefix=`lk`;this.name=scriptName;this.id=scriptId;this.data=null;this.dataFile=`${this.prefix}${this.id}.json`;this.bgImgPath=`${this.prefix}${this.id}Bg.jpg`;this.bgImgPath=this.local.joinPath(this.local.documentsDirectory(),this.bgImgPath);this.lang=Device.language();this.msg={zh:{s0:"在开始之前,先进入主屏幕,进入图标排列模式。滑到最右边的空白页,并进行截图。",s1:"看起来你选择的图片不是iPhone的截图,或者你的iPhone不支持。请换一张图片再试一次。",s2:"你想创建什么尺寸的widget?",s3:"你想把widget放在哪里?",s4:" (请注意,您的设备只支持两行小部件,所以中间和底部的选项是一样的)。",s5:"widget的背景图已裁切完成,想在Scriptable内部使用还是导出到相册?",s6:"已经截图,继续",s7:"退出去截图",s8:"小",s9:"中",s10:"大",s11:"顶部左边",s12:"顶部右边",s13:"中间左边",s14:"中间右边",s15:"底部左边",s16:"底部右边",s17:"顶部",s18:"中间",s19:"底部",s20:"在Scriptable内部使用",s21:"导出到相册",s22:"填写遮罩层颜色。(格式:#000000)",s23:"颜色(格式:#000000)",s24:"填写遮罩层不透明度(0-1之间)",s25:"0-1之间",s26:"确定",s27:"取消",s28:"预览widget",s29:"设置widget背景",s30:"入口",s31:"你用的是哪个型号?",s32:"退出",s33:"清除缓存",s34:"开始清除缓存",s35:"清除缓存完成"},en:{s0:"Before you start, go to your home screen and enter wiggle mode. Scroll to the empty page on the far right and take a screenshot.",s1:"It looks like you selected an image that isn't an iPhone screenshot, or your iPhone is not supported. Try again with a different image.",s2:"What size of widget are you creating?",s3:"What position will it be in?",s4:" (Note that your device only supports two rows of widgets, so the middle and bottom options are the same.)",s5:"Your widget background is ready. Would you like to use it in a Scriptable widget or export the image?",s6:"Continue",s7:"Exit to Take Screenshot",s8:"Small",s9:"Medium",s10:"Large",s11:"Top left",s12:"Top right",s13:"Middle left",s14:"Middle right",s15:"Bottom left",s16:"Bottom right",s17:"Top",s18:"Middle",s19:"Bottom",s20:"Use in Scriptable",s21:"Export to Photos",s22:"Fill in the mask layer color. (Format: #000000)",s23:"Color.(Format: #000000)",s24:"Fill in the mask layer opacity (between 0-1)",s25:"between 0-1",s26:"Confirm",s27:"Cancel",s28:"Preview widget",s29:"Setting widget background",s30:"ENTER",s31:"What type of iPhone do you have?",s32:"Exit",s33:"Clean cache",s34:"Clean cache started",s35:"Clean cache finished"}};this.curLang=this.msg[this.lang]||this.msg.en;this.isSaveLog=this.getResultByKey(`${this.prefix}IsSaveLog${this.id}`,false);this.isEnableLog=this.getResultByKey(`${this.prefix}IsEnableLog${this.id}`,true);this.logDir=this.icloud.documentsDirectory()+"/lklogs/"+this.id;this.logSeparator="\n██";this.now=new Date;this.execStatus=true;this.notifyInfo=[];this.operations=[]}async checkLimit(){const lastRunningTime=await this.getVal(`${this.prefix}LastRunningTime${this.id}`,"local",0);const runLimitNum=this.getResultByKey(`${this.prefix}RunLimitNum${this.id}`,3e5);this.log(`上次运行时间:${lastRunningTime},运行频率限制:${runLimitNum}`);if(lastRunningTime>=0){if(this.now.getTime()-lastRunningTime<=runLimitNum){this.appendNotifyInfo("限制运行");this.isLimited=true}else{await this.setVal(`${this.prefix}LastRunningTime${this.id}`,this.now.getTime(),"local")}}return this.isLimited}getResultByKey(key,defaultValue){if(!this.options){return defaultValue}const val=this.options[key];if(this.isEmpty(val)){return defaultValue}else{return val}}appendNotifyInfo(info,type){if(type==1){this.notifyInfo=info}else{this.notifyInfo.push(`${this.logSeparator}${this.formatDate(new Date,"yyyy-MM-dd HH:mm:ss.S")}█${info}`)}}saveLog(){if(this.isSaveLog){let message;if(Array.isArray(this.notifyInfo)){message=this.notifyInfo.join("")}else{message=this.notifyInfo}if(!this.icloud.isDirectory(this.logDir)){this.icloud.createDirectory(this.logDir,true)}this.icloud.writeString(`${this.logDir}/${this.formatDate(this.now,"yyyyMMddHHmmss")}.log`,message)}}prependNotifyInfo(info){this.notifyInfo.splice(0,0,info)}execFail(){this.execStatus=false}sleep(time){return new Promise(resolve=>setTimeout(resolve,time))}log(message){if(this.isEnableLog)console.log(`${this.logSeparator}${JSON.stringify(message)}`);this.appendNotifyInfo(message)}logErr(message){this.execStatus=false;if(this.isEnableLog){console.warn(`${this.logSeparator}${this.name}执行异常:`);console.warn(message);console.warn(`\n${message.message}`)}}getContainer(key){return key=="local"?this.local:this.icloud}async getVal(key,container,defaultValue){let containerInstance=this.getContainer(container);let data="";try{let realDataFile=containerInstance.joinPath(containerInstance.documentsDirectory(),this.dataFile);if(!containerInstance.fileExists(realDataFile)){await this.setVal(key,defaultValue,container);return defaultValue}data=await containerInstance.readString(realDataFile);data=JSON.parse(data)}catch(e){throw e}if(data.hasOwnProperty(key)){return data[key]}else{await this.setVal(key,defaultValue,container);return defaultValue}}async getDataFile(container){let containerInstance=this.getContainer(container);let data="";try{let realDataFile=containerInstance.joinPath(containerInstance.documentsDirectory(),this.dataFile);if(!containerInstance.fileExists(realDataFile)){return Promise.resolve("")}data=await containerInstance.readString(realDataFile)}catch(e){throw e}return Promise.resolve(data)}async saveImage(fileName,image,container){let containerInstance=this.getContainer(container);let imagePath=containerInstance.joinPath(containerInstance.documentsDirectory(),`${this.prefix}${this.id}/${fileName}`);let imageDir=imagePath.substring(0,imagePath.lastIndexOf("/")+1);if(!containerInstance.isDirectory(imageDir)){containerInstance.createDirectory(imageDir,true)}containerInstance.writeImage(imagePath,image)}async getImage(fileName,container){let containerInstance=this.getContainer(container);let imagePath=containerInstance.joinPath(containerInstance.documentsDirectory(),`${this.prefix}${this.id}/${fileName}`);if(!containerInstance.fileExists(imagePath)){this.logErr(`file not exist: ${imagePath}`);return false}return await containerInstance.readImage(imagePath)}async setVal(key,val,container){let containerInstance=this.getContainer(container);let data;let realDataFile=containerInstance.joinPath(containerInstance.documentsDirectory(),this.dataFile);try{if(!containerInstance.fileExists(realDataFile)){data={}}else{data=await containerInstance.readString(realDataFile);data=JSON.parse(data)}}catch(e){data={}}data[key]=val;await containerInstance.writeString(realDataFile,JSON.stringify(data))}async get(options,callback=(()=>{})){let request=new Request("");request.url=options.url;request.method="GET";request.headers=options.headers;try{const result=await request.loadString();callback(request.response,result);return result}catch(e){this.logErr(e);callback(undefined,undefined)}}async post(options,callback=(()=>{})){let request=new Request("");request.url=options.url;request.body=options.body;request.method="POST";request.headers=options.headers;request.timeout=5e3;try{const result=await request.loadString();callback(request.response,result);return result}catch(e){this.logErr(e);callback(undefined,undefined)}}async loadScript({scriptName:scriptName,url:url}){this.log(`获取脚本【${scriptName}】`);const content=await this.get({url:url});this.icloud.writeString(`${this.icloud.documentsDirectory()}/${scriptName}.js`,content);this.log(`获取脚本【${scriptName}】完成🎉`)}require({scriptName:scriptName,url:url="",reload:reload=false}){if(this.icloud.fileExists(this.icloud.joinPath(this.icloud.documentsDirectory(),`${scriptName}.js`))&&!reload){this.log(`引用脚本【${scriptName}】`);return importModule(scriptName)}else{this.loadScript({scriptName:scriptName,url:url});this.log(`引用脚本【${scriptName}】`);return importModule(scriptName)}}async generateInputAlert(message,field,defaultValue){let result=[];let alert=new Alert;alert.message=message;alert.addTextField(field,defaultValue);alert.addCancelAction(this.curLang.s27);alert.addAction(this.curLang.s26);result[0]=await alert.presentAlert();result[1]=alert.textFieldValue(0);return result}async generateAlert(message,options){let alert=new Alert;alert.message=message;for(const option of options){alert.addAction(option)}return await alert.presentAlert()}isEmpty(obj){return typeof obj=="undefined"||obj==null||obj==""||obj=="null"}isWorkingDays(now,workingDaysFlag="curlybraces",holidayFlag="gamecontroller"){return new Promise(async(resolve,reject)=>{let sp="≈";const d=this.formatDate(now,"yyyy-MM-dd");let resultStr=0;try{let curDate=await this.getVal("curDateCache","local","fff");let curDateErrorTime=await this.getVal("curDateCacheErrorTime","local",this.now.getTime());let isPreError=!this.isEmpty(curDateErrorTime)&&Number(curDateErrorTime)+5*60*1e3{if(data.indexOf("<")==0){resultStr="❌"}else{resultStr=JSON.parse(data);if(resultStr.code==-1){resultStr="❌"}else{resultStr=resultStr.type.type}}})}}catch(e){resultStr="❌";this.logErr(e)}finally{await this.setVal("curDateCache",`${d}${sp}${resultStr}`,"local");if(resultStr=="❌"){resolve(resultStr);this.log("写入运行错误时间,5分钟后重新请求!");this.setVal("curDateCache","","local");this.setVal("curDateCacheErrorTime",`${this.now.getTime()}`,"local")}else{this.setVal("curDateCacheErrorTime","","local");this.setVal("curDateCache",`${d}${sp}${resultStr}`,"local");resolve(resultStr==0||resultStr==3?workingDaysFlag:holidayFlag)}}})}randomString(len){len=len||32;var $chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";var maxPos=$chars.length;var pwd="";for(let i=0;i{return item.name[this.lang]});let customEnterCallback=customEnter.map((item,index)=>{return item.callback});if(isReset){options=customEnterNames}else{this.operations.push({callback:main});this.operations.push({callback:function(){$.widgetCutBg()}});this.operations.push({callback:function(){$.cleanCache()}});options=options.concat(customEnterNames)}customEnterCallback.forEach(callback=>{this.operations.push({callback:callback})})}options.push(this.curLang.s32);this.operations.push({callback:function(){}});return await this.generateAlert(this.curLang.s30,options)}async handleOperations(index){await this.operations[index].callback()}cleanCache(){this.log(this.curLang.s34);let filePath=this.local.joinPath(this.local.documentsDirectory(),this.dataFile);if(this.local.fileExists(filePath)){this.local.remove(filePath)}filePath=this.bgImgPath;if(this.local.fileExists(filePath)){this.local.remove(filePath)}this.log(this.curLang.s35)}formatTimeDuring(total,lang="zh",n=0){total=Number(total);let zhUnitArr=["毫秒","秒","分钟","小时","天","月","年"];let enUnitArr=["ms","s","min","h","d","m","y"];let scaleArr=[1e3,60,60,24,30,12,100];let len=total;if(len>scaleArr[n]){len=total/scaleArr[n];return this.formatTimeDuring(len,lang,++n)}else{let unit=zhUnitArr[n];if(lang==="en"){unit=enUnitArr[n]}return len.toFixed(2)+""+unit}}fileLengthFormat(total,unit="",toByte=false){total=Number(total);var unitArr=["","KB","MB","GB","TB","PB","EB","ZB"];var n=0;try{n=unitArr.indexOf(unit)}catch(e){throw e}if(toByte){if(n==0){return total}return this.fileLengthFormat(total*1024,unitArr[--n],true)}var len=total;if(len>1e3){len=total/1024;return this.fileLengthFormat(len,unitArr[++n])}else{if(n==0){return len.toFixed(2)}return len.toFixed(2)+" "+unitArr[n]}}}(scriptName,scriptId,options)}
+function ScriptableToolKit(scriptName,scriptId,options){return new class{constructor(scriptName,scriptId,options){this.local=FileManager.local();this.icloud=FileManager.iCloud();this.curDateCache=this.local.joinPath(this.local.documentsDirectory(),"curDateCache");this.options=options;this.tgEscapeCharMapping={"&":"&"};this.userAgent=`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.2 Safari/605.1.15`;this.prefix=`lk`;this.name=scriptName;this.id=scriptId;this.data=null;this.dataFile=`${this.prefix}${this.id}.json`;this.bgImgPath=`${this.prefix}${this.id}Bg.jpg`;this.bgImgPath=this.local.joinPath(this.local.documentsDirectory(),this.bgImgPath);this.lang=Device.language();this.msg={zh:{s0:"在开始之前,先进入主屏幕,进入图标排列模式。滑到最右边的空白页,并进行截图。",s1:"看起来你选择的图片不是iPhone的截图,或者你的iPhone不支持。请换一张图片再试一次。",s2:"你想创建什么尺寸的widget?",s3:"你想把widget放在哪里?",s4:" (请注意,您的设备只支持两行小部件,所以中间和底部的选项是一样的)。",s5:"widget的背景图已裁切完成,想在Scriptable内部使用还是导出到相册?",s6:"已经截图,继续",s7:"退出去截图",s8:"小",s9:"中",s10:"大",s11:"顶部左边",s12:"顶部右边",s13:"中间左边",s14:"中间右边",s15:"底部左边",s16:"底部右边",s17:"顶部",s18:"中间",s19:"底部",s20:"在Scriptable内部使用",s21:"导出到相册",s22:"填写遮罩层颜色。(格式:#000000)",s23:"颜色(格式:#000000)",s24:"填写遮罩层不透明度(0-1之间)",s25:"0-1之间",s26:"确定",s27:"取消",s28:"预览widget",s29:"设置widget背景",s30:"入口",s31:"你用的是哪个型号?",s32:"退出",s33:"清除缓存",s34:"开始清除缓存",s35:"清除缓存完成"},en:{s0:"Before you start, go to your home screen and enter wiggle mode. Scroll to the empty page on the far right and take a screenshot.",s1:"It looks like you selected an image that isn't an iPhone screenshot, or your iPhone is not supported. Try again with a different image.",s2:"What size of widget are you creating?",s3:"What position will it be in?",s4:" (Note that your device only supports two rows of widgets, so the middle and bottom options are the same.)",s5:"Your widget background is ready. Would you like to use it in a Scriptable widget or export the image?",s6:"Continue",s7:"Exit to Take Screenshot",s8:"Small",s9:"Medium",s10:"Large",s11:"Top left",s12:"Top right",s13:"Middle left",s14:"Middle right",s15:"Bottom left",s16:"Bottom right",s17:"Top",s18:"Middle",s19:"Bottom",s20:"Use in Scriptable",s21:"Export to Photos",s22:"Fill in the mask layer color. (Format: #000000)",s23:"Color.(Format: #000000)",s24:"Fill in the mask layer opacity (between 0-1)",s25:"between 0-1",s26:"Confirm",s27:"Cancel",s28:"Preview widget",s29:"Setting widget background",s30:"ENTER",s31:"What type of iPhone do you have?",s32:"Exit",s33:"Clean cache",s34:"Clean cache started",s35:"Clean cache finished"}};this.curLang=this.msg[this.lang]||this.msg.en;this.isSaveLog=this.getResultByKey(`${this.prefix}IsSaveLog${this.id}`,false);this.isEnableLog=this.getResultByKey(`${this.prefix}IsEnableLog${this.id}`,true);this.logDir=this.icloud.documentsDirectory()+"/lklogs/"+this.id;this.logSeparator="\n██";this.now=new Date;this.execStatus=true;this.notifyInfo=[];this.operations=[];this.isLimited=false;this.checkLimit()}async checkLimit(){const lastRunningTime=await this.getVal(`${this.prefix}LastRunningTime${this.id}`,"local",0);const runLimitNum=this.getResultByKey(`${this.prefix}RunLimitNum${this.id}`,3e5);this.log(`上次运行时间:${this.formatDate(new Date(lastRunningTime),"yyyy-MM-dd HH:mm:ss.S")} ${lastRunningTime},运行频率限制:${runLimitNum}`);if(lastRunningTime>=0){if(this.now.getTime()-lastRunningTime<=runLimitNum){this.appendNotifyInfo("限制运行");this.isLimited=true}else{await this.setVal(`${this.prefix}LastRunningTime${this.id}`,this.now.getTime(),"local")}}return this.isLimited}getResultByKey(key,defaultValue){if(!this.options){return defaultValue}const val=this.options[key];if(this.isEmpty(val)){return defaultValue}else{return val}}appendNotifyInfo(info,type){if(type==1){this.notifyInfo=info}else{this.notifyInfo.push(`${this.logSeparator}${this.formatDate(new Date,"yyyy-MM-dd HH:mm:ss.S")}█${info}`)}}saveLog(){if(this.isSaveLog){let message;if(Array.isArray(this.notifyInfo)){message=this.notifyInfo.join("")}else{message=this.notifyInfo}if(!this.icloud.isDirectory(this.logDir)){this.icloud.createDirectory(this.logDir,true)}this.icloud.writeString(`${this.logDir}/${this.formatDate(this.now,"yyyyMMddHHmmss")}.log`,message)}}prependNotifyInfo(info){this.notifyInfo.splice(0,0,info)}execFail(){this.execStatus=false}sleep(time){return new Promise(resolve=>setTimeout(resolve,time))}log(message){if(this.isEnableLog)console.log(`${this.logSeparator}${JSON.stringify(message)}`);this.appendNotifyInfo(message)}logErr(message){this.execStatus=false;if(this.isEnableLog){console.warn(`${this.logSeparator}${this.name}执行异常:`);console.warn(message);console.warn(`\n${message.message}`)}}getContainer(key){return key=="local"?this.local:this.icloud}async getVal(key,container,defaultValue){let containerInstance=this.getContainer(container);let data="";try{let realDataFile=containerInstance.joinPath(containerInstance.documentsDirectory(),this.dataFile);if(!containerInstance.fileExists(realDataFile)){await this.setVal(key,defaultValue,container);return defaultValue}data=await containerInstance.readString(realDataFile);data=JSON.parse(data)}catch(e){throw e}if(data.hasOwnProperty(key)){return data[key]}else{await this.setVal(key,defaultValue,container);return defaultValue}}async getDataFile(container){let containerInstance=this.getContainer(container);let data="";try{let realDataFile=containerInstance.joinPath(containerInstance.documentsDirectory(),this.dataFile);if(!containerInstance.fileExists(realDataFile)){return Promise.resolve("")}data=await containerInstance.readString(realDataFile)}catch(e){throw e}return Promise.resolve(data)}async saveImage(fileName,image,container){let containerInstance=this.getContainer(container);let imagePath=containerInstance.joinPath(containerInstance.documentsDirectory(),`${this.prefix}${this.id}/${fileName}`);let imageDir=imagePath.substring(0,imagePath.lastIndexOf("/")+1);if(!containerInstance.isDirectory(imageDir)){containerInstance.createDirectory(imageDir,true)}containerInstance.writeImage(imagePath,image)}async getImage(fileName,container){let containerInstance=this.getContainer(container);let imagePath=containerInstance.joinPath(containerInstance.documentsDirectory(),`${this.prefix}${this.id}/${fileName}`);if(!containerInstance.fileExists(imagePath)){this.logErr(`file not exist: ${imagePath}`);return false}return await containerInstance.readImage(imagePath)}async setVal(key,val,container){let containerInstance=this.getContainer(container);let data;let realDataFile=containerInstance.joinPath(containerInstance.documentsDirectory(),this.dataFile);try{if(!containerInstance.fileExists(realDataFile)){data={}}else{data=await containerInstance.readString(realDataFile);data=JSON.parse(data)}}catch(e){data={}}data[key]=val;await containerInstance.writeString(realDataFile,JSON.stringify(data))}async get(options,callback=(()=>{})){let request=new Request("");request.url=options.url;request.method="GET";request.headers=options.headers;try{const result=await request.loadString();callback(request.response,result);return result}catch(e){this.logErr(e);callback(undefined,undefined)}}async post(options,callback=(()=>{})){let request=new Request("");request.url=options.url;request.body=options.body;request.method="POST";request.headers=options.headers;request.timeout=5e3;try{const result=await request.loadString();callback(request.response,result);return result}catch(e){this.logErr(e);callback(undefined,undefined)}}async loadScript({scriptName:scriptName,url:url}){this.log(`获取脚本【${scriptName}】`);const content=await this.get({url:url});this.icloud.writeString(`${this.icloud.documentsDirectory()}/${scriptName}.js`,content);this.log(`获取脚本【${scriptName}】完成🎉`)}require({scriptName:scriptName,url:url="",reload:reload=false}){if(this.icloud.fileExists(this.icloud.joinPath(this.icloud.documentsDirectory(),`${scriptName}.js`))&&!reload){this.log(`引用脚本【${scriptName}】`);return importModule(scriptName)}else{this.loadScript({scriptName:scriptName,url:url});this.log(`引用脚本【${scriptName}】`);return importModule(scriptName)}}async generateInputAlert(message,field,defaultValue){let result=[];let alert=new Alert;alert.message=message;alert.addTextField(field,defaultValue);alert.addCancelAction(this.curLang.s27);alert.addAction(this.curLang.s26);result[0]=await alert.presentAlert();result[1]=alert.textFieldValue(0);return result}async generateAlert(message,options){let alert=new Alert;alert.message=message;for(const option of options){alert.addAction(option)}return await alert.presentAlert()}isEmpty(obj){return typeof obj=="undefined"||obj==null||obj==""||obj=="null"}isWorkingDays(now,workingDaysFlag="curlybraces",holidayFlag="gamecontroller"){return new Promise(async(resolve,reject)=>{let sp="≈";const d=this.formatDate(now,"yyyy-MM-dd");let resultStr=0;try{let curDate=await this.getVal("curDateCache","local","fff");let curDateErrorTime=await this.getVal("curDateCacheErrorTime","local",this.now.getTime());let isPreError=!this.isEmpty(curDateErrorTime)&&Number(curDateErrorTime)+5*60*1e3{if(data.indexOf("<")==0){resultStr="❌"}else{resultStr=JSON.parse(data);if(resultStr.code==-1){resultStr="❌"}else{resultStr=resultStr.type.type}}})}}catch(e){resultStr="❌";this.logErr(e)}finally{await this.setVal("curDateCache",`${d}${sp}${resultStr}`,"local");if(resultStr=="❌"){resolve(resultStr);this.log("写入运行错误时间,5分钟后重新请求!");this.setVal("curDateCache","","local");this.setVal("curDateCacheErrorTime",`${this.now.getTime()}`,"local")}else{this.setVal("curDateCacheErrorTime","","local");this.setVal("curDateCache",`${d}${sp}${resultStr}`,"local");resolve(resultStr==0||resultStr==3?workingDaysFlag:holidayFlag)}}})}randomString(len){len=len||32;var $chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";var maxPos=$chars.length;var pwd="";for(let i=0;i{return item.name[this.lang]});let customEnterCallback=customEnter.map((item,index)=>{return item.callback});if(isReset){options=customEnterNames}else{this.operations.push({callback:main});this.operations.push({callback:function(){$.widgetCutBg()}});this.operations.push({callback:function(){$.cleanCache()}});options=options.concat(customEnterNames)}customEnterCallback.forEach(callback=>{this.operations.push({callback:callback})})}options.push(this.curLang.s32);this.operations.push({callback:function(){}});return await this.generateAlert(this.curLang.s30,options)}async handleOperations(index){await this.operations[index].callback()}cleanCache(){this.log(this.curLang.s34);let filePath=this.local.joinPath(this.local.documentsDirectory(),this.dataFile);if(this.local.fileExists(filePath)){this.local.remove(filePath)}filePath=this.bgImgPath;if(this.local.fileExists(filePath)){this.local.remove(filePath)}this.log(this.curLang.s35)}formatTimeDuring(total,lang="zh",n=0){total=Number(total);let zhUnitArr=["毫秒","秒","分钟","小时","天","月","年"];let enUnitArr=["ms","s","min","h","d","m","y"];let scaleArr=[1e3,60,60,24,30,12,100];let len=total;if(len>scaleArr[n]){len=total/scaleArr[n];return this.formatTimeDuring(len,lang,++n)}else{let unit=zhUnitArr[n];if(lang==="en"){unit=enUnitArr[n]}return len.toFixed(2)+""+unit}}fileLengthFormat(total,unit="",toByte=false){total=Number(total);var unitArr=["","KB","MB","GB","TB","PB","EB","ZB"];var n=0;try{n=unitArr.indexOf(unit)}catch(e){throw e}if(toByte){if(n==0){return total}return this.fileLengthFormat(total*1024,unitArr[--n],true)}var len=total;if(len>1e3){len=total/1024;return this.fileLengthFormat(len,unitArr[++n])}else{if(n==0){return len.toFixed(2)}return len.toFixed(2)+" "+unitArr[n]}}}(scriptName,scriptId,options)}
//ScriptableToolKit-end
diff --git a/Scriptable/10086.js b/Scriptable/10086.js
deleted file mode 100644
index 0aeda4a..0000000
--- a/Scriptable/10086.js
+++ /dev/null
@@ -1,306 +0,0 @@
-// https://gist.githubusercontent.com/mzeryck/3a97ccd1e059b3afa3c6666d27a496c9/raw/bbcac348d540e452228bd85aa80a5b45bb023a65/mz_invisible_widget.js
-// 这是原作者gist地址,本人就汉化,只为引用到自己修改的Scriptable中
-// 10086来源GideonSenku,https://github.com/GideonSenku/Scriptable/blob/master/10086/10086.js
-const $ = new ScriptableToolKit(`10086`, `10086`, {lkIsSaveLog10086: true, lkRunLimitNum10086: 300000})
-const prefix = "boxjs.net" //修改成你用的域名
-// 余额警告阈值
-const warnFee = 20
-// 流量警告阈值,只判断单位MB的,如果是kb没做处理
-const warnData = 200
-// 语音警告阈值
-const warnVoice = 20
-// 工作日和节假日标志
-const workingDaysFlag = '💡'
-const holidayFlag = '🎈'
-
-const chavy_autologin_cmcc = ``
-
-const chavy_getfee_cmcc = ``
-
-$.KEY_autologin = "chavy_autologin_cmcc"
-
-$.KEY_getfee = "chavy_getfee_cmcc"
-
-const crypto = {
- scriptName: 'crypto',
- url: 'https://raw.githubusercontent.com/GideonSenku/Scriptable/master/crypto-js.min.js'
-}
-
-const now = new Date()
-const minutes = now.getMinutes()
-const hours = now.getHours()
-
-async function getdata(key) {
- const url = `http://${prefix}/query/boxdata`
- const boxdata = JSON.parse(await $.get({ url }))
- if (boxdata.datas[key]) {
- return boxdata.datas[key]
- } else {
- return undefined
- }
-}
-
-if (config.runsInWidget) {
- $.log('在小组件运行')
- if (await $.checkLimit()) {
- $.execFail()
- $.saveLog()
- return false;
- }
- main()
-} else {
- $.log('手动运行')
- let enter = await $.widgetEnter()
- await $.handleOperations(enter)
-}
-
-async function main() {
- let widget = new ListWidget()
- try {
- widget.backgroundImage = $.getWidgetBg()
- // Your code here
- if (now.getDate() == 1) {
- // 每个月1号维护查询不到数据
- $.log('每个月1号维护查询不到数据,直接降级处理')
- widget = await createWidget(widget, "移不动", '-', '-', '-')
- } else {
- if (true || minutes >= 0 && minutes <= 20) {
- $.CryptoJS = $.require(crypto)
- $.autologin = await getdata($.KEY_autologin)
- $.getfee = await getdata($.KEY_getfee)
- await loginapp()
- await queryfee()
- await querymeal()
- // 执行失败,降级处理
- if (!$.execStatus) {
- $.log('整个流程有错误发生,降级处理,读取上次成功执行的数据')
- $.log(`读取数据:${await $.getDataFile('local')}`)
- widget = await createWidget(widget, "移不动", await $.getVal('subt', 'local', '-'), await $.getVal('flowRes', 'local', '-'), await $.getVal('voiceRes', 'local', '-'))
- } else {
- $.log('整个流程执行正常')
- widget = await showmsg(widget)
- }
- }
- }
- $.saveLog()
- Script.setWidget(widget)
- Script.complete()
- } catch (e) {
- // 为了不影响正常显示
- $.logErr(e)
- }
-}
-
-function showmsg(w) {
- return new Promise(async (resolve) => {
- $.log('显示信息')
- $.subt = `[话费] ${$.fee.rspBody.curFee}元`
- const res = $.meal.rspBody.qryInfoRsp[0].resourcesTotal
- const flowRes = res.find((r) => r.resourcesCode === '04')
- const voiceRes = res.find((r) => r.resourcesCode === '01')
- $.log(JSON.stringify(flowRes))
- if (flowRes) {
- const remUnit = flowRes.remUnit === '05' ? 'GB' : 'MB'
- const usedUnit = flowRes.usedUnit === '05' ? 'GB' : 'MB'
- const unit = flowRes.allUnit === '05' ? 'GB' : 'MB'
- $.flowRes = `[流量] ${flowRes.allRemainRes}${remUnit}`
- }
- if (voiceRes) {
- const remUnit = flowRes.remUnit === '01' ? '分钟' : ''
- const usedUnit = flowRes.usedUnit === '01' ? '分钟' : ''
- const allUnit = '分钟'
- $.voiceRes = `[语音] ${voiceRes.allRemainRes}${allUnit}`
- }
-
- let widget = await createWidget(w, "移不动", $.subt, $.flowRes, $.voiceRes)
-
- $.log('显示信息end')
- resolve(widget)
- })
-}
-
-async function createWidget(w, pretitle, title, subtitle, other) {
- $.log('创建widget')
-
- // 保存成功执行的数据
- if (title != '-') {
- $.setVal('subt', title, 'local')
- $.setVal('flowRes', subtitle, 'local')
- $.setVal('voiceRes', other, 'local')
- $.log(`写入数据:${await $.getDataFile('local')}`)
- }
- const bgColor = new LinearGradient()
- bgColor.colors = [new Color("#001A27"), new Color("#00334e")]
- bgColor.locations = [0.0, 1.0]
-
- // 获取第二天是否工作日
- let targetDate = new Date()
- let isWD = await $.isWorkingDays(new Date(targetDate.setDate(now.getDate() + 1)))
- $.log(`设置标题-${pretitle}${isWD}`)
- let normalColor = new Color("#ccc")
- let preTxt = w.addText(pretitle + isWD)
- let preColor = normalColor
- preTxt.textColor = preColor
- preTxt.font = Font.boldSystemFont(18)
- // preTxt.applyHeadlineTextStyling()
- w.addSpacer(7)
- // preTxt.applySubheadlineTextStyling()
-
-
- $.log('设置话费')
- let titleTxt = w.addText(title)
- let warnColor = new Color("#82632C")
- let normalFontSize = 14
- const sp = 3
- preColor = normalColor
- if (Number(title.replace('元', '').substring(title.indexOf(']') + 1)) < warnFee) {
- preColor = warnColor
- }
- titleTxt.textColor = preColor
- titleTxt.font = Font.systemFont(14)
- titleTxt.textSize = normalFontSize
- w.addSpacer(sp)
-
-
- $.log('设置流量')
- let subTxt = w.addText(subtitle)
- preColor = normalColor
- if (subtitle.indexOf('MB') && Number(subtitle.replace('MB', '').substring(subtitle.indexOf(']') + 1)) < warnData) {
- preColor = warnColor
- }
- subTxt.textColor = preColor
- subTxt.font = Font.systemFont(14)
- subTxt.textSize = normalFontSize
- w.addSpacer(sp)
-
- $.log('设置语音')
- let otherTxt = w.addText(other)
- preColor = normalColor
- if (other.indexOf('分钟') && Number(other.replace('分钟', '').substring(other.indexOf(']') + 1)) < warnVoice) {
- preColor = warnColor
- }
- otherTxt.textColor = preColor
- otherTxt.font = Font.systemFont(14)
- otherTxt.textSize = normalFontSize
- w.addSpacer(sp)
-
- $.log('设置更新时间')
- let minTxt = w.addText(`${$.execStatus?'':'⚬'}更新于:${hours > 9 ? hours : "0" + hours}:${minutes > 9 ? minutes : "0" + minutes}`)
- minTxt.textColor = new Color("#777")
- minTxt.font = Font.systemFont(11)
- minTxt.textSize = 11
- w.addSpacer(sp)
-
- w.presentSmall()
- $.log('创建widget end')
- return w
-}
-
-function loginapp() {
- return new Promise((resolve) => {
- $.log('登录开始')
- const url = $.autologin
- ? JSON.parse($.autologin)
- : JSON.parse(chavy_autologin_cmcc)
- $.post(url, (resp, data) => {
- $.log('登录接口响应返回')
- try {
- $.setck = resp.headers["Set-Cookie"]
- $.log('登录完成')
- } catch (e) {
- $.log('登录异常')
- $.logErr(e)
- $.log(resp)
- } finally {
- resolve()
- }
- })
- })
-}
-
-function queryfee() {
- return new Promise((resolve) => {
- $.log('查询余额')
- const url = $.getfee ? JSON.parse($.getfee) : JSON.parse(chavy_getfee_cmcc)
- const body = JSON.parse(decrypt(url.body, "bAIgvwAuA4tbDr9d"))
- const cellNum = body.reqBody.cellNum
- const bodystr = `{"t":"${$.CryptoJS.MD5(
- $.setck
- ).toString()}","cv":"9.9.9","reqBody":{"cellNum":"${cellNum}"}}`
- url.body = encrypt(bodystr, "bAIgvwAuA4tbDr9d")
- url.headers["Cookie"] = $.setck
- url.headers["xs"] = $.CryptoJS.MD5(
- url.url + "_" + bodystr + "_Leadeon/SecurityOrganization"
- ).toString()
-
- $.post(url, (resp, data) => {
- $.log('查询余额响应返回')
- try {
- $.log(`解密结果:${decrypt(data, "GS7VelkJl5IT1uwQ")}`)
- $.fee = JSON.parse(decrypt(data, "GS7VelkJl5IT1uwQ"))
- $.log('查询余额结束')
- } catch (e) {
- $.log('查询余额异常')
- $.logErr(e)
- $.log(data)
- $.log(`查询余额异常,请求体:${JSON.stringify(url)}`)
- } finally {
- resolve()
- }
- })
- })
-}
-
-function querymeal() {
- return new Promise((resolve) => {
- $.log('查询套餐')
- const url = $.getfee ? JSON.parse($.getfee) : JSON.parse(chavy_getfee_cmcc)
- url.url =
- "https://clientaccess.10086.cn/biz-orange/BN/newComboMealResouceUnite/getNewComboMealResource"
- const body = JSON.parse(decrypt(url.body, "bAIgvwAuA4tbDr9d"))
- const cellNum = body.reqBody.cellNum
- const bodystr = `{"t":"${$.CryptoJS.MD5(
- $.setck
- ).toString()}","cv":"9.9.9","reqBody":{"cellNum":"${cellNum}","tag":"3"}}`
- url.body = encrypt(bodystr, "bAIgvwAuA4tbDr9d")
- url.headers["Cookie"] = $.setck
- url.headers["xs"] = $.CryptoJS.MD5(
- url.url + "_" + bodystr + "_Leadeon/SecurityOrganization"
- ).toString()
- $.post(url, (resp, data) => {
- $.log('查询套餐响应返回')
- try {
- $.meal = JSON.parse(decrypt(data, "GS7VelkJl5IT1uwQ"))
- $.log('查询套餐完成')
- } catch (e) {
- $.log('查询套餐异常')
- $.logErr(e)
- $.log(data)
- $.log(`查询套餐异常,请求体:${JSON.stringify(url)}`)
- } finally {
- resolve()
- }
- })
- })
-}
-
-
-function encrypt(str, key) {
- return $.CryptoJS.AES.encrypt($.CryptoJS.enc.Utf8.parse(str), $.CryptoJS.enc.Utf8.parse(key), {
- iv: $.CryptoJS.enc.Utf8.parse('9791027341711819'),
- mode: $.CryptoJS.mode.CBC,
- padding: $.CryptoJS.pad.Pkcs7
- }).toString()
-}
-
-function decrypt(str, key) {
- return $.CryptoJS.AES.decrypt(str, $.CryptoJS.enc.Utf8.parse(key), {
- iv: $.CryptoJS.enc.Utf8.parse('9791027341711819'),
- mode: $.CryptoJS.mode.CBC,
- padding: $.CryptoJS.pad.Pkcs7
- }).toString($.CryptoJS.enc.Utf8)
-}
-
-//ScriptableToolKit-start
-function ScriptableToolKit(scriptName,scriptId,options){return new class{constructor(scriptName,scriptId,options){this.isLimited=false;this.checkLimit();this.local=FileManager.local();this.icloud=FileManager.iCloud();this.curDateCache=this.local.joinPath(this.local.documentsDirectory(),"curDateCache");this.options=options;this.tgEscapeCharMapping={"&":"&"};this.userAgent=`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.2 Safari/605.1.15`;this.prefix=`lk`;this.name=scriptName;this.id=scriptId;this.data=null;this.dataFile=`${this.prefix}${this.id}.json`;this.bgImgPath=`${this.prefix}${this.id}Bg.jpg`;this.bgImgPath=this.local.joinPath(this.local.documentsDirectory(),this.bgImgPath);this.lang=Device.language();this.msg={zh:{s0:"在开始之前,先进入主屏幕,进入图标排列模式。滑到最右边的空白页,并进行截图。",s1:"看起来你选择的图片不是iPhone的截图,或者你的iPhone不支持。请换一张图片再试一次。",s2:"你想创建什么尺寸的widget?",s3:"你想把widget放在哪里?",s4:" (请注意,您的设备只支持两行小部件,所以中间和底部的选项是一样的)。",s5:"widget的背景图已裁切完成,想在Scriptable内部使用还是导出到相册?",s6:"已经截图,继续",s7:"退出去截图",s8:"小",s9:"中",s10:"大",s11:"顶部左边",s12:"顶部右边",s13:"中间左边",s14:"中间右边",s15:"底部左边",s16:"底部右边",s17:"顶部",s18:"中间",s19:"底部",s20:"在Scriptable内部使用",s21:"导出到相册",s22:"填写遮罩层颜色。(格式:#000000)",s23:"颜色(格式:#000000)",s24:"填写遮罩层不透明度(0-1之间)",s25:"0-1之间",s26:"确定",s27:"取消",s28:"预览widget",s29:"设置widget背景",s30:"入口",s31:"你用的是哪个型号?",s32:"退出",s33:"清除缓存",s34:"开始清除缓存",s35:"清除缓存完成"},en:{s0:"Before you start, go to your home screen and enter wiggle mode. Scroll to the empty page on the far right and take a screenshot.",s1:"It looks like you selected an image that isn't an iPhone screenshot, or your iPhone is not supported. Try again with a different image.",s2:"What size of widget are you creating?",s3:"What position will it be in?",s4:" (Note that your device only supports two rows of widgets, so the middle and bottom options are the same.)",s5:"Your widget background is ready. Would you like to use it in a Scriptable widget or export the image?",s6:"Continue",s7:"Exit to Take Screenshot",s8:"Small",s9:"Medium",s10:"Large",s11:"Top left",s12:"Top right",s13:"Middle left",s14:"Middle right",s15:"Bottom left",s16:"Bottom right",s17:"Top",s18:"Middle",s19:"Bottom",s20:"Use in Scriptable",s21:"Export to Photos",s22:"Fill in the mask layer color. (Format: #000000)",s23:"Color.(Format: #000000)",s24:"Fill in the mask layer opacity (between 0-1)",s25:"between 0-1",s26:"Confirm",s27:"Cancel",s28:"Preview widget",s29:"Setting widget background",s30:"ENTER",s31:"What type of iPhone do you have?",s32:"Exit",s33:"Clean cache",s34:"Clean cache started",s35:"Clean cache finished"}};this.curLang=this.msg[this.lang]||this.msg.en;this.isSaveLog=this.getResultByKey(`${this.prefix}IsSaveLog${this.id}`,false);this.isEnableLog=this.getResultByKey(`${this.prefix}IsEnableLog${this.id}`,true);this.logDir=this.icloud.documentsDirectory()+"/lklogs/"+this.id;this.logSeparator="\n██";this.now=new Date;this.execStatus=true;this.notifyInfo=[];this.operations=[]}async checkLimit(){const lastRunningTime=await this.getVal(`${this.prefix}LastRunningTime${this.id}`,"local",0);const runLimitNum=this.getResultByKey(`${this.prefix}RunLimitNum${this.id}`,3e5);this.log(`上次运行时间:${lastRunningTime},运行频率限制:${runLimitNum}`);if(lastRunningTime>=0){if(this.now.getTime()-lastRunningTime<=runLimitNum){this.appendNotifyInfo("限制运行");this.isLimited=true}else{await this.setVal(`${this.prefix}LastRunningTime${this.id}`,this.now.getTime(),"local")}}return this.isLimited}getResultByKey(key,defaultValue){if(!this.options){return defaultValue}const val=this.options[key];if(this.isEmpty(val)){return defaultValue}else{return val}}appendNotifyInfo(info,type){if(type==1){this.notifyInfo=info}else{this.notifyInfo.push(`${this.logSeparator}${this.formatDate(new Date,"yyyy-MM-dd HH:mm:ss.S")}█${info}`)}}saveLog(){if(this.isSaveLog){let message;if(Array.isArray(this.notifyInfo)){message=this.notifyInfo.join("")}else{message=this.notifyInfo}if(!this.icloud.isDirectory(this.logDir)){this.icloud.createDirectory(this.logDir,true)}this.icloud.writeString(`${this.logDir}/${this.formatDate(this.now,"yyyyMMddHHmmss")}.log`,message)}}prependNotifyInfo(info){this.notifyInfo.splice(0,0,info)}execFail(){this.execStatus=false}sleep(time){return new Promise(resolve=>setTimeout(resolve,time))}log(message){if(this.isEnableLog)console.log(`${this.logSeparator}${JSON.stringify(message)}`);this.appendNotifyInfo(message)}logErr(message){this.execStatus=false;if(this.isEnableLog){console.warn(`${this.logSeparator}${this.name}执行异常:`);console.warn(message);console.warn(`\n${message.message}`)}}getContainer(key){return key=="local"?this.local:this.icloud}async getVal(key,container,defaultValue){let containerInstance=this.getContainer(container);let data="";try{let realDataFile=containerInstance.joinPath(containerInstance.documentsDirectory(),this.dataFile);if(!containerInstance.fileExists(realDataFile)){await this.setVal(key,defaultValue,container);return defaultValue}data=await containerInstance.readString(realDataFile);data=JSON.parse(data)}catch(e){throw e}if(data.hasOwnProperty(key)){return data[key]}else{await this.setVal(key,defaultValue,container);return defaultValue}}async getDataFile(container){let containerInstance=this.getContainer(container);let data="";try{let realDataFile=containerInstance.joinPath(containerInstance.documentsDirectory(),this.dataFile);if(!containerInstance.fileExists(realDataFile)){return Promise.resolve("")}data=await containerInstance.readString(realDataFile)}catch(e){throw e}return Promise.resolve(data)}async saveImage(fileName,image,container){let containerInstance=this.getContainer(container);let imagePath=containerInstance.joinPath(containerInstance.documentsDirectory(),`${this.prefix}${this.id}/${fileName}`);let imageDir=imagePath.substring(0,imagePath.lastIndexOf("/")+1);if(!containerInstance.isDirectory(imageDir)){containerInstance.createDirectory(imageDir,true)}containerInstance.writeImage(imagePath,image)}async getImage(fileName,container){let containerInstance=this.getContainer(container);let imagePath=containerInstance.joinPath(containerInstance.documentsDirectory(),`${this.prefix}${this.id}/${fileName}`);if(!containerInstance.fileExists(imagePath)){this.logErr(`file not exist: ${imagePath}`);return false}return await containerInstance.readImage(imagePath)}async setVal(key,val,container){let containerInstance=this.getContainer(container);let data;let realDataFile=containerInstance.joinPath(containerInstance.documentsDirectory(),this.dataFile);try{if(!containerInstance.fileExists(realDataFile)){data={}}else{data=await containerInstance.readString(realDataFile);data=JSON.parse(data)}}catch(e){data={}}data[key]=val;await containerInstance.writeString(realDataFile,JSON.stringify(data))}async get(options,callback=(()=>{})){let request=new Request("");request.url=options.url;request.method="GET";request.headers=options.headers;try{const result=await request.loadString();callback(request.response,result);return result}catch(e){this.logErr(e);callback(undefined,undefined)}}async post(options,callback=(()=>{})){let request=new Request("");request.url=options.url;request.body=options.body;request.method="POST";request.headers=options.headers;request.timeout=5e3;try{const result=await request.loadString();callback(request.response,result);return result}catch(e){this.logErr(e);callback(undefined,undefined)}}async loadScript({scriptName:scriptName,url:url}){this.log(`获取脚本【${scriptName}】`);const content=await this.get({url:url});this.icloud.writeString(`${this.icloud.documentsDirectory()}/${scriptName}.js`,content);this.log(`获取脚本【${scriptName}】完成🎉`)}require({scriptName:scriptName,url:url="",reload:reload=false}){if(this.icloud.fileExists(this.icloud.joinPath(this.icloud.documentsDirectory(),`${scriptName}.js`))&&!reload){this.log(`引用脚本【${scriptName}】`);return importModule(scriptName)}else{this.loadScript({scriptName:scriptName,url:url});this.log(`引用脚本【${scriptName}】`);return importModule(scriptName)}}async generateInputAlert(message,field,defaultValue){let result=[];let alert=new Alert;alert.message=message;alert.addTextField(field,defaultValue);alert.addCancelAction(this.curLang.s27);alert.addAction(this.curLang.s26);result[0]=await alert.presentAlert();result[1]=alert.textFieldValue(0);return result}async generateAlert(message,options){let alert=new Alert;alert.message=message;for(const option of options){alert.addAction(option)}return await alert.presentAlert()}isEmpty(obj){return typeof obj=="undefined"||obj==null||obj==""||obj=="null"}isWorkingDays(now,workingDaysFlag="curlybraces",holidayFlag="gamecontroller"){return new Promise(async(resolve,reject)=>{let sp="≈";const d=this.formatDate(now,"yyyy-MM-dd");let resultStr=0;try{let curDate=await this.getVal("curDateCache","local","fff");let curDateErrorTime=await this.getVal("curDateCacheErrorTime","local",this.now.getTime());let isPreError=!this.isEmpty(curDateErrorTime)&&Number(curDateErrorTime)+5*60*1e3{if(data.indexOf("<")==0){resultStr="❌"}else{resultStr=JSON.parse(data);if(resultStr.code==-1){resultStr="❌"}else{resultStr=resultStr.type.type}}})}}catch(e){resultStr="❌";this.logErr(e)}finally{await this.setVal("curDateCache",`${d}${sp}${resultStr}`,"local");if(resultStr=="❌"){resolve(resultStr);this.log("写入运行错误时间,5分钟后重新请求!");this.setVal("curDateCache","","local");this.setVal("curDateCacheErrorTime",`${this.now.getTime()}`,"local")}else{this.setVal("curDateCacheErrorTime","","local");this.setVal("curDateCache",`${d}${sp}${resultStr}`,"local");resolve(resultStr==0||resultStr==3?workingDaysFlag:holidayFlag)}}})}randomString(len){len=len||32;var $chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";var maxPos=$chars.length;var pwd="";for(let i=0;i{return item.name[this.lang]});let customEnterCallback=customEnter.map((item,index)=>{return item.callback});if(isReset){options=customEnterNames}else{this.operations.push({callback:main});this.operations.push({callback:function(){$.widgetCutBg()}});this.operations.push({callback:function(){$.cleanCache()}});options=options.concat(customEnterNames)}customEnterCallback.forEach(callback=>{this.operations.push({callback:callback})})}options.push(this.curLang.s32);this.operations.push({callback:function(){}});return await this.generateAlert(this.curLang.s30,options)}async handleOperations(index){await this.operations[index].callback()}cleanCache(){this.log(this.curLang.s34);let filePath=this.local.joinPath(this.local.documentsDirectory(),this.dataFile);if(this.local.fileExists(filePath)){this.local.remove(filePath)}filePath=this.bgImgPath;if(this.local.fileExists(filePath)){this.local.remove(filePath)}this.log(this.curLang.s35)}formatTimeDuring(total,lang="zh",n=0){total=Number(total);let zhUnitArr=["毫秒","秒","分钟","小时","天","月","年"];let enUnitArr=["ms","s","min","h","d","m","y"];let scaleArr=[1e3,60,60,24,30,12,100];let len=total;if(len>scaleArr[n]){len=total/scaleArr[n];return this.formatTimeDuring(len,lang,++n)}else{let unit=zhUnitArr[n];if(lang==="en"){unit=enUnitArr[n]}return len.toFixed(2)+""+unit}}fileLengthFormat(total,unit="",toByte=false){total=Number(total);var unitArr=["","KB","MB","GB","TB","PB","EB","ZB"];var n=0;try{n=unitArr.indexOf(unit)}catch(e){throw e}if(toByte){if(n==0){return total}return this.fileLengthFormat(total*1024,unitArr[--n],true)}var len=total;if(len>1e3){len=total/1024;return this.fileLengthFormat(len,unitArr[++n])}else{if(n==0){return len.toFixed(2)}return len.toFixed(2)+" "+unitArr[n]}}}(scriptName,scriptId,options)}
-//ScriptableToolKit-end
diff --git a/Scriptable/ScriptableToolKit.js b/Scriptable/ScriptableToolKit.js
index 85accfe..53230e0 100644
--- a/Scriptable/ScriptableToolKit.js
+++ b/Scriptable/ScriptableToolKit.js
@@ -28,10 +28,6 @@
function ScriptableToolKit(scriptName, scriptId, options) {
return new (class {
constructor(scriptName, scriptId, options) {
- //脚本执行限制
- this.isLimited = false
- this.checkLimit()
-
//scriptable公共组件
this.local = FileManager.local()
this.icloud = FileManager.iCloud()
@@ -142,12 +138,16 @@ function ScriptableToolKit(scriptName, scriptId, options) {
this.execStatus = true
this.notifyInfo = []
this.operations = []
+
+ //脚本执行限制
+ this.isLimited = false
+ this.checkLimit()
}
async checkLimit() {
const lastRunningTime = await this.getVal(`${this.prefix}LastRunningTime${this.id}`, 'local', 0)
const runLimitNum = this.getResultByKey(`${this.prefix}RunLimitNum${this.id}`, 300000)
- this.log(`上次运行时间:${lastRunningTime},运行频率限制:${runLimitNum}`)
+ this.log(`上次运行时间:${this.formatDate(new Date(lastRunningTime), "yyyy-MM-dd HH:mm:ss.S")} ${lastRunningTime},运行频率限制:${runLimitNum}`)
if (lastRunningTime >= 0) {
if (this.now.getTime() - lastRunningTime <= runLimitNum) {
this.appendNotifyInfo('限制运行')
diff --git a/Scriptable/module/weatherInfo.js b/Scriptable/module/weatherInfo.js
new file mode 100644
index 0000000..756befe
--- /dev/null
+++ b/Scriptable/module/weatherInfo.js
@@ -0,0 +1,79 @@
+const json = {
+ "weatherIcon": {
+ "阳光明媚": "CLEAR_DAYs",
+ "晴朗无云": "CLEAR_DAYs",
+ "晴朗": "CLEAR_DAYs",
+ "繁星点点": "CLEAR_NIGHT",
+ "局部多云": "PARTLY_CLOUDY_DAY",
+ "多云": "PARTLY_CLOUDY_DAY",
+ "大部晴朗": "PARTLY_CLOUDY_DAY",
+ "大部多云": "PARTLY_CLOUDY_DAY",
+ "雷阵雨": "IsolatedThundershowers",
+ "冰雹": "MixedSnowAndSleet",
+ "细雨": "LIGHT_RAIN",
+ "有雨": "LIGHT_RAIN",
+ "阵雨": "LIGHT_RAIN",
+ "局部雷暴雨": "LIGHT_RAIN",
+ "局部阵雨": "LIGHT_RAIN",
+ "雨夹冰雹": "FREEZING_RAIN",
+ "雨": "MODERATE_RAIN",
+ "烟雾": "LIGHT_HAZE",
+ "有烟雾": "LIGHT_HAZE",
+ "有霾": "LIGHT_HAZE",
+ "雾霾": "LIGHT_HAZE",
+ "阴霾": "LIGHT_HAZE",
+ "薄雾": "LIGHT_HAZE",
+ "有雾": "LIGHT_HAZE",
+ "大雾": "LIGHT_HAZE",
+ "零星阵雪": "SNOW",
+ "雨雪交加": "SNOW",
+ "小阵雪": "SNOW",
+ "有雪": "SNOW",
+ "大雪": "SNOW",
+ "暴雪": "SNOW",
+ "雪": "SNOW",
+ "刮风": "WIND",
+ "有风": "WIND",
+ },
+ "weatherSF": {
+ "阳光明媚": "sun.max.fill",
+ "晴朗": "sun.max.fill",
+ "晴朗无云": "sun.max.fill",
+ "繁星点点": "moon.stars.fill",
+ "局部多云": "cloud.fill",
+ "多云": "cloud.fill",
+ "大部晴朗": "cloud.fill",
+ "大部多云": "cloud.fill",
+ "雷阵雨": "cloud.drizzle.fill",
+ "冰雹": "cloud.drizzle.fill",
+ "细雨": "cloud.drizzle.fill",
+ "有雨": "cloud.rain.fill",
+ "阵雨": "cloud.drizzle.fill",
+ "局部阵雨": "cloud.drizzle.fill",
+ "局部雷暴雨": "cloud.drizzle.fill",
+ "雨夹冰雹": "cloud.drizzle.fill",
+ "雨": "cloud.drizzle.fill",
+ "烟雾": "sun.haze.fill",
+ "有霾": "sun.haze.fill",
+ "雾霾": "sun.haze.fill",
+ "阴霾": "sun.haze.fill",
+ "薄雾": "sun.haze.fill",
+ "有雾": "sun.haze.fill",
+ "大雾": "sun.haze.fill",
+ "零星阵雪": "cloud.snow.fill",
+ "雨雪交加": "cloud.snow.fill",
+ "小阵雪": "cloud.snow.fill",
+ "有雪": "cloud.snow.fill",
+ "大雪": "cloud.snow.fill",
+ "暴雪": "cloud.snow.fill",
+ "雪": "cloud.snow.fill",
+ "刮风": "wind",
+ "有风": "wind",
+ },
+}
+
+const weatherInfo = () => {
+ return json;
+}
+
+module.exports = weatherInfo;
\ No newline at end of file
diff --git a/cmy/CmyCheckin.boxjs.json b/cmy/CmyCheckin.boxjs.json
new file mode 100644
index 0000000..a385137
--- /dev/null
+++ b/cmy/CmyCheckin.boxjs.json
@@ -0,0 +1,263 @@
+{
+ "id": "lowking.personal.app.sub",
+ "name": "lowking个人应用订阅",
+ "author": "@lowking",
+ "icon": "https://avatars0.githubusercontent.com/u/33308659?s=460&u=9223074586cb14f2ae7ee0953515f8781ded8be9&v=4",
+ "repo": "https://github.com/lowking/Scripts/",
+ "apps": [
+ {
+ "id": "lkCmyCheckin",
+ "name": "CMY机场签到",
+ "desc_html": "⚠️使用说明详情【点我查看】",
+ "icons": [
+ "https://cmy.network/favicon.ico",
+ "https://cmy.network/favicon.ico"
+ ],
+ "keys": [
+ "lkCmyCheckinCookie",
+ "lkCmyCheckinLoginId",
+ "lkCmyCheckinPassword"
+ ],
+ "settings": [
+ {
+ "id": "lkIsEnableLogCmyCheckin",
+ "name": "开启/关闭日志",
+ "val": true,
+ "type": "boolean",
+ "desc": "默认开启"
+ },
+ {
+ "id": "lkNotifyOnlyFailCmyCheckin",
+ "name": "只当执行失败才通知",
+ "val": false,
+ "type": "boolean",
+ "desc": "默认关闭"
+ },
+ {
+ "id": "lkIsEnableTgNotifyCmyCheckin",
+ "name": "开启/关闭Telegram通知",
+ "val": false,
+ "type": "boolean",
+ "desc": "默认关闭"
+ },
+ {
+ "id": "lkTgNotifyUrlCmyCheckin",
+ "name": "Telegram通知地址",
+ "val": "",
+ "type": "text",
+ "desc": "Tg的通知地址,如:https://api.telegram.org/bot-token/sendMessage?chat_id=-100140&parse_mode=Markdown&text="
+ },
+ {
+ "id": "lkCmyCheckinCookie",
+ "name": "cookie",
+ "val": "",
+ "type": "text",
+ "desc": "cookie"
+ },
+ {
+ "id": "lkCmyCheckinLoginId",
+ "name": "账号",
+ "val": "",
+ "type": "text",
+ "desc": "账号"
+ },
+ {
+ "id": "lkCmyCheckinPassword",
+ "name": "密码",
+ "val": "",
+ "type": "text",
+ "desc": "密码"
+ }
+ ],
+ "author": "@lowking",
+ "repo": "https://github.com/lowking/Scripts",
+ "script": "https://raw.githubusercontent.com/lowking/Scripts/personal/cmy/cmy.js"
+ },
+ {
+ "id": "lkSteam",
+ "name": "Steam 价格监控",
+ "keys": [
+ "@steam.games"
+ ],
+ "settings": [
+ {
+ "id": "@steam.games",
+ "name": "游戏列表",
+ "val": "[\n\t{\n\t\t\"id\": 271590,\n\t\t\"name\": \"GTA V\"\n\t},\n\t{\n\t\t\"id\": 814380,\n\t\t\"name\": \"只狼:影逝二度\"\n\t},\n\t{\n\t\t\"id\": 292030,\n\t\t\"name\": \"巫师 3:狂猎\"\n\t}\n]\n",
+ "type": "textarea",
+ "autoGrow": true,
+ "rows": 5,
+ "desc": "游戏列表 (JSON 格式)",
+ "primary": ["name"],
+ "child": [
+ {
+ "id": "name",
+ "name": "游戏名",
+ "type": "text"
+ },
+ {
+ "id": "id",
+ "name": "游戏ID",
+ "type": "number"
+ }
+ ]
+ }
+ ],
+ "author": "@Peng-YM",
+ "repo": "https://github.com/Peng-YM/QuanX",
+ "icons": [
+ "https://raw.githubusercontent.com/Orz-3/mini/master/steam.png",
+ "https://raw.githubusercontent.com/Orz-3/task/master/steam.png"
+ ],
+ "script": "https://raw.githubusercontent.com/Peng-YM/QuanX/master/Tasks/steam.js"
+ },
+ {
+ "id": "lkSolitaire",
+ "name": "米游社自动接龙",
+ "desc_html": "⚠️使用说明详情【点我查看】",
+ "icons": [
+ "https://raw.githubusercontent.com/lowking/Scripts/master/doc/icon/miyoushe.png",
+ "https://raw.githubusercontent.com/lowking/Scripts/master/doc/icon/miyoushe.png"
+ ],
+ "keys": [
+ "solitaireTargetPostConfigKey"
+ ],
+ "settings": [
+ {
+ "id": "lkIsEnableLogSolitaire",
+ "name": "开启/关闭日志",
+ "val": true,
+ "type": "boolean",
+ "desc": "默认开启"
+ },
+ {
+ "id": "lkNotifyOnlyFailSolitaire",
+ "name": "只当执行失败才通知",
+ "val": false,
+ "type": "boolean",
+ "desc": "默认关闭"
+ },
+ {
+ "id": "lkIsEnableTgNotifySolitaire",
+ "name": "开启/关闭Telegram通知",
+ "val": false,
+ "type": "boolean",
+ "desc": "默认关闭"
+ },
+ {
+ "id": "lkTgNotifyUrlSolitaire",
+ "name": "Telegram通知地址",
+ "val": "",
+ "type": "text",
+ "desc": "Tg的通知地址,如:https://api.telegram.org/bot-token/sendMessage?chat_id=-100140&parse_mode=Markdown&text="
+ },
+ {
+ "id": "solitaireTargetPostConfigKey",
+ "name": "接龙配置",
+ "val": "",
+ "type": "textarea",
+ "autoGrow": true,
+ "rows": 5,
+ "desc": "",
+ "primary": [
+ "name"
+ ],
+ "child": [
+ {
+ "id": "name",
+ "name": "描述",
+ "type": "text"
+ },
+ {
+ "id": "postId",
+ "name": "帖子id",
+ "type": "text"
+ },
+ {
+ "id": "content",
+ "name": "发送内容",
+ "type": "textarea"
+ },
+ {
+ "id": "limit",
+ "name": "限制时间单位ms",
+ "type": "number"
+ }
+ ]
+ }
+ ],
+ "author": "@lowking",
+ "repo": "https://github.com/lowking/Scripts",
+ "script": "https://github.com/lowking/Scripts/blob/master/mihoyo/solitaire.js?raw=true",
+ "script_timeout": 10
+ },
+ {
+ "id": "lkFastLink",
+ "name": "FastLink",
+ "desc_html": "⚠️使用说明详情【点我查看】",
+ "icons": [
+ "https://github.com/lowking/Scripts/blob/master/boxjs-empty.bmp?raw=true",
+ "https://github.com/lowking/Scripts/blob/master/boxjs-empty.bmp?raw=true"
+ ],
+ "keys": [
+ "fastLinkUserName",
+ "fastLinkPassword"
+ ],
+ "settings": [
+ {
+ "id": "lkIsEnableLogFastLink",
+ "name": "开启/关闭日志",
+ "val": true,
+ "type": "boolean",
+ "desc": "默认开启"
+ },
+ {
+ "id": "lkNotifyOnlyFailFastLink",
+ "name": "只当执行失败才通知",
+ "val": false,
+ "type": "boolean",
+ "desc": "默认关闭"
+ },
+ {
+ "id": "lkIsEnableTgNotifyFastLink",
+ "name": "开启/关闭Telegram通知",
+ "val": false,
+ "type": "boolean",
+ "desc": "默认关闭"
+ },
+ {
+ "id": "lkTgNotifyUrlFastLink",
+ "name": "Telegram通知地址",
+ "val": "",
+ "type": "text",
+ "desc": "Tg的通知地址,如: https://api.telegram.org/bot-token/sendMessage?chat_id=-100140&parse_mode=Markdown&text="
+ },
+ {
+ "id": "fastLinkDomain",
+ "name": "域名",
+ "val": "",
+ "type": "text",
+ "desc": "https://xxxxx.xxx"
+ },
+ {
+ "id": "fastLinkUserName",
+ "name": "用户名",
+ "val": "",
+ "type": "text",
+ "desc": ""
+ },
+ {
+ "id": "fastLinkPassword",
+ "name": "密码",
+ "val": "",
+ "type": "text",
+ "desc": ""
+ }
+ ],
+ "author": "@lowking",
+ "repo": "https://github.com/lowking/Scripts",
+ "script": "https://github.com/lowking/Scripts/blob/personal/fastlink/fastlink.js?raw=true",
+ "script_timeout": 10
+ }
+ ]
+}
\ No newline at end of file
diff --git a/cmy/cmy.js b/cmy/cmy.js
new file mode 100644
index 0000000..3f3aec7
--- /dev/null
+++ b/cmy/cmy.js
@@ -0,0 +1,219 @@
+/*
+CMY机场签到-lowking-v1.0
+
+⚠️需要订阅BoxJs之后填写帐号密码
+
+hostname = cmy.network
+
+************************
+Surge 4.2.0+ 脚本配置:
+************************
+[Script]
+# > CMY机场签到
+朴朴签到cookie = type=http-request,pattern=https:\/\/cmy.network\/api\/user,script-path=https://raw.githubusercontent.com/lowking/Scripts/personal/cmy/cmy.js
+CMY机场签到 = type=cron,cronexp="0 0 0 * * ?",wake-system=1,script-path=https://raw.githubusercontent.com/lowking/Scripts/personal/cmy/cmy.js
+
+
+
+
+************************
+QuantumultX 脚本配置:
+************************
+
+[rewrite_local]
+#朴朴签到cookie
+https:\/\/cmy.network\/api\/user url script-request-header https://raw.githubusercontent.com/lowking/Scripts/personal/cmy/cmy.js
+
+[task_local]
+0 0 0 * * ? https://raw.githubusercontent.com/lowking/Scripts/personal/cmy/cmy.js
+
+
+
+
+************************
+LOON 脚本配置:
+************************
+[Script]
+http-request https:\/\/cmy.network\/api\/user script-path=https://raw.githubusercontent.com/lowking/Scripts/personal/cmy/cmy.js, timeout=10, tag=朴朴签到cookie
+cron "0 0 0 * * *" script-path=https://raw.githubusercontent.com/lowking/Scripts/personal/cmy/cmy.js, tag=CMY机场签到
+
+*/
+const lk = new ToolKit(`CMY机场签到`, `CmyCheckin`)
+const cmyCookieKey = 'lkCmyCheckinCookie'
+let cmyCookie = !lk.getVal(cmyCookieKey) ? '' : lk.getVal(cmyCookieKey)
+
+if(!lk.isExecComm) {
+ if (lk.isRequest()) {
+ getCookie()
+ lk.done()
+ } else {
+ lk.boxJsJsonBuilder({
+ keys: ["lkCmyCheckinCookie", "lkCmyCheckinLoginId", "lkCmyCheckinPassword"],
+ settings:[
+ {
+ "id": "lkCmyCheckinCookie",
+ "name": "cookie",
+ "val": "",
+ "type": "text",
+ "desc": "cookie"
+ },
+ {
+ "id": "lkCmyCheckinLoginId",
+ "name": "账号",
+ "val": "",
+ "type": "text",
+ "desc": "账号"
+ },
+ {
+ "id": "lkCmyCheckinPassword",
+ "name": "密码",
+ "val": "",
+ "type": "text",
+ "desc": "密码"
+ }
+ ],
+ icons: [
+ "https://cmy.network/favicon.ico",
+ "https://cmy.network/favicon.ico"
+ ],
+ script: "https://raw.githubusercontent.com/lowking/Scripts/personal/cmy/cmy.js?type=raw",
+ desc_html: "⚠️使用说明详情【点我查看】"
+ })
+ all()
+ }
+}
+
+function getCookie() {
+ if (lk.isGetCookie(/cmy\.network\/api\/user/)) {
+ if ($request.headers.hasOwnProperty('access-token')) {
+ lk.setVal(cmyCookieKey, JSON.stringify($request.headers))
+ lk.appendNotifyInfo('🎉成功获取CMY-Cookie,可以关闭相应脚本')
+ } else {
+ lk.appendNotifyInfo('❌获取CMY-Cookie失败')
+ }
+ lk.msg('')
+ }
+}
+
+async function all() {
+ let result = ""
+ if (lk.isEmpty(cmyCookie)) {
+ result = await login()
+ lk.log(`test${result}`)
+ if (result == "ok") {
+ await checkIn()
+ }
+ } else {
+ await checkIn()
+ }
+ lk.msg(``)
+ lk.done()
+}
+
+function login(type) {
+ return new Promise( (resolve, reject) => {
+ let loginId = lk.getVal("lkCmyCheckinLoginId")
+ let pwd = lk.getVal("lkCmyCheckinPassword")
+ let loginUrl = {
+ url: `https://cmy.network/api/auth/login`,
+ headers: {
+ "accept": "application/json, text/plain, */*",
+ "accept-language": "zh-CN,zh;q=0.9,zh-TW;q=0.8,en;q=0.7,ja;q=0.6",
+ "content-type": "application/json;charset=UTF-8",
+ "sec-fetch-dest": "empty",
+ "sec-fetch-mode": "cors",
+ "sec-fetch-site": "same-origin",
+ },
+ body: JSON.stringify({
+ "email": loginId,
+ "passwd": pwd,
+ "remember_me": false
+ })
+ }
+ lk.log(JSON.stringify(loginUrl))
+ lk.post(loginUrl, async (error, response, data) => {
+ try {
+ lk.log(data)
+ const result = JSON.parse(data)
+ if (result.ret == 1) {
+ //登录成功,调用签到
+ lk.log(`登录成功`)
+ lk.execStatus = true
+ loginUrl.headers["access-token"] = result.data.token
+ cmyCookie = JSON.stringify(loginUrl.headers)
+ lk.setVal(cmyCookieKey, cmyCookie)
+ resolve("ok")
+ } else {
+ lk.log(result.msg)
+ lk.appendNotifyInfo(`❌登录失败:${result.msg}`)
+ lk.execFail()
+ resolve("fail")
+ }
+ } catch (e) {
+ lk.logErr(e)
+ lk.log(`登录异常:${data}`)
+ lk.execFail()
+ resolve("fail")
+ }
+ })
+ })
+}
+
+async function checkIn(count = 0) {
+ return new Promise(async (resolve, reject) => {
+ let checkInUrl = {
+ url: `https://cmy.network/api/checkin`,
+ headers: JSON.parse(cmyCookie)
+ }
+ lk.log(JSON.stringify(checkInUrl))
+ lk.get(checkInUrl, async (error, response, data) => {
+ try {
+ lk.log(data)
+ const result = JSON.parse(data)
+ if (result.ret == 1) {
+ //签到成功
+ lk.notifyInfo = []
+ lk.appendNotifyInfo(`🎉签到${result.msg}\n今天使用:${result.trafficInfo.todayUsedTraffic}\n总共使用:${result.trafficInfo.lastUsedTraffic}\n剩余流量:${result.trafficInfo.unUsedTraffic}`)
+ lk.log(`签到成功`)
+ lk.setVal(cmyCookieKey, JSON.stringify(checkInUrl.headers))
+ } else if (result.ret == 0) {
+ if (result.msg == "token is null") {
+ cmyCookie = ""
+ lk.setVal(cmyCookieKey, "")
+ await all()
+ } else {
+ //签到成功
+ lk.notifyInfo = []
+ lk.appendNotifyInfo(`🔁${result.msg}`)
+ lk.log(`重复签到`)
+ lk.setVal(cmyCookieKey, JSON.stringify(checkInUrl.headers))
+ }
+ } else {
+ lk.appendNotifyInfo(`❌签到失败:${result.msg}`)
+ lk.setVal(cmyCookieKey, "")
+ if (count > 0) {
+ lk.execFail()
+ resolve()
+ } else {
+ count++
+ let result = await login()
+ if (result == "ok") {
+ await checkIn(count)
+ }
+ }
+ }
+ } catch (e) {
+ lk.logErr(e)
+ lk.log(`签到返回数据:${data}`)
+ lk.execFail()
+ lk.appendNotifyInfo(`❌签到失败,请带上日志联系作者`)
+ } finally {
+ resolve()
+ }
+ })
+ })
+}
+
+//ToolKit-start
+function ToolKit(t,s,i){return new class{constructor(t,s,i){this.tgEscapeCharMapping={"&":"&","#":"#"};this.userAgent=`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.2 Safari/605.1.15`;this.prefix=`lk`;this.name=t;this.id=s;this.data=null;this.dataFile=this.getRealPath(`${this.prefix}${this.id}.dat`);this.boxJsJsonFile=this.getRealPath(`${this.prefix}${this.id}.boxjs.json`);this.options=i;this.isExecComm=false;this.isEnableLog=this.getVal(`${this.prefix}IsEnableLog${this.id}`);this.isEnableLog=this.isEmpty(this.isEnableLog)?true:JSON.parse(this.isEnableLog);this.isNotifyOnlyFail=this.getVal(`${this.prefix}NotifyOnlyFail${this.id}`);this.isNotifyOnlyFail=this.isEmpty(this.isNotifyOnlyFail)?false:JSON.parse(this.isNotifyOnlyFail);this.isEnableTgNotify=this.getVal(`${this.prefix}IsEnableTgNotify${this.id}`);this.isEnableTgNotify=this.isEmpty(this.isEnableTgNotify)?false:JSON.parse(this.isEnableTgNotify);this.tgNotifyUrl=this.getVal(`${this.prefix}TgNotifyUrl${this.id}`);this.isEnableTgNotify=this.isEnableTgNotify?!this.isEmpty(this.tgNotifyUrl):this.isEnableTgNotify;this.costTotalStringKey=`${this.prefix}CostTotalString${this.id}`;this.costTotalString=this.getVal(this.costTotalStringKey);this.costTotalString=this.isEmpty(this.costTotalString)?`0,0`:this.costTotalString.replace('"',"");this.costTotalMs=this.costTotalString.split(",")[0];this.execCount=this.costTotalString.split(",")[1];this.costTotalMs=this.isEmpty(this.costTotalMs)?0:parseInt(this.costTotalMs);this.execCount=this.isEmpty(this.execCount)?0:parseInt(this.execCount);this.logSeparator="\n██";this.startTime=(new Date).getTime();this.node=(()=>{if(this.isNode()){const t=require("request");return{request:t}}else{return null}})();this.execStatus=true;this.notifyInfo=[];this.log(`${this.name}, 开始执行!`);this.execComm()}getRealPath(t){if(this.isNode()){let s=process.argv.slice(1,2)[0].split("/");s[s.length-1]=t;return s.join("/")}return t}async execComm(){if(this.isNode()){this.comm=process.argv.slice(1);let t=false;if(this.comm[1]=="p"){this.isExecComm=true;this.log(`开始执行指令【${this.comm[1]}】=> 发送到手机测试脚本!`);if(this.isEmpty(this.options)||this.isEmpty(this.options.httpApi)){this.log(`未设置options,使用默认值`);if(this.isEmpty(this.options)){this.options={}}this.options.httpApi=`ffff@10.0.0.9:6166`}else{if(!/.*?@.*?:[0-9]+/.test(this.options.httpApi)){t=true;this.log(`❌httpApi格式错误!格式:ffff@3.3.3.18:6166`);this.done()}}if(!t){await this.callApi(this.comm[2])}}}}callApi(t){let s=this.comm[0];this.log(`获取【${s}】内容传给手机`);let i="";this.fs=this.fs?this.fs:require("fs");this.path=this.path?this.path:require("path");const e=this.path.resolve(s);const h=this.path.resolve(process.cwd(),s);const o=this.fs.existsSync(e);const r=!o&&this.fs.existsSync(h);if(o||r){const t=o?e:h;try{i=this.fs.readFileSync(t)}catch(t){i=""}}else{i=""}let n={url:`http://${this.options.httpApi.split("@")[1]}/v1/scripting/evaluate`,headers:{"X-Key":`${this.options.httpApi.split("@")[0]}`},body:{script_text:`${i}`,mock_type:"cron",timeout:!this.isEmpty(t)&&t>5?t:5},json:true};this.post(n,(t,i,e)=>{this.log(`已将脚本【${s}】发给手机!`);this.done()})}getCallerFileNameAndLine(){let t;try{throw Error("")}catch(s){t=s}const s=t.stack;const i=s.split("\n");let e=1;if(e!==0){const t=i[e];this.path=this.path?this.path:require("path");return`[${t.substring(t.lastIndexOf(this.path.sep)+1,t.lastIndexOf(":"))}]`}else{return"[-]"}}getFunName(t){var s=t.toString();s=s.substr("function ".length);s=s.substr(0,s.indexOf("("));return s}boxJsJsonBuilder(t,s){if(this.isNode()){this.log("using node");let i=["keys","settings"];const e="https://raw.githubusercontent.com/Orz-3";let h={};let o="script_url";if(s&&s.hasOwnProperty("script_url")){o=this.isEmpty(s["script_url"])?"script_url":s["script_url"]}h.id=`${this.prefix}${this.id}`;h.name=this.name;h.desc_html=`⚠️使用说明详情【点我查看】`;h.icons=[`${e}/mini/master/Alpha/${this.id.toLocaleLowerCase()}.png`,`${e}/mini/master/Color/${this.id.toLocaleLowerCase()}.png`];h.keys=[];h.settings=[{id:`${this.prefix}IsEnableLog${this.id}`,name:"开启/关闭日志",val:true,type:"boolean",desc:"默认开启"},{id:`${this.prefix}NotifyOnlyFail${this.id}`,name:"只当执行失败才通知",val:false,type:"boolean",desc:"默认关闭"},{id:`${this.prefix}IsEnableTgNotify${this.id}`,name:"开启/关闭Telegram通知",val:false,type:"boolean",desc:"默认关闭"},{id:`${this.prefix}TgNotifyUrl${this.id}`,name:"Telegram通知地址",val:"",type:"text",desc:"Tg的通知地址,如:https://api.telegram.org/bot-token/sendMessage?chat_id=-100140&parse_mode=Markdown&text="}];h.author="@lowking";h.repo="https://github.com/lowking/Scripts";h.script=`${o}?raw=true`;if(!this.isEmpty(t)){for(let s in i){let e=i[s];if(!this.isEmpty(t[e])){h[e]=h[e].concat(t[e])}delete t[e]}}Object.assign(h,t);if(this.isNode()){this.fs=this.fs?this.fs:require("fs");this.path=this.path?this.path:require("path");const t=this.path.resolve(this.boxJsJsonFile);const s=this.path.resolve(process.cwd(),this.boxJsJsonFile);const i=this.fs.existsSync(t);const e=!i&&this.fs.existsSync(s);const o=JSON.stringify(h,null,"\t");if(i){this.fs.writeFileSync(t,o)}else if(e){this.fs.writeFileSync(s,o)}else{this.fs.writeFileSync(t,o)}}}}appendNotifyInfo(t,s){if(s==1){this.notifyInfo=t}else{this.notifyInfo.push(t)}}prependNotifyInfo(t){this.notifyInfo.splice(0,0,t)}execFail(){this.execStatus=false}isRequest(){return typeof $request!="undefined"}isSurge(){return typeof $httpClient!="undefined"}isQuanX(){return typeof $task!="undefined"}isLoon(){return typeof $loon!="undefined"}isJSBox(){return typeof $app!="undefined"&&typeof $http!="undefined"}isNode(){return typeof require=="function"&&!this.isJSBox()}sleep(t){return new Promise(s=>setTimeout(s,t))}log(t){if(this.isEnableLog)console.log(`${this.logSeparator}${t}`)}logErr(t){this.execStatus=true;if(this.isEnableLog){console.log(`${this.logSeparator}${this.name}执行异常:`);console.log(t);console.log(`\n${t.message}`)}}msg(t,s,i,e){if(!this.isRequest()&&this.isNotifyOnlyFail&&this.execStatus){}else{if(this.isEmpty(s)){if(Array.isArray(this.notifyInfo)){s=this.notifyInfo.join("\n")}else{s=this.notifyInfo}}if(!this.isEmpty(s)){if(this.isEnableTgNotify){this.log(`${this.name}Tg通知开始`);for(let t in this.tgEscapeCharMapping){if(!this.tgEscapeCharMapping.hasOwnProperty(t)){continue}s=s.replace(t,this.tgEscapeCharMapping[t])}this.get({url:encodeURI(`${this.tgNotifyUrl}📌${this.name}\n${s}`)},(t,s,i)=>{this.log(`Tg通知完毕`)})}else{let h={};const o=!this.isEmpty(i);const r=!this.isEmpty(e);if(this.isQuanX()){if(o)h["open-url"]=i;if(r)h["media-url"]=e;$notify(this.name,t,s,h)}if(this.isSurge()){if(o)h["url"]=i;$notification.post(this.name,t,s,h)}if(this.isNode())this.log("⭐️"+this.name+t+s);if(this.isJSBox())$push.schedule({title:this.name,body:t?t+"\n"+s:s})}}}}getVal(t){if(this.isSurge()||this.isLoon()){return $persistentStore.read(t)}else if(this.isQuanX()){return $prefs.valueForKey(t)}else if(this.isNode()){this.data=this.loadData();return this.data[t]}else{return this.data&&this.data[t]||null}}setVal(t,s){if(this.isSurge()||this.isLoon()){return $persistentStore.write(s,t)}else if(this.isQuanX()){return $prefs.setValueForKey(s,t)}else if(this.isNode()){this.data=this.loadData();this.data[t]=s;this.writeData();return true}else{return this.data&&this.data[t]||null}}loadData(){if(this.isNode()){this.fs=this.fs?this.fs:require("fs");this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile);const s=this.path.resolve(process.cwd(),this.dataFile);const i=this.fs.existsSync(t);const e=!i&&this.fs.existsSync(s);if(i||e){const e=i?t:s;try{return JSON.parse(this.fs.readFileSync(e))}catch(t){return{}}}else return{}}else return{}}writeData(){if(this.isNode()){this.fs=this.fs?this.fs:require("fs");this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile);const s=this.path.resolve(process.cwd(),this.dataFile);const i=this.fs.existsSync(t);const e=!i&&this.fs.existsSync(s);const h=JSON.stringify(this.data);if(i){this.fs.writeFileSync(t,h)}else if(e){this.fs.writeFileSync(s,h)}else{this.fs.writeFileSync(t,h)}}}adapterStatus(t){if(t){if(t.status){t["statusCode"]=t.status}else if(t.statusCode){t["status"]=t.statusCode}}return t}get(t,s=(()=>{})){if(this.isQuanX()){if(typeof t=="string")t={url:t};t["method"]="GET";$task.fetch(t).then(t=>{s(null,this.adapterStatus(t),t.body)},t=>s(t.error,null,null))}if(this.isSurge())$httpClient.get(t,(t,i,e)=>{s(t,this.adapterStatus(i),e)});if(this.isNode()){this.node.request(t,(t,i,e)=>{s(t,this.adapterStatus(i),e)})}if(this.isJSBox()){if(typeof t=="string")t={url:t};t["header"]=t["headers"];t["handler"]=function(t){let i=t.error;if(i)i=JSON.stringify(t.error);let e=t.data;if(typeof e=="object")e=JSON.stringify(t.data);s(i,this.adapterStatus(t.response),e)};$http.get(t)}}post(t,s=(()=>{})){if(this.isQuanX()){if(typeof t=="string")t={url:t};t["method"]="POST";$task.fetch(t).then(t=>{s(null,this.adapterStatus(t),t.body)},t=>s(t.error,null,null))}if(this.isSurge()){$httpClient.post(t,(t,i,e)=>{s(t,this.adapterStatus(i),e)})}if(this.isNode()){this.node.request.post(t,(t,i,e)=>{s(t,this.adapterStatus(i),e)})}if(this.isJSBox()){if(typeof t=="string")t={url:t};t["header"]=t["headers"];t["handler"]=function(t){let i=t.error;if(i)i=JSON.stringify(t.error);let e=t.data;if(typeof e=="object")e=JSON.stringify(t.data);s(i,this.adapterStatus(t.response),e)};$http.post(t)}}costTime(){let t=`${this.name}执行完毕!`;if(this.isNode()&&this.isExecComm){t=`指令【${this.comm[1]}】执行完毕!`}const s=(new Date).getTime();const i=s-this.startTime;const e=i/1e3;this.execCount++;this.costTotalMs+=i;this.log(`${t}耗时【${e}】秒\n总共执行【${this.execCount}】次,平均耗时【${(this.costTotalMs/this.execCount/1e3).toFixed(4)}】秒`);this.setVal(this.costTotalStringKey,JSON.stringify(`${this.costTotalMs},${this.execCount}`))}done(t={}){this.costTime();if(this.isSurge()||this.isQuanX()||this.isLoon()){$done(t)}}getRequestUrl(){return $request.url}getResponseBody(){return $response.body}isGetCookie(t){return!!($request.method!="OPTIONS"&&this.getRequestUrl().match(t))}isEmpty(t){return typeof t=="undefined"||t==null||t==""||t=="null"||t=="undefined"||t.length===0}randomString(t){t=t||32;var s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";var i=s.length;var e="";for(let h=0;h {
+ return await lk.req.post({
+ url: `${domain}/auth/login?email=${userName}&passwd=${password}&code=&remember_me=on`,
+ headers: {
+ 'authority': domain.split("//")[1],
+ 'accept': 'application/json, text/javascript, */*; q=0.01',
+ 'accept-language': 'zh-CN,zh;q=0.9',
+ 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
+ 'dnt': '1',
+ 'origin': domain,
+ 'referer': `${domain}/auth/login`,
+ 'sec-ch-ua': '"Not(A:Brand";v="24", "Chromium";v="122"',
+ 'sec-ch-ua-mobile': '?0',
+ 'sec-ch-ua-platform': '"macOS"',
+ 'sec-fetch-dest': 'empty',
+ 'sec-fetch-mode': 'cors',
+ 'sec-fetch-site': 'same-origin',
+ 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
+ 'x-requested-with': 'XMLHttpRequest',
+ },
+ body: {
+ "email": userName,
+ "passwd": password,
+ "code": "",
+ "remember_me": "on"
+ }.s()
+ }).then(({ error, resp, data }) => {
+ data = data.o()
+ if (data.ret != 1) {
+ return ""
+ }
+ if (!resp.headers.hasOwnProperty("set-cookie")) {
+ lk.log("登录请求未返回cookie")
+ return ""
+ }
+ return resp.headers["set-cookie"].join("; ")
+ })
+}
+
+const checkIn = async cookie => {
+ await lk.req.post({
+ url: `${domain}/user/checkin`,
+ headers:{
+ 'authority': domain.split("//")[1],
+ 'accept': 'application/json, text/javascript, */*; q=0.01',
+ 'accept-language': 'zh-CN,zh;q=0.9',
+ 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
+ 'dnt': '1',
+ 'origin': domain,
+ 'referer': `${domain}/user`,
+ 'sec-ch-ua': '"Not(A:Brand";v="24", "Chromium";v="122"',
+ 'sec-ch-ua-mobile': '?0',
+ 'sec-ch-ua-platform': '"macOS"',
+ 'sec-fetch-dest': 'empty',
+ 'sec-fetch-mode': 'cors',
+ 'sec-fetch-site': 'same-origin',
+ 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
+ 'x-requested-with': 'XMLHttpRequest',
+ cookie
+ }
+ }).then(({ error, resp, data }) => {
+ data = data.o()
+ if (data.ret != 1) {
+ lk.appendNotifyInfo(`❌签到失败:${data.msg}`)
+ } else {
+ lk.appendNotifyInfo(`🎉签到成功:${data.msg}`)
+ }
+ })
+}
+
+const all = async () => {
+ if (!userName || !password || !domain) {
+ throw "⚠️请先设置账号密码和域名"
+ }
+ await login().then(async (cookie) => {
+ if (!cookie) return
+ await checkIn(cookie)
+ })
+}
+
+const main = () => {
+ if (lk.isRequest()) {
+ lk.done()
+ return
+ }
+ lk.boxJsJsonBuilder(BoxJsInfo, BoxJsParam)
+ all().catch((err) => {
+ lk.logErr(err)
+ lk.execFail()
+ lk.msg(``)
+ }).finally(() => {
+ lk.msg(``)
+ lk.done()
+ })
+}
+
+if(!lk.isExecComm) main()
+
+// * ToolKit v1.3.2 build 152
+function ToolKit(scriptName,scriptId,options){class Request{constructor(tk){this.tk=tk}fetch(options,method="GET"){options=typeof options=="string"?{url:options}:options;let fetcher;switch(method){case"PUT":fetcher=this.put;break;case"POST":fetcher=this.post;break;default:fetcher=this.get}const doFetch=new Promise((resolve,reject)=>{fetcher.call(this,options,(error,resp,data)=>error?reject({error,resp,data}):resolve({error,resp,data}))}),delayFetch=(promise,timeout=5e3)=>Promise.race([promise,new Promise((_,reject)=>setTimeout(()=>reject(new Error("请求超时")),timeout))]);return options.timeout>0?delayFetch(doFetch,options.timeout):doFetch}async get(options){return this.fetch.call(this.tk,options)}async post(options){return this.fetch.call(this.tk,options,"POST")}async put(options){return this.fetch.call(this.tk,options,"PUT")}}return new class{constructor(scriptName,scriptId,options){Object.prototype.s=function(replacer,space){return typeof this=="string"?this:JSON.stringify(this,replacer,space)},Object.prototype.o=function(reviver){return JSON.parse(this,reviver)},this.userAgent=`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.2 Safari/605.1.15`,this.a=`lk`,this.name=scriptName,this.id=scriptId,this.req=new Request(this),this.data=null,this.b=this.fb(`${this.a}${this.id}.dat`),this.c=this.fb(`${this.a}${this.id}.boxjs.json`),this.d=options,this.isExecComm=!1,this.f=this.getVal(`${this.a}IsEnableLog${this.id}`),this.f=!!this.isEmpty(this.f)||this.f.o(),this.g=this.getVal(`${this.a}NotifyOnlyFail${this.id}`),this.g=!this.isEmpty(this.g)&&this.g.o(),this.h=this.getVal(`${this.a}IsEnableTgNotify${this.id}`),this.h=!this.isEmpty(this.h)&&this.h.o(),this.i=this.getVal(`${this.a}TgNotifyUrl${this.id}`),this.h=this.h?!this.isEmpty(this.i):this.h,this.j=`${this.a}CostTotalString${this.id}`,this.k=this.getVal(this.j),this.k=this.isEmpty(this.k)?`0,0`:this.k.replace('"',""),this.l=this.k.split(",")[0],this.m=this.k.split(",")[1],this.n=0,this.o=`
+██`,this.p=" ",this.now=new Date,this.q=this.now.getTime(),this.node=(()=>{if(this.isNode()){const request=require("request");return{request}}return null})(),this.r=!0,this.s=[],this.t="chavy_boxjs_cur__acs",this.u="chavy_boxjs__acs",this.v={"|`|":",backQuote,"},this.w={",backQuote,":"`","%2CbackQuote%2C":"`"},this.y={"_":"\\_","*":"\\*","`":"\\`"},this.x={"_":"\\_","*":"\\*","[":"\\[","]":"\\]","(":"\\(",")":"\\)","~":"\\~","`":"\\`",">":"\\>","#":"\\#","+":"\\+","-":"\\-","=":"\\=","|":"\\|","{":"\\{","}":"\\}",".":"\\.","!":"\\!"},this.log(`${this.name}, 开始执行!`),this.fd()}fb(_a){if(!this.isNode())return _a;let _b=process.argv.slice(1,2)[0].split("/");return _b[_b.length-1]=_a,_b.join("/")}fc(_a){const _c=this.path.resolve(_a),_d=this.path.resolve(process.cwd(),_a),_e=this.fs.existsSync(_c),_f=!_e&&this.fs.existsSync(_d);return{_c,_d,_e,_f}}async fd(){if(!this.isNode())return;if(this.e=process.argv.slice(1),this.e[1]!="p")return;this.isExecComm=!0,this.log(`开始执行指令【${this.e[1]}】=> 发送到其他终端测试脚本!`);let httpApi=this.d?.httpApi,_h;if(this.isEmpty(this?.d?.httpApi))this.log(`未设置options,使用默认值`),this.isEmpty(this?.d)&&(this.d={}),this.d.httpApi=`ffff@10.0.0.6:6166`,httpApi=this.d.httpApi,_h=httpApi.split("@")[1];else{if(typeof httpApi=="object")if(_h=this.isNumeric(this.e[2])?this.e[3]||"unknown":this.e[2],httpApi[_h])httpApi=httpApi[_h];else{const keys=Object.keys(httpApi);keys[0]?(_h=keys[0],httpApi=httpApi[keys[0]]):httpApi="error"}if(!/.*?@.*?:[0-9]+/.test(httpApi)){this.log(`❌httpApi格式错误!格式: ffff@3.3.3.18:6166`),this.done();return}}this.fe(this.e[2],_h,httpApi)}fe(timeout,_h,httpApi){let _i=this.e[0];const[_j,_k]=httpApi.split("@");this.log(`获取【${_i}】内容传给【${_h||_k}】`),this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const{_c,_d,_e,_f}=this.fc(_i);if(!_e&&!_f){lk.done();return}const _m=_e?_c:_d;let options={url:`http://${_k}/v1/scripting/evaluate`,headers:{"X-Key":_j},body:{script_text:String(this.fs.readFileSync(_m)),mock_type:"cron",timeout:!this.isEmpty(timeout)&&timeout>5?timeout:5},json:!0};this.req.post(options).then(({error,resp,data})=>{this.log(`已将脚本【${_i}】发给【${_h||_k}】,执行结果:
+${this.p}error: ${error}
+${this.p}resp: ${resp?.s()}
+${this.p}data: ${this.fj(data)}`),this.done()})}boxJsJsonBuilder(info,param){if(!this.isNode())return;if(!this.isJsonObject(info)||!this.isJsonObject(param)){this.log("构建BoxJsJson传入参数格式错误,请传入json对象");return}let _p=param?.targetBoxjsJsonPath||"/Users/lowking/Desktop/Scripts/lowking.boxjs.json";if(!this.fs.existsSync(_p))return;this.log("using node");let _q=["settings","keys"];const _r="https://raw.githubusercontent.com/Orz-3";let boxJsJson={},scritpUrl="#lk{script_url}";if(boxJsJson.id=`${this.a}${this.id}`,boxJsJson.name=this.name,boxJsJson.desc_html=`⚠️使用说明详情【点我查看】`,boxJsJson.icons=[`${_r}/mini/master/Alpha/${this.id.toLocaleLowerCase()}.png`,`${_r}/mini/master/Color/${this.id.toLocaleLowerCase()}.png`],boxJsJson.keys=[],boxJsJson.settings=[{id:`${this.a}IsEnableLog${this.id}`,name:"开启/关闭日志",val:!0,type:"boolean",desc:"默认开启"},{id:`${this.a}NotifyOnlyFail${this.id}`,name:"只当执行失败才通知",val:!1,type:"boolean",desc:"默认关闭"},{id:`${this.a}IsEnableTgNotify${this.id}`,name:"开启/关闭Telegram通知",val:!1,type:"boolean",desc:"默认关闭"},{id:`${this.a}TgNotifyUrl${this.id}`,name:"Telegram通知地址",val:"",type:"text",desc:"Tg的通知地址,如: https://api.telegram.org/bot-token/sendMessage?chat_id=-100140&parse_mode=Markdown&text="}],boxJsJson.author="#lk{author}",boxJsJson.repo="#lk{repo}",boxJsJson.script=`${scritpUrl}?raw=true`,!this.isEmpty(info))for(let key of _q){if(this.isEmpty(info[key]))break;if(key==="settings")for(let i=0;iapp.id==boxJsJson.id)[0]);targetIdx>=0?boxjsJson.apps[targetIdx]=boxJsJson:boxjsJson.apps.push(boxJsJson);let ret=boxjsJson.s(null,2);if(!this.isEmpty(param))for(const key in param){let val=param[key];if(!val)switch(key){case"author":val="@lowking";break;case"repo":val="https://github.com/lowking/Scripts";break;default:continue}ret=ret.replaceAll(`#lk{${key}}`,val)}const regex=/(?:#lk\{)(.+?)(?=\})/;let m=regex.exec(ret);m!==null&&this.log(`⚠️生成BoxJs还有未配置的参数,请参考:
+${this.p}https://github.com/lowking/Scripts/blob/master/util/example/ToolKitDemo.js#L17-L19
+${this.p}传入参数: `);let _n=new Set;for(;(m=regex.exec(ret))!==null;)_n.add(m[1]),ret=ret.replace(`#lk{${m[1]}}`,``);_n.forEach(p=>console.log(`${this.p}${p}`)),this.fs.writeFileSync(_p,ret)}isJsonObject(obj){return typeof obj=="object"&&Object.prototype.toString.call(obj).toLowerCase()=="[object object]"&&!obj.length}appendNotifyInfo(info,type){type==1?this.s=info:this.s.push(info)}prependNotifyInfo(info){this.s.splice(0,0,info)}execFail(){this.r=!1}isRequest(){return typeof $request!="undefined"}isSurge(){return typeof $httpClient!="undefined"}isQuanX(){return typeof $task!="undefined"}isLoon(){return typeof $loon!="undefined"}isJSBox(){return typeof $app!="undefined"&&typeof $http!="undefined"}isStash(){return"undefined"!=typeof $environment&&$environment["stash-version"]}isNode(){return typeof require=="function"&&!this.isJSBox()}sleep(ms){return this.n+=ms,new Promise(resolve=>setTimeout(resolve,ms))}randomSleep(minMs,maxMs){return this.sleep(this.randomNumber(minMs,maxMs))}randomNumber(min,max){return Math.floor(Math.random()*(max-min+1)+min)}log(message){this.f&&console.log(`${this.o}${message}`)}logErr(message){if(this.r=!0,this.f){let msg="";this.isEmpty(message.error)||(msg=`${msg}
+${this.p}${message.error.s()}`),this.isEmpty(message.message)||(msg=`${msg}
+${this.p}${message.message.s()}`),msg=`${this.o}${this.name}执行异常:${this.p}${msg}`,message&&(msg=`${msg}
+${this.p}${message.s()}`),console.log(msg)}}ff(mapping,message){for(let key in mapping){if(!mapping.hasOwnProperty(key))continue;message=message.replaceAll(key,mapping[key])}return message}msg(subtitle,message,openUrl,mediaUrl,copyText,disappearS){if(!this.isRequest()&&this.g&&this.r)return;if(this.isEmpty(message)&&(Array.isArray(this.s)?message=this.s.join(`
+`):message=this.s),this.isEmpty(message))return;if(this.h){this.log(`${this.name}Tg通知开始`);const fa=this.i&&this.i.indexOf("parse_mode=Markdown")!=-1;if(fa){message=this.ff(this.v,message);let _t=this.y;this.i.indexOf("parse_mode=MarkdownV2")!=-1&&(_t=this.x),message=this.ff(_t,message)}message=`📌${this.name}
+${message}`,fa&&(message=this.ff(this.w,message));let u=`${this.i}${encodeURIComponent(message)}`;this.req.get({url:u})}else{let options={};const _u=!this.isEmpty(openUrl),_v=!this.isEmpty(mediaUrl),_w=!this.isEmpty(copyText),_x=disappearS>0;this.isSurge()||this.isLoon()||this.isStash()?(_u&&(options.url=openUrl,options.action="open-url"),_w&&(options.text=copyText,options.action="clipboard"),this.isSurge()&&_x&&(options["auto-dismiss"]=disappearS),_v&&(options["media-url"]=mediaUrl),$notification.post(this.name,subtitle,message,options)):this.isQuanX()?(_u&&(options["open-url"]=openUrl),_v&&(options["media-url"]=mediaUrl),$notify(this.name,subtitle,message,options)):this.isNode()?this.log("⭐️"+this.name+`
+`+subtitle+`
+`+message):this.isJSBox()&&$push.schedule({title:this.name,body:subtitle?subtitle+`
+`+message:message})}}getVal(key,defaultValue){let value;return this.isSurge()||this.isLoon()||this.isStash()?value=$persistentStore.read(key):this.isQuanX()?value=$prefs.valueForKey(key):this.isNode()?(this.data=this.fh(),value=process.env[key]||this.data[key]):value=this.data&&this.data[key]||null,value||defaultValue}fg(key,val){if(key==this.u)return;const _y=`${this.a}${this.id}`;let _z=this.getVal(this.t,"{}").o();if(!_z.hasOwnProperty(_y))return;let curSessionId=_z[_y],_aa=this.getVal(this.u,"[]").o();if(_aa.length==0)return;let _ab=[];if(_aa.forEach(_ac=>{_ac.id==curSessionId&&(_ab=_ac.datas)}),_ab.length==0)return;let _ad=!1;_ab.forEach(kv=>{kv.key==key&&(kv.val=val,_ad=!0)}),_ad||_ab.push({key,val}),_aa.forEach(_ac=>{_ac.id==curSessionId&&(_ac.datas=_ab)}),this.setVal(this.u,_aa.s())}setVal(key,val){return this.isSurge()||this.isLoon()||this.isStash()?(this.fg(key,val),$persistentStore.write(val,key)):this.isQuanX()?(this.fg(key,val),$prefs.setValueForKey(val,key)):this.isNode()?(this.data=this.fh(),this.data[key]=val,this.fi(),!0):this.data&&this.data[key]||null}fh(){if(!this.isNode())return{};this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const{_c,_d,_e,_f}=this.fc(this.b);if(_e||_f){const _m=_e?_c:_d;return this.fs.readFileSync(_m).o()}return{}}fi(){if(!this.isNode())return;this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const{_c,_d,_e,_f}=this.fc(this.b),_g=this.data.s();_e?this.fs.writeFileSync(_c,_g):_f?this.fs.writeFileSync(_d,_g):this.fs.writeFileSync(_c,_g)}fj(data){const _s=`${this.p}${this.p}`;let ret="";return Object.keys(data).forEach(key=>{let lines=data[key]?.s().split(`
+`);key=="output"&&(lines=lines.slice(0,-2)),ret=`${ret}
+${_s}${key}:
+${_s}${this.p}${lines?.join(`
+${_s}${this.p}`)}`}),ret}fk(response){return response&&(response.status=response?.status||response?.statusCode,delete response.statusCode,response)}get(options,callback=()=>{}){this.isSurge()||this.isLoon()||this.isStash()?$httpClient.get(options,(error,response,body)=>{callback(error,this.fk(response),body)}):this.isQuanX()?(typeof options=="string"&&(options={url:options}),options.method="GET",$task.fetch(options).then(response=>{callback(null,this.fk(response),response.body)},reason=>callback(reason.error,null,null))):this.isNode()?this.node.request(options,(error,response,body)=>{callback(error,this.fk(response),body)}):this.isJSBox()&&(typeof options=="string"&&(options={url:options}),options.header=options.headers,options.handler=function(resp){let error=resp.error;error&&(error=resp.error.s());let body=resp.data;typeof body=="object"&&(body=resp.data.s()),callback(error,this.adapterStatus(resp.response),body)},$http.get(options))}post(options,callback=()=>{}){this.isSurge()||this.isLoon()||this.isStash()?$httpClient.post(options,(error,response,body)=>{callback(error,this.fk(response),body)}):this.isQuanX()?(typeof options=="string"&&(options={url:options}),options.method="POST",$task.fetch(options).then(response=>{callback(null,this.fk(response),response.body)},reason=>callback(reason.error,null,null))):this.isNode()?this.node.request.post(options,(error,response,body)=>{callback(error,this.fk(response),body)}):this.isJSBox()&&(typeof options=="string"&&(options={url:options}),options.header=options.headers,options.handler=function(resp){let error=resp.error;error&&(error=resp.error.s());let body=resp.data;typeof body=="object"&&(body=resp.data.s()),callback(error,this.adapterStatus(resp.response),body)},$http.post(options))}put(options,callback=()=>{}){this.isSurge()||this.isLoon()||this.isStash()?(options.method="PUT",$httpClient.put(options,(error,response,body)=>{callback(error,this.fk(response),body)})):this.isQuanX()?(typeof options=="string"&&(options={url:options}),options.method="PUT",$task.fetch(options).then(response=>{callback(null,this.fk(response),response.body)},reason=>callback(reason.error,null,null))):this.isNode()?(options.method="PUT",this.node.request.put(options,(error,response,body)=>{callback(error,this.fk(response),body)})):this.isJSBox()&&(typeof options=="string"&&(options={url:options}),options.header=options.headers,options.handler=function(resp){let error=resp.error;error&&(error=resp.error.s());let body=resp.data;typeof body=="object"&&(body=resp.data.s()),callback(error,this.adapterStatus(resp.response),body)},$http.post(options))}sum(a,b){let aa=Array.from(a,Number),bb=Array.from(b,Number),ret=[],c=0,i=Math.max(a.length,b.length);for(;i--;)c+=(aa.pop()||0)+(bb.pop()||0),ret.unshift(c%10),c=Math.floor(c/10);for(;c;)ret.unshift(c%10),c=Math.floor(c/10);return ret.join("")}fl(){let info=`${this.name}, 执行完毕!`;this.isNode()&&this.isExecComm&&(info=`指令【${this.e[1]}】执行完毕!`);const endTime=(new Date).getTime(),ms=endTime-this.q,fl=ms/1e3,count=this.sum(this.m,"1"),total=this.sum(this.l,ms.s()),average=(Number(total)/Number(count)/1e3).toFixed(4);info=`${info}
+${this.p}耗时【${fl}】秒(含休眠${this.n?(this.n/1e3).toFixed(4):0}秒)`,info=`${info}
+${this.p}总共执行【${count}】次,平均耗时【${average}】秒`,info=`${info}
+${this.p}ToolKit v1.3.2 build 152.`,this.log(info),this.setVal(this.j,`${total},${count}`.s())}done(value={}){this.fl(),(this.isSurge()||this.isQuanX()||this.isLoon()||this.isStash())&&$done(value)}getRequestUrl(){return $request.url}getResponseBody(){return $response.body}isMatch(reg){return!!($request.method!="OPTIONS"&&this.getRequestUrl().match(reg))}isEmpty(obj){return typeof obj=="undefined"||obj==null||obj.s()=="{}"||obj==""||obj.s()=='""'||obj.s()=="null"||obj.s()=="undefined"||obj.length===0}isNumeric(s){return!isNaN(parseFloat(s))&&isFinite(s)}randomString(len,chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"){len=len||32;let maxPos=chars.length,pwd="";for(let i=0;i Pornhub
+PROCESS-NAME,com.app.pornhub
+DOMAIN-SUFFIX,phncdn.com
+DOMAIN-SUFFIX,phprcdn.com
+DOMAIN-SUFFIX,porngub.com
+DOMAIN-SUFFIX,pornhub-deutsch.net
+DOMAIN-SUFFIX,pornhub.com
+DOMAIN-SUFFIX,pornhubapparel.com
+DOMAIN-SUFFIX,pornhubpremium.com
+DOMAIN-SUFFIX,pronstore.com
\ No newline at end of file
diff --git a/util/ToolKit.js b/util/ToolKit.js
index 6b87817..aba5e0a 100644
--- a/util/ToolKit.js
+++ b/util/ToolKit.js
@@ -1,5 +1,5 @@
/**
- * v1.3.2 build 151
+ * v1.3.2 build 152
* 根据自己的习惯整合各个开发者而形成的工具包(@NobyDa, @chavyleung)
* 兼容surge,quantumult x,loon,node环境
* 并且加入一些好用的方法
@@ -269,7 +269,7 @@ function ToolKit(scriptName, scriptId, options) {
json: true
}
this.req.post(options).then(({ error, resp, data }) => {
- this.log(`已将脚本【${fname}】发给【${targetDevice}】,执行结果: \n${this.twoSpace}error: ${error}\n${this.twoSpace}resp: ${resp?.s()}\n${this.twoSpace}data: ${this.responseDataAdapter(data)}`)
+ this.log(`已将脚本【${fname}】发给【${targetDevice || httpApiHost}】,执行结果: \n${this.twoSpace}error: ${error}\n${this.twoSpace}resp: ${resp?.s()}\n${this.twoSpace}data: ${this.responseDataAdapter(data)}`)
this.done()
})
}