Skip to content

Commit cc6e508

Browse files
committed
实现Box上传gist的工具函数
1 parent 7e6823c commit cc6e508

1 file changed

Lines changed: 104 additions & 0 deletions

File tree

‎box/chavy.boxjs.js‎

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -505,6 +505,104 @@ async function apiRunScript() {
505505
* 工具类函数
506506
* ===================================
507507
*/
508+
// gist备份工具
509+
function GistBox(token) {
510+
const BOX_BACKUP_KEY = "BoxJs Gist";
511+
const $http = HTTP("https://api.github.com", {
512+
headers: {
513+
Authorization: `token ${token}`,
514+
"User-Agent":
515+
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.141 Safari/537.36",
516+
},
517+
events: {
518+
onResponse: (resp) => {
519+
if (String(resp.statusCode).startsWith("4")) {
520+
return Promise.reject(`ERROR: ${JSON.parse(resp.body).message}`);
521+
} else {
522+
return resp;
523+
}
524+
},
525+
},
526+
});
527+
const genFileName = (timestamp) => `boxjs.bak.${timestamp}.json`;
528+
const genTimestamp = (fname) => fname.match(/boxjs\.bak\.(\d+)\.json/)[1];
529+
530+
return new (class {
531+
async findDatabase() {
532+
return $http.get("/gists").then((response) => {
533+
const gists = JSON.parse(response.body);
534+
for (let g of gists) {
535+
if (g.description === BOX_BACKUP_KEY) {
536+
return g.id;
537+
}
538+
}
539+
return -1;
540+
});
541+
}
542+
543+
async createDatabase(backups) {
544+
if (!(backups instanceof Array)) backups = [backups];
545+
const files = {};
546+
backups.forEach((b) => {
547+
files[genFileName(b.time)] = {
548+
content: b.content,
549+
};
550+
});
551+
return $http
552+
.post({
553+
url: "/gists",
554+
body: JSON.stringify({
555+
description: BOX_BACKUP_KEY,
556+
public: false,
557+
files,
558+
}),
559+
})
560+
.then((resp) => {
561+
return JSON.parse(resp.body).id;
562+
});
563+
}
564+
565+
async deleteDatabase(id) {
566+
return $http.delete(`/gists/${id}`);
567+
}
568+
569+
async getBackups(id) {
570+
const gist = await $http
571+
.get(`/gists/${id}`)
572+
.then((resp) => JSON.parse(resp.body));
573+
const { files } = gist;
574+
const backups = [];
575+
for (let name of Object.keys(files)) {
576+
backups.push({
577+
time: genTimestamp(name),
578+
url: files[name].raw_url,
579+
});
580+
}
581+
return backups;
582+
}
583+
584+
async addBackups(id, backups) {
585+
if (!(backups instanceof Array)) backups = [backups];
586+
const files = {};
587+
backups.forEach((b) => (files[genFileName(b.time)] = {content: b.content}));
588+
return this.updateBackups(id, files);
589+
}
590+
591+
async deleteBackups(id, timestamps) {
592+
if (!(timestamps instanceof Array)) timestamps = [timestamps];
593+
const files = {};
594+
timestamps.forEach((t) => (files[genFileName(t)] = {}));
595+
return this.updateBackups(id, files);
596+
}
597+
598+
async updateBackups(id, files) {
599+
return $http.patch({
600+
url: `/gists/${id}`,
601+
body: JSON.stringify({ files }),
602+
});
603+
}
604+
})();
605+
}
508606

509607
function reloadAppSubCache(url) {
510608
return $.http.get(url).then((resp) => {
@@ -633,3 +731,9 @@ function doneApi() {
633731

634732
// prettier-ignore
635733
function Env(t,s){class e{constructor(t){this.env=t}send(t,s="GET"){t="string"==typeof t?{url:t}:t;let e=this.get;return"POST"===s&&(e=this.post),new Promise((s,i)=>{e.call(this,t,(t,e,o)=>{t?i(t):s(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,s){this.name=t,this.http=new e(this),this.data=null,this.dataFile="box.dat",this.logs=[],this.isMute=!1,this.logSeparator="\n",this.startTime=(new Date).getTime(),Object.assign(this,s),this.log("",`\ud83d\udd14${this.name}, \u5f00\u59cb!`)}isNode(){return"undefined"!=typeof module&&!!module.exports}isQuanX(){return"undefined"!=typeof $task}isSurge(){return"undefined"!=typeof $httpClient&&"undefined"==typeof $loon}isLoon(){return"undefined"!=typeof $loon}toObj(t,s=null){try{return JSON.parse(t)}catch{return s}}toStr(t,s=null){try{return JSON.stringify(t)}catch{return s}}getjson(t,s){let e=s;const i=this.getdata(t);if(i)try{e=JSON.parse(this.getdata(t))}catch{}return e}setjson(t,s){try{return this.setdata(JSON.stringify(t),s)}catch{return!1}}getScript(t){return new Promise(s=>{this.get({url:t},(t,e,i)=>s(i))})}runScript(t,s){return new Promise(e=>{let i=this.getdata("@chavy_boxjs_userCfgs.httpapi");i=i?i.replace(/\n/g,"").trim():i;let o=this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout");o=o?1*o:20,o=s&&s.timeout?s.timeout:o;const[h,a]=i.split("@"),r={url:`http://${a}/v1/scripting/evaluate`,body:{script_text:t,mock_type:"cron",timeout:o},headers:{"X-Key":h,Accept:"*/*"}};this.post(r,(t,s,i)=>e(i))}).catch(t=>this.logErr(t))}loaddata(){if(!this.isNode())return{};{this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(this.dataFile),s=this.path.resolve(process.cwd(),this.dataFile),e=this.fs.existsSync(t),i=!e&&this.fs.existsSync(s);if(!e&&!i)return{};{const i=e?t:s;try{return JSON.parse(this.fs.readFileSync(i))}catch(t){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),s=this.path.resolve(process.cwd(),this.dataFile),e=this.fs.existsSync(t),i=!e&&this.fs.existsSync(s),o=JSON.stringify(this.data);e?this.fs.writeFileSync(t,o):i?this.fs.writeFileSync(s,o):this.fs.writeFileSync(t,o)}}lodash_get(t,s,e){const i=s.replace(/\[(\d+)\]/g,".$1").split(".");let o=t;for(const t of i)if(o=Object(o)[t],void 0===o)return e;return o}lodash_set(t,s,e){return Object(t)!==t?t:(Array.isArray(s)||(s=s.toString().match(/[^.[\]]+/g)||[]),s.slice(0,-1).reduce((t,e,i)=>Object(t[e])===t[e]?t[e]:t[e]=Math.abs(s[i+1])>>0==+s[i+1]?[]:{},t)[s[s.length-1]]=e,t)}getdata(t){let s=this.getval(t);if(/^@/.test(t)){const[,e,i]=/^@(.*?)\.(.*?)$/.exec(t),o=e?this.getval(e):"";if(o)try{const t=JSON.parse(o);s=t?this.lodash_get(t,i,""):s}catch(t){s=""}}return s}setdata(t,s){let e=!1;if(/^@/.test(s)){const[,i,o]=/^@(.*?)\.(.*?)$/.exec(s),h=this.getval(i),a=i?"null"===h?null:h||"{}":"{}";try{const s=JSON.parse(a);this.lodash_set(s,o,t),e=this.setval(JSON.stringify(s),i)}catch(s){const h={};this.lodash_set(h,o,t),e=this.setval(JSON.stringify(h),i)}}else e=this.setval(t,s);return e}getval(t){return this.isSurge()||this.isLoon()?$persistentStore.read(t):this.isQuanX()?$prefs.valueForKey(t):this.isNode()?(this.data=this.loaddata(),this.data[t]):this.data&&this.data[t]||null}setval(t,s){return this.isSurge()||this.isLoon()?$persistentStore.write(t,s):this.isQuanX()?$prefs.setValueForKey(t,s):this.isNode()?(this.data=this.loaddata(),this.data[s]=t,this.writedata(),!0):this.data&&this.data[s]||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,t&&(t.headers=t.headers?t.headers:{},void 0===t.headers.Cookie&&void 0===t.cookieJar&&(t.cookieJar=this.ckjar))}get(t,s=(()=>{})){t.headers&&(delete t.headers["Content-Type"],delete t.headers["Content-Length"]),this.isSurge()||this.isLoon()?$httpClient.get(t,(t,e,i)=>{!t&&e&&(e.body=i,e.statusCode=e.status),s(t,e,i)}):this.isQuanX()?$task.fetch(t).then(t=>{const{statusCode:e,statusCode:i,headers:o,body:h}=t;s(null,{status:e,statusCode:i,headers:o,body:h},h)},t=>s(t)):this.isNode()&&(this.initGotEnv(t),this.got(t).on("redirect",(t,s)=>{try{const e=t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString();this.ckjar.setCookieSync(e,null),s.cookieJar=this.ckjar}catch(t){this.logErr(t)}}).then(t=>{const{statusCode:e,statusCode:i,headers:o,body:h}=t;s(null,{status:e,statusCode:i,headers:o,body:h},h)},t=>s(t)))}post(t,s=(()=>{})){if(t.body&&t.headers&&!t.headers["Content-Type"]&&(t.headers["Content-Type"]="application/x-www-form-urlencoded"),t.headers&&delete t.headers["Content-Length"],this.isSurge()||this.isLoon())$httpClient.post(t,(t,e,i)=>{!t&&e&&(e.body=i,e.statusCode=e.status),s(t,e,i)});else if(this.isQuanX())t.method="POST",$task.fetch(t).then(t=>{const{statusCode:e,statusCode:i,headers:o,body:h}=t;s(null,{status:e,statusCode:i,headers:o,body:h},h)},t=>s(t));else if(this.isNode()){this.initGotEnv(t);const{url:e,...i}=t;this.got.post(e,i).then(t=>{const{statusCode:e,statusCode:i,headers:o,body:h}=t;s(null,{status:e,statusCode:i,headers:o,body:h},h)},t=>s(t))}}time(t){let s={"M+":(new Date).getMonth()+1,"d+":(new Date).getDate(),"H+":(new Date).getHours(),"m+":(new Date).getMinutes(),"s+":(new Date).getSeconds(),"q+":Math.floor(((new Date).getMonth()+3)/3),S:(new Date).getMilliseconds()};/(y+)/.test(t)&&(t=t.replace(RegExp.$1,((new Date).getFullYear()+"").substr(4-RegExp.$1.length)));for(let e in s)new RegExp("("+e+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?s[e]:("00"+s[e]).substr((""+s[e]).length)));return t}msg(s=t,e="",i="",o){const h=t=>!t||!this.isLoon()&&this.isSurge()?t:"string"==typeof t?this.isLoon()?t:this.isQuanX()?{"open-url":t}:void 0:"object"==typeof t&&(t["open-url"]||t["media-url"])?this.isLoon()?t["open-url"]:this.isQuanX()?t:void 0:void 0;this.isMute||(this.isSurge()||this.isLoon()?$notification.post(s,e,i,h(o)):this.isQuanX()&&$notify(s,e,i,h(o)));let a=["","==============\ud83d\udce3\u7cfb\u7edf\u901a\u77e5\ud83d\udce3=============="];a.push(s),e&&a.push(e),i&&a.push(i),console.log(a.join("\n")),this.logs=this.logs.concat(a)}log(...t){t.length>0&&(this.logs=[...this.logs,...t]),console.log(t.join(this.logSeparator))}logErr(t,s){const e=!this.isSurge()&&!this.isQuanX()&&!this.isLoon();e?this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t.stack):this.log("",`\u2757\ufe0f${this.name}, \u9519\u8bef!`,t)}wait(t){return new Promise(s=>setTimeout(s,t))}done(t={}){const s=(new Date).getTime(),e=(s-this.startTime)/1e3;this.log("",`\ud83d\udd14${this.name}, \u7ed3\u675f! \ud83d\udd5b ${e} \u79d2`),this.log(),(this.isSurge()||this.isQuanX()||this.isLoon())&&$done(t)}}(t,s)}
734+
735+
// HTTP utility function, original source: https://github.com/Peng-YM/QuanX/tree/master/Tools/OpenAPI/API.js
736+
737+
// prettier-ignore
738+
function ENV(){const e="undefined"!=typeof $task,n="undefined"!=typeof $loon,o="undefined"!=typeof $httpClient&&!this.isLoon,i="function"==typeof require&&"undefined"!=typeof $jsbox;return{isQX:e,isLoon:n,isSurge:o,isNode:"function"==typeof require&&!i,isJSBox:i}}
739+
function HTTP(e,t={}){const{isQX:o,isLoon:s,isSurge:n}=ENV();const r={};return["GET","POST","PUT","DELETE","HEAD","OPTIONS","PATCH"].forEach(u=>r[u.toLowerCase()]=(r=>(function(r,u){(u="string"==typeof u?{url:u}:u).url=e?e+u.url:u.url;const i=(u={...t,...u}).timeout,T={onRequest:()=>{},onResponse:e=>e,onTimeout:()=>{},...u.events};let a,c;T.onRequest(r,u),a=o?$task.fetch({method:r,...u}):new Promise((e,t)=>{(n||s?$httpClient:require("request"))[r.toLowerCase()](u,(o,s,n)=>{o?t(o):e({statusCode:s.status||s.statusCode,headers:s.headers,body:n})})});const m=i?new Promise((e,t)=>{c=setTimeout(()=>(T.onTimeout(),t(`${r} URL: ${u.url} exceeds the timeout ${i} ms`)),i)}):null;return(m?Promise.race([m,a]).then(e=>(clearTimeout(c),e)):a).then(e=>T.onResponse(e))})(u,r))),r}

0 commit comments

Comments
 (0)