-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathEnv.min.js
1 lines (1 loc) · 9.8 KB
/
Env.min.js
1
function Env(i,t){class s{constructor(t){this.env=t}send(t,e="GET"){t=typeof t==="string"?{url:t}:t;let s=this.get;if(e==="POST"){s=this.post}return new Promise((r,a)=>{s.call(this,t,(t,e,s)=>{if(t)a(t);else r(e)})})}get(t){return this.send.call(this.env,t)}post(t){return this.send.call(this.env,t,"POST")}}return new class{constructor(t,e){this.name=t;this.http=new s(this);this.data=null;this.dataFile="box.dat";this.logs=[];this.isMute=false;this.isNeedRewrite=false;this.logSeparator="\n";this.encoding="utf-8";this.startTime=(new Date).getTime();Object.assign(this,e);this.log("",`🔔${this.name}, 开始!`)}getEnv(){if("undefined"!==typeof $environment&&$environment["surge-version"])return"Surge";if("undefined"!==typeof $environment&&$environment["stash-version"])return"Stash";if("undefined"!==typeof module&&!!module.exports)return"Node.js";if("undefined"!==typeof $task)return"Quantumult X";if("undefined"!==typeof $loon)return"Loon";if("undefined"!==typeof $rocket)return"Shadowrocket"}isNode(){return"Node.js"===this.getEnv()}isQuanX(){return"Quantumult X"===this.getEnv()}isSurge(){return"Surge"===this.getEnv()}isLoon(){return"Loon"===this.getEnv()}isShadowrocket(){return"Shadowrocket"===this.getEnv()}isStash(){return"Stash"===this.getEnv()}toObj(t,e=null){try{return JSON.parse(t)}catch{return e}}toStr(t,e=null){try{return JSON.stringify(t)}catch{return e}}getjson(t,e){let s=e;const r=this.getdata(t);if(r){try{s=JSON.parse(this.getdata(t))}catch{}}return s}setjson(t,e){try{return this.setdata(JSON.stringify(t),e)}catch{return false}}getScript(t){return new Promise(r=>{this.get({url:t},(t,e,s)=>r(s))})}runScript(o,n){return new Promise(r=>{let t=this.getdata("@chavy_boxjs_userCfgs.httpapi");t=t?t.replace(/\n/g,"").trim():t;let e=this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout");e=e?e*1:20;e=n&&n.timeout?n.timeout:e;const[s,a]=t.split("@");const i={url:`http://${a}/v1/scripting/evaluate`,body:{script_text:o,mock_type:"cron",timeout:e},headers:{"X-Key":s,Accept:"*/*"},timeout:e};this.post(i,(t,e,s)=>r(s))})["catch"](t=>this.logErr(t))}loaddata(){if(this.isNode()){this.fs=this.fs?this.fs:require("fs");this.path=this.path?this.path:require("path");const e=this.path.resolve(this.dataFile);const s=this.path.resolve(process.cwd(),this.dataFile);const r=this.fs.existsSync(e);const a=!r&&this.fs.existsSync(s);if(r||a){const i=r?e:s;try{return JSON.parse(this.fs.readFileSync(i))}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 e=this.path.resolve(process.cwd(),this.dataFile);const s=this.fs.existsSync(t);const r=!s&&this.fs.existsSync(e);const a=JSON.stringify(this.data);if(s){this.fs.writeFileSync(t,a)}else if(r){this.fs.writeFileSync(e,a)}else{this.fs.writeFileSync(t,a)}}}lodash_get(t,e,s=undefined){const r=e.replace(/\[(\d+)\]/g,".$1").split(".");let a=t;for(const i of r){a=Object(a)[i];if(a===undefined){return s}}return a}lodash_set(t,r,e){if(Object(t)!==t)return t;if(!Array.isArray(r))r=r.toString().match(/[^.[\]]+/g)||[];r.slice(0,-1).reduce((t,e,s)=>Object(t[e])===t[e]?t[e]:t[e]=Math.abs(r[s+1])>>0===+r[s+1]?[]:{},t)[r[r.length-1]]=e;return t}getdata(t){let e=this.getval(t);if(/^@/.test(t)){const[,r,a]=/^@(.*?)\.(.*?)$/.exec(t);const i=r?this.getval(r):"";if(i){try{const o=JSON.parse(i);e=o?this.lodash_get(o,a,""):e}catch(s){e=""}}}return e}setdata(t,e){let s=false;if(/^@/.test(e)){const[,a,i]=/^@(.*?)\.(.*?)$/.exec(e);const o=this.getval(a);const n=a?o==="null"?null:o||"{}":"{}";try{const h=JSON.parse(n);this.lodash_set(h,i,t);s=this.setval(JSON.stringify(h),a)}catch(r){const h={};this.lodash_set(h,i,t);s=this.setval(JSON.stringify(h),a)}}else{s=this.setval(t,e)}return s}getval(t){switch(this.getEnv()){case"Surge":case"Loon":case"Stash":case"Shadowrocket":return $persistentStore.read(t);case"Quantumult X":return $prefs.valueForKey(t);case"Node.js":this.data=this.loaddata();return this.data[t];default:return this.data&&this.data[t]||null}}setval(t,e){switch(this.getEnv()){case"Surge":case"Loon":case"Stash":case"Shadowrocket":return $persistentStore.write(t,e);case"Quantumult X":return $prefs.setValueForKey(t,e);case"Node.js":this.data=this.loaddata();this.data[e]=t;this.writedata();return true;default:return this.data&&this.data[e]||null}}initGotEnv(t){this.got=this.got?this.got:require("got");this.cktough=this.cktough?this.cktough:require("tough-cookie");this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar;if(t){t.headers=t.headers?t.headers:{};if(undefined===t.headers.Cookie&&undefined===t.cookieJar){t.cookieJar=this.ckjar}}}get(t,n=()=>{}){if(t.headers){delete t.headers["Content-Type"];delete t.headers["Content-Length"];delete t.headers["content-type"];delete t.headers["content-length"]}if(t.params){t.url+="?"+this.queryStr(t.params)}switch(this.getEnv()){case"Surge":case"Loon":case"Stash":case"Shadowrocket":default:if(this.isSurge()&&this.isNeedRewrite){t.headers=t.headers||{};Object.assign(t.headers,{"X-Surge-Skip-Scripting":false})}$httpClient.get(t,(t,e,s)=>{if(!t&&e){e.body=s;e.statusCode=e.status?e.status:e.statusCode;e.status=e.statusCode}n(t,e,s)});break;case"Quantumult X":if(this.isNeedRewrite){t.opts=t.opts||{};Object.assign(t.opts,{hints:false})}$task.fetch(t).then(t=>{const{statusCode:e,statusCode:s,headers:r,body:a,bodyBytes:i}=t;n(null,{status:e,statusCode:s,headers:r,body:a,bodyBytes:i},a,i)},t=>n(t&&t.error||"UndefinedError"));break;case"Node.js":let o=require("iconv-lite");this.initGotEnv(t);this.got(t).on("redirect",(t,e)=>{try{if(t.headers["set-cookie"]){const r=t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString();if(r){this.ckjar.setCookieSync(r,null)}e.cookieJar=this.ckjar}}catch(s){this.logErr(s)}}).then(t=>{const{statusCode:e,statusCode:s,headers:r,rawBody:a}=t;const i=o.decode(a,this.encoding);n(null,{status:e,statusCode:s,headers:r,rawBody:a,body:i},i)},t=>{const{message:e,response:s}=t;n(e,s,s&&o.decode(s.rawBody,this.encoding))});break}}post(t,n=()=>{}){const e=t.method?t.method.toLocaleLowerCase():"post";if(t.body&&t.headers&&!t.headers["Content-Type"]&&!t.headers["content-type"]){t.headers["content-type"]="application/x-www-form-urlencoded"}if(t.headers){delete t.headers["Content-Length"];delete t.headers["content-length"]}switch(this.getEnv()){case"Surge":case"Loon":case"Stash":case"Shadowrocket":default:if(this.isSurge()&&this.isNeedRewrite){t.headers=t.headers||{};Object.assign(t.headers,{"X-Surge-Skip-Scripting":false})}$httpClient[e](t,(t,e,s)=>{if(!t&&e){e.body=s;e.statusCode=e.status?e.status:e.statusCode;e.status=e.statusCode}n(t,e,s)});break;case"Quantumult X":t.method=e;if(this.isNeedRewrite){t.opts=t.opts||{};Object.assign(t.opts,{hints:false})}$task.fetch(t).then(t=>{const{statusCode:e,statusCode:s,headers:r,body:a,bodyBytes:i}=t;n(null,{status:e,statusCode:s,headers:r,body:a,bodyBytes:i},a,i)},t=>n(t&&t.error||"UndefinedError"));break;case"Node.js":let o=require("iconv-lite");this.initGotEnv(t);const{url:s,...r}=t;this.got[e](s,r).then(t=>{const{statusCode:e,statusCode:s,headers:r,rawBody:a}=t;const i=o.decode(a,this.encoding);n(null,{status:e,statusCode:s,headers:r,rawBody:a,body:i},i)},t=>{const{message:e,response:s}=t;n(e,s,s&&o.decode(s.rawBody,this.encoding))});break}}time(e,t=null){const s=t?new Date(t):new Date;let r={"M+":s.getMonth()+1,"d+":s.getDate(),"H+":s.getHours(),"m+":s.getMinutes(),"s+":s.getSeconds(),"q+":Math.floor((s.getMonth()+3)/3),S:s.getMilliseconds()};if(/(y+)/.test(e))e=e.replace(RegExp.$1,(s.getFullYear()+"").substr(4-RegExp.$1.length));for(let t in r)if(new RegExp("("+t+")").test(e))e=e.replace(RegExp.$1,RegExp.$1.length==1?r[t]:("00"+r[t]).substr((""+r[t]).length));return e}queryStr(e){let s="";for(const r in e){let t=e[r];if(t!=null&&t!==""){if(typeof t==="object"){t=JSON.stringify(t)}s+=`${r}=${t}&`}}s=s.substring(0,s.length-1);return s}msg(e=i,s="",r="",t){const a=r=>{switch(typeof r){case undefined:return r;case"string":switch(this.getEnv()){case"Surge":case"Stash":default:return{url:r};case"Loon":case"Shadowrocket":return r;case"Quantumult X":return{"open-url":r};case"Node.js":return{"open-url":r}}case"object":switch(this.getEnv()){case"Surge":case"Stash":case"Shadowrocket":default:{let t=r.url||r.openUrl||r["open-url"];return{url:t}}case"Loon":{let t=r.openUrl||r.url||r["open-url"];let e=r.mediaUrl||r["media-url"];return{openUrl:t,mediaUrl:e}}case"Quantumult X":{let t=r["open-url"]||r.url||r.openUrl;let e=r["media-url"]||r.mediaUrl;let s=r["update-pasteboard"]||r.updatePasteboard;return{"open-url":t,"media-url":e,"update-pasteboard":s}}case"Node.js":{let t=r.openUrl||r.url||r["open-url"];let e=r.mediaUrl||r["media-url"];let s=(t?`\n点击跳转: ${t}`:"")+(e?`\n多媒体: ${e}`:"");return{desc_:s}}}default:return undefined}};if(!this.isMute){switch(this.getEnv()){case"Surge":case"Loon":case"Stash":case"Shadowrocket":default:$notification.post(e,s,r,a(t));break;case"Quantumult X":$notify(e,s,r,a(t));break;case"Node.js":if(a(t)){console.log(a(t).desc_)}break}}if(!this.isMuteLog){let t=["","==============📣系统通知📣=============="];t.push(e);s?t.push(s):"";r?t.push(r):"";console.log(t.join("\n"));this.logs=this.logs.concat(t)}}log(...t){if(t.length>0){this.logs=[...this.logs,...t]}console.log(t.join(this.logSeparator))}logErr(t,e){switch(this.getEnv()){case"Surge":case"Loon":case"Stash":case"Shadowrocket":case"Quantumult X":default:this.log("",`❗️${this.name}, 错误!`,t);break;case"Node.js":this.log("",`❗️${this.name}, 错误!`,t.stack);break}}wait(e){return new Promise(t=>setTimeout(t,e))}done(t={}){const e=(new Date).getTime();const s=(e-this.startTime)/1e3;this.log("",`🔔${this.name}, 结束! 🕛 ${s} 秒`);this.log();switch(this.getEnv()){case"Surge":case"Loon":case"Stash":case"Shadowrocket":case"Quantumult X":default:$done(t);break;case"Node.js":if(typeof $context!=="undefined"){$context.headers=t.headers;$context.statusCode=t.statusCode;$context.body=t.body}}}}(i,t)}