/*************************************************************************
* ADOBE CONFIDENTIAL
* ___________________
*
*  Copyright 2015 Adobe Systems Incorporated
*  All Rights Reserved.
*
* NOTICE:  All information contained herein is, and remains
* the property of Adobe Systems Incorporated and its suppliers,
* if any.  The intellectual and technical concepts contained
* herein are proprietary to Adobe Systems Incorporated and its
* suppliers and are protected by all applicable intellectual property laws,
* including trade secret and or copyright laws.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Adobe Systems Incorporated.
**************************************************************************/
import{analytics as e}from"../common/analytics.js";import{communicate as t}from"./communicate.js";import{util as n}from"./util.js";import{SETTINGS as a}from"./settings.js";import{dcLocalStorage as r}from"../common/local-storage.js";import{downloadManager as s}from"./download-manager.js";import{privateApi as o}from"./private-api.js";import{viewerModuleUtils as i}from"./viewer-module-utils.js";import{checkAndInitialiseWhatsNewAlarm as c}from"./whats-new-handler.js";import{floodgate as l}from"./floodgate.js";import{openLocalFileFTEPrompts as u}from"./ch-context-menu.js";import{offscreenActions as d}from"./offscreen-actions.js";import{CACHE_PURGE_SCHEME as m}from"./constant.js";import{setExperimentCodeForAnalytics as p,removeExperimentCodeForAnalytics as f}from"../common/experimentUtils.js";import{loggingApi as g}from"../common/loggingApi.js";import{checkForBlockedDomain as b,isAddWebpageToProjectEnabled as h}from"./add-webpage-to-project.js";import{getExpressMenuIds as E,isExpressDomainBlocked as I}from"./express/express-context-menu.js";import{ONE_DAY_IN_MS as _}from"../common/constant.js";let v=null,R=chrome.runtime.getURL("viewer.html"),w={},P={};const L=new Map,C={"dc-sp-enable-fab-auto-positioning":"enableFabAutoPositioning","dc-sp-url-hash-scrolling-feature":"enableURLHashScrollingFeature","dc-sp-enable-fab-drag":"enableFabDrag","dc-cv-genai-webpages-master":"","dc-cv-all-domain-tracking":"allDomainTracking","dc-cv-enable-splunk-logging":"","dc-cv-enable-genai-webpages":"","dc-sp-enable-scrolled-content-ingestion":"enableScrolledContentIngestionInGenAI","dc-sp-enable-gen-ai-unlimited-offer":"enableGenAIUnlimitedOffer","dc-cv-enable-paid-content-detection":"enablePaidContentDetection","dc-sp-enable-fab-for-paid-users":"enableFabForPaidUsers","dc-sp-enable-cs-ssr-for-anon":"enableCSSSRForAnon","dc-sp-enable-html-to-pdf-pill":"enableHtmlToPdfPill"};function D(e){if(void 0!==e.responseHeaders){const t=x(e.responseHeaders,"content-length");if(t)return t.value}}const F=e=>{chrome.management.getSelf().then(async t=>{const n=await Promise.all(Object.entries(C).map(([e,t])=>l.hasFlag(e).then(n=>(t&&r.setItem(t,n),[e,n])))),a=Object.fromEntries(n),s=await l.getReleaseVariant("dc-sp-fab-variant");r.setItem("enableReactFab","dc-sp-enable-react-fab"===s),"dc-sp-enable-react-fab"===s?r.setItem("fabVariant","ReactFAB"):"dc-sp-keep-vanilla-fab"===s&&r.setItem("fabVariant","VanillaFAB");const o="true"===r.getItem("adobeInternal"),u=r.getItem("isAdminUser"),d=r.getItem("isGenAIPaidUser");if(chrome.sidePanel){if(o||a["dc-cv-genai-webpages-master"]&&"admin"!==t.installType&&!u){const t=a["dc-cv-enable-genai-webpages"]||d;!r.getItem("enableGenAIFab")&&t&&r.setItem("enableGenAIFab",`${t}`),t?p("EGW"):f("EGW");const{version:n}=chrome.runtime.getManifest();chrome.sidePanel?.setOptions({enabled:!0,tabId:e.tabId,path:`resources/SidePanel/index.html?tabId=${e.tabId}&version=${n}`}),r.setItem("sidePanelRegistered",!0)}else r.setItem("sidePanelRegistered",!1);const n=a["dc-cv-enable-splunk-logging"];i.enableSplunk(n)}try{c()}catch(e){}});const t=l.getFeatureMeta("dc-cv-genai-webpage-blocklist");if(t){const e=JSON.parse(t);r.setItem("genaiWebpageBlockList",e)}const n=l.getFeatureMeta("dc-cv-genai-webpage-regex-blocklist");if(n)try{const e=JSON.parse(n);Array.isArray(e)&&r.setItem("genaiWebpageRegexBlockList",e)}catch(e){}l.hasFlag("dc-cv-all-domain-tracking").then(e=>{r.setItem("allDomainTracking",e)}),chrome.tabs.get(e.tabId,e=>{chrome.runtime.lastError||O(e)})};function A(e){e&&e!==chrome.windows.WINDOW_ID_NONE&&chrome.tabs.query({active:!0,windowId:e},e=>{e.length>0&&O(e[0])})}export function disableContextMenus(e=[]){e.forEach(async e=>{try{await chrome.contextMenus.update(e,{visible:!1})}catch(e){}})}export function enableContextMenus(e=[]){e.forEach(async e=>{try{await chrome.contextMenus.update(e,{visible:!0})}catch(e){}})}function O(e){if(e.url){const n=new URL(e.url);a.IS_READER||0==t.version||1==t.version&&0==t.NMHConnStatus||(chrome.runtime.id===n.host?disableContextMenus(["convertPageContextMenu","appendPageContextMenu"]):enableContextMenus(["convertPageContextMenu","appendPageContextMenu"])),chrome.runtime.id!==n.host?(Promise.all([h(),b({url:e.url})]).then(([e,t])=>{e&&!t?enableContextMenus(["addWebpageToProject"]):disableContextMenus(["addWebpageToProject"])}),I(e.url).then(e=>{e?disableContextMenus(E()):enableContextMenus(E())})):disableContextMenus(["addWebpageToProject"])}}function S(e){const t=new Date;t.setMinutes(t.getMinutes()+a.VIEWER_RECHECK_CDN_ACCESS_DELAY_MINS),r.setItem("netAccAdT",t.getTime()),r.setItem("netAcc",e)}function T(){try{return"true"===r.getItem("pdfViewer")}catch(e){return!1}}function x(e,t){for(let n=0;n<e.length;++n){let a=e[n];if(a.name.toLowerCase()===t)return a}}function y(t){if(void 0!==t.responseHeaders){const n=x(t.responseHeaders,"content-type"),a=x(t.responseHeaders,"content-disposition"),r=t.url&&new URLSearchParams(t.url)?.has("acrobatPromotionSource");if(n){const s=n.value.toLowerCase().split(";",1)[0].trim();if(a&&/^\s*attachment[;]?/i.test(a.value)&&!r)return!1;if("application/pdf"===s)return!0;if("application/octet-stream"===s){if(a&&/\.pdf(["']|$)/i.test(a.value))return e.event(e.e.VIEWER_PDF_PROCESS_OS_CD),!0;t.url.toLowerCase().indexOf(".pdf")>0&&e.event(e.e.VIEWER_PDF_PROCESS_OS_URL)}}}else if("file"==function(e){let t=e.indexOf("/");return e.substr(0,t-1)}(t.url)&&"PDF"==function(e){if(e)try{let t=new URL(e).pathname;return t.substr(t.lastIndexOf(".")+1).toUpperCase()}catch(e){return""}return""}(t.url))return!0;return!1}const U=async(a,r,o)=>{"loading"===r.status&&r.url&&(n.consoleLog("onTabsUpdated",r.url),chrome.tabs.sendMessage(a,{main_op:"rerunGenAiWebpage"}));const c=o.incognito;if("complete"===o.status&&O(o),"loading"===r.status){t.loading({id:a});try{!n.isViewerURL(o.url)||(T()||i.isTabURLFromExternalTouchPoint(o.url)||i.isPDFSourceFromWhatsNew(o.url))&&!c||W(a,i.extractUrlValue("pdfurl",o.url))}catch(e){}}else if("complete"===r.status){s.newTab(o.url,a);const t=await chrome.extension.isAllowedFileSchemeAccess();o.url.toLowerCase().startsWith("file://")&&o.url.toLowerCase().endsWith(".pdf")&&!t&&(u(o),e.logEventOnce(e.e.LOCAL_FILE_OPENED,{storageKey:"loggedLocalFileEnabled",timePeriod:_}))}};function W(e,t){e&&t&&chrome.tabs.update(e,{url:t})}function M(t){if("GET"!==t.method||!a.VIEWER_ENABLED||!T())return!1;let n=t.url,s=`reloadurl-${t.tabId}`;const o=r.getItem(s),i=r.getItem("nativeFallbackLogging");if(o&&o===n){try{r.removeItem(s)}catch(e){}return!1}const c=y(t);if(!(e=>{if(!e||null===e||"undefined"===e)return!1;let t=[/^chrome\:\/\//,/^chrome\-extension\:\/\//,/^https:\/\/([a-zA-Z\d-]+\.){0,}officeapps.live.com/,/^https\:\/\/*.*\/(saml|login)/,/^https:\/\/sharedcloud.([a-zA-Z\d-]+)+.(s3|s3-accelerate).amazonaws.com/,/^https\:\/\/*.*.\/(login|auth|okta|saml).*\/S*|\/(login|auth|okta|saml|IWA|owa)\//,/^https\:\/\/www.google.com\/search\?q/,/^https\:\/\/www.citibank.*/,/^https:\/\/[^/]*\.*\/([$-/:-?{-~!"^_`\[\]A-Za-z0-9]*)view-sdk/],n=l.getFeatureMeta("dc-cv-invalid-urls");if(n)try{n=JSON.parse(n);for(let e in n)n[e]=new RegExp(n[e]);t=n}catch(e){g.error({message:"Error in parsing dc-cv-invalid-urls meta",error:e})}return!![/^http\:\/\/[^/]/,/^https\:\/\/[^/]/,/^file?:/].find(t=>t.test(e))&&!t.find(t=>t.test(e))})(n)){if(i&&c)try{const t=new URL(n).hostname;e.event(e.e.VIEWER_PDF_UNSUPPORTED_URL,{domain:t})}catch(e){}return!1}return c}function N(e){try{const t=new URL(e.url),n=new URLSearchParams(t.search);let a=!1;const r=e.initiator;return r&&["https://classroom.google.com","https://mail.google.com","https://drive.google.com"].includes(r)&&n.forEach((e,t)=>{t.startsWith("print")&&"true"===e&&(a=!0)}),a}catch(e){return!1}}async function V(t){try{if(r.getItem("retryOnNextPage")){await chrome.scripting.executeScript({target:{tabId:t},files:["content_scripts/injectCopyLSIframe.js"]}),await n.sleep(300),e.event(e.e.LOCAL_STORAGE_MIGRATION_RETRYING);const a=await chrome.runtime.sendMessage({main_op:"copy-ls"});chrome.tabs.sendMessage(t,{content_op:"remove-lsCopy"}).catch(()=>null),"succeed"===a&&(e.event(e.e.LOCAL_STORAGE_MIGRATION_RETRYING_SUCCESS),r.removeItem("retryOnNextPage"),Object.assign(r.storage,await chrome.storage.local.get()))}}catch(e){}}const j=(k=chrome.runtime.getURL(""),k?.replace(/\/+$/,""));var k;function G(t){t.initiator!==j&&"main_frame"!==t.type&&function(t){if(void 0!==t.responseHeaders){const n=x(t.responseHeaders,"content-type"),a=x(t.responseHeaders,"content-disposition");if(n){const r=n.value.toLowerCase().split(";",1)[0].trim();if("application/pdf"===r)return e.event(e.e.VIEWER_PDF_DETECT_EMBED_PDF_TYPE_PDF),!0;if("application/octet-stream"===r){if(a&&/\.pdf(["']|$)/i.test(a.value))return e.event(e.e.VIEWER_PDF_DETECT_EMBED_PDF_OCTET_CD),!0;if(new URL(t.url).pathname.toLowerCase().endsWith(".pdf"))return e.event(e.e.VIEWER_PDF_DETECT_EMBED_PDF_OCTET_URL),!0}}}return!1}(t)&&e.event(e.e.VIEWER_PDF_DETECT_EMBED_PDF)}function H(t){o.isMimeHandlerAvailable().then(async s=>{const{tabId:o}=t;if(await V(o),r.getItem("sessionStarted")||(r.setItem("sessionId",n.uuid()),r.setItem("sessionStarted",!0)),!s){let r=n.parseExtensionURL(t.url);if(r){r=R+"?pdfurl="+r+"&tabId="+o+"&aw=true";let n=t.url.indexOf("#");n>0&&(r+=t.url.slice(n)),a.VIEWER_ENABLED&&T()&&e.event(e.e.VIEWER_EXTN_PDF_OPENED,{tabURL:r}),chrome.tabs.update(o,{url:r})}}})}function B(t){try{l.hasFlag("dc-cv-enable-webpage-domain-tracking",m.NO_CALL).then(n=>{if(n&&"main_frame"===t.type){const n=new URL(t.url).hostname;(a=t.tabId,new Promise(e=>{P[a]=e})).then(t=>{e.event(e.e.VIEWER_PDF_WEBPAGE_OPENED,{domain:n,hasPDFLink:t})})}var a})}catch(e){}}function $(a,s){o.isMimeHandlerAvailable().then(async o=>{r.getItem("sessionStarted")||(r.setItem("sessionId",n.uuid()),r.setItem("sessionStarted",!0));const{tabId:c}=a;if(o){const e=N(a),t=a.tabId;t>-1&&(w[t]={isGooglePrint:e})}else{if("main_frame"===a.type){if(await V(c),!function(){const e=new Date,t=r.getItem("netAcc"),n=r.getItem("netAccAdT");return!(n&&n>e.getTime())||t}()||!M(a))return;if(s&&!await chrome.extension.isAllowedFileSchemeAccess())return void e.event(e.e.VIEWER_PDF_LOCAL_FILE_IGNORED);v=a.url,s&&e.event(e.e.VIEWER_PDF_LOCAL_FILE),i.updateVariables(t.version),i.fetchAndUpdateVersionConfig();let{viewerURL:n,acceptRanges:o}=function(e){let t=R,n=!1;if(t+="?pdfurl="+encodeURIComponent(e.url),t+="&tabId="+e.tabId,void 0!==e.responseHeaders){const a=D(e);a&&(t+="&clen="+a);const r=x(e.responseHeaders,"accept-ranges");r&&r.value&&"bytes"===r.value.toLowerCase()&&!N(e)&&(t+="&chunk=true",n=!0);const s=x(e.responseHeaders,"content-disposition");if(s&&s.value&&/\.pdf(["']|$)/i.test(s.value)){const e=/filename[^;=\n\*]?=((['"]).*?\2|[^;\n]*)/.exec(s.value);null!=e&&e.length>1&&(t+="&pdffilename="+e[1].replace(/['"]/g,""))}}return N(e)&&(t+="&googlePrint=true"),{viewerURL:t,acceptRanges:n}}(a);e.event(e.e.VIEWER_EXTN_PDF_OPENED,{tabURL:v});const l=D(a),u=void 0!==l?Number(l):l;N(a)||d.setupWorkerOffscreen({tabId:c,pdfURL:a.url,pdfSize:u,acceptRanges:o});for(let e=0;e<20;e++)try{await chrome.tabs.update(c,{url:n})}catch(e){}}"sub_frame"===a.type&&function(e){return/^https:\/\/[^/]*(acrobat|adobe)\.com\/dc-chrome-extension/.test(e)}(a.url)&&(200!==a.statusCode?403===a.statusCode?(r.setItem("pdfViewer","false"),e.event(e.e.VIEWER_FALLBACK_TO_NATIVE_CDN_FORBIDDEN,{tabURL:a.url}),W(a.tabId,v)):(S(!1),e.event(e.e.VIEWER_FALLBACK_TO_NATIVE_CDN_OFFLINE,{tabURL:a.url}),W(a.tabId,v)):S(!0))}})}function q(t){try{if(!r.getItem("ignorePrefetchRequests"))return!1;if(L.size>200)return L.clear(),!1;const n=`${t.tabId}_${t.requestId}`,a=L.get(n);if(a){if(a===t.url){L.delete(n);return y(t)&&e.event(e.e.PDF_PREFETCH_REQUEST_SKIPPED),!0}L.delete(n)}return!1}catch(e){return!1}}function z(e){try{if(!r.getItem("ignorePrefetchRequests"))return;const t=e.requestHeaders||[];if(t.some(e=>{const t=e.name.toLowerCase(),n=e.value.toLowerCase();return("purpose"===t||"sec-purpose"===t)&&n.includes("prefetch")})){const t=`${e.tabId}_${e.requestId}`;L.set(t,e.url)}}catch(e){}}function K(e){try{if(!r.getItem("ignorePrefetchRequests"))return;const t=[];for(const[n,a]of L.entries())n.startsWith(`${e}_`)&&t.push(n);t.forEach(e=>L.delete(e))}catch(e){}}t.registerHandlers({"check-is-google-print":function(e,t,n){return w&&w[e.tabId]?n({isGooglePrint:w[e.tabId].isGooglePrint}):n({isGooglePrint:!1})},"resolve-has-pdf-promise":({hasPDFLink:e,tabId:t})=>function(e,t){const n=P[t];n&&(n(e),delete P[t])}(e,t)});export{$ as processRequest,H as honorRequest,F as onTabActivated,U as onTabsUpdated,G as detectEmbeddedPDF,B as logWebpageDomain,q as handlePrefetchValidation,z as detectAndStorePrefetch,K as cleanupPrefetchForTab,A as onWindowFocusChanged};