From 8d47f7a79aba48b2d58891cea48530fa7c7bb99d Mon Sep 17 00:00:00 2001 From: troyeguo <13820674+troyeguo@users.noreply.github.com> Date: Fri, 2 May 2025 10:12:21 +0800 Subject: [PATCH] fix: update font files and enhance popup assist functionality with new features --- package.json | 2 +- src/assets/lib/kookit-extra-browser.min.js | 2 +- src/assets/lib/kookit-extra.min.mjs | 2 +- src/assets/locales/en/translation.json | 2 + src/assets/locales/zh-CN/translation.json | 12 + src/assets/styles/fonts/icomoon.eot | Bin 25704 -> 26016 bytes src/assets/styles/fonts/icomoon.svg | 2 + src/assets/styles/fonts/icomoon.ttf | Bin 25540 -> 25852 bytes src/assets/styles/fonts/icomoon.woff | Bin 25616 -> 25928 bytes src/assets/styles/style.css | 16 +- .../popups/popupAssist/component.tsx | 725 +++++++++++------- .../popups/popupAssist/interface.tsx | 12 +- .../popups/popupAssist/popupAssist.css | 50 ++ src/components/popups/popupBox/component.tsx | 5 +- src/constants/settingList.tsx | 18 + src/utils/request/reader.ts | 19 + yarn.lock | 8 +- 17 files changed, 570 insertions(+), 305 deletions(-) diff --git a/package.json b/package.json index 31bc149e..1716ba17 100644 --- a/package.json +++ b/package.json @@ -40,7 +40,7 @@ "jszip": "^3.10.1", "localforage": "^1.10.0", "mammoth": "^1.8.0", - "marked": "^15.0.3", + "marked": "^15.0.11", "megajs": "^1.3.7", "mhtml2html": "^3.0.0", "node-machine-id": "^1.1.12", diff --git a/src/assets/lib/kookit-extra-browser.min.js b/src/assets/lib/kookit-extra-browser.min.js index 96eceee1..e5b2bb5c 100644 --- a/src/assets/lib/kookit-extra-browser.min.js +++ b/src/assets/lib/kookit-extra-browser.min.js @@ -1 +1 @@ -import e from"axios";import{Storage as t}from"megajs";import{Buffer as r}from"buffer";import{createClient as o,AuthType as i}from"webdav/dist/web/index.js";import{isElectron as n}from"react-device-detect";function s(e,t,r,o){return new(r||(r=Promise))((function(i,n){function s(e){try{c(o.next(e))}catch(e){n(e)}}function a(e){try{c(o.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((o=o.apply(e,t||[])).next())}))}const a=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,c=["books","notes","bookmarks","plugins","words"];class l{constructor(e){this.queue=[],this.runningTasks=0,this.totalTasks=0,this.completedTasks=0,this.maxConcurrency=e}addTask(e){return s(this,void 0,void 0,(function*(){return this.totalTasks++,new Promise(((t,r)=>{const o=()=>s(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"application/json"===e?"json":e.startsWith("image/")?e.split("/")[1]:"application/zip"===e?"zip":"application/epub+zip"===e?"epub":"text/plain"===e?"txt":"application/pdf"===e?"pdf":"application/x-mobipocket-ebook"===e?"mobi":"application/vnd.amazon.ebook"===e?"azw3":"application/x-cbz"===e?"cbz":"application/x-cbr"===e?"cbr":"application/x-cbt"===e?"cbt":"application/x-cb7"===e?"cb7":"application/x-fictionbook+xml"===e?"fb2":"text/html"===e?"html":"text/css"===e?"css":"application/javascript"===e?"js":"application/xml"===e?"xml":"application/xhtml+xml"===e?"xhtml":"application/oebps-package+xml"===e?"opf":"application/x-dtbncx+xml"===e?"ncx":"audio/mpeg"===e?"mp3":"audio/wav"===e?"wav":"audio/ogg"===e?"ogg":"video/mp4"===e?"mp4":"video/webm"===e?"webm":"video/x-msvideo"===e?"avi":"video/x-ms-wmv"===e?"wmv":"video/x-flv"===e?"flv":"application/x-mpegURL"===e?"m3u8":"video/MP2T"===e?"ts":"video/3gpp"===e?"3gp":"video/3gpp2"===e?"3g2":"application/x-sqlite3"===e?"db":"",databaseList:c,configList:["themeColors","readingTime","cloudSyncTime","recentBooks","recentAdd","deletedBooks","favoriteBooks","shelfList","txtParsers","noteTags","recordLocation","sortedShelfList","kindleDeviceList"],copyArrayBuffer:e=>{var t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e)),t},base64ToArrayBuffer:e=>{const t=atob(e),r=t.length,o=new Uint8Array(r);for(let e=0;e{let t="";const r=new Uint8Array(e),o=r.byteLength;for(let e=0;ee.toString(16).padStart(2,"0"))).join("")}))},EmailProviders:["gmail.com","qq.com","163.com","yahoo.com","sina.com","126.com","outlook.com","yeah.net","foxmail.com","hotmail.com","protonmail.com","proton.me","icloud.com","mail.com","live.com","aliyun.com"]};const u={publicUrl:"https://api.960960.xyz",cloudUrl:"https://cloud.960960.xyz",devUrl:"http://192.168.28.159:8000"},p={callbackUrl:"https://web.koodoreader.com/",dropboxClientId:"vnc67byrssocvy1",pcloudClientId:"pg8ten0B3vH",boxClientId:"ltimecqanmpxoaicn9qw3es6l3sdl1ya",microsoftClientId:"506df58a-29ab-4020-afc5-6f423dc80f35",googleClientId:"1051055003225-ph1f5fvh328dhv7bco5jitlnfhg6ks2t.apps.googleusercontent.com",facebookClientId:"2845583825559500",githubClientId:"Ov23liJVzfvJMMEEZ8v2",adriveClientId:"a128ae7b9c094545af623de61dc0a1ef"};var h={CloudConfig:u,ThirdpartyConfig:p,LoginAuthRequest:{google:{clientId:p.googleClientId,scopes:["openid"],usePKCE:!1,responseType:"code",redirectUri:p.callbackUrl,extraParams:{prompt:"consent",scope:"openid"}},microsoft:{clientId:p.microsoftClientId,scopes:["openid","profile","User.Read","offline_access"],usePKCE:!1,responseType:"code",redirectUri:p.callbackUrl,extraParams:{scope:"openid profile User.Read offline_access"}},facebook:{clientId:p.facebookClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:p.callbackUrl,extraParams:{scope:""}},github:{clientId:p.githubClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:p.callbackUrl,extraParams:{scope:""}},email:{clientId:"",scopes:[],usePKCE:!1,responseType:"code",redirectUri:p.callbackUrl,extraParams:{scope:""}}},LoginDiscovery:{microsoft:{authorizationEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/authorize",tokenEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/token"},google:{authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token"},facebook:{authorizationEndpoint:"https://www.facebook.com/v12.0/dialog/oauth",tokenEndpoint:"https://graph.facebook.com/v12.0/oauth/access_token"},github:{authorizationEndpoint:"https://github.com/login/oauth/authorize",tokenEndpoint:"https://github.com/login/oauth/access_token"},email:{authorizationEndpoint:"",tokenEndpoint:""}},DriveAuthRequest:{dropbox:{clientId:p.dropboxClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:p.callbackUrl,extraParams:{token_access_type:"offline"}},boxnet:{clientId:p.boxClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:p.callbackUrl,extraParams:{grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}},pcloud:{clientId:p.pcloudClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:p.callbackUrl,extraParams:{grant_type:"authorization_code"}},adrive:{clientId:p.adriveClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:p.callbackUrl,extraParams:{grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}},microsoft:{clientId:p.microsoftClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:p.callbackUrl,extraParams:{scope:"files.readwrite.appfolder offline_access"}},google:{clientId:p.googleClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:p.callbackUrl,extraParams:{prompt:"consent",scope:"https://www.googleapis.com/auth/drive.appdata",access_type:"offline"}}},DriveDiscovery:{dropbox:{authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",tokenEndpoint:"https://www.dropbox.com/oauth2/token"},boxnet:{authorizationEndpoint:"https://account.box.com/api/oauth2/authorize",tokenEndpoint:"https://api.box.com/oauth2/token"},pcloud:{authorizationEndpoint:"https://my.pcloud.com/oauth2/authorize",tokenEndpoint:"https://api.pcloud.com/oauth2_token"},adrive:{authorizationEndpoint:"https://openapi.alipan.com/oauth/authorize",tokenEndpoint:"https://openapi.alipan.com/oauth/token"},microsoft:{authorizationEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/authorize",tokenEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/token"},google:{authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token"}}};class f{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.driveId="",this.refreshTokenPromise=null,this.taskQueue=new l(1)}retryOperation(e,t=5){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}getDriveId(){return s(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 s(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),o=yield this.getDriveId();try{try{const i=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:o,file_path:t},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});if(i.data)return i.data.file_id}catch(i){const n=t.split("/").filter((e=>e));let s="",a="root";for(const t of n){s+="/"+t;try{a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:o,file_path:s},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.file_id}catch(i){a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:o,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(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=yield this.getDriveId(),i=yield this.getFolderIdByPath("/KoodoReader/"+t);let n=[],s="",a=!0;for(;a;){const t=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/list",{drive_id:o,parent_file_id:i,marker:s||void 0},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}),c=t.data.items||[];n=n.concat(c),s=t.data.next_marker,a=!!s&&100===c.length}return[...new Set(n.map((e=>e.name)))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=yield this.getDriveId(),i=yield this.getFolderIdByPath("/KoodoReader/"+t);return!i||(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/delete",{drive_id:o,file_id:i},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}),!0)}catch(e){return console.error("Error deleting file:",e),!1}}))}checkExists(t){var r;return s(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken(),i=yield this.getDriveId(),n=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:i,file_path:t},{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}});(null===(r=n.data)||void 0===r?void 0:r.file_id)&&(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/recyclebin/trash",{drive_id:i,file_id:n.data.file_id},{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}}))}catch(e){}}))}refreshToken(){return s(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=(()=>s(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"adrive",refresh_token:e});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})});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){return s(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"adrive",redirect_uri:p.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://openapi.alipan.com/oauth/authorize?${new URLSearchParams({response_type:"code",client_id:p.adriveClientId,redirect_uri:p.callbackUrl,grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}).toString()}`}}class g extends f{constructor(e,t){super(e,t)}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return new Promise(((o,i)=>s(this,void 0,void 0,(function*(){try{const i=yield this.refreshToken(),n=yield this.getDriveId(),s=r.substring(0,r.lastIndexOf("/")),a=r.substring(r.lastIndexOf("/")+1),c=yield this.getFolderIdByPath("/KoodoReader/"+s),l=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:n,parent_file_id:c,name:a,type:"file",check_name_mode:"ignore"},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}),{file_id:d,upload_id:u,part_info_list:p}=l.data;yield e.put(p[0].upload_url,t,{headers:{"Content-Type":"application/octet-stream"}}),yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/complete",{drive_id:n,file_id:d,upload_id:u},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}),o(!0)}catch(e){console.error("Error uploading file:",e),o(!1)}}))))}))}downloadFile(t){return new Promise(((r,o)=>s(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken(),i=yield this.getDriveId(),n=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:i,file_path:"/KoodoReader/"+t},{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}})).data.file_id,s=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/getDownloadUrl",{drive_id:i,file_id:n},{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}}),a=yield e.get(s.data.url,{responseType:"arraybuffer"});r(a.data)}catch(e){console.error("Error downloading file:",e),r(!1)}}))))}}class y{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new l(3)}retryOperation(e,t=3){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}getFolderIdByPath(t){return s(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),o=t.split("/");let i="0";for(const t of o){const o=`https://api.box.com/2.0/folders/${i}/items?fields=id,name&type=folder&limit=1000`;try{const n=(yield e.get(o,{headers:{Authorization:`Bearer ${r}`}})).data.entries.find((e=>e.name===t&&"folder"===e.type));if(n)i=n.id;else{const o={name:t,parent:{id:i},type:"folder"};i=(yield e.post("https://api.box.com/2.0/folders",o,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.id}}catch(e){return console.error("Error occurred during folder creation:",e),""}}return i}))}listFiles(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let o=yield this.getFolderIdByPath("KoodoReader/"+t),i=[],n=0,s=!0;const a=1e3;for(;s;){const t=yield e.get(`https://api.box.com/2.0/folders/${o}/items`,{params:{limit:a,offset:n},headers:{Authorization:`Bearer ${r}`}}),c=t.data.entries||[];i=i.concat(c),n+=c.length,s=c.length===a&&t.data.total_count>n}return[...new Set(i.map((e=>e.name)))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=t.substring(0,t.lastIndexOf("/")),i=t.substring(t.lastIndexOf("/")+1),n=yield this.getFolderIdByPath("KoodoReader/"+o);if(!n)return!0;const s=`https://api.box.com/2.0/folders/${n}/items?fields=id,name&type=file&limit=1000`,a=(yield e.get(s,{headers:{Authorization:`Bearer ${r}`}})).data.entries.find((e=>e.name===i&&"file"===e.type));return!a||(yield e.delete(`https://api.box.com/2.0/files/${a.id}`,{headers:{Authorization:`Bearer ${r}`}}),!0)}catch(e){return console.error("Error deleting file:",e),!1}}))}refreshToken(){return s(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=(()=>s(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"boxnet",refresh_token:e});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})});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){return s(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"boxnet",redirect_uri:p.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://account.box.com/api/oauth2/authorize?${new URLSearchParams({response_type:"code",client_id:p.boxClientId,redirect_uri:p.callbackUrl,grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}).toString()}`}}class m extends y{constructor(e,t){super(e,t)}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken(),i=r.substring(0,r.lastIndexOf("/")),n=r.substring(r.lastIndexOf("/")+1),s=yield this.getFolderIdByPath("KoodoReader/"+i);if(!s)throw new Error("Folder not found");const a=(yield this.listFiles(i)).find((e=>e===n));a&&(yield this.deleteFileWithoutQueue(i+"/"+n));let c=new File([t],n,{lastModified:(new Date).getTime(),type:t.type});const l=new FormData;l.append("file",c),l.append("parent_id",s);const d=yield e.post("https://upload.box.com/api/2.0/files/content",l,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"multipart/form-data"},params:{if_match:"false",fields:"name,id"},maxContentLength:1/0,maxBodyLength:1/0});return!(d.status>=300)||(console.error("Error occurred during file upload:",d),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(t){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=t.substring(0,t.lastIndexOf("/")),i=t.substring(t.lastIndexOf("/")+1),n=yield this.getFolderIdByPath("KoodoReader/"+o);if(!n)return console.error("Folder not found"),!0;const s=`https://api.box.com/2.0/folders/${n}/items?fields=id,name&type=file&limit=1000`,a=(yield e.get(s,{headers:{Authorization:`Bearer ${r}`}})).data.entries.find((e=>e.name===i&&"file"===e.type));if(!a)return console.error("File not found:",i),!0;const c=yield e({url:`https://api.box.com/2.0/files/${a.id}/content`,method:"get",headers:{Authorization:`Bearer ${r}`},responseType:"arraybuffer"});return c.status>=300?(console.error("Error occurred during file download:",c),!1):c.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class v{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new l(3)}retryOperation(e,t=3){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}listFiles(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let o=[],i=!0,n=null;for(;i;){let s;s=n?yield e.post("https://api.dropboxapi.com/2/files/list_folder/continue",{cursor:n},{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=s.data.entries||[];o=o.concat(a),i=s.data.has_more,n=s.data.cursor}return[...new Set(o.map((e=>e.name)))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return s(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 s(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=(()=>s(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"dropbox",refresh_token:e});return 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){return s(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"dropbox",redirect_uri:p.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://www.dropbox.com/oauth2/authorize?response_type=code&token_access_type=offline&client_id=${p.dropboxClientId}&redirect_uri=${p.callbackUrl}`}}class k extends v{constructor(e,t){super(e,t)}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken();let i=r.split("/").pop()||"",n=new File([t],i,{lastModified:(new Date).getTime(),type:t.type});const s=yield e.post("https://content.dropboxapi.com/2/files/upload",n,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/octet-stream","Dropbox-API-Arg":JSON.stringify({path:"/"+r,mode:"overwrite",autorename:!0,mute:!1})},maxContentLength:1/0,maxBodyLength:1/0});return!(s.status>=300)||(console.error("Error occurred during file upload:",s),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(t){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=yield e({url:"https://content.dropboxapi.com/2/files/download",method:"post",headers:{Authorization:`Bearer ${r}`,"Dropbox-API-Arg":JSON.stringify({path:"/"+t})},maxContentLength:1/0,maxBodyLength:1/0,responseType:"arraybuffer"});return o.status>=300?(console.error("Error occurred during file download:",o),!1):o.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class b{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new l(3)}retryOperation(e,t=3){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}getFileId(t,r){return s(this,void 0,void 0,(function*(){const o=yield this.refreshToken(),i=`https://www.googleapis.com/drive/v3/files?q=name='${t}'+and+'${r}'+in+parents&spaces=appDataFolder&fields=files(id,name)`;try{const t=yield e.get(i,{headers:{Authorization:"Bearer "+o}});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 s(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),o=yield this.getFolderId(t);if(o)return o;const i={name:t,mimeType:"application/vnd.google-apps.folder",parents:["appDataFolder"]};try{return(yield e.post("https://www.googleapis.com/drive/v3/files",i,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.id}catch(e){throw console.error("Error occurred during folder creation:",e),e}}))}getFolderId(t){return s(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),o=`https://www.googleapis.com/drive/v3/files?q=name='${t}'+and+mimeType='application/vnd.google-apps.folder'+and+'appDataFolder'+in+parents&spaces=appDataFolder&fields=files(id,name)`;try{const t=(yield e.get(o,{headers:{Authorization:`Bearer ${r}`}})).data.files;return t.length>0?t[0].id:null}catch(e){throw console.error("Error occurred during fetching folder ID:",e),e}}))}listFiles(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let o=yield this.checkFolder(t),i=[],n="",s=!0;for(;s;){let t=`https://www.googleapis.com/drive/v3/files?q='${o}'+in+parents&spaces=appDataFolder&fields=nextPageToken,files(id,name)&pageSize=1000`;n&&(t+=`&pageToken=${n}`);const a=yield e.get(t,{headers:{Authorization:`Bearer ${r}`}}),c=a.data.files||[];i=i.concat(c),n=a.data.nextPageToken,s=!!n}return[...new Set(i.map((e=>e.name)))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQue(e)}))))))}))}deleteFileWithoutQue(t){return s(this,void 0,void 0,(function*(){const r=t.split("/")[1],o=t.split("/")[0],i=yield this.getFolderId(o),n=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 ${n}`}});return console.error("File deleted:",t),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}refreshToken(){return s(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=(()=>s(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"google",refresh_token:e});return 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){return s(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"google",redirect_uri:p.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${p.callbackUrl}&prompt=consent&response_type=code&client_id=${p.googleClientId}&scope=https://www.googleapis.com/auth/drive.appdata&access_type=offline`}}class w extends b{constructor(e,t){super(e,t)}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken();let i=r.split("/").pop()||"",n=new File([t],i,{lastModified:(new Date).getTime(),type:t.type}),s=r.split(".").pop(),c=a(s||""),l=r.split("/")[0],d=yield this.checkFolder(l),u=yield this.getFileId(i||"",d);const p={mimeType:c,name:i,parents:[d]},h=u?`https://www.googleapis.com/upload/drive/v3/files/${u}?uploadType=resumable`:"https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",f=(yield e({method:u?"PATCH":"POST",url:h,data:u?null:JSON.stringify(p),headers:{Authorization:"Bearer "+o,"Content-Type":"application/json; charset=UTF-8"},maxContentLength:1/0,maxBodyLength:1/0})).headers.location,g=yield this.getData(n);if(0===Object.keys(g).length)return!1;const y=yield e.put(f,g.data,{headers:{Authorization:"Bearer "+o,"Content-Type":"application/zip","Content-Range":`bytes 0-${g.fileSize-1}/${g.fileSize}`},maxContentLength:1/0,maxBodyLength:1/0});return!(y.status>=300)||(console.error("Error occurred during file download:",y),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(t){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let o=t.split("/").pop(),i=t.split("/")[0],n=yield this.checkFolder(i),s=yield this.getFileId(o||"",n);if(!s)return console.error("File not found:",o),!0;const a=`https://www.googleapis.com/drive/v3/files/${s}?alt=media`,c=yield e.get(a,{headers:{Authorization:"Bearer "+r},maxContentLength:1/0,maxBodyLength:1/0,responseType:"arraybuffer"});return c.status>=300?(console.error("Error occurred during file download:",c),!1):c.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}getData(e){return s(this,void 0,void 0,(function*(){return e?new Promise(((t,r)=>{const o=new FileReader;o.onload=r=>t({fileName:e.name,mimeType:e.type,fileSize:e.size,data:r.target.result}),o.onerror=e=>r(e),o.readAsArrayBuffer(e)})):{}}))}}class T{constructor(e){this.folderCreationLocks=new Map,this.config=e,this.taskQueue=new l(3)}retryOperation(e,t=3){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}getStorage(){return s(this,void 0,void 0,(function*(){if(this.storage)return this.storage;let{email:e,password:r}=this.config;return this.storage=yield new t({email:e,password:r}).ready,this.storage}))}getRoot(){return s(this,void 0,void 0,(function*(){if(this.root)return this.root;const e=(yield this.getStorage()).root;let t=e.children.find((e=>"KoodoReader"===e.name&&e.directory));return t||(t=yield e.mkdir("KoodoReader")),this.root=t,this.root}))}createFolder(e,t){return s(this,void 0,void 0,(function*(){const r=`${e.nodeId}_${t}`;if(this.folderCreationLocks.has(r))return yield this.folderCreationLocks.get(r);const o=(()=>s(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,o),yield o}))}listFiles(e){return s(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.filter((e=>!e.directory)).map((e=>e.name))}catch(e){return console.error("Error listing MEGA files:",e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(e){return s(this,void 0,void 0,(function*(){try{let t=yield this.getRoot();const r=e.split("/"),o=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 i=t.children.find((e=>e.name===o&&!e.directory));return!i||(yield i.delete(),!0)}catch(e){return console.error("Error deleting MEGA file:",e),!1}}))}}class E extends T{constructor(e){super(e)}uploadFile(e,t){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{let o=yield this.getRoot();const i=t.split("/"),n=i.pop()||"";for(const e of i){if(!e)continue;let t=o.children.find((t=>t.name===e&&t.directory));t||(t=yield this.createFolder(o,e)),o=t}const s=new File([e],n,{lastModified:(new Date).getTime(),type:e.type}),a=yield e.arrayBuffer(),c=new Uint8Array(a),l=r.from(c),d=o.children.find((e=>e.name===n&&!e.directory));return d&&(yield d.delete()),yield o.upload({name:n,size:s.size},l).complete,!0}catch(e){return console.error("Error occurred during MEGA file upload:",e),!1}}))))))}))}downloadFile(e){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{let t=yield this.getRoot();const r=e.split("/"),o=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 i=t.children.find((e=>e.name===o&&!e.directory));if(!i)return!0;return yield i.downloadBuffer()}catch(e){return console.error("Error occurred during MEGA file download:",e),!1}}))))))}))}}class C{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new l(3)}retryOperation(e,t=3){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}listFiles(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let o=[],i=`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${t}:/children`;for(;i;){const t=yield e.get(i,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});if(t.status>=300)break;const n=t.data.value||[];o=o.concat(n),i=t.data["@odata.nextLink"]||""}return[...new Set(o.map((e=>e.name)))]}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=yield e.delete(`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${t}`,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});return!(o.status>=300)||(console.error("Error deleting file:",o),!0)}catch(e){return console.error("Error occurred during file delete:",e),!1}}))}refreshToken(){return s(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=(()=>s(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"microsoft",refresh_token:e});return 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){return s(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"microsoft",redirect_uri:p.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${p.microsoftClientId}&scope=files.readwrite.appfolder offline_access&response_type=code&redirect_uri=${p.callbackUrl}`}}class x extends C{constructor(e,t){super(e,t)}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken();let i=r.split("/").pop()||"",n=new File([t],i,{lastModified:(new Date).getTime(),type:t.type});const s="https://graph.microsoft.com/v1.0/me/drive/special/approot:/"+r+":/createUploadSession",a=yield e.post(s,null,{headers:{Authorization:"Bearer "+o,"Content-Type":"application/json"},maxContentLength:1/0,maxBodyLength:1/0});let c=n.size;const l=n.type,d=a.data.uploadUrl,u=yield e.put(d,n,{headers:{"Content-Type":l,"Content-Range":`bytes 0-${c-1}/${c}`},maxContentLength:1/0,maxBodyLength:1/0});return!(u.status>=300)||(console.error("Error occurred during file download:",u),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(t){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${t}:/content`,i=yield e.get(o,{responseType:"arraybuffer",headers:{Authorization:"Bearer "+r},maxContentLength:1/0,maxBodyLength:1/0});return i.status>=300?(console.error("Error occurred during file download:",i),!1):i.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class _{downloadFile(e,t){return s(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}uploadFile(e,t){return s(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}listFiles(e){return s(this,void 0,void 0,(function*(){return new Promise((e=>{e([])}))}))}authToken(e){return s(this,void 0,void 0,(function*(){return new Promise((e=>{e("")}))}))}getAuthUrl(){return""}}class S{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.taskQueue=new l(3)}retryOperation(e,t=5){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}checkFolderExists(t,r){return s(this,void 0,void 0,(function*(){try{return 0===(yield e.get("https://api.pcloud.com/listfolder",{params:{access_token:r,path:`/${t}`}})).data.result}catch(e){return console.error("Error checking folder:",e),!1}}))}createFolder(t,r){return s(this,void 0,void 0,(function*(){try{return 0===(yield e.get("https://api.pcloud.com/createfolderifnotexists",{params:{access_token:r,path:`/${t}`}})).data.result}catch(e){return console.error("Error creating folder:",e),!1}}))}listFiles(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=yield e.get("https://api.pcloud.com/listfolder",{params:{access_token:r,path:"/"+t,recursive:0}});return 0!==o.data.result?[]:o.data.metadata.contents.map((e=>e.name))}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=yield e.get("https://api.pcloud.com/deletefile",{params:{access_token:r,path:"/"+t}});return 0===o.data.result||(console.error("Error deleting file:",o.data),!0)}catch(e){return console.error("Error occurred during file delete:",e),!1}}))}refreshToken(){return s(this,void 0,void 0,(function*(){return this.config.refresh_token}))}authToken(e){return s(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"pcloud",redirect_uri:p.callbackUrl,code:e})).data.access_token}))}getAuthUrl(){return`https://my.pcloud.com/oauth2/authorize?client_id=${p.pcloudClientId}&response_type=code&redirect_uri=${p.callbackUrl}`}}class R extends S{constructor(e,t){super(e,t)}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken(),i=r.split("/").slice(0,-1).join("/");if(!(yield this.checkFolderExists(i,o))){if(!(yield this.createFolder(i,o)))return!1}let n=r.split("/").pop()||"",s=new File([t],n,{lastModified:(new Date).getTime(),type:t.type});const a=new FormData;a.append("file",s);const c=yield e.post("https://api.pcloud.com/uploadfile",a,{params:{access_token:o,path:`/${i}`,renew:1},maxContentLength:1/0,maxBodyLength:1/0});return 0===c.data.result||(console.error("Error uploading file:",c.data),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(t){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=yield e.get("https://api.pcloud.com/getfilelink",{params:{access_token:r,path:`/${t}`}});if(0!==o.data.result)return console.error("Error getting file link:",o.data),!0;const i=`https://${o.data.hosts[0]}${o.data.path}`,n=yield e.get(i,{responseType:"arraybuffer",maxContentLength:1/0,maxBodyLength:1/0});return n.status>=300?(console.error("Error downloading file:",n),!1):n.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class O{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.taskQueue=new l(5)}retryOperation(e,t=0){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}listFiles(e){return s(this,void 0,void 0,(function*(){let{endpoint:t,region:r,bucketName:o,accessKeyId:i,secretAccessKey:n,dir:s}=this.config;s||(s="KoodoReader");try{return(yield this.thirdpartyRequest.s3List({bucket_name:o,prefix:s+"/"+e,region:r,endpoint:t,access_key_id:i,secret_access_key:n})).data.contents.map((e=>e.split("/").pop()))}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){let{endpoint:t,region:r,bucketName:o,accessKeyId:i,secretAccessKey:n,dir:s}=this.config;s||(s="KoodoReader");try{let a=yield this.thirdpartyRequest.s3Delete({bucket_name:o,object_key:s+"/"+e,region:r,endpoint:t,access_key_id:i,secret_access_key:n});return 200===a.code||(console.error("Error deleting file:",a),!1)}catch(e){return console.error("Error deleting file:",e),!1}}))}}class A extends O{constructor(e,t){super(e,t)}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){let{endpoint:o,region:i,bucketName:n,accessKeyId:s,secretAccessKey:a,dir:c}=this.config;c||(c="KoodoReader");try{const l=(yield this.thirdpartyRequest.s3Upload({bucket_name:n,object_key:c+"/"+r,region:i,endpoint:o,access_key_id:s,secret_access_key:a})).data.url;let d=r.split("/").pop()||"",u=new File([t],d,{lastModified:(new Date).getTime(),type:t.type});const p=yield e.put(l,u,{headers:{},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 occurred during file upload:",e),!1}}))))))}))}downloadFile(t){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){let{endpoint:r,region:o,bucketName:i,accessKeyId:n,secretAccessKey:s,dir:a}=this.config;a||(a="KoodoReader");try{const c=(yield this.thirdpartyRequest.s3Download({bucket_name:i,object_key:a+"/"+t,region:o,endpoint:r,access_key_id:n,secret_access_key:s})).data.url;return(yield e({url:c,method:"get",headers:{},responseType:"arraybuffer",maxContentLength:1/0,maxBodyLength:1/0})).data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class F{constructor(e){let{username:t,password:r,url:n,dir:s}=e;s||(s="KoodoReader"),this.client=o(n,{authType:i.Password,username:t,password:r}),this.username=t,this.password=r,this.dir=s,this.taskQueue=new l(5)}retryOperation(e,t=0){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{!1===(yield this.client.exists(this.dir+"/"+r.substring(0,r.lastIndexOf("/"))))&&(yield this.client.createDirectory(this.dir+"/"+r.substring(0,r.lastIndexOf("/"))));let o=r.split("/").pop()||"",i=new File([t],o,{lastModified:(new Date).getTime(),type:t.type}),n=this.client.getFileUploadLink(this.dir+"/"+r);const s=new URL(n);s.search="",n=s.toString();const a=btoa(this.username+":"+this.password),c=yield e.put(n,i,{headers:{Authorization:"Basic "+a},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(t){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const r=this.client.getFileDownloadLink(this.dir+"/"+t),o=btoa(this.username+":"+this.password),i=yield e({url:r,method:"get",headers:{Authorization:"Basic "+o},responseType:"arraybuffer",maxContentLength:1/0,maxBodyLength:1/0});return i.status>=300?(console.error("Error occurred during file download:",i),!1):i.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}listFiles(e){return s(this,void 0,void 0,(function*(){try{return(yield this.client.getDirectoryContents(this.dir+"/"+e)).map((e=>e.basename))}catch(t){return t.response&&404===t.response.status&&(yield this.client.createDirectory(this.dir+"/"+e)),console.error("Error listing files:",t),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){try{return yield this.client.deleteFile(this.dir+"/"+e),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}}const I=["book","config","cover","font"];class L{constructor(e,t,r){this.type=e,this.remote="dropbox"===e?new k(t,r):"microsoft"===e?new x(t,r):"google"===e?new w(t,r):"s3compatible"===e?new A(t,r):"webdav"===e?new F(t):"boxnet"===e?new m(t,r):"mega"===e?new E(t):"adrive"===e?new g(t,r):"pcloud"===e?new R(t,r):new _}downloadFile(e,t){return s(this,void 0,void 0,(function*(){return!!(yield this.listFiles(t)).find((t=>e.indexOf(t)>-1))&&(yield this.remote.downloadFile(t+"/"+e))}))}uploadFile(e,t,r){return s(this,void 0,void 0,(function*(){return yield this.remote.uploadFile(r,t+"/"+e)}))}deleteFile(e,t){return s(this,void 0,void 0,(function*(){return!(yield this.listFiles(t)).find((t=>e.indexOf(t)>-1))||(yield this.remote.deleteFile(t+"/"+e))}))}listFiles(e){return s(this,void 0,void 0,(function*(){return yield this.remote.listFiles(e)}))}isExist(e,t){return s(this,void 0,void 0,(function*(){return(yield this.listFiles(t)).find((t=>-1!==t.indexOf(e)))}))}downloadAllFiles(){return s(this,void 0,void 0,(function*(){for(let e of I){let t=yield this.listFiles(e);for(let r of t)yield this.downloadFile(r,e)}}))}authToken(e){return s(this,void 0,void 0,(function*(){return yield this.remote.authToken(e)}))}getAuthUrl(){return this.remote.getAuthUrl?this.remote.getAuthUrl():""}getStats(){return this.remote.taskQueue.getStats()}resetCounters(){this.remote.taskQueue.resetCounters()}}const M={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 = ?"},j={notes:"SELECT * FROM notes WHERE bookKey = ?",bookmarks:"SELECT * FROM bookmarks WHERE bookKey = ?",words:"SELECT * FROM words WHERE bookKey = ?",books:"SELECT * FROM books WHERE key = ?"},z={notes:"DELETE FROM notes WHERE bookKey = ?",bookmarks:"DELETE FROM bookmarks WHERE bookKey = ?",words:"DELETE FROM words WHERE bookKey = ?"};function B(e){for(const t in e)e.hasOwnProperty(t)&&(e[`temp-${t}`]=e[t]);return e}const P={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 $,D={sqlStatement:{createTableStatement:B({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:B({notes:"SELECT * FROM notes",bookmarks:"SELECT * FROM bookmarks",books:"SELECT * FROM books",plugins:"SELECT * FROM plugins",words:"SELECT * FROM words"}),saveStatement:B({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:B({notes:"DELETE FROM notes",bookmarks:"DELETE FROM bookmarks",books:"DELETE FROM books",plugins:"DELETE FROM plugins",words:"DELETE FROM words"}),updateStatement:B({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:B({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:B({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:B(M),getByBookKeyStatement:B(j),getByBookKeysStatement:B({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(",")})`}),deleteByBookKeyStatement:B(z)},jsonToSqlite:B({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:B(P)};class N{constructor(e,t,r,o,i,n,s,a,c,l,d,u){this.key=e,this.name=t,this.author=r,this.description=o,this.md5=i,this.cover=n,this.format=s,this.publisher=a,this.size=c,this.page=l,this.path=d,this.charset=u}}class q{static generateBook(e,t,r,o,i,n,a){return new Promise(((c,l)=>s(this,void 0,void 0,(function*(){try{let s,l,d,u,p,h,f,g,y="";switch([l,d,p,u,h,f]=[e,"","","","",0],t){case"pdf":case"epub":case"mobi":case"azw":case"azw3":case"fb2":g=yield a.getMetadata(),[l,d,p,u,y]=[g.name||e,g.author||"",g.description||"",g.publisher||"",g.cover||""];break;case"cbr":case"cbt":case"cbz":case"cb7":g=yield a.getMetadata(),y=g.cover;break;case"txt":g=yield a.getMetadata(n),h=g.charset}let m=t.toUpperCase();s=(new Date).getTime()+"",c(new N(s,l,d,p,r,y,m,u,o,f,i,h))}catch(e){console.error(e),l(e)}}))))}}$=q,q.getRendtion=(e,t,r,o,i,n,s,a,c,l)=>{let d;var u,p;return"CACHE"===t?d=new l.CacheRender(e,{readerMode:r,animation:i,convertChinese:n,isDarkMode:a,isMobile:c}):"MOBI"===t||"AZW3"===t||"AZW"===t?d=new l.MobiRender(e,{readerMode:r,animation:i,convertChinese:n,isDarkMode:a,isMobile:c}):"EPUB"===t?d=new l.EpubRender(e,{readerMode:r,animation:i,convertChinese:n,isDarkMode:a,isMobile:c}):"TXT"===t?d=new l.TxtRender(e,{readerMode:r,animation:i,charset:o,convertChinese:n,parserRegex:s,isDarkMode:a,isMobile:c}):"MD"===t?d=new l.MdRender(e,{readerMode:r,animation:i,convertChinese:n,isDarkMode:a,isMobile:c}):"PDF"===t?d=new l.PdfRender(e,{readerMode:r,animation:i,convertChinese:n,isDarkMode:a,isMobile:c}):"FB2"===t?d=new l.Fb2Render(e,{readerMode:r,animation:i,convertChinese:n,isDarkMode:a,isMobile:c}):"DOCX"===t?d=new l.DocxRender(e,{readerMode:r,animation:i,convertChinese:n,isDarkMode:a,isMobile:c}):"HTML"===t||"XHTML"===t||"MHTML"===t||"HTM"===t||"XML"===t?d=new l.HtmlRender(e,{readerMode:r,format:t,animation:i,convertChinese:n,isDarkMode:a,isMobile:c}):"CBR"!==t&&"CBT"!==t&&"CBZ"!==t&&"CB7"!==t||(d=new l.ComicRender((u=e,p=new ArrayBuffer(u.byteLength),new Uint8Array(p).set(new Uint8Array(u)),p),{readerMode:r,format:t,animation:i,convertChinese:n,isDarkMode:a,isMobile:c})),d},q.initMobileBook=(e,t,r,o,i,n,a,c,l)=>s(void 0,void 0,void 0,(function*(){try{const s=yield fetch(e);if(!s.ok)throw new Error(`Failed to download book: ${s.status} ${s.statusText}`);const d=yield s.arrayBuffer();window.ReactNativeWebView.postMessage(JSON.stringify({event:"finish-download"})),window.file_content=d;let u=$.getRendtion(d,t,r,o,i,n,a,l,"yes",window.Kookit);window.rendition=u;let p=document.getElementById("page-area");t&&"TXT"===t.toUpperCase()?yield window.rendition.renderTo(p,c):yield window.rendition.renderTo(p),window.rendition.on("rendered",(()=>{let e=window.rendition.getPosition();window.ReactNativeWebView.postMessage(JSON.stringify({event:"content-loaded",bookLocation:e})),window.rendition.tsTransform()})),window.rendition.on("page-changed",(()=>{let e=window.rendition.getPosition();window.ReactNativeWebView.postMessage(JSON.stringify({event:"page-changed",bookLocation:e}))})),window.ReactNativeWebView.postMessage(JSON.stringify({event:"book-inited",chapterList:window.rendition.getChapter()}))}catch(e){window.ReactNativeWebView.postMessage(JSON.stringify({event:"error",message:"Parse book failed"}))}})),q.addMobileBook=(e,t,r,o,i,n,a="")=>s(void 0,void 0,void 0,(function*(){var s;try{const c=yield fetch(e);if(!c.ok)throw new Error(`Failed to download book: ${c.status} ${c.statusText}`);const l=yield c.arrayBuffer();null===(s=window.ReactNativeWebView)||void 0===s||s.postMessage(JSON.stringify({event:"finish-download"})),window.file_content=l;let d=$.getRendtion(l,r.toUpperCase(),"","","","no",a,"no","yes",window.Kookit);window.rendition=d,t=t.replace(/\.[^/.]+$/,"");let u=yield q.generateBook(t,r,o,i,n,l,d);if(!u||!u.key)return;window.ReactNativeWebView.postMessage(JSON.stringify({event:"metadata",bookInfo:u}))}catch(e){window.ReactNativeWebView.postMessage(JSON.stringify({event:"error",message:"Parse book failed"}))}})),q.precacheMobileBook=(e,t)=>s(void 0,void 0,void 0,(function*(){let r=yield window.rendition.preCache(window.file_content);if(""===r)window.ReactNativeWebView.postMessage(JSON.stringify({event:"cache",cacheBase64:"",key:t}));else if("err"!==r){try{const o=`${e}/dav/${"cache-"+t+".zip"}`,i=yield fetch(o,{method:"PUT",headers:{"Content-Type":"application/octet-stream",Overwrite:"T"},body:r});if(!i.ok)throw new Error(`上传失败: ${i.status}`);console.info("文件上传成功")}catch(e){console.error("操作失败:"+e)}window.ReactNativeWebView.postMessage(JSON.stringify({event:"cache",key:t}))}else window.ReactNativeWebView.postMessage(JSON.stringify({event:"error",message:"Parse book failed"}));window.file_content=null,window.rendition=null}));const U=u.cloudUrl;class W{constructor(e,t){this.processingQueue=!1,this.requestQueue=[],this.TokenService=e,this.ConfigService=t,this.refreshToken="",this.accessToken="",this.streamPromise=null}refreshUserToken(){return s(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(U+"/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),this.accessToken=t.data.access_token,this.refreshToken=t.data.refresh_token),t}))}requestWithRetry(e){return s(this,void 0,void 0,(function*(){return this.requestQueue||(this.requestQueue=[]),new Promise(((t,r)=>{this.requestQueue.push({config:e,resolve:t,reject:r}),this.processingQueue||this.processQueue()}))}))}processQueue(){return s(this,void 0,void 0,(function*(){if(!this.processingQueue){this.processingQueue=!0;try{for(;this.requestQueue.length>0;){const e=this.requestQueue.shift();try{let t=yield this.executeRequest(e.config);e.resolve(t)}catch(t){e.reject(t)}}}finally{this.processingQueue=!1}}}))}executeRequest(t){return s(this,void 0,void 0,(function*(){try{try{this.accessToken=(yield this.TokenService.getToken("access_token"))||""}catch(e){console.error("Error get Token:",e)}let r="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);t.baseURL=U,t.headers?(t.headers.Authorization="Bearer "+this.accessToken,t.headers["X-Request-ID"]=r):t.headers={Authorization:"Bearer "+this.accessToken,"X-Request-ID":r};let o=(yield e(t)).data;if(402===o.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!==o.code&&this.ConfigService.setItem("errorLog",JSON.stringify({request:t.data,url:t.url,result:o,requestID:r})),o}catch(e){return console.error("Request execution error:",e),{code:503,message:"network error",data:null}}}))}requestWithStream(e,t,r){return s(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>s(this,void 0,void 0,(function*(){try{let o="";try{o=(yield this.TokenService.getToken("access_token"))||""}catch(e){console.error("Error get Token:",e)}let i="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((n,a)=>{const c=new r(U+e.url,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+o,"X-Request-ID":i},method:e.method,body:JSON.stringify(e.data),pollingInterval:0});c.addEventListener("open",(()=>{console.info("Connection to OpenAI established.")})),c.addEventListener("message",(e=>s(this,void 0,void 0,(function*(){if(!e.data)return;const r=JSON.parse(e.data);r.done?(c.close(),n(r)):(402===r.code&&(yield this.refreshUserToken()),t(r.data))})))),c.addEventListener("error",(e=>{console.error("Error:",e),n({code:500,message:"internal error"}),c.close()}))}))}finally{this.streamPromise=null}})))()),this.streamPromise}))}requestWithFetch(e,t){return s(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>s(this,void 0,void 0,(function*(){try{let r="";try{r=(yield this.TokenService.getToken("access_token"))||""}catch(e){console.error("Error get Token:",e)}let o="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((i,n)=>s(this,void 0,void 0,(function*(){const n=yield fetch(U+e.url,{method:"POST",headers:{"Content-Type":"text/event-stream",Authorization:"Bearer "+r,"X-Request-ID":o},body:JSON.stringify(e.data)});if(!n.body)throw new Error("Response body is null");const s=n.body.pipeThrough(new TextDecoderStream).getReader();for(;;){const{value:e,done:r}=yield s.read();if(r){t({done:!0});break}if(e)if(e.includes('"code":400')||e.includes('"code":401')||e.includes('"code":402')){let t=JSON.parse(e);402===t.code&&(yield this.refreshUserToken()),i(t)}else e.split("\n").forEach((e=>{if(e.startsWith("data:")){const r=JSON.parse(e.substring(5));t(r.data)}}))}}))))}finally{this.streamPromise=null}})))()),this.streamPromise}))}}class K extends W{constructor(e,t){super(e,t)}getTransStream(e,t,r){return s(this,void 0,void 0,(function*(){const o={method:"post",url:"/api/v1/pro/reader/get_llm_trans_stream",data:e};return yield this.requestWithStream(o,t,r)}))}getTransFetch(e,t){return s(this,void 0,void 0,(function*(){const r={method:"post",url:"/api/v1/pro/reader/get_llm_trans_stream",data:e};return yield this.requestWithFetch(r,t)}))}getDictionary(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/reader/get_llm_dict",data:e};return yield this.requestWithRetry(t)}))}getSummaryStream(e,t,r){return s(this,void 0,void 0,(function*(){const o={method:"post",url:"/api/v1/pro/reader/get_llm_sum_stream",data:e};return yield this.requestWithStream(o,t,r)}))}getAnswerStream(e,t,r){return s(this,void 0,void 0,(function*(){const o={method:"post",url:"/api/v1/pro/reader/get_llm_answer_stream",data:e};return yield this.requestWithStream(o,t,r)}))}getSummaryFetch(e,t){return s(this,void 0,void 0,(function*(){const r={method:"post",url:"/api/v1/pro/reader/get_llm_sum_stream",data:e};return yield this.requestWithFetch(r,t)}))}getGoogleFont(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/reader/get_google_font",data:e};return yield this.requestWithRetry(t)}))}sendToKindle(e){return s(this,void 0,void 0,(function*(){let t=new FormData;t.append("file",e.file),t.append("email",e.email),t.append("file_name",e.fileName);const r={method:"post",url:"/api/v1/pro/reader/send_to_kindle",headers:{"Content-Type":"multipart/form-data"},data:t};return yield this.requestWithRetry(r)}))}}class Q extends W{constructor(e,t){super(e,t)}encryptToken(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/encrypt_token",data:e};return yield this.requestWithRetry(t)}))}decryptToken(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/decrypt_token",data:e};return yield this.requestWithRetry(t)}))}authThirdToken(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/auth_token",data:e};return yield this.requestWithRetry(t)}))}refreshThirdToken(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/refresh_token",data:e};return yield this.requestWithRetry(t)}))}s3Upload(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/s3_upload",data:e};return yield this.executeRequest(t)}))}s3Download(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/s3_download",data:e};return yield this.executeRequest(t)}))}s3List(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/s3_list",data:e};return yield this.executeRequest(t)}))}s3Delete(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/s3_delete",data:e};return yield this.executeRequest(t)}))}getSyncState(){return s(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"get",url:"/api/v1/pro/thirdparty/get_sync_state"})}))}deleteSyncState(){return s(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"post",url:"/api/v1/pro/thirdparty/delete_sync_state"})}))}}class J extends W{constructor(e,t){super(e,t)}loginRegister(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/public/user/login_register",data:e};return yield this.requestWithRetry(t)}))}logout(){return s(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"post",url:"/api/v1/member/user/logout"})}))}getLogins(){return s(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"post",url:"/api/v1/member/user/get_logins"})}))}addLogin(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/member/user/add_login",data:e};return yield this.requestWithRetry(t)}))}removeLogin(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/member/user/remove_login",data:e};return yield this.requestWithRetry(t)}))}getUserInfo(){return s(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"post",url:"/api/v1/member/user/get_info"})}))}getTempToken(){return s(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"get",url:"/api/v1/member/user/get_temp_token"})}))}sendEmailCode(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/public/user/send_email_code",data:e};return yield this.requestWithRetry(t)}))}checkEmailRegistration(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/public/user/check_email_registration",data:e};return yield this.requestWithRetry(t)}))}redeemCode(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/member/user/redeem_code",data:e};return yield this.requestWithRetry(t)}))}deleteAccount(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/member/user/delete_account",data:e};return yield this.requestWithRetry(t)}))}}var H={getAuthUrl:(e,t)=>{let r="";if("github"===e?r=`https://github.com/login/oauth/authorize?client_id=${p.githubClientId}&redirect_uri=${p.callbackUrl}&scope=openid`:"google"===e?r=`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${p.callbackUrl}&prompt=consent&response_type=code&client_id=${p.googleClientId}&scope=openid&access_type=offline`:"facebook"===e?r=`https://www.facebook.com/v12.0/dialog/oauth?client_id=${p.facebookClientId}&redirect_uri=${p.callbackUrl}&scope=&response_type=code`:"microsoft"===e&&(r=`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${p.microsoftClientId}&scope=openid profile User.Read offline_access&response_type=code&redirect_uri=${p.callbackUrl}`),"manual"===t)return r;let o=JSON.stringify({deeplink:"desktop"===t?"koodo-reader://callback":"browser"===t?"https://web.koodoreader.com/#/login":"",service:e});return`${r}&state=${"state|"+encodeURIComponent(o)}`}};class V{static CompareDatabase(e,t,r){return s(this,void 0,void 0,(function*(){let o=Object.keys(e).filter((e=>e.startsWith("database.sqlite.books"))),i=Object.keys(e).filter((e=>e.startsWith("database.sqlite.notes"))),n=Object.keys(e).filter((e=>e.startsWith("database.sqlite.bookmarks"))),s=Object.keys(e).filter((e=>e.startsWith("database.sqlite.plugins"))),a=Object.keys(e).filter((e=>e.startsWith("database.sqlite.words"))),c=Object.keys(t).filter((e=>e.startsWith("database.sqlite.books"))),l=Object.keys(t).filter((e=>e.startsWith("database.sqlite.notes"))),d=Object.keys(t).filter((e=>e.startsWith("database.sqlite.bookmarks"))),u=Object.keys(t).filter((e=>e.startsWith("database.sqlite.plugins"))),p=Object.keys(t).filter((e=>e.startsWith("database.sqlite.words"))),h={books:Array.from(new Set(o.concat(c))),notes:Array.from(new Set(i.concat(l))),bookmarks:Array.from(new Set(n.concat(d))),plugins:Array.from(new Set(s.concat(u))),words:Array.from(new Set(a.concat(p)))},f={books:{save:[],update:[],delete:[],conflict:[],upload:[]},notes:{save:[],update:[],delete:[],conflict:[],upload:[]},bookmarks:{save:[],update:[],delete:[],conflict:[],upload:[]},plugins:{save:[],update:[],delete:[],conflict:[],upload:[]},words:{save:[],update:[],delete:[],conflict:[],upload:[]}},g=["books","notes","bookmarks","plugins","words"];for(let o of g)for(let i of h[o]){let n=i.split(".")[3],s=e[i],a=t[i];s?a?("save"===a.operation&&("update"===s.operation||"delete"===s.operation?f[o].upload.push(n):console.info("ignore",a)),"delete"===a.operation&&("save"===s.operation&&(f[o].delete.push(n),e[i]=a),"update"===s.operation&&(s.timea.time?(f[o].conflict.push(n),"cloud"===r?(f[o].delete.push(n),e[i]=a):f[o].upload.push(n)):console.info("ignore",a)),"delete"===s.operation&&console.info("ignore",a)),"update"===a.operation&&("save"===s.operation&&(f[o].update.push(n),e[i]=a),"update"===s.operation&&(s.timea.time?f[o].upload.push(n):console.info("ignore",a)),"delete"===s.operation&&(s.timea.time?f[o].upload.push(n):console.info("ignore",a)))):f[o].upload.push(n):(f[o].save.push(n),e[i]=a)}return{compareResult:f,syncRecords:e}}))}static CompareConfig(e,t,r){return s(this,void 0,void 0,(function*(){let o=Object.keys(e).filter((e=>e.startsWith("config.readerConfig"))),i=Object.keys(e).filter((e=>e.startsWith("config.listConfig"))),n=Object.keys(e).filter((e=>e.startsWith("config.objectConfig"))),s=Object.keys(e).filter((e=>e.startsWith("config.mapConfig"))),a=Object.keys(t).filter((e=>e.startsWith("config.readerConfig"))),c=Object.keys(t).filter((e=>e.startsWith("config.listConfig"))),l=Object.keys(t).filter((e=>e.startsWith("config.objectConfig"))),d=Object.keys(t).filter((e=>e.startsWith("config.mapConfig"))),u={readerConfig:Array.from(new Set(o.concat(a))),listConfig:Array.from(new Set(i.concat(c))),objectConfig:Array.from(new Set(n.concat(l))),mapConfig:Array.from(new Set(s.concat(d)))},p={readerConfig:{update:[],upload:[]},listConfig:{update:[],upload:[]},objectConfig:{update:[],delete:[],conflict:[],upload:[]},mapConfig:{update:[],delete:[],conflict:[],upload:[]}},h=["readerConfig","listConfig"];for(let r of h)for(let o of u[r]){let i=o,n=e[o],s=t[o];n?s?n.times.time?p[r].upload.push(i):console.info("ignore",s):p[r].upload.push(i):(p[r].update.push(i),e[o]=s)}let f=["objectConfig","mapConfig"];for(let o of f)for(let i of u[o]){let n=i,s=e[i],a=t[i];s?a?("delete"===a.operation&&("update"===s.operation&&(s.timea.time?(p[o].conflict.push(n),"cloud"===r?(p[o].delete.push(n),e[i]=a):p[o].upload.push(n)):console.info("ignore",a)),"delete"===s.operation&&console.info("ignore",a)),"update"===a.operation&&("update"===s.operation&&(s.timea.time?p[o].upload.push(n):console.info("ignore",a)),"delete"===s.operation&&(s.timea.time?p[o].upload.push(n):console.info("ignore",a)))):p[o].upload.push(n):(p[o].update.push(n),e[i]=a)}return{compareResult:p,syncRecords:e}}))}static compareAll(e,t,r,o,i){return s(this,void 0,void 0,(function*(){let n="cloud";if("yes"===r.getReaderConfig("isKeepLocal")){n="local";let e=r.getObjectConfig(yield o.getFingerprint(),"cloudSyncTime",{time:0,conflictMode:"cloud"}),t=yield i.getCloudConfig("config"),s=JSON.parse(t.cloudSyncTime||"{}");delete s[yield o.getFingerprint()],Object.values(s).filter((t=>"local"===t.conflictMode&&t.time>e.time)).length>0&&(n="cloud")}let{compareResult:s,syncRecords:a}=yield this.CompareDatabase(e,t,n),{compareResult:c,syncRecords:l}=yield this.CompareConfig(a,t,n),d=Object.assign(Object.assign({},s),c);return r.setAllSyncRecord(l),"local"===n&&(d.books.conflict.length>0||d.notes.conflict.length>0||d.bookmarks.conflict.length>0||d.plugins.conflict.length>0||d.words.conflict.length>0||d.objectConfig.conflict.length>0||d.mapConfig.conflict.length>0)?r.setObjectConfig(yield o.getFingerprint(),{time:(new Date).getTime(),conflictMode:"local"},"cloudSyncTime"):r.setObjectConfig(yield o.getFingerprint(),{time:(new Date).getTime(),conflictMode:"cloud"},"cloudSyncTime"),d}))}static startSync(e,t,r,o,i,n){return s(this,void 0,void 0,(function*(){return[...yield this.syncConfig(e,t,r,i,o),...yield this.syncCover(t,n,i),...yield this.syncBook(t,i)]}))}static syncConfig(e,t,r,o,i){return s(this,void 0,void 0,(function*(){let n=[];for(let t of c){if(e[t].save.length+e[t].update.length>0){let o=yield i.getCloudDatabase(t);for(let i of e[t].save){let e=o.find((e=>e.key===i));e&&(yield r.saveRecord(e,t))}for(let i of e[t].update){let e=o.find((e=>e.key===i));e&&(yield r.updateRecord(e,t,!1))}}if(e[t].delete.length>0)for(let i of e[t].delete)yield r.deleteRecord(i,t),"books"===t&&(yield o.deleteOfflineBook(i))}if(e.readerConfig.update.length>0||e.listConfig.update.length>0||e.objectConfig.update.length>0||e.mapConfig.update.length>0){let r=yield i.getCloudConfig("config");for(let o of e.readerConfig.update){let e=o.split(".")[3];r.readerConfig&&t.setReaderConfig(e,JSON.parse(r.readerConfig)[e],!1)}for(let o of e.listConfig.update){let e=o.split(".")[3];r[e]&&t.setAllListConfig(JSON.parse(r[e]),e,!1)}for(let o of e.objectConfig.update){let e=o.split(".")[3],i=o.split(".")[2];r[i]&&JSON.parse(r[i])&&JSON.parse(r[i])[e]&&t.setObjectConfig(e,JSON.parse(r[i])[e],i,!1)}for(let o of e.mapConfig.update){let e=o.split(".")[3],i=o.split(".")[2];if(r[i]&&JSON.parse(r[i])&&JSON.parse(r[i])[e]){let o=JSON.parse(r[i])[e];t.setOneMapConfig(e,o,i,!1)}}}if(e.objectConfig.delete.length>0||e.mapConfig.delete.length>0){for(let r of e.objectConfig.delete){let e=r.split(".")[3],o=r.split(".")[2];t.deleteObjectConfig(e,o)}for(let r of e.mapConfig.delete){let e=r.split(".")[3],o=r.split(".")[2];t.deleteMapConfig(e,o)}}for(let t of c)e[t].upload.length>0&&n.push((()=>i.uploadDatabase(t)));return n.push((()=>i.uploadConfig("config"))),n.push((()=>i.uploadConfig("sync"))),n}))}static syncCover(e,t,r){return s(this,void 0,void 0,(function*(){let r=yield t.getLocalCoverList(),o=yield t.getCloudCoverList(),i=Array.from(new Set([...r,...o])),n=[];for(let s of i)r.includes(s)&&!o.includes(s)&&n.push((()=>t.uploadCover(s))),!r.includes(s)&&o.includes(s)&&"adrive"!==e.getItem("defaultSyncOption")&&n.push((()=>t.downloadCover(s)));return n}))}static syncBook(e,t){return s(this,void 0,void 0,(function*(){let r=yield t.getLocalBookList(),o=yield t.getCloudBookList(),i=[],n=Array.from(new Set([...r,...o]));for(let s of n){if(r.includes(s)&&!o.includes(s)){let e=s.split(".")[0],r=s.split(".")[1];i.push((()=>t.uploadBook(e,r)))}let n="yes"===e.getReaderConfig("autoOffline");if(!r.includes(s)&&o.includes(s)&&n&&"adrive"!==e.getItem("defaultSyncOption")){let e=s.split(".")[0],r=s.split(".")[1];i.push((()=>t.offlineBook(e,r.toUpperCase())))}}return i}))}static runTasksWithLimit(e,t,r){return s(this,void 0,void 0,(function*(){if("ftp"!==r&&"adrive"!==r){const r=[],o=[];for(const i of e){const e=i().then((t=>(o.splice(o.indexOf(e),1),t)));r.push(e),o.push(e),o.length>=t&&(yield Promise.race(o))}return Promise.all(r)}for(let t of e)yield t()}))}}const X=(Y=class{static getItem(e){return localStorage.getItem(e)}static setItem(e,t){localStorage.setItem(e,t)}static removeItem(e){localStorage.removeItem(e)}},G="browser",class extends Y{static getReaderConfig(e){return JSON.parse(this.getItem("readerConfig")||"{}")[e]}static setReaderConfig(e,t,r=!0){let o=JSON.parse(this.getItem("readerConfig")||"{}");o[e]=t,this.setItem("readerConfig",JSON.stringify(o)),r&&this.setSyncRecord({type:"config",catergory:"readerConfig",name:G,key:e},{operation:"update",time:Date.now()})}static getAllListConfig(e){return("{}"!==this.getItem(e)&&this.getItem(e)?JSON.parse(this.getItem(e)||""):[])||[]}static deleteListConfig(e,t){let r=this.getAllListConfig(t);const o=r.indexOf(e);o>-1&&r.splice(o,1),this.setAllListConfig(r,t)}static setListConfig(e,t){let r=this.getAllListConfig(t);const o=r.indexOf(e);o>-1?(r.splice(o,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,o=!0){let i=this.getAllObjectConfig(r);i[e]=t,o&&this.setSyncRecord({type:"config",catergory:"objectConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllObjectConfig(i,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 o=this.getAllMapConfig(r);void 0===o[e]&&(o[e]=[]),t&&-1===o[e].indexOf(t)&&o[e].unshift(t),this.setSyncRecord({type:"config",catergory:"mapConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(o,r)}static setOneMapConfig(e,t,r,o=!0){let i=this.getAllMapConfig(r);i[e]=t,o&&this.setSyncRecord({type:"config",catergory:"mapConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(i,r)}static deleteFromMapConfig(e,t,r){let o=this.getAllMapConfig(r),i=o[e].indexOf(t);o[e].splice(i,1),this.setSyncRecord({type:"config",catergory:"mapConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(o,r)}static deleteFromAllMapConfig(e,t){let r=this.getAllMapConfig(t);Object.keys(r).forEach((o=>{let i=r[o].indexOf(e);i>-1&&(r[o].splice(i,1),this.setSyncRecord({type:"config",catergory:"mapConfig",name:t,key:o},{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),o=[];for(let t in r)r[t]&&r[t].indexOf(e)>-1&&o.push(t);return o}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 setSyncRecord(e,t){let r=JSON.parse(this.getItem("syncRecord")||"{}");r[e.type+"."+e.catergory+"."+e.name+"."+e.key]=t,this.setItem("syncRecord",JSON.stringify(r))}static setAllSyncRecord(e){this.setItem("syncRecord",JSON.stringify(e))}});var Y,G;let Z;const ee=new Uint8Array(16);function te(){if(!Z&&(Z="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Z))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Z(ee)}const re=[];for(let e=0;e<256;++e)re.push((e+256).toString(16).slice(1));var oe={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function ie(e,t,r){if(oe.randomUUID&&!t&&!e)return oe.randomUUID();const o=(e=e||{}).random||(e.rng||te)();if(o[6]=15&o[6]|64,o[8]=63&o[8]|128,t){r=r||0;for(let e=0;e<16;++e)t[r+e]=o[e];return t}return function(e,t=0){return re[e[t+0]]+re[e[t+1]]+re[e[t+2]]+re[e[t+3]]+"-"+re[e[t+4]]+re[e[t+5]]+"-"+re[e[t+6]]+re[e[t+7]]+"-"+re[e[t+8]]+re[e[t+9]]+"-"+re[e[t+10]]+re[e[t+11]]+re[e[t+12]]+re[e[t+13]]+re[e[t+14]]+re[e[t+15]]}(o)}class ne{static saveAllToken(e){return s(this,void 0,void 0,(function*(){if(e)if(n){const{ipcRenderer:t}=window.require("electron");t.invoke("encrypt-data",{token:e})}else{const t=yield this.encryptString(e);localStorage.setItem("encryptedToken",t)}}))}static getAllToken(){return s(this,void 0,void 0,(function*(){if(n){const{ipcRenderer:e}=window.require("electron");return yield e.invoke("decrypt-data")}{let e=localStorage.getItem("encryptedToken")||"";return e?yield this.decryptString(e):null}}))}static setToken(e,t){return s(this,void 0,void 0,(function*(){const r=JSON.parse((yield this.getAllToken())||"{}");r[e]=t,yield this.saveAllToken(JSON.stringify(r))}))}static getToken(e){return s(this,void 0,void 0,(function*(){return JSON.parse((yield this.getAllToken())||"{}")[e]||null}))}static deleteToken(e){return s(this,void 0,void 0,(function*(){const t=JSON.parse((yield this.getAllToken())||"{}");delete t[e],yield this.saveAllToken(JSON.stringify(t))}))}static encryptString(e){return s(this,void 0,void 0,(function*(){try{let t=yield this.getFingerprint();const r=yield ce(t),o=yield function(e,t,r={alg:"HS256",typ:"JWT"}){return s(this,void 0,void 0,(function*(){const o=se((new TextEncoder).encode(JSON.stringify(r))),i=se((new TextEncoder).encode(JSON.stringify(e))),n=(new TextEncoder).encode(`${o}.${i}`),s=yield crypto.subtle.importKey("raw",(new TextEncoder).encode(t),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return`${o}.${i}.${se(yield crypto.subtle.sign("HMAC",s,n))}`}))}(e,r);return o}catch(e){return console.error("Error generating secret:",e),""}}))}static decryptString(e){return s(this,void 0,void 0,(function*(){try{let t=yield this.getFingerprint();const r=yield ce(t),o=yield function(e,t){return s(this,void 0,void 0,(function*(){const[r,o,i]=e.split("."),n=(new TextEncoder).encode(`${r}.${o}`),s=yield ae(i),a=yield crypto.subtle.importKey("raw",(new TextEncoder).encode(t),{name:"HMAC",hash:{name:"SHA-256"}},!1,["verify"]);if(!(yield crypto.subtle.verify("HMAC",a,s,n)))throw new Error("Invalid signature");return JSON.parse((new TextDecoder).decode(ae(o)))}))}(e,r);return o}catch(e){return console.error("Error generating secret:",e),""}}))}static oldDecryptString(e){return s(this,void 0,void 0,(function*(){let t=yield this.getFingerprint();const r=yield crypto.subtle.digest("SHA-256",(new TextEncoder).encode(t)),o=yield crypto.subtle.importKey("raw",r,{name:"AES-GCM",length:256},!1,["decrypt"]),i=new Uint8Array(e.split("").map((e=>e.charCodeAt(0)))),n=i.slice(0,12),s=i.slice(12),a=yield crypto.subtle.decrypt({name:"AES-GCM",iv:n},o,s);return(new TextDecoder).decode(a)}))}static getFingerprint(){return s(this,void 0,void 0,(function*(){if(n){const{ipcRenderer:e}=window.require("electron");return yield e.invoke("get-mac")}{let e=X.getItem("fingerPrint");if(e)return e;let t=ie().replace(/-/g,"");return X.setItem("fingerPrint",t),t}}))}}function se(e){return btoa(String.fromCharCode.apply(null,Array.from(new Uint8Array(e)))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function ae(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=atob(t),o=new Uint8Array(r.length);for(let e=0;e=0&&r<=Re}}function rt(e){return function(t){return null==t?void 0:t[e]}}var ot=rt("byteLength"),it=tt(ot),nt=/\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/;var st=ve?function(e){return Ee?Ee(e)&&!He(e):it(e)&&nt.test(ye.call(e))}:et(!1),at=rt("length");function ct(e,t){t=function(e){for(var t={},r=e.length,o=0;o":">",'"':""","'":"'","`":"`"},Gt=Xt(Yt),Zt=Xt(Ot(Yt)),er=ut.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g},tr=/(.)^/,rr={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},or=/\\|'|\r|\n|\u2028|\u2029/g;function ir(e){return"\\"+rr[e]}var nr=/^\s*(\w|\$)+\s*$/;var sr=0;function ar(e,t,r,o,i){if(!(o instanceof t))return e.apply(r,i);var n=jt(e.prototype),s=e.apply(n,i);return Ae(s)?s:n}var cr=Oe((function(e,t){var r=cr.placeholder,o=function(){for(var i=0,n=t.length,s=Array(n),a=0;a1)ur(a,t-1,r,o),i=o.length;else for(var c=0,l=a.length;c0&&(r=t.apply(this,arguments)),e<=1&&(t=null),r}}var mr=cr(yr,2);function vr(e,t,r){t=Qt(t,r);for(var o,i=lt(e),n=0,s=i.length;n0?0:i-1;n>=0&&n0?s=n>=0?n:Math.max(n+a,s):a=n>=0?Math.min(n+1,a):n+a+1;else if(r&&n&&a)return o[n=r(o,i)]===i?n:-1;if(i!=i)return(n=t(ge.call(o,s,a),Ze))>=0?n+s:-1;for(n=e>0?s:a-1;n>=0&&n=3;return function(t,r,o,i){var n=!dr(t)&<(t),s=(n||t).length,a=e>0?0:s-1;for(i||(o=t[n?n[a]:a],a+=e);a>=0&&a=0}var zr=Oe((function(e,t,r){var o,i;return Ue(t)?i=t:(t=Bt(t),o=t.slice(0,-1),t=t[t.length-1]),Rr(e,(function(e){var n=i;if(!n){if(o&&o.length&&(e=Pt(e,o)),null==e)return;n=e[t]}return null==n?n:n.apply(e,r)}))}));function Br(e,t){return Rr(e,qt(t))}function Pr(e,t,r){var o,i,n=-1/0,s=-1/0;if(null==t||"number"==typeof t&&"object"!=typeof e[0]&&null!=e)for(var a=0,c=(e=dr(e)?e:Rt(e)).length;an&&(n=o);else t=Qt(t,r),Sr(e,(function(e,r,o){((i=t(e,r,o))>s||i===-1/0&&n===-1/0)&&(n=e,s=i)}));return n}var $r=/[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g;function Dr(e){return e?Ve(e)?ge.call(e):Me(e)?e.match($r):dr(e)?Rr(e,Dt):Rt(e):[]}function Nr(e,t,r){if(null==t||r)return dr(e)||(e=Rt(e)),e[Ht(e.length-1)];var o=Dr(e),i=at(o);t=Math.max(Math.min(t,i),0);for(var n=i-1,s=0;s1&&(o=Ut(o,t[1])),t=yt(e)):(o=Jr,t=ur(t,!1,!1),e=Object(e));for(var i=0,n=t.length;i1&&(r=t[1])):(t=Rr(ur(t,!1,!1),String),o=function(e,r){return!jr(t,r)}),Hr(e,o,r)}));function Xr(e,t,r){return ge.call(e,0,Math.max(0,e.length-(null==t||r?1:t)))}function Yr(e,t,r){return null==e||e.length<1?null==t||r?void 0:[]:null==t||r?e[0]:Xr(e,e.length-t)}function Gr(e,t,r){return ge.call(e,null==t||r?1:t)}var Zr=Oe((function(e,t){return t=ur(t,!0,!0),Ir(e,(function(e){return!jr(t,e)}))})),eo=Oe((function(e,t){return Zr(e,t)}));function to(e,t,r,o){Ie(t)||(o=r,r=t,t=!1),null!=r&&(r=Qt(r,o));for(var i=[],n=[],s=0,a=at(e);st?(o&&(clearTimeout(o),o=null),a=l,s=e.apply(i,n),o||(i=n=null)):o||!1===r.trailing||(o=setTimeout(c,d)),s};return l.cancel=function(){clearTimeout(o),a=0,o=i=n=null},l},debounce:function(e,t,r){var o,i,n,s,a,c=function(){var l=Vt()-i;t>l?o=setTimeout(c,t-l):(o=null,r||(s=e.apply(a,n)),o||(n=a=null))},l=Oe((function(l){return a=this,n=l,i=Vt(),o||(o=setTimeout(c,t),r&&(s=e.apply(a,n))),s}));return l.cancel=function(){clearTimeout(o),o=n=a=null},l},wrap:function(e,t){return cr(t,e)},negate:gr,compose:function(){var e=arguments,t=e.length-1;return function(){for(var r=t,o=e[t].apply(this,arguments);r--;)o=e[r].call(this,o);return o}},after:function(e,t){return function(){if(--e<1)return t.apply(this,arguments)}},before:yr,once:mr,findKey:vr,findIndex:br,findLastIndex:wr,sortedIndex:Tr,indexOf:Cr,lastIndexOf:xr,find:_r,detect:_r,findWhere:function(e,t){return _r(e,Nt(t))},each:Sr,forEach:Sr,map:Rr,collect:Rr,reduce:Ar,foldl:Ar,inject:Ar,reduceRight:Fr,foldr:Fr,filter:Ir,select:Ir,reject:function(e,t,r){return Ir(e,gr(Qt(t)),r)},every:Lr,all:Lr,some:Mr,any:Mr,contains:jr,includes:jr,include:jr,invoke:zr,pluck:Br,where:function(e,t){return Ir(e,Nt(t))},max:Pr,min:function(e,t,r){var o,i,n=1/0,s=1/0;if(null==t||"number"==typeof t&&"object"!=typeof e[0]&&null!=e)for(var a=0,c=(e=dr(e)?e:Rt(e)).length;ao||void 0===r)return 1;if(re.map((e=>e.name)),uo=e=>e.map((e=>e.key)),po=(e,t)=>{let r=[];for(let o=0;o-1&&r.push(t.indexOf(e[o]));return r.length{if(-1===e.indexOf(o))for(let e=0;ee-Math.min(...r))))]};class ho{static sortBooks(e,t,r){let o=e.map((e=>e.key)),i=(e=>e.getAllListConfig("recentBooks"))(r);if(1===t.sort||0===t.sort)return 1===t.order?po(i,o).reverse():po(i,o);if(2===t.sort){let r=lo(e),o=lo(e).sort();return 1===t.order?po(o,r).reverse():po(o,r)}if(3===t.sort){let r=[];for(let t=0;t{let t=e.getAllObjectConfig("readingTime");var r=[];for(let e in t)r.push([e,t[e]]);return r.sort((function(e,t){return e[1]-t[1]})),Object.keys(t)})(r),i=uo(e);return 1===t.order?po(co.union(o,i),i).reverse():po(co.union(o,i),i)}if(5===t.sort){let r=uo(e),o=(e=>co.sortBy(e.map((e=>({key:e.key,author:e.author}))),"author").map((e=>e.key)))(e);return 1===t.order?po(o,r).reverse():po(o,r)}if(6===t.sort){let o=(e=>{let t=e.getAllObjectConfig("recordLocation");var r=[];for(let e in t)r.push([e,t[e].percentage||0]);return r.sort((function(e,t){return e[1]-t[1]})),r.map((e=>e[0]))})(r),i=uo(e);return 1===t.order?po(o,i).reverse():po(o,i)}}static sortNotes(e,t,r=[]){if(3===t.sort){let r=co.clone(e).reverse(),o=co.uniq(e.map((e=>({chapter:e.chapter,chapterIndex:e.chapterIndex}))));o=1===t.order?co.sortBy(o,"chapterIndex"):co.sortBy(o,"chapterIndex").reverse();let i=co.uniq(o.map((e=>e.chapter))),n={};return i.forEach((e=>{n[e]=[]})),r.forEach((e=>{n[e.chapter].push(e)})),i.map((e=>({group:e,notes:n[e]})))||[]}if(2===t.sort){let r=co.clone(e).reverse(),o=co.uniq(e.map((e=>e.date.year+"-"+e.date.month+"-"+e.date.day)));1===t.order?o.sort():o.sort().reverse();let i={};return o.forEach((e=>{i[e]=[]})),r.forEach((e=>{o.forEach((t=>{t===e.date.year+"-"+e.date.month+"-"+e.date.day&&i[t].push(e)}))})),i||{}}if(1===t.sort){let o=co.clone(e).reverse(),i=co.uniq(e.map((e=>{let t=co.findLastIndex(r,{key:e.bookKey});return t>-1?r[t].name:""})));1===t.order?i.sort():i.sort().reverse();let n={};return i.forEach((e=>{n[e]=[]})),o.forEach((e=>{i.forEach((t=>{let o=co.findLastIndex(r,{key:e.bookKey});o>-1&&t===r[o].name&&n[t].push(e)}))})),n||{}}}static sortBookmarks(e,t){if(3===t.sort){let r=co.clone(e).reverse(),o=co.uniq(e.map((e=>({chapter:e.chapter,chapterIndex:parseInt(JSON.parse(e.cfi).chapterDocIndex)}))));o=1===t.order?co.sortBy(o,"chapterIndex"):co.sortBy(o,"chapterIndex").reverse();let i=co.uniq(o.map((e=>e.chapter))),n={};return i.forEach((e=>{n[e]=[]})),r.forEach((e=>{n[e.chapter].push(e)})),i.map((e=>({group:e,bookmarks:n[e]})))||[]}}}class fo{static getDefaultCss(e){return`::selection{background:#f3a6a68c}::-moz-selection{background:#f3a6a68c}.kookit-note:hover{cursor:pointer;}img{max-width:100% !important}body,html{margin: 0px !important; padding: 0px !important;}.kookit-text{${this.getCustomCss(e)}}code,pre{white-space: pre-wrap;}p{margin-block: 0;margin-inline: 0;}${"yes"===e.getReaderConfig("isOverwriteLink")?"a{color: #0066cc !important; text-decoration: underline !important; cursor: pointer !important;}a:hover{color: #004080 !important;}a:visited{color: #6600cc !important;}":""}${"yes"===e.getReaderConfig("isMergeWord")?`h1{font-size: ${e.getReaderConfig("fontSize")||18}px !important;}`:""}`}static getCustomCss(e){return`font-size: ${e.getReaderConfig("fontSize")?e.getReaderConfig("fontSize"):"18"}px !important;line-height: ${e.getReaderConfig("lineHeight")||"1.25"} !important;font-family: ${e.getReaderConfig("fontFamily")||""} !important;background-color: transparent;color: ${e.getReaderConfig("textColor")?e.getReaderConfig("textColor"):"rgba(44,47,49,1)"===e.getReaderConfig("backgroundColor")||"night"===e.getReaderConfig("appSkin")||"system"===e.getReaderConfig("appSkin")&&"yes"===e.getReaderConfig("isOSNight")?"white":""} !important;letter-spacing: ${e.getReaderConfig("letterSpacing")}px !important;text-align: ${e.getReaderConfig("textAlign")?e.getReaderConfig("textAlign"):""} !important;font-weight: ${"yes"===e.getReaderConfig("isBold")?"bold !important":""};font-style: ${"yes"===e.getReaderConfig("isItalic")?"italic !important":""};text-shadow: ${"yes"===e.getReaderConfig("isShadow")?"2px 2px 2px #cccccc !important":""};text-indent: ${"yes"===e.getReaderConfig("isIndent")?"2rem":""};text-decoration: ${"yes"===e.getReaderConfig("isUnderline")?"underline !important":""};margin-bottom: ${e.getReaderConfig("paraSpacing")||0}px !important;padding:0px !important;word-wrap: break-word !important; writing-mode: horizontal-tb !important; `}}class go{static mergeArray(e,t){var r=[];for(let t of e)r.push(t);for(let i of t){var o=!0;for(let t of e)if(i===t){o=!1;break}o&&r.push(i)}return r}static fuzzyQuery(e,t){for(var r=[],o=0;o-1&&r.push(o);return r}static mouseSearch(e){let t=document.querySelector(".header-search-box").value.toLowerCase(),r=[],o=[];if(!e)return[];e.forEach((e=>{r.push(e.name.toLowerCase()),o.push(e.author.toLowerCase())}));let i=this.fuzzyQuery(r,t),n=this.fuzzyQuery(o,t);return this.mergeArray(i,n)}static keywordSearch(e,t){let r=[],o=[];if(!t)return[];t.forEach((e=>{r.push(e.name.toLowerCase()),o.push(e.author.toLowerCase())}));let i=this.fuzzyQuery(r,e),n=this.fuzzyQuery(o,e);return this.mergeArray(i,n)}static keySearch(e,t){if(e&&13===e.keyCode){let r=[],o=[];if(!t)return[];t.forEach((e=>{r.push(e.name.toLowerCase()),o.push(e.author.toLowerCase())}));let i=this.fuzzyQuery(r,e.target.value.toLowerCase()),n=this.fuzzyQuery(o,e.target.value.toLowerCase());return this.mergeArray(i,n)}}static mouseNoteSearch(e){let t=document.querySelector(".header-search-box").value.toLowerCase(),r=[],o=[];e.forEach((e=>{r.push(e.notes.toLowerCase()),o.push(e.text.toLowerCase())}));let i=this.fuzzyQuery(r,t),n=this.fuzzyQuery(o,t);return this.mergeArray(i,n)}static keyNoteSearch(e,t){if(e&&13===e.keyCode){let r=[],o=[];t.forEach((e=>{r.push(e.notes.toLowerCase()),o.push(e.text.toLowerCase())}));let i=this.fuzzyQuery(r,e.target.value.toLowerCase()),n=this.fuzzyQuery(o,e.target.value.toLowerCase());return this.mergeArray(i,n)}}}export{q as BookHelper,d as CommonTool,X as ConfigService,h as KookitConfig,H as LoginHelper,K as ReaderRequest,go as SearchUtil,ho as SortUtil,D as SqlStatement,fo as StyleHelper,V as SyncHelper,L as SyncUtil,Q as ThirdpartyRequest,ne as TokenService,J as UserRequest}; +import e from"axios";import{Storage as t}from"megajs";import{Buffer as r}from"buffer";import{createClient as o,AuthType as i}from"webdav/dist/web/index.js";import{isElectron as n}from"react-device-detect";function s(e,t,r,o){return new(r||(r=Promise))((function(i,n){function s(e){try{c(o.next(e))}catch(e){n(e)}}function a(e){try{c(o.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((o=o.apply(e,t||[])).next())}))}const a=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,c=["books","notes","bookmarks","plugins","words"];class l{constructor(e){this.queue=[],this.runningTasks=0,this.totalTasks=0,this.completedTasks=0,this.maxConcurrency=e}addTask(e){return s(this,void 0,void 0,(function*(){return this.totalTasks++,new Promise(((t,r)=>{const o=()=>s(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"application/json"===e?"json":e.startsWith("image/")?e.split("/")[1]:"application/zip"===e?"zip":"application/epub+zip"===e?"epub":"text/plain"===e?"txt":"application/pdf"===e?"pdf":"application/x-mobipocket-ebook"===e?"mobi":"application/vnd.amazon.ebook"===e?"azw3":"application/x-cbz"===e?"cbz":"application/x-cbr"===e?"cbr":"application/x-cbt"===e?"cbt":"application/x-cb7"===e?"cb7":"application/x-fictionbook+xml"===e?"fb2":"text/html"===e?"html":"text/css"===e?"css":"application/javascript"===e?"js":"application/xml"===e?"xml":"application/xhtml+xml"===e?"xhtml":"application/oebps-package+xml"===e?"opf":"application/x-dtbncx+xml"===e?"ncx":"audio/mpeg"===e?"mp3":"audio/wav"===e?"wav":"audio/ogg"===e?"ogg":"video/mp4"===e?"mp4":"video/webm"===e?"webm":"video/x-msvideo"===e?"avi":"video/x-ms-wmv"===e?"wmv":"video/x-flv"===e?"flv":"application/x-mpegURL"===e?"m3u8":"video/MP2T"===e?"ts":"video/3gpp"===e?"3gp":"video/3gpp2"===e?"3g2":"application/x-sqlite3"===e?"db":"",databaseList:c,configList:["themeColors","readingTime","cloudSyncTime","recentBooks","recentAdd","deletedBooks","favoriteBooks","shelfList","txtParsers","noteTags","recordLocation","sortedShelfList","kindleDeviceList"],copyArrayBuffer:e=>{var t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e)),t},base64ToArrayBuffer:e=>{const t=atob(e),r=t.length,o=new Uint8Array(r);for(let e=0;e{let t="";const r=new Uint8Array(e),o=r.byteLength;for(let e=0;ee.toString(16).padStart(2,"0"))).join("")}))},EmailProviders:["gmail.com","qq.com","163.com","yahoo.com","sina.com","126.com","outlook.com","yeah.net","foxmail.com","hotmail.com","protonmail.com","proton.me","icloud.com","mail.com","live.com","aliyun.com"]};const u={publicUrl:"https://api.960960.xyz",cloudUrl:"https://cloud.960960.xyz",devUrl:"http://192.168.28.159:8000"},p={callbackUrl:"https://web.koodoreader.com/",dropboxClientId:"vnc67byrssocvy1",pcloudClientId:"pg8ten0B3vH",boxClientId:"ltimecqanmpxoaicn9qw3es6l3sdl1ya",microsoftClientId:"506df58a-29ab-4020-afc5-6f423dc80f35",googleClientId:"1051055003225-ph1f5fvh328dhv7bco5jitlnfhg6ks2t.apps.googleusercontent.com",facebookClientId:"2845583825559500",githubClientId:"Ov23liJVzfvJMMEEZ8v2",adriveClientId:"a128ae7b9c094545af623de61dc0a1ef"};var h={CloudConfig:u,ThirdpartyConfig:p,LoginAuthRequest:{google:{clientId:p.googleClientId,scopes:["openid"],usePKCE:!1,responseType:"code",redirectUri:p.callbackUrl,extraParams:{prompt:"consent",scope:"openid"}},microsoft:{clientId:p.microsoftClientId,scopes:["openid","profile","User.Read","offline_access"],usePKCE:!1,responseType:"code",redirectUri:p.callbackUrl,extraParams:{scope:"openid profile User.Read offline_access"}},facebook:{clientId:p.facebookClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:p.callbackUrl,extraParams:{scope:""}},github:{clientId:p.githubClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:p.callbackUrl,extraParams:{scope:""}},email:{clientId:"",scopes:[],usePKCE:!1,responseType:"code",redirectUri:p.callbackUrl,extraParams:{scope:""}}},LoginDiscovery:{microsoft:{authorizationEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/authorize",tokenEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/token"},google:{authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token"},facebook:{authorizationEndpoint:"https://www.facebook.com/v12.0/dialog/oauth",tokenEndpoint:"https://graph.facebook.com/v12.0/oauth/access_token"},github:{authorizationEndpoint:"https://github.com/login/oauth/authorize",tokenEndpoint:"https://github.com/login/oauth/access_token"},email:{authorizationEndpoint:"",tokenEndpoint:""}},DriveAuthRequest:{dropbox:{clientId:p.dropboxClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:p.callbackUrl,extraParams:{token_access_type:"offline"}},boxnet:{clientId:p.boxClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:p.callbackUrl,extraParams:{grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}},pcloud:{clientId:p.pcloudClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:p.callbackUrl,extraParams:{grant_type:"authorization_code"}},adrive:{clientId:p.adriveClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:p.callbackUrl,extraParams:{grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}},microsoft:{clientId:p.microsoftClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:p.callbackUrl,extraParams:{scope:"files.readwrite.appfolder offline_access"}},google:{clientId:p.googleClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:p.callbackUrl,extraParams:{prompt:"consent",scope:"https://www.googleapis.com/auth/drive.appdata",access_type:"offline"}}},DriveDiscovery:{dropbox:{authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",tokenEndpoint:"https://www.dropbox.com/oauth2/token"},boxnet:{authorizationEndpoint:"https://account.box.com/api/oauth2/authorize",tokenEndpoint:"https://api.box.com/oauth2/token"},pcloud:{authorizationEndpoint:"https://my.pcloud.com/oauth2/authorize",tokenEndpoint:"https://api.pcloud.com/oauth2_token"},adrive:{authorizationEndpoint:"https://openapi.alipan.com/oauth/authorize",tokenEndpoint:"https://openapi.alipan.com/oauth/token"},microsoft:{authorizationEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/authorize",tokenEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/token"},google:{authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token"}}};class f{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.driveId="",this.refreshTokenPromise=null,this.taskQueue=new l(1)}retryOperation(e,t=5){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}getDriveId(){return s(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 s(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),o=yield this.getDriveId();try{try{const i=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:o,file_path:t},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});if(i.data)return i.data.file_id}catch(i){const n=t.split("/").filter((e=>e));let s="",a="root";for(const t of n){s+="/"+t;try{a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:o,file_path:s},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.file_id}catch(i){a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:o,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(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=yield this.getDriveId(),i=yield this.getFolderIdByPath("/KoodoReader/"+t);let n=[],s="",a=!0;for(;a;){const t=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/list",{drive_id:o,parent_file_id:i,marker:s||void 0},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}),c=t.data.items||[];n=n.concat(c),s=t.data.next_marker,a=!!s&&100===c.length}return[...new Set(n.map((e=>e.name)))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=yield this.getDriveId(),i=yield this.getFolderIdByPath("/KoodoReader/"+t);return!i||(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/delete",{drive_id:o,file_id:i},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}),!0)}catch(e){return console.error("Error deleting file:",e),!1}}))}checkExists(t){var r;return s(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken(),i=yield this.getDriveId(),n=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:i,file_path:t},{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}});(null===(r=n.data)||void 0===r?void 0:r.file_id)&&(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/recyclebin/trash",{drive_id:i,file_id:n.data.file_id},{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}}))}catch(e){}}))}refreshToken(){return s(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=(()=>s(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"adrive",refresh_token:e});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})});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){return s(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"adrive",redirect_uri:p.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://openapi.alipan.com/oauth/authorize?${new URLSearchParams({response_type:"code",client_id:p.adriveClientId,redirect_uri:p.callbackUrl,grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}).toString()}`}}class g extends f{constructor(e,t){super(e,t)}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return new Promise(((o,i)=>s(this,void 0,void 0,(function*(){try{const i=yield this.refreshToken(),n=yield this.getDriveId(),s=r.substring(0,r.lastIndexOf("/")),a=r.substring(r.lastIndexOf("/")+1),c=yield this.getFolderIdByPath("/KoodoReader/"+s),l=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:n,parent_file_id:c,name:a,type:"file",check_name_mode:"ignore"},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}),{file_id:d,upload_id:u,part_info_list:p}=l.data;yield e.put(p[0].upload_url,t,{headers:{"Content-Type":"application/octet-stream"}}),yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/complete",{drive_id:n,file_id:d,upload_id:u},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}),o(!0)}catch(e){console.error("Error uploading file:",e),o(!1)}}))))}))}downloadFile(t){return new Promise(((r,o)=>s(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken(),i=yield this.getDriveId(),n=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:i,file_path:"/KoodoReader/"+t},{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}})).data.file_id,s=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/getDownloadUrl",{drive_id:i,file_id:n},{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}}),a=yield e.get(s.data.url,{responseType:"arraybuffer"});r(a.data)}catch(e){console.error("Error downloading file:",e),r(!1)}}))))}}class y{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new l(3)}retryOperation(e,t=3){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}getFolderIdByPath(t){return s(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),o=t.split("/");let i="0";for(const t of o){const o=`https://api.box.com/2.0/folders/${i}/items?fields=id,name&type=folder&limit=1000`;try{const n=(yield e.get(o,{headers:{Authorization:`Bearer ${r}`}})).data.entries.find((e=>e.name===t&&"folder"===e.type));if(n)i=n.id;else{const o={name:t,parent:{id:i},type:"folder"};i=(yield e.post("https://api.box.com/2.0/folders",o,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.id}}catch(e){return console.error("Error occurred during folder creation:",e),""}}return i}))}listFiles(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let o=yield this.getFolderIdByPath("KoodoReader/"+t),i=[],n=0,s=!0;const a=1e3;for(;s;){const t=yield e.get(`https://api.box.com/2.0/folders/${o}/items`,{params:{limit:a,offset:n},headers:{Authorization:`Bearer ${r}`}}),c=t.data.entries||[];i=i.concat(c),n+=c.length,s=c.length===a&&t.data.total_count>n}return[...new Set(i.map((e=>e.name)))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=t.substring(0,t.lastIndexOf("/")),i=t.substring(t.lastIndexOf("/")+1),n=yield this.getFolderIdByPath("KoodoReader/"+o);if(!n)return!0;const s=`https://api.box.com/2.0/folders/${n}/items?fields=id,name&type=file&limit=1000`,a=(yield e.get(s,{headers:{Authorization:`Bearer ${r}`}})).data.entries.find((e=>e.name===i&&"file"===e.type));return!a||(yield e.delete(`https://api.box.com/2.0/files/${a.id}`,{headers:{Authorization:`Bearer ${r}`}}),!0)}catch(e){return console.error("Error deleting file:",e),!1}}))}refreshToken(){return s(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=(()=>s(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"boxnet",refresh_token:e});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})});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){return s(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"boxnet",redirect_uri:p.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://account.box.com/api/oauth2/authorize?${new URLSearchParams({response_type:"code",client_id:p.boxClientId,redirect_uri:p.callbackUrl,grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}).toString()}`}}class m extends y{constructor(e,t){super(e,t)}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken(),i=r.substring(0,r.lastIndexOf("/")),n=r.substring(r.lastIndexOf("/")+1),s=yield this.getFolderIdByPath("KoodoReader/"+i);if(!s)throw new Error("Folder not found");const a=(yield this.listFiles(i)).find((e=>e===n));a&&(yield this.deleteFileWithoutQueue(i+"/"+n));let c=new File([t],n,{lastModified:(new Date).getTime(),type:t.type});const l=new FormData;l.append("file",c),l.append("parent_id",s);const d=yield e.post("https://upload.box.com/api/2.0/files/content",l,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"multipart/form-data"},params:{if_match:"false",fields:"name,id"},maxContentLength:1/0,maxBodyLength:1/0});return!(d.status>=300)||(console.error("Error occurred during file upload:",d),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(t){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=t.substring(0,t.lastIndexOf("/")),i=t.substring(t.lastIndexOf("/")+1),n=yield this.getFolderIdByPath("KoodoReader/"+o);if(!n)return console.error("Folder not found"),!0;const s=`https://api.box.com/2.0/folders/${n}/items?fields=id,name&type=file&limit=1000`,a=(yield e.get(s,{headers:{Authorization:`Bearer ${r}`}})).data.entries.find((e=>e.name===i&&"file"===e.type));if(!a)return console.error("File not found:",i),!0;const c=yield e({url:`https://api.box.com/2.0/files/${a.id}/content`,method:"get",headers:{Authorization:`Bearer ${r}`},responseType:"arraybuffer"});return c.status>=300?(console.error("Error occurred during file download:",c),!1):c.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class v{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new l(3)}retryOperation(e,t=3){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}listFiles(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let o=[],i=!0,n=null;for(;i;){let s;s=n?yield e.post("https://api.dropboxapi.com/2/files/list_folder/continue",{cursor:n},{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=s.data.entries||[];o=o.concat(a),i=s.data.has_more,n=s.data.cursor}return[...new Set(o.map((e=>e.name)))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return s(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 s(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=(()=>s(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"dropbox",refresh_token:e});return 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){return s(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"dropbox",redirect_uri:p.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://www.dropbox.com/oauth2/authorize?response_type=code&token_access_type=offline&client_id=${p.dropboxClientId}&redirect_uri=${p.callbackUrl}`}}class k extends v{constructor(e,t){super(e,t)}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken();let i=r.split("/").pop()||"",n=new File([t],i,{lastModified:(new Date).getTime(),type:t.type});const s=yield e.post("https://content.dropboxapi.com/2/files/upload",n,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/octet-stream","Dropbox-API-Arg":JSON.stringify({path:"/"+r,mode:"overwrite",autorename:!0,mute:!1})},maxContentLength:1/0,maxBodyLength:1/0});return!(s.status>=300)||(console.error("Error occurred during file upload:",s),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(t){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=yield e({url:"https://content.dropboxapi.com/2/files/download",method:"post",headers:{Authorization:`Bearer ${r}`,"Dropbox-API-Arg":JSON.stringify({path:"/"+t})},maxContentLength:1/0,maxBodyLength:1/0,responseType:"arraybuffer"});return o.status>=300?(console.error("Error occurred during file download:",o),!1):o.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class b{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new l(3)}retryOperation(e,t=3){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}getFileId(t,r){return s(this,void 0,void 0,(function*(){const o=yield this.refreshToken(),i=`https://www.googleapis.com/drive/v3/files?q=name='${t}'+and+'${r}'+in+parents&spaces=appDataFolder&fields=files(id,name)`;try{const t=yield e.get(i,{headers:{Authorization:"Bearer "+o}});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 s(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),o=yield this.getFolderId(t);if(o)return o;const i={name:t,mimeType:"application/vnd.google-apps.folder",parents:["appDataFolder"]};try{return(yield e.post("https://www.googleapis.com/drive/v3/files",i,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.id}catch(e){throw console.error("Error occurred during folder creation:",e),e}}))}getFolderId(t){return s(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),o=`https://www.googleapis.com/drive/v3/files?q=name='${t}'+and+mimeType='application/vnd.google-apps.folder'+and+'appDataFolder'+in+parents&spaces=appDataFolder&fields=files(id,name)`;try{const t=(yield e.get(o,{headers:{Authorization:`Bearer ${r}`}})).data.files;return t.length>0?t[0].id:null}catch(e){throw console.error("Error occurred during fetching folder ID:",e),e}}))}listFiles(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let o=yield this.checkFolder(t),i=[],n="",s=!0;for(;s;){let t=`https://www.googleapis.com/drive/v3/files?q='${o}'+in+parents&spaces=appDataFolder&fields=nextPageToken,files(id,name)&pageSize=1000`;n&&(t+=`&pageToken=${n}`);const a=yield e.get(t,{headers:{Authorization:`Bearer ${r}`}}),c=a.data.files||[];i=i.concat(c),n=a.data.nextPageToken,s=!!n}return[...new Set(i.map((e=>e.name)))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQue(e)}))))))}))}deleteFileWithoutQue(t){return s(this,void 0,void 0,(function*(){const r=t.split("/")[1],o=t.split("/")[0],i=yield this.getFolderId(o),n=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 ${n}`}});return console.error("File deleted:",t),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}refreshToken(){return s(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=(()=>s(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"google",refresh_token:e});return 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){return s(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"google",redirect_uri:p.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${p.callbackUrl}&prompt=consent&response_type=code&client_id=${p.googleClientId}&scope=https://www.googleapis.com/auth/drive.appdata&access_type=offline`}}class w extends b{constructor(e,t){super(e,t)}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken();let i=r.split("/").pop()||"",n=new File([t],i,{lastModified:(new Date).getTime(),type:t.type}),s=r.split(".").pop(),c=a(s||""),l=r.split("/")[0],d=yield this.checkFolder(l),u=yield this.getFileId(i||"",d);const p={mimeType:c,name:i,parents:[d]},h=u?`https://www.googleapis.com/upload/drive/v3/files/${u}?uploadType=resumable`:"https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",f=(yield e({method:u?"PATCH":"POST",url:h,data:u?null:JSON.stringify(p),headers:{Authorization:"Bearer "+o,"Content-Type":"application/json; charset=UTF-8"},maxContentLength:1/0,maxBodyLength:1/0})).headers.location,g=yield this.getData(n);if(0===Object.keys(g).length)return!1;const y=yield e.put(f,g.data,{headers:{Authorization:"Bearer "+o,"Content-Type":"application/zip","Content-Range":`bytes 0-${g.fileSize-1}/${g.fileSize}`},maxContentLength:1/0,maxBodyLength:1/0});return!(y.status>=300)||(console.error("Error occurred during file download:",y),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(t){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let o=t.split("/").pop(),i=t.split("/")[0],n=yield this.checkFolder(i),s=yield this.getFileId(o||"",n);if(!s)return console.error("File not found:",o),!0;const a=`https://www.googleapis.com/drive/v3/files/${s}?alt=media`,c=yield e.get(a,{headers:{Authorization:"Bearer "+r},maxContentLength:1/0,maxBodyLength:1/0,responseType:"arraybuffer"});return c.status>=300?(console.error("Error occurred during file download:",c),!1):c.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}getData(e){return s(this,void 0,void 0,(function*(){return e?new Promise(((t,r)=>{const o=new FileReader;o.onload=r=>t({fileName:e.name,mimeType:e.type,fileSize:e.size,data:r.target.result}),o.onerror=e=>r(e),o.readAsArrayBuffer(e)})):{}}))}}class T{constructor(e){this.folderCreationLocks=new Map,this.config=e,this.taskQueue=new l(3)}retryOperation(e,t=3){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}getStorage(){return s(this,void 0,void 0,(function*(){if(this.storage)return this.storage;let{email:e,password:r}=this.config;return this.storage=yield new t({email:e,password:r}).ready,this.storage}))}getRoot(){return s(this,void 0,void 0,(function*(){if(this.root)return this.root;const e=(yield this.getStorage()).root;let t=e.children.find((e=>"KoodoReader"===e.name&&e.directory));return t||(t=yield e.mkdir("KoodoReader")),this.root=t,this.root}))}createFolder(e,t){return s(this,void 0,void 0,(function*(){const r=`${e.nodeId}_${t}`;if(this.folderCreationLocks.has(r))return yield this.folderCreationLocks.get(r);const o=(()=>s(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,o),yield o}))}listFiles(e){return s(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.filter((e=>!e.directory)).map((e=>e.name))}catch(e){return console.error("Error listing MEGA files:",e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(e){return s(this,void 0,void 0,(function*(){try{let t=yield this.getRoot();const r=e.split("/"),o=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 i=t.children.find((e=>e.name===o&&!e.directory));return!i||(yield i.delete(),!0)}catch(e){return console.error("Error deleting MEGA file:",e),!1}}))}}class E extends T{constructor(e){super(e)}uploadFile(e,t){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{let o=yield this.getRoot();const i=t.split("/"),n=i.pop()||"";for(const e of i){if(!e)continue;let t=o.children.find((t=>t.name===e&&t.directory));t||(t=yield this.createFolder(o,e)),o=t}const s=new File([e],n,{lastModified:(new Date).getTime(),type:e.type}),a=yield e.arrayBuffer(),c=new Uint8Array(a),l=r.from(c),d=o.children.find((e=>e.name===n&&!e.directory));return d&&(yield d.delete()),yield o.upload({name:n,size:s.size},l).complete,!0}catch(e){return console.error("Error occurred during MEGA file upload:",e),!1}}))))))}))}downloadFile(e){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{let t=yield this.getRoot();const r=e.split("/"),o=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 i=t.children.find((e=>e.name===o&&!e.directory));if(!i)return!0;return yield i.downloadBuffer()}catch(e){return console.error("Error occurred during MEGA file download:",e),!1}}))))))}))}}class C{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new l(3)}retryOperation(e,t=3){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}listFiles(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let o=[],i=`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${t}:/children`;for(;i;){const t=yield e.get(i,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});if(t.status>=300)break;const n=t.data.value||[];o=o.concat(n),i=t.data["@odata.nextLink"]||""}return[...new Set(o.map((e=>e.name)))]}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=yield e.delete(`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${t}`,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});return!(o.status>=300)||(console.error("Error deleting file:",o),!0)}catch(e){return console.error("Error occurred during file delete:",e),!1}}))}refreshToken(){return s(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=(()=>s(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"microsoft",refresh_token:e});return 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){return s(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"microsoft",redirect_uri:p.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${p.microsoftClientId}&scope=files.readwrite.appfolder offline_access&response_type=code&redirect_uri=${p.callbackUrl}`}}class x extends C{constructor(e,t){super(e,t)}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken();let i=r.split("/").pop()||"",n=new File([t],i,{lastModified:(new Date).getTime(),type:t.type});const s="https://graph.microsoft.com/v1.0/me/drive/special/approot:/"+r+":/createUploadSession",a=yield e.post(s,null,{headers:{Authorization:"Bearer "+o,"Content-Type":"application/json"},maxContentLength:1/0,maxBodyLength:1/0});let c=n.size;const l=n.type,d=a.data.uploadUrl,u=yield e.put(d,n,{headers:{"Content-Type":l,"Content-Range":`bytes 0-${c-1}/${c}`},maxContentLength:1/0,maxBodyLength:1/0});return!(u.status>=300)||(console.error("Error occurred during file download:",u),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(t){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${t}:/content`,i=yield e.get(o,{responseType:"arraybuffer",headers:{Authorization:"Bearer "+r},maxContentLength:1/0,maxBodyLength:1/0});return i.status>=300?(console.error("Error occurred during file download:",i),!1):i.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class _{downloadFile(e,t){return s(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}uploadFile(e,t){return s(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}listFiles(e){return s(this,void 0,void 0,(function*(){return new Promise((e=>{e([])}))}))}authToken(e){return s(this,void 0,void 0,(function*(){return new Promise((e=>{e("")}))}))}getAuthUrl(){return""}}class S{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.taskQueue=new l(3)}retryOperation(e,t=5){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}checkFolderExists(t,r){return s(this,void 0,void 0,(function*(){try{return 0===(yield e.get("https://api.pcloud.com/listfolder",{params:{access_token:r,path:`/${t}`}})).data.result}catch(e){return console.error("Error checking folder:",e),!1}}))}createFolder(t,r){return s(this,void 0,void 0,(function*(){try{return 0===(yield e.get("https://api.pcloud.com/createfolderifnotexists",{params:{access_token:r,path:`/${t}`}})).data.result}catch(e){return console.error("Error creating folder:",e),!1}}))}listFiles(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=yield e.get("https://api.pcloud.com/listfolder",{params:{access_token:r,path:"/"+t,recursive:0}});return 0!==o.data.result?[]:o.data.metadata.contents.map((e=>e.name))}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=yield e.get("https://api.pcloud.com/deletefile",{params:{access_token:r,path:"/"+t}});return 0===o.data.result||(console.error("Error deleting file:",o.data),!0)}catch(e){return console.error("Error occurred during file delete:",e),!1}}))}refreshToken(){return s(this,void 0,void 0,(function*(){return this.config.refresh_token}))}authToken(e){return s(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"pcloud",redirect_uri:p.callbackUrl,code:e})).data.access_token}))}getAuthUrl(){return`https://my.pcloud.com/oauth2/authorize?client_id=${p.pcloudClientId}&response_type=code&redirect_uri=${p.callbackUrl}`}}class R extends S{constructor(e,t){super(e,t)}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken(),i=r.split("/").slice(0,-1).join("/");if(!(yield this.checkFolderExists(i,o))){if(!(yield this.createFolder(i,o)))return!1}let n=r.split("/").pop()||"",s=new File([t],n,{lastModified:(new Date).getTime(),type:t.type});const a=new FormData;a.append("file",s);const c=yield e.post("https://api.pcloud.com/uploadfile",a,{params:{access_token:o,path:`/${i}`,renew:1},maxContentLength:1/0,maxBodyLength:1/0});return 0===c.data.result||(console.error("Error uploading file:",c.data),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(t){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=yield e.get("https://api.pcloud.com/getfilelink",{params:{access_token:r,path:`/${t}`}});if(0!==o.data.result)return console.error("Error getting file link:",o.data),!0;const i=`https://${o.data.hosts[0]}${o.data.path}`,n=yield e.get(i,{responseType:"arraybuffer",maxContentLength:1/0,maxBodyLength:1/0});return n.status>=300?(console.error("Error downloading file:",n),!1):n.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class O{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.taskQueue=new l(5)}retryOperation(e,t=0){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}listFiles(e){return s(this,void 0,void 0,(function*(){let{endpoint:t,region:r,bucketName:o,accessKeyId:i,secretAccessKey:n,dir:s}=this.config;s||(s="KoodoReader");try{return(yield this.thirdpartyRequest.s3List({bucket_name:o,prefix:s+"/"+e,region:r,endpoint:t,access_key_id:i,secret_access_key:n})).data.contents.map((e=>e.split("/").pop()))}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){let{endpoint:t,region:r,bucketName:o,accessKeyId:i,secretAccessKey:n,dir:s}=this.config;s||(s="KoodoReader");try{let a=yield this.thirdpartyRequest.s3Delete({bucket_name:o,object_key:s+"/"+e,region:r,endpoint:t,access_key_id:i,secret_access_key:n});return 200===a.code||(console.error("Error deleting file:",a),!1)}catch(e){return console.error("Error deleting file:",e),!1}}))}}class A extends O{constructor(e,t){super(e,t)}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){let{endpoint:o,region:i,bucketName:n,accessKeyId:s,secretAccessKey:a,dir:c}=this.config;c||(c="KoodoReader");try{const l=(yield this.thirdpartyRequest.s3Upload({bucket_name:n,object_key:c+"/"+r,region:i,endpoint:o,access_key_id:s,secret_access_key:a})).data.url;let d=r.split("/").pop()||"",u=new File([t],d,{lastModified:(new Date).getTime(),type:t.type});const p=yield e.put(l,u,{headers:{},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 occurred during file upload:",e),!1}}))))))}))}downloadFile(t){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){let{endpoint:r,region:o,bucketName:i,accessKeyId:n,secretAccessKey:s,dir:a}=this.config;a||(a="KoodoReader");try{const c=(yield this.thirdpartyRequest.s3Download({bucket_name:i,object_key:a+"/"+t,region:o,endpoint:r,access_key_id:n,secret_access_key:s})).data.url;return(yield e({url:c,method:"get",headers:{},responseType:"arraybuffer",maxContentLength:1/0,maxBodyLength:1/0})).data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class F{constructor(e){let{username:t,password:r,url:n,dir:s}=e;s||(s="KoodoReader"),this.client=o(n,{authType:i.Password,username:t,password:r}),this.username=t,this.password=r,this.dir=s,this.taskQueue=new l(5)}retryOperation(e,t=0){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{!1===(yield this.client.exists(this.dir+"/"+r.substring(0,r.lastIndexOf("/"))))&&(yield this.client.createDirectory(this.dir+"/"+r.substring(0,r.lastIndexOf("/"))));let o=r.split("/").pop()||"",i=new File([t],o,{lastModified:(new Date).getTime(),type:t.type}),n=this.client.getFileUploadLink(this.dir+"/"+r);const s=new URL(n);s.search="",n=s.toString();const a=btoa(this.username+":"+this.password),c=yield e.put(n,i,{headers:{Authorization:"Basic "+a},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(t){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const r=this.client.getFileDownloadLink(this.dir+"/"+t),o=btoa(this.username+":"+this.password),i=yield e({url:r,method:"get",headers:{Authorization:"Basic "+o},responseType:"arraybuffer",maxContentLength:1/0,maxBodyLength:1/0});return i.status>=300?(console.error("Error occurred during file download:",i),!1):i.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}listFiles(e){return s(this,void 0,void 0,(function*(){try{return(yield this.client.getDirectoryContents(this.dir+"/"+e)).map((e=>e.basename))}catch(t){return t.response&&404===t.response.status&&(yield this.client.createDirectory(this.dir+"/"+e)),console.error("Error listing files:",t),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){try{return yield this.client.deleteFile(this.dir+"/"+e),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}}const I=["book","config","cover","font"];class L{constructor(e,t,r){this.type=e,this.remote="dropbox"===e?new k(t,r):"microsoft"===e?new x(t,r):"google"===e?new w(t,r):"s3compatible"===e?new A(t,r):"webdav"===e?new F(t):"boxnet"===e?new m(t,r):"mega"===e?new E(t):"adrive"===e?new g(t,r):"pcloud"===e?new R(t,r):new _}downloadFile(e,t){return s(this,void 0,void 0,(function*(){return!!(yield this.listFiles(t)).find((t=>e.indexOf(t)>-1))&&(yield this.remote.downloadFile(t+"/"+e))}))}uploadFile(e,t,r){return s(this,void 0,void 0,(function*(){return yield this.remote.uploadFile(r,t+"/"+e)}))}deleteFile(e,t){return s(this,void 0,void 0,(function*(){return!(yield this.listFiles(t)).find((t=>e.indexOf(t)>-1))||(yield this.remote.deleteFile(t+"/"+e))}))}listFiles(e){return s(this,void 0,void 0,(function*(){return yield this.remote.listFiles(e)}))}isExist(e,t){return s(this,void 0,void 0,(function*(){return(yield this.listFiles(t)).find((t=>-1!==t.indexOf(e)))}))}downloadAllFiles(){return s(this,void 0,void 0,(function*(){for(let e of I){let t=yield this.listFiles(e);for(let r of t)yield this.downloadFile(r,e)}}))}authToken(e){return s(this,void 0,void 0,(function*(){return yield this.remote.authToken(e)}))}getAuthUrl(){return this.remote.getAuthUrl?this.remote.getAuthUrl():""}getStats(){return this.remote.taskQueue.getStats()}resetCounters(){this.remote.taskQueue.resetCounters()}}const M={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 = ?"},j={notes:"SELECT * FROM notes WHERE bookKey = ?",bookmarks:"SELECT * FROM bookmarks WHERE bookKey = ?",words:"SELECT * FROM words WHERE bookKey = ?",books:"SELECT * FROM books WHERE key = ?"},z={notes:"DELETE FROM notes WHERE bookKey = ?",bookmarks:"DELETE FROM bookmarks WHERE bookKey = ?",words:"DELETE FROM words WHERE bookKey = ?"};function B(e){for(const t in e)e.hasOwnProperty(t)&&(e[`temp-${t}`]=e[t]);return e}const P={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 $,D={sqlStatement:{createTableStatement:B({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:B({notes:"SELECT * FROM notes",bookmarks:"SELECT * FROM bookmarks",books:"SELECT * FROM books",plugins:"SELECT * FROM plugins",words:"SELECT * FROM words"}),saveStatement:B({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:B({notes:"DELETE FROM notes",bookmarks:"DELETE FROM bookmarks",books:"DELETE FROM books",plugins:"DELETE FROM plugins",words:"DELETE FROM words"}),updateStatement:B({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:B({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:B({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:B(M),getByBookKeyStatement:B(j),getByBookKeysStatement:B({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(",")})`}),deleteByBookKeyStatement:B(z)},jsonToSqlite:B({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:B(P)};class N{constructor(e,t,r,o,i,n,s,a,c,l,d,u){this.key=e,this.name=t,this.author=r,this.description=o,this.md5=i,this.cover=n,this.format=s,this.publisher=a,this.size=c,this.page=l,this.path=d,this.charset=u}}class q{static generateBook(e,t,r,o,i,n,a){return new Promise(((c,l)=>s(this,void 0,void 0,(function*(){try{let s,l,d,u,p,h,f,g,y="";switch([l,d,p,u,h,f]=[e,"","","","",0],t){case"pdf":case"epub":case"mobi":case"azw":case"azw3":case"fb2":g=yield a.getMetadata(),[l,d,p,u,y]=[g.name||e,g.author||"",g.description||"",g.publisher||"",g.cover||""];break;case"cbr":case"cbt":case"cbz":case"cb7":g=yield a.getMetadata(),y=g.cover;break;case"txt":g=yield a.getMetadata(n),h=g.charset}let m=t.toUpperCase();s=(new Date).getTime()+"",c(new N(s,l,d,p,r,y,m,u,o,f,i,h))}catch(e){console.error(e),l(e)}}))))}}$=q,q.getRendtion=(e,t,r,o,i,n,s,a,c,l)=>{let d;var u,p;return"CACHE"===t?d=new l.CacheRender(e,{readerMode:r,animation:i,convertChinese:n,isDarkMode:a,isMobile:c}):"MOBI"===t||"AZW3"===t||"AZW"===t?d=new l.MobiRender(e,{readerMode:r,animation:i,convertChinese:n,isDarkMode:a,isMobile:c}):"EPUB"===t?d=new l.EpubRender(e,{readerMode:r,animation:i,convertChinese:n,isDarkMode:a,isMobile:c}):"TXT"===t?d=new l.TxtRender(e,{readerMode:r,animation:i,charset:o,convertChinese:n,parserRegex:s,isDarkMode:a,isMobile:c}):"MD"===t?d=new l.MdRender(e,{readerMode:r,animation:i,convertChinese:n,isDarkMode:a,isMobile:c}):"PDF"===t?d=new l.PdfRender(e,{readerMode:r,animation:i,convertChinese:n,isDarkMode:a,isMobile:c}):"FB2"===t?d=new l.Fb2Render(e,{readerMode:r,animation:i,convertChinese:n,isDarkMode:a,isMobile:c}):"DOCX"===t?d=new l.DocxRender(e,{readerMode:r,animation:i,convertChinese:n,isDarkMode:a,isMobile:c}):"HTML"===t||"XHTML"===t||"MHTML"===t||"HTM"===t||"XML"===t?d=new l.HtmlRender(e,{readerMode:r,format:t,animation:i,convertChinese:n,isDarkMode:a,isMobile:c}):"CBR"!==t&&"CBT"!==t&&"CBZ"!==t&&"CB7"!==t||(d=new l.ComicRender((u=e,p=new ArrayBuffer(u.byteLength),new Uint8Array(p).set(new Uint8Array(u)),p),{readerMode:r,format:t,animation:i,convertChinese:n,isDarkMode:a,isMobile:c})),d},q.initMobileBook=(e,t,r,o,i,n,a,c,l)=>s(void 0,void 0,void 0,(function*(){try{const s=yield fetch(e);if(!s.ok)throw new Error(`Failed to download book: ${s.status} ${s.statusText}`);const d=yield s.arrayBuffer();window.ReactNativeWebView.postMessage(JSON.stringify({event:"finish-download"})),window.file_content=d;let u=$.getRendtion(d,t,r,o,i,n,a,l,"yes",window.Kookit);window.rendition=u;let p=document.getElementById("page-area");t&&"TXT"===t.toUpperCase()?yield window.rendition.renderTo(p,c):yield window.rendition.renderTo(p),window.rendition.on("rendered",(()=>{let e=window.rendition.getPosition();window.ReactNativeWebView.postMessage(JSON.stringify({event:"content-loaded",bookLocation:e})),window.rendition.tsTransform()})),window.rendition.on("page-changed",(()=>{let e=window.rendition.getPosition();window.ReactNativeWebView.postMessage(JSON.stringify({event:"page-changed",bookLocation:e}))})),window.ReactNativeWebView.postMessage(JSON.stringify({event:"book-inited",chapterList:window.rendition.getChapter()}))}catch(e){window.ReactNativeWebView.postMessage(JSON.stringify({event:"error",message:"Parse book failed"}))}})),q.addMobileBook=(e,t,r,o,i,n,a="")=>s(void 0,void 0,void 0,(function*(){var s;try{const c=yield fetch(e);if(!c.ok)throw new Error(`Failed to download book: ${c.status} ${c.statusText}`);const l=yield c.arrayBuffer();null===(s=window.ReactNativeWebView)||void 0===s||s.postMessage(JSON.stringify({event:"finish-download"})),window.file_content=l;let d=$.getRendtion(l,r.toUpperCase(),"","","","no",a,"no","yes",window.Kookit);window.rendition=d,t=t.replace(/\.[^/.]+$/,"");let u=yield q.generateBook(t,r,o,i,n,l,d);if(!u||!u.key)return;window.ReactNativeWebView.postMessage(JSON.stringify({event:"metadata",bookInfo:u}))}catch(e){window.ReactNativeWebView.postMessage(JSON.stringify({event:"error",message:"Parse book failed"}))}})),q.precacheMobileBook=(e,t)=>s(void 0,void 0,void 0,(function*(){let r=yield window.rendition.preCache(window.file_content);if(""===r)window.ReactNativeWebView.postMessage(JSON.stringify({event:"cache",cacheBase64:"",key:t}));else if("err"!==r){try{const o=`${e}/dav/${"cache-"+t+".zip"}`,i=yield fetch(o,{method:"PUT",headers:{"Content-Type":"application/octet-stream",Overwrite:"T"},body:r});if(!i.ok)throw new Error(`上传失败: ${i.status}`);console.info("文件上传成功")}catch(e){console.error("操作失败:"+e)}window.ReactNativeWebView.postMessage(JSON.stringify({event:"cache",key:t}))}else window.ReactNativeWebView.postMessage(JSON.stringify({event:"error",message:"Parse book failed"}));window.file_content=null,window.rendition=null}));const U=u.devUrl;class W{constructor(e,t){this.processingQueue=!1,this.requestQueue=[],this.TokenService=e,this.ConfigService=t,this.refreshToken="",this.accessToken="",this.streamPromise=null}refreshUserToken(){return s(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(U+"/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),this.accessToken=t.data.access_token,this.refreshToken=t.data.refresh_token),t}))}requestWithRetry(e){return s(this,void 0,void 0,(function*(){return this.requestQueue||(this.requestQueue=[]),new Promise(((t,r)=>{this.requestQueue.push({config:e,resolve:t,reject:r}),this.processingQueue||this.processQueue()}))}))}processQueue(){return s(this,void 0,void 0,(function*(){if(!this.processingQueue){this.processingQueue=!0;try{for(;this.requestQueue.length>0;){const e=this.requestQueue.shift();try{let t=yield this.executeRequest(e.config);e.resolve(t)}catch(t){e.reject(t)}}}finally{this.processingQueue=!1}}}))}executeRequest(t){return s(this,void 0,void 0,(function*(){try{try{this.accessToken=(yield this.TokenService.getToken("access_token"))||""}catch(e){console.error("Error get Token:",e)}let r="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);t.baseURL=U,t.headers?(t.headers.Authorization="Bearer "+this.accessToken,t.headers["X-Request-ID"]=r):t.headers={Authorization:"Bearer "+this.accessToken,"X-Request-ID":r};let o=(yield e(t)).data;if(402===o.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!==o.code&&this.ConfigService.setItem("errorLog",JSON.stringify({request:t.data,url:t.url,result:o,requestID:r})),o}catch(e){return console.error("Request execution error:",e),{code:503,message:"network error",data:null}}}))}requestWithStream(e,t,r){return s(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>s(this,void 0,void 0,(function*(){try{let o="";try{o=(yield this.TokenService.getToken("access_token"))||""}catch(e){console.error("Error get Token:",e)}let i="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((n,a)=>{const c=new r(U+e.url,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+o,"X-Request-ID":i},method:e.method,body:JSON.stringify(e.data),pollingInterval:0});c.addEventListener("open",(()=>{console.info("Connection to OpenAI established.")})),c.addEventListener("message",(e=>s(this,void 0,void 0,(function*(){if(!e.data)return;const r=JSON.parse(e.data);console.log(r,"res3455"),r.done?(c.close(),console.log('"Stream completed:", res);',r),n(r)):(402===r.code&&(yield this.refreshUserToken()),t(r.data))})))),c.addEventListener("error",(e=>{if(console.info("Error:",e),!e.data)return;const t=JSON.parse(e.data);n(t),c.close()}))}))}finally{this.streamPromise=null}})))()),this.streamPromise}))}requestWithFetch(e,t){return s(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>s(this,void 0,void 0,(function*(){try{let r="";try{r=(yield this.TokenService.getToken("access_token"))||""}catch(e){console.error("Error get Token:",e)}let o="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((i,n)=>s(this,void 0,void 0,(function*(){const n=yield fetch(U+e.url,{method:"POST",headers:{"Content-Type":"text/event-stream",Authorization:"Bearer "+r,"X-Request-ID":o},body:JSON.stringify(e.data)});if(!n.body)throw new Error("Response body is null");const s=n.body.pipeThrough(new TextDecoderStream).getReader();for(;;){const{value:e,done:r}=yield s.read();if(console.log(e,"value"),console.log(r,"done"),r){t({done:!0});break}if(e)if(e.includes('"code":400')||e.includes('"code":401')||e.includes('"code":402')){let t=JSON.parse(e);402===t.code&&(yield this.refreshUserToken()),i(t)}else e.split("\n").forEach((e=>{if(e.startsWith("data:")){const r=JSON.parse(e.substring(5));t(r.data)}}))}i({code:200,data:{done:!0}})}))))}finally{this.streamPromise=null}})))()),this.streamPromise}))}}class K extends W{constructor(e,t){super(e,t)}getTransStream(e,t,r){return s(this,void 0,void 0,(function*(){const o={method:"post",url:"/api/v1/pro/reader/get_llm_trans_stream",data:e};return yield this.requestWithStream(o,t,r)}))}getTransFetch(e,t){return s(this,void 0,void 0,(function*(){const r={method:"post",url:"/api/v1/pro/reader/get_llm_trans_stream",data:e};return yield this.requestWithFetch(r,t)}))}getDictionary(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/reader/get_llm_dict",data:e};return yield this.requestWithRetry(t)}))}getSummaryStream(e,t,r){return s(this,void 0,void 0,(function*(){const o={method:"post",url:"/api/v1/pro/reader/get_llm_sum_stream",data:e};return yield this.requestWithStream(o,t,r)}))}getAnswerStream(e,t,r){return s(this,void 0,void 0,(function*(){const o={method:"post",url:"/api/v1/pro/reader/get_llm_answer_stream",data:e};let i=yield this.requestWithStream(o,t,r);return console.log(i,"safasdfsderw"),i}))}getAnswerFetch(e,t){return s(this,void 0,void 0,(function*(){const r={method:"post",url:"/api/v1/pro/reader/get_llm_answer_stream",data:e};return yield this.requestWithFetch(r,t)}))}getSummaryFetch(e,t){return s(this,void 0,void 0,(function*(){const r={method:"post",url:"/api/v1/pro/reader/get_llm_sum_stream",data:e};return yield this.requestWithFetch(r,t)}))}getGoogleFont(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/reader/get_google_font",data:e};return yield this.requestWithRetry(t)}))}sendToKindle(e){return s(this,void 0,void 0,(function*(){let t=new FormData;t.append("file",e.file),t.append("email",e.email),t.append("file_name",e.fileName);const r={method:"post",url:"/api/v1/pro/reader/send_to_kindle",headers:{"Content-Type":"multipart/form-data"},data:t};return yield this.requestWithRetry(r)}))}}class J extends W{constructor(e,t){super(e,t)}encryptToken(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/encrypt_token",data:e};return yield this.requestWithRetry(t)}))}decryptToken(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/decrypt_token",data:e};return yield this.requestWithRetry(t)}))}authThirdToken(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/auth_token",data:e};return yield this.requestWithRetry(t)}))}refreshThirdToken(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/refresh_token",data:e};return yield this.requestWithRetry(t)}))}s3Upload(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/s3_upload",data:e};return yield this.executeRequest(t)}))}s3Download(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/s3_download",data:e};return yield this.executeRequest(t)}))}s3List(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/s3_list",data:e};return yield this.executeRequest(t)}))}s3Delete(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/s3_delete",data:e};return yield this.executeRequest(t)}))}getSyncState(){return s(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"get",url:"/api/v1/pro/thirdparty/get_sync_state"})}))}deleteSyncState(){return s(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"post",url:"/api/v1/pro/thirdparty/delete_sync_state"})}))}}class Q extends W{constructor(e,t){super(e,t)}loginRegister(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/public/user/login_register",data:e};return yield this.requestWithRetry(t)}))}logout(){return s(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"post",url:"/api/v1/member/user/logout"})}))}getLogins(){return s(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"post",url:"/api/v1/member/user/get_logins"})}))}addLogin(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/member/user/add_login",data:e};return yield this.requestWithRetry(t)}))}removeLogin(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/member/user/remove_login",data:e};return yield this.requestWithRetry(t)}))}getUserInfo(){return s(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"post",url:"/api/v1/member/user/get_info"})}))}getTempToken(){return s(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"get",url:"/api/v1/member/user/get_temp_token"})}))}sendEmailCode(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/public/user/send_email_code",data:e};return yield this.requestWithRetry(t)}))}checkEmailRegistration(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/public/user/check_email_registration",data:e};return yield this.requestWithRetry(t)}))}redeemCode(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/member/user/redeem_code",data:e};return yield this.requestWithRetry(t)}))}deleteAccount(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/member/user/delete_account",data:e};return yield this.requestWithRetry(t)}))}}var H={getAuthUrl:(e,t)=>{let r="";if("github"===e?r=`https://github.com/login/oauth/authorize?client_id=${p.githubClientId}&redirect_uri=${p.callbackUrl}&scope=openid`:"google"===e?r=`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${p.callbackUrl}&prompt=consent&response_type=code&client_id=${p.googleClientId}&scope=openid&access_type=offline`:"facebook"===e?r=`https://www.facebook.com/v12.0/dialog/oauth?client_id=${p.facebookClientId}&redirect_uri=${p.callbackUrl}&scope=&response_type=code`:"microsoft"===e&&(r=`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${p.microsoftClientId}&scope=openid profile User.Read offline_access&response_type=code&redirect_uri=${p.callbackUrl}`),"manual"===t)return r;let o=JSON.stringify({deeplink:"desktop"===t?"koodo-reader://callback":"browser"===t?"https://web.koodoreader.com/#/login":"",service:e});return`${r}&state=${"state|"+encodeURIComponent(o)}`}};class V{static CompareDatabase(e,t,r){return s(this,void 0,void 0,(function*(){let o=Object.keys(e).filter((e=>e.startsWith("database.sqlite.books"))),i=Object.keys(e).filter((e=>e.startsWith("database.sqlite.notes"))),n=Object.keys(e).filter((e=>e.startsWith("database.sqlite.bookmarks"))),s=Object.keys(e).filter((e=>e.startsWith("database.sqlite.plugins"))),a=Object.keys(e).filter((e=>e.startsWith("database.sqlite.words"))),c=Object.keys(t).filter((e=>e.startsWith("database.sqlite.books"))),l=Object.keys(t).filter((e=>e.startsWith("database.sqlite.notes"))),d=Object.keys(t).filter((e=>e.startsWith("database.sqlite.bookmarks"))),u=Object.keys(t).filter((e=>e.startsWith("database.sqlite.plugins"))),p=Object.keys(t).filter((e=>e.startsWith("database.sqlite.words"))),h={books:Array.from(new Set(o.concat(c))),notes:Array.from(new Set(i.concat(l))),bookmarks:Array.from(new Set(n.concat(d))),plugins:Array.from(new Set(s.concat(u))),words:Array.from(new Set(a.concat(p)))},f={books:{save:[],update:[],delete:[],conflict:[],upload:[]},notes:{save:[],update:[],delete:[],conflict:[],upload:[]},bookmarks:{save:[],update:[],delete:[],conflict:[],upload:[]},plugins:{save:[],update:[],delete:[],conflict:[],upload:[]},words:{save:[],update:[],delete:[],conflict:[],upload:[]}},g=["books","notes","bookmarks","plugins","words"];for(let o of g)for(let i of h[o]){let n=i.split(".")[3],s=e[i],a=t[i];s?a?("save"===a.operation&&("update"===s.operation||"delete"===s.operation?f[o].upload.push(n):console.info("ignore",a)),"delete"===a.operation&&("save"===s.operation&&(f[o].delete.push(n),e[i]=a),"update"===s.operation&&(s.timea.time?(f[o].conflict.push(n),"cloud"===r?(f[o].delete.push(n),e[i]=a):f[o].upload.push(n)):console.info("ignore",a)),"delete"===s.operation&&console.info("ignore",a)),"update"===a.operation&&("save"===s.operation&&(f[o].update.push(n),e[i]=a),"update"===s.operation&&(s.timea.time?f[o].upload.push(n):console.info("ignore",a)),"delete"===s.operation&&(s.timea.time?f[o].upload.push(n):console.info("ignore",a)))):f[o].upload.push(n):(f[o].save.push(n),e[i]=a)}return{compareResult:f,syncRecords:e}}))}static CompareConfig(e,t,r){return s(this,void 0,void 0,(function*(){let o=Object.keys(e).filter((e=>e.startsWith("config.readerConfig"))),i=Object.keys(e).filter((e=>e.startsWith("config.listConfig"))),n=Object.keys(e).filter((e=>e.startsWith("config.objectConfig"))),s=Object.keys(e).filter((e=>e.startsWith("config.mapConfig"))),a=Object.keys(t).filter((e=>e.startsWith("config.readerConfig"))),c=Object.keys(t).filter((e=>e.startsWith("config.listConfig"))),l=Object.keys(t).filter((e=>e.startsWith("config.objectConfig"))),d=Object.keys(t).filter((e=>e.startsWith("config.mapConfig"))),u={readerConfig:Array.from(new Set(o.concat(a))),listConfig:Array.from(new Set(i.concat(c))),objectConfig:Array.from(new Set(n.concat(l))),mapConfig:Array.from(new Set(s.concat(d)))},p={readerConfig:{update:[],upload:[]},listConfig:{update:[],upload:[]},objectConfig:{update:[],delete:[],conflict:[],upload:[]},mapConfig:{update:[],delete:[],conflict:[],upload:[]}},h=["readerConfig","listConfig"];for(let r of h)for(let o of u[r]){let i=o,n=e[o],s=t[o];n?s?n.times.time?p[r].upload.push(i):console.info("ignore",s):p[r].upload.push(i):(p[r].update.push(i),e[o]=s)}let f=["objectConfig","mapConfig"];for(let o of f)for(let i of u[o]){let n=i,s=e[i],a=t[i];s?a?("delete"===a.operation&&("update"===s.operation&&(s.timea.time?(p[o].conflict.push(n),"cloud"===r?(p[o].delete.push(n),e[i]=a):p[o].upload.push(n)):console.info("ignore",a)),"delete"===s.operation&&console.info("ignore",a)),"update"===a.operation&&("update"===s.operation&&(s.timea.time?p[o].upload.push(n):console.info("ignore",a)),"delete"===s.operation&&(s.timea.time?p[o].upload.push(n):console.info("ignore",a)))):p[o].upload.push(n):(p[o].update.push(n),e[i]=a)}return{compareResult:p,syncRecords:e}}))}static compareAll(e,t,r,o,i){return s(this,void 0,void 0,(function*(){let n="cloud";if("yes"===r.getReaderConfig("isKeepLocal")){n="local";let e=r.getObjectConfig(yield o.getFingerprint(),"cloudSyncTime",{time:0,conflictMode:"cloud"}),t=yield i.getCloudConfig("config"),s=JSON.parse(t.cloudSyncTime||"{}");delete s[yield o.getFingerprint()],Object.values(s).filter((t=>"local"===t.conflictMode&&t.time>e.time)).length>0&&(n="cloud")}let{compareResult:s,syncRecords:a}=yield this.CompareDatabase(e,t,n),{compareResult:c,syncRecords:l}=yield this.CompareConfig(a,t,n),d=Object.assign(Object.assign({},s),c);return r.setAllSyncRecord(l),"local"===n&&(d.books.conflict.length>0||d.notes.conflict.length>0||d.bookmarks.conflict.length>0||d.plugins.conflict.length>0||d.words.conflict.length>0||d.objectConfig.conflict.length>0||d.mapConfig.conflict.length>0)?r.setObjectConfig(yield o.getFingerprint(),{time:(new Date).getTime(),conflictMode:"local"},"cloudSyncTime"):r.setObjectConfig(yield o.getFingerprint(),{time:(new Date).getTime(),conflictMode:"cloud"},"cloudSyncTime"),d}))}static startSync(e,t,r,o,i,n){return s(this,void 0,void 0,(function*(){return[...yield this.syncConfig(e,t,r,i,o),...yield this.syncCover(t,n,i),...yield this.syncBook(t,i)]}))}static syncConfig(e,t,r,o,i){return s(this,void 0,void 0,(function*(){let n=[];for(let t of c){if(e[t].save.length+e[t].update.length>0){let o=yield i.getCloudDatabase(t);for(let i of e[t].save){let e=o.find((e=>e.key===i));e&&(yield r.saveRecord(e,t))}for(let i of e[t].update){let e=o.find((e=>e.key===i));e&&(yield r.updateRecord(e,t,!1))}}if(e[t].delete.length>0)for(let i of e[t].delete)yield r.deleteRecord(i,t),"books"===t&&(yield o.deleteOfflineBook(i))}if(e.readerConfig.update.length>0||e.listConfig.update.length>0||e.objectConfig.update.length>0||e.mapConfig.update.length>0){let r=yield i.getCloudConfig("config");for(let o of e.readerConfig.update){let e=o.split(".")[3];r.readerConfig&&t.setReaderConfig(e,JSON.parse(r.readerConfig)[e],!1)}for(let o of e.listConfig.update){let e=o.split(".")[3];r[e]&&t.setAllListConfig(JSON.parse(r[e]),e,!1)}for(let o of e.objectConfig.update){let e=o.split(".")[3],i=o.split(".")[2];r[i]&&JSON.parse(r[i])&&JSON.parse(r[i])[e]&&t.setObjectConfig(e,JSON.parse(r[i])[e],i,!1)}for(let o of e.mapConfig.update){let e=o.split(".")[3],i=o.split(".")[2];if(r[i]&&JSON.parse(r[i])&&JSON.parse(r[i])[e]){let o=JSON.parse(r[i])[e];t.setOneMapConfig(e,o,i,!1)}}}if(e.objectConfig.delete.length>0||e.mapConfig.delete.length>0){for(let r of e.objectConfig.delete){let e=r.split(".")[3],o=r.split(".")[2];t.deleteObjectConfig(e,o)}for(let r of e.mapConfig.delete){let e=r.split(".")[3],o=r.split(".")[2];t.deleteMapConfig(e,o)}}for(let t of c)e[t].upload.length>0&&n.push((()=>i.uploadDatabase(t)));return n.push((()=>i.uploadConfig("config"))),n.push((()=>i.uploadConfig("sync"))),n}))}static syncCover(e,t,r){return s(this,void 0,void 0,(function*(){let r=yield t.getLocalCoverList(),o=yield t.getCloudCoverList(),i=Array.from(new Set([...r,...o])),n=[];for(let s of i)r.includes(s)&&!o.includes(s)&&n.push((()=>t.uploadCover(s))),!r.includes(s)&&o.includes(s)&&"adrive"!==e.getItem("defaultSyncOption")&&n.push((()=>t.downloadCover(s)));return n}))}static syncBook(e,t){return s(this,void 0,void 0,(function*(){let r=yield t.getLocalBookList(),o=yield t.getCloudBookList(),i=[],n=Array.from(new Set([...r,...o]));for(let s of n){if(r.includes(s)&&!o.includes(s)){let e=s.split(".")[0],r=s.split(".")[1];i.push((()=>t.uploadBook(e,r)))}let n="yes"===e.getReaderConfig("autoOffline");if(!r.includes(s)&&o.includes(s)&&n&&"adrive"!==e.getItem("defaultSyncOption")){let e=s.split(".")[0],r=s.split(".")[1];i.push((()=>t.offlineBook(e,r.toUpperCase())))}}return i}))}static runTasksWithLimit(e,t,r){return s(this,void 0,void 0,(function*(){if("ftp"!==r&&"adrive"!==r){const r=[],o=[];for(const i of e){const e=i().then((t=>(o.splice(o.indexOf(e),1),t)));r.push(e),o.push(e),o.length>=t&&(yield Promise.race(o))}return Promise.all(r)}for(let t of e)yield t()}))}}const X=(Y=class{static getItem(e){return localStorage.getItem(e)}static setItem(e,t){localStorage.setItem(e,t)}static removeItem(e){localStorage.removeItem(e)}},G="browser",class extends Y{static getReaderConfig(e){return JSON.parse(this.getItem("readerConfig")||"{}")[e]}static setReaderConfig(e,t,r=!0){let o=JSON.parse(this.getItem("readerConfig")||"{}");o[e]=t,this.setItem("readerConfig",JSON.stringify(o)),r&&this.setSyncRecord({type:"config",catergory:"readerConfig",name:G,key:e},{operation:"update",time:Date.now()})}static getAllListConfig(e){return("{}"!==this.getItem(e)&&this.getItem(e)?JSON.parse(this.getItem(e)||""):[])||[]}static deleteListConfig(e,t){let r=this.getAllListConfig(t);const o=r.indexOf(e);o>-1&&r.splice(o,1),this.setAllListConfig(r,t)}static setListConfig(e,t){let r=this.getAllListConfig(t);const o=r.indexOf(e);o>-1?(r.splice(o,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,o=!0){let i=this.getAllObjectConfig(r);i[e]=t,o&&this.setSyncRecord({type:"config",catergory:"objectConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllObjectConfig(i,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 o=this.getAllMapConfig(r);void 0===o[e]&&(o[e]=[]),t&&-1===o[e].indexOf(t)&&o[e].unshift(t),this.setSyncRecord({type:"config",catergory:"mapConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(o,r)}static setOneMapConfig(e,t,r,o=!0){let i=this.getAllMapConfig(r);i[e]=t,o&&this.setSyncRecord({type:"config",catergory:"mapConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(i,r)}static deleteFromMapConfig(e,t,r){let o=this.getAllMapConfig(r),i=o[e].indexOf(t);o[e].splice(i,1),this.setSyncRecord({type:"config",catergory:"mapConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(o,r)}static deleteFromAllMapConfig(e,t){let r=this.getAllMapConfig(t);Object.keys(r).forEach((o=>{let i=r[o].indexOf(e);i>-1&&(r[o].splice(i,1),this.setSyncRecord({type:"config",catergory:"mapConfig",name:t,key:o},{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),o=[];for(let t in r)r[t]&&r[t].indexOf(e)>-1&&o.push(t);return o}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 setSyncRecord(e,t){let r=JSON.parse(this.getItem("syncRecord")||"{}");r[e.type+"."+e.catergory+"."+e.name+"."+e.key]=t,this.setItem("syncRecord",JSON.stringify(r))}static setAllSyncRecord(e){this.setItem("syncRecord",JSON.stringify(e))}});var Y,G;let Z;const ee=new Uint8Array(16);function te(){if(!Z&&(Z="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Z))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Z(ee)}const re=[];for(let e=0;e<256;++e)re.push((e+256).toString(16).slice(1));var oe={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function ie(e,t,r){if(oe.randomUUID&&!t&&!e)return oe.randomUUID();const o=(e=e||{}).random||(e.rng||te)();if(o[6]=15&o[6]|64,o[8]=63&o[8]|128,t){r=r||0;for(let e=0;e<16;++e)t[r+e]=o[e];return t}return function(e,t=0){return re[e[t+0]]+re[e[t+1]]+re[e[t+2]]+re[e[t+3]]+"-"+re[e[t+4]]+re[e[t+5]]+"-"+re[e[t+6]]+re[e[t+7]]+"-"+re[e[t+8]]+re[e[t+9]]+"-"+re[e[t+10]]+re[e[t+11]]+re[e[t+12]]+re[e[t+13]]+re[e[t+14]]+re[e[t+15]]}(o)}class ne{static saveAllToken(e){return s(this,void 0,void 0,(function*(){if(e)if(n){const{ipcRenderer:t}=window.require("electron");t.invoke("encrypt-data",{token:e})}else{const t=yield this.encryptString(e);localStorage.setItem("encryptedToken",t)}}))}static getAllToken(){return s(this,void 0,void 0,(function*(){if(n){const{ipcRenderer:e}=window.require("electron");return yield e.invoke("decrypt-data")}{let e=localStorage.getItem("encryptedToken")||"";return e?yield this.decryptString(e):null}}))}static setToken(e,t){return s(this,void 0,void 0,(function*(){const r=JSON.parse((yield this.getAllToken())||"{}");r[e]=t,yield this.saveAllToken(JSON.stringify(r))}))}static getToken(e){return s(this,void 0,void 0,(function*(){return JSON.parse((yield this.getAllToken())||"{}")[e]||null}))}static deleteToken(e){return s(this,void 0,void 0,(function*(){const t=JSON.parse((yield this.getAllToken())||"{}");delete t[e],yield this.saveAllToken(JSON.stringify(t))}))}static encryptString(e){return s(this,void 0,void 0,(function*(){try{let t=yield this.getFingerprint();const r=yield ce(t),o=yield function(e,t,r={alg:"HS256",typ:"JWT"}){return s(this,void 0,void 0,(function*(){const o=se((new TextEncoder).encode(JSON.stringify(r))),i=se((new TextEncoder).encode(JSON.stringify(e))),n=(new TextEncoder).encode(`${o}.${i}`),s=yield crypto.subtle.importKey("raw",(new TextEncoder).encode(t),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return`${o}.${i}.${se(yield crypto.subtle.sign("HMAC",s,n))}`}))}(e,r);return o}catch(e){return console.error("Error generating secret:",e),""}}))}static decryptString(e){return s(this,void 0,void 0,(function*(){try{let t=yield this.getFingerprint();const r=yield ce(t),o=yield function(e,t){return s(this,void 0,void 0,(function*(){const[r,o,i]=e.split("."),n=(new TextEncoder).encode(`${r}.${o}`),s=yield ae(i),a=yield crypto.subtle.importKey("raw",(new TextEncoder).encode(t),{name:"HMAC",hash:{name:"SHA-256"}},!1,["verify"]);if(!(yield crypto.subtle.verify("HMAC",a,s,n)))throw new Error("Invalid signature");return JSON.parse((new TextDecoder).decode(ae(o)))}))}(e,r);return o}catch(e){return console.error("Error generating secret:",e),""}}))}static oldDecryptString(e){return s(this,void 0,void 0,(function*(){let t=yield this.getFingerprint();const r=yield crypto.subtle.digest("SHA-256",(new TextEncoder).encode(t)),o=yield crypto.subtle.importKey("raw",r,{name:"AES-GCM",length:256},!1,["decrypt"]),i=new Uint8Array(e.split("").map((e=>e.charCodeAt(0)))),n=i.slice(0,12),s=i.slice(12),a=yield crypto.subtle.decrypt({name:"AES-GCM",iv:n},o,s);return(new TextDecoder).decode(a)}))}static getFingerprint(){return s(this,void 0,void 0,(function*(){if(n){const{ipcRenderer:e}=window.require("electron");return yield e.invoke("get-mac")}{let e=X.getItem("fingerPrint");if(e)return e;let t=ie().replace(/-/g,"");return X.setItem("fingerPrint",t),t}}))}}function se(e){return btoa(String.fromCharCode.apply(null,Array.from(new Uint8Array(e)))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function ae(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=atob(t),o=new Uint8Array(r.length);for(let e=0;e=0&&r<=Re}}function rt(e){return function(t){return null==t?void 0:t[e]}}var ot=rt("byteLength"),it=tt(ot),nt=/\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/;var st=ve?function(e){return Ee?Ee(e)&&!He(e):it(e)&&nt.test(ye.call(e))}:et(!1),at=rt("length");function ct(e,t){t=function(e){for(var t={},r=e.length,o=0;o":">",'"':""","'":"'","`":"`"},Gt=Xt(Yt),Zt=Xt(Ot(Yt)),er=ut.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g},tr=/(.)^/,rr={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},or=/\\|'|\r|\n|\u2028|\u2029/g;function ir(e){return"\\"+rr[e]}var nr=/^\s*(\w|\$)+\s*$/;var sr=0;function ar(e,t,r,o,i){if(!(o instanceof t))return e.apply(r,i);var n=jt(e.prototype),s=e.apply(n,i);return Ae(s)?s:n}var cr=Oe((function(e,t){var r=cr.placeholder,o=function(){for(var i=0,n=t.length,s=Array(n),a=0;a1)ur(a,t-1,r,o),i=o.length;else for(var c=0,l=a.length;c0&&(r=t.apply(this,arguments)),e<=1&&(t=null),r}}var mr=cr(yr,2);function vr(e,t,r){t=Jt(t,r);for(var o,i=lt(e),n=0,s=i.length;n0?0:i-1;n>=0&&n0?s=n>=0?n:Math.max(n+a,s):a=n>=0?Math.min(n+1,a):n+a+1;else if(r&&n&&a)return o[n=r(o,i)]===i?n:-1;if(i!=i)return(n=t(ge.call(o,s,a),Ze))>=0?n+s:-1;for(n=e>0?s:a-1;n>=0&&n=3;return function(t,r,o,i){var n=!dr(t)&<(t),s=(n||t).length,a=e>0?0:s-1;for(i||(o=t[n?n[a]:a],a+=e);a>=0&&a=0}var zr=Oe((function(e,t,r){var o,i;return Ue(t)?i=t:(t=Bt(t),o=t.slice(0,-1),t=t[t.length-1]),Rr(e,(function(e){var n=i;if(!n){if(o&&o.length&&(e=Pt(e,o)),null==e)return;n=e[t]}return null==n?n:n.apply(e,r)}))}));function Br(e,t){return Rr(e,qt(t))}function Pr(e,t,r){var o,i,n=-1/0,s=-1/0;if(null==t||"number"==typeof t&&"object"!=typeof e[0]&&null!=e)for(var a=0,c=(e=dr(e)?e:Rt(e)).length;an&&(n=o);else t=Jt(t,r),Sr(e,(function(e,r,o){((i=t(e,r,o))>s||i===-1/0&&n===-1/0)&&(n=e,s=i)}));return n}var $r=/[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g;function Dr(e){return e?Ve(e)?ge.call(e):Me(e)?e.match($r):dr(e)?Rr(e,Dt):Rt(e):[]}function Nr(e,t,r){if(null==t||r)return dr(e)||(e=Rt(e)),e[Ht(e.length-1)];var o=Dr(e),i=at(o);t=Math.max(Math.min(t,i),0);for(var n=i-1,s=0;s1&&(o=Ut(o,t[1])),t=yt(e)):(o=Qr,t=ur(t,!1,!1),e=Object(e));for(var i=0,n=t.length;i1&&(r=t[1])):(t=Rr(ur(t,!1,!1),String),o=function(e,r){return!jr(t,r)}),Hr(e,o,r)}));function Xr(e,t,r){return ge.call(e,0,Math.max(0,e.length-(null==t||r?1:t)))}function Yr(e,t,r){return null==e||e.length<1?null==t||r?void 0:[]:null==t||r?e[0]:Xr(e,e.length-t)}function Gr(e,t,r){return ge.call(e,null==t||r?1:t)}var Zr=Oe((function(e,t){return t=ur(t,!0,!0),Ir(e,(function(e){return!jr(t,e)}))})),eo=Oe((function(e,t){return Zr(e,t)}));function to(e,t,r,o){Ie(t)||(o=r,r=t,t=!1),null!=r&&(r=Jt(r,o));for(var i=[],n=[],s=0,a=at(e);st?(o&&(clearTimeout(o),o=null),a=l,s=e.apply(i,n),o||(i=n=null)):o||!1===r.trailing||(o=setTimeout(c,d)),s};return l.cancel=function(){clearTimeout(o),a=0,o=i=n=null},l},debounce:function(e,t,r){var o,i,n,s,a,c=function(){var l=Vt()-i;t>l?o=setTimeout(c,t-l):(o=null,r||(s=e.apply(a,n)),o||(n=a=null))},l=Oe((function(l){return a=this,n=l,i=Vt(),o||(o=setTimeout(c,t),r&&(s=e.apply(a,n))),s}));return l.cancel=function(){clearTimeout(o),o=n=a=null},l},wrap:function(e,t){return cr(t,e)},negate:gr,compose:function(){var e=arguments,t=e.length-1;return function(){for(var r=t,o=e[t].apply(this,arguments);r--;)o=e[r].call(this,o);return o}},after:function(e,t){return function(){if(--e<1)return t.apply(this,arguments)}},before:yr,once:mr,findKey:vr,findIndex:br,findLastIndex:wr,sortedIndex:Tr,indexOf:Cr,lastIndexOf:xr,find:_r,detect:_r,findWhere:function(e,t){return _r(e,Nt(t))},each:Sr,forEach:Sr,map:Rr,collect:Rr,reduce:Ar,foldl:Ar,inject:Ar,reduceRight:Fr,foldr:Fr,filter:Ir,select:Ir,reject:function(e,t,r){return Ir(e,gr(Jt(t)),r)},every:Lr,all:Lr,some:Mr,any:Mr,contains:jr,includes:jr,include:jr,invoke:zr,pluck:Br,where:function(e,t){return Ir(e,Nt(t))},max:Pr,min:function(e,t,r){var o,i,n=1/0,s=1/0;if(null==t||"number"==typeof t&&"object"!=typeof e[0]&&null!=e)for(var a=0,c=(e=dr(e)?e:Rt(e)).length;ao||void 0===r)return 1;if(re.map((e=>e.name)),uo=e=>e.map((e=>e.key)),po=(e,t)=>{let r=[];for(let o=0;o-1&&r.push(t.indexOf(e[o]));return r.length{if(-1===e.indexOf(o))for(let e=0;ee-Math.min(...r))))]};class ho{static sortBooks(e,t,r){let o=e.map((e=>e.key)),i=(e=>e.getAllListConfig("recentBooks"))(r);if(1===t.sort||0===t.sort)return 1===t.order?po(i,o).reverse():po(i,o);if(2===t.sort){let r=lo(e),o=lo(e).sort();return 1===t.order?po(o,r).reverse():po(o,r)}if(3===t.sort){let r=[];for(let t=0;t{let t=e.getAllObjectConfig("readingTime");var r=[];for(let e in t)r.push([e,t[e]]);return r.sort((function(e,t){return e[1]-t[1]})),Object.keys(t)})(r),i=uo(e);return 1===t.order?po(co.union(o,i),i).reverse():po(co.union(o,i),i)}if(5===t.sort){let r=uo(e),o=(e=>co.sortBy(e.map((e=>({key:e.key,author:e.author}))),"author").map((e=>e.key)))(e);return 1===t.order?po(o,r).reverse():po(o,r)}if(6===t.sort){let o=(e=>{let t=e.getAllObjectConfig("recordLocation");var r=[];for(let e in t)r.push([e,t[e].percentage||0]);return r.sort((function(e,t){return e[1]-t[1]})),r.map((e=>e[0]))})(r),i=uo(e);return 1===t.order?po(o,i).reverse():po(o,i)}}static sortNotes(e,t,r=[]){if(3===t.sort){let r=co.clone(e).reverse(),o=co.uniq(e.map((e=>({chapter:e.chapter,chapterIndex:e.chapterIndex}))));o=1===t.order?co.sortBy(o,"chapterIndex"):co.sortBy(o,"chapterIndex").reverse();let i=co.uniq(o.map((e=>e.chapter))),n={};return i.forEach((e=>{n[e]=[]})),r.forEach((e=>{n[e.chapter].push(e)})),i.map((e=>({group:e,notes:n[e]})))||[]}if(2===t.sort){let r=co.clone(e).reverse(),o=co.uniq(e.map((e=>e.date.year+"-"+e.date.month+"-"+e.date.day)));1===t.order?o.sort():o.sort().reverse();let i={};return o.forEach((e=>{i[e]=[]})),r.forEach((e=>{o.forEach((t=>{t===e.date.year+"-"+e.date.month+"-"+e.date.day&&i[t].push(e)}))})),i||{}}if(1===t.sort){let o=co.clone(e).reverse(),i=co.uniq(e.map((e=>{let t=co.findLastIndex(r,{key:e.bookKey});return t>-1?r[t].name:""})));1===t.order?i.sort():i.sort().reverse();let n={};return i.forEach((e=>{n[e]=[]})),o.forEach((e=>{i.forEach((t=>{let o=co.findLastIndex(r,{key:e.bookKey});o>-1&&t===r[o].name&&n[t].push(e)}))})),n||{}}}static sortBookmarks(e,t){if(3===t.sort){let r=co.clone(e).reverse(),o=co.uniq(e.map((e=>({chapter:e.chapter,chapterIndex:parseInt(JSON.parse(e.cfi).chapterDocIndex)}))));o=1===t.order?co.sortBy(o,"chapterIndex"):co.sortBy(o,"chapterIndex").reverse();let i=co.uniq(o.map((e=>e.chapter))),n={};return i.forEach((e=>{n[e]=[]})),r.forEach((e=>{n[e.chapter].push(e)})),i.map((e=>({group:e,bookmarks:n[e]})))||[]}}}class fo{static getDefaultCss(e){return`::selection{background:#f3a6a68c}::-moz-selection{background:#f3a6a68c}.kookit-note:hover{cursor:pointer;}img{max-width:100% !important}body,html{margin: 0px !important; padding: 0px !important;}.kookit-text{${this.getCustomCss(e)}}code,pre{white-space: pre-wrap;}p{margin-block: 0;margin-inline: 0;}${"yes"===e.getReaderConfig("isOverwriteLink")?"a{color: #0066cc !important; text-decoration: underline !important; cursor: pointer !important;}a:hover{color: #004080 !important;}a:visited{color: #6600cc !important;}":""}${"yes"===e.getReaderConfig("isMergeWord")?`h1{font-size: ${e.getReaderConfig("fontSize")||18}px !important;}`:""}`}static getCustomCss(e){return`font-size: ${e.getReaderConfig("fontSize")?e.getReaderConfig("fontSize"):"18"}px !important;line-height: ${e.getReaderConfig("lineHeight")||"1.25"} !important;font-family: ${e.getReaderConfig("fontFamily")||""} !important;background-color: transparent;color: ${e.getReaderConfig("textColor")?e.getReaderConfig("textColor"):"rgba(44,47,49,1)"===e.getReaderConfig("backgroundColor")||"night"===e.getReaderConfig("appSkin")||"system"===e.getReaderConfig("appSkin")&&"yes"===e.getReaderConfig("isOSNight")?"white":""} !important;letter-spacing: ${e.getReaderConfig("letterSpacing")}px !important;text-align: ${e.getReaderConfig("textAlign")?e.getReaderConfig("textAlign"):""} !important;font-weight: ${"yes"===e.getReaderConfig("isBold")?"bold !important":""};font-style: ${"yes"===e.getReaderConfig("isItalic")?"italic !important":""};text-shadow: ${"yes"===e.getReaderConfig("isShadow")?"2px 2px 2px #cccccc !important":""};text-indent: ${"yes"===e.getReaderConfig("isIndent")?"2rem":""};text-decoration: ${"yes"===e.getReaderConfig("isUnderline")?"underline !important":""};margin-bottom: ${e.getReaderConfig("paraSpacing")||0}px !important;padding:0px !important;word-wrap: break-word !important; writing-mode: horizontal-tb !important; `}}class go{static mergeArray(e,t){var r=[];for(let t of e)r.push(t);for(let i of t){var o=!0;for(let t of e)if(i===t){o=!1;break}o&&r.push(i)}return r}static fuzzyQuery(e,t){for(var r=[],o=0;o-1&&r.push(o);return r}static mouseSearch(e){let t=document.querySelector(".header-search-box").value.toLowerCase(),r=[],o=[];if(!e)return[];e.forEach((e=>{r.push(e.name.toLowerCase()),o.push(e.author.toLowerCase())}));let i=this.fuzzyQuery(r,t),n=this.fuzzyQuery(o,t);return this.mergeArray(i,n)}static keywordSearch(e,t){let r=[],o=[];if(!t)return[];t.forEach((e=>{r.push(e.name.toLowerCase()),o.push(e.author.toLowerCase())}));let i=this.fuzzyQuery(r,e),n=this.fuzzyQuery(o,e);return this.mergeArray(i,n)}static keySearch(e,t){if(e&&13===e.keyCode){let r=[],o=[];if(!t)return[];t.forEach((e=>{r.push(e.name.toLowerCase()),o.push(e.author.toLowerCase())}));let i=this.fuzzyQuery(r,e.target.value.toLowerCase()),n=this.fuzzyQuery(o,e.target.value.toLowerCase());return this.mergeArray(i,n)}}static mouseNoteSearch(e){let t=document.querySelector(".header-search-box").value.toLowerCase(),r=[],o=[];e.forEach((e=>{r.push(e.notes.toLowerCase()),o.push(e.text.toLowerCase())}));let i=this.fuzzyQuery(r,t),n=this.fuzzyQuery(o,t);return this.mergeArray(i,n)}static keyNoteSearch(e,t){if(e&&13===e.keyCode){let r=[],o=[];t.forEach((e=>{r.push(e.notes.toLowerCase()),o.push(e.text.toLowerCase())}));let i=this.fuzzyQuery(r,e.target.value.toLowerCase()),n=this.fuzzyQuery(o,e.target.value.toLowerCase());return this.mergeArray(i,n)}}}export{q as BookHelper,d as CommonTool,X as ConfigService,h as KookitConfig,H as LoginHelper,K as ReaderRequest,go as SearchUtil,ho as SortUtil,D as SqlStatement,fo as StyleHelper,V as SyncHelper,L as SyncUtil,J as ThirdpartyRequest,ne as TokenService,Q as UserRequest}; diff --git a/src/assets/lib/kookit-extra.min.mjs b/src/assets/lib/kookit-extra.min.mjs index 6597b8b8..3b4681f2 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 n}from"basic-ftp";import{S3Client as s,PutObjectCommand as a,GetObjectCommand as d,ListObjectsV2Command as c,DeleteObjectCommand as l}from"@aws-sdk/client-s3";import{createClient as h,AuthType as u}from"webdav";import p from"ssh2-sftp-client";import f from"form-data";import{Storage as y}from"megajs";import g from"electron-store";import m from"node-machine-id";function v(e,t,r,i){return new(r||(r=Promise))((function(o,n){function s(e){try{d(i.next(e))}catch(e){n(e)}}function a(e){try{d(i.throw(e))}catch(e){n(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(s,a)}d((i=i.apply(e,t||[])).next())}))}const k=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;class T{constructor(e){this.queue=[],this.runningTasks=0,this.totalTasks=0,this.completedTasks=0,this.maxConcurrency=e}addTask(e){return v(this,void 0,void 0,(function*(){return this.totalTasks++,new Promise(((t,r)=>{const i=()=>v(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 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(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let i=[],o=!0,n=null;for(;o;){let s;s=n?yield e.post("https://api.dropboxapi.com/2/files/list_folder/continue",{cursor:n},{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=s.data.entries||[];i=i.concat(a),o=s.data.has_more,n=s.data.cursor}return[...new Set(i.map((e=>e.name)))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return v(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 v(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=(()=>v(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"dropbox",refresh_token:e});return 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){return v(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"dropbox",redirect_uri:E,code:e})).data.refresh_token}))}getAuthUrl(){return`https://www.dropbox.com/oauth2/authorize?response_type=code&token_access_type=offline&client_id=${w}&redirect_uri=${E}`}}const O=i(o.pipeline);class C extends F{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),s=t.createReadStream(r.join(this.storagePath,i));return yield e.post("https://content.dropboxapi.com/2/files/upload",s,{headers:{Authorization:`Bearer ${n}`,"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 v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),s=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 ${n}`,"Dropbox-API-Arg":JSON.stringify({path:"/"+i})},maxContentLength:1/0,maxBodyLength:1/0});return yield O(a.data,s),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class A{constructor(e,t){this.config=e,this.storagePath=t,this.taskQueue=new T(1)}retryOperation(e,t=0){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return 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 v(this,void 0,void 0,(function*(){if(this.client)return this.client;let{url:e,username:t,password:r,dir:i,ssl:o,port:s}=this.config;const a=new n;return a.ftp.verbose=!0,yield a.access({host:e,port:parseInt(s),user:t,password:r,secure:"1"===o}),this.client=a,a}))}uploadFile(e,t){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){let{dir:i}=this.config;i||(i="KoodoReader");const o=yield this.getClient(),n=()=>v(this,void 0,void 0,(function*(){yield o.uploadFrom(r.join(this.storagePath,e),i+"/"+t)}));try{return yield n(),!0}catch(e){return console.error(e),!1}}))))))}))}downloadFile(e,t){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){let{dir:i}=this.config;i||(i="KoodoReader");const o=yield this.getClient(),n=()=>v(this,void 0,void 0,(function*(){yield o.downloadTo(r.join(this.storagePath,t),i+"/"+e)}));try{return yield n(),!0}catch(e){return console.error(e),!1}}))))))}))}listFiles(e){return v(this,void 0,void 0,(function*(){let{dir:t}=this.config;t||(t="KoodoReader");const r=yield this.getClient(),i=()=>v(this,void 0,void 0,(function*(){return yield r.list(t+"/"+e)}));try{return(yield i()).map((e=>e.name))}catch(e){return console.error(e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){let{dir:t}=this.config;t||(t="KoodoReader");const r=yield this.getClient(),i=()=>v(this,void 0,void 0,(function*(){yield r.remove(t+"/"+e)}));try{return yield i(),!0}catch(e){return console.error(e),!1}}))}}class P{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new T(3)}retryOperation(e,t=3){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return 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(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let i=[],o=`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${t}:/children`;for(;o;){const t=yield e.get(o,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});if(t.status>=300)break;const n=t.data.value||[];i=i.concat(n),o=t.data["@odata.nextLink"]||""}return[...new Set(i.map((e=>e.name)))]}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=yield e.delete(`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${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 v(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=(()=>v(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"microsoft",refresh_token:e});return 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){return v(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"microsoft",redirect_uri:E,code:e})).data.refresh_token}))}getAuthUrl(){return`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${R}&scope=files.readwrite.appfolder offline_access&response_type=code&redirect_uri=${E}`}}const I=209715200;class L extends P{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){var n;let s=null;try{const n=yield this.refreshToken(),a=r.join(this.storagePath,i),d=yield this.getFileSize(a),c=o.split(".").pop(),l=(k(c||""),`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${o}:/createUploadSession`),h=(yield e.post(l,{item:{"@microsoft.graph.conflictBehavior":"replace"}},{headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"}})).data.uploadUrl;s=yield t.promises.open(a,"r");let u=0,p=Buffer.alloc(I);for(;uthis.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken(),n=`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${e}:/content`;let s=(yield fetch(n,{headers:{Authorization:"Bearer "+o},redirect:"manual"})).headers.get("location");if(s){const e=yield fetch(s,{headers:{}}),o=yield e.arrayBuffer();return t.writeFileSync(r.join(this.storagePath,i),Buffer.from(o)),!0}return!1}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}getFileSize(e){return v(this,void 0,void 0,(function*(){try{return(yield t.promises.stat(e)).size}catch(e){throw e}}))}}class ${constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new T(3)}retryOperation(e,t=3){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return 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 v(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&spaces=appDataFolder&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 v(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),i=yield this.getFolderId(t);if(i)return i;const o={name:t,mimeType:"application/vnd.google-apps.folder",parents:["appDataFolder"]};try{return(yield e.post("https://www.googleapis.com/drive/v3/files",o,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.id}catch(e){throw console.error("Error occurred during folder creation:",e),e}}))}getFolderId(t){return v(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),i=`https://www.googleapis.com/drive/v3/files?q=name='${t}'+and+mimeType='application/vnd.google-apps.folder'+and+'appDataFolder'+in+parents&spaces=appDataFolder&fields=files(id,name)`;try{const t=(yield e.get(i,{headers:{Authorization:`Bearer ${r}`}})).data.files;return t.length>0?t[0].id:null}catch(e){throw console.error("Error occurred during fetching folder ID:",e),e}}))}listFiles(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let i=yield this.checkFolder(t),o=[],n="",s=!0;for(;s;){let t=`https://www.googleapis.com/drive/v3/files?q='${i}'+in+parents&spaces=appDataFolder&fields=nextPageToken,files(id,name)&pageSize=1000`;n&&(t+=`&pageToken=${n}`);const a=yield e.get(t,{headers:{Authorization:`Bearer ${r}`}}),d=a.data.files||[];o=o.concat(d),n=a.data.nextPageToken,s=!!n}return[...new Set(o.map((e=>e.name)))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQue(e)}))))))}))}deleteFileWithoutQue(t){return v(this,void 0,void 0,(function*(){const r=t.split("/")[1],i=t.split("/")[0],o=yield this.getFolderId(i),n=yield this.refreshToken(),s=yield this.getFileId(r,o);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 ${n}`}});return console.error("File deleted:",t),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}refreshToken(){return v(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=(()=>v(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"google",refresh_token:e});return 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){return v(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"google",redirect_uri:E,code:e})).data.refresh_token}))}getAuthUrl(){return`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${E}&prompt=consent&response_type=code&client_id=${x}&scope=https://www.googleapis.com/auth/drive.appdata&access_type=offline`}}class B extends ${constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken();let s=i.split("/").pop(),a=o.split(".").pop(),d=k(a||""),c=o.split("/")[0],l=yield this.checkFolder(c),h=yield this.getFileId(s||"",l);const u={mimeType:d,name:s,parents:[l]},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 "+n,"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 "+n,"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 v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken();let s=i.split("/").pop(),a=i.split("/")[0],d=yield this.checkFolder(a),c=yield this.getFileId(s||"",d);if(!c)return console.error("File not found"),!0;const l=`https://www.googleapis.com/drive/v3/files/${c}?alt=media`;return new Promise((i=>{const s=t.createWriteStream(r.join(this.storagePath,o));e({url:l,method:"GET",responseType:"stream",headers:{Authorization:"Bearer "+n},maxContentLength:1/0,maxBodyLength:1/0}).then((e=>{e.data.pipe(s),s.on("finish",(()=>{i(!0)})),s.on("error",(()=>{i(!1)}))})).catch((()=>{i(!1)}))}))}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}getFileSize(e){return v(this,void 0,void 0,(function*(){try{return(yield t.promises.stat(e)).size}catch(e){throw e}}))}}class j{constructor(e,t){this.config=e,this.storagePath=t,this.taskQueue=new T(5)}retryOperation(e,t=0){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return 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 v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){let{endpoint:o,region:n,bucketName:d,accessKeyId:c,secretAccessKey:l,dir:h}=this.config;const u=new s({endpoint:o,region:n,credentials:{accessKeyId:c,secretAccessKey:l}});h||(h="KoodoReader");try{let o=yield u.send(new a({Bucket:d,Key:h+"/"+i,Body:t.createReadStream(r.join(this.storagePath,e))}));return 200===o.$metadata.httpStatusCode||(console.error("Error uploading file:",o),!1)}catch(e){return console.error("Error: ",e),!1}}))))))}))}downloadFile(e,i){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){let{endpoint:o,region:n,bucketName:a,accessKeyId:c,secretAccessKey:l,dir:h}=this.config;h||(h="KoodoReader");const u=()=>new Promise(((u,p)=>{const f=new s({region:n,endpoint:o,credentials:{accessKeyId:c,secretAccessKey:l}});let y=t.createWriteStream(r.join(this.storagePath,i));(function(e,t,r,i){return new Promise(((o,n)=>v(this,void 0,void 0,(function*(){const n=yield e.send(new d({Bucket:t,Key:r}));n.Body?(n.Body.pipe(i),i.on("finish",(e=>{e&&o(!1),o(!0)}))):o(!1)}))))})(f,a,h+"/"+e,y).then((e=>{u(!0)})).catch((e=>{console.error(e),u(!1)}))}));try{return yield u()}catch(e){return console.error(e),!1}}))))))}))}listFiles(e){return v(this,void 0,void 0,(function*(){let{endpoint:t,region:r,bucketName:i,accessKeyId:o,secretAccessKey:n,dir:a}=this.config;a||(a="KoodoReader");const d=new s({endpoint:t,region:r,credentials:{accessKeyId:o,secretAccessKey:n}});try{let t,r=[],o=!0;for(;o;){const n=yield d.send(new c({Bucket:i,Prefix:a+"/"+e,ContinuationToken:t}));n.Contents&&(r=r.concat(n.Contents)),t=n.NextContinuationToken,o=!!t}return 0===r.length?[]:[...new Set(r.map((t=>{var r;return null===(r=t.Key)||void 0===r?void 0:r.substring((a+"/"+e).length+1)})).filter((e=>e&&e.length>0)))]}catch(e){return console.error(e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){let{endpoint:t,region:r,bucketName:i,accessKeyId:o,secretAccessKey:n,dir:a}=this.config;a||(a="KoodoReader");const d=new s({endpoint:t,region:r,credentials:{accessKeyId:o,secretAccessKey:n}});try{return yield d.send(new l({Bucket:i,Key:a+"/"+e})),!0}catch(e){return console.error(e),!1}}))}}class M{constructor(e,t){this.storagePath=t;let{username:r,password:i,url:o,dir:n}=e;n||(n="KoodoReader"),this.client=h(o,{authType:u.Password,username:r,password:i}),this.username=r,this.password=i,this.dir=n,this.taskQueue=new T(5)}retryOperation(e,t=0){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return 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 v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{!1===(yield this.client.exists(r.dirname(this.dir+"/"+i)))&&(yield this.client.createDirectory(r.dirname(this.dir+"/"+i)));let o=this.client.createWriteStream(this.dir+"/"+i);return t.createReadStream(r.join(this.storagePath,e)).pipe(o),new Promise(((e,t)=>{o.on("finish",(()=>{e(!0)})),o.on("error",(t=>{console.error(t),e(!1)}))}))}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(e,i){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{if(!1===(yield this.client.exists(this.dir+"/"+e)))return!0;let o=t.createWriteStream(r.join(this.storagePath,i));return this.client.createReadStream(this.dir+"/"+e).pipe(o),new Promise(((e,t)=>{o.on("finish",(()=>{e(!0)})),o.on("error",(t=>{e(!1)}))}))}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}listFiles(e){return v(this,void 0,void 0,(function*(){try{return(yield this.client.getDirectoryContents(this.dir+"/"+e)).map((e=>e.basename))}catch(t){return console.error("Error listing files:",t),t.response&&404===t.response.status&&(yield this.client.createDirectory(this.dir+"/"+e)),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){try{return yield this.client.deleteFile(this.dir+"/"+e),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}}class z{constructor(e,t){this.config=e,this.storagePath=t,this.taskQueue=new T(5)}retryOperation(e,t=0){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return 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 v(this,void 0,void 0,(function*(){if(this.client)return this.client;let{url:e,username:t,password:r,dir:i,port:o}=this.config;const n=new p;return yield n.connect({host:e,port:o,username:t,password:r}),this.client=n,n}))}uploadFile(e,i){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){let{dir:o}=this.config;o||(o="KoodoReader");let n=yield this.getClient();const s=()=>new Promise(((s,a)=>{let d=t.createReadStream(r.join(this.storagePath,e)),c="/"+o+"/"+i;n.put(d,c).then((()=>{s(!0)})).catch((e=>{console.error(e.message),s(!1)}))}));try{return yield s()}catch(e){return console.error(e),!1}}))))))}))}downloadFile(e,i){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){let{dir:o}=this.config;o||(o="KoodoReader");let n=yield this.getClient();const s=()=>new Promise(((s,a)=>{let d="/"+o+"/"+e,c=t.createWriteStream(r.join(this.storagePath,i));n.get(d,c).then((()=>{s(!0)})).catch((e=>{console.error(e.message),s(!1)}))}));try{return yield s()}catch(e){return console.error(e),!1}}))))))}))}listFiles(e){return v(this,void 0,void 0,(function*(){let{dir:t}=this.config;t||(t="KoodoReader");let r=yield this.getClient();try{return yield new Promise(((i,o)=>{let n="/"+t+"/"+e;r.list(n).then((e=>{i(e.map((e=>e.name)))})).catch((e=>{console.error(e.message),i([])}))}))}catch(e){return console.error(e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){let{dir:t}=this.config;t||(t="KoodoReader");let r=yield this.getClient();try{return yield new Promise(((i,o)=>{let n="/"+t+"/"+e;r.delete(n).then((()=>{i(!0)})).catch((e=>{console.error(e.message),i(!1)}))}))}catch(e){return console.error(e),!1}}))}}class K{downloadFile(e,t){return v(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}uploadFile(e,t){return v(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}listFiles(e){return v(this,void 0,void 0,(function*(){return new Promise((e=>{e([])}))}))}authToken(e){return v(this,void 0,void 0,(function*(){return new Promise((e=>{e("")}))}))}getAuthUrl(){return""}}class N{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new T(3)}retryOperation(e,t=3){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return 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 v(this,void 0,void 0,(function*(){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 n=(yield e.get(i,{headers:{Authorization:`Bearer ${r}`}})).data.entries.find((e=>e.name===t&&"folder"===e.type));if(n)o=n.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(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let i=yield this.getFolderIdByPath("KoodoReader/"+t),o=[],n=0,s=!0;const a=1e3;for(;s;){const t=yield e.get(`https://api.box.com/2.0/folders/${i}/items`,{params:{limit:a,offset:n},headers:{Authorization:`Bearer ${r}`}}),d=t.data.entries||[];o=o.concat(d),n+=d.length,s=d.length===a&&t.data.total_count>n}return[...new Set(o.map((e=>e.name)))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=t.substring(0,t.lastIndexOf("/")),o=t.substring(t.lastIndexOf("/")+1),n=yield this.getFolderIdByPath("KoodoReader/"+i);if(!n)return!0;const s=`https://api.box.com/2.0/folders/${n}/items?fields=id,name&type=file&limit=1000`,a=(yield e.get(s,{headers:{Authorization:`Bearer ${r}`}})).data.entries.find((e=>e.name===o&&"file"===e.type));return!a||(yield e.delete(`https://api.box.com/2.0/files/${a.id}`,{headers:{Authorization:`Bearer ${r}`}}),!0)}catch(e){return console.error("Error deleting file:",e),!1}}))}refreshToken(){return v(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=(()=>v(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"boxnet",refresh_token:e});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})});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){return v(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"boxnet",redirect_uri:E,code:e})).data.refresh_token}))}getAuthUrl(){return`https://account.box.com/api/oauth2/authorize?${new URLSearchParams({response_type:"code",client_id:S,redirect_uri:E,grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}).toString()}`}}class D extends N{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),s=o.substring(0,o.lastIndexOf("/")),a=o.substring(o.lastIndexOf("/")+1),d=yield this.getFolderIdByPath("KoodoReader/"+s);if(!d)throw new Error("Folder not found");const c=yield this.listFiles(s);c.find((e=>e===a))&&(yield this.deleteFileWithoutQueue(s+"/"+a));const l=new f,h=JSON.stringify({name:a,parent:{id:d}});l.append("attributes",h),l.append("file",t.createReadStream(r.join(this.storagePath,i)));const u=yield e.post("https://upload.box.com/api/2.0/files/content",l,{headers:Object.assign({Authorization:`Bearer ${n}`},l.getHeaders()),maxContentLength:1/0,maxBodyLength:1/0});return!(u.status>=300)||(console.error("Error occurred during file upload:",u),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),s=i.substring(0,i.lastIndexOf("/")),a=i.substring(i.lastIndexOf("/")+1),d=yield this.getFolderIdByPath("KoodoReader/"+s);if(!d)return console.error("Folder not found"),!0;const c=`https://api.box.com/2.0/folders/${d}/items?fields=id,name&type=file&limit=1000`,l=(yield e.get(c,{headers:{Authorization:`Bearer ${n}`}})).data.entries.find((e=>e.name===a&&"file"===e.type));if(!l)return console.error("File not found:",a),!0;const h=yield e({url:`https://api.box.com/2.0/files/${l.id}/content`,method:"get",responseType:"stream",headers:{Authorization:`Bearer ${n}`}});return yield new Promise(((e,i)=>{const n=t.createWriteStream(r.join(this.storagePath,o));h.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 Q{constructor(e){this.folderCreationLocks=new Map,this.config=e,this.taskQueue=new T(3)}retryOperation(e,t=3){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return 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 v(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}).ready,this.storage}))}getRoot(){return v(this,void 0,void 0,(function*(){if(this.root)return this.root;const e=(yield this.getStorage()).root;let t=e.children.find((e=>"KoodoReader"===e.name&&e.directory));return t||(t=yield e.mkdir("KoodoReader")),this.root=t,this.root}))}createFolder(e,t){return v(this,void 0,void 0,(function*(){const r=`${e.nodeId}_${t}`;if(this.folderCreationLocks.has(r))return yield this.folderCreationLocks.get(r);const i=(()=>v(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 v(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.filter((e=>!e.directory)).map((e=>e.name))}catch(e){return console.error("Error listing MEGA files:",e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(e){return v(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 q extends Q{constructor(e,t){super(e),this.storagePath=t}uploadFile(e,i){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{let o=yield this.getRoot();const n=i.split("/"),s=n.pop()||"";for(const e of n){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===s&&!e.directory));a&&(yield a.delete());const d=t.createReadStream(r.join(this.storagePath,e)),c=t.statSync(r.join(this.storagePath,e)).size;return yield o.upload({name:s,size:c},d).complete,!0}catch(e){return console.error("Error occurred during MEGA file upload:",e),!1}}))))))}))}downloadFile(e,i){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{let o=yield this.getRoot();const n=e.split("/"),s=n.pop()||"";for(const e of n){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===s&&!e.directory));if(!a)return!0;const d=t.createWriteStream(r.join(this.storagePath,i));return new Promise((e=>{a.download().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 W{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.driveId="",this.refreshTokenPromise=null,this.taskQueue=new T(1)}retryOperation(e,t=5){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return 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 v(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 v(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 n=t.split("/").filter((e=>e));let s="",a="root";for(const t of n){s+="/"+t;try{a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:i,file_path:s},{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(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=yield this.getDriveId(),o=yield this.getFolderIdByPath("/KoodoReader/"+t);let n=[],s="",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:s||void 0},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}),d=t.data.items||[];n=n.concat(d),s=t.data.next_marker,a=!!s&&100===d.length}return[...new Set(n.map((e=>e.name)))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=yield this.getDriveId(),o=yield this.getFolderIdByPath("/KoodoReader/"+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 v(this,void 0,void 0,(function*(){try{const i=yield this.refreshToken(),o=yield this.getDriveId(),n=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=n.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:n.data.file_id},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}))}catch(e){}}))}refreshToken(){return v(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=(()=>v(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"adrive",refresh_token:e});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})});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){return v(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"adrive",redirect_uri:E,code:e})).data.refresh_token}))}getAuthUrl(){return`https://openapi.alipan.com/oauth/authorize?${new URLSearchParams({response_type:"code",client_id:_,redirect_uri:E,grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}).toString()}`}}class J extends W{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),s=yield this.getDriveId(),a=o.substring(0,o.lastIndexOf("/")),d=o.substring(o.lastIndexOf("/")+1);yield this.deleteFileWithoutQueue(o);const c=yield this.getFolderIdByPath("/KoodoReader/"+a),l=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:s,parent_file_id:c,name:d,type:"file",check_name_mode:"ignore"},{headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"}}),{file_id:h,upload_id:u,part_info_list:p}=l.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:s,file_id:h,upload_id:u},{headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"}}),!0}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),s=yield this.getDriveId(),a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:s,file_path:"/KoodoReader/"+i},{headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"}})).data.file_id,d=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/getDownloadUrl",{drive_id:s,file_id:a},{headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"}}),c=yield e({url:d.data.url,method:"get",responseType:"stream"}),l=t.createWriteStream(r.join(this.storagePath,o));return c.data.pipe(l),new Promise((e=>{l.on("finish",(()=>{e(!0)})),l.on("error",(t=>{console.error("Error occurred during file download:",t),e(!1)}))}))}catch(e){return console.error("Error downloading file:",e),!1}}))))))}))}}class U{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.taskQueue=new T(3)}retryOperation(e,t=5){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return 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 v(this,void 0,void 0,(function*(){try{return 0===(yield e.get("https://api.pcloud.com/listfolder",{params:{access_token:r,path:`/${t}`}})).data.result}catch(e){return console.error("Error checking folder:",e),!1}}))}createFolder(t,r){return v(this,void 0,void 0,(function*(){try{return 0===(yield e.get("https://api.pcloud.com/createfolderifnotexists",{params:{access_token:r,path:`/${t}`}})).data.result}catch(e){return console.error("Error creating folder:",e),!1}}))}listFiles(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=yield e.get("https://api.pcloud.com/listfolder",{params:{access_token:r,path:"/"+t,recursive:0}});return 0!==i.data.result?[]:i.data.metadata.contents.map((e=>e.name))}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=yield e.get("https://api.pcloud.com/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 v(this,void 0,void 0,(function*(){return this.config.refresh_token}))}authToken(e){return v(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"pcloud",redirect_uri:E,code:e})).data.access_token}))}getAuthUrl(){return`https://my.pcloud.com/oauth2/authorize?client_id=${b}&response_type=code&redirect_uri=${E}`}}class H extends U{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),s=o.split("/").slice(0,-1).join("/");if(!(yield this.checkFolderExists(s,n))){if(!(yield this.createFolder(s,n)))return!1}const a=r.join(this.storagePath,i),d=t.createReadStream(a),c=t.statSync(a),l=r.basename(i),h=yield e({method:"put",url:"https://api.pcloud.com/uploadfile",params:{access_token:n,path:`/${s}`,renew:1,filename:l},data:d,headers:{"Content-Length":c.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 v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),s=yield e.get("https://api.pcloud.com/getfilelink",{params:{access_token:n,path:`/${i}`}});if(0!==s.data.result)return console.error("Error getting file link:",s.data),!1;const a=r.join(this.storagePath,o),d=t.createWriteStream(a),c=`https://${s.data.hosts[0]}${s.data.path}`,l=yield e({method:"get",url:c,responseType:"stream",maxContentLength:1/0,maxBodyLength:1/0});return new Promise((e=>{l.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}}))))))}))}}const V=["book","config","cover","font"];class X{constructor(e,t,r,i){this.type=e,this.storagePath=r,this.remote="dropbox"===e?new C(t,r,i):"microsoft"===e?new L(t,r,i):"google"===e?new B(t,r,i):"s3compatible"===e?new j(t,r):"webdav"===e?new M(t,r):"ftp"===e?new A(t,r):"sftp"===e?new z(t,r):"boxnet"===e?new D(t,r,i):"mega"===e?new q(t,r):"adrive"===e?new J(t,r,i):"pcloud"===e?new H(t,r,i):new K}downloadFile(e,i,o){return v(this,void 0,void 0,(function*(){return t.existsSync(r.join(this.storagePath+"/"+o))||t.mkdirSync(r.join(this.storagePath+"/"+o)),!!(yield this.listFiles(o)).find((t=>e.indexOf(t)>-1))&&(yield this.remote.downloadFile(o+"/"+e,o+"/"+i))}))}uploadFile(e,t,r){return v(this,void 0,void 0,(function*(){return yield this.remote.uploadFile(r+"/"+e,r+"/"+t)}))}deleteFile(e,t){return v(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 v(this,void 0,void 0,(function*(){return(yield this.listFiles(t)).find((t=>-1!==t.indexOf(e)))}))}listFiles(e){return v(this,void 0,void 0,(function*(){return yield this.remote.listFiles(e)}))}downloadAllFiles(){return v(this,void 0,void 0,(function*(){for(let e of V){let t=yield this.listFiles(e);for(let r of t)yield this.downloadFile(r,r,e)}}))}authToken(e){return v(this,void 0,void 0,(function*(){return yield this.remote.authToken(e)}))}getAuthUrl(){return this.remote.getAuthUrl()}getStats(){return this.remote.taskQueue.getStats()}resetCounters(){this.remote.taskQueue.resetCounters()}}const Y={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 = ?"},G={notes:"SELECT * FROM notes WHERE bookKey = ?",bookmarks:"SELECT * FROM bookmarks WHERE bookKey = ?",words:"SELECT * FROM words WHERE bookKey = ?",books:"SELECT * FROM books WHERE key = ?"},Z={notes:"DELETE FROM notes WHERE bookKey = ?",bookmarks:"DELETE FROM bookmarks WHERE bookKey = ?",words:"DELETE FROM words WHERE bookKey = ?"};function ee(e){for(const t in e)e.hasOwnProperty(t)&&(e[`temp-${t}`]=e[t]);return e}const te={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:ee({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:ee({notes:"SELECT * FROM notes",bookmarks:"SELECT * FROM bookmarks",books:"SELECT * FROM books",plugins:"SELECT * FROM plugins",words:"SELECT * FROM words"}),saveStatement:ee({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:ee({notes:"DELETE FROM notes",bookmarks:"DELETE FROM bookmarks",books:"DELETE FROM books",plugins:"DELETE FROM plugins",words:"DELETE FROM words"}),updateStatement:ee({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:ee({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:ee({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:ee(Y),getByBookKeyStatement:ee(G),getByBookKeysStatement:ee({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(",")})`}),deleteByBookKeyStatement:ee(Z)},jsonToSqlite:ee({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:ee(te)};const ie="https://cloud.960960.xyz";class oe{constructor(e,t){this.processingQueue=!1,this.requestQueue=[],this.TokenService=e,this.ConfigService=t,this.refreshToken="",this.accessToken="",this.streamPromise=null}refreshUserToken(){return v(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(ie+"/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),this.accessToken=t.data.access_token,this.refreshToken=t.data.refresh_token),t}))}requestWithRetry(e){return v(this,void 0,void 0,(function*(){return this.requestQueue||(this.requestQueue=[]),new Promise(((t,r)=>{this.requestQueue.push({config:e,resolve:t,reject:r}),this.processingQueue||this.processQueue()}))}))}processQueue(){return v(this,void 0,void 0,(function*(){if(!this.processingQueue){this.processingQueue=!0;try{for(;this.requestQueue.length>0;){const e=this.requestQueue.shift();try{let t=yield this.executeRequest(e.config);e.resolve(t)}catch(t){e.reject(t)}}}finally{this.processingQueue=!1}}}))}executeRequest(t){return v(this,void 0,void 0,(function*(){try{try{this.accessToken=(yield this.TokenService.getToken("access_token"))||""}catch(e){console.error("Error get Token:",e)}let r="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);t.baseURL=ie,t.headers?(t.headers.Authorization="Bearer "+this.accessToken,t.headers["X-Request-ID"]=r):t.headers={Authorization:"Bearer "+this.accessToken,"X-Request-ID":r};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",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 v(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>v(this,void 0,void 0,(function*(){try{let i="";try{i=(yield this.TokenService.getToken("access_token"))||""}catch(e){console.error("Error get Token:",e)}let o="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((n,s)=>{const a=new r(ie+e.url,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+i,"X-Request-ID":o},method:e.method,body:JSON.stringify(e.data),pollingInterval:0});a.addEventListener("open",(()=>{console.info("Connection to OpenAI established.")})),a.addEventListener("message",(e=>v(this,void 0,void 0,(function*(){if(!e.data)return;const r=JSON.parse(e.data);r.done?(a.close(),n(r)):(402===r.code&&(yield this.refreshUserToken()),t(r.data))})))),a.addEventListener("error",(e=>{console.error("Error:",e),n({code:500,message:"internal error"}),a.close()}))}))}finally{this.streamPromise=null}})))()),this.streamPromise}))}requestWithFetch(e,t){return v(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>v(this,void 0,void 0,(function*(){try{let r="";try{r=(yield this.TokenService.getToken("access_token"))||""}catch(e){console.error("Error get Token:",e)}let i="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((o,n)=>v(this,void 0,void 0,(function*(){const n=yield fetch(ie+e.url,{method:"POST",headers:{"Content-Type":"text/event-stream",Authorization:"Bearer "+r,"X-Request-ID":i},body:JSON.stringify(e.data)});if(!n.body)throw new Error("Response body is null");const s=n.body.pipeThrough(new TextDecoderStream).getReader();for(;;){const{value:e,done:r}=yield s.read();if(r){t({done:!0});break}if(e)if(e.includes('"code":400')||e.includes('"code":401')||e.includes('"code":402')){let t=JSON.parse(e);402===t.code&&(yield this.refreshUserToken()),o(t)}else e.split("\n").forEach((e=>{if(e.startsWith("data:")){const r=JSON.parse(e.substring(5));t(r.data)}}))}}))))}finally{this.streamPromise=null}})))()),this.streamPromise}))}}class ne extends oe{constructor(e,t){super(e,t)}encryptToken(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/encrypt_token",data:e};return yield this.requestWithRetry(t)}))}decryptToken(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/decrypt_token",data:e};return yield this.requestWithRetry(t)}))}authThirdToken(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/auth_token",data:e};return yield this.requestWithRetry(t)}))}refreshThirdToken(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/refresh_token",data:e};return yield this.requestWithRetry(t)}))}s3Upload(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/s3_upload",data:e};return yield this.executeRequest(t)}))}s3Download(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/s3_download",data:e};return yield this.executeRequest(t)}))}s3List(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/s3_list",data:e};return yield this.executeRequest(t)}))}s3Delete(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/s3_delete",data:e};return yield this.executeRequest(t)}))}getSyncState(){return v(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"get",url:"/api/v1/pro/thirdparty/get_sync_state"})}))}deleteSyncState(){return v(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"post",url:"/api/v1/pro/thirdparty/delete_sync_state"})}))}}const se=new g;class ae{static encrypt(e,t){let r="";for(let i=0;i-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 setSyncRecord(e,t){let r=JSON.parse(this.getItem("syncRecord")||"{}");r[e.type+"."+e.catergory+"."+e.name+"."+e.key]=t,this.setItem("syncRecord",JSON.stringify(r))}static setAllSyncRecord(e){this.setItem("syncRecord",JSON.stringify(e))}});var le,he;export{ce as ConfigService,re as SqlStatement,X as SyncUtil,ne as ThirdpartyRequest,ae 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 n}from"basic-ftp";import{S3Client as s,PutObjectCommand as a,GetObjectCommand as d,ListObjectsV2Command as c,DeleteObjectCommand as l}from"@aws-sdk/client-s3";import{createClient as h,AuthType as u}from"webdav";import p from"ssh2-sftp-client";import f from"form-data";import{Storage as y}from"megajs";import g from"electron-store";import m from"node-machine-id";function v(e,t,r,i){return new(r||(r=Promise))((function(o,n){function s(e){try{d(i.next(e))}catch(e){n(e)}}function a(e){try{d(i.throw(e))}catch(e){n(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(s,a)}d((i=i.apply(e,t||[])).next())}))}const k=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;class T{constructor(e){this.queue=[],this.runningTasks=0,this.totalTasks=0,this.completedTasks=0,this.maxConcurrency=e}addTask(e){return v(this,void 0,void 0,(function*(){return this.totalTasks++,new Promise(((t,r)=>{const i=()=>v(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 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(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let i=[],o=!0,n=null;for(;o;){let s;s=n?yield e.post("https://api.dropboxapi.com/2/files/list_folder/continue",{cursor:n},{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=s.data.entries||[];i=i.concat(a),o=s.data.has_more,n=s.data.cursor}return[...new Set(i.map((e=>e.name)))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return v(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 v(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=(()=>v(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"dropbox",refresh_token:e});return 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){return v(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"dropbox",redirect_uri:E,code:e})).data.refresh_token}))}getAuthUrl(){return`https://www.dropbox.com/oauth2/authorize?response_type=code&token_access_type=offline&client_id=${w}&redirect_uri=${E}`}}const O=i(o.pipeline);class C extends F{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),s=t.createReadStream(r.join(this.storagePath,i));return yield e.post("https://content.dropboxapi.com/2/files/upload",s,{headers:{Authorization:`Bearer ${n}`,"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 v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),s=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 ${n}`,"Dropbox-API-Arg":JSON.stringify({path:"/"+i})},maxContentLength:1/0,maxBodyLength:1/0});return yield O(a.data,s),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class A{constructor(e,t){this.config=e,this.storagePath=t,this.taskQueue=new T(1)}retryOperation(e,t=0){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return 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 v(this,void 0,void 0,(function*(){if(this.client)return this.client;let{url:e,username:t,password:r,dir:i,ssl:o,port:s}=this.config;const a=new n;return a.ftp.verbose=!0,yield a.access({host:e,port:parseInt(s),user:t,password:r,secure:"1"===o}),this.client=a,a}))}uploadFile(e,t){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){let{dir:i}=this.config;i||(i="KoodoReader");const o=yield this.getClient(),n=()=>v(this,void 0,void 0,(function*(){yield o.uploadFrom(r.join(this.storagePath,e),i+"/"+t)}));try{return yield n(),!0}catch(e){return console.error(e),!1}}))))))}))}downloadFile(e,t){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){let{dir:i}=this.config;i||(i="KoodoReader");const o=yield this.getClient(),n=()=>v(this,void 0,void 0,(function*(){yield o.downloadTo(r.join(this.storagePath,t),i+"/"+e)}));try{return yield n(),!0}catch(e){return console.error(e),!1}}))))))}))}listFiles(e){return v(this,void 0,void 0,(function*(){let{dir:t}=this.config;t||(t="KoodoReader");const r=yield this.getClient(),i=()=>v(this,void 0,void 0,(function*(){return yield r.list(t+"/"+e)}));try{return(yield i()).map((e=>e.name))}catch(e){return console.error(e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){let{dir:t}=this.config;t||(t="KoodoReader");const r=yield this.getClient(),i=()=>v(this,void 0,void 0,(function*(){yield r.remove(t+"/"+e)}));try{return yield i(),!0}catch(e){return console.error(e),!1}}))}}class P{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new T(3)}retryOperation(e,t=3){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return 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(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let i=[],o=`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${t}:/children`;for(;o;){const t=yield e.get(o,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});if(t.status>=300)break;const n=t.data.value||[];i=i.concat(n),o=t.data["@odata.nextLink"]||""}return[...new Set(i.map((e=>e.name)))]}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=yield e.delete(`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${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 v(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=(()=>v(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"microsoft",refresh_token:e});return 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){return v(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"microsoft",redirect_uri:E,code:e})).data.refresh_token}))}getAuthUrl(){return`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${R}&scope=files.readwrite.appfolder offline_access&response_type=code&redirect_uri=${E}`}}const I=209715200;class L extends P{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){var n;let s=null;try{const n=yield this.refreshToken(),a=r.join(this.storagePath,i),d=yield this.getFileSize(a),c=o.split(".").pop(),l=(k(c||""),`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${o}:/createUploadSession`),h=(yield e.post(l,{item:{"@microsoft.graph.conflictBehavior":"replace"}},{headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"}})).data.uploadUrl;s=yield t.promises.open(a,"r");let u=0,p=Buffer.alloc(I);for(;uthis.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken(),n=`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${e}:/content`;let s=(yield fetch(n,{headers:{Authorization:"Bearer "+o},redirect:"manual"})).headers.get("location");if(s){const e=yield fetch(s,{headers:{}}),o=yield e.arrayBuffer();return t.writeFileSync(r.join(this.storagePath,i),Buffer.from(o)),!0}return!1}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}getFileSize(e){return v(this,void 0,void 0,(function*(){try{return(yield t.promises.stat(e)).size}catch(e){throw e}}))}}class ${constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new T(3)}retryOperation(e,t=3){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return 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 v(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&spaces=appDataFolder&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 v(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),i=yield this.getFolderId(t);if(i)return i;const o={name:t,mimeType:"application/vnd.google-apps.folder",parents:["appDataFolder"]};try{return(yield e.post("https://www.googleapis.com/drive/v3/files",o,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.id}catch(e){throw console.error("Error occurred during folder creation:",e),e}}))}getFolderId(t){return v(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),i=`https://www.googleapis.com/drive/v3/files?q=name='${t}'+and+mimeType='application/vnd.google-apps.folder'+and+'appDataFolder'+in+parents&spaces=appDataFolder&fields=files(id,name)`;try{const t=(yield e.get(i,{headers:{Authorization:`Bearer ${r}`}})).data.files;return t.length>0?t[0].id:null}catch(e){throw console.error("Error occurred during fetching folder ID:",e),e}}))}listFiles(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let i=yield this.checkFolder(t),o=[],n="",s=!0;for(;s;){let t=`https://www.googleapis.com/drive/v3/files?q='${i}'+in+parents&spaces=appDataFolder&fields=nextPageToken,files(id,name)&pageSize=1000`;n&&(t+=`&pageToken=${n}`);const a=yield e.get(t,{headers:{Authorization:`Bearer ${r}`}}),d=a.data.files||[];o=o.concat(d),n=a.data.nextPageToken,s=!!n}return[...new Set(o.map((e=>e.name)))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQue(e)}))))))}))}deleteFileWithoutQue(t){return v(this,void 0,void 0,(function*(){const r=t.split("/")[1],i=t.split("/")[0],o=yield this.getFolderId(i),n=yield this.refreshToken(),s=yield this.getFileId(r,o);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 ${n}`}});return console.error("File deleted:",t),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}refreshToken(){return v(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=(()=>v(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"google",refresh_token:e});return 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){return v(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"google",redirect_uri:E,code:e})).data.refresh_token}))}getAuthUrl(){return`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${E}&prompt=consent&response_type=code&client_id=${x}&scope=https://www.googleapis.com/auth/drive.appdata&access_type=offline`}}class B extends ${constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken();let s=i.split("/").pop(),a=o.split(".").pop(),d=k(a||""),c=o.split("/")[0],l=yield this.checkFolder(c),h=yield this.getFileId(s||"",l);const u={mimeType:d,name:s,parents:[l]},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 "+n,"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 "+n,"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 v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken();let s=i.split("/").pop(),a=i.split("/")[0],d=yield this.checkFolder(a),c=yield this.getFileId(s||"",d);if(!c)return console.error("File not found"),!0;const l=`https://www.googleapis.com/drive/v3/files/${c}?alt=media`;return new Promise((i=>{const s=t.createWriteStream(r.join(this.storagePath,o));e({url:l,method:"GET",responseType:"stream",headers:{Authorization:"Bearer "+n},maxContentLength:1/0,maxBodyLength:1/0}).then((e=>{e.data.pipe(s),s.on("finish",(()=>{i(!0)})),s.on("error",(()=>{i(!1)}))})).catch((()=>{i(!1)}))}))}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}getFileSize(e){return v(this,void 0,void 0,(function*(){try{return(yield t.promises.stat(e)).size}catch(e){throw e}}))}}class j{constructor(e,t){this.config=e,this.storagePath=t,this.taskQueue=new T(5)}retryOperation(e,t=0){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return 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 v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){let{endpoint:o,region:n,bucketName:d,accessKeyId:c,secretAccessKey:l,dir:h}=this.config;const u=new s({endpoint:o,region:n,credentials:{accessKeyId:c,secretAccessKey:l}});h||(h="KoodoReader");try{let o=yield u.send(new a({Bucket:d,Key:h+"/"+i,Body:t.createReadStream(r.join(this.storagePath,e))}));return 200===o.$metadata.httpStatusCode||(console.error("Error uploading file:",o),!1)}catch(e){return console.error("Error: ",e),!1}}))))))}))}downloadFile(e,i){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){let{endpoint:o,region:n,bucketName:a,accessKeyId:c,secretAccessKey:l,dir:h}=this.config;h||(h="KoodoReader");const u=()=>new Promise(((u,p)=>{const f=new s({region:n,endpoint:o,credentials:{accessKeyId:c,secretAccessKey:l}});let y=t.createWriteStream(r.join(this.storagePath,i));(function(e,t,r,i){return new Promise(((o,n)=>v(this,void 0,void 0,(function*(){const n=yield e.send(new d({Bucket:t,Key:r}));n.Body?(n.Body.pipe(i),i.on("finish",(e=>{e&&o(!1),o(!0)}))):o(!1)}))))})(f,a,h+"/"+e,y).then((e=>{u(!0)})).catch((e=>{console.error(e),u(!1)}))}));try{return yield u()}catch(e){return console.error(e),!1}}))))))}))}listFiles(e){return v(this,void 0,void 0,(function*(){let{endpoint:t,region:r,bucketName:i,accessKeyId:o,secretAccessKey:n,dir:a}=this.config;a||(a="KoodoReader");const d=new s({endpoint:t,region:r,credentials:{accessKeyId:o,secretAccessKey:n}});try{let t,r=[],o=!0;for(;o;){const n=yield d.send(new c({Bucket:i,Prefix:a+"/"+e,ContinuationToken:t}));n.Contents&&(r=r.concat(n.Contents)),t=n.NextContinuationToken,o=!!t}return 0===r.length?[]:[...new Set(r.map((t=>{var r;return null===(r=t.Key)||void 0===r?void 0:r.substring((a+"/"+e).length+1)})).filter((e=>e&&e.length>0)))]}catch(e){return console.error(e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){let{endpoint:t,region:r,bucketName:i,accessKeyId:o,secretAccessKey:n,dir:a}=this.config;a||(a="KoodoReader");const d=new s({endpoint:t,region:r,credentials:{accessKeyId:o,secretAccessKey:n}});try{return yield d.send(new l({Bucket:i,Key:a+"/"+e})),!0}catch(e){return console.error(e),!1}}))}}class M{constructor(e,t){this.storagePath=t;let{username:r,password:i,url:o,dir:n}=e;n||(n="KoodoReader"),this.client=h(o,{authType:u.Password,username:r,password:i}),this.username=r,this.password=i,this.dir=n,this.taskQueue=new T(5)}retryOperation(e,t=0){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return 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 v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{!1===(yield this.client.exists(r.dirname(this.dir+"/"+i)))&&(yield this.client.createDirectory(r.dirname(this.dir+"/"+i)));let o=this.client.createWriteStream(this.dir+"/"+i);return t.createReadStream(r.join(this.storagePath,e)).pipe(o),new Promise(((e,t)=>{o.on("finish",(()=>{e(!0)})),o.on("error",(t=>{console.error(t),e(!1)}))}))}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(e,i){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{if(!1===(yield this.client.exists(this.dir+"/"+e)))return!0;let o=t.createWriteStream(r.join(this.storagePath,i));return this.client.createReadStream(this.dir+"/"+e).pipe(o),new Promise(((e,t)=>{o.on("finish",(()=>{e(!0)})),o.on("error",(t=>{e(!1)}))}))}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}listFiles(e){return v(this,void 0,void 0,(function*(){try{return(yield this.client.getDirectoryContents(this.dir+"/"+e)).map((e=>e.basename))}catch(t){return console.error("Error listing files:",t),t.response&&404===t.response.status&&(yield this.client.createDirectory(this.dir+"/"+e)),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){try{return yield this.client.deleteFile(this.dir+"/"+e),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}}class N{constructor(e,t){this.config=e,this.storagePath=t,this.taskQueue=new T(5)}retryOperation(e,t=0){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return 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 v(this,void 0,void 0,(function*(){if(this.client)return this.client;let{url:e,username:t,password:r,dir:i,port:o}=this.config;const n=new p;return yield n.connect({host:e,port:o,username:t,password:r}),this.client=n,n}))}uploadFile(e,i){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){let{dir:o}=this.config;o||(o="KoodoReader");let n=yield this.getClient();const s=()=>new Promise(((s,a)=>{let d=t.createReadStream(r.join(this.storagePath,e)),c="/"+o+"/"+i;n.put(d,c).then((()=>{s(!0)})).catch((e=>{console.error(e.message),s(!1)}))}));try{return yield s()}catch(e){return console.error(e),!1}}))))))}))}downloadFile(e,i){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){let{dir:o}=this.config;o||(o="KoodoReader");let n=yield this.getClient();const s=()=>new Promise(((s,a)=>{let d="/"+o+"/"+e,c=t.createWriteStream(r.join(this.storagePath,i));n.get(d,c).then((()=>{s(!0)})).catch((e=>{console.error(e.message),s(!1)}))}));try{return yield s()}catch(e){return console.error(e),!1}}))))))}))}listFiles(e){return v(this,void 0,void 0,(function*(){let{dir:t}=this.config;t||(t="KoodoReader");let r=yield this.getClient();try{return yield new Promise(((i,o)=>{let n="/"+t+"/"+e;r.list(n).then((e=>{i(e.map((e=>e.name)))})).catch((e=>{console.error(e.message),i([])}))}))}catch(e){return console.error(e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){let{dir:t}=this.config;t||(t="KoodoReader");let r=yield this.getClient();try{return yield new Promise(((i,o)=>{let n="/"+t+"/"+e;r.delete(n).then((()=>{i(!0)})).catch((e=>{console.error(e.message),i(!1)}))}))}catch(e){return console.error(e),!1}}))}}class K{downloadFile(e,t){return v(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}uploadFile(e,t){return v(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}listFiles(e){return v(this,void 0,void 0,(function*(){return new Promise((e=>{e([])}))}))}authToken(e){return v(this,void 0,void 0,(function*(){return new Promise((e=>{e("")}))}))}getAuthUrl(){return""}}class z{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new T(3)}retryOperation(e,t=3){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return 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 v(this,void 0,void 0,(function*(){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 n=(yield e.get(i,{headers:{Authorization:`Bearer ${r}`}})).data.entries.find((e=>e.name===t&&"folder"===e.type));if(n)o=n.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(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let i=yield this.getFolderIdByPath("KoodoReader/"+t),o=[],n=0,s=!0;const a=1e3;for(;s;){const t=yield e.get(`https://api.box.com/2.0/folders/${i}/items`,{params:{limit:a,offset:n},headers:{Authorization:`Bearer ${r}`}}),d=t.data.entries||[];o=o.concat(d),n+=d.length,s=d.length===a&&t.data.total_count>n}return[...new Set(o.map((e=>e.name)))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=t.substring(0,t.lastIndexOf("/")),o=t.substring(t.lastIndexOf("/")+1),n=yield this.getFolderIdByPath("KoodoReader/"+i);if(!n)return!0;const s=`https://api.box.com/2.0/folders/${n}/items?fields=id,name&type=file&limit=1000`,a=(yield e.get(s,{headers:{Authorization:`Bearer ${r}`}})).data.entries.find((e=>e.name===o&&"file"===e.type));return!a||(yield e.delete(`https://api.box.com/2.0/files/${a.id}`,{headers:{Authorization:`Bearer ${r}`}}),!0)}catch(e){return console.error("Error deleting file:",e),!1}}))}refreshToken(){return v(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=(()=>v(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"boxnet",refresh_token:e});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})});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){return v(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"boxnet",redirect_uri:E,code:e})).data.refresh_token}))}getAuthUrl(){return`https://account.box.com/api/oauth2/authorize?${new URLSearchParams({response_type:"code",client_id:b,redirect_uri:E,grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}).toString()}`}}class D extends z{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),s=o.substring(0,o.lastIndexOf("/")),a=o.substring(o.lastIndexOf("/")+1),d=yield this.getFolderIdByPath("KoodoReader/"+s);if(!d)throw new Error("Folder not found");const c=yield this.listFiles(s);c.find((e=>e===a))&&(yield this.deleteFileWithoutQueue(s+"/"+a));const l=new f,h=JSON.stringify({name:a,parent:{id:d}});l.append("attributes",h),l.append("file",t.createReadStream(r.join(this.storagePath,i)));const u=yield e.post("https://upload.box.com/api/2.0/files/content",l,{headers:Object.assign({Authorization:`Bearer ${n}`},l.getHeaders()),maxContentLength:1/0,maxBodyLength:1/0});return!(u.status>=300)||(console.error("Error occurred during file upload:",u),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),s=i.substring(0,i.lastIndexOf("/")),a=i.substring(i.lastIndexOf("/")+1),d=yield this.getFolderIdByPath("KoodoReader/"+s);if(!d)return console.error("Folder not found"),!0;const c=`https://api.box.com/2.0/folders/${d}/items?fields=id,name&type=file&limit=1000`,l=(yield e.get(c,{headers:{Authorization:`Bearer ${n}`}})).data.entries.find((e=>e.name===a&&"file"===e.type));if(!l)return console.error("File not found:",a),!0;const h=yield e({url:`https://api.box.com/2.0/files/${l.id}/content`,method:"get",responseType:"stream",headers:{Authorization:`Bearer ${n}`}});return yield new Promise(((e,i)=>{const n=t.createWriteStream(r.join(this.storagePath,o));h.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 Q{constructor(e){this.folderCreationLocks=new Map,this.config=e,this.taskQueue=new T(3)}retryOperation(e,t=3){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return 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 v(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}).ready,this.storage}))}getRoot(){return v(this,void 0,void 0,(function*(){if(this.root)return this.root;const e=(yield this.getStorage()).root;let t=e.children.find((e=>"KoodoReader"===e.name&&e.directory));return t||(t=yield e.mkdir("KoodoReader")),this.root=t,this.root}))}createFolder(e,t){return v(this,void 0,void 0,(function*(){const r=`${e.nodeId}_${t}`;if(this.folderCreationLocks.has(r))return yield this.folderCreationLocks.get(r);const i=(()=>v(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 v(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.filter((e=>!e.directory)).map((e=>e.name))}catch(e){return console.error("Error listing MEGA files:",e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(e){return v(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 q extends Q{constructor(e,t){super(e),this.storagePath=t}uploadFile(e,i){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{let o=yield this.getRoot();const n=i.split("/"),s=n.pop()||"";for(const e of n){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===s&&!e.directory));a&&(yield a.delete());const d=t.createReadStream(r.join(this.storagePath,e)),c=t.statSync(r.join(this.storagePath,e)).size;return yield o.upload({name:s,size:c},d).complete,!0}catch(e){return console.error("Error occurred during MEGA file upload:",e),!1}}))))))}))}downloadFile(e,i){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{let o=yield this.getRoot();const n=e.split("/"),s=n.pop()||"";for(const e of n){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===s&&!e.directory));if(!a)return!0;const d=t.createWriteStream(r.join(this.storagePath,i));return new Promise((e=>{a.download().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 W{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.driveId="",this.refreshTokenPromise=null,this.taskQueue=new T(1)}retryOperation(e,t=5){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return 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 v(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 v(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 n=t.split("/").filter((e=>e));let s="",a="root";for(const t of n){s+="/"+t;try{a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:i,file_path:s},{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(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=yield this.getDriveId(),o=yield this.getFolderIdByPath("/KoodoReader/"+t);let n=[],s="",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:s||void 0},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}),d=t.data.items||[];n=n.concat(d),s=t.data.next_marker,a=!!s&&100===d.length}return[...new Set(n.map((e=>e.name)))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=yield this.getDriveId(),o=yield this.getFolderIdByPath("/KoodoReader/"+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 v(this,void 0,void 0,(function*(){try{const i=yield this.refreshToken(),o=yield this.getDriveId(),n=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=n.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:n.data.file_id},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}))}catch(e){}}))}refreshToken(){return v(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=(()=>v(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"adrive",refresh_token:e});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})});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){return v(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"adrive",redirect_uri:E,code:e})).data.refresh_token}))}getAuthUrl(){return`https://openapi.alipan.com/oauth/authorize?${new URLSearchParams({response_type:"code",client_id:_,redirect_uri:E,grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}).toString()}`}}class J extends W{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),s=yield this.getDriveId(),a=o.substring(0,o.lastIndexOf("/")),d=o.substring(o.lastIndexOf("/")+1);yield this.deleteFileWithoutQueue(o);const c=yield this.getFolderIdByPath("/KoodoReader/"+a),l=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:s,parent_file_id:c,name:d,type:"file",check_name_mode:"ignore"},{headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"}}),{file_id:h,upload_id:u,part_info_list:p}=l.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:s,file_id:h,upload_id:u},{headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"}}),!0}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),s=yield this.getDriveId(),a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:s,file_path:"/KoodoReader/"+i},{headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"}})).data.file_id,d=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/getDownloadUrl",{drive_id:s,file_id:a},{headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"}}),c=yield e({url:d.data.url,method:"get",responseType:"stream"}),l=t.createWriteStream(r.join(this.storagePath,o));return c.data.pipe(l),new Promise((e=>{l.on("finish",(()=>{e(!0)})),l.on("error",(t=>{console.error("Error occurred during file download:",t),e(!1)}))}))}catch(e){return console.error("Error downloading file:",e),!1}}))))))}))}}class U{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.taskQueue=new T(3)}retryOperation(e,t=5){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return 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 v(this,void 0,void 0,(function*(){try{return 0===(yield e.get("https://api.pcloud.com/listfolder",{params:{access_token:r,path:`/${t}`}})).data.result}catch(e){return console.error("Error checking folder:",e),!1}}))}createFolder(t,r){return v(this,void 0,void 0,(function*(){try{return 0===(yield e.get("https://api.pcloud.com/createfolderifnotexists",{params:{access_token:r,path:`/${t}`}})).data.result}catch(e){return console.error("Error creating folder:",e),!1}}))}listFiles(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=yield e.get("https://api.pcloud.com/listfolder",{params:{access_token:r,path:"/"+t,recursive:0}});return 0!==i.data.result?[]:i.data.metadata.contents.map((e=>e.name))}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=yield e.get("https://api.pcloud.com/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 v(this,void 0,void 0,(function*(){return this.config.refresh_token}))}authToken(e){return v(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"pcloud",redirect_uri:E,code:e})).data.access_token}))}getAuthUrl(){return`https://my.pcloud.com/oauth2/authorize?client_id=${S}&response_type=code&redirect_uri=${E}`}}class H extends U{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),s=o.split("/").slice(0,-1).join("/");if(!(yield this.checkFolderExists(s,n))){if(!(yield this.createFolder(s,n)))return!1}const a=r.join(this.storagePath,i),d=t.createReadStream(a),c=t.statSync(a),l=r.basename(i),h=yield e({method:"put",url:"https://api.pcloud.com/uploadfile",params:{access_token:n,path:`/${s}`,renew:1,filename:l},data:d,headers:{"Content-Length":c.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 v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),s=yield e.get("https://api.pcloud.com/getfilelink",{params:{access_token:n,path:`/${i}`}});if(0!==s.data.result)return console.error("Error getting file link:",s.data),!1;const a=r.join(this.storagePath,o),d=t.createWriteStream(a),c=`https://${s.data.hosts[0]}${s.data.path}`,l=yield e({method:"get",url:c,responseType:"stream",maxContentLength:1/0,maxBodyLength:1/0});return new Promise((e=>{l.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}}))))))}))}}const V=["book","config","cover","font"];class X{constructor(e,t,r,i){this.type=e,this.storagePath=r,this.remote="dropbox"===e?new C(t,r,i):"microsoft"===e?new L(t,r,i):"google"===e?new B(t,r,i):"s3compatible"===e?new j(t,r):"webdav"===e?new M(t,r):"ftp"===e?new A(t,r):"sftp"===e?new N(t,r):"boxnet"===e?new D(t,r,i):"mega"===e?new q(t,r):"adrive"===e?new J(t,r,i):"pcloud"===e?new H(t,r,i):new K}downloadFile(e,i,o){return v(this,void 0,void 0,(function*(){return t.existsSync(r.join(this.storagePath+"/"+o))||t.mkdirSync(r.join(this.storagePath+"/"+o)),!!(yield this.listFiles(o)).find((t=>e.indexOf(t)>-1))&&(yield this.remote.downloadFile(o+"/"+e,o+"/"+i))}))}uploadFile(e,t,r){return v(this,void 0,void 0,(function*(){return yield this.remote.uploadFile(r+"/"+e,r+"/"+t)}))}deleteFile(e,t){return v(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 v(this,void 0,void 0,(function*(){return(yield this.listFiles(t)).find((t=>-1!==t.indexOf(e)))}))}listFiles(e){return v(this,void 0,void 0,(function*(){return yield this.remote.listFiles(e)}))}downloadAllFiles(){return v(this,void 0,void 0,(function*(){for(let e of V){let t=yield this.listFiles(e);for(let r of t)yield this.downloadFile(r,r,e)}}))}authToken(e){return v(this,void 0,void 0,(function*(){return yield this.remote.authToken(e)}))}getAuthUrl(){return this.remote.getAuthUrl()}getStats(){return this.remote.taskQueue.getStats()}resetCounters(){this.remote.taskQueue.resetCounters()}}const Y={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 = ?"},G={notes:"SELECT * FROM notes WHERE bookKey = ?",bookmarks:"SELECT * FROM bookmarks WHERE bookKey = ?",words:"SELECT * FROM words WHERE bookKey = ?",books:"SELECT * FROM books WHERE key = ?"},Z={notes:"DELETE FROM notes WHERE bookKey = ?",bookmarks:"DELETE FROM bookmarks WHERE bookKey = ?",words:"DELETE FROM words WHERE bookKey = ?"};function ee(e){for(const t in e)e.hasOwnProperty(t)&&(e[`temp-${t}`]=e[t]);return e}const te={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:ee({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:ee({notes:"SELECT * FROM notes",bookmarks:"SELECT * FROM bookmarks",books:"SELECT * FROM books",plugins:"SELECT * FROM plugins",words:"SELECT * FROM words"}),saveStatement:ee({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:ee({notes:"DELETE FROM notes",bookmarks:"DELETE FROM bookmarks",books:"DELETE FROM books",plugins:"DELETE FROM plugins",words:"DELETE FROM words"}),updateStatement:ee({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:ee({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:ee({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:ee(Y),getByBookKeyStatement:ee(G),getByBookKeysStatement:ee({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(",")})`}),deleteByBookKeyStatement:ee(Z)},jsonToSqlite:ee({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:ee(te)};const ie="http://192.168.28.159:8000";class oe{constructor(e,t){this.processingQueue=!1,this.requestQueue=[],this.TokenService=e,this.ConfigService=t,this.refreshToken="",this.accessToken="",this.streamPromise=null}refreshUserToken(){return v(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(ie+"/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),this.accessToken=t.data.access_token,this.refreshToken=t.data.refresh_token),t}))}requestWithRetry(e){return v(this,void 0,void 0,(function*(){return this.requestQueue||(this.requestQueue=[]),new Promise(((t,r)=>{this.requestQueue.push({config:e,resolve:t,reject:r}),this.processingQueue||this.processQueue()}))}))}processQueue(){return v(this,void 0,void 0,(function*(){if(!this.processingQueue){this.processingQueue=!0;try{for(;this.requestQueue.length>0;){const e=this.requestQueue.shift();try{let t=yield this.executeRequest(e.config);e.resolve(t)}catch(t){e.reject(t)}}}finally{this.processingQueue=!1}}}))}executeRequest(t){return v(this,void 0,void 0,(function*(){try{try{this.accessToken=(yield this.TokenService.getToken("access_token"))||""}catch(e){console.error("Error get Token:",e)}let r="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);t.baseURL=ie,t.headers?(t.headers.Authorization="Bearer "+this.accessToken,t.headers["X-Request-ID"]=r):t.headers={Authorization:"Bearer "+this.accessToken,"X-Request-ID":r};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",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 v(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>v(this,void 0,void 0,(function*(){try{let i="";try{i=(yield this.TokenService.getToken("access_token"))||""}catch(e){console.error("Error get Token:",e)}let o="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((n,s)=>{const a=new r(ie+e.url,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+i,"X-Request-ID":o},method:e.method,body:JSON.stringify(e.data),pollingInterval:0});a.addEventListener("open",(()=>{console.info("Connection to OpenAI established.")})),a.addEventListener("message",(e=>v(this,void 0,void 0,(function*(){if(!e.data)return;const r=JSON.parse(e.data);console.log(r,"res3455"),r.done?(a.close(),console.log('"Stream completed:", res);',r),n(r)):(402===r.code&&(yield this.refreshUserToken()),t(r.data))})))),a.addEventListener("error",(e=>{if(console.info("Error:",e),!e.data)return;const t=JSON.parse(e.data);n(t),a.close()}))}))}finally{this.streamPromise=null}})))()),this.streamPromise}))}requestWithFetch(e,t){return v(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>v(this,void 0,void 0,(function*(){try{let r="";try{r=(yield this.TokenService.getToken("access_token"))||""}catch(e){console.error("Error get Token:",e)}let i="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((o,n)=>v(this,void 0,void 0,(function*(){const n=yield fetch(ie+e.url,{method:"POST",headers:{"Content-Type":"text/event-stream",Authorization:"Bearer "+r,"X-Request-ID":i},body:JSON.stringify(e.data)});if(!n.body)throw new Error("Response body is null");const s=n.body.pipeThrough(new TextDecoderStream).getReader();for(;;){const{value:e,done:r}=yield s.read();if(console.log(e,"value"),console.log(r,"done"),r){t({done:!0});break}if(e)if(e.includes('"code":400')||e.includes('"code":401')||e.includes('"code":402')){let t=JSON.parse(e);402===t.code&&(yield this.refreshUserToken()),o(t)}else e.split("\n").forEach((e=>{if(e.startsWith("data:")){const r=JSON.parse(e.substring(5));t(r.data)}}))}o({code:200,data:{done:!0}})}))))}finally{this.streamPromise=null}})))()),this.streamPromise}))}}class ne extends oe{constructor(e,t){super(e,t)}encryptToken(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/encrypt_token",data:e};return yield this.requestWithRetry(t)}))}decryptToken(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/decrypt_token",data:e};return yield this.requestWithRetry(t)}))}authThirdToken(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/auth_token",data:e};return yield this.requestWithRetry(t)}))}refreshThirdToken(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/refresh_token",data:e};return yield this.requestWithRetry(t)}))}s3Upload(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/s3_upload",data:e};return yield this.executeRequest(t)}))}s3Download(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/s3_download",data:e};return yield this.executeRequest(t)}))}s3List(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/s3_list",data:e};return yield this.executeRequest(t)}))}s3Delete(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/s3_delete",data:e};return yield this.executeRequest(t)}))}getSyncState(){return v(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"get",url:"/api/v1/pro/thirdparty/get_sync_state"})}))}deleteSyncState(){return v(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"post",url:"/api/v1/pro/thirdparty/delete_sync_state"})}))}}const se=new g;class ae{static encrypt(e,t){let r="";for(let i=0;i-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 setSyncRecord(e,t){let r=JSON.parse(this.getItem("syncRecord")||"{}");r[e.type+"."+e.catergory+"."+e.name+"."+e.key]=t,this.setItem("syncRecord",JSON.stringify(r))}static setAllSyncRecord(e){this.setItem("syncRecord",JSON.stringify(e))}});var le,he;export{ce as ConfigService,re as SqlStatement,X as SyncUtil,ne as ThirdpartyRequest,ae as TokenService}; diff --git a/src/assets/locales/en/translation.json b/src/assets/locales/en/translation.json index 6b4e4193..a1fc37a0 100644 --- a/src/assets/locales/en/translation.json +++ b/src/assets/locales/en/translation.json @@ -63,6 +63,8 @@ "Default": "Default", "Small": "Small", "Medium": "Medium", + "Reading Assistant": "Reading", + "Chat Assistant": "Chat", "Large": "Large", "Cancellation successful": "Cancellation successful", "Only supported by desktop version": "Only supported with the desktop version", diff --git a/src/assets/locales/zh-CN/translation.json b/src/assets/locales/zh-CN/translation.json index c39c0c83..04325823 100644 --- a/src/assets/locales/zh-CN/translation.json +++ b/src/assets/locales/zh-CN/translation.json @@ -284,6 +284,18 @@ "Your trial period has expired": "您的试用已结束", "Exit Pro": "退出专业版", "I've paid": "我已支付", + "Summarize this chapter for me": "帮我总结这一章的内容", + "What are the key points of this chapter": "整理并输出格式清晰的内容要点", + "Remove data source": "移除数据源", + "Ask anything about this chapter": "询问关于这篇文章的任何内容", + "Ask anything about reading or learning": "询问关于阅读和学习的任何问题", + "Hi there! I'm happy to help with any questions about reading or learning": "你好,我可以解答你关于阅读和学习的任何问题。", + "Hi there! What questions do you have about this chapter?": "你好,关于这章内容,您有什么想知道的吗?", + "Thinking, please wait...": "思考中,请稍候...", + "Chat Assistant": "AI 助手", + "Reading Assistant": "AI 问书", + "Recommend me some books from Colleen Hoover": "推荐几本刘慈欣的小说", + "Explain Stoicism and its principles to me": "斯多葛学派的主要思想和观点是什么", "Need help": "需要帮助", "Upgrade": "升级", "You haven't upgraded to Pro yet": "您还不是会员哦", diff --git a/src/assets/styles/fonts/icomoon.eot b/src/assets/styles/fonts/icomoon.eot index c0ac56ed572d152008d644df848be8c9431fa680..78df0741549b18e14e0cff0843aee2244a148191 100644 GIT binary patch delta 584 zcmYLFy=xO;7=NC7FYmPt=FaBh63{l+N;+6A&38efT^uwJ3T-H~*t=W;84{anhYUhM zL{Jz(AHFra7aD)q=R5$`0XBl=l2M%BIf;;EhkVI0 z5$6uaG{RlNm&(=c`ooWOf&POsk1Cs{kIw`cFGQ55@soN6=!HAk29*5 zai2PYG_hzhg&ESkS~Qu6N2WD4itNVKEjNPe!0K8 ziz!7_6}z{~3jODJ>>lUXmIRl}?~ygdZdB}wJSlquTwtPzZ8Zq7X$#0_kL;+R3OmWtlaVc|9Y17Giny#N3J delta 253 zcmZ2*n(@U6Mz)L;28JWa6WPpIteMOHO>`(1oX)_&um^|}l5-Oa#KSH2MFB$r<02sc50I~rmzbM6(~I*r14EJwP<>lLesKu{Gf;*h zc?n3Kfth7;GNS`y)Z`_M-i%S3KQKzhDKi3PfcRe-vvoYb%~u9)7LW#pCyW_Db0PHP dh(vS7_{|d%YZxbsBp+Y{sb`4ad@uPBBLHnkMehIr diff --git a/src/assets/styles/fonts/icomoon.svg b/src/assets/styles/fonts/icomoon.svg index 89a60cdb..b33f652c 100644 --- a/src/assets/styles/fonts/icomoon.svg +++ b/src/assets/styles/fonts/icomoon.svg @@ -98,4 +98,6 @@ + + \ No newline at end of file diff --git a/src/assets/styles/fonts/icomoon.ttf b/src/assets/styles/fonts/icomoon.ttf index f9666af0fa1847e0710587a184e5509052cb0b94..ad6165af98bdfd0bb3e632c7cd41d7c713e02f88 100644 GIT binary patch delta 597 zcmX?dobk^|#(D-u1_lOhh6V;^1_S?KeItG$wwXYYJwTk0oSRr69(L(50|TQBkROts zSX=<41%P}I&5@o{nf90Yb{LRf!N3qNk&&91VmRTm8c^#5puAZIP=NO^mm-jV0?1d% z$StX8x(Z}5B)kFYY01e?woEil@Q+|%NCFvnBsa05fT4(S5d%ZA36QUlmzbM6(~I*r zkRJln&{mLNT*AN%G9cy7#2xO8F_Rd*8Dlp4FiOVNGchpyKfwH*`2d4FgAP!!9-}%C zv-5$FxG*!Dh`1ah5E&bpnKRk}<%AWD%uG$xlogpd8JWMc3UmLN&!@o8FV4Zv#5QLR zD?6JwKRX{gmk1wEA#N3Y2+|1YrKq!GJhe!a!4;1S_eB~rtbUeS!R|aktpa28I6N~HiFnV%F vyg6gy<^%CHjBFrT7KX`IiHAh=-Sm6F+7lTUfRX|bFiqZ=EWBAhX(=NBCZdI3 delta 270 zcmex!lJUrK#(D-u1_lOhh6V;^1_S?KeItG$w&_5TJwTk0oSRr69(L&=0|TQBkROts zSX=<41%P}I&5@o{nI``vuMWtsU|@)SlaZR3VyGnghJhhI1t@Qp0Tkdp%q0)x&jIpP zGIC2Qs;&ZA4DknmdTMg=lPwe3q~y;qFeKUlMGxdARunK4FfIb}{{Z<4d5O8HGrc%} zGcY6p9l+RDkY8K^bSMxcFPXT*oiS<>qc>yJW*tB0R3S^sQ>@~ diff --git a/src/assets/styles/fonts/icomoon.woff b/src/assets/styles/fonts/icomoon.woff index 7f81c407692671ffb58cd2e2d6da454c370cb0c1..8fb4a1c58a1ec346f8b27331dc93947a51fb1d74 100644 GIT binary patch delta 613 zcmbPmg7L&DMv-!VH#Y`G1|UfFVBiMPDSsx4XxGn7&P^;}U|`GuiiCi$c-W=K>50W4 zu{}UO2NVmW=TxQv#f~sA#7ltiU*_9k8L5dW3=9c(fNIP@*l@yUwG5yj14E(+kgo#5 zyob3IGjdBRfMOOv{VgEebd`Z2CqEge&MpaL3D8i6Bc=)d5xI#KK#P+bfP4ioE@E7i zmzbLh6k7n)*apHgy*Pgtk5L_n+4(?7T$q_nL|l#$h>VTQ%o*)~a>9y6W~L@;%8JaKjLhFzg}MLC=TqS4 z7w2GSVw*FEm7PtTpPi4LONfIxQC5`yPsDUaa{+O2fqy5bGbjC-$M}R>h>dY0I}wc}{Cr|;Ow24Sj2rpw(!UpdJZ9nWv`m4TZDD8Rt* r#NxU=jGlZY-kdRUGfzSdBO6GTg<*1A;vp`5H~k*4_QcJ8NrxB#J%fk* delta 319 zcmX?cigCgTMzL~#H#Y`G1|UcgVBiMP$wwF%CmW`UP1F&tpPrnXSir!*m;n?I0b%j5 zOApf%i$P+0fP4-p7D&&jOaqD?VPJ@T1H$r8^6D~D6H^!%;x_=*n1QgNlIWWZpde7} z1(2@-!n}vM3p6SK;yCA=~1n7?s6aV-#Moso%^k$6OJcCg(P8sA+ApTdz zY#q;U^Ob>{1t`G4@PsjA5saRcXwDeF*&?xqaq^y|0|MZniDz8EAOKd$1PmDA&5M(l GG6DcUFilGU diff --git a/src/assets/styles/style.css b/src/assets/styles/style.css index ab8420a1..45f4aaa0 100644 --- a/src/assets/styles/style.css +++ b/src/assets/styles/style.css @@ -1,10 +1,10 @@ @font-face { font-family: 'icomoon'; - src: url('fonts/icomoon.eot?6v0s5e'); - src: url('fonts/icomoon.eot?6v0s5e#iefix') format('embedded-opentype'), - url('fonts/icomoon.ttf?6v0s5e') format('truetype'), - url('fonts/icomoon.woff?6v0s5e') format('woff'), - url('fonts/icomoon.svg?6v0s5e#icomoon') format('svg'); + src: url('fonts/icomoon.eot?rfb0hg'); + src: url('fonts/icomoon.eot?rfb0hg#iefix') format('embedded-opentype'), + url('fonts/icomoon.ttf?rfb0hg') format('truetype'), + url('fonts/icomoon.woff?rfb0hg') format('woff'), + url('fonts/icomoon.svg?rfb0hg#icomoon') format('svg'); font-weight: normal; font-style: normal; font-display: block; @@ -25,6 +25,12 @@ -moz-osx-font-smoothing: grayscale; } +.icon-loading:before { + content: "\e95c"; +} +.icon-send:before { + content: "\e95b"; +} .icon-email:before { content: "\e953"; } diff --git a/src/components/popups/popupAssist/component.tsx b/src/components/popups/popupAssist/component.tsx index 48eb22e4..6f206418 100644 --- a/src/components/popups/popupAssist/component.tsx +++ b/src/components/popups/popupAssist/component.tsx @@ -15,75 +15,70 @@ import { import toast from "react-hot-toast"; import DatabaseService from "../../../utils/storage/databaseService"; import { checkPlugin } from "../../../utils/common"; -import { getSummaryStream } from "../../../utils/request/reader"; +import { getAnswerStream } from "../../../utils/request/reader"; +import { marked } from "marked"; +import { sampleQuestion } from "../../../constants/settingList"; declare var window: any; class PopupAssist extends React.Component { + private chatBoxRef: React.RefObject; + constructor(props: PopupAssistProps) { super(props); this.state = { - sumText: this.props.t("Please wait"), - prototype: "", - sumService: - ConfigService.getReaderConfig("sumService") || + answer: "", + aiService: + ConfigService.getReaderConfig("aiService") || "official-ai-assistant-plugin", - sumTarget: - ConfigService.getReaderConfig("sumTarget") || - getDefaultTransTarget({ - English: "English", - "Simplified Chinese": "Simplified Chinese", - "Traditional Chinese": "Traditional Chinese", - }), isAddNew: false, + isWaiting: false, + question: "", + chatHistory: [], + askHistory: [], + mode: "ask", + inputQuestion: "", }; + this.chatBoxRef = React.createRef(); } - componentDidMount() { - this.handleSum(); - } - async handleSum() { - let originalText = this.props.originalText - .replace(/(\r\n|\n|\r)/gm, "") - .replace(/-/gm, "") - // Remove common garbage characters - .replace( - /[^\x20-\x7E\u00A0-\u00FF\u0100-\u017F\u4E00-\u9FFF\u3000-\u303F]/g, - "" - ) - // Remove consecutive spaces - .replace(/\s{2,}/g, " ") - .trim(); + scrollToBottom = () => { + if (this.chatBoxRef.current) { + const scrollHeight = this.chatBoxRef.current.scrollHeight; + const height = this.chatBoxRef.current.clientHeight; + const maxScrollTop = scrollHeight - height; + this.chatBoxRef.current.scrollTop = maxScrollTop > 0 ? maxScrollTop : 0; + } + }; + async handleAnswer() { + let originalText = + this.state.mode === "ask" + ? this.props.originalText + .replace(/(\r\n|\n|\r)/gm, "") + .replace(/-/gm, "") + // Remove common garbage characters + .replace( + /[^\x20-\x7E\u00A0-\u00FF\u0100-\u017F\u4E00-\u9FFF\u3000-\u303F]/g, + "" + ) + // Remove consecutive spaces + .replace(/\s{2,}/g, " ") + .trim() + : ""; if ( - (!this.state.sumService || + (!this.state.aiService || this.props.plugins.findIndex( - (item) => item.key === this.state.sumService + (item) => item.key === this.state.aiService ) === -1) && !this.props.isAuthed ) { this.setState({ isAddNew: true }); } - this.handleSummary(originalText); + this.handleDoAnswer(originalText); } - handleSummary = async (text: string) => { - let sumText = ""; + handleDoAnswer = async (text: string) => { try { if ( - this.state.sumService && - this.state.sumService !== "official-ai-assistant-plugin" + this.state.aiService && + this.state.aiService !== "official-ai-assistant-plugin" ) { - let plugin = this.props.plugins.find( - (item) => item.key === this.state.sumService - ); - if (!plugin) return; - let dictFunc = plugin.script; - // eslint-disable-next-line no-eval - eval(dictFunc); - sumText = await window.getsumText( - text, - "auto", - this.state.sumTarget, - axios, - this.props.t, - plugin.config - ); } else if (this.props.isAuthed) { let plugin = this.props.plugins.find( (item) => item.key === "official-ai-assistant-plugin" @@ -92,283 +87,437 @@ class PopupAssist extends React.Component { return; } let isFirst = true; - getSummaryStream( + let res = await getAnswerStream( text, - ConfigService.getReaderConfig("sumTarget") || - getDefaultTransTarget(plugin.langList), + this.state.question, + this.state.mode === "ask" + ? this.state.askHistory + : this.state.chatHistory, + this.state.mode, (result) => { + console.log(result, "result"); if (result && result.text) { if (isFirst) { this.setState({ - sumText: result.text, + answer: result.text, + isWaiting: false, }); isFirst = false; } else { this.setState({ - sumText: this.state.sumText + result.text, + answer: this.state.answer + result.text, }); } } + this.scrollToBottom(); } ); - } - - if (sumText.startsWith("https://")) { - openExternalUrl(sumText, true); - } else { - this.setState( - { - sumText: sumText, - }, - () => { - let moreElement = document.querySelector(".dict-learn-more"); - if (moreElement) { - moreElement.addEventListener("click", () => { - openExternalUrl( - window.learnMoreUrl || "https://www.koodoreader.com" - ); - }); - } + console.log(res, "res4534543"); + if (res.data && res.data.done) { + if (this.state.mode === "ask") { + this.setState({ + askHistory: [ + ...this.state.askHistory, + { + role: "assistant", + content: this.state.answer, + }, + ], + answer: "", + question: "", + isWaiting: false, + }); + } else { + this.setState({ + chatHistory: [ + ...this.state.chatHistory, + { + role: "assistant", + content: this.state.answer, + }, + ], + answer: "", + question: "", + isWaiting: false, + }); } - ); + } + if (res.code === 20006) { + this.setState({ + isWaiting: false, + answer: "", + question: "", + }); + } + this.scrollToBottom(); } } catch (error) { console.error(error); this.setState({ - sumText: this.props.t("Error happened"), + answer: this.props.t("Error happened"), }); } }; - handleChangesumService = (sumService: string) => { - let plugin = this.props.plugins.find((item) => item.key === sumService); + handleChangeAiService = (aiService: string) => { + let plugin = this.props.plugins.find((item) => item.key === aiService); if (!plugin) { return; } this.setState( { - sumService: sumService, + aiService: aiService, isAddNew: false, }, () => { - ConfigService.setReaderConfig("sumService", sumService); + ConfigService.setReaderConfig("aiService", aiService); if (!plugin) return; - this.setState( - { - sumTarget: getDefaultTransTarget(plugin.langList), - }, - () => { - if (!plugin) return; - ConfigService.setReaderConfig( - "sumTarget", - getDefaultTransTarget(plugin.langList) - ); - this.handleSum(); - } - ); + this.handleAnswer(); } ); }; - - render() { - const renderSumBox = () => { + handleRenderHistoryMessage = (message: any[]) => { + return message.map((item, index) => { return ( -
-
- -
- -
- -
- {this.state.isAddNew && ( -
-