From dedb1445dfd7d29656944e06d76feb83da988a89 Mon Sep 17 00:00:00 2001 From: troyeguo <13820674+troyeguo@users.noreply.github.com> Date: Sat, 31 Jan 2026 16:23:13 +0800 Subject: [PATCH] fix bug --- src/assets/lib/kookit-extra.min.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/assets/lib/kookit-extra.min.mjs b/src/assets/lib/kookit-extra.min.mjs index ebffdd1d..7fb34300 100644 --- a/src/assets/lib/kookit-extra.min.mjs +++ b/src/assets/lib/kookit-extra.min.mjs @@ -1 +1 @@ -import e from"axios";import t from"fs";import r from"path";import{promisify as i}from"util";import o from"stream";import{Client as s}from"basic-ftp";import{S3Client as n,ListObjectsV2Command as a,DeleteObjectCommand as d,PutObjectCommand as l,GetObjectCommand as c}from"@aws-sdk/client-s3";import{AuthType as h,createClient as u}from"webdav";import p from"ssh2-sftp-client";import f from"form-data";import{Storage as y}from"megajs";import g from"crypto";import m from"os";import{SSE as k}from"sse.js";import v from"electron-store";import T from"node-machine-id";function b(e,t,r,i){return new(r||(r=Promise))((function(o,s){function n(e){try{d(i.next(e))}catch(e){s(e)}}function a(e){try{d(i.throw(e))}catch(e){s(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(n,a)}d((i=i.apply(e,t||[])).next())}))}const F=e=>"json"===e?"application/json":["jpg","jpeg","png","gif","bmp"].includes(e)?"image/"+e:"zip"===e?"application/zip":"epub"===e?"application/epub+zip":"txt"===e?"text/plain":"pdf"===e?"application/pdf":"mobi"===e?"application/x-mobipocket-ebook":"azw3"===e||"azw"===e?"application/vnd.amazon.ebook":"cbz"===e?"application/x-cbz":"cbr"===e?"application/x-cbr":"cbt"===e?"application/x-cbt":"cb7"===e?"application/x-cb7":"fb2"===e?"application/x-fictionbook+xml":"html"===e?"text/html":"css"===e?"text/css":"js"===e?"application/javascript":"xml"===e?"application/xml":"xhtml"===e?"application/xhtml+xml":"opf"===e?"application/oebps-package+xml":"ncx"===e?"application/x-dtbncx+xml":"mp3"===e?"audio/mpeg":"wav"===e?"audio/wav":"ogg"===e?"audio/ogg":"mp4"===e?"video/mp4":"webm"===e?"video/webm":"avi"===e?"video/x-msvideo":"wmv"===e?"video/x-ms-wmv":"flv"===e?"video/x-flv":"m3u8"===e?"application/x-mpegURL":"ts"===e?"video/MP2T":"3gp"===e?"video/3gpp":"3g2"===e?"video/3gpp2":"db"===e?"application/x-sqlite3":void 0,w={_chars:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",encode(e){if("string"!=typeof e)throw new Error("Input must be a string");let t="",r=0;const i=this._stringToUtf8Bytes(e),o=i.length;for(;r>2,d=(3&e)<<4|s>>4,l=(15&s)<<2|n>>6,c=63&n;t+=this._chars.charAt(a),t+=this._chars.charAt(d),t+=r-2>=o?"=":this._chars.charAt(l),t+=r-1>=o?"=":this._chars.charAt(c)}return t},decode(e){if("string"!=typeof e)throw new Error("Input must be a string");for(e=e.replace(/[^A-Za-z0-9+/]/g,"");e.length%4!=0;)e+="=";const t=[];let r=0;const i=e.length;for(;r>4,d=(15&o)<<4|s>>2,l=(3&s)<<6|n;t.push(a),-1!==s&&t.push(d),-1!==n&&t.push(l)}return this._utf8BytesToString(t)},_stringToUtf8Bytes(e){const t=[];for(let r=0;r>6),t.push(128|63&i);else if(55296==(64512&i)&&r+1>18),t.push(128|e>>12&63),t.push(128|e>>6&63),t.push(128|63&e)}else t.push(239,191,189),r--}else t.push(224|i>>12),t.push(128|i>>6&63),t.push(128|63&i)}return t},_utf8BytesToString(e){let t="",r=0;for(;r65535){const r=e-65536;t+=String.fromCharCode(55296|r>>10),t+=String.fromCharCode(56320|1023&r)}else t+=String.fromCharCode(e)}else t+="�"}else t+="�"}return t},encodeURL(e){return this.encode(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")},decodeURL(e){for(e=e.replace(/-/g,"+").replace(/_/g,"/");e.length%4;)e+="=";return this.decode(e)}};class E{constructor(e){this.queue=[],this.runningTasks=0,this.totalTasks=0,this.completedTasks=0,this.hasFailedTasks=!1,this.downloadedSize=0,this.maxConcurrency=e}addTask(e){return b(this,void 0,void 0,(function*(){return this.totalTasks++,new Promise(((t,r)=>{if(this.hasFailedTasks)return void t(void 0);const i=()=>b(this,void 0,void 0,(function*(){try{this.runningTasks++;const r=yield e();return this.completedTasks++,t(r),r}catch(e){throw this.completedTasks++,r(e),e}finally{this.runningTasks--,this.runNext()}}));this.runningTasks0&&this.runningTasks=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let i=[],o=!0,s=null;for(;o;){let n;n=s?yield e.post("https://api.dropboxapi.com/2/files/list_folder/continue",{cursor:s},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}):yield e.post("https://api.dropboxapi.com/2/files/list_folder",{path:"/"+t,limit:2e3},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});const a=n.data.entries||[];i=i.concat(a),o=n.data.has_more,s=n.data.cursor}return[...new Set(i.map((e=>({name:e.name,size:e.size||0,type:e[".tag"],modified:e.client_modified}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();yield e.post("https://api.dropboxapi.com/2/files/delete_v2",{path:"/"+t},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});return!0}catch(e){return console.error("Error deleting file:",e),!1}}))}refreshToken(){return b(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>b(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"dropbox",refresh_token:e});return t.data.access_token?(this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,t.data.access_token):""}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e,t){return b(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"dropbox",redirect_uri:t,code:e})).data}))}getAuthUrl(e){return`https://www.dropbox.com/oauth2/authorize?response_type=code&token_access_type=offline&client_id=${O}&redirect_uri=${e}`}}const j=i(o.pipeline);class U extends D{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken(),n=t.createReadStream(r.join(this.storagePath,i));return yield e.post("https://content.dropboxapi.com/2/files/upload",n,{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/octet-stream","Dropbox-API-Arg":JSON.stringify({path:"/"+o,mode:"overwrite",autorename:!0,mute:!1})},maxContentLength:1/0,maxBodyLength:1/0}),!0}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=yield this.refreshToken(),n=t.createWriteStream(r.join(this.storagePath,o)),a=yield e({url:"https://content.dropboxapi.com/2/files/download",method:"GET",responseType:"stream",headers:{Authorization:`Bearer ${s}`,"Dropbox-API-Arg":JSON.stringify({path:"/"+i})},maxContentLength:1/0,maxBodyLength:1/0});let d=0;return a.data.on("data",(e=>{d+=e.length,this.taskQueue.setDownloadedSize(d)})),yield j(a.data,n),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class M{constructor(e,t){this.config=e,this.storagePath=t,this.taskQueue=new E(1),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=0){return b(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}getClient(){return b(this,void 0,void 0,(function*(){try{if(this.client&&!1===this.client.closed)return this.client;let{url:e,username:t,password:r,dir:i,ssl:o,port:n}=this.config;const a=new s(0);a.ftp.verbose=!0;const d=a.access({host:e,port:parseInt(n),user:t,password:r,secure:"1"===o}),l=new Promise(((e,t)=>{setTimeout((()=>t(new Error("FTP connection timeout"))),5e3)}));return yield Promise.race([d,l]),this.client=a,a}catch(e){throw console.error("Error connecting to FTP server:",e),this.client=null,e}}))}uploadFile(e,t){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{let{dir:i}=this.config;i=i&&"KoodoReader"===this.baseFolder?i:this.baseFolder;const o=yield this.getClient(),s=()=>b(this,void 0,void 0,(function*(){yield o.ensureDir(r.dirname(i+"/"+t)),yield o.cd("/"),yield o.uploadFrom(r.join(this.storagePath,e),i+"/"+t)}));try{return yield s(),!0}catch(e){return console.error(e),!1}}catch(e){return console.error("Error in uploadFile:",e),!1}}))))))}))}downloadFile(e,i){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{let{dir:o}=this.config;o=o&&"KoodoReader"===this.baseFolder?o:this.baseFolder;const s=yield this.getClient(),n=t.createWriteStream(r.join(this.storagePath,i)),a=()=>b(this,void 0,void 0,(function*(){s.trackProgress((e=>{this.taskQueue.setDownloadedSize(e.bytes||0)})),yield s.downloadTo(n,o+"/"+e),s.trackProgress()}));try{return yield a(),!0}catch(e){return console.error(e),!1}}catch(e){return console.error("Error in downloadFile:",e),!1}}))))))}))}listFiles(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.listFilesWithoutQueue(e)}))))))}))}listFilesWithoutQueue(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return b(this,void 0,void 0,(function*(){let{dir:t}=this.config;t=t&&"KoodoReader"===this.baseFolder?t:this.baseFolder;const r=yield this.getClient(),i=()=>b(this,void 0,void 0,(function*(){return yield r.list(t+"/"+e)}));try{return(yield i()).map((e=>({name:e.name,size:e.size||0,type:e.isFile?"file":"folder",modified:e.modifiedAt?e.modifiedAt.toISOString():""})))}catch(e){return console.error(e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(e){return b(this,void 0,void 0,(function*(){let{dir:t}=this.config;t=t&&"KoodoReader"===this.baseFolder?t:this.baseFolder;const r=yield this.getClient(),i=()=>b(this,void 0,void 0,(function*(){yield r.remove(t+"/"+e)}));try{return yield i(),!0}catch(e){return console.error(e),!1}}))}}class B{constructor(e,t){this.isExp=!1,this.baseUrl="https://graph.microsoft.com/v1.0/me/drive/special/approot",this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new E(3),this.isExp=this.config.isExp||!1,this.baseUrl=this.isExp?"https://graph.microsoft.com/v1.0/me/drive/root":"https://graph.microsoft.com/v1.0/me/drive/special/approot",void 0===this.config.baseFolder?this.baseFolder=this.isExp?"KoodoReader":"":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return b(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();for(t=this.baseFolder+"/"+t;t.startsWith("/");)t=t.substring(1);let i,o=[];if(""===t)i=`${this.baseUrl}/children`;else{const e=encodeURIComponent(t);i=`${this.baseUrl}:/${e}:/children`}for(;i;){const t=yield e.get(i,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});if(t.status>=300)break;const s=t.data.value||[];o=o.concat(s),i=t.data["@odata.nextLink"]||""}return[...new Set(o.map((e=>({name:e.name,size:e.size||0,type:e.folder?"folder":"file",modified:e.lastModifiedDateTime}))))]}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();for(t=this.baseFolder+"/"+t;t.startsWith("/");)t=t.substring(1);const i=yield e.delete(`${this.baseUrl}:/${t}`,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});return!(i.status>=300)||(console.error("Error deleting file:",i),!0)}catch(e){return console.error("Error occurred during file delete:",e),!1}}))}refreshToken(){return b(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>b(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"microsoft",refresh_token:e});return t.data.access_token?(this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,t.data.access_token):""}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e,t){return b(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"microsoft",redirect_uri:t,code:e})).data}))}getAuthUrl(e){return`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${L}&scope=${this.isExp?"files.readwrite.all":"files.readwrite.appfolder"} offline_access&response_type=code&redirect_uri=${e}`}}const W=209715200;class N extends B{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){var s;let n=null;try{const s=yield this.refreshToken();let a=this.baseFolder+"/"+o;for(;a.startsWith("/");)a=a.substring(1);const d=r.join(this.storagePath,i),l=yield this.getFileSize(d),c=a.split(".").pop(),h=(F(c||""),`${this.baseUrl}:/${a}:/createUploadSession`),u=(yield e.post(h,{item:{"@microsoft.graph.conflictBehavior":"replace"}},{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}})).data.uploadUrl;n=yield t.promises.open(d,"r");let p=0,f=Buffer.alloc(W);for(;pthis.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=yield this.refreshToken();let n=this.baseFolder+"/"+i;for(;n.startsWith("/");)n=n.substring(1);const a=`${this.baseUrl}:/${n}:/content`;let d=(yield fetch(a,{headers:{Authorization:"Bearer "+s},redirect:"manual"})).headers.get("location");if(d){const i=yield e.get(d,{responseType:"stream"});let s=0;const n=t.createWriteStream(r.join(this.storagePath,o));return i.data.on("data",(e=>{s+=e.length,this.taskQueue.setDownloadedSize(s)})),yield new Promise(((e,t)=>{i.data.pipe(n),n.on("finish",(()=>{e()})),n.on("error",t)})),!0}return!1}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}getFileSize(e){return b(this,void 0,void 0,(function*(){try{return(yield t.promises.stat(e)).size}catch(e){throw e}}))}}class q{constructor(e,t){this.isExp=!1,this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new E(3),this.isExp=this.config.isExp||!1,this.baseFolder="KoodoReader"}retryOperation(e,t=3){return b(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}getFileId(t,r){return b(this,void 0,void 0,(function*(){const i=yield this.refreshToken(),o=`https://www.googleapis.com/drive/v3/files?q=name='${t}'+and+'${r}'+in+parents&fields=files(id,name)`;try{const t=yield e.get(o,{headers:{Authorization:"Bearer "+i}});if(0===t.data.files.length)return"";const r=t.data.files;return r.length>0?r[0].id:null}catch(e){return console.error("Error occurred during file list retrieval:",e),""}}))}checkFolder(t){return b(this,void 0,void 0,(function*(){t=this.baseFolder+"/"+t;const r=yield this.refreshToken();if(""===t)return"root";const i=t.split("/").filter((e=>""!==e.trim()));let o="root";for(const t of i){let i=yield this.getFolderId(t,o);if(!i){const s={name:t,mimeType:"application/vnd.google-apps.folder",parents:[o]};try{i=(yield e.post("https://www.googleapis.com/drive/v3/files",s,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.id}catch(e){throw console.error(`Error occurred during folder creation for ${t}:`,e),e}}o=i}return o}))}getFolderId(t,r){return b(this,void 0,void 0,(function*(){const i=yield this.refreshToken(),o=`https://www.googleapis.com/drive/v3/files?q=name='${t=encodeURIComponent(t)}'+and+mimeType='application/vnd.google-apps.folder'+and+'${r}'+in+parents&fields=files(id,name)`;try{const t=(yield e.get(o,{headers:{Authorization:`Bearer ${i}`}})).data.files;return t.length>0?t[0].id:null}catch(e){throw console.error("Error occurred during fetching folder ID:",e),e}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let i=yield this.checkFolder(t),o=[],s="",n=!0;for(;n;){let t=`https://www.googleapis.com/drive/v3/files?q='${i}'+in+parents&fields=nextPageToken,files(id,name,size,mimeType)&pageSize=1000`;s&&(t+=`&pageToken=${s}`);const a=yield e.get(t,{headers:{Authorization:`Bearer ${r}`}}),d=a.data.files||[];o=o.concat(d),s=a.data.nextPageToken,n=!!s}return[...new Set(o.map((e=>({name:e.name,size:e.size||0,type:"application/vnd.google-apps.folder"===e.mimeType?"folder":"file",modified:e.modifiedTime}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQue(e)}))))))}))}deleteFileWithoutQue(t){return b(this,void 0,void 0,(function*(){const r=t.split("/")[1],i=yield this.checkFolder(t),o=yield this.refreshToken(),s=yield this.getFileId(r,i);if(""===s)return console.error("File not found:",r),!0;try{const t=yield e.delete(`https://www.googleapis.com/drive/v3/files/${s}`,{headers:{Authorization:`Bearer ${o}`}});return console.error("File deleted:",t),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}refreshToken(){return b(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>b(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"google",refresh_token:e});return t.data.access_token?(this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,t.data.access_token):""}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e,t){return b(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"google",redirect_uri:t,code:e})).data}))}getAuthUrl(e){return`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${e}&prompt=consent&response_type=code&client_id=${z}&scope=https://www.googleapis.com/auth/${this.isExp?"drive":"drive.file"}&access_type=offline`}}class K extends q{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken();let n=i.split("/").pop(),a=o.split(".").pop(),d=F(a||""),l=o.split("/").slice(0,-1).join("/"),c=yield this.checkFolder(l),h=yield this.getFileId(n||"",c);const u={mimeType:d,name:n,parents:[c]},p=h?`https://www.googleapis.com/upload/drive/v3/files/${h}?uploadType=resumable`:"https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",f=(yield e({method:h?"PATCH":"POST",url:p,data:h?null:JSON.stringify(u),headers:{Authorization:"Bearer "+s,"Content-Type":"application/json; charset=UTF-8"},maxContentLength:1/0,maxBodyLength:1/0})).headers.location;let y=yield this.getFileSize(r.join(this.storagePath,i));const g=t.createReadStream(r.join(this.storagePath,i));yield e.put(f,g,{headers:{Authorization:"Bearer "+s,"Content-Type":"application/zip","Content-Range":`bytes 0-${y-1}/${y}`},maxContentLength:1/0,maxBodyLength:1/0});return!0}catch(e){return console.error("Error occurred during upload:",e),!1}}))))))}))}downloadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=yield this.refreshToken();let n=i.split("/").pop(),a=i.split("/").slice(0,-1).join("/"),d=yield this.checkFolder(a),l=yield this.getFileId(n||"",d);if(!l)return console.error("File not found"),!0;const c=`https://www.googleapis.com/drive/v3/files/${l}?alt=media`;return new Promise((i=>{const n=t.createWriteStream(r.join(this.storagePath,o));e({url:c,method:"GET",responseType:"stream",headers:{Authorization:"Bearer "+s},maxContentLength:1/0,maxBodyLength:1/0}).then((e=>{let t=0;e.data.on("data",(e=>{t+=e.length,this.taskQueue.setDownloadedSize(t)})),e.data.pipe(n),n.on("finish",(()=>{i(!0)})),n.on("error",(()=>{i(!1)}))})).catch((e=>{console.error("Error downloading file:",e),i(!1)}))}))}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}getFileSize(e){return b(this,void 0,void 0,(function*(){try{return(yield t.promises.stat(e)).size}catch(e){throw e}}))}}class H{constructor(e){this.config=e,this.taskQueue=new E(5),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=0){return b(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}shouldUsePathStyle(e){try{const t=new URL(e),r=t.hostname,i=/^(\d{1,3}\.){3}\d{1,3}$/.test(r),o=""!==t.port;return!i&&o}catch(e){return!0}}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return b(this,void 0,void 0,(function*(){let{endpoint:t,region:r,bucketName:i,accessKeyId:o,secretAccessKey:s,dir:d}=this.config;d=d&&"KoodoReader"===this.baseFolder?d:this.baseFolder;let l=d+"/"+e;for(;l.startsWith("/");)l=l.substring(1);""===l||l.endsWith("/")||(l+="/");const c=new n({endpoint:t,region:r,credentials:{accessKeyId:o,secretAccessKey:s},forcePathStyle:this.shouldUsePathStyle(t)});try{let e,t=[],r=[],o=!0;for(;o;){const s=yield c.send(new a({Bucket:i,Prefix:l,Delimiter:"/",ContinuationToken:e}));s.Contents&&(t=t.concat(s.Contents)),s.CommonPrefixes&&(r=r.concat(s.CommonPrefixes)),e=s.NextContinuationToken,o=!!e}let s=[];return t.forEach((e=>{if(!e.Key.endsWith("/")){const t=e.Key.substring(l.length);t.includes("/")||s.push({name:t,size:e.Size||0,type:"file",modified:e.LastModified?e.LastModified.toISOString():""})}})),r.forEach((e=>{const t=e.Prefix.substring(l.length).replace(/\/$/,"");t&&s.push({name:t,size:0,type:"folder",modified:""})})),s}catch(e){return console.error(e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){let{endpoint:t,region:r,bucketName:i,accessKeyId:o,secretAccessKey:s,dir:a}=this.config;a=a&&"KoodoReader"===this.baseFolder?a:this.baseFolder;const l=new n({endpoint:t,region:r,credentials:{accessKeyId:o,secretAccessKey:s},forcePathStyle:this.shouldUsePathStyle(t)});let c=a+"/"+e;for(;c.startsWith("/");)c=c.substring(1);try{return yield l.send(new d({Bucket:i,Key:c})),!0}catch(e){return console.error(e),!1}}))}}class J extends H{constructor(e,t){super(e),this.storagePath=t}uploadFile(e,i){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){let{endpoint:o,region:s,bucketName:a,accessKeyId:d,secretAccessKey:c,dir:h}=this.config;const u=new n({endpoint:o,region:s,credentials:{accessKeyId:d,secretAccessKey:c},forcePathStyle:this.shouldUsePathStyle(o)});h=h&&"KoodoReader"===this.baseFolder?h:this.baseFolder;let p=h+"/"+i;for(;p.startsWith("/");)p=p.substring(1);try{let i=yield u.send(new l({Bucket:a,Key:p,Body:t.createReadStream(r.join(this.storagePath,e))}));return 200===i.$metadata.httpStatusCode||(console.error("Error uploading file:",i),!1)}catch(e){return console.error("Error: ",e),!1}}))))))}))}downloadFile(e,i){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);let{endpoint:o,region:s,bucketName:a,accessKeyId:d,secretAccessKey:l,dir:h}=this.config;h=h&&"KoodoReader"===this.baseFolder?h:this.baseFolder;const u=(e,t,r,i)=>new Promise(((o,s)=>b(this,void 0,void 0,(function*(){const s=yield e.send(new c({Bucket:t,Key:r}));let n=0;s.Body?(s.Body.on("data",(e=>{n+=e.length,this.taskQueue.setDownloadedSize(n)})),s.Body.pipe(i),i.on("finish",(e=>{e&&o(!1),o(!0)}))):o(!1)})))),p=()=>new Promise(((c,p)=>{const f=new n({region:s,endpoint:o,credentials:{accessKeyId:d,secretAccessKey:l},forcePathStyle:this.shouldUsePathStyle(o)});let y=t.createWriteStream(r.join(this.storagePath,i)),g=h+"/"+e;for(;g.startsWith("/");)g=g.substring(1);u(f,a,g,y).then((e=>{c(!0)})).catch((e=>{console.error(e),c(!1)}))}));try{return yield p()}catch(e){return console.error(e),!1}}))))))}))}}class V{constructor(e){let{username:t,password:r,url:i,dir:o,AuthType:s,createClient:n}=e;void 0===e.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=e.baseFolder,o=o&&"KoodoReader"===this.baseFolder?o:this.baseFolder,this.username=t,this.password=r,this.url=i,this.dir=o,this.taskQueue=new E(5),this.AuthType=s,this.createClient=n}getClient(){return b(this,void 0,void 0,(function*(){return this.webdavClient||(this.url=yield this.handleUrlRedirection(this.url),this.webdavClient=this.createClient(this.url,{authType:this.AuthType.Password,username:this.username,password:this.password})),this.webdavClient}))}handleUrlRedirection(t){return b(this,void 0,void 0,(function*(){try{const r=yield e.head(t,{maxRedirects:0,validateStatus:()=>!0});return r.request&&r.request.responseURL&&r.request.responseURL!==t?r.request.responseURL:r.status>=300&&r.status<400&&r.headers.location?r.headers.location:t}catch(e){return console.info("Error handling URL redirection:",e),t}}))}retryOperation(e,t=1){return b(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return b(this,void 0,void 0,(function*(){const t=yield this.getClient();try{return(yield t.getDirectoryContents(this.dir+"/"+e)).filter((t=>"."!==t.filename&&".."!==t.filename&&t.filename!==e)).map((e=>({name:e.basename,size:e.size||0,type:"directory"===e.type?"folder":"file",modified:e.lastmod})))}catch(r){return r.response&&404===r.response.status&&(yield t.createDirectory(this.dir+"/"+e)),console.error("Error listing files:",r),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){const t=yield this.getClient();try{return yield t.deleteFile(this.dir+"/"+e),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}ensureDirectoryExists(e){return b(this,void 0,void 0,(function*(){let t=yield this.getClient();try{const r=e.replace(/^\/+|\/+$/g,"").split("/").filter((e=>e.length>0));let i="";for(const e of r)i=i?`${i}/${e}`:e,(yield t.exists(`/${i}`))||(yield t.createDirectory(`/${i}`));return!0}catch(e){return console.error("Error ensuring directory exists:",e),!1}}))}}class Y extends V{constructor(e,t){super(Object.assign(Object.assign({},e),{AuthType:h,createClient:u})),this.storagePath=t}uploadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{let s=yield this.getClient();const n=s.exists(r.dirname(this.dir+"/"+o)),a=new Promise(((e,t)=>{setTimeout((()=>t(new Error("WebDAV exists check timeout"))),5e3)}));!1===(yield Promise.race([n,a]))&&(yield this.ensureDirectoryExists(r.dirname(this.dir+"/"+o)));let d=s.createWriteStream(this.dir+"/"+o);return t.createReadStream(r.join(this.storagePath,i)).pipe(d),new Promise(((n,a)=>{d.on("finish",(()=>{n(!0)})),d.on("error",(a=>b(this,void 0,void 0,(function*(){console.error("Error occurred during file upload:",a);try{let a=t.readFileSync(r.join(this.storagePath,i)),d=s.getFileUploadLink(this.dir+"/"+o);const l=new URL(d);l.search="",d=l.toString();const c=Buffer.from(this.username+":"+this.password,"binary").toString("base64");yield e.put(d,a,{headers:{Authorization:"Basic "+c},maxContentLength:1/0,maxBodyLength:1/0});n(!0)}catch(e){console.error("Error occurred during file upload:",e),n(!1)}}))))}))}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(e,i){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){if(this.taskQueue.setDownloadedSize(0),-1===e.indexOf("."))return new ArrayBuffer(0);try{let o=yield this.getClient();if(!1===(yield o.exists(this.dir+"/"+e)))return!0;let s=0,n=t.createWriteStream(r.join(this.storagePath,i)),a=o.createReadStream(this.dir+"/"+e);return a.on("data",(e=>{s+=e.length,this.taskQueue.setDownloadedSize(s)})),a.pipe(n),new Promise(((e,t)=>{n.on("finish",(()=>{e(!0)})),n.on("error",(t=>{e(!1)}))}))}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class X{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new E(3),void 0===this.config.baseFolder?this.baseFolder="/KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return b(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){var r,i;return b(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken();for(t=this.baseFolder+"/"+t;t.startsWith("/");)t=t.substring(1);let s=[],n=0;const a=1e3;let d=!0;for(;d;){const l=yield e.get("https://cloud-api.yandex.net/v1/disk/resources",{headers:{Authorization:`OAuth ${o}`,"Content-Type":"application/json"},params:{path:t?`/${t}`:"/",limit:a,offset:n,fields:"_embedded.items.name,_embedded.items.size,_embedded.items.type,_embedded.items.modified,_embedded.total"}}),c=(null===(r=l.data._embedded)||void 0===r?void 0:r.items)||[];s=s.concat(c);const h=(null===(i=l.data._embedded)||void 0===i?void 0:i.total)||0;n+=c.length,d=n({name:e.name,size:e.size||0,type:"file"===e.type?"file":"folder",modified:e.modified}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();for(t=this.baseFolder+"/"+t;t.startsWith("/");)t=t.substring(1);const i=yield e.delete("https://cloud-api.yandex.net/v1/disk/resources",{headers:{Authorization:`OAuth ${r}`,"Content-Type":"application/json"},params:{path:t?`/${t}`:"/",permanently:!1}});return 202===i.status||204===i.status}catch(e){return console.error("Error deleting file:",e),!1}}))}ensureDirectoryExists(t){var r,i;return b(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken(),s=t.split("/").filter((e=>e.length>0));let n="";for(const t of s){n+="/"+t;try{yield e.get("https://cloud-api.yandex.net/v1/disk/resources",{headers:{Authorization:`OAuth ${o}`,"Content-Type":"application/json"},params:{path:n}})}catch(t){if(404!==(null===(r=t.response)||void 0===r?void 0:r.status))return console.error("Error checking directory:",t),!1;try{yield e.put(`https://cloud-api.yandex.net/v1/disk/resources?path=${encodeURIComponent(n)}`,null,{headers:{Authorization:`OAuth ${o}`}})}catch(e){if(409!==(null===(i=e.response)||void 0===i?void 0:i.status))return console.error("Error creating directory:",e),!1}}}return!0}catch(e){return console.error("Error ensuring directory exists:",e),!1}}))}refreshToken(){return b(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>b(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"yandex",refresh_token:e});return t.data.access_token?(this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,t.data.access_token):""}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e,t){return b(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"yandex",redirect_uri:t,code:e})).data}))}getAuthUrl(e){return`https://oauth.yandex.com/authorize?response_type=code&client_id=${C}&redirect_uri=${e}&force_confirm=true`}}const G=i(o.pipeline);class Z extends X{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken();let n=this.baseFolder+"/"+o;for(;n.startsWith("/");)n=n.substring(1);const a=n.substring(0,n.lastIndexOf("/"));if(a){if(!(yield this.ensureDirectoryExists(a)))return console.error("Failed to create directory:",a),!1}const d=yield e.get("https://cloud-api.yandex.net/v1/disk/resources/upload",{headers:{Authorization:`OAuth ${s}`,"Content-Type":"application/json"},params:{path:`/${n}`,overwrite:!0}});if(200!==d.status)return console.error("Error getting upload URL:",d),!1;const l=d.data.href,c=t.createReadStream(r.join(this.storagePath,i));return yield e.put(l,c,{headers:{"Content-Type":"application/octet-stream"},maxContentLength:1/0,maxBodyLength:1/0}),!0}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);let s=this.baseFolder+"/"+i;for(;s.startsWith("/");)s=s.substring(1);try{const i=yield this.refreshToken(),n=yield e.get("https://cloud-api.yandex.net/v1/disk/resources/download",{headers:{Authorization:`OAuth ${i}`,"Content-Type":"application/json"},params:{path:`/${s}`}});if(200!==n.status)return console.error("Error getting download URL:",n),!1;const a=n.data.href,d=t.createWriteStream(r.join(this.storagePath,o)),l=yield e({url:a,method:"GET",responseType:"stream",maxContentLength:1/0,maxBodyLength:1/0});let c=0;return l.data.on("data",(e=>{c+=e.length,this.taskQueue.setDownloadedSize(c)})),yield G(l.data,d),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class ee{constructor(e,t){this.config=e,this.storagePath=t,this.taskQueue=new E(5),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=0){return b(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}getClient(){return b(this,void 0,void 0,(function*(){try{if(this.client)return this.client;let{url:e,username:t,password:r,dir:i,port:o}=this.config;const s=new p,n=s.connect({host:e||"",port:o||22,username:t||"",password:r||""}),a=new Promise(((e,t)=>{setTimeout((()=>t(new Error("SFTP connection timeout"))),5e3)}));return yield Promise.race([n,a]),this.client=s,s}catch(e){throw console.error("Error connecting to SFTP server:",e),this.client=null,e}}))}uploadFile(e,i){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{let{dir:o}=this.config;o=o&&"KoodoReader"===this.baseFolder?o:this.baseFolder;let s=yield this.getClient();const n=()=>new Promise(((n,a)=>b(this,void 0,void 0,(function*(){let a=t.createReadStream(r.join(this.storagePath,e)),d="/"+o+"/"+i,l="/"+o+"/"+r.dirname(i);(yield s.exists(l))||(yield s.mkdir(l,!0)),s.put(a,d).then((()=>{n(!0)})).catch((e=>{console.error(e.message),n(!1)}))}))));try{return yield n()}catch(e){return console.error(e),!1}}catch(e){return console.error("Error in uploadFile:",e),!1}}))))))}))}downloadFile(e,i){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{let{dir:o}=this.config;o=o&&"KoodoReader"===this.baseFolder?o:this.baseFolder;let s=yield this.getClient();const n=()=>new Promise(((n,a)=>b(this,void 0,void 0,(function*(){let a="/"+o+"/"+e,d=r.join(this.storagePath,i),l=t.createWriteStream(d);s.get(a,l).then((()=>{this.taskQueue.setDownloadedSize(l.bytesWritten||0),n(!0)})).catch((e=>{console.error(e.message),n(!1)}))}))));try{return yield n()}catch(e){return console.error(e),!1}}catch(e){return console.error("Error in downloadFile:",e),!1}}))))))}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return b(this,void 0,void 0,(function*(){let{dir:t}=this.config;t=t&&"KoodoReader"===this.baseFolder?t:this.baseFolder;let r=yield this.getClient();const i=()=>new Promise(((i,o)=>b(this,void 0,void 0,(function*(){let o="/"+t+"/"+e;(yield r.exists(o))||(yield r.mkdir(o,!0),i([])),r.list(o).then((e=>{i(e.map((e=>({name:e.name,size:e.size||0,type:"d"===e.type?"folder":"file",modified:e.modifyTime}))))})).catch((e=>b(this,void 0,void 0,(function*(){console.error(e.message,"list file error"),i([])}))))}))));try{return yield i()}catch(e){return console.error(e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){let{dir:t}=this.config;t=t&&"KoodoReader"===this.baseFolder?t:this.baseFolder;let r=yield this.getClient();try{return yield new Promise(((i,o)=>{let s="/"+t+"/"+e;r.delete(s).then((()=>{i(!0)})).catch((e=>{console.error(e.message),i(!1)}))}))}catch(e){return console.error(e),!1}}))}}class te{downloadFile(e,t){return b(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}uploadFile(e,t){return b(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}listFiles(e){return b(this,void 0,void 0,(function*(){return new Promise((e=>{e([])}))}))}authToken(e,t){return b(this,void 0,void 0,(function*(){return new Promise((e=>{e("")}))}))}getAuthUrl(){return""}}class re{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new E(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return b(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}getFolderIdByPath(t){return b(this,void 0,void 0,(function*(){if(""==t)return"0";const r=yield this.refreshToken(),i=t.split("/");let o="0";for(const t of i){const i=`https://api.box.com/2.0/folders/${o}/items?fields=id,name&type=folder&limit=1000`;try{const s=(yield e.get(i,{headers:{Authorization:`Bearer ${r}`}})).data.entries.find((e=>e.name===t&&"folder"===e.type));if(s)o=s.id;else{const i={name:t,parent:{id:o},type:"folder"};o=(yield e.post("https://api.box.com/2.0/folders",i,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.id}}catch(e){return console.error("Error occurred during folder creation:",e),""}}return o}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let i=this.baseFolder+"/"+t;for(;i.startsWith("/");)i=i.substring(1);let o=yield this.getFolderIdByPath(i),s=[],n=0,a=!0;const d=1e3;for(;a;){const t=yield e.get(`https://api.box.com/2.0/folders/${o}/items`,{params:{limit:d,offset:n},headers:{Authorization:`Bearer ${r}`}}),i=t.data.entries||[];s=s.concat(i),n+=i.length,a=i.length===d&&t.data.total_count>n}return[...new Set(s.map((e=>({name:e.name,size:e.size||0,type:e.type,modified:e.content_modified_at}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=t.substring(0,t.lastIndexOf("/")),o=t.substring(t.lastIndexOf("/")+1);let s=this.baseFolder+"/"+i;for(;s.startsWith("/");)s=s.substring(1);const n=yield this.getFolderIdByPath(s);if(!n)return!0;const a=`https://api.box.com/2.0/folders/${n}/items?fields=id,name&type=file&limit=1000`,d=(yield e.get(a,{headers:{Authorization:`Bearer ${r}`}})).data.entries.find((e=>e.name===o&&"file"===e.type));return!d||(yield e.delete(`https://api.box.com/2.0/files/${d.id}`,{headers:{Authorization:`Bearer ${r}`}}),!0)}catch(e){return console.error("Error deleting file:",e),!1}}))}refreshToken(){return b(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>b(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"boxnet",refresh_token:e});if(!t.data.access_token)return"";this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,this.config.refresh_token=t.data.refresh_token;let r=yield this.thirdpartyRequest.encryptToken({token:JSON.stringify({refresh_token:t.data.refresh_token,access_token:t.data.access_token,expires_at:this.config.expires_at})});return 200===r.code&&(yield this.thirdpartyRequest.TokenService.setToken("boxnet_token",r.data.encrypted_token)),t.data.access_token}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e,t){return b(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"boxnet",redirect_uri:t,code:e})).data}))}getAuthUrl(e){return`https://account.box.com/api/oauth2/authorize?${new URLSearchParams({response_type:"code",client_id:A,redirect_uri:e,grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}).toString()}`}}class ie extends re{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken(),n=o.substring(0,o.lastIndexOf("/")),a=o.substring(o.lastIndexOf("/")+1);let d=this.baseFolder+"/"+n;for(;d.startsWith("/");)d=d.substring(1);const l=yield this.getFolderIdByPath(d);if(!l)throw new Error("Folder not found");const c=yield this.listFiles(n);c.find((e=>e===a))&&(yield this.deleteFileWithoutQueue(n+"/"+a));const h=new f,u=JSON.stringify({name:a,parent:{id:l}});h.append("attributes",u),h.append("file",t.createReadStream(r.join(this.storagePath,i)));const p=yield e.post("https://upload.box.com/api/2.0/files/content",h,{headers:Object.assign({Authorization:`Bearer ${s}`},h.getHeaders()),maxContentLength:1/0,maxBodyLength:1/0});return!(p.status>=300)||(console.error("Error occurred during file upload:",p),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=yield this.refreshToken(),n=i.substring(0,i.lastIndexOf("/")),a=i.substring(i.lastIndexOf("/")+1);let d=this.baseFolder+"/"+n;for(;d.startsWith("/");)d=d.substring(1);const l=yield this.getFolderIdByPath(d);if(!l)return console.error("Folder not found"),!0;const c=`https://api.box.com/2.0/folders/${l}/items?fields=id,name&type=file&limit=1000`,h=(yield e.get(c,{headers:{Authorization:`Bearer ${s}`}})).data.entries.find((e=>e.name===a&&"file"===e.type));if(!h)return console.error("File not found:",a),!0;const u=yield e({url:`https://api.box.com/2.0/files/${h.id}/content`,method:"get",responseType:"stream",headers:{Authorization:`Bearer ${s}`}});return yield new Promise(((e,i)=>{let s=0;const n=t.createWriteStream(r.join(this.storagePath,o));u.data.on("data",(e=>{s+=e.length,this.taskQueue.setDownloadedSize(s)})),u.data.pipe(n),n.on("finish",e),n.on("error",i)})),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class oe{constructor(e){this.folderCreationLocks=new Map,this.config=e,this.taskQueue=new E(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=2){return b(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}getStorage(){return b(this,void 0,void 0,(function*(){if(this.storage)return this.storage;let{email:e,password:t}=this.config;return this.storage=yield new y({email:e,password:t,userAgent:"KoodoReader/1.0"}).ready,this.storage}))}getRoot(){return b(this,void 0,void 0,(function*(){if(this.root)return this.root;const e=(yield this.getStorage()).root;if(""===this.baseFolder)return this.root=e,this.root;let t=e.children.find((e=>e.name===this.baseFolder&&e.directory));return t||(t=yield e.mkdir(this.baseFolder)),this.root=t,this.root}))}createFolder(e,t){return b(this,void 0,void 0,(function*(){const r=`${e.nodeId}_${t}`;if(this.folderCreationLocks.has(r))return yield this.folderCreationLocks.get(r);const i=(()=>b(this,void 0,void 0,(function*(){try{let r=e.children.find((e=>e.name===t&&e.directory));return r||(r=yield e.mkdir(t),r)}finally{this.folderCreationLocks.delete(r)}})))();return this.folderCreationLocks.set(r,i),yield i}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return b(this,void 0,void 0,(function*(){try{let t=yield this.getRoot();if(e){const r=e.split("/").filter((e=>e));for(const e of r){const r=t.children.find((t=>t.name===e&&t.directory));if(!r)return[];t=r}}return t.children.map((e=>({name:e.name,size:e.size||0,type:e.directory?"folder":"file",modified:e.timestamp?new Date(1e3*e.timestamp).toISOString():""})))}catch(e){return console.error("Error listing MEGA files:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(e){return b(this,void 0,void 0,(function*(){try{let t=yield this.getRoot();const r=e.split("/"),i=r.pop();for(const e of r){if(!e)continue;const r=t.children.find((t=>t.name===e&&t.directory));if(!r)return!0;t=r}const o=t.children.find((e=>e.name===i&&!e.directory));return!o||(yield o.delete(),!0)}catch(e){return console.error("Error deleting MEGA file:",e),!1}}))}}class se extends oe{constructor(e,t){super(e),this.storagePath=t}uploadFile(e,i){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{let o=yield this.getRoot();const s=i.split("/"),n=s.pop()||"";for(const e of s){if(!e)continue;let t=o.children.find((t=>t.name===e&&t.directory));t||(t=yield this.createFolder(o,e)),o=t}const a=o.children.find((e=>e.name===n&&!e.directory));a&&(yield a.delete());const d=t.createReadStream(r.join(this.storagePath,e)),l=t.statSync(r.join(this.storagePath,e)).size;return yield o.upload({name:n,size:l},d).complete,!0}catch(e){return console.error("Error occurred during MEGA file upload:",e),!1}}))))))}))}downloadFile(e,i){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{let o=yield this.getRoot();const s=e.split("/"),n=s.pop()||"";for(const e of s){if(!e)continue;const t=o.children.find((t=>t.name===e&&t.directory));if(!t)return!0;o=t}const a=o.children.find((e=>e.name===n&&!e.directory));if(!a)return!0;const d=t.createWriteStream(r.join(this.storagePath,i));let l=0;return new Promise((e=>{const t=a.download();t.on("data",(e=>{l+=e.length,this.taskQueue.setDownloadedSize(l)})),t.pipe(d),d.on("finish",(()=>e(!0))),d.on("error",(t=>{console.error("Error writing file:",t),e(!1)}))}))}catch(e){return console.error("Error occurred during MEGA file download:",e),!1}}))))))}))}}class ne{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.driveId="",this.refreshTokenPromise=null,this.taskQueue=new E(1),void 0===this.config.baseFolder?this.baseFolder="/KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return b(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}getDriveId(){return b(this,void 0,void 0,(function*(){if(this.driveId)return this.driveId;const t=yield this.refreshToken(),r=yield e.post("https://openapi.alipan.com/adrive/v1.0/user/getDriveInfo",{},{headers:{Authorization:`Bearer ${t}`}});return this.driveId=r.data.default_drive_id,this.driveId}))}getFolderIdByPath(t){return b(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),i=yield this.getDriveId();try{try{const o=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:i,file_path:t},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});if(o.data)return o.data.file_id}catch(o){const s=t.split("/").filter((e=>e));let n="",a="root";for(const t of s){n+="/"+t;try{a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:i,file_path:n},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.file_id}catch(o){a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:i,parent_file_id:a,name:t,type:"folder",check_name_mode:"refuse"},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.file_id}}return a}}catch(e){return console.error("Error getting/creating folder by path:",e),""}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=yield this.getDriveId(),o=yield this.getFolderIdByPath(this.baseFolder+"/"+t);let s=[],n="",a=!0;for(;a;){const t=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/list",{drive_id:i,parent_file_id:o,marker:n||void 0},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}),d=t.data.items.filter((e=>!e.punish_flag||2!==e.punish_flag))||[];s=s.concat(d),n=t.data.next_marker,a=!!n&&100===d.length}return[...new Set(s.map((e=>({name:e.name,size:e.size,type:e.type,modified:e.updated_at}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=yield this.getDriveId(),o=yield this.getFolderIdByPath(this.baseFolder+"/"+t);return!o||(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/delete",{drive_id:i,file_id:o},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}),!0)}catch(e){return console.error("Error deleting file:",e),!1}}))}checkExists(t){var r;return b(this,void 0,void 0,(function*(){try{const i=yield this.refreshToken(),o=yield this.getDriveId(),s=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:o,file_path:t},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}});(null===(r=s.data)||void 0===r?void 0:r.file_id)&&(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/recyclebin/trash",{drive_id:o,file_id:s.data.file_id},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}))}catch(e){}}))}refreshToken(){return b(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>b(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"adrive",refresh_token:e});if(!t.data.access_token)return"";this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,this.config.refresh_token=t.data.refresh_token;let r=yield this.thirdpartyRequest.encryptToken({token:JSON.stringify({refresh_token:t.data.refresh_token,access_token:t.data.access_token,expires_at:this.config.expires_at})});return 200===r.code&&(yield this.thirdpartyRequest.TokenService.setToken("adrive_token",r.data.encrypted_token)),t.data.access_token}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e,t){return b(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"adrive",redirect_uri:t,code:e})).data}))}getAuthUrl(e){return`https://openapi.alipan.com/oauth/authorize?${new URLSearchParams({response_type:"code",client_id:Q,redirect_uri:e,grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}).toString()}`}}class ae extends ne{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken(),n=yield this.getDriveId(),a=o.substring(0,o.lastIndexOf("/")),d=o.substring(o.lastIndexOf("/")+1);yield this.deleteFileWithoutQueue(o);const l=yield this.getFolderIdByPath(this.baseFolder+"/"+a),c=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:n,parent_file_id:l,name:d,type:"file",check_name_mode:"ignore"},{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}),{file_id:h,upload_id:u,part_info_list:p}=c.data,f=yield t.promises.readFile(r.join(this.storagePath,i));return yield fetch(p[0].upload_url,{method:"PUT",body:f,headers:{"Content-Length":t.statSync(r.join(this.storagePath,i)).size.toString()}}),yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/complete",{drive_id:n,file_id:h,upload_id:u},{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}),!0}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=yield this.refreshToken(),n=yield this.getDriveId(),a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:n,file_path:this.baseFolder+"/"+i},{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}})).data.file_id,d=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/getDownloadUrl",{drive_id:n,file_id:a},{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}),l=yield e({url:d.data.url,method:"get",responseType:"stream"});let c=0;const h=t.createWriteStream(r.join(this.storagePath,o+".temp"));return l.data.on("data",(e=>{c+=e.length,this.taskQueue.setDownloadedSize(c)})),l.data.pipe(h),new Promise((e=>{h.on("finish",(()=>{t.renameSync(r.join(this.storagePath,o+".temp"),r.join(this.storagePath,o)),e(!0)})),h.on("error",(t=>{console.error("Error occurred during file download:",t),e(!1)}))}))}catch(e){return console.error("Error downloading file:",e),!1}}))))))}))}}class de{constructor(e,t){this.baseUrl="https://api.pcloud.com",this.config=e,this.thirdpartyRequest=t,this.taskQueue=new E(3),this.baseUrl="2"===e.region?"https://eapi.pcloud.com":"https://api.pcloud.com"}retryOperation(e,t=3){return b(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}checkFolderExists(t,r){return b(this,void 0,void 0,(function*(){try{return 0===(yield e.get(`${this.baseUrl}/listfolder`,{params:{access_token:r,path:`/${t}`}})).data.result}catch(e){return console.error("Error checking folder:",e),!1}}))}createFolder(t,r){return b(this,void 0,void 0,(function*(){try{return 0===(yield e.get(`${this.baseUrl}/createfolderifnotexists`,{params:{access_token:r,path:`/${t}`}})).data.result}catch(e){return console.error("Error creating folder:",e),!1}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=yield e.get(`${this.baseUrl}/listfolder`,{params:{access_token:r,path:"/"+t,recursive:0}});return 0!==i.data.result?[]:i.data.metadata.contents.map((e=>({name:e.name,size:e.size||0,type:e.isfolder?"folder":"file",modified:e.modified})))}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=yield e.get(`${this.baseUrl}/deletefile`,{params:{access_token:r,path:"/"+t}});return 0===i.data.result||(console.error("Error deleting file:",i.data),!0)}catch(e){return console.error("Error occurred during file delete:",e),!1}}))}refreshToken(){return b(this,void 0,void 0,(function*(){return this.config.refresh_token}))}authToken(e,t){return b(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"pcloud",redirect_uri:t,code:e})).data}))}getAuthUrl(e){return`https://my.pcloud.com/oauth2/authorize?client_id=${P}&response_type=code&redirect_uri=${e}`}}class le extends de{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken(),n=o.split("/").slice(0,-1).join("/");if(!(yield this.checkFolderExists(n,s))){if(!(yield this.createFolder(n,s)))return!1}const a=r.join(this.storagePath,i),d=t.createReadStream(a),l=t.statSync(a),c=r.basename(i),h=yield e({method:"put",url:`${this.baseUrl}/uploadfile`,params:{access_token:s,path:`/${n}`,renew:1,filename:c},data:d,headers:{"Content-Length":l.size,"Content-Type":"application/octet-stream"},maxContentLength:1/0,maxBodyLength:1/0});return 0===h.data.result||(console.error("Error uploading file:",h.data),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=yield this.refreshToken(),n=yield e.get(`${this.baseUrl}/getfilelink`,{params:{access_token:s,path:`/${i}`}});if(0!==n.data.result)return console.error("Error getting file link:",n.data),!1;const a=r.join(this.storagePath,o),d=t.createWriteStream(a),l=`https://${n.data.hosts[0]}${n.data.path}`,c=yield e({method:"get",url:l,responseType:"stream",maxContentLength:1/0,maxBodyLength:1/0});return new Promise((e=>{let t=0;c.data.on("data",(e=>{t+=e.length,this.taskQueue.setDownloadedSize(t)})),c.data.pipe(d),d.on("finish",(()=>{e(!0)})),d.on("error",(t=>{console.error("Error writing file:",t),e(!1)}))}))}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class ce{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new E(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=1){return b(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let i=this.baseFolder;t&&""!==t.trim()&&(i=i+"/"+t),i=i.replace(/\/+/g,"/"),i.startsWith("/")&&(i=i.substring(1));let o=[],s=0;const n=1e3;for(;;){const t=yield e.get("https://pan.baidu.com/rest/2.0/xpan/file",{params:{method:"list",access_token:r,dir:"/"+i,start:s,limit:n,order:"name",desc:0,web:1,folder:0},headers:{"User-Agent":"pan.baidu.com"}});if(t.status>=300||0!==t.data.errno){console.error("百度网盘API错误:",t.data);break}const a=t.data.list||[];if(0===a.length)break;if(o=o.concat(a),a.length({name:e.server_filename,size:e.size||0,type:e.isdir?"folder":"file",modified:new Date(1e3*e.server_mtime).toISOString(),path:e.path})))}catch(e){return console.error("获取百度网盘文件列表时发生错误:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let i=this.baseFolder+"/"+t;i=i.replace(/\/+/g,"/"),i.startsWith("/")&&(i=i.substring(1));const o=new URLSearchParams({async:"0",filelist:JSON.stringify(["/"+i])}),s=yield e.post(`https://pan.baidu.com/rest/2.0/xpan/file?method=filemanager&access_token=${r}&opera=delete`,o.toString(),{headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":"pan.baidu.com"}});if(0!==s.data.errno)return console.error("百度网盘删除文件API错误:",s.data),-9===s.data.errno?console.error("文件不存在"):111===s.data.errno?console.error("有其他异步任务正在执行"):-7===s.data.errno&&console.error("文件名非法"),!1;const n=s.data.info||[];for(const e of n)if(0!==e.errno)return console.error(`文件删除失败: ${e.path}, 错误码: ${e.errno}`),!1;return!0}catch(e){return console.error("删除文件时发生错误:",e),!1}}))}refreshToken(){return b(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>b(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"dubox",refresh_token:e});if(!t.data.access_token)return"";this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,this.config.refresh_token=t.data.refresh_token;let r=yield this.thirdpartyRequest.encryptToken({token:JSON.stringify({refresh_token:t.data.refresh_token,access_token:t.data.access_token,expires_at:this.config.expires_at})});return 200===r.code&&(yield this.thirdpartyRequest.TokenService.setToken("dubox_token",r.data.encrypted_token)),t.data.access_token}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e,t){return b(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"dubox",redirect_uri:t,code:e})).data}))}getAuthUrl(e){return`https://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id=${I}&redirect_uri=${e}&scope=basic,netdisk&device_id=119827642&display=page&qrcode=1`}}const he=4194304;class ue extends ce{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){var s;let n=null;try{const s=yield this.refreshToken();let a=this.baseFolder+"/"+o;a=a.replace(/\/+/g,"/"),a.startsWith("/")&&(a=a.substring(1));const d=r.join(this.storagePath,i),l=yield this.getFileSize(d),{contentMd5:c,sliceMd5:h,blockList:u}=yield this.calculateFileMd5(d,l),p=new URLSearchParams({path:"/"+a,size:l.toString(),isdir:"0",autoinit:"1",rtype:"3",block_list:JSON.stringify(u),"content-md5":c,"slice-md5":h,local_ctime:Math.floor(Date.now()/1e3).toString(),local_mtime:Math.floor(Date.now()/1e3).toString()}),y=yield e.post(`https://pan.baidu.com/rest/2.0/xpan/file?method=precreate&access_token=${s}`,p.toString(),{headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":"pan.baidu.com"}});if(0!==y.data.errno)return console.error("预上传失败:",y.data),-7===y.data.errno?console.error("文件或目录名错误或无权访问"):-10===y.data.errno&&console.error("容量不足"),!1;const g=y.data.uploadid,m=y.data.block_list||[];if(0===m.length)return!0;const k=yield this.getUploadDomain(s,"/"+a,g);if(!k)return console.error("获取上传域名失败"),!1;n=yield t.promises.open(d,"r");for(const t of m){const r=t*he,i=Math.min(he,l-r),o=Buffer.alloc(i),{bytesRead:d}=yield n.read(o,0,i,r);if(0===d)break;const c=o.slice(0,d),h=u[t],p=new f;p.append("file",c,{filename:`chunk_${t}`,contentType:"application/octet-stream",knownLength:c.length});const y=`${k}/rest/2.0/pcs/superfile2?method=upload&access_token=${s}&type=tmpfile&path=${encodeURIComponent("/"+a)}&uploadid=${g}&partseq=${t}`,m=yield e.post(y,p,{headers:Object.assign(Object.assign({"User-Agent":"pan.baidu.com"},p.getHeaders()),{"Content-Length":p.getLengthSync().toString()}),maxContentLength:1/0,maxBodyLength:1/0,timeout:0});if(m.status>=300)throw 31024===m.data.errno?console.error("没有申请上传权限"):31299===m.data.errno?console.error("第一个分片的大小小于4MB"):31364===m.data.errno?console.error("超出分片大小限制"):31363===m.data.errno&&console.error("分片缺失"),new Error(`分片上传失败: ${JSON.stringify(m.data)}`);const v=m.data.md5;v&&v!==h&&console.warn(`分片 ${t} MD5不匹配: 期望 ${h}, 实际 ${v}`)}const v=new URLSearchParams({path:"/"+a,size:l.toString(),isdir:"0",block_list:JSON.stringify(u),uploadid:g,rtype:"3",local_ctime:Math.floor(Date.now()/1e3).toString(),local_mtime:Math.floor(Date.now()/1e3).toString()}),T=yield e.post(`https://pan.baidu.com/rest/2.0/xpan/file?method=create&access_token=${s}`,v.toString(),{headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":"pan.baidu.com"}});return 0===T.data.errno||(console.error("创建文件失败:",T.data),-7===T.data.errno?console.error("文件或目录名错误或无权访问"):-8===T.data.errno?console.error("文件或目录已存在"):-10===T.data.errno?console.error("云端容量已满"):10===T.data.errno?console.error("创建文件失败,一般是分片问题"):31190===T.data.errno?console.error("文件不存在,一般是分片上传阶段有问题"):31355===T.data.errno?console.error("参数异常,一般是uploadid参数传的有问题"):31365===T.data.errno&&console.error("文件总大小超限"),!1)}catch(e){return console.error("文件上传过程中发生错误:",(null===(s=e.response)||void 0===s?void 0:s.data)||e.message||e),!1}finally{n&&(yield n.close())}}))))))}))}getUploadDomain(t,r,i){return b(this,void 0,void 0,(function*(){try{const o=yield e.get("https://d.pcs.baidu.com/rest/2.0/pcs/file",{params:{method:"locateupload",appid:"250528",access_token:t,path:r,uploadid:i,upload_version:"2.0"},headers:{"User-Agent":"pan.baidu.com"}});if(0!==o.data.error_code)return console.error("获取上传域名失败:",o.data),null;const s=o.data.servers||[],n=s.find((e=>e.server.startsWith("https://")));return n?n.server:s.length>0?s[0].server:(console.error("没有可用的上传服务器"),null)}catch(e){return console.error("获取上传域名时出错:",e),null}}))}calculateFileMd5(e,r){return b(this,void 0,void 0,(function*(){const i=yield t.promises.open(e,"r");try{const e=g.createHash("md5"),t=[];let o="",s=0;for(;sthis.retryOperation((()=>b(this,void 0,void 0,(function*(){var s,n;this.taskQueue.setDownloadedSize(0);try{const a=yield this.refreshToken();let d,l=this.baseFolder+"/"+i;l=l.replace(/\/+/g,"/"),l.startsWith("/")&&(l=l.substring(1));const c=yield e.get("https://pan.baidu.com/rest/2.0/xpan/file",{params:{method:"list",access_token:a,dir:"/"+l.substring(0,l.lastIndexOf("/")),web:1},headers:{"User-Agent":"pan.baidu.com"}});if(0!==c.data.errno)return console.error("获取文件列表失败:",c.data),!1;const h=l.split("/").pop(),u=null===(s=c.data.list)||void 0===s?void 0:s.find((e=>e.server_filename===h));if(!u)return console.error("文件不存在:",i),!1;const p=yield e.get("https://pan.baidu.com/rest/2.0/xpan/multimedia",{params:{method:"filemetas",access_token:a,fsids:JSON.stringify([u.fs_id]),dlink:1},headers:{"User-Agent":"pan.baidu.com"}});if(0!==p.data.errno||!(null===(n=p.data.list)||void 0===n?void 0:n[0]))return console.error("获取下载链接失败:",p.data),!1;d=p.data.list[0];const f=d.dlink,y=yield e.get(f,{responseType:"stream",params:{access_token:a},headers:{"User-Agent":"pan.baidu.com"}});let g=0;const m=t.createWriteStream(r.join(this.storagePath,o));y.data.on("data",(e=>{g+=e.length,this.taskQueue.setDownloadedSize(g)})),yield new Promise(((e,t)=>{y.data.pipe(m),m.on("finish",(()=>{e()})),m.on("error",t)}));return(yield this.getFileSize(r.join(this.storagePath,o)))===d.size||(console.error("Downloaded file size does not match expected size."),yield t.promises.unlink(r.join(this.storagePath,o)),!1)}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}getFileSize(e){return b(this,void 0,void 0,(function*(){try{return(yield t.promises.stat(e)).size}catch(e){throw e}}))}}class pe{constructor(e){this.username=e.username,this.password=e.password,this.url=e.url,this.refreshTokenPromise=null,this.taskQueue=new E(3)}retryOperation(e,t=1){return b(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{return(yield e.get(`${this.url}/list`,{params:{dir:t},auth:{username:this.username,password:this.password}})).data.files.map((e=>({name:e.name,size:e.size||0,type:"file"===e.type?"file":"folder",modified:e.modifiedTime})))||[]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{return(yield e.delete(`${this.url}/delete`,{params:{dir:t.split("/").slice(0,-1).join("/")||"",filename:t.split("/").pop()},auth:{username:this.username,password:this.password}})).data.success}catch(e){return console.error("Error deleting file:",e),!1}}))}}const fe=i(o.pipeline);class ye extends pe{constructor(e,t){super(e),this.storagePath=t}getAuthHeader(){return`Basic ${btoa(`${this.username}:${this.password}`)}`}uploadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{o.split("/").pop();const s=o.substring(0,o.lastIndexOf("/"))||"";let n=this.listFiles("");const a=new Promise(((e,t)=>{setTimeout((()=>t(new Error("Docker connection timeout"))),5e3)}));yield Promise.race([n,a]);const d=t.createReadStream(r.join(this.storagePath,i)),l=new f;l.append("file",d);const c=yield e.post(`${this.url}/upload?dir=${encodeURIComponent(s)}`,l,{headers:Object.assign(Object.assign({},l.getHeaders()),{Authorization:this.getAuthHeader()}),maxContentLength:1/0,maxBodyLength:1/0});return!(c.status>=300)||(console.error("Error occurred during file upload:",c),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=i.split("/").pop()||"",n=i.substring(0,i.lastIndexOf("/"))||"",a=t.createWriteStream(r.join(this.storagePath,o)),d=yield e({url:`${this.url}/download`,method:"GET",params:{dir:n,filename:s},headers:{Authorization:this.getAuthHeader()},maxContentLength:1/0,maxBodyLength:1/0,responseType:"stream"});if(d.status>=300)return console.error("Error occurred during file download:",d),a.destroy(),t.existsSync(r.join(this.storagePath,o))&&t.unlinkSync(r.join(this.storagePath,o)),!1;let l=0;return d.data.on("data",(e=>{l+=e.length,this.taskQueue.setDownloadedSize(l)})),yield fe(d.data,a),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class ge{constructor(e,t){this.baseUrl="https://proapi.115.com",this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new E(1),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return b(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}getUploadCredentials(t){return b(this,void 0,void 0,(function*(){try{const r=yield e.get(`${this.baseUrl}/open/upload/get_token`,{headers:{Authorization:`Bearer ${t}`}});return r.status>=300||!r.data.state?(console.error("Error getting upload credentials:",r.data),null):r.data.data}catch(e){return console.error("Error occurred during get upload credentials:",e),null}}))}generateOSSPolicy(e,t,r=new Date(Date.now()+36e5)){const i={expiration:r.toISOString(),conditions:[{bucket:e},{key:t},["starts-with","$success_action_status","2"],["content-length-range",0,1073741824]]};return JSON.stringify(i)}refreshToken(){return b(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>b(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token;if(!e)throw new Error("No refresh token available");let t=yield this.thirdpartyRequest.refreshThirdToken({provider:"yiyiwu",refresh_token:e});if(!t.data.access_token)return"";if(this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+18e5,!t.data.refresh_token)throw new Error("No refresh token returned");this.config.refresh_token=t.data.refresh_token;let r=yield this.thirdpartyRequest.encryptToken({token:JSON.stringify({refresh_token:t.data.refresh_token,access_token:t.data.access_token,expires_at:this.config.expires_at})});return 200===r.code&&(yield this.thirdpartyRequest.TokenService.setToken("yiyiwu_token",r.data.encrypted_token)),t.data.access_token}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e,t){return b(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"yiyiwu",redirect_uri:t,code:e})).data}))}getAuthUrl(e){return`https://passportapi.115.com/open/authorize?client_id=${$}&response_type=code&redirect_uri=${e}`}}class me extends ge{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(e,t){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){var i;try{const i=yield this.refreshToken();let o=this.baseFolder+"/"+t;o.startsWith("/")||(o="/"+o);let s=r.dirname(o),n=yield this.getFolderInfo(s,!0),a="0";if(n)a=n.file_id;else{let e=yield this.createFolder(s);if(!e)return console.error("Failed to create folder:",s),!1;a=e}const d=r.join(this.storagePath,e),l=yield this.getFileSize(d),c=yield this.calculateFileSha1(d),h=yield this.calculatePreSha1(d),u=r.basename(t);yield this.deleteFileWithoutQueue(t);let p=yield this.initializeUpload(a,u,l,c,h,i);if(!p)return console.error("Failed to initialize upload"),!1;if((6===p.status||7===p.status||8===p.status)&&(p=yield this.handleSecondAuth(a,p,d,u,l,c,h,i),!p))return console.error("Second authentication failed"),!1;if(2===p.status)return console.info(`File ${e} uploaded successfully via instant upload.`),!0;const f=yield this.getUploadCredentials(i);if(!f)return console.error("Failed to get upload credentials"),!1;return(yield this.uploadToObjectStorage(d,p,f))?(console.info(`File ${e} uploaded successfully.`),!0):(console.error("Failed to upload to object storage"),!1)}catch(e){return console.error("Error occurred during file upload:",(null===(i=e.response)||void 0===i?void 0:i.data)||e.message||e),!1}}))))))}))}calculateFileSha1(e){return b(this,void 0,void 0,(function*(){return new Promise(((r,i)=>{const o=g.createHash("sha1"),s=t.createReadStream(e);s.on("data",(e=>{o.update(e)})),s.on("end",(()=>{r(o.digest("hex"))})),s.on("error",(e=>{i(e)}))}))}))}calculatePreSha1(e){return b(this,void 0,void 0,(function*(){return new Promise(((r,i)=>{const o=g.createHash("sha1"),s=t.createReadStream(e,{start:0,end:131071});s.on("data",(e=>{o.update(e)})),s.on("end",(()=>{r(o.digest("hex"))})),s.on("error",(e=>{i(e)}))}))}))}handleSecondAuth(e,r,i,o,s,n,a,d){return b(this,void 0,void 0,(function*(){try{if(!r.sign_check)return console.error("No sign_check provided for second authentication"),null;const[l,c]=r.sign_check.split("-"),h=parseInt(l),u=parseInt(c),p=Buffer.alloc(u-h+1),f=yield t.promises.open(i,"r");try{yield f.read(p,0,p.length,h);const t=g.createHash("sha1");t.update(p);const i=t.digest("hex").toUpperCase();return yield this.initializeUpload(e,o,s,n,a,d,r.sign_key,i,r.pick_code)}finally{yield f.close()}}catch(e){return console.error("Error during second authentication:",e),null}}))}calculateOSSSignature(e,t){const r=Buffer.from(t).toString("base64");return g.createHmac("sha1",e).update(r).digest("base64")}uploadToObjectStorage(i,o,s){var n;return b(this,void 0,void 0,(function*(){try{const n=s.endpoint,a=o.bucket,d=o.object;let l;if(n.includes(a))l=n;else{l=`https://${a}.${n.replace(/^https?:\/\//,"")}`}const c=this.generateOSSPolicy(a,d),h=this.calculateOSSSignature(s.AccessKeySecret,c),u=Buffer.from(c).toString("base64"),p=new f;if(p.append("key",d),p.append("policy",u),p.append("OSSAccessKeyId",s.AccessKeyId),p.append("signature",h),p.append("x-oss-security-token",s.SecurityToken),p.append("success_action_status","200"),o.callback&&o.callback.callback){const e=Buffer.from(o.callback.callback).toString("base64");if(p.append("callback",e),o.callback.callback_var){const e=JSON.parse(o.callback.callback_var);for(const[t,r]of Object.entries(e))p.append(t,String(r))}}const y=t.createReadStream(i);p.append("file",y,r.basename(i));const g=yield e.post(l,p,{headers:Object.assign({},p.getHeaders()),maxContentLength:1/0,maxBodyLength:1/0});return 200===g.status||204===g.status||(console.error("Upload failed with status:",g.status),!1)}catch(e){return console.error("Error uploading file via REST API:",(null===(n=e.response)||void 0===n?void 0:n.data)||e.message||e),!1}}))}downloadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{let s=this.baseFolder+"/"+i;s=s.replace(/\/+/g,"/"),s.startsWith("/")||(s="/"+s);const n=yield this.getFolderInfo(s,!1);if(!n||!n.pick_code)return console.error("Failed to get file info or pick_code for:",i),!1;const a=yield this.getFileDownloadUrl(n.pick_code);if(!a)return console.error("Failed to get download URL for:",i),!1;const d=yield e.get(a.url,{responseType:"stream"});let l=0;const c=t.createWriteStream(r.join(this.storagePath,o));return d.data.on("data",(e=>{l+=e.length,this.taskQueue.setDownloadedSize(l)})),yield new Promise(((e,t)=>{d.data.pipe(c),c.on("finish",(()=>{e()})),c.on("error",t)})),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();(t=this.baseFolder+"/"+t).startsWith("/")||(t="/"+t);let i=[],o=0;const s=1150;let n=!0,a=yield this.getFolderInfo(t,!0),d="";if(a)d=a.file_id;else{let e=yield this.createFolder(t);if(!e)return console.error("Failed to create folder:",t),[];d=e}if(!d)return console.error("Failed to get or create folder ID:",t),[];let l=d;for(;n;){const t={offset:o,limit:s,cur:1,show_dir:1};l&&(t.cid=l);const a=yield e.get(`${this.baseUrl}/open/ufile/files`,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},params:t});if(a.status>=300)break;const d=a.data.data||[];i=i.concat(d),d.length({name:e.fn,size:e.fs||0,type:"0"===e.fc?"folder":"file",modified:new Date(1e3*e.upt).toISOString()})))}catch(e){return console.error("Error occurred during file list:",e),[]}}))}getFileDownloadUrl(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=new f;i.append("pick_code",t);const o=yield e.post(`${this.baseUrl}/open/ufile/downurl`,i,{headers:Object.assign({Authorization:`Bearer ${r}`},i.getHeaders())});if(o.status>=300)return console.error("Error getting download URL:",o.data),null;const s=o.data.data,n=Object.keys(s)[0];return n&&s[n]?s[n].url:(console.error("No file data found in download URL response"),null)}catch(e){return console.error("Error occurred during get download URL:",e),null}}))}initializeUpload(t,r,i,o,s,n,a,d,l){return b(this,void 0,void 0,(function*(){try{const c=new f;c.append("file_name",r),c.append("file_size",i.toString()),t?c.append("target","U_1_"+t):c.append("target","U_1_0"),c.append("fileid",o),c.append("preid",s),c.append("topupload","0"),l&&c.append("pick_code",l),a&&c.append("sign_key",a),d&&c.append("sign_val",d);const h=yield e.post(`${this.baseUrl}/open/upload/init`,c,{headers:Object.assign({Authorization:`Bearer ${n}`},c.getHeaders())});return h.status>=300||!h.data.state?(console.error("Error initializing upload:",h.data),null):h.data.data}catch(e){return console.error("Error occurred during upload initialization:",e),null}}))}createFolder(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=t.replace(/^\/+|\/+$/g,"");if(!i)return"";const o=i.split("/");let s="",n="0";for(const t of o){s=s?`${s}/${t}`:t;const i=yield this.getFolderInfo(s,!0);if(i&&i.file_id)n=i.file_id;else{const i=new f;i.append("pid",n),i.append("file_name",t);const o=yield e.post(`${this.baseUrl}/open/folder/add`,i,{headers:Object.assign({Authorization:`Bearer ${r}`},i.getHeaders())});if(o.status>=300||!o.data.state)return console.error("Error creating folder:",o.data),"";n=o.data.data.file_id}}return n}catch(e){return console.error("Error occurred during folder creation:",e),""}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();t=this.baseFolder+"/"+t;let i=yield this.getFolderInfo(t,!1);if(!i)return!0;let o=new f;o.append("file_ids",i.file_id);const s=yield e.post(`${this.baseUrl}/open/ufile/delete`,o,{headers:Object.assign({Authorization:`Bearer ${r}`},o.getHeaders())});return!(s.status>=300||!s.data.state)||(console.error("Error deleting file:",s),!1)}catch(e){return console.error("Error occurred during file delete:",e),!1}}))}getFolderInfo(t,r){return b(this,void 0,void 0,(function*(){if(""===t||"/"===t)return{file_id:"0"};t.startsWith("/")||(t="/"+t);try{const r=yield this.refreshToken();let i=new f;i.append("path",t);const o=yield e.post(`${this.baseUrl}/open/folder/get_info`,i,{headers:Object.assign(Object.assign({},i.getHeaders()),{Authorization:`Bearer ${r}`})});return o.status>=300||!o.data.state||0===o.data.data.length?(console.error("Error getting file info:",o.data),null):o.data.data}catch(e){return console.error("Error occurred during get file info:",e),null}}))}getFileSize(e){return b(this,void 0,void 0,(function*(){try{return(yield t.promises.stat(e)).size}catch(e){throw e}}))}}const ke=()=>{let e="";if("darwin"===process.platform){const i=r.join(m.homedir(),"Library","Mobile Documents","com~apple~CloudDocs");t.existsSync(i)&&(e=i)}else if("win32"===process.platform){const i=[r.join(m.homedir(),"iCloudDrive","iCloud~com~koodoreader~expo")];for(const r of i)if(t.existsSync(r)){e=r;break}}return e&&t.existsSync(e)&&e&&t.existsSync(e)?e:""};class ve{constructor(e,t){this.config=e,this.storagePath=t,this.taskQueue=new E(5)}retryOperation(e,t=0){return b(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}uploadFile(e,i){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{const o=()=>new Promise(((o,s)=>b(this,void 0,void 0,(function*(){let s=ke();if(!s)return console.error("iCloud Drive path not found"),void o(!1);let n=s+"/"+i,a=s+"/"+r.dirname(i);t.existsSync(a)||t.mkdirSync(a,{recursive:!0}),t.copyFile(r.join(this.storagePath,e),n,(e=>{e?(console.error("Error uploading file:",e),o(!1)):o(!0)}))}))));try{return yield o()}catch(e){return console.error(e),!1}}catch(e){return console.error("Error in uploadFile:",e),!1}}))))))}))}downloadFile(e,i){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const o=()=>new Promise(((o,s)=>b(this,void 0,void 0,(function*(){let s=ke();if(!s)return console.error("iCloud Drive path not found"),void o(!1);let n=s+"/"+e,a=r.join(this.storagePath,i);console.log(n,"remotepath"),t.copyFile(n,a,(e=>{if(e)console.error("Error downloading file:",e),o(!1);else{let e=t.statSync(a);console.log(e,"status"),this.taskQueue.setDownloadedSize(e.size),o(!0)}}))}))));try{return yield o()}catch(e){return console.error(e),!1}}catch(e){return console.error("Error in downloadFile:",e),!1}}))))))}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return b(this,void 0,void 0,(function*(){const i=()=>new Promise(((i,o)=>b(this,void 0,void 0,(function*(){let o=ke();if(!o)return console.error("iCloud Drive path not found"),void i(!1);let s=o+"/"+e;t.existsSync(s)||t.mkdirSync(s,{recursive:!0}),t.readdir(s,{withFileTypes:!0},((e,o)=>{if(e)return console.error("Error reading directory:",e),void i([]);let n=o.map((e=>{let i=r.join(s,e.name),o=t.statSync(i);return{name:e.name,size:o.size,type:e.isDirectory()?"folder":"file",modified:o.mtime.toISOString()}}));i(n)}))}))));try{return yield i()}catch(e){return console.error(e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){try{return yield new Promise(((r,i)=>{let o=ke();if(!o)return console.error("iCloud Drive path not found"),void r(!1);let s=o+"/"+e;t.unlink(s,(e=>{e?(console.error("Error deleting file:",e),r(!1)):r(!0)}))}))}catch(e){return console.error(e),!1}}))}}const Te=["book","config","cover","font"];class be{constructor(e,t,r,i){this.type=e,this.storagePath=r,this.remote="dropbox"===e?new U(t,r,i):"microsoft"===e?new N(t,r,i):"google"===e?new K(t,r,i):"microsoft_exp"===e?new N(Object.assign(Object.assign({},t),{isExp:!0}),r,i):"google_exp"===e?new K(Object.assign(Object.assign({},t),{isExp:!0}),r,i):"s3compatible"===e?new J(t,r):"webdav"===e?new Y(t,r):"docker"===e?new ye(t,r):"ftp"===e?new M(t,r):"sftp"===e?new ee(t,r):"boxnet"===e?new ie(t,r,i):"mega"===e?new se(t,r):"adrive"===e?new ae(t,r,i):"pcloud"===e?new le(t,r,i):"dubox"===e?new ue(t,r,i):"yandex"===e?new Z(t,r,i):"yiyiwu"===e?new me(t,r,i):"icloud"===e?new ve(t,r):new te}downloadFile(e,i,o){return b(this,void 0,void 0,(function*(){if(t.existsSync(r.join(this.storagePath+"/"+o))||t.mkdirSync(r.join(this.storagePath+"/"+o)),"cover"!==o){if(!(yield this.listFiles(o)).find((t=>e.indexOf(t)>-1)))return!1}return yield this.remote.downloadFile(o+"/"+e,o+"/"+i)}))}uploadFile(e,t,r){return b(this,void 0,void 0,(function*(){return yield this.remote.uploadFile(r+"/"+e,r+"/"+t)}))}deleteFile(e,t){return b(this,void 0,void 0,(function*(){return!!(yield this.listFiles(t)).find((t=>e.indexOf(t)>-1))&&(yield this.remote.deleteFile(t+"/"+e))}))}isExist(e,t){return b(this,void 0,void 0,(function*(){return(yield this.listFiles(t)).find((t=>-1!==t.indexOf(e)))}))}listFiles(e){return b(this,void 0,void 0,(function*(){return yield this.remote.listFiles(e)}))}listFileInfos(e){return b(this,void 0,void 0,(function*(){return yield this.remote.listFileInfos(e)}))}downloadAllFiles(){return b(this,void 0,void 0,(function*(){for(let e of Te){let t=yield this.listFiles(e);for(let r of t)yield this.downloadFile(r,r,e)}}))}authToken(e,t){return b(this,void 0,void 0,(function*(){return yield this.remote.authToken(e,t)}))}getAuthUrl(e){return this.remote.getAuthUrl(e)}getStats(){return this.remote.taskQueue.getStats()}resetCounters(){this.remote.taskQueue.resetCounters()}getDownloadedSize(){return this.remote.taskQueue.getDownloadedSize()}}const Fe={notes:"SELECT * FROM notes WHERE key = ?",bookmarks:"SELECT * FROM bookmarks WHERE key = ?",books:"SELECT * FROM books WHERE key = ?",plugins:"SELECT * FROM plugins WHERE key = ?",words:"SELECT * FROM words WHERE key = ?"},we={notes:"SELECT * FROM notes WHERE bookKey = ?",bookmarks:"SELECT * FROM bookmarks WHERE bookKey = ?",words:"SELECT * FROM words WHERE bookKey = ?",books:"SELECT * FROM books WHERE key = ?"},Ee={notes:"DELETE FROM notes WHERE bookKey = ?",bookmarks:"DELETE FROM bookmarks WHERE bookKey = ?",words:"DELETE FROM words WHERE bookKey = ?"};function Se(e){for(const t in e)e.hasOwnProperty(t)&&(e[`temp-${t}`]=e[t]);return e}const _e={notes:e=>{let t=Object.assign({},e);return t.date=JSON.parse(e.date),t.tag=JSON.parse(e.tag),t},bookmarks:e=>e,books:e=>e,plugins:e=>{let t=Object.assign({},e);return e.autoValue||delete t.autoValue,e.langList?t.langList=JSON.parse(e.langList):delete t.langList,e.voiceList?t.voiceList=JSON.parse(e.voiceList):delete t.voiceList,t.config=JSON.parse(e.config),t},words:e=>{let t=Object.assign({},e);return t.date=JSON.parse(e.date),t}};var Re={sqlStatement:{createTableStatement:Se({notes:'\n CREATE TABLE IF NOT EXISTS "notes" (\n "key" text PRIMARY KEY,\n "bookKey" text,\n "date" object,\n "chapter" text,\n "chapterIndex" integer,\n "text" text,\n "cfi" text,\n "range" text,\n "notes" text,\n "percentage" text,\n "color" integer,\n "tag" array\n )\n ',bookmarks:'\n CREATE TABLE IF NOT EXISTS "bookmarks" (\n "key" text PRIMARY KEY,\n "bookKey" text,\n "cfi" text,\n "label" text,\n "percentage" text,\n "chapter" text\n );\n ',books:'\n CREATE TABLE IF NOT EXISTS "books" (\n "key" text PRIMARY KEY,\n "name" text,\n "author" text,\n "description" text,\n "md5" text,\n "cover" text,\n "format" text,\n "publisher" text,\n "size" integer,\n "page" integer,\n "path" text,\n "charset" text\n );\n ',plugins:'\n CREATE TABLE IF NOT EXISTS "plugins" (\n "key" text PRIMARY KEY,\n "type" text,\n "displayName" text,\n "icon" text,\n "version" text,\n "config" object,\n "autoValue" string,\n "langList" text,\n "voiceList" text,\n "scriptSHA256" text,\n "script" text\n );\n ',words:'\n CREATE TABLE IF NOT EXISTS "words" (\n "key" text PRIMARY KEY,\n "bookKey" text,\n "date" object,\n "word" text,\n "chapter" text\n );\n '}),getAllStatement:Se({notes:"SELECT * FROM notes",bookmarks:"SELECT * FROM bookmarks",books:"SELECT * FROM books",plugins:"SELECT * FROM plugins",words:"SELECT * FROM words"}),getPagedStatement:Se({notes:"SELECT * FROM notes LIMIT ? OFFSET ?",bookmarks:"SELECT * FROM bookmarks LIMIT ? OFFSET ?",books:"SELECT * FROM books LIMIT ? OFFSET ?",plugins:"SELECT * FROM plugins LIMIT ? OFFSET ?",words:"SELECT * FROM words LIMIT ? OFFSET ?"}),getCountStatement:Se({notes:"SELECT COUNT(*) as count FROM notes",bookmarks:"SELECT COUNT(*) as count FROM bookmarks",books:"SELECT COUNT(*) as count FROM books",plugins:"SELECT COUNT(*) as count FROM plugins",words:"SELECT COUNT(*) as count FROM words"}),saveStatement:Se({notes:"INSERT OR REPLACE INTO notes (key, bookKey, chapter, chapterIndex, text, cfi, range, notes, date, percentage, color, tag) VALUES (@key, @bookKey, @chapter, @chapterIndex, @text, @cfi, @range, @notes, @date, @percentage, @color, @tag)",bookmarks:"INSERT OR REPLACE INTO bookmarks (key, bookKey, cfi, label, percentage, chapter) VALUES (@key, @bookKey, @cfi, @label, @percentage, @chapter)",books:"INSERT OR REPLACE INTO books (key, name, author, description, md5, cover, format, publisher, size, page, path, charset) VALUES (@key, @name, @author, @description, @md5, @cover, @format, @publisher, @size, @page, @path, @charset)",plugins:"INSERT OR REPLACE INTO plugins (key, type, displayName, icon, version, config, autoValue, langList, voiceList, scriptSHA256, script) VALUES (@key, @type, @displayName, @icon, @version, @config, @autoValue, @langList, @voiceList, @scriptSHA256, @script)",words:"INSERT OR REPLACE INTO words (key, bookKey, date, word, chapter) VALUES (@key, @bookKey, @date, @word, @chapter)"}),deleteAllStatement:Se({notes:"DELETE FROM notes",bookmarks:"DELETE FROM bookmarks",books:"DELETE FROM books",plugins:"DELETE FROM plugins",words:"DELETE FROM words"}),updateStatement:Se({notes:"UPDATE notes SET bookKey = @bookKey, chapter = @chapter, chapterIndex = @chapterIndex, text = @text, cfi = @cfi, range = @range, notes = @notes, date = @date, percentage = @percentage, color = @color, tag = @tag WHERE key = @key",bookmarks:"UPDATE bookmarks SET bookKey = @bookKey, cfi = @cfi, label = @label, percentage = @percentage, chapter = @chapter WHERE key = @key",books:"UPDATE books SET name = @name, author = @author, description = @description, md5 = @md5, cover = @cover, format = @format, publisher = @publisher, size = @size, page = @page, path = @path, charset = @charset WHERE key = @key",plugins:"UPDATE plugins SET type = @type, displayName = @displayName, icon = @icon, version = @version, config = @config, autoValue = @autoValue, langList = @langList, voiceList = @voiceList, scriptSHA256 = @scriptSHA256, script = @script WHERE key = @key",words:"UPDATE words SET bookKey = @bookKey, date = @date, word = @word, chapter = @chapter WHERE key = @key"}),deleteStatement:Se({notes:"DELETE FROM notes WHERE key = ?",bookmarks:"DELETE FROM bookmarks WHERE key = ?",books:"DELETE FROM books WHERE key = ?",plugins:"DELETE FROM plugins WHERE key = ?",words:"DELETE FROM words WHERE key = ?"}),dropStatement:Se({notes:"DROP TABLE IF EXISTS notes",bookmarks:"DROP TABLE IF EXISTS bookmarks",books:"DROP TABLE IF EXISTS books",plugins:"DROP TABLE IF EXISTS plugins",words:"DROP TABLE IF EXISTS words"}),getStatement:Se(Fe),getByBookKeyStatement:Se(we),getByBookKeysStatement:Se({notes:e=>`SELECT * FROM notes WHERE bookKey IN (${e.map((()=>"?")).join(",")})`,bookmarks:e=>`SELECT * FROM bookmarks WHERE bookKey IN (${e.map((()=>"?")).join(",")})`,words:e=>`SELECT * FROM words WHERE bookKey IN (${e.map((()=>"?")).join(",")})`,books:e=>`SELECT * FROM books WHERE key IN (${e.map((()=>"?")).join(",")})`}),getKeysStatement:Se({notes:"SELECT key FROM notes",bookmarks:"SELECT key FROM bookmarks",books:"SELECT key FROM books",plugins:"SELECT key FROM plugins",words:"SELECT key FROM words"}),getWithSortAndPageStatement:Se({notes:(e,t,r,i)=>`SELECT * FROM notes ORDER BY ${e} ${t} LIMIT ${r} OFFSET ${i}`,bookmarks:(e,t,r,i)=>`SELECT * FROM bookmarks ORDER BY ${e} ${t} LIMIT ${r} OFFSET ${i}`,books:(e,t,r,i)=>`SELECT * FROM books ORDER BY ${e} ${t} LIMIT ${r} OFFSET ${i}`,plugins:(e,t,r,i)=>`SELECT * FROM plugins ORDER BY ${e} ${t} LIMIT ${r} OFFSET ${i}`,words:(e,t,r,i)=>`SELECT * FROM words ORDER BY ${e} ${t} LIMIT ${r} OFFSET ${i}`}),getByKeysStatement:Se({notes:e=>`SELECT * FROM notes WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,t)=>`WHEN ? THEN ${t}`)).join(" ")} END`,bookmarks:e=>`SELECT * FROM bookmarks WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,t)=>`WHEN ? THEN ${t}`)).join(" ")} END`,books:e=>`SELECT * FROM books WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,t)=>`WHEN ? THEN ${t}`)).join(" ")} END`,plugins:e=>`SELECT * FROM plugins WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,t)=>`WHEN ? THEN ${t}`)).join(" ")} END`,words:e=>`SELECT * FROM words WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,t)=>`WHEN ? THEN ${t}`)).join(" ")} END`}),deleteByBookKeyStatement:Se(Ee)},jsonToSqlite:Se({notes:e=>{let t=Object.assign({},e);return t.date=JSON.stringify(e.date),t.tag=JSON.stringify(e.tag),t},bookmarks:e=>e,books:e=>{let t=Object.assign({},e);return t.page=e.page||0,t},plugins:e=>{let t=Object.assign({},e);return e.autoValue||(t.autoValue=null),e.langList?t.langList=JSON.stringify(e.langList):t.langList=null,e.voiceList?t.voiceList=JSON.stringify(e.voiceList):t.voiceList=null,t.config=JSON.stringify(e.config),t},words:e=>{let t=Object.assign({},e);return t.date=JSON.stringify(e.date),t}}),sqliteToJson:Se(_e)};const xe=S,Oe=_,Ce=R;class Pe{constructor(e,t,r){this.TokenService=e,this.ConfigService=t,this.baseUrl="china"===r?Oe:xe,this.serverRegion=r,this.refreshToken="",this.accessToken="",this.streamPromise=null,this.expiresAt=0}refreshUserToken(){return b(this,void 0,void 0,(function*(){if(this.refreshToken=yield this.TokenService.getToken("refresh_token"),!this.refreshToken)return{code:401,message:"refresh token not found"};let t=(yield e.post(this.baseUrl+"/api/v1/public/user/refresh_token",{refresh_token:this.refreshToken})).data;return 200===t.code&&(yield this.TokenService.setToken("access_token",t.data.access_token),yield this.TokenService.setToken("refresh_token",t.data.refresh_token),yield this.TokenService.setToken("expires_at",(1e3*t.data.expires_at).toString()),this.accessToken=t.data.access_token,this.refreshToken=t.data.refresh_token,this.expiresAt=1e3*t.data.expires_at),t}))}requestWithRetry(e){return b(this,void 0,void 0,(function*(){return Pe.requestQueue||(Pe.requestQueue=[]),new Promise(((t,r)=>{Pe.requestQueue.push({config:e,resolve:t,reject:r}),Pe.processingQueue||this.processQueue()}))}))}isTokenValid(){return b(this,void 0,void 0,(function*(){if(this.accessToken||(this.accessToken=(yield this.TokenService.getToken("access_token"))||""),!this.expiresAt){const e=yield this.TokenService.getToken("expires_at");this.expiresAt=e?parseInt(e):(new Date).getTime()+31536e9}return""!==this.accessToken&&this.expiresAt>(new Date).getTime()+6e4}))}processQueue(){return b(this,void 0,void 0,(function*(){if(!Pe.processingQueue){Pe.processingQueue=!0;try{for(;Pe.requestQueue.length>0;){const e=Pe.requestQueue.shift();try{let t=yield this.executeRequest(e.config);t&&"object"==typeof t&&"code"in t&&503===t.code&&(t.msg="Network error, please try again later. 网络错误,请稍后再试。"),e.resolve(t)}catch(t){e.reject(t)}}}finally{Pe.processingQueue=!1}}}))}executeRequest(t){return b(this,void 0,void 0,(function*(){try{(yield this.isTokenValid())||(yield this.refreshUserToken());let r="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);if(t.baseURL=this.baseUrl,"china"===this.serverRegion&&"/api/v1/pro/reader/get_tts_audio"===t.url&&(t.baseURL=Ce),t.headers)t.headers.Authorization="Bearer "+this.accessToken,t.headers["X-Request-ID"]=r;else{let e=this.ConfigService.getItem("appVersion"),i=this.ConfigService.getItem("appPlatform");t.headers={Authorization:"Bearer "+this.accessToken,"X-Request-ID":r,"X-App-Version":e||"1.0.0","X-App-Platform":i||"web"}}let i=(yield e(t)).data;if(402===i.code){let r=yield this.refreshUserToken();if(200===r.code){return t.headers=t.headers||{},t.headers.Authorization="Bearer "+this.accessToken,(yield e(t)).data}return r}return 200!==i.code&&this.ConfigService.setItem("errorLog",this.ConfigService.getItem("errorLog")+"\n"+JSON.stringify({request:t.data,url:t.url,result:i,requestID:r})),i}catch(e){return console.error("Request execution error:",e),{code:503,message:"network error",data:null}}}))}requestWithStream(e,t,r){return b(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>b(this,void 0,void 0,(function*(){try{(yield this.isTokenValid())||(yield this.refreshUserToken());let i=this.accessToken||"",o="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((s,n)=>{let a=this.ConfigService.getItem("appVersion"),d=this.ConfigService.getItem("appPlatform");const l=new r(("china"===this.serverRegion?Ce:this.baseUrl)+e.url,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+i,"X-Request-ID":o,"X-App-Version":a||"1.0.0","X-App-Platform":d||"web"},method:e.method,body:JSON.stringify(e.data),pollingInterval:0});l.addEventListener("open",(()=>{console.info("Connection to OpenAI established.")})),l.addEventListener("message",(e=>b(this,void 0,void 0,(function*(){if(!e.data)return;const r=JSON.parse(e.data);r.done?(l.close(),s(r)):t(r.data)})))),l.addEventListener("error",(e=>{if(console.info("Error:",e),!e.data)return;const t=JSON.parse(e.data);s(t),l.close()}))}))}finally{this.streamPromise=null}})))()),this.streamPromise}))}requestWithFetch(e,t){return b(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>b(this,void 0,void 0,(function*(){try{(yield this.isTokenValid())||(yield this.refreshUserToken());let r=this.accessToken||"",i="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((o,s)=>b(this,void 0,void 0,(function*(){let s=this.ConfigService.getItem("appVersion"),n=this.ConfigService.getItem("appPlatform");var a=new k(("china"===this.serverRegion?Ce:this.baseUrl)+e.url,{headers:{"Content-Type":"text/plain",Authorization:"Bearer "+r,"X-Request-ID":i,"X-App-Version":s||"1.0.0","X-App-Platform":n||"web"},payload:JSON.stringify(e.data),method:"POST"});a.addEventListener("message",(e=>b(this,void 0,void 0,(function*(){if(!e.data)return;const r=JSON.parse(e.data);r.done?(a.close(),o(r)):t(r.data)})))),a.addEventListener("open",(e=>{console.info(e,"Connection to OpenAI established.")})),a.addEventListener("error",(e=>{if(console.error(e,"Error occurred while connecting to OpenAI"),!e.data)return;const t=JSON.parse(e.data);o(t),a.close()}))}))))}finally{this.streamPromise=null}})))()),this.streamPromise}))}}Pe.processingQueue=!1,Pe.requestQueue=[];class Ae extends Pe{constructor(e,t,r){super(e,t,r),this.serverRegion=r}encryptToken(e){return b(this,void 0,void 0,(function*(){let t=e.token,r=w.encode(t),{extracted:i,remaining:o}=function(e){let t="",r="",i=[],o=1;for(;o<=e.length;)i.push(o-1),o*=2;for(let o=0;o-1){let r=t.split("#");e.encrypted_token=r[1]}const r={method:"post",url:"/api/v1/pro/thirdparty/decrypt_token",data:e};let i=yield this.requestWithRetry(r);if(t.indexOf("#")>-1&&i.data&&i.data.token){let e=t.split("#"),r=function(e,t){let r="",i=[],o=1,s=e.length+t.length;for(;o<=s;)i.push(o-1),o*=2;let n=0,a=0;for(let o=0;o-1&&r.splice(i,1),this.setAllListConfig(r,t)}static setListConfig(e,t){let r=this.getAllListConfig(t);const i=r.indexOf(e);i>-1?(r.splice(i,1),r.unshift(e)):r.unshift(e),this.setAllListConfig(r,t)}static setAllListConfig(e,t,r=!0){this.setItem(t,JSON.stringify(e)),r&&this.setSyncRecord({type:"config",catergory:"listConfig",name:"general",key:t},{operation:"update",time:Date.now()})}static setObjectConfig(e,t,r,i=!0){let o=this.getAllObjectConfig(r);o[e]=t,i&&this.setSyncRecord({type:"config",catergory:"objectConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllObjectConfig(o,r)}static getObjectConfig(e,t,r){return this.getAllObjectConfig(t)[e]||r}static getAllObjectConfig(e){let t=this.getItem(e);return JSON.parse(t)||{}}static setAllObjectConfig(e,t){this.setItem(t,JSON.stringify(e))}static deleteObjectConfig(e,t){let r=this.getAllObjectConfig(t);delete r[e],this.setSyncRecord({type:"config",catergory:"objectConfig",name:t,key:e},{operation:"delete",time:Date.now()}),this.setAllObjectConfig(r,t)}static getAllMapConfig(e){let t=this.getItem(e);return JSON.parse(t)||{}}static getMapConfig(e,t){return this.getAllMapConfig(t)[e]||[]}static setAllMapConfig(e,t){this.setItem(t,JSON.stringify(e))}static setMapConfig(e,t,r){let i=this.getAllMapConfig(r);void 0===i[e]&&(i[e]=[]),t&&-1===i[e].indexOf(t)&&i[e].unshift(t),this.setSyncRecord({type:"config",catergory:"mapConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(i,r)}static setOneMapConfig(e,t,r,i=!0){let o=this.getAllMapConfig(r);o[e]=t,i&&this.setSyncRecord({type:"config",catergory:"mapConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(o,r)}static deleteFromMapConfig(e,t,r){let i=this.getAllMapConfig(r),o=i[e].indexOf(t);i[e].splice(o,1),this.setSyncRecord({type:"config",catergory:"mapConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(i,r)}static deleteFromAllMapConfig(e,t){let r=this.getAllMapConfig(t);Object.keys(r).forEach((i=>{let o=r[i].indexOf(e);o>-1&&(r[i].splice(o,1),this.setSyncRecord({type:"config",catergory:"mapConfig",name:t,key:i},{operation:"update",time:Date.now()}))})),this.setAllMapConfig(r,t)}static deleteMapConfig(e,t){let r=this.getAllMapConfig(t);delete r[e],this.setSyncRecord({type:"config",catergory:"mapConfig",name:t,key:e},{operation:"delete",time:Date.now()}),this.setAllMapConfig(r,t)}static getFromAllMapConfig(e,t){let r=this.getAllMapConfig(t),i=[];for(let t in r)r[t]&&r[t].indexOf(e)>-1&&i.push(t);return i}static getSyncRecord(e){return JSON.parse(this.getItem("syncRecord")||"{}")[e.type+"."+e.catergory+"."+e.name+"."+e.key]||{operation:"",time:0}}static getAllSyncRecord(){return JSON.parse(this.getItem("syncRecord")||"{}")}static flushSyncRecords(){if(0===Object.keys(this.pendingSyncRecords).length)return;let e=JSON.parse(this.getItem("syncRecord")||"{}");Object.assign(e,this.pendingSyncRecords),this.setItem("syncRecord",JSON.stringify(e)),this.pendingSyncRecords={},this.syncRecordTimer=null}static setSyncRecord(e,t){const r=e.type+"."+e.catergory+"."+e.name+"."+e.key;this.pendingSyncRecords[r]=t,null!==this.syncRecordTimer&&clearTimeout(this.syncRecordTimer),this.syncRecordTimer=setTimeout((()=>{this.flushSyncRecords()}),this.DEBOUNCE_DELAY)}static setAllSyncRecord(e){this.setItem("syncRecord",JSON.stringify(e))}}).pendingSyncRecords={},Qe.syncRecordTimer=null,Qe.DEBOUNCE_DELAY=1e3,Qe);var Le,ze,Qe;let De;const je=new Uint8Array(16);function Ue(){if(!De&&(De="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!De))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return De(je)}const Me=[];for(let e=0;e<256;++e)Me.push((e+256).toString(16).slice(1));var Be={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function We(e,t,r){if(Be.randomUUID&&!t&&!e)return Be.randomUUID();const i=(e=e||{}).random||(e.rng||Ue)();if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t){r=r||0;for(let e=0;e<16;++e)t[r+e]=i[e];return t}return function(e,t=0){return Me[e[t+0]]+Me[e[t+1]]+Me[e[t+2]]+Me[e[t+3]]+"-"+Me[e[t+4]]+Me[e[t+5]]+"-"+Me[e[t+6]]+Me[e[t+7]]+"-"+Me[e[t+8]]+Me[e[t+9]]+"-"+Me[e[t+10]]+Me[e[t+11]]+Me[e[t+12]]+Me[e[t+13]]+Me[e[t+14]]+Me[e[t+15]]}(i)}const Ne=new v;class qe{static encrypt(e,t){let r="";for(let i=0;i0)return $e.setItem("fingerPrint",e),e}catch(e){console.error("Failed to get machine ID:",e)}let t=We().replace(/-/g,"");return $e.setItem("fingerPrint",t),t}))}}export{$e as ConfigService,Re as SqlStatement,be as SyncUtil,Ae as ThirdpartyRequest,qe as TokenService}; +import e from"axios";import t from"fs";import r from"path";import{promisify as i}from"util";import o from"stream";import{Client as s}from"basic-ftp";import{S3Client as n,ListObjectsV2Command as a,DeleteObjectCommand as d,PutObjectCommand as l,GetObjectCommand as c}from"@aws-sdk/client-s3";import{AuthType as h,createClient as u}from"webdav";import p from"ssh2-sftp-client";import f from"form-data";import{Storage as y}from"megajs";import g from"crypto";import m from"os";import{SSE as k}from"sse.js";import v from"electron-store";import T from"node-machine-id";function b(e,t,r,i){return new(r||(r=Promise))((function(o,s){function n(e){try{d(i.next(e))}catch(e){s(e)}}function a(e){try{d(i.throw(e))}catch(e){s(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(n,a)}d((i=i.apply(e,t||[])).next())}))}const F=e=>"json"===e?"application/json":["jpg","jpeg","png","gif","bmp"].includes(e)?"image/"+e:"zip"===e?"application/zip":"epub"===e?"application/epub+zip":"txt"===e?"text/plain":"pdf"===e?"application/pdf":"mobi"===e?"application/x-mobipocket-ebook":"azw3"===e||"azw"===e?"application/vnd.amazon.ebook":"cbz"===e?"application/x-cbz":"cbr"===e?"application/x-cbr":"cbt"===e?"application/x-cbt":"cb7"===e?"application/x-cb7":"fb2"===e?"application/x-fictionbook+xml":"html"===e?"text/html":"css"===e?"text/css":"js"===e?"application/javascript":"xml"===e?"application/xml":"xhtml"===e?"application/xhtml+xml":"opf"===e?"application/oebps-package+xml":"ncx"===e?"application/x-dtbncx+xml":"mp3"===e?"audio/mpeg":"wav"===e?"audio/wav":"ogg"===e?"audio/ogg":"mp4"===e?"video/mp4":"webm"===e?"video/webm":"avi"===e?"video/x-msvideo":"wmv"===e?"video/x-ms-wmv":"flv"===e?"video/x-flv":"m3u8"===e?"application/x-mpegURL":"ts"===e?"video/MP2T":"3gp"===e?"video/3gpp":"3g2"===e?"video/3gpp2":"db"===e?"application/x-sqlite3":void 0,w={_chars:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",encode(e){if("string"!=typeof e)throw new Error("Input must be a string");let t="",r=0;const i=this._stringToUtf8Bytes(e),o=i.length;for(;r>2,d=(3&e)<<4|s>>4,l=(15&s)<<2|n>>6,c=63&n;t+=this._chars.charAt(a),t+=this._chars.charAt(d),t+=r-2>=o?"=":this._chars.charAt(l),t+=r-1>=o?"=":this._chars.charAt(c)}return t},decode(e){if("string"!=typeof e)throw new Error("Input must be a string");for(e=e.replace(/[^A-Za-z0-9+/]/g,"");e.length%4!=0;)e+="=";const t=[];let r=0;const i=e.length;for(;r>4,d=(15&o)<<4|s>>2,l=(3&s)<<6|n;t.push(a),-1!==s&&t.push(d),-1!==n&&t.push(l)}return this._utf8BytesToString(t)},_stringToUtf8Bytes(e){const t=[];for(let r=0;r>6),t.push(128|63&i);else if(55296==(64512&i)&&r+1>18),t.push(128|e>>12&63),t.push(128|e>>6&63),t.push(128|63&e)}else t.push(239,191,189),r--}else t.push(224|i>>12),t.push(128|i>>6&63),t.push(128|63&i)}return t},_utf8BytesToString(e){let t="",r=0;for(;r65535){const r=e-65536;t+=String.fromCharCode(55296|r>>10),t+=String.fromCharCode(56320|1023&r)}else t+=String.fromCharCode(e)}else t+="�"}else t+="�"}return t},encodeURL(e){return this.encode(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")},decodeURL(e){for(e=e.replace(/-/g,"+").replace(/_/g,"/");e.length%4;)e+="=";return this.decode(e)}};class E{constructor(e){this.queue=[],this.runningTasks=0,this.totalTasks=0,this.completedTasks=0,this.hasFailedTasks=!1,this.downloadedSize=0,this.maxConcurrency=e}addTask(e){return b(this,void 0,void 0,(function*(){return this.totalTasks++,new Promise(((t,r)=>{if(this.hasFailedTasks)return void t(void 0);const i=()=>b(this,void 0,void 0,(function*(){try{this.runningTasks++;const r=yield e();return this.completedTasks++,t(r),r}catch(e){throw this.completedTasks++,r(e),e}finally{this.runningTasks--,this.runNext()}}));this.runningTasks0&&this.runningTasks=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let i=[],o=!0,s=null;for(;o;){let n;n=s?yield e.post("https://api.dropboxapi.com/2/files/list_folder/continue",{cursor:s},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}):yield e.post("https://api.dropboxapi.com/2/files/list_folder",{path:"/"+t,limit:2e3},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});const a=n.data.entries||[];i=i.concat(a),o=n.data.has_more,s=n.data.cursor}return[...new Set(i.map((e=>({name:e.name,size:e.size||0,type:e[".tag"],modified:e.client_modified}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();yield e.post("https://api.dropboxapi.com/2/files/delete_v2",{path:"/"+t},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});return!0}catch(e){return console.error("Error deleting file:",e),!1}}))}refreshToken(){return b(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>b(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"dropbox",refresh_token:e});return t.data.access_token?(this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,t.data.access_token):""}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e,t){return b(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"dropbox",redirect_uri:t,code:e})).data}))}getAuthUrl(e){return`https://www.dropbox.com/oauth2/authorize?response_type=code&token_access_type=offline&client_id=${O}&redirect_uri=${e}`}}const j=i(o.pipeline);class U extends D{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken(),n=t.createReadStream(r.join(this.storagePath,i));return yield e.post("https://content.dropboxapi.com/2/files/upload",n,{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/octet-stream","Dropbox-API-Arg":JSON.stringify({path:"/"+o,mode:"overwrite",autorename:!0,mute:!1})},maxContentLength:1/0,maxBodyLength:1/0}),!0}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=yield this.refreshToken(),n=t.createWriteStream(r.join(this.storagePath,o)),a=yield e({url:"https://content.dropboxapi.com/2/files/download",method:"GET",responseType:"stream",headers:{Authorization:`Bearer ${s}`,"Dropbox-API-Arg":JSON.stringify({path:"/"+i})},maxContentLength:1/0,maxBodyLength:1/0});let d=0;return a.data.on("data",(e=>{d+=e.length,this.taskQueue.setDownloadedSize(d)})),yield j(a.data,n),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class M{constructor(e,t){this.config=e,this.storagePath=t,this.taskQueue=new E(1),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=0){return b(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}getClient(){return b(this,void 0,void 0,(function*(){try{if(this.client&&!1===this.client.closed)return this.client;let{url:e,username:t,password:r,dir:i,ssl:o,port:n}=this.config;const a=new s(0);a.ftp.verbose=!0;const d=a.access({host:e,port:parseInt(n),user:t,password:r,secure:"1"===o}),l=new Promise(((e,t)=>{setTimeout((()=>t(new Error("FTP connection timeout"))),5e3)}));return yield Promise.race([d,l]),this.client=a,a}catch(e){throw console.error("Error connecting to FTP server:",e),this.client=null,e}}))}uploadFile(e,t){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{let{dir:i}=this.config;i=i&&"KoodoReader"===this.baseFolder?i:this.baseFolder;const o=yield this.getClient(),s=()=>b(this,void 0,void 0,(function*(){yield o.ensureDir(r.dirname(i+"/"+t)),yield o.cd("/"),yield o.uploadFrom(r.join(this.storagePath,e),i+"/"+t)}));try{return yield s(),!0}catch(e){return console.error(e),!1}}catch(e){return console.error("Error in uploadFile:",e),!1}}))))))}))}downloadFile(e,i){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{let{dir:o}=this.config;o=o&&"KoodoReader"===this.baseFolder?o:this.baseFolder;const s=yield this.getClient(),n=t.createWriteStream(r.join(this.storagePath,i)),a=()=>b(this,void 0,void 0,(function*(){s.trackProgress((e=>{this.taskQueue.setDownloadedSize(e.bytes||0)})),yield s.downloadTo(n,o+"/"+e),s.trackProgress()}));try{return yield a(),!0}catch(e){return console.error(e),!1}}catch(e){return console.error("Error in downloadFile:",e),!1}}))))))}))}listFiles(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.listFilesWithoutQueue(e)}))))))}))}listFilesWithoutQueue(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return b(this,void 0,void 0,(function*(){let{dir:t}=this.config;t=t&&"KoodoReader"===this.baseFolder?t:this.baseFolder;const r=yield this.getClient(),i=()=>b(this,void 0,void 0,(function*(){return yield r.list(t+"/"+e)}));try{return(yield i()).map((e=>({name:e.name,size:e.size||0,type:e.isFile?"file":"folder",modified:e.modifiedAt?e.modifiedAt.toISOString():""})))}catch(e){return console.error(e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(e){return b(this,void 0,void 0,(function*(){let{dir:t}=this.config;t=t&&"KoodoReader"===this.baseFolder?t:this.baseFolder;const r=yield this.getClient(),i=()=>b(this,void 0,void 0,(function*(){yield r.remove(t+"/"+e)}));try{return yield i(),!0}catch(e){return console.error(e),!1}}))}}class B{constructor(e,t){this.isExp=!1,this.baseUrl="https://graph.microsoft.com/v1.0/me/drive/special/approot",this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new E(3),this.isExp=this.config.isExp||!1,this.baseUrl=this.isExp?"https://graph.microsoft.com/v1.0/me/drive/root":"https://graph.microsoft.com/v1.0/me/drive/special/approot",void 0===this.config.baseFolder?this.baseFolder=this.isExp?"KoodoReader":"":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return b(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();for(t=this.baseFolder+"/"+t;t.startsWith("/");)t=t.substring(1);let i,o=[];if(""===t)i=`${this.baseUrl}/children`;else{const e=encodeURIComponent(t);i=`${this.baseUrl}:/${e}:/children`}for(;i;){const t=yield e.get(i,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});if(t.status>=300)break;const s=t.data.value||[];o=o.concat(s),i=t.data["@odata.nextLink"]||""}return[...new Set(o.map((e=>({name:e.name,size:e.size||0,type:e.folder?"folder":"file",modified:e.lastModifiedDateTime}))))]}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();for(t=this.baseFolder+"/"+t;t.startsWith("/");)t=t.substring(1);const i=yield e.delete(`${this.baseUrl}:/${t}`,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});return!(i.status>=300)||(console.error("Error deleting file:",i),!0)}catch(e){return console.error("Error occurred during file delete:",e),!1}}))}refreshToken(){return b(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>b(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"microsoft",refresh_token:e});return t.data.access_token?(this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,t.data.access_token):""}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e,t){return b(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"microsoft",redirect_uri:t,code:e})).data}))}getAuthUrl(e){return`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${L}&scope=${this.isExp?"files.readwrite.all":"files.readwrite.appfolder"} offline_access&response_type=code&redirect_uri=${e}`}}const W=209715200;class N extends B{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){var s;let n=null;try{const s=yield this.refreshToken();let a=this.baseFolder+"/"+o;for(;a.startsWith("/");)a=a.substring(1);const d=r.join(this.storagePath,i),l=yield this.getFileSize(d),c=a.split(".").pop(),h=(F(c||""),`${this.baseUrl}:/${a}:/createUploadSession`),u=(yield e.post(h,{item:{"@microsoft.graph.conflictBehavior":"replace"}},{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}})).data.uploadUrl;n=yield t.promises.open(d,"r");let p=0,f=Buffer.alloc(W);for(;pthis.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=yield this.refreshToken();let n=this.baseFolder+"/"+i;for(;n.startsWith("/");)n=n.substring(1);const a=`${this.baseUrl}:/${n}:/content`;let d=(yield fetch(a,{headers:{Authorization:"Bearer "+s},redirect:"manual"})).headers.get("location");if(d){const i=yield e.get(d,{responseType:"stream"});let s=0;const n=t.createWriteStream(r.join(this.storagePath,o));return i.data.on("data",(e=>{s+=e.length,this.taskQueue.setDownloadedSize(s)})),yield new Promise(((e,t)=>{i.data.pipe(n),n.on("finish",(()=>{e()})),n.on("error",t)})),!0}return!1}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}getFileSize(e){return b(this,void 0,void 0,(function*(){try{return(yield t.promises.stat(e)).size}catch(e){throw e}}))}}class q{constructor(e,t){this.isExp=!1,this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new E(3),this.isExp=this.config.isExp||!1,this.baseFolder="KoodoReader"}retryOperation(e,t=3){return b(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}getFileId(t,r){return b(this,void 0,void 0,(function*(){const i=yield this.refreshToken(),o=`https://www.googleapis.com/drive/v3/files?q=name='${t}'+and+'${r}'+in+parents&fields=files(id,name)`;try{const t=yield e.get(o,{headers:{Authorization:"Bearer "+i}});if(0===t.data.files.length)return"";const r=t.data.files;return r.length>0?r[0].id:null}catch(e){return console.error("Error occurred during file list retrieval:",e),""}}))}checkFolder(t){return b(this,void 0,void 0,(function*(){t=this.baseFolder+"/"+t;const r=yield this.refreshToken();if(""===t)return"root";const i=t.split("/").filter((e=>""!==e.trim()));let o="root";for(const t of i){let i=yield this.getFolderId(t,o);if(!i){const s={name:t,mimeType:"application/vnd.google-apps.folder",parents:[o]};try{i=(yield e.post("https://www.googleapis.com/drive/v3/files",s,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.id}catch(e){throw console.error(`Error occurred during folder creation for ${t}:`,e),e}}o=i}return o}))}getFolderId(t,r){return b(this,void 0,void 0,(function*(){const i=yield this.refreshToken(),o=`https://www.googleapis.com/drive/v3/files?q=name='${t=encodeURIComponent(t)}'+and+mimeType='application/vnd.google-apps.folder'+and+'${r}'+in+parents&fields=files(id,name)`;try{const t=(yield e.get(o,{headers:{Authorization:`Bearer ${i}`}})).data.files;return t.length>0?t[0].id:null}catch(e){throw console.error("Error occurred during fetching folder ID:",e),e}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let i=yield this.checkFolder(t),o=[],s="",n=!0;for(;n;){let t=`https://www.googleapis.com/drive/v3/files?q='${i}'+in+parents&fields=nextPageToken,files(id,name,size,mimeType)&pageSize=1000`;s&&(t+=`&pageToken=${s}`);const a=yield e.get(t,{headers:{Authorization:`Bearer ${r}`}}),d=a.data.files||[];o=o.concat(d),s=a.data.nextPageToken,n=!!s}return[...new Set(o.map((e=>({name:e.name,size:e.size||0,type:"application/vnd.google-apps.folder"===e.mimeType?"folder":"file",modified:e.modifiedTime}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQue(e)}))))))}))}deleteFileWithoutQue(t){return b(this,void 0,void 0,(function*(){const r=t.split("/")[1],i=yield this.checkFolder(t),o=yield this.refreshToken(),s=yield this.getFileId(r,i);if(""===s)return console.error("File not found:",r),!0;try{const t=yield e.delete(`https://www.googleapis.com/drive/v3/files/${s}`,{headers:{Authorization:`Bearer ${o}`}});return console.error("File deleted:",t),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}refreshToken(){return b(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>b(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"google",refresh_token:e});return t.data.access_token?(this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,t.data.access_token):""}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e,t){return b(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"google",redirect_uri:t,code:e})).data}))}getAuthUrl(e){return`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${e}&prompt=consent&response_type=code&client_id=${z}&scope=https://www.googleapis.com/auth/${this.isExp?"drive":"drive.file"}&access_type=offline`}}class K extends q{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken();let n=i.split("/").pop(),a=o.split(".").pop(),d=F(a||""),l=o.split("/").slice(0,-1).join("/"),c=yield this.checkFolder(l),h=yield this.getFileId(n||"",c);const u={mimeType:d,name:n,parents:[c]},p=h?`https://www.googleapis.com/upload/drive/v3/files/${h}?uploadType=resumable`:"https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",f=(yield e({method:h?"PATCH":"POST",url:p,data:h?null:JSON.stringify(u),headers:{Authorization:"Bearer "+s,"Content-Type":"application/json; charset=UTF-8"},maxContentLength:1/0,maxBodyLength:1/0})).headers.location;let y=yield this.getFileSize(r.join(this.storagePath,i));const g=t.createReadStream(r.join(this.storagePath,i));yield e.put(f,g,{headers:{Authorization:"Bearer "+s,"Content-Type":"application/zip","Content-Range":`bytes 0-${y-1}/${y}`},maxContentLength:1/0,maxBodyLength:1/0});return!0}catch(e){return console.error("Error occurred during upload:",e),!1}}))))))}))}downloadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=yield this.refreshToken();let n=i.split("/").pop(),a=i.split("/").slice(0,-1).join("/"),d=yield this.checkFolder(a),l=yield this.getFileId(n||"",d);if(!l)return console.error("File not found"),!0;const c=`https://www.googleapis.com/drive/v3/files/${l}?alt=media`;return new Promise((i=>{const n=t.createWriteStream(r.join(this.storagePath,o));e({url:c,method:"GET",responseType:"stream",headers:{Authorization:"Bearer "+s},maxContentLength:1/0,maxBodyLength:1/0}).then((e=>{let t=0;e.data.on("data",(e=>{t+=e.length,this.taskQueue.setDownloadedSize(t)})),e.data.pipe(n),n.on("finish",(()=>{i(!0)})),n.on("error",(()=>{i(!1)}))})).catch((e=>{console.error("Error downloading file:",e),i(!1)}))}))}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}getFileSize(e){return b(this,void 0,void 0,(function*(){try{return(yield t.promises.stat(e)).size}catch(e){throw e}}))}}class H{constructor(e){this.config=e,this.taskQueue=new E(5),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=0){return b(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}shouldUsePathStyle(e){try{const t=new URL(e),r=t.hostname,i=/^(\d{1,3}\.){3}\d{1,3}$/.test(r),o=""!==t.port;return!i&&o}catch(e){return!0}}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return b(this,void 0,void 0,(function*(){let{endpoint:t,region:r,bucketName:i,accessKeyId:o,secretAccessKey:s,dir:d}=this.config;d=d&&"KoodoReader"===this.baseFolder?d:this.baseFolder;let l=d+"/"+e;for(;l.startsWith("/");)l=l.substring(1);""===l||l.endsWith("/")||(l+="/");const c=new n({endpoint:t,region:r,credentials:{accessKeyId:o,secretAccessKey:s},forcePathStyle:this.shouldUsePathStyle(t)});try{let e,t=[],r=[],o=!0;for(;o;){const s=yield c.send(new a({Bucket:i,Prefix:l,Delimiter:"/",ContinuationToken:e}));s.Contents&&(t=t.concat(s.Contents)),s.CommonPrefixes&&(r=r.concat(s.CommonPrefixes)),e=s.NextContinuationToken,o=!!e}let s=[];return t.forEach((e=>{if(!e.Key.endsWith("/")){const t=e.Key.substring(l.length);t.includes("/")||s.push({name:t,size:e.Size||0,type:"file",modified:e.LastModified?e.LastModified.toISOString():""})}})),r.forEach((e=>{const t=e.Prefix.substring(l.length).replace(/\/$/,"");t&&s.push({name:t,size:0,type:"folder",modified:""})})),s}catch(e){return console.error(e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){let{endpoint:t,region:r,bucketName:i,accessKeyId:o,secretAccessKey:s,dir:a}=this.config;a=a&&"KoodoReader"===this.baseFolder?a:this.baseFolder;const l=new n({endpoint:t,region:r,credentials:{accessKeyId:o,secretAccessKey:s},forcePathStyle:this.shouldUsePathStyle(t)});let c=a+"/"+e;for(;c.startsWith("/");)c=c.substring(1);try{return yield l.send(new d({Bucket:i,Key:c})),!0}catch(e){return console.error(e),!1}}))}}class J extends H{constructor(e,t){super(e),this.storagePath=t}uploadFile(e,i){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){let{endpoint:o,region:s,bucketName:a,accessKeyId:d,secretAccessKey:c,dir:h}=this.config;const u=new n({endpoint:o,region:s,credentials:{accessKeyId:d,secretAccessKey:c},forcePathStyle:this.shouldUsePathStyle(o)});h=h&&"KoodoReader"===this.baseFolder?h:this.baseFolder;let p=h+"/"+i;for(;p.startsWith("/");)p=p.substring(1);try{let i=yield u.send(new l({Bucket:a,Key:p,Body:t.createReadStream(r.join(this.storagePath,e))}));return 200===i.$metadata.httpStatusCode||(console.error("Error uploading file:",i),!1)}catch(e){return console.error("Error: ",e),!1}}))))))}))}downloadFile(e,i){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);let{endpoint:o,region:s,bucketName:a,accessKeyId:d,secretAccessKey:l,dir:h}=this.config;h=h&&"KoodoReader"===this.baseFolder?h:this.baseFolder;const u=(e,t,r,i)=>new Promise(((o,s)=>b(this,void 0,void 0,(function*(){const s=yield e.send(new c({Bucket:t,Key:r}));let n=0;s.Body?(s.Body.on("data",(e=>{n+=e.length,this.taskQueue.setDownloadedSize(n)})),s.Body.pipe(i),i.on("finish",(e=>{e&&o(!1),o(!0)}))):o(!1)})))),p=()=>new Promise(((c,p)=>{const f=new n({region:s,endpoint:o,credentials:{accessKeyId:d,secretAccessKey:l},forcePathStyle:this.shouldUsePathStyle(o)});let y=t.createWriteStream(r.join(this.storagePath,i)),g=h+"/"+e;for(;g.startsWith("/");)g=g.substring(1);u(f,a,g,y).then((e=>{c(!0)})).catch((e=>{console.error(e),c(!1)}))}));try{return yield p()}catch(e){return console.error(e),!1}}))))))}))}}class V{constructor(e){let{username:t,password:r,url:i,dir:o,AuthType:s,createClient:n}=e;void 0===e.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=e.baseFolder,o=o&&"KoodoReader"===this.baseFolder?o:this.baseFolder,this.username=t,this.password=r,this.url=i,this.dir=o,this.taskQueue=new E(5),this.AuthType=s,this.createClient=n}getClient(){return b(this,void 0,void 0,(function*(){return this.webdavClient||(this.url=yield this.handleUrlRedirection(this.url),this.webdavClient=this.createClient(this.url,{authType:this.AuthType.Password,username:this.username,password:this.password})),this.webdavClient}))}handleUrlRedirection(t){return b(this,void 0,void 0,(function*(){try{const r=yield e.head(t,{maxRedirects:0,validateStatus:()=>!0});return r.request&&r.request.responseURL&&r.request.responseURL!==t?r.request.responseURL:r.status>=300&&r.status<400&&r.headers.location?r.headers.location:t}catch(e){return console.info("Error handling URL redirection:",e),t}}))}retryOperation(e,t=1){return b(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return b(this,void 0,void 0,(function*(){const t=yield this.getClient();try{return(yield t.getDirectoryContents(this.dir+"/"+e)).filter((t=>"."!==t.filename&&".."!==t.filename&&t.filename!==e)).map((e=>({name:e.basename,size:e.size||0,type:"directory"===e.type?"folder":"file",modified:e.lastmod})))}catch(r){return r.response&&404===r.response.status&&(yield t.createDirectory(this.dir+"/"+e)),console.error("Error listing files:",r),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){const t=yield this.getClient();try{return yield t.deleteFile(this.dir+"/"+e),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}ensureDirectoryExists(e){return b(this,void 0,void 0,(function*(){let t=yield this.getClient();try{const r=e.replace(/^\/+|\/+$/g,"").split("/").filter((e=>e.length>0));let i="";for(const e of r)i=i?`${i}/${e}`:e,(yield t.exists(`/${i}`))||(yield t.createDirectory(`/${i}`));return!0}catch(e){return console.error("Error ensuring directory exists:",e),!1}}))}}class Y extends V{constructor(e,t){super(Object.assign(Object.assign({},e),{AuthType:h,createClient:u})),this.storagePath=t}uploadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{let s=yield this.getClient();const n=s.exists(r.dirname(this.dir+"/"+o)),a=new Promise(((e,t)=>{setTimeout((()=>t(new Error("WebDAV exists check timeout"))),5e3)}));!1===(yield Promise.race([n,a]))&&(yield this.ensureDirectoryExists(r.dirname(this.dir+"/"+o)));let d=s.createWriteStream(this.dir+"/"+o);return t.createReadStream(r.join(this.storagePath,i)).pipe(d),new Promise(((n,a)=>{d.on("finish",(()=>{n(!0)})),d.on("error",(a=>b(this,void 0,void 0,(function*(){console.error("Error occurred during file upload:",a);try{let a=t.readFileSync(r.join(this.storagePath,i)),d=s.getFileUploadLink(this.dir+"/"+o);const l=new URL(d);l.search="",d=l.toString();const c=Buffer.from(this.username+":"+this.password,"binary").toString("base64");yield e.put(d,a,{headers:{Authorization:"Basic "+c},maxContentLength:1/0,maxBodyLength:1/0});n(!0)}catch(e){console.error("Error occurred during file upload:",e),n(!1)}}))))}))}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(e,i){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){if(this.taskQueue.setDownloadedSize(0),-1===e.indexOf("."))return new ArrayBuffer(0);try{let o=yield this.getClient();if(!1===(yield o.exists(this.dir+"/"+e)))return!0;let s=0,n=t.createWriteStream(r.join(this.storagePath,i)),a=o.createReadStream(this.dir+"/"+e);return a.on("data",(e=>{s+=e.length,this.taskQueue.setDownloadedSize(s)})),a.pipe(n),new Promise(((e,t)=>{n.on("finish",(()=>{e(!0)})),n.on("error",(t=>{e(!1)}))}))}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class X{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new E(3),void 0===this.config.baseFolder?this.baseFolder="/KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return b(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){var r,i;return b(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken();for(t=this.baseFolder+"/"+t;t.startsWith("/");)t=t.substring(1);let s=[],n=0;const a=1e3;let d=!0;for(;d;){const l=yield e.get("https://cloud-api.yandex.net/v1/disk/resources",{headers:{Authorization:`OAuth ${o}`,"Content-Type":"application/json"},params:{path:t?`/${t}`:"/",limit:a,offset:n,fields:"_embedded.items.name,_embedded.items.size,_embedded.items.type,_embedded.items.modified,_embedded.total"}}),c=(null===(r=l.data._embedded)||void 0===r?void 0:r.items)||[];s=s.concat(c);const h=(null===(i=l.data._embedded)||void 0===i?void 0:i.total)||0;n+=c.length,d=n({name:e.name,size:e.size||0,type:"file"===e.type?"file":"folder",modified:e.modified}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();for(t=this.baseFolder+"/"+t;t.startsWith("/");)t=t.substring(1);const i=yield e.delete("https://cloud-api.yandex.net/v1/disk/resources",{headers:{Authorization:`OAuth ${r}`,"Content-Type":"application/json"},params:{path:t?`/${t}`:"/",permanently:!1}});return 202===i.status||204===i.status}catch(e){return console.error("Error deleting file:",e),!1}}))}ensureDirectoryExists(t){var r,i;return b(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken(),s=t.split("/").filter((e=>e.length>0));let n="";for(const t of s){n+="/"+t;try{yield e.get("https://cloud-api.yandex.net/v1/disk/resources",{headers:{Authorization:`OAuth ${o}`,"Content-Type":"application/json"},params:{path:n}})}catch(t){if(404!==(null===(r=t.response)||void 0===r?void 0:r.status))return console.error("Error checking directory:",t),!1;try{yield e.put(`https://cloud-api.yandex.net/v1/disk/resources?path=${encodeURIComponent(n)}`,null,{headers:{Authorization:`OAuth ${o}`}})}catch(e){if(409!==(null===(i=e.response)||void 0===i?void 0:i.status))return console.error("Error creating directory:",e),!1}}}return!0}catch(e){return console.error("Error ensuring directory exists:",e),!1}}))}refreshToken(){return b(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>b(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"yandex",refresh_token:e});return t.data.access_token?(this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,t.data.access_token):""}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e,t){return b(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"yandex",redirect_uri:t,code:e})).data}))}getAuthUrl(e){return`https://oauth.yandex.com/authorize?response_type=code&client_id=${C}&redirect_uri=${e}&force_confirm=true`}}const G=i(o.pipeline);class Z extends X{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken();let n=this.baseFolder+"/"+o;for(;n.startsWith("/");)n=n.substring(1);const a=n.substring(0,n.lastIndexOf("/"));if(a){if(!(yield this.ensureDirectoryExists(a)))return console.error("Failed to create directory:",a),!1}const d=yield e.get("https://cloud-api.yandex.net/v1/disk/resources/upload",{headers:{Authorization:`OAuth ${s}`,"Content-Type":"application/json"},params:{path:`/${n}`,overwrite:!0}});if(200!==d.status)return console.error("Error getting upload URL:",d),!1;const l=d.data.href,c=t.createReadStream(r.join(this.storagePath,i));return yield e.put(l,c,{headers:{"Content-Type":"application/octet-stream"},maxContentLength:1/0,maxBodyLength:1/0}),!0}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);let s=this.baseFolder+"/"+i;for(;s.startsWith("/");)s=s.substring(1);try{const i=yield this.refreshToken(),n=yield e.get("https://cloud-api.yandex.net/v1/disk/resources/download",{headers:{Authorization:`OAuth ${i}`,"Content-Type":"application/json"},params:{path:`/${s}`}});if(200!==n.status)return console.error("Error getting download URL:",n),!1;const a=n.data.href,d=t.createWriteStream(r.join(this.storagePath,o)),l=yield e({url:a,method:"GET",responseType:"stream",maxContentLength:1/0,maxBodyLength:1/0});let c=0;return l.data.on("data",(e=>{c+=e.length,this.taskQueue.setDownloadedSize(c)})),yield G(l.data,d),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class ee{constructor(e,t){this.config=e,this.storagePath=t,this.taskQueue=new E(5),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=0){return b(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}getClient(){return b(this,void 0,void 0,(function*(){try{if(this.client)return this.client;let{url:e,username:t,password:r,dir:i,port:o}=this.config;const s=new p,n=s.connect({host:e||"",port:o||22,username:t||"",password:r||""}),a=new Promise(((e,t)=>{setTimeout((()=>t(new Error("SFTP connection timeout"))),5e3)}));return yield Promise.race([n,a]),this.client=s,s}catch(e){throw console.error("Error connecting to SFTP server:",e),this.client=null,e}}))}uploadFile(e,i){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{let{dir:o}=this.config;o=o&&"KoodoReader"===this.baseFolder?o:this.baseFolder;let s=yield this.getClient();const n=()=>new Promise(((n,a)=>b(this,void 0,void 0,(function*(){let a=t.createReadStream(r.join(this.storagePath,e)),d="/"+o+"/"+i,l="/"+o+"/"+r.dirname(i);(yield s.exists(l))||(yield s.mkdir(l,!0)),s.put(a,d).then((()=>{n(!0)})).catch((e=>{console.error(e.message),n(!1)}))}))));try{return yield n()}catch(e){return console.error(e),!1}}catch(e){return console.error("Error in uploadFile:",e),!1}}))))))}))}downloadFile(e,i){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{let{dir:o}=this.config;o=o&&"KoodoReader"===this.baseFolder?o:this.baseFolder;let s=yield this.getClient();const n=()=>new Promise(((n,a)=>b(this,void 0,void 0,(function*(){let a="/"+o+"/"+e,d=r.join(this.storagePath,i),l=t.createWriteStream(d);s.get(a,l).then((()=>{this.taskQueue.setDownloadedSize(l.bytesWritten||0),n(!0)})).catch((e=>{console.error(e.message),n(!1)}))}))));try{return yield n()}catch(e){return console.error(e),!1}}catch(e){return console.error("Error in downloadFile:",e),!1}}))))))}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return b(this,void 0,void 0,(function*(){let{dir:t}=this.config;t=t&&"KoodoReader"===this.baseFolder?t:this.baseFolder;let r=yield this.getClient();const i=()=>new Promise(((i,o)=>b(this,void 0,void 0,(function*(){let o="/"+t+"/"+e;(yield r.exists(o))||(yield r.mkdir(o,!0),i([])),r.list(o).then((e=>{i(e.map((e=>({name:e.name,size:e.size||0,type:"d"===e.type?"folder":"file",modified:e.modifyTime}))))})).catch((e=>b(this,void 0,void 0,(function*(){console.error(e.message,"list file error"),i([])}))))}))));try{return yield i()}catch(e){return console.error(e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){let{dir:t}=this.config;t=t&&"KoodoReader"===this.baseFolder?t:this.baseFolder;let r=yield this.getClient();try{return yield new Promise(((i,o)=>{let s="/"+t+"/"+e;r.delete(s).then((()=>{i(!0)})).catch((e=>{console.error(e.message),i(!1)}))}))}catch(e){return console.error(e),!1}}))}}class te{downloadFile(e,t){return b(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}uploadFile(e,t){return b(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}listFiles(e){return b(this,void 0,void 0,(function*(){return new Promise((e=>{e([])}))}))}authToken(e,t){return b(this,void 0,void 0,(function*(){return new Promise((e=>{e("")}))}))}getAuthUrl(){return""}}class re{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new E(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return b(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}getFolderIdByPath(t){return b(this,void 0,void 0,(function*(){if(""==t)return"0";const r=yield this.refreshToken(),i=t.split("/");let o="0";for(const t of i){const i=`https://api.box.com/2.0/folders/${o}/items?fields=id,name&type=folder&limit=1000`;try{const s=(yield e.get(i,{headers:{Authorization:`Bearer ${r}`}})).data.entries.find((e=>e.name===t&&"folder"===e.type));if(s)o=s.id;else{const i={name:t,parent:{id:o},type:"folder"};o=(yield e.post("https://api.box.com/2.0/folders",i,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.id}}catch(e){return console.error("Error occurred during folder creation:",e),""}}return o}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let i=this.baseFolder+"/"+t;for(;i.startsWith("/");)i=i.substring(1);let o=yield this.getFolderIdByPath(i),s=[],n=0,a=!0;const d=1e3;for(;a;){const t=yield e.get(`https://api.box.com/2.0/folders/${o}/items`,{params:{limit:d,offset:n},headers:{Authorization:`Bearer ${r}`}}),i=t.data.entries||[];s=s.concat(i),n+=i.length,a=i.length===d&&t.data.total_count>n}return[...new Set(s.map((e=>({name:e.name,size:e.size||0,type:e.type,modified:e.content_modified_at}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=t.substring(0,t.lastIndexOf("/")),o=t.substring(t.lastIndexOf("/")+1);let s=this.baseFolder+"/"+i;for(;s.startsWith("/");)s=s.substring(1);const n=yield this.getFolderIdByPath(s);if(!n)return!0;const a=`https://api.box.com/2.0/folders/${n}/items?fields=id,name&type=file&limit=1000`,d=(yield e.get(a,{headers:{Authorization:`Bearer ${r}`}})).data.entries.find((e=>e.name===o&&"file"===e.type));return!d||(yield e.delete(`https://api.box.com/2.0/files/${d.id}`,{headers:{Authorization:`Bearer ${r}`}}),!0)}catch(e){return console.error("Error deleting file:",e),!1}}))}refreshToken(){return b(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>b(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"boxnet",refresh_token:e});if(!t.data.access_token)return"";this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,this.config.refresh_token=t.data.refresh_token;let r=yield this.thirdpartyRequest.encryptToken({token:JSON.stringify({refresh_token:t.data.refresh_token,access_token:t.data.access_token,expires_at:this.config.expires_at})});return 200===r.code&&(yield this.thirdpartyRequest.TokenService.setToken("boxnet_token",r.data.encrypted_token)),t.data.access_token}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e,t){return b(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"boxnet",redirect_uri:t,code:e})).data}))}getAuthUrl(e){return`https://account.box.com/api/oauth2/authorize?${new URLSearchParams({response_type:"code",client_id:A,redirect_uri:e,grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}).toString()}`}}class ie extends re{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken(),n=o.substring(0,o.lastIndexOf("/")),a=o.substring(o.lastIndexOf("/")+1);let d=this.baseFolder+"/"+n;for(;d.startsWith("/");)d=d.substring(1);const l=yield this.getFolderIdByPath(d);if(!l)throw new Error("Folder not found");const c=yield this.listFiles(n);c.find((e=>e===a))&&(yield this.deleteFileWithoutQueue(n+"/"+a));const h=new f,u=JSON.stringify({name:a,parent:{id:l}});h.append("attributes",u),h.append("file",t.createReadStream(r.join(this.storagePath,i)));const p=yield e.post("https://upload.box.com/api/2.0/files/content",h,{headers:Object.assign({Authorization:`Bearer ${s}`},h.getHeaders()),maxContentLength:1/0,maxBodyLength:1/0});return!(p.status>=300)||(console.error("Error occurred during file upload:",p),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=yield this.refreshToken(),n=i.substring(0,i.lastIndexOf("/")),a=i.substring(i.lastIndexOf("/")+1);let d=this.baseFolder+"/"+n;for(;d.startsWith("/");)d=d.substring(1);const l=yield this.getFolderIdByPath(d);if(!l)return console.error("Folder not found"),!0;const c=`https://api.box.com/2.0/folders/${l}/items?fields=id,name&type=file&limit=1000`,h=(yield e.get(c,{headers:{Authorization:`Bearer ${s}`}})).data.entries.find((e=>e.name===a&&"file"===e.type));if(!h)return console.error("File not found:",a),!0;const u=yield e({url:`https://api.box.com/2.0/files/${h.id}/content`,method:"get",responseType:"stream",headers:{Authorization:`Bearer ${s}`}});return yield new Promise(((e,i)=>{let s=0;const n=t.createWriteStream(r.join(this.storagePath,o));u.data.on("data",(e=>{s+=e.length,this.taskQueue.setDownloadedSize(s)})),u.data.pipe(n),n.on("finish",e),n.on("error",i)})),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class oe{constructor(e){this.folderCreationLocks=new Map,this.config=e,this.taskQueue=new E(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=2){return b(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}getStorage(){return b(this,void 0,void 0,(function*(){if(this.storage)return this.storage;let{email:e,password:t}=this.config;return this.storage=yield new y({email:e,password:t,userAgent:"KoodoReader/1.0"}).ready,this.storage}))}getRoot(){return b(this,void 0,void 0,(function*(){if(this.root)return this.root;const e=(yield this.getStorage()).root;if(""===this.baseFolder)return this.root=e,this.root;let t=e.children.find((e=>e.name===this.baseFolder&&e.directory));return t||(t=yield e.mkdir(this.baseFolder)),this.root=t,this.root}))}createFolder(e,t){return b(this,void 0,void 0,(function*(){const r=`${e.nodeId}_${t}`;if(this.folderCreationLocks.has(r))return yield this.folderCreationLocks.get(r);const i=(()=>b(this,void 0,void 0,(function*(){try{let r=e.children.find((e=>e.name===t&&e.directory));return r||(r=yield e.mkdir(t),r)}finally{this.folderCreationLocks.delete(r)}})))();return this.folderCreationLocks.set(r,i),yield i}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return b(this,void 0,void 0,(function*(){try{let t=yield this.getRoot();if(e){const r=e.split("/").filter((e=>e));for(const e of r){const r=t.children.find((t=>t.name===e&&t.directory));if(!r)return[];t=r}}return t.children.map((e=>({name:e.name,size:e.size||0,type:e.directory?"folder":"file",modified:e.timestamp?new Date(1e3*e.timestamp).toISOString():""})))}catch(e){return console.error("Error listing MEGA files:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(e){return b(this,void 0,void 0,(function*(){try{let t=yield this.getRoot();const r=e.split("/"),i=r.pop();for(const e of r){if(!e)continue;const r=t.children.find((t=>t.name===e&&t.directory));if(!r)return!0;t=r}const o=t.children.find((e=>e.name===i&&!e.directory));return!o||(yield o.delete(),!0)}catch(e){return console.error("Error deleting MEGA file:",e),!1}}))}}class se extends oe{constructor(e,t){super(e),this.storagePath=t}uploadFile(e,i){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{let o=yield this.getRoot();const s=i.split("/"),n=s.pop()||"";for(const e of s){if(!e)continue;let t=o.children.find((t=>t.name===e&&t.directory));t||(t=yield this.createFolder(o,e)),o=t}const a=o.children.find((e=>e.name===n&&!e.directory));a&&(yield a.delete());const d=t.createReadStream(r.join(this.storagePath,e)),l=t.statSync(r.join(this.storagePath,e)).size;return yield o.upload({name:n,size:l},d).complete,!0}catch(e){return console.error("Error occurred during MEGA file upload:",e),!1}}))))))}))}downloadFile(e,i){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{let o=yield this.getRoot();const s=e.split("/"),n=s.pop()||"";for(const e of s){if(!e)continue;const t=o.children.find((t=>t.name===e&&t.directory));if(!t)return!0;o=t}const a=o.children.find((e=>e.name===n&&!e.directory));if(!a)return!0;const d=t.createWriteStream(r.join(this.storagePath,i));let l=0;return new Promise((e=>{const t=a.download();t.on("data",(e=>{l+=e.length,this.taskQueue.setDownloadedSize(l)})),t.pipe(d),d.on("finish",(()=>e(!0))),d.on("error",(t=>{console.error("Error writing file:",t),e(!1)}))}))}catch(e){return console.error("Error occurred during MEGA file download:",e),!1}}))))))}))}}class ne{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.driveId="",this.refreshTokenPromise=null,this.taskQueue=new E(1),void 0===this.config.baseFolder?this.baseFolder="/KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return b(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}getDriveId(){return b(this,void 0,void 0,(function*(){if(this.driveId)return this.driveId;const t=yield this.refreshToken(),r=yield e.post("https://openapi.alipan.com/adrive/v1.0/user/getDriveInfo",{},{headers:{Authorization:`Bearer ${t}`}});return this.driveId=r.data.default_drive_id,this.driveId}))}getFolderIdByPath(t){return b(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),i=yield this.getDriveId();try{try{const o=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:i,file_path:t},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});if(o.data)return o.data.file_id}catch(o){const s=t.split("/").filter((e=>e));let n="",a="root";for(const t of s){n+="/"+t;try{a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:i,file_path:n},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.file_id}catch(o){a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:i,parent_file_id:a,name:t,type:"folder",check_name_mode:"refuse"},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.file_id}}return a}}catch(e){return console.error("Error getting/creating folder by path:",e),""}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=yield this.getDriveId(),o=yield this.getFolderIdByPath(this.baseFolder+"/"+t);let s=[],n="",a=!0;for(;a;){const t=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/list",{drive_id:i,parent_file_id:o,marker:n||void 0},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}),d=t.data.items.filter((e=>!e.punish_flag||2!==e.punish_flag))||[];s=s.concat(d),n=t.data.next_marker,a=!!n&&100===d.length}return[...new Set(s.map((e=>({name:e.name,size:e.size,type:e.type,modified:e.updated_at}))))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=yield this.getDriveId(),o=yield this.getFolderIdByPath(this.baseFolder+"/"+t);return!o||(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/delete",{drive_id:i,file_id:o},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}),!0)}catch(e){return console.error("Error deleting file:",e),!1}}))}checkExists(t){var r;return b(this,void 0,void 0,(function*(){try{const i=yield this.refreshToken(),o=yield this.getDriveId(),s=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:o,file_path:t},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}});(null===(r=s.data)||void 0===r?void 0:r.file_id)&&(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/recyclebin/trash",{drive_id:o,file_id:s.data.file_id},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}))}catch(e){}}))}refreshToken(){return b(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>b(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"adrive",refresh_token:e});if(!t.data.access_token)return"";this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,this.config.refresh_token=t.data.refresh_token;let r=yield this.thirdpartyRequest.encryptToken({token:JSON.stringify({refresh_token:t.data.refresh_token,access_token:t.data.access_token,expires_at:this.config.expires_at})});return 200===r.code&&(yield this.thirdpartyRequest.TokenService.setToken("adrive_token",r.data.encrypted_token)),t.data.access_token}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e,t){return b(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"adrive",redirect_uri:t,code:e})).data}))}getAuthUrl(e){return`https://openapi.alipan.com/oauth/authorize?${new URLSearchParams({response_type:"code",client_id:Q,redirect_uri:e,grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}).toString()}`}}class ae extends ne{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken(),n=yield this.getDriveId(),a=o.substring(0,o.lastIndexOf("/")),d=o.substring(o.lastIndexOf("/")+1);yield this.deleteFileWithoutQueue(o);const l=yield this.getFolderIdByPath(this.baseFolder+"/"+a),c=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:n,parent_file_id:l,name:d,type:"file",check_name_mode:"ignore"},{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}),{file_id:h,upload_id:u,part_info_list:p}=c.data,f=yield t.promises.readFile(r.join(this.storagePath,i));return yield fetch(p[0].upload_url,{method:"PUT",body:f,headers:{"Content-Length":t.statSync(r.join(this.storagePath,i)).size.toString()}}),yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/complete",{drive_id:n,file_id:h,upload_id:u},{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}),!0}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=yield this.refreshToken(),n=yield this.getDriveId(),a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:n,file_path:this.baseFolder+"/"+i},{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}})).data.file_id,d=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/getDownloadUrl",{drive_id:n,file_id:a},{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}),l=yield e({url:d.data.url,method:"get",responseType:"stream"});let c=0;const h=t.createWriteStream(r.join(this.storagePath,o+".temp"));return l.data.on("data",(e=>{c+=e.length,this.taskQueue.setDownloadedSize(c)})),l.data.pipe(h),new Promise((e=>{h.on("finish",(()=>{t.renameSync(r.join(this.storagePath,o+".temp"),r.join(this.storagePath,o)),e(!0)})),h.on("error",(t=>{console.error("Error occurred during file download:",t),e(!1)}))}))}catch(e){return console.error("Error downloading file:",e),!1}}))))))}))}}class de{constructor(e,t){this.baseUrl="https://api.pcloud.com",this.config=e,this.thirdpartyRequest=t,this.taskQueue=new E(3),this.baseUrl="2"===e.region?"https://eapi.pcloud.com":"https://api.pcloud.com"}retryOperation(e,t=3){return b(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}checkFolderExists(t,r){return b(this,void 0,void 0,(function*(){try{return 0===(yield e.get(`${this.baseUrl}/listfolder`,{params:{access_token:r,path:`/${t}`}})).data.result}catch(e){return console.error("Error checking folder:",e),!1}}))}createFolder(t,r){return b(this,void 0,void 0,(function*(){try{return 0===(yield e.get(`${this.baseUrl}/createfolderifnotexists`,{params:{access_token:r,path:`/${t}`}})).data.result}catch(e){return console.error("Error creating folder:",e),!1}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=yield e.get(`${this.baseUrl}/listfolder`,{params:{access_token:r,path:"/"+t,recursive:0}});return 0!==i.data.result?[]:i.data.metadata.contents.map((e=>({name:e.name,size:e.size||0,type:e.isfolder?"folder":"file",modified:e.modified})))}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=yield e.get(`${this.baseUrl}/deletefile`,{params:{access_token:r,path:"/"+t}});return 0===i.data.result||(console.error("Error deleting file:",i.data),!0)}catch(e){return console.error("Error occurred during file delete:",e),!1}}))}refreshToken(){return b(this,void 0,void 0,(function*(){return this.config.refresh_token}))}authToken(e,t){return b(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"pcloud",redirect_uri:t,code:e})).data}))}getAuthUrl(e){return`https://my.pcloud.com/oauth2/authorize?client_id=${P}&response_type=code&redirect_uri=${e}`}}class le extends de{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken(),n=o.split("/").slice(0,-1).join("/");if(!(yield this.checkFolderExists(n,s))){if(!(yield this.createFolder(n,s)))return!1}const a=r.join(this.storagePath,i),d=t.createReadStream(a),l=t.statSync(a),c=r.basename(i),h=yield e({method:"put",url:`${this.baseUrl}/uploadfile`,params:{access_token:s,path:`/${n}`,renew:1,filename:c},data:d,headers:{"Content-Length":l.size,"Content-Type":"application/octet-stream"},maxContentLength:1/0,maxBodyLength:1/0});return 0===h.data.result||(console.error("Error uploading file:",h.data),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=yield this.refreshToken(),n=yield e.get(`${this.baseUrl}/getfilelink`,{params:{access_token:s,path:`/${i}`}});if(0!==n.data.result)return console.error("Error getting file link:",n.data),!1;const a=r.join(this.storagePath,o),d=t.createWriteStream(a),l=`https://${n.data.hosts[0]}${n.data.path}`,c=yield e({method:"get",url:l,responseType:"stream",maxContentLength:1/0,maxBodyLength:1/0});return new Promise((e=>{let t=0;c.data.on("data",(e=>{t+=e.length,this.taskQueue.setDownloadedSize(t)})),c.data.pipe(d),d.on("finish",(()=>{e(!0)})),d.on("error",(t=>{console.error("Error writing file:",t),e(!1)}))}))}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class ce{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new E(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=1){return b(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let i=this.baseFolder;t&&""!==t.trim()&&(i=i+"/"+t),i=i.replace(/\/+/g,"/"),i.startsWith("/")&&(i=i.substring(1));let o=[],s=0;const n=1e3;for(;;){const t=yield e.get("https://pan.baidu.com/rest/2.0/xpan/file",{params:{method:"list",access_token:r,dir:"/"+i,start:s,limit:n,order:"name",desc:0,web:1,folder:0},headers:{"User-Agent":"pan.baidu.com"}});if(t.status>=300||0!==t.data.errno){console.error("百度网盘API错误:",t.data);break}const a=t.data.list||[];if(0===a.length)break;if(o=o.concat(a),a.length({name:e.server_filename,size:e.size||0,type:e.isdir?"folder":"file",modified:new Date(1e3*e.server_mtime).toISOString(),path:e.path})))}catch(e){return console.error("获取百度网盘文件列表时发生错误:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let i=this.baseFolder+"/"+t;i=i.replace(/\/+/g,"/"),i.startsWith("/")&&(i=i.substring(1));const o=new URLSearchParams({async:"0",filelist:JSON.stringify(["/"+i])}),s=yield e.post(`https://pan.baidu.com/rest/2.0/xpan/file?method=filemanager&access_token=${r}&opera=delete`,o.toString(),{headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":"pan.baidu.com"}});if(0!==s.data.errno)return console.error("百度网盘删除文件API错误:",s.data),-9===s.data.errno?console.error("文件不存在"):111===s.data.errno?console.error("有其他异步任务正在执行"):-7===s.data.errno&&console.error("文件名非法"),!1;const n=s.data.info||[];for(const e of n)if(0!==e.errno)return console.error(`文件删除失败: ${e.path}, 错误码: ${e.errno}`),!1;return!0}catch(e){return console.error("删除文件时发生错误:",e),!1}}))}refreshToken(){return b(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>b(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"dubox",refresh_token:e});if(!t.data.access_token)return"";this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,this.config.refresh_token=t.data.refresh_token;let r=yield this.thirdpartyRequest.encryptToken({token:JSON.stringify({refresh_token:t.data.refresh_token,access_token:t.data.access_token,expires_at:this.config.expires_at})});return 200===r.code&&(yield this.thirdpartyRequest.TokenService.setToken("dubox_token",r.data.encrypted_token)),t.data.access_token}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e,t){return b(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"dubox",redirect_uri:t,code:e})).data}))}getAuthUrl(e){return`https://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id=${I}&redirect_uri=${e}&scope=basic,netdisk&device_id=119827642&display=page&qrcode=1`}}const he=4194304;class ue extends ce{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){var s;let n=null;try{const s=yield this.refreshToken();let a=this.baseFolder+"/"+o;a=a.replace(/\/+/g,"/"),a.startsWith("/")&&(a=a.substring(1));const d=r.join(this.storagePath,i),l=yield this.getFileSize(d),{contentMd5:c,sliceMd5:h,blockList:u}=yield this.calculateFileMd5(d,l),p=new URLSearchParams({path:"/"+a,size:l.toString(),isdir:"0",autoinit:"1",rtype:"3",block_list:JSON.stringify(u),"content-md5":c,"slice-md5":h,local_ctime:Math.floor(Date.now()/1e3).toString(),local_mtime:Math.floor(Date.now()/1e3).toString()}),y=yield e.post(`https://pan.baidu.com/rest/2.0/xpan/file?method=precreate&access_token=${s}`,p.toString(),{headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":"pan.baidu.com"}});if(0!==y.data.errno)return console.error("预上传失败:",y.data),-7===y.data.errno?console.error("文件或目录名错误或无权访问"):-10===y.data.errno&&console.error("容量不足"),!1;const g=y.data.uploadid,m=y.data.block_list||[];if(0===m.length)return!0;const k=yield this.getUploadDomain(s,"/"+a,g);if(!k)return console.error("获取上传域名失败"),!1;n=yield t.promises.open(d,"r");for(const t of m){const r=t*he,i=Math.min(he,l-r),o=Buffer.alloc(i),{bytesRead:d}=yield n.read(o,0,i,r);if(0===d)break;const c=o.slice(0,d),h=u[t],p=new f;p.append("file",c,{filename:`chunk_${t}`,contentType:"application/octet-stream",knownLength:c.length});const y=`${k}/rest/2.0/pcs/superfile2?method=upload&access_token=${s}&type=tmpfile&path=${encodeURIComponent("/"+a)}&uploadid=${g}&partseq=${t}`,m=yield e.post(y,p,{headers:Object.assign(Object.assign({"User-Agent":"pan.baidu.com"},p.getHeaders()),{"Content-Length":p.getLengthSync().toString()}),maxContentLength:1/0,maxBodyLength:1/0,timeout:0});if(m.status>=300)throw 31024===m.data.errno?console.error("没有申请上传权限"):31299===m.data.errno?console.error("第一个分片的大小小于4MB"):31364===m.data.errno?console.error("超出分片大小限制"):31363===m.data.errno&&console.error("分片缺失"),new Error(`分片上传失败: ${JSON.stringify(m.data)}`);const v=m.data.md5;v&&v!==h&&console.warn(`分片 ${t} MD5不匹配: 期望 ${h}, 实际 ${v}`)}const v=new URLSearchParams({path:"/"+a,size:l.toString(),isdir:"0",block_list:JSON.stringify(u),uploadid:g,rtype:"3",local_ctime:Math.floor(Date.now()/1e3).toString(),local_mtime:Math.floor(Date.now()/1e3).toString()}),T=yield e.post(`https://pan.baidu.com/rest/2.0/xpan/file?method=create&access_token=${s}`,v.toString(),{headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":"pan.baidu.com"}});return 0===T.data.errno||(console.error("创建文件失败:",T.data),-7===T.data.errno?console.error("文件或目录名错误或无权访问"):-8===T.data.errno?console.error("文件或目录已存在"):-10===T.data.errno?console.error("云端容量已满"):10===T.data.errno?console.error("创建文件失败,一般是分片问题"):31190===T.data.errno?console.error("文件不存在,一般是分片上传阶段有问题"):31355===T.data.errno?console.error("参数异常,一般是uploadid参数传的有问题"):31365===T.data.errno&&console.error("文件总大小超限"),!1)}catch(e){return console.error("文件上传过程中发生错误:",(null===(s=e.response)||void 0===s?void 0:s.data)||e.message||e),!1}finally{n&&(yield n.close())}}))))))}))}getUploadDomain(t,r,i){return b(this,void 0,void 0,(function*(){try{const o=yield e.get("https://d.pcs.baidu.com/rest/2.0/pcs/file",{params:{method:"locateupload",appid:"250528",access_token:t,path:r,uploadid:i,upload_version:"2.0"},headers:{"User-Agent":"pan.baidu.com"}});if(0!==o.data.error_code)return console.error("获取上传域名失败:",o.data),null;const s=o.data.servers||[],n=s.find((e=>e.server.startsWith("https://")));return n?n.server:s.length>0?s[0].server:(console.error("没有可用的上传服务器"),null)}catch(e){return console.error("获取上传域名时出错:",e),null}}))}calculateFileMd5(e,r){return b(this,void 0,void 0,(function*(){const i=yield t.promises.open(e,"r");try{const e=g.createHash("md5"),t=[];let o="",s=0;for(;sthis.retryOperation((()=>b(this,void 0,void 0,(function*(){var s,n;this.taskQueue.setDownloadedSize(0);try{const a=yield this.refreshToken();let d,l=this.baseFolder+"/"+i;l=l.replace(/\/+/g,"/"),l.startsWith("/")&&(l=l.substring(1));const c=yield e.get("https://pan.baidu.com/rest/2.0/xpan/file",{params:{method:"list",access_token:a,dir:"/"+l.substring(0,l.lastIndexOf("/")),web:1},headers:{"User-Agent":"pan.baidu.com"}});if(0!==c.data.errno)return console.error("获取文件列表失败:",c.data),!1;const h=l.split("/").pop(),u=null===(s=c.data.list)||void 0===s?void 0:s.find((e=>e.server_filename===h));if(!u)return console.error("文件不存在:",i),!1;const p=yield e.get("https://pan.baidu.com/rest/2.0/xpan/multimedia",{params:{method:"filemetas",access_token:a,fsids:JSON.stringify([u.fs_id]),dlink:1},headers:{"User-Agent":"pan.baidu.com"}});if(0!==p.data.errno||!(null===(n=p.data.list)||void 0===n?void 0:n[0]))return console.error("获取下载链接失败:",p.data),!1;d=p.data.list[0];const f=d.dlink,y=yield e.get(f,{responseType:"stream",params:{access_token:a},headers:{"User-Agent":"pan.baidu.com"}});let g=0;const m=t.createWriteStream(r.join(this.storagePath,o));y.data.on("data",(e=>{g+=e.length,this.taskQueue.setDownloadedSize(g)})),yield new Promise(((e,t)=>{y.data.pipe(m),m.on("finish",(()=>{e()})),m.on("error",t)}));return(yield this.getFileSize(r.join(this.storagePath,o)))===d.size||(console.error("Downloaded file size does not match expected size."),yield t.promises.unlink(r.join(this.storagePath,o)),!1)}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}getFileSize(e){return b(this,void 0,void 0,(function*(){try{return(yield t.promises.stat(e)).size}catch(e){throw e}}))}}class pe{constructor(e){this.username=e.username,this.password=e.password,this.url=e.url,this.refreshTokenPromise=null,this.taskQueue=new E(3)}retryOperation(e,t=1){return b(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{return(yield e.get(`${this.url}/list`,{params:{dir:t},auth:{username:this.username,password:this.password}})).data.files.map((e=>({name:e.name,size:e.size||0,type:"file"===e.type?"file":"folder",modified:e.modifiedTime})))||[]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{return(yield e.delete(`${this.url}/delete`,{params:{dir:t.split("/").slice(0,-1).join("/")||"",filename:t.split("/").pop()},auth:{username:this.username,password:this.password}})).data.success}catch(e){return console.error("Error deleting file:",e),!1}}))}}const fe=i(o.pipeline);class ye extends pe{constructor(e,t){super(e),this.storagePath=t}getAuthHeader(){return`Basic ${btoa(`${this.username}:${this.password}`)}`}uploadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{o.split("/").pop();const s=o.substring(0,o.lastIndexOf("/"))||"";let n=this.listFiles("");const a=new Promise(((e,t)=>{setTimeout((()=>t(new Error("Docker connection timeout"))),5e3)}));yield Promise.race([n,a]);const d=t.createReadStream(r.join(this.storagePath,i)),l=new f;l.append("file",d);const c=yield e.post(`${this.url}/upload?dir=${encodeURIComponent(s)}`,l,{headers:Object.assign(Object.assign({},l.getHeaders()),{Authorization:this.getAuthHeader()}),maxContentLength:1/0,maxBodyLength:1/0});return!(c.status>=300)||(console.error("Error occurred during file upload:",c),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const s=i.split("/").pop()||"",n=i.substring(0,i.lastIndexOf("/"))||"",a=t.createWriteStream(r.join(this.storagePath,o)),d=yield e({url:`${this.url}/download`,method:"GET",params:{dir:n,filename:s},headers:{Authorization:this.getAuthHeader()},maxContentLength:1/0,maxBodyLength:1/0,responseType:"stream"});if(d.status>=300)return console.error("Error occurred during file download:",d),a.destroy(),t.existsSync(r.join(this.storagePath,o))&&t.unlinkSync(r.join(this.storagePath,o)),!1;let l=0;return d.data.on("data",(e=>{l+=e.length,this.taskQueue.setDownloadedSize(l)})),yield fe(d.data,a),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class ge{constructor(e,t){this.baseUrl="https://proapi.115.com",this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new E(1),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return b(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}getUploadCredentials(t){return b(this,void 0,void 0,(function*(){try{const r=yield e.get(`${this.baseUrl}/open/upload/get_token`,{headers:{Authorization:`Bearer ${t}`}});return r.status>=300||!r.data.state?(console.error("Error getting upload credentials:",r.data),null):r.data.data}catch(e){return console.error("Error occurred during get upload credentials:",e),null}}))}generateOSSPolicy(e,t,r=new Date(Date.now()+36e5)){const i={expiration:r.toISOString(),conditions:[{bucket:e},{key:t},["starts-with","$success_action_status","2"],["content-length-range",0,1073741824]]};return JSON.stringify(i)}refreshToken(){return b(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>b(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token;if(!e)throw new Error("No refresh token available");let t=yield this.thirdpartyRequest.refreshThirdToken({provider:"yiyiwu",refresh_token:e});if(!t.data.access_token)return"";if(this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+18e5,!t.data.refresh_token)throw new Error("No refresh token returned");this.config.refresh_token=t.data.refresh_token;let r=yield this.thirdpartyRequest.encryptToken({token:JSON.stringify({refresh_token:t.data.refresh_token,access_token:t.data.access_token,expires_at:this.config.expires_at})});return 200===r.code&&(yield this.thirdpartyRequest.TokenService.setToken("yiyiwu_token",r.data.encrypted_token)),t.data.access_token}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e,t){return b(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"yiyiwu",redirect_uri:t,code:e})).data}))}getAuthUrl(e){return`https://passportapi.115.com/open/authorize?client_id=${$}&response_type=code&redirect_uri=${e}`}}class me extends ge{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(e,t){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){var i;try{const i=yield this.refreshToken();let o=this.baseFolder+"/"+t;o.startsWith("/")||(o="/"+o);let s=r.dirname(o),n=yield this.getFolderInfo(s,!0),a="0";if(n)a=n.file_id;else{let e=yield this.createFolder(s);if(!e)return console.error("Failed to create folder:",s),!1;a=e}const d=r.join(this.storagePath,e),l=yield this.getFileSize(d),c=yield this.calculateFileSha1(d),h=yield this.calculatePreSha1(d),u=r.basename(t);yield this.deleteFileWithoutQueue(t);let p=yield this.initializeUpload(a,u,l,c,h,i);if(!p)return console.error("Failed to initialize upload"),!1;if((6===p.status||7===p.status||8===p.status)&&(p=yield this.handleSecondAuth(a,p,d,u,l,c,h,i),!p))return console.error("Second authentication failed"),!1;if(2===p.status)return console.info(`File ${e} uploaded successfully via instant upload.`),!0;const f=yield this.getUploadCredentials(i);if(!f)return console.error("Failed to get upload credentials"),!1;return(yield this.uploadToObjectStorage(d,p,f))?(console.info(`File ${e} uploaded successfully.`),!0):(console.error("Failed to upload to object storage"),!1)}catch(e){return console.error("Error occurred during file upload:",(null===(i=e.response)||void 0===i?void 0:i.data)||e.message||e),!1}}))))))}))}calculateFileSha1(e){return b(this,void 0,void 0,(function*(){return new Promise(((r,i)=>{const o=g.createHash("sha1"),s=t.createReadStream(e);s.on("data",(e=>{o.update(e)})),s.on("end",(()=>{r(o.digest("hex"))})),s.on("error",(e=>{i(e)}))}))}))}calculatePreSha1(e){return b(this,void 0,void 0,(function*(){return new Promise(((r,i)=>{const o=g.createHash("sha1"),s=t.createReadStream(e,{start:0,end:131071});s.on("data",(e=>{o.update(e)})),s.on("end",(()=>{r(o.digest("hex"))})),s.on("error",(e=>{i(e)}))}))}))}handleSecondAuth(e,r,i,o,s,n,a,d){return b(this,void 0,void 0,(function*(){try{if(!r.sign_check)return console.error("No sign_check provided for second authentication"),null;const[l,c]=r.sign_check.split("-"),h=parseInt(l),u=parseInt(c),p=Buffer.alloc(u-h+1),f=yield t.promises.open(i,"r");try{yield f.read(p,0,p.length,h);const t=g.createHash("sha1");t.update(p);const i=t.digest("hex").toUpperCase();return yield this.initializeUpload(e,o,s,n,a,d,r.sign_key,i,r.pick_code)}finally{yield f.close()}}catch(e){return console.error("Error during second authentication:",e),null}}))}calculateOSSSignature(e,t){const r=Buffer.from(t).toString("base64");return g.createHmac("sha1",e).update(r).digest("base64")}uploadToObjectStorage(i,o,s){var n;return b(this,void 0,void 0,(function*(){try{const n=s.endpoint,a=o.bucket,d=o.object;let l;if(n.includes(a))l=n;else{l=`https://${a}.${n.replace(/^https?:\/\//,"")}`}const c=this.generateOSSPolicy(a,d),h=this.calculateOSSSignature(s.AccessKeySecret,c),u=Buffer.from(c).toString("base64"),p=new f;if(p.append("key",d),p.append("policy",u),p.append("OSSAccessKeyId",s.AccessKeyId),p.append("signature",h),p.append("x-oss-security-token",s.SecurityToken),p.append("success_action_status","200"),o.callback&&o.callback.callback){const e=Buffer.from(o.callback.callback).toString("base64");if(p.append("callback",e),o.callback.callback_var){const e=JSON.parse(o.callback.callback_var);for(const[t,r]of Object.entries(e))p.append(t,String(r))}}const y=t.createReadStream(i);p.append("file",y,r.basename(i));const g=yield e.post(l,p,{headers:Object.assign({},p.getHeaders()),maxContentLength:1/0,maxBodyLength:1/0});return 200===g.status||204===g.status||(console.error("Upload failed with status:",g.status),!1)}catch(e){return console.error("Error uploading file via REST API:",(null===(n=e.response)||void 0===n?void 0:n.data)||e.message||e),!1}}))}downloadFile(i,o){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{let s=this.baseFolder+"/"+i;s=s.replace(/\/+/g,"/"),s.startsWith("/")||(s="/"+s);const n=yield this.getFolderInfo(s,!1);if(!n||!n.pick_code)return console.error("Failed to get file info or pick_code for:",i),!1;const a=yield this.getFileDownloadUrl(n.pick_code);if(!a)return console.error("Failed to get download URL for:",i),!1;const d=yield e.get(a.url,{responseType:"stream"});let l=0;const c=t.createWriteStream(r.join(this.storagePath,o));return d.data.on("data",(e=>{l+=e.length,this.taskQueue.setDownloadedSize(l)})),yield new Promise(((e,t)=>{d.data.pipe(c),c.on("finish",(()=>{e()})),c.on("error",t)})),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();(t=this.baseFolder+"/"+t).startsWith("/")||(t="/"+t);let i=[],o=0;const s=1150;let n=!0,a=yield this.getFolderInfo(t,!0),d="";if(a)d=a.file_id;else{let e=yield this.createFolder(t);if(!e)return console.error("Failed to create folder:",t),[];d=e}if(!d)return console.error("Failed to get or create folder ID:",t),[];let l=d;for(;n;){const t={offset:o,limit:s,cur:1,show_dir:1};l&&(t.cid=l);const a=yield e.get(`${this.baseUrl}/open/ufile/files`,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},params:t});if(a.status>=300)break;const d=a.data.data||[];i=i.concat(d),d.length({name:e.fn,size:e.fs||0,type:"0"===e.fc?"folder":"file",modified:new Date(1e3*e.upt).toISOString()})))}catch(e){return console.error("Error occurred during file list:",e),[]}}))}getFileDownloadUrl(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=new f;i.append("pick_code",t);const o=yield e.post(`${this.baseUrl}/open/ufile/downurl`,i,{headers:Object.assign({Authorization:`Bearer ${r}`},i.getHeaders())});if(o.status>=300)return console.error("Error getting download URL:",o.data),null;const s=o.data.data,n=Object.keys(s)[0];return n&&s[n]?s[n].url:(console.error("No file data found in download URL response"),null)}catch(e){return console.error("Error occurred during get download URL:",e),null}}))}initializeUpload(t,r,i,o,s,n,a,d,l){return b(this,void 0,void 0,(function*(){try{const c=new f;c.append("file_name",r),c.append("file_size",i.toString()),t?c.append("target","U_1_"+t):c.append("target","U_1_0"),c.append("fileid",o),c.append("preid",s),c.append("topupload","0"),l&&c.append("pick_code",l),a&&c.append("sign_key",a),d&&c.append("sign_val",d);const h=yield e.post(`${this.baseUrl}/open/upload/init`,c,{headers:Object.assign({Authorization:`Bearer ${n}`},c.getHeaders())});return h.status>=300||!h.data.state?(console.error("Error initializing upload:",h.data),null):h.data.data}catch(e){return console.error("Error occurred during upload initialization:",e),null}}))}createFolder(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=t.replace(/^\/+|\/+$/g,"");if(!i)return"";const o=i.split("/");let s="",n="0";for(const t of o){s=s?`${s}/${t}`:t;const i=yield this.getFolderInfo(s,!0);if(i&&i.file_id)n=i.file_id;else{const i=new f;i.append("pid",n),i.append("file_name",t);const o=yield e.post(`${this.baseUrl}/open/folder/add`,i,{headers:Object.assign({Authorization:`Bearer ${r}`},i.getHeaders())});if(o.status>=300||!o.data.state)return console.error("Error creating folder:",o.data),"";n=o.data.data.file_id}}return n}catch(e){return console.error("Error occurred during folder creation:",e),""}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return b(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();t=this.baseFolder+"/"+t;let i=yield this.getFolderInfo(t,!1);if(!i)return!0;let o=new f;o.append("file_ids",i.file_id);const s=yield e.post(`${this.baseUrl}/open/ufile/delete`,o,{headers:Object.assign({Authorization:`Bearer ${r}`},o.getHeaders())});return!(s.status>=300||!s.data.state)||(console.error("Error deleting file:",s),!1)}catch(e){return console.error("Error occurred during file delete:",e),!1}}))}getFolderInfo(t,r){return b(this,void 0,void 0,(function*(){if(""===t||"/"===t)return{file_id:"0"};t.startsWith("/")||(t="/"+t);try{const r=yield this.refreshToken();let i=new f;i.append("path",t);const o=yield e.post(`${this.baseUrl}/open/folder/get_info`,i,{headers:Object.assign(Object.assign({},i.getHeaders()),{Authorization:`Bearer ${r}`})});return o.status>=300||!o.data.state||0===o.data.data.length?(console.error("Error getting file info:",o.data),null):o.data.data}catch(e){return console.error("Error occurred during get file info:",e),null}}))}getFileSize(e){return b(this,void 0,void 0,(function*(){try{return(yield t.promises.stat(e)).size}catch(e){throw e}}))}}const ke=()=>{let e="";if("darwin"===process.platform){const i=r.join(m.homedir(),"Library","Mobile Documents","iCloud~com~koodoreader~expo","Documents");t.existsSync(i)&&(e=i)}else if("win32"===process.platform){const i=[r.join(m.homedir(),"iCloudDrive","iCloud~com~koodoreader~expo")];for(const r of i)if(t.existsSync(r)){e=r;break}}return e&&t.existsSync(e)&&e&&t.existsSync(e)?e:""};class ve{constructor(e,t){this.config=e,this.storagePath=t,this.taskQueue=new E(5)}retryOperation(e,t=0){return b(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return this.taskQueue.hasFailedTasks=!0,this.taskQueue.clearQueue(),i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}uploadFile(e,i){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){try{const o=()=>new Promise(((o,s)=>b(this,void 0,void 0,(function*(){let s=ke();if(!s)return console.error("iCloud Drive path not found"),void o(!1);let n=s+"/"+i,a=s+"/"+r.dirname(i);t.existsSync(a)||t.mkdirSync(a,{recursive:!0}),t.copyFile(r.join(this.storagePath,e),n,(e=>{e?(console.error("Error uploading file:",e),o(!1)):o(!0)}))}))));try{return yield o()}catch(e){return console.error(e),!1}}catch(e){return console.error("Error in uploadFile:",e),!1}}))))))}))}downloadFile(e,i){return b(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>b(this,void 0,void 0,(function*(){this.taskQueue.setDownloadedSize(0);try{const o=()=>new Promise(((o,s)=>b(this,void 0,void 0,(function*(){let s=ke();if(!s)return console.error("iCloud Drive path not found"),void o(!1);let n=s+"/"+e,a=r.join(this.storagePath,i);console.log(n,"remotepath"),t.copyFile(n,a,(e=>{if(e)console.error("Error downloading file:",e),o(!1);else{let e=t.statSync(a);console.log(e,"status"),this.taskQueue.setDownloadedSize(e.size),o(!0)}}))}))));try{return yield o()}catch(e){return console.error(e),!1}}catch(e){return console.error("Error in downloadFile:",e),!1}}))))))}))}listFiles(e){return b(this,void 0,void 0,(function*(){return(yield this.listFileInfos(e)).map((e=>e.name))}))}listFileInfos(e){return b(this,void 0,void 0,(function*(){const i=()=>new Promise(((i,o)=>b(this,void 0,void 0,(function*(){let o=ke();if(!o)return console.error("iCloud Drive path not found"),void i(!1);let s=o+"/"+e;t.existsSync(s)||t.mkdirSync(s,{recursive:!0}),t.readdir(s,{withFileTypes:!0},((e,o)=>{if(e)return console.error("Error reading directory:",e),void i([]);let n=o.map((e=>{let i=r.join(s,e.name),o=t.statSync(i);return{name:e.name,size:o.size,type:e.isDirectory()?"folder":"file",modified:o.mtime.toISOString()}}));i(n)}))}))));try{return yield i()}catch(e){return console.error(e),[]}}))}deleteFile(e){return b(this,void 0,void 0,(function*(){try{return yield new Promise(((r,i)=>{let o=ke();if(!o)return console.error("iCloud Drive path not found"),void r(!1);let s=o+"/"+e;t.unlink(s,(e=>{e?(console.error("Error deleting file:",e),r(!1)):r(!0)}))}))}catch(e){return console.error(e),!1}}))}}const Te=["book","config","cover","font"];class be{constructor(e,t,r,i){this.type=e,this.storagePath=r,this.remote="dropbox"===e?new U(t,r,i):"microsoft"===e?new N(t,r,i):"google"===e?new K(t,r,i):"microsoft_exp"===e?new N(Object.assign(Object.assign({},t),{isExp:!0}),r,i):"google_exp"===e?new K(Object.assign(Object.assign({},t),{isExp:!0}),r,i):"s3compatible"===e?new J(t,r):"webdav"===e?new Y(t,r):"docker"===e?new ye(t,r):"ftp"===e?new M(t,r):"sftp"===e?new ee(t,r):"boxnet"===e?new ie(t,r,i):"mega"===e?new se(t,r):"adrive"===e?new ae(t,r,i):"pcloud"===e?new le(t,r,i):"dubox"===e?new ue(t,r,i):"yandex"===e?new Z(t,r,i):"yiyiwu"===e?new me(t,r,i):"icloud"===e?new ve(t,r):new te}downloadFile(e,i,o){return b(this,void 0,void 0,(function*(){if(t.existsSync(r.join(this.storagePath+"/"+o))||t.mkdirSync(r.join(this.storagePath+"/"+o)),"cover"!==o){if(!(yield this.listFiles(o)).find((t=>e.indexOf(t)>-1)))return!1}return yield this.remote.downloadFile(o+"/"+e,o+"/"+i)}))}uploadFile(e,t,r){return b(this,void 0,void 0,(function*(){return yield this.remote.uploadFile(r+"/"+e,r+"/"+t)}))}deleteFile(e,t){return b(this,void 0,void 0,(function*(){return!!(yield this.listFiles(t)).find((t=>e.indexOf(t)>-1))&&(yield this.remote.deleteFile(t+"/"+e))}))}isExist(e,t){return b(this,void 0,void 0,(function*(){return(yield this.listFiles(t)).find((t=>-1!==t.indexOf(e)))}))}listFiles(e){return b(this,void 0,void 0,(function*(){return yield this.remote.listFiles(e)}))}listFileInfos(e){return b(this,void 0,void 0,(function*(){return yield this.remote.listFileInfos(e)}))}downloadAllFiles(){return b(this,void 0,void 0,(function*(){for(let e of Te){let t=yield this.listFiles(e);for(let r of t)yield this.downloadFile(r,r,e)}}))}authToken(e,t){return b(this,void 0,void 0,(function*(){return yield this.remote.authToken(e,t)}))}getAuthUrl(e){return this.remote.getAuthUrl(e)}getStats(){return this.remote.taskQueue.getStats()}resetCounters(){this.remote.taskQueue.resetCounters()}getDownloadedSize(){return this.remote.taskQueue.getDownloadedSize()}}const Fe={notes:"SELECT * FROM notes WHERE key = ?",bookmarks:"SELECT * FROM bookmarks WHERE key = ?",books:"SELECT * FROM books WHERE key = ?",plugins:"SELECT * FROM plugins WHERE key = ?",words:"SELECT * FROM words WHERE key = ?"},we={notes:"SELECT * FROM notes WHERE bookKey = ?",bookmarks:"SELECT * FROM bookmarks WHERE bookKey = ?",words:"SELECT * FROM words WHERE bookKey = ?",books:"SELECT * FROM books WHERE key = ?"},Ee={notes:"DELETE FROM notes WHERE bookKey = ?",bookmarks:"DELETE FROM bookmarks WHERE bookKey = ?",words:"DELETE FROM words WHERE bookKey = ?"};function Se(e){for(const t in e)e.hasOwnProperty(t)&&(e[`temp-${t}`]=e[t]);return e}const _e={notes:e=>{let t=Object.assign({},e);return t.date=JSON.parse(e.date),t.tag=JSON.parse(e.tag),t},bookmarks:e=>e,books:e=>e,plugins:e=>{let t=Object.assign({},e);return e.autoValue||delete t.autoValue,e.langList?t.langList=JSON.parse(e.langList):delete t.langList,e.voiceList?t.voiceList=JSON.parse(e.voiceList):delete t.voiceList,t.config=JSON.parse(e.config),t},words:e=>{let t=Object.assign({},e);return t.date=JSON.parse(e.date),t}};var Re={sqlStatement:{createTableStatement:Se({notes:'\n CREATE TABLE IF NOT EXISTS "notes" (\n "key" text PRIMARY KEY,\n "bookKey" text,\n "date" object,\n "chapter" text,\n "chapterIndex" integer,\n "text" text,\n "cfi" text,\n "range" text,\n "notes" text,\n "percentage" text,\n "color" integer,\n "tag" array\n )\n ',bookmarks:'\n CREATE TABLE IF NOT EXISTS "bookmarks" (\n "key" text PRIMARY KEY,\n "bookKey" text,\n "cfi" text,\n "label" text,\n "percentage" text,\n "chapter" text\n );\n ',books:'\n CREATE TABLE IF NOT EXISTS "books" (\n "key" text PRIMARY KEY,\n "name" text,\n "author" text,\n "description" text,\n "md5" text,\n "cover" text,\n "format" text,\n "publisher" text,\n "size" integer,\n "page" integer,\n "path" text,\n "charset" text\n );\n ',plugins:'\n CREATE TABLE IF NOT EXISTS "plugins" (\n "key" text PRIMARY KEY,\n "type" text,\n "displayName" text,\n "icon" text,\n "version" text,\n "config" object,\n "autoValue" string,\n "langList" text,\n "voiceList" text,\n "scriptSHA256" text,\n "script" text\n );\n ',words:'\n CREATE TABLE IF NOT EXISTS "words" (\n "key" text PRIMARY KEY,\n "bookKey" text,\n "date" object,\n "word" text,\n "chapter" text\n );\n '}),getAllStatement:Se({notes:"SELECT * FROM notes",bookmarks:"SELECT * FROM bookmarks",books:"SELECT * FROM books",plugins:"SELECT * FROM plugins",words:"SELECT * FROM words"}),getPagedStatement:Se({notes:"SELECT * FROM notes LIMIT ? OFFSET ?",bookmarks:"SELECT * FROM bookmarks LIMIT ? OFFSET ?",books:"SELECT * FROM books LIMIT ? OFFSET ?",plugins:"SELECT * FROM plugins LIMIT ? OFFSET ?",words:"SELECT * FROM words LIMIT ? OFFSET ?"}),getCountStatement:Se({notes:"SELECT COUNT(*) as count FROM notes",bookmarks:"SELECT COUNT(*) as count FROM bookmarks",books:"SELECT COUNT(*) as count FROM books",plugins:"SELECT COUNT(*) as count FROM plugins",words:"SELECT COUNT(*) as count FROM words"}),saveStatement:Se({notes:"INSERT OR REPLACE INTO notes (key, bookKey, chapter, chapterIndex, text, cfi, range, notes, date, percentage, color, tag) VALUES (@key, @bookKey, @chapter, @chapterIndex, @text, @cfi, @range, @notes, @date, @percentage, @color, @tag)",bookmarks:"INSERT OR REPLACE INTO bookmarks (key, bookKey, cfi, label, percentage, chapter) VALUES (@key, @bookKey, @cfi, @label, @percentage, @chapter)",books:"INSERT OR REPLACE INTO books (key, name, author, description, md5, cover, format, publisher, size, page, path, charset) VALUES (@key, @name, @author, @description, @md5, @cover, @format, @publisher, @size, @page, @path, @charset)",plugins:"INSERT OR REPLACE INTO plugins (key, type, displayName, icon, version, config, autoValue, langList, voiceList, scriptSHA256, script) VALUES (@key, @type, @displayName, @icon, @version, @config, @autoValue, @langList, @voiceList, @scriptSHA256, @script)",words:"INSERT OR REPLACE INTO words (key, bookKey, date, word, chapter) VALUES (@key, @bookKey, @date, @word, @chapter)"}),deleteAllStatement:Se({notes:"DELETE FROM notes",bookmarks:"DELETE FROM bookmarks",books:"DELETE FROM books",plugins:"DELETE FROM plugins",words:"DELETE FROM words"}),updateStatement:Se({notes:"UPDATE notes SET bookKey = @bookKey, chapter = @chapter, chapterIndex = @chapterIndex, text = @text, cfi = @cfi, range = @range, notes = @notes, date = @date, percentage = @percentage, color = @color, tag = @tag WHERE key = @key",bookmarks:"UPDATE bookmarks SET bookKey = @bookKey, cfi = @cfi, label = @label, percentage = @percentage, chapter = @chapter WHERE key = @key",books:"UPDATE books SET name = @name, author = @author, description = @description, md5 = @md5, cover = @cover, format = @format, publisher = @publisher, size = @size, page = @page, path = @path, charset = @charset WHERE key = @key",plugins:"UPDATE plugins SET type = @type, displayName = @displayName, icon = @icon, version = @version, config = @config, autoValue = @autoValue, langList = @langList, voiceList = @voiceList, scriptSHA256 = @scriptSHA256, script = @script WHERE key = @key",words:"UPDATE words SET bookKey = @bookKey, date = @date, word = @word, chapter = @chapter WHERE key = @key"}),deleteStatement:Se({notes:"DELETE FROM notes WHERE key = ?",bookmarks:"DELETE FROM bookmarks WHERE key = ?",books:"DELETE FROM books WHERE key = ?",plugins:"DELETE FROM plugins WHERE key = ?",words:"DELETE FROM words WHERE key = ?"}),dropStatement:Se({notes:"DROP TABLE IF EXISTS notes",bookmarks:"DROP TABLE IF EXISTS bookmarks",books:"DROP TABLE IF EXISTS books",plugins:"DROP TABLE IF EXISTS plugins",words:"DROP TABLE IF EXISTS words"}),getStatement:Se(Fe),getByBookKeyStatement:Se(we),getByBookKeysStatement:Se({notes:e=>`SELECT * FROM notes WHERE bookKey IN (${e.map((()=>"?")).join(",")})`,bookmarks:e=>`SELECT * FROM bookmarks WHERE bookKey IN (${e.map((()=>"?")).join(",")})`,words:e=>`SELECT * FROM words WHERE bookKey IN (${e.map((()=>"?")).join(",")})`,books:e=>`SELECT * FROM books WHERE key IN (${e.map((()=>"?")).join(",")})`}),getKeysStatement:Se({notes:"SELECT key FROM notes",bookmarks:"SELECT key FROM bookmarks",books:"SELECT key FROM books",plugins:"SELECT key FROM plugins",words:"SELECT key FROM words"}),getWithSortAndPageStatement:Se({notes:(e,t,r,i)=>`SELECT * FROM notes ORDER BY ${e} ${t} LIMIT ${r} OFFSET ${i}`,bookmarks:(e,t,r,i)=>`SELECT * FROM bookmarks ORDER BY ${e} ${t} LIMIT ${r} OFFSET ${i}`,books:(e,t,r,i)=>`SELECT * FROM books ORDER BY ${e} ${t} LIMIT ${r} OFFSET ${i}`,plugins:(e,t,r,i)=>`SELECT * FROM plugins ORDER BY ${e} ${t} LIMIT ${r} OFFSET ${i}`,words:(e,t,r,i)=>`SELECT * FROM words ORDER BY ${e} ${t} LIMIT ${r} OFFSET ${i}`}),getByKeysStatement:Se({notes:e=>`SELECT * FROM notes WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,t)=>`WHEN ? THEN ${t}`)).join(" ")} END`,bookmarks:e=>`SELECT * FROM bookmarks WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,t)=>`WHEN ? THEN ${t}`)).join(" ")} END`,books:e=>`SELECT * FROM books WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,t)=>`WHEN ? THEN ${t}`)).join(" ")} END`,plugins:e=>`SELECT * FROM plugins WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,t)=>`WHEN ? THEN ${t}`)).join(" ")} END`,words:e=>`SELECT * FROM words WHERE key IN (${e.map((()=>"?")).join(",")}) ORDER BY CASE key ${e.map(((e,t)=>`WHEN ? THEN ${t}`)).join(" ")} END`}),deleteByBookKeyStatement:Se(Ee)},jsonToSqlite:Se({notes:e=>{let t=Object.assign({},e);return t.date=JSON.stringify(e.date),t.tag=JSON.stringify(e.tag),t},bookmarks:e=>e,books:e=>{let t=Object.assign({},e);return t.page=e.page||0,t},plugins:e=>{let t=Object.assign({},e);return e.autoValue||(t.autoValue=null),e.langList?t.langList=JSON.stringify(e.langList):t.langList=null,e.voiceList?t.voiceList=JSON.stringify(e.voiceList):t.voiceList=null,t.config=JSON.stringify(e.config),t},words:e=>{let t=Object.assign({},e);return t.date=JSON.stringify(e.date),t}}),sqliteToJson:Se(_e)};const xe=S,Oe=_,Ce=R;class Pe{constructor(e,t,r){this.TokenService=e,this.ConfigService=t,this.baseUrl="china"===r?Oe:xe,this.serverRegion=r,this.refreshToken="",this.accessToken="",this.streamPromise=null,this.expiresAt=0}refreshUserToken(){return b(this,void 0,void 0,(function*(){if(this.refreshToken=yield this.TokenService.getToken("refresh_token"),!this.refreshToken)return{code:401,message:"refresh token not found"};let t=(yield e.post(this.baseUrl+"/api/v1/public/user/refresh_token",{refresh_token:this.refreshToken})).data;return 200===t.code&&(yield this.TokenService.setToken("access_token",t.data.access_token),yield this.TokenService.setToken("refresh_token",t.data.refresh_token),yield this.TokenService.setToken("expires_at",(1e3*t.data.expires_at).toString()),this.accessToken=t.data.access_token,this.refreshToken=t.data.refresh_token,this.expiresAt=1e3*t.data.expires_at),t}))}requestWithRetry(e){return b(this,void 0,void 0,(function*(){return Pe.requestQueue||(Pe.requestQueue=[]),new Promise(((t,r)=>{Pe.requestQueue.push({config:e,resolve:t,reject:r}),Pe.processingQueue||this.processQueue()}))}))}isTokenValid(){return b(this,void 0,void 0,(function*(){if(this.accessToken||(this.accessToken=(yield this.TokenService.getToken("access_token"))||""),!this.expiresAt){const e=yield this.TokenService.getToken("expires_at");this.expiresAt=e?parseInt(e):(new Date).getTime()+31536e9}return""!==this.accessToken&&this.expiresAt>(new Date).getTime()+6e4}))}processQueue(){return b(this,void 0,void 0,(function*(){if(!Pe.processingQueue){Pe.processingQueue=!0;try{for(;Pe.requestQueue.length>0;){const e=Pe.requestQueue.shift();try{let t=yield this.executeRequest(e.config);t&&"object"==typeof t&&"code"in t&&503===t.code&&(t.msg="Network error, please try again later. 网络错误,请稍后再试。"),e.resolve(t)}catch(t){e.reject(t)}}}finally{Pe.processingQueue=!1}}}))}executeRequest(t){return b(this,void 0,void 0,(function*(){try{(yield this.isTokenValid())||(yield this.refreshUserToken());let r="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);if(t.baseURL=this.baseUrl,"china"===this.serverRegion&&"/api/v1/pro/reader/get_tts_audio"===t.url&&(t.baseURL=Ce),t.headers)t.headers.Authorization="Bearer "+this.accessToken,t.headers["X-Request-ID"]=r;else{let e=this.ConfigService.getItem("appVersion"),i=this.ConfigService.getItem("appPlatform");t.headers={Authorization:"Bearer "+this.accessToken,"X-Request-ID":r,"X-App-Version":e||"1.0.0","X-App-Platform":i||"web"}}let i=(yield e(t)).data;if(402===i.code){let r=yield this.refreshUserToken();if(200===r.code){return t.headers=t.headers||{},t.headers.Authorization="Bearer "+this.accessToken,(yield e(t)).data}return r}return 200!==i.code&&this.ConfigService.setItem("errorLog",this.ConfigService.getItem("errorLog")+"\n"+JSON.stringify({request:t.data,url:t.url,result:i,requestID:r})),i}catch(e){return console.error("Request execution error:",e),{code:503,message:"network error",data:null}}}))}requestWithStream(e,t,r){return b(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>b(this,void 0,void 0,(function*(){try{(yield this.isTokenValid())||(yield this.refreshUserToken());let i=this.accessToken||"",o="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((s,n)=>{let a=this.ConfigService.getItem("appVersion"),d=this.ConfigService.getItem("appPlatform");const l=new r(("china"===this.serverRegion?Ce:this.baseUrl)+e.url,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+i,"X-Request-ID":o,"X-App-Version":a||"1.0.0","X-App-Platform":d||"web"},method:e.method,body:JSON.stringify(e.data),pollingInterval:0});l.addEventListener("open",(()=>{console.info("Connection to OpenAI established.")})),l.addEventListener("message",(e=>b(this,void 0,void 0,(function*(){if(!e.data)return;const r=JSON.parse(e.data);r.done?(l.close(),s(r)):t(r.data)})))),l.addEventListener("error",(e=>{if(console.info("Error:",e),!e.data)return;const t=JSON.parse(e.data);s(t),l.close()}))}))}finally{this.streamPromise=null}})))()),this.streamPromise}))}requestWithFetch(e,t){return b(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>b(this,void 0,void 0,(function*(){try{(yield this.isTokenValid())||(yield this.refreshUserToken());let r=this.accessToken||"",i="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((o,s)=>b(this,void 0,void 0,(function*(){let s=this.ConfigService.getItem("appVersion"),n=this.ConfigService.getItem("appPlatform");var a=new k(("china"===this.serverRegion?Ce:this.baseUrl)+e.url,{headers:{"Content-Type":"text/plain",Authorization:"Bearer "+r,"X-Request-ID":i,"X-App-Version":s||"1.0.0","X-App-Platform":n||"web"},payload:JSON.stringify(e.data),method:"POST"});a.addEventListener("message",(e=>b(this,void 0,void 0,(function*(){if(!e.data)return;const r=JSON.parse(e.data);r.done?(a.close(),o(r)):t(r.data)})))),a.addEventListener("open",(e=>{console.info(e,"Connection to OpenAI established.")})),a.addEventListener("error",(e=>{if(console.error(e,"Error occurred while connecting to OpenAI"),!e.data)return;const t=JSON.parse(e.data);o(t),a.close()}))}))))}finally{this.streamPromise=null}})))()),this.streamPromise}))}}Pe.processingQueue=!1,Pe.requestQueue=[];class Ae extends Pe{constructor(e,t,r){super(e,t,r),this.serverRegion=r}encryptToken(e){return b(this,void 0,void 0,(function*(){let t=e.token,r=w.encode(t),{extracted:i,remaining:o}=function(e){let t="",r="",i=[],o=1;for(;o<=e.length;)i.push(o-1),o*=2;for(let o=0;o-1){let r=t.split("#");e.encrypted_token=r[1]}const r={method:"post",url:"/api/v1/pro/thirdparty/decrypt_token",data:e};let i=yield this.requestWithRetry(r);if(t.indexOf("#")>-1&&i.data&&i.data.token){let e=t.split("#"),r=function(e,t){let r="",i=[],o=1,s=e.length+t.length;for(;o<=s;)i.push(o-1),o*=2;let n=0,a=0;for(let o=0;o-1&&r.splice(i,1),this.setAllListConfig(r,t)}static setListConfig(e,t){let r=this.getAllListConfig(t);const i=r.indexOf(e);i>-1?(r.splice(i,1),r.unshift(e)):r.unshift(e),this.setAllListConfig(r,t)}static setAllListConfig(e,t,r=!0){this.setItem(t,JSON.stringify(e)),r&&this.setSyncRecord({type:"config",catergory:"listConfig",name:"general",key:t},{operation:"update",time:Date.now()})}static setObjectConfig(e,t,r,i=!0){let o=this.getAllObjectConfig(r);o[e]=t,i&&this.setSyncRecord({type:"config",catergory:"objectConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllObjectConfig(o,r)}static getObjectConfig(e,t,r){return this.getAllObjectConfig(t)[e]||r}static getAllObjectConfig(e){let t=this.getItem(e);return JSON.parse(t)||{}}static setAllObjectConfig(e,t){this.setItem(t,JSON.stringify(e))}static deleteObjectConfig(e,t){let r=this.getAllObjectConfig(t);delete r[e],this.setSyncRecord({type:"config",catergory:"objectConfig",name:t,key:e},{operation:"delete",time:Date.now()}),this.setAllObjectConfig(r,t)}static getAllMapConfig(e){let t=this.getItem(e);return JSON.parse(t)||{}}static getMapConfig(e,t){return this.getAllMapConfig(t)[e]||[]}static setAllMapConfig(e,t){this.setItem(t,JSON.stringify(e))}static setMapConfig(e,t,r){let i=this.getAllMapConfig(r);void 0===i[e]&&(i[e]=[]),t&&-1===i[e].indexOf(t)&&i[e].unshift(t),this.setSyncRecord({type:"config",catergory:"mapConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(i,r)}static setOneMapConfig(e,t,r,i=!0){let o=this.getAllMapConfig(r);o[e]=t,i&&this.setSyncRecord({type:"config",catergory:"mapConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(o,r)}static deleteFromMapConfig(e,t,r){let i=this.getAllMapConfig(r),o=i[e].indexOf(t);i[e].splice(o,1),this.setSyncRecord({type:"config",catergory:"mapConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(i,r)}static deleteFromAllMapConfig(e,t){let r=this.getAllMapConfig(t);Object.keys(r).forEach((i=>{let o=r[i].indexOf(e);o>-1&&(r[i].splice(o,1),this.setSyncRecord({type:"config",catergory:"mapConfig",name:t,key:i},{operation:"update",time:Date.now()}))})),this.setAllMapConfig(r,t)}static deleteMapConfig(e,t){let r=this.getAllMapConfig(t);delete r[e],this.setSyncRecord({type:"config",catergory:"mapConfig",name:t,key:e},{operation:"delete",time:Date.now()}),this.setAllMapConfig(r,t)}static getFromAllMapConfig(e,t){let r=this.getAllMapConfig(t),i=[];for(let t in r)r[t]&&r[t].indexOf(e)>-1&&i.push(t);return i}static getSyncRecord(e){return JSON.parse(this.getItem("syncRecord")||"{}")[e.type+"."+e.catergory+"."+e.name+"."+e.key]||{operation:"",time:0}}static getAllSyncRecord(){return JSON.parse(this.getItem("syncRecord")||"{}")}static flushSyncRecords(){if(0===Object.keys(this.pendingSyncRecords).length)return;let e=JSON.parse(this.getItem("syncRecord")||"{}");Object.assign(e,this.pendingSyncRecords),this.setItem("syncRecord",JSON.stringify(e)),this.pendingSyncRecords={},this.syncRecordTimer=null}static setSyncRecord(e,t){const r=e.type+"."+e.catergory+"."+e.name+"."+e.key;this.pendingSyncRecords[r]=t,null!==this.syncRecordTimer&&clearTimeout(this.syncRecordTimer),this.syncRecordTimer=setTimeout((()=>{this.flushSyncRecords()}),this.DEBOUNCE_DELAY)}static setAllSyncRecord(e){this.setItem("syncRecord",JSON.stringify(e))}}).pendingSyncRecords={},Qe.syncRecordTimer=null,Qe.DEBOUNCE_DELAY=1e3,Qe);var Le,ze,Qe;let De;const je=new Uint8Array(16);function Ue(){if(!De&&(De="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!De))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return De(je)}const Me=[];for(let e=0;e<256;++e)Me.push((e+256).toString(16).slice(1));var Be={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function We(e,t,r){if(Be.randomUUID&&!t&&!e)return Be.randomUUID();const i=(e=e||{}).random||(e.rng||Ue)();if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t){r=r||0;for(let e=0;e<16;++e)t[r+e]=i[e];return t}return function(e,t=0){return Me[e[t+0]]+Me[e[t+1]]+Me[e[t+2]]+Me[e[t+3]]+"-"+Me[e[t+4]]+Me[e[t+5]]+"-"+Me[e[t+6]]+Me[e[t+7]]+"-"+Me[e[t+8]]+Me[e[t+9]]+"-"+Me[e[t+10]]+Me[e[t+11]]+Me[e[t+12]]+Me[e[t+13]]+Me[e[t+14]]+Me[e[t+15]]}(i)}const Ne=new v;class qe{static encrypt(e,t){let r="";for(let i=0;i0)return $e.setItem("fingerPrint",e),e}catch(e){console.error("Failed to get machine ID:",e)}let t=We().replace(/-/g,"");return $e.setItem("fingerPrint",t),t}))}}export{$e as ConfigService,Re as SqlStatement,be as SyncUtil,Ae as ThirdpartyRequest,qe as TokenService};