/*************************************************************************
* 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{communicate as e}from"./communicate.js";import{privateApi as t}from"./private-api.js";import{dcLocalStorage as r}from"../common/local-storage.js";import{util as o}from"./util.js";import{getExpressAssetResponse as s}from"./express.js";import{EXPRESS as a}from"./constant.js";import{common as i}from"./common.js";import{analytics as n,events as c}from"../common/analytics.js";import{OptionPageActions as l,LOCAL_FILE_PERMISSION_URL as d,POPUP_CONTEXT as u,OptionsPageSource as g}from"../common/constant.js";import{loggingApi as m}from"../common/loggingApi.js";import{isRequestIdValid as p}from"./request-validator.js";import{openPreferences as b}from"../common/navigation-helper.js";function f(){let e;return r.getItem("pdfViewer")?"true"===r.getItem("pdfViewer")?e="enabled":"false"===r.getItem("pdfViewer")&&(e="disabled"):e="neverEnabled",e}chrome.runtime.onConnectExternal.addListener(e=>{let t=!1;(e=>{try{return["https://dev.acrobat.adobe.com","https://stage.acrobat.adobe.com","https://acrobat.adobe.com","https://documentcloud.adobe.com"].includes(e)}catch(e){return!1}})(e.sender?.origin)&&(e.onDisconnect.addListener(()=>{t=!0}),e.onMessage.addListener(async r=>{if(t)return;if("get_webpage_html"!==r.task)return void e.postMessage({type:"error",code:"invalid_task",message:"Invalid task"});const o=(e=>{try{if(!e)return null;let t=e.replace(/-/g,"+").replace(/_/g,"/");for(;t.length%4;)t+="=";const r=atob(t),o=new Uint8Array(r.length);for(let e=0;e<r.length;e++)o[e]=r.charCodeAt(e);const s=new TextDecoder("utf-8").decode(o);return JSON.parse(s)}catch(e){return m.error({message:"Error decoding payload",error:e?.message}),null}})(r.payload);if(!o)return void e.postMessage({type:"error",code:"invalid_payload",message:"Invalid payload"});const{tabId:s,requestId:a}=o;try{p(a)}catch(t){return e.postMessage({type:"error",code:"invalid_request_id",message:t.message}),void m.error({message:"Invalid request ID",requestId:a,error:t.message})}let i=null;try{if(!s)return void e.postMessage({type:"error",code:"invalid_tab_id",message:"Invalid tab ID"});try{if(!await chrome.tabs.get(s))throw new Error(`Tab with id ${s} not found`)}catch(t){return e.postMessage({type:"error",code:"tab_not_found",message:`Tab not found: ${t.message}`}),void m.error({message:"Tab not found",error:t.message,requestId:a})}const r=await Promise.race([chrome.scripting.executeScript({target:{tabId:s},func:async()=>await(window.extractWebpageHTML?.())}),new Promise((e,t)=>{setTimeout(()=>{t(new Error("Webpage HTML extraction timeout"))},6e4)})]);if(!r||0===r.length||!r[0]?.result)return m.error({message:"Webpage HTML extraction failed",error:"No result",url:i?.url,requestId:a}),void e.postMessage({type:"error",code:"no_result",message:"Webpage HTML extraction failed: No result"});i=r[0]?.result;const o=i?.html;if(!o)return m.error({message:"Webpage HTML extraction failed",error:"No HTML response",url:i?.url,requestId:a}),void e.postMessage({type:"error",code:"no_html_response",message:"Webpage HTML extraction failed: No HTML response"});m.info({message:"Webpage HTML extracted successfully",processingTime:i?.processingTime,url:i?.url,requestId:a});let n=0;for await(const r of async function*(e,t=33554432){let r=await new Promise((t,r)=>{const o=new Blob([e],{type:"text/html"}),s=new FileReader,a=setTimeout(()=>{r(new Error("FileReader timeout"))},1e4);s.onload=function(){clearTimeout(a);const e=s.result?.split(",")?.[1]||"";t(e)},s.onerror=function(e){clearTimeout(a),r(new Error(`FileReader error: ${e.message||"Unknown error"}`))},s.readAsDataURL(o)});const o=Math.ceil(r.length/t);for(let e=0;e<r.length;e+=t)yield{index:Math.floor(e/t),total:o,data:r.slice(e,e+t),encoding:"base64"};r=null}(o)){if(t)return;e.postMessage({type:"chunk",index:r.index,total:r.total,data:r.data,encoding:r.encoding}),n++}t||e.postMessage({type:"end"})}catch(r){m.error({message:"Webpage HTML extraction failed",error:r?.message,url:i?.url,requestId:a}),t||e.postMessage({type:"error",code:"execution_error",message:`Webpage HTML extraction failed: ${r?.message}`})}finally{i=null}}))});const h=["redirectJob","redirectAuth","user_tags","frictionless_return_user"];export function externalClients(a,l,p){if(m.info({message:"externalClients origins sending message to extension",origin:l.origin}),/^https:\/\/([a-zA-Z\d-]+\.){0,}(adobe|acrobat)\.com(:[0-9]*)?$/.test(l.origin))if("WebRequest"===a.type)switch(a.task){case"detect_extension":p({status:"success",result:"true"});break;case"detect_desktop":try{if(0!=e.version&&1!=e.version){const t=e.version===SETTINGS.READER_VER||e.version===SETTINGS.ERP_READER_VER;p(t?{status:"success",result:"Reader"}:{status:"success",result:"Acrobat"})}else p({status:"success",result:"NoApp"})}catch(e){p({status:"error",code:"error"})}break;case"detect_viewer_enabled":try{p({status:"success",result:f()})}catch(e){p({status:"error",code:"error"})}break;case"enable_viewer":if(!o.isAcrobatOrigin(l.origin)&&!l.origin.includes("local-test.acrobat.com:11010"))return;try{r.setItem("pdfViewer","true"),t.setViewerState("enabled"),p({status:"success"})}catch(e){p({status:"error",code:"error"})}break;case"open_acrobat_clicked":if(!/^https:\/\/((dev|stage)+\.){0,}acrobat\.adobe\.com?$/.test(l.origin)&&!l.origin.includes("local-test.acrobat.com:11010"))return;try{const e=r.getItem("firstOpenedTabId");e?(chrome.tabs.update(e,{active:!0},function(){a?.reload&&chrome.tabs.reload(e)}),p({status:"success"})):p({status:"error",code:"NoTab"})}catch(e){p({status:"error",code:"Error"})}break;case"upsell_redirect_to_pdf":if(!o.isAcrobatOrigin(l.origin)&&!l.origin.includes("local-test.acrobat.com:9019"))return;chrome.tabs.update(l.tab.id,{url:a.pdfUrl});break;case"storage_bulk_read":{if(!o.isAcrobatOrigin(l.origin)&&!o.isAdobeOrigin(l.origin))return;const{keys:e=[]}=a,t={};e.forEach(e=>h.includes(e)&&(t[e]=r.getItem(e))),p({values:t});break}case"storage_bulk_write":{if(!o.isAcrobatOrigin(l.origin)&&!o.isAdobeOrigin(l.origin))return;const{data:e={}}=a;Object.entries(e).forEach(([e,t])=>h.includes(e)&&r.setItem(e,t)),p({status:200});break}case"storage_bulk_remove":{if(!o.isAcrobatOrigin(l.origin)&&!o.isAdobeOrigin(l.origin))return;const{keys:e=[]}=a;e.forEach(e=>h.includes(e)&&r.removeItem(e)),p({status:200});break}case"fetch_express_asset":{const e=new URL(i.getExpressURLs().webAppUrl).origin;if(l.origin!==e)return;const{options:t={}}=a,r=t.sessionId;s(r).then(e=>{const t=e.domain;delete e.domain;try{p(e)}catch(r){n.event(c.EXPRESS_EXECUTE_VERB_FAILED,{eventContext:r.toString(),dvDisableSessionCount:e.buffer?.length,domain:t})}});break}case"openNotificationPreferences":if(!o.isAcrobatOrigin(l.origin)&&!l.origin.includes("local-test.acrobat.adobe.com:9019"))return;r.setItem("optionsPageSource",g.NOTIFICATION_PREFERENCES).then(async()=>{b({preferenceTabId:"general",controlId:"whatsNewAutoOpenTitle",sectionClassNames:["whats-new-auto-open-toggle"]}),p({success:!0})});break;case"openNewTab":{if(!o.isAcrobatOrigin(l.origin)&&!l.origin.includes("local-test.acrobat.adobe.com:9019"))return;const{url:e,storageKey:t,ttl:r}=a;o.createTabWithOptionalTracking(e,t,r).then(e=>{p(e)}).catch(e=>{p({status:"error",message:e?.message})});break}case"openLFASettingsPageWithAnimation":{if(!o.isAcrobatOrigin(l.origin)&&!l.origin.includes("local-test.acrobat.adobe.com:9019"))return;const e=o.constructUrlWithParams(d,{context:u.LOCAL_FILE_COACHMARK,autoDismiss:!0});r.setItem("localFileFteData",{tabId:l?.tab?.id,url:l?.tab?.url}),o.createLocalFilePromptPopup(e,{type:"normal"},e=>{chrome.action.openPopup().catch(e=>console.error(e)),r.setItem("settingsWindow",{id:e?.tabs?.[0]?.id})}).catch(e=>console.error("Failed to create popup window:",e)),p({status:"success"});break}default:p({status:"error",code:"invalid_task"})}else p({status:"error",code:"invalid_type"})}