MagicJS2.min.js 10 KB

1
  1. function MagicJS(e="MagicJS",t="INFO"){return new class{constructor(){if(this._startTime=Date.now(),this.version="2.2.3.7",this.scriptName=e,this.logLevels={DEBUG:5,INFO:4,NOTIFY:3,WARNING:2,ERROR:1,CRITICAL:0,NONE:-1},this.isLoon="undefined"!=typeof $loon,this.isQuanX="undefined"!=typeof $task,this.isJSBox="undefined"!=typeof $drive,this.isNode="undefined"!=typeof module&&!this.isJSBox,this.isSurge="undefined"!=typeof $httpClient&&!this.isLoon,this.node={request:void 0,fs:void 0,data:{}},this.iOSUserAgent="Mozilla/5.0 (iPhone; CPU iPhone OS 13_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.5 Mobile/15E148 Safari/604.1",this.pcUserAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36 Edg/84.0.522.59",this._logLevel="INFO",this.logLevel=t,this._barkUrl="",this._barkKey="",this.isNode){this.node.fs=require("fs"),this.node.request=require("request");try{this.node.fs.accessSync("./magic.json",this.node.fs.constants.R_OK|this.node.fs.constants.W_OK)}catch(e){this.node.fs.writeFileSync("./magic.json","{}",{encoding:"utf8"})}this.node.data=require("./magic.json")}else this.isJSBox&&($file.exists("drive://MagicJS")||$file.mkdir("drive://MagicJS"),$file.exists("drive://MagicJS/magic.json")||$file.write({data:$data({string:"{}"}),path:"drive://MagicJS/magic.json"}));this.log(e+", 开始执行!")}set barkUrl(e){try{var t=e.replace(/\/+$/g,"");this._barkUrl=/^https?:\/\/([^/]*)/.exec(t)[0]+"/push",this._barkKey=/\/([^\/]+)\/?$/.exec(t)[1]}catch(e){this.logDebug("Bark config error.")}}set logLevel(e){var t=this.read("magicjs_loglevel");this._logLevel=t||e.toUpperCase()}get logLevel(){return this._logLevel}get isRequest(){return"undefined"!=typeof $request&&"undefined"==typeof $response}get isResponse(){return"undefined"!=typeof $response}get isDebug(){return"DEBUG"===this.logLevel}get request(){return"undefined"!=typeof $request?$request:void 0}get response(){if("undefined"!=typeof $response)return $response.hasOwnProperty("status")&&($response.statusCode=$response.status),$response.hasOwnProperty("statusCode")&&($response.status=$response.statusCode),$response}get platform(){return this.isSurge?"Surge":this.isQuanX?"Quantumult X":this.isLoon?"Loon":this.isJSBox?"JSBox":this.isNode?"Node.js":"Unknown"}read(t,s=""){let i="";this.isSurge||this.isLoon?i=$persistentStore.read(t):this.isQuanX?i=$prefs.valueForKey(t):this.isNode?i=this.node.data:this.isJSBox&&(i=$file.read("drive://MagicJS/magic.json").string);try{this.isNode&&(i=i[t]),this.isJSBox&&(i=JSON.parse(i)[t]),s&&(i=(i="string"==typeof i?JSON.parse(i):i)&&"object"==typeof i?i[s]:null)}catch(e){this.logError(e),i=s?{}:null,this.del(t)}void 0===i&&(i=null);try{var e;i&&"string"==typeof i&&"object"==typeof(e=JSON.parse(i))&&e&&(i=e)}catch(e){}return this.logDebug(`READ DATA [${t}]${s?`[${s}]`:""}(${typeof i})`+"\n"+JSON.stringify(i)),i}write(t,e,s=""){let i=s?{}:"";if(s&&(this.isSurge||this.isLoon)?i=$persistentStore.read(t):s&&this.isQuanX?i=$prefs.valueForKey(t):this.isNode?i=this.node.data:this.isJSBox&&(i=JSON.parse($file.read("drive://MagicJS/magic.json").string)),s){try{i="object"==typeof(i="string"==typeof i?JSON.parse(i):i)&&i?i:{}}catch(e){this.logError(e),this.del(t),i={}}this.isJSBox||this.isNode?(i[t]&&"object"==typeof i[t]||(i[t]={}),i[t].hasOwnProperty(s)||(i[t][s]=null),void 0===e?delete i[t][s]:i[t][s]=e):void 0===e?delete i[s]:i[s]=e}else this.isNode||this.isJSBox?void 0===e?delete i[t]:i[t]=e:i=void 0===e?null:e;"object"==typeof i&&(i=JSON.stringify(i)),this.isSurge||this.isLoon?$persistentStore.write(i,t):this.isQuanX?$prefs.setValueForKey(i,t):this.isNode?this.node.fs.writeFileSync("./magic.json",i):this.isJSBox&&$file.write({data:$data({string:i}),path:"drive://MagicJS/magic.json"}),this.logDebug(`WRITE DATA [${t}]${s?`[${s}]`:""}(${typeof e})`+"\n"+JSON.stringify(e))}del(e,t=""){this.logDebug(`DELETE KEY [${e}]`+(t?`[${t}]`:"")),this.write(e,null,t)}notify(e=this.scriptName,t="",s="",i=""){i=(e=>{let t={};return"string"==typeof e?0<e.length&&(this.isLoon?t={openUrl:e}:this.isQuanX?t={"open-url":e}:this.isSurge&&(t={url:e})):"object"==typeof e&&(this.isLoon?(t.openUrl=e["open-url"]||"",t.mediaUrl=e["media-url"]||""):this.isQuanX?t=e["open-url"]||e["media-url"]?e:{}:this.isSurge&&(e=e["open-url"]||e.openUrl,t=e?{url:e}:{})),t})(i),1==arguments.length&&(e=this.scriptName,t="",s=arguments[0]),this.logNotify("\ntitle:"+e+"\nsubTitle:"+t+"\nbody:"+s+"\noptions:"+("object"==typeof i?JSON.stringify(i):i)),this.isSurge?$notification.post(e,t,s,i):this.isLoon?i?$notification.post(e,t,s,i):$notification.post(e,t,s):this.isQuanX?$notify(e,t,s,i):this.isJSBox&&$push.schedule({title:e,body:t?t+"\n"+s:s}),this._barkUrl&&this._barkKey&&this.notifyBark(e,t,s)}notifyDebug(e=this.scriptName,t="",s="",i=""){"DEBUG"===this.logLevel&&(1==arguments.length&&(e=this.scriptName,t="",s=arguments[0]),this.notify(e,t,s,i))}notifyBark(e=this.scriptName,t="",s="",i){e={url:this._barkUrl,headers:{"Content-Type":"application/json; charset=utf-8"},body:{title:e,body:t?t+"\n"+s:s,device_key:this._barkKey}};this.post(e,e=>{})}log(e,t="INFO"){this.logLevels[this._logLevel]<this.logLevels[t.toUpperCase()]||console.log(`██[${this.scriptName}][${t}]`+e+"\n")}logDebug(e){this.log(e,"DEBUG")}logInfo(e){this.log(e,"INFO")}logNotify(e){this.log(e,"NOTIFY")}logWarning(e){this.log(e,"WARNING")}logError(e){this.log(e,"ERROR")}logRetry(e){this.log(e,"RETRY")}adapterHttpOptions(e,t){let s="object"==typeof e?Object.assign({},e):{url:e,headers:{}},i=(s.hasOwnProperty("header")&&!s.hasOwnProperty("headers")&&(s.headers=s.header,delete s.header),s.headers&&"object"==typeof s.headers&&(s.headers["User-Agent"]||s.headers["user-agent"])||(s.headers&&"object"==typeof s.headers||(s.headers={}),this.isNode?s.headers["User-Agent"]=this.pcUserAgent:s.headers["User-Agent"]=this.iOSUserAgent),!1);return(i="object"==typeof s.opts&&(!0===s.opts.hints||!0===s.opts["Skip-Scripting"])||"object"==typeof s.headers&&!0===s.headers["X-Surge-Skip-Scripting"]?!0:i)||(this.isSurge?s.headers["X-Surge-Skip-Scripting"]=!1:this.isLoon?s.headers["X-Requested-With"]="XMLHttpRequest":this.isQuanX&&("object"!=typeof s.opts&&(s.opts={}),s.opts.hints=!1)),this.isSurge&&!i||delete s.headers["X-Surge-Skip-Scripting"],!this.isQuanX&&s.hasOwnProperty("opts")&&delete s.opts,this.isQuanX&&s.hasOwnProperty("opts")&&delete s.opts["Skip-Scripting"],"GET"===t&&!this.isNode&&s.body&&(e=Object.keys(s.body).map(e=>void 0===s.body?"":encodeURIComponent(e)+"="+encodeURIComponent(s.body[e])).join("&"),s.url.indexOf("?")<0&&(s.url+="?"),s.url.lastIndexOf("&")+1!=s.url.length&&s.url.lastIndexOf("?")+1!=s.url.length&&(s.url+="&"),s.url+=e,delete s.body),this.isQuanX?(s.hasOwnProperty("body")&&"string"!=typeof s.body&&(s.body=JSON.stringify(s.body)),s.method=t):this.isNode?(delete s.headers["Accept-Encoding"],"object"==typeof s.body&&("GET"===t?(s.qs=s.body,delete s.body):"POST"===t&&(s.json=!0,s.body=s.body))):this.isJSBox&&(s.header=s.headers,delete s.headers),s}adapterHttpResponse(e){let t={body:e.body,headers:e.headers,json:()=>JSON.parse(t.body)};return e.hasOwnProperty("statusCode")&&e.statusCode&&(t.status=e.statusCode),t}get(e,i){e=this.adapterHttpOptions(e,"GET");this.logDebug("HTTP GET: "+JSON.stringify(e)),this.isSurge||this.isLoon?$httpClient.get(e,i):this.isQuanX?$task.fetch(e).then(e=>{e.status=e.statusCode,i(null,e,e.body)},e=>i(e.error,null,null)):this.isNode?this.node.request.get(e,(e,t,s)=>{t=this.adapterHttpResponse(t),i(e,t,s)}):this.isJSBox&&(e.handler=e=>{var t=e.error?JSON.stringify(e.error):void 0,s="object"==typeof e.data?JSON.stringify(e.data):e.data;i(t,e.response,s)},$http.get(e))}getPromise(e){return new Promise((s,i)=>{magicJS.get(e,(e,t)=>{e?i(e):s(t)})})}post(e,i){var t,e=this.adapterHttpOptions(e,"POST");this.logDebug("HTTP POST: "+JSON.stringify(e)),this.isSurge||this.isLoon?$httpClient.post(e,i):this.isQuanX?$task.fetch(e).then(e=>{e.status=e.statusCode,i(null,e,e.body)},e=>{i(e.error,null,null)}):this.isNode?((t=this.node.request.post(e,i)).status=t.statusCode,delete t.statusCode):this.isJSBox&&(e.handler=e=>{var t=e.error?JSON.stringify(e.error):void 0,s="object"==typeof e.data?JSON.stringify(e.data):e.data;i(t,e.response,s)},$http.post(e,{}))}costTime(){var e=this.scriptName+"执行完毕!",t=(this._endTime=(new Date).getTime(),this._endTime-this._startTime);this.log(e+`耗时【${t/1e3}】秒`)}done(e={}){this.costTime(),"undefined"!=typeof $done&&$done(e)}isToday(e){var t;return null!=e&&(t=new Date,"string"==typeof e&&(e=new Date(e)),t.getFullYear()==e.getFullYear())&&t.getMonth()==e.getMonth()&&t.getDay()==e.getDay()}isNumber(e){return"NaN"!==parseFloat(e).toString()}attempt(e,t=null){return e.then(e=>[null,e]).catch(e=>(this.logError(e),[e,t]))}retry(r,n=5,a=0,h=null){return(...e)=>new Promise((s,i)=>{function o(...t){Promise.resolve().then(()=>r.apply(this,t)).then(e=>{"function"==typeof h?Promise.resolve().then(()=>h(e)).then(()=>{s(e)}).catch(e=>{1<=n?0<a?setTimeout(()=>o.apply(this,t),a):o.apply(this,t):i(e),n--}):s(e)}).catch(e=>{this.logRetry(e),1<=n&&0<a?setTimeout(()=>o.apply(this,t),a):1<=n?o.apply(this,t):i(e),n--})}o.apply(this,e)})}formatTime(e,t="yyyy-MM-dd hh:mm:ss"){var s,i={"M+":e.getMonth()+1,"d+":e.getDate(),"h+":e.getHours(),"m+":e.getMinutes(),"s+":e.getSeconds(),"q+":Math.floor((e.getMonth()+3)/3),S:e.getMilliseconds()};for(s in/(y+)/.test(t)&&(t=t.replace(RegExp.$1,(e.getFullYear()+"").substr(4-RegExp.$1.length))),i)new RegExp("("+s+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?i[s]:("00"+i[s]).substr((""+i[s]).length)));return t}now(){return this.formatTime(new Date,"yyyy-MM-dd hh:mm:ss")}today(){return this.formatTime(new Date,"yyyy-MM-dd")}sleep(t){return new Promise(e=>setTimeout(e,t))}objToQueryStr(t,s){let i="";for(const o in t){let e=t[o];null!=e&&""!==e&&("object"==typeof e?e=JSON.stringify(e):s&&(e=encodeURIComponent(e)),i+=`${o}=${e}&`)}return i=i.substring(0,i.length-1)}parseQueryStr(e){var t={},s=(e=-1<e.indexOf("?")?e.split("?")[1]:e).split("&");for(let e=0;e<s.length;e++){var i=s[e].split("=");t[i[0]]=i[1]}return t}deepClone(e,t){for(var s in t=t||{},e)"object"==typeof e[s]?(t[s]=e[s].constructor===Array?[]:{},this.deepClone(e[s],t[s])):t[s]=e[s];return t}convertToObject(t){if("string"!=typeof t)return t instanceof Array||null==t||t!=t||"boolean"==typeof t?{}:t;{let e={};try{var s=typeof(e=JSON.parse(t));("object"!=s||e instanceof Array||"boolean"==s||null===e)&&(e={})}catch{}return e}}}(e)}