Files
omnivore/apple/Sources/SafariExtension/Resources/scripts/background.js
2023-10-04 11:13:23 +08:00

1 line
10 KiB
JavaScript

(()=>{"use strict";var e,t=new Uint8Array(16);function n(){if(!e&&!(e="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return e(t)}const s=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;for(var a=[],o=0;o<256;++o)a.push((o+256).toString(16).substr(1));const r=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=(a[e[t+0]]+a[e[t+1]]+a[e[t+2]]+a[e[t+3]]+"-"+a[e[t+4]]+a[e[t+5]]+"-"+a[e[t+6]]+a[e[t+7]]+"-"+a[e[t+8]]+a[e[t+9]]+"-"+a[e[t+10]]+a[e[t+11]]+a[e[t+12]]+a[e[t+13]]+a[e[t+14]]+a[e[t+15]]).toLowerCase();if(!function(e){return"string"==typeof e&&s.test(e)}(n))throw TypeError("Stringified UUID is invalid");return n},i=function(e,t,s){var a=(e=e||{}).random||(e.rng||n)();if(a[6]=15&a[6]|64,a[8]=63&a[8]|128,t){s=s||0;for(var o=0;o<16;++o)t[s+o]=a[o];return t}return r(a)};let c=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce(((e,t)=>e+((t&=63)<36?t.toString(36):t<62?(t-26).toString(36).toUpperCase():t>62?"-":"_")),"");const u=new class{constructor(){this.queue=[],this.isRunning=!1,this.isReady=!1}enqueue(e){this.queue.push(e),this.isReady&&this.runNext()}async runNext(){if(this.isRunning||0===this.queue.length||!this.isReady)return;this.isRunning=!0;const e=this.queue.shift();try{await e()}catch(e){console.error("Task failed:",e)}finally{this.isRunning=!1,this.isReady&&this.runNext()}}setReady(){this.isReady=!0,this.runNext()}},d="https://omnivore.app",l="https://api-prod.omnivore.app/api/";let p={};async function g(e,t){const n=JSON.stringify({query:"mutation UploadFileRequest($input: UploadFileRequestInput!) {\n uploadFileRequest(input:$input) {\n ... on UploadFileRequestError {\n errorCodes\n }\n ... on UploadFileRequestSuccess {\n id\n createdPageId\n uploadSignedUrl\n }\n }\n }",variables:{input:{url:e,contentType:t,createPageEntry:!0}}}),s="uploadFileRequest",a=await gqlRequest(l+"graphql",n);if(!a[s].errorCodes)return a.uploadFileRequest;"UNAUTHORIZED"===a[s].errorCodes[0]?(browserApi.tabs.sendMessage(currentTab.id,{action:ACTIONS.UpdateStatus,payload:{target:"logged_out",status:"logged_out",message:"You are not logged in.",ctx:toolbarCtx}}),b()):browserApi.tabs.sendMessage(currentTab.id,{action:ACTIONS.UpdateStatus,payload:{status:"failure",message:"Unable to save page.",ctx:toolbarCtx}})}function b(){getStorageItem("postInstallClickComplete").then((e=>{e&&removeStorage("postInstallClickComplete")}))}async function f(e,t){const n=i();await I(e,SAVE_URL_QUERY,"saveUrl",{source:"extension",clientRequestId:n,url:encodeURI(t)})}async function I(e,t,n,s){const a={omnivoreURL:d,originalURL:s.url,requestId:s.clientRequestId};p[a.requestId]=void 0;const o=JSON.stringify({query:t,variables:{input:s}});browserApi.tabs.sendMessage(e.id,{action:ACTIONS.ShowToolbar,payload:{type:"loading",ctx:a}});try{const t=await gqlRequest(l+"graphql",o);if(t[n].errorCodes)return void("UNAUTHORIZED"===t[n].errorCodes[0]?(browserApi.tabs.sendMessage(e.id,{action:ACTIONS.UpdateStatus,payload:{target:"logged_out",status:"logged_out",message:"You are not logged in.",ctx:a}}),b()):browserApi.tabs.sendMessage(e.id,{action:ACTIONS.UpdateStatus,payload:{status:"failure",message:"Unable to save page.",ctx:a}}));const s=t[n]?t[n].url:void 0,r=t[n]?t[n].clientRequestId:void 0;browserApi.tabs.sendMessage(e.id,{action:ACTIONS.UpdateStatus,payload:{status:"success",target:"page",ctx:{readerURL:s,responseId:r,requestId:a.requestId}}}),p[a.requestId]={readerURL:s,responseId:r,requestId:a.requestId}}catch(e){console.log("error saving: ",e)}u.setReady()}function y(e,t,n,s){browserApi.tabs.sendMessage(e,{action:ACTIONS.UpdateStatus,payload:{target:t,status:n,message:s}})}async function h(e,t){browserApi.tabs.sendMessage(e.id,{action:ACTIONS.GetContent,payload:{createHighlight:t}},(async t=>{if(!t||"object"!=typeof t)return void await f(e,e.url);const n=i();var{type:s}=t;const{pageInfo:a,doc:o,uploadContentObjUrl:r}=t;switch("html"==s&&handleBackendUrl(e.url)&&(s="url"),s){case"html":await I(e,SAVE_PAGE_QUERY,"savePage",{source:"extension",clientRequestId:n,originalContent:o,title:a.title,url:encodeURI(e.url)});break;case"url":await I(e,SAVE_URL_QUERY,"saveUrl",{source:"extension",clientRequestId:n,url:encodeURI(e.url)});break;case"pdf":{const t=await async function(e,t,n,s,a){const o={omnivoreURL:d,originalURL:t,requestId:n};p[o.requestId]=void 0,browserApi.tabs.sendMessage(e.id,{action:ACTIONS.ShowToolbar,payload:{type:"loading",ctx:o}});const r=await g(t,s);console.log("done uploading pdf",r);const i=await function({id:e,uploadSignedUrl:t},n,s){return fetch(s).then((e=>e.blob())).then((e=>fetch(t,{method:"PUT",headers:{"Content-Type":n},body:e}))).catch((e=>{console.error("error uploading file",e)}))}(r,s,a);return URL.revokeObjectURL(a),i&&r.createdPageId&&(p[o.requestId]={requestId:o.requestId,responseId:r.createdPageId},browserApi.tabs.sendMessage(e.id,{action:ACTIONS.UpdateStatus,payload:{status:"success",target:"page",ctx:{requestId:o.requestId,responseId:r.createdPageId}}})),i}(e,encodeURI(e.url),n,a.contentType,r);if(!t||!t.id)return void await I(e,SAVE_URL_QUERY,"saveUrl",{source:"extension",clientRequestId:n,url:encodeURI(e.url)});break}}}))}async function q(e){const t=await getStorageItem(e+"_saveInProgress");if(!t)return;clearInterval(t);const n=await getStorageItem(e+"_saveInProgressTimeoutId_"+t);n&&clearTimeout(n)}function R(e,t){function n(n,s){browserApi.tabs.get(e,(async e=>{if("complete"!==e.status)browserApi.tabs.sendMessage(e.id,{action:ACTIONS.ShowMessage,payload:{type:"loading",text:"Page loading..."}}),s&&"function"==typeof s&&s();else{n&&"function"==typeof n&&n(),await h(e,t);try{await updateLabelsCache(l+"graphql",e),browserApi.tabs.sendMessage(e.id,{action:ACTIONS.LabelCacheUpdated,payload:{}})}catch(e){return void console.error("error fetching labels",e,l)}}}))}t=!!t,q(e),n(null,(()=>{!function(e,t,n,s=1e3,a=10500){const o=setInterval(e,s),r=setTimeout((()=>{clearInterval(o),t()}),a);n&&"function"==typeof n&&n(o,r)}((()=>{n((()=>{q(e)}))}),(()=>{q(e),browserApi.tabs.get(e,(async e=>{await h(e,t)}))}),((t,n)=>{const s={};s[e+"_saveInProgress"]=t,s[e+"_saveInProgressTimeoutId_"+t]=n,setStorage(s)}))}))}function w(e){return Promise.resolve(!0)}function A(e){new Promise((e=>{browserApi.tabs.query({active:!0,currentWindow:!0},(function(t){e(t[0]||null)}))})).then((t=>{browserApi.tabs.sendMessage(t.id,{action:ACTIONS.Ping},(async function(n){if(n&&n.pong)await w(t.id)&&e(t);else{const n=browserApi.runtime.getManifest().content_scripts,s=[...n[0].js,...n[1].js];!function(n,s,a){function o(e,t,n){return function(){browserScriptingApi.executeScript(e,t,n)}}let r=async function(){await w(t.id)&&e(t)};for(let e=s.length-1;e>=0;--e)r=o(n,{file:s[e]},r);null!==r&&r()}(t.id,s)}}))}))}browserApi.tabs.onActivated.addListener((({tabId:e})=>{!function t(){browserApi.tabs.get(e,(function(e){browserApi.runtime.lastError&&setTimeout(t,150)}))}()})),browserApi.tabs.onRemoved.addListener((e=>{!function(e){getStorage().then((function(t){const n=[],s=Object.keys(t),a=e+"_saveInProgress";for(let e=0;e<s.length;e++){const t=s[e];t.startsWith(a)&&n.push(t)}0!==n.length&&removeStorage(n)}))}(e)})),browserActionApi.onClicked.addListener((function(){A((function(e){R(e.id)}))})),browserApi.runtime.onMessage.addListener(((e,t,n)=>{if(e.forwardToTab)return delete e.forwardToTab,void browserApi.tabs.sendRequest(t.tab.id,e);e.action===ACTIONS.EditTitle&&u.enqueue((()=>async function(e,t){const n=p[t.clientRequestId];return handled=await async function(e,t,n){return updatePageTitle(l+"graphql",n.responseId,t.title).then((()=>(y(e,"title","success","Title updated."),!0))).catch((t=>(console.log("caught error updating title: ",t),y(e,"title","failure","Error updating title."),!0)))}(e,t,n),console.log("processEditTitleRequest: ",handled),handled}(t.tab.id,{id:i(),type:"EDIT_TITLE",tabId:t.tab.id,title:e.payload.title,clientRequestId:e.payload.ctx.requestId}))),e.action===ACTIONS.Archive&&u.enqueue((()=>async function(e,t){const n=p[t.clientRequestId],s=await async function(e,t,n){return archive(l+"graphql",n.responseId).then((()=>(y(e,"extra","success","Archived"),!0))).catch((()=>(y(e,"extra","failure","Error archiving"),!0)))}(e,0,n);return console.log("processArchiveRequest: ",s),s}(t.tab.id,{id:i(),type:"ARCHIVE",tabId:t.tab.id,clientRequestId:e.payload.ctx.requestId}))),e.action===ACTIONS.Delete&&u.enqueue((()=>async function(e,t){const n=p[t.clientRequestId],s=await async function(e,t,n){return deleteItem(l+"graphql",n.responseId).then((()=>(y(e,"extra","success","Deleted"),!0))).catch((()=>(y(e,"extra","failure","Error deleting"),!0)))}(e,0,n);return console.log("processDeleteRequest: ",s),s}(t.tab.id,{type:"DELETE",tabId:t.tab.id,clientRequestId:e.payload.ctx.requestId}))),e.action===ACTIONS.AddNote&&u.enqueue((()=>async function(e,t){const n=p[t.clientRequestId],s=await async function(e,t,n){const s=i(),a=c(8);return addNote(l+"graphql",n.responseId,s,a,t.note).then((()=>(y(e,"note","success","Note updated."),!0))).catch((t=>(console.log("caught error updating title: ",t),y(e,"note","failure","Error adding note."),!0)))}(e,t,n);return console.log("processAddNoteRequest: ",s),s}(t.tab.id,{id:i(),type:"ADD_NOTE",tabId:t.tab.id,note:e.payload.note,clientRequestId:e.payload.ctx.requestId}))),e.action===ACTIONS.SetLabels&&u.enqueue((()=>async function(e,t){const n=p[t.clientRequestId],s=await async function(e,t,n){return setLabels(l+"graphql",n.responseId,t.labels).then((()=>(y(e,"labels","success","Labels updated."),!0))).then((()=>{browserApi.tabs.sendMessage(e,{action:ACTIONS.LabelCacheUpdated,payload:{}})})).catch((()=>(y(e,"labels","failure","Error updating labels."),!0)))}(e,t,n);return console.log("processSetLabelsRequest: ",s),s}(t.tab.id,{id:i(),type:"SET_LABELS",tabId:t.tab.id,labels:e.payload.labels,clientRequestId:e.payload.ctx.requestId})))})),browserApi.contextMenus.create({id:"save-link-selection",title:"Save this link to Omnivore",contexts:["link"],onclick:async function(e){A((async function(t){await f(t,e.linkUrl)}))}}),browserApi.contextMenus.create({id:"save-page-selection",title:"Save this page to Omnivore",contexts:["page"],onclick:async function(e){A((function(e){R(e.id)}))}}),browserApi.contextMenus.create({id:"save-text-selection",title:"Create Highlight and Save to Omnivore",contexts:["selection"],onclick:async function(e){A((function(e){R(e.id,!0)}))}})})();