/*************************************************************************
* 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{events as e}from"../../common/analytics.js";import{util as t}from"./content-util.js";import{privateApi as a}from"./content-privateApi.js";import{dcLocalStorage as o}from"../../common/local-storage.js";import{isEdgeBrowser as n,updateExtUserState as s,isChromeViewerOpened as i,getLocalFilePromptDimensions as c,isLocalFileUrl as r}from"../../common/util.js";import{LOCAL_FILE_PERMISSION_URL as l,OptionPageActions as m,OptionsPageSource as d,OptionsPageToggles as u,POPUP_CONTEXT as p}from"../../common/constant.js";import{loggingApi as g}from"../../common/loggingApi.js";import{indexedDBScript as f}from"../../common/indexDB.js";import _ from"../../sw_modules/dynamic-tab-context-manager.js";import{CACHE_PURGE_SCHEME as h}from"../../sw_modules/constant.js";import{floodgate as E}from"../../sw_modules/floodgate.js";await o.init();const I=o.getItem("appLocale");let A,w,y,L,C;const b=new Promise(e=>C=e),k=$("#cdn-iframe"),S=await chrome.tabs.query({active:!0,lastFocusedWindow:!0}),O={contexts:{},register(e,t,a=!1,o){this.contexts[e]={containerId:t,isDefault:a},o&&o()},show(e){Object.values(this.contexts).forEach(e=>{const t=document.getElementById(e.containerId);t&&(t.style.display="none")});const t=this.contexts[e];if(t){const e=document.getElementById(t.containerId);if(e)return e.style.display="block",!0}const a=Object.values(this.contexts).find(e=>e.isDefault);if(a){const t=document.getElementById(a.containerId);if(t)return t.style.display="block",console.warn(`Context "${e}" not found, falling back to default`),!1}return console.error("No default context found"),!1},init(){this.register(p.DEFAULT,"default-container",!0),this.register(p.LOCAL_FILE_COACHMARK,"local-file-coachmark-container",!1,D),this.register(p.LOCAL_FILE_ACCESS_AND_SUMMARY_COACHMARK,"local-file-access-and-summary-coachmark-container",!1),this.register(p.LOCAL_FILE_SUMMARY_COACHMARK,"local-file-summary-coachmark-container",!1,M)}};async function F(){O.init(),await _.init();let a=p.DEFAULT;const n=S?.[0];if(n?.url)try{const e=new URL(n.url).searchParams.get("context");e&&(a=e)}catch(e){}if(a===p.DEFAULT){const e=_.getPopupContext(n?.id,n?.url);e&&e!==p.DEFAULT&&(a=e)}switch(O.show(a),a){case p.LOCAL_FILE_COACHMARK:P(e.LOCAL_FILE_ANIMATION_COACHMARK_SHOWN);break;case p.LOCAL_FILE_ACCESS_AND_SUMMARY_COACHMARK:P(e.LOCAL_FILE_ACCESS_AND_SUMMARY_COACHMARK_SHOWN),async function(){try{function a(){const e=document.getElementById("local-file-access-and-summary-coachmark-fte"),t=document.getElementById("local-file-access-and-summary-coachmark-fte-primary"),a=document.getElementById("local-file-access-and-summary-coachmark-fte-fallback");if(e&&t&&a){const o=I||chrome.i18n.getMessage("@@ui_locale");t.src=`../images/LocalizedSummaryFte/${o}/summary.mp4`,a.src="../images/LocalizedSummaryFte/en_US/summary.mp4",e.load()}else g.error({message:"Error in Local file summary coachmark on extension popup: FTE element not found"})}t.translateElements(".translate");const n=document.getElementById("local-file-access-and-summary-coachmark-container-content"),s="true"===o.getItem("localFileAccessAndSummaryCochmarkShown");s?n&&n.classList.add("local-file-access-and-summary-coachmark-container-content-second-time"):(n&&(n.classList.remove("local-file-access-and-summary-coachmark-container-content-second-time"),o.setItem("localFileAccessAndSummaryCochmarkShown","true")),a());const i=document.getElementById("local-file-access-and-summary-coachmark-card-content-button");if(i&&n){let c=!1;i.addEventListener("click",async()=>{P(e.LOCAL_FILE_ACCESS_AND_SUMMARY_COACHMARK_BUTTON_CLICKED,{VARIANT:s?"Nudge2":"Nudge1"}),T("localFileAccessAndSummaryCoachmark",p.LOCAL_FILE_SUMMARY_COACHMARK)}),i.addEventListener("mouseover",()=>{n.classList.contains("local-file-access-and-summary-coachmark-container-content-second-time")&&!c&&(a(),c=!0,n.classList.add("button-hovered"))})}}catch(r){g.error({message:"Error in Local file access and summary coachmark on extension popup",error:`initialize: Error in initialization: ${r}`})}}();break;case p.LOCAL_FILE_SUMMARY_COACHMARK:P(e.LOCAL_FILE_SUMMARY_COACHMARK_SHOWN)}}async function T(e,t){const a=await chrome.windows.get(S[0].windowId),{height:n,width:s,left:i,top:r}=c(a);let m=l;const d=l.split("#");m=`${d[0]}&context=${t}&autoDismiss=true#${d[1]}`,chrome.windows.create({height:n,width:s,left:i,top:r,focused:!0,type:"normal",url:m},t=>{chrome.runtime.lastError?g.error({message:"Error in Local File prompt window on extension popup",error:"Error creating window"}):(chrome.action.openPopup().catch(e=>console.error(e)),o.setItem("settingsWindow",{id:t.tabs[0].id,action:e}))})}async function M(){try{t.translateElements(".translate");const e=document.getElementById("local-file-summary-coachmark-fte"),a=document.getElementById("local-file-summary-coachmark-fte-primary"),o=document.getElementById("local-file-summary-coachmark-fte-fallback");if(e&&a&&o){const t=I||chrome.i18n.getMessage("@@ui_locale");a.src=`../images/LocalizedSummaryFte/${t}/summary_nudge_local_file_access.mp4`,o.src="../images/LocalizedSummaryFte/en_US/summary_nudge_local_file_access.mp4",e.load()}else g.error({message:"Error in Local file summary coachmark on extension popup: FTE element not found"})}catch(e){g.error({message:"Error in Local file summary coachmark on extension popup",error:`initialize: Error in initialization: ${e}`})}finally{if(S?.[0]?.url)try{const e=new URL(S[0].url);if(e.searchParams.get("autoDismiss")||!1){const t=parseInt(e.searchParams.get("dismissTimeout"))||1e4;setTimeout(()=>{window.close()},t)}}catch(e){}}}async function D(){try{t.translateElements(".translate");const e=document.getElementById("local-file-animated-fte");if(e){const t=I||chrome.i18n.getMessage("@@ui_locale");e.style.backgroundImage=`url(../images/LocalizedFte/${t}/fte_old.svg),url(../images/LocalizedFte/en_US/fte_old.svg)`}else g.error({message:"Error in Local file animation coachmark on extension popup: FTE element not found"})}catch(e){g.error({message:"Error in Local file animation coachmark on extension popup",error:`initialize: Error in initialization: ${e}`})}finally{if(S?.[0]?.url)try{const e=new URL(S[0].url);if(e.searchParams.get("autoDismiss")||!1){const t=parseInt(e.searchParams.get("dismissTimeout"))||1e4;setTimeout(()=>{window.close()},t)}}catch(e){}}}function R(e){let t=e;return e.tab||(t={...e,tab:S[0]}),chrome.runtime.sendMessage(t)}function P(e,t){R({main_op:"analytics",analytics:[[e,t]]})}const v=e=>{try{const t=new URL(A),a=[/^https:\/\/([a-zA-Z\d-]+\.){0,}(adobe|acrobat)\.com(:[0-9]*)?$/];return e===t.origin&&!!a.find(t=>t.test(e))}catch(e){return!1}},N=async(e,t)=>{const a=k[0];if(a&&v(t)){const o=new Promise(e=>setTimeout(()=>e(!1),1e5));await Promise.race([b,o])&&a.contentWindow.postMessage(e,t)}};async function U(n){let s={main_op:"send-analytics"};n.target.checked&&o.setItem("viewer-enabled-source","ownership-consent"),o.getWithTTL("ownership-upgrade")&&!n.target.checked&&(t.analytics(s,e.USE_ACROBAT_VIEWER_DISABLED_DEFAULT_OWNERSHIP,{SOURCE:"trefoilMenu"}),t.analytics(s,e.USE_ACROBAT_VIEWER_DISABLED_DEFAULT_OWNERSHIP_EXPERIMENT,{SOURCE:"trefoilMenu",EXPERIMENT:o.getItem("experiment-ownership")}),o.removeItem("ownership-upgrade"),o.removeItem("defaultOwnerShipExperiment")),o.setItem("pdfViewer",`${n.target.checked}`),E.hasFlag("dc-cv-new-preferences",h.NO_CALL).then(e=>{e||(R({main_op:"changeDefaultViewershipForSurface",surfaceId:"gmail",isDefault:n.target.checked,source:"extensionPopup"}),R({main_op:"changeDefaultViewershipForSurface",surfaceId:"gdrive",isDefault:n.target.checked,source:"extensionPopup"}))});const i=n.target.checked?"enabled":"disabled";await a.setViewerState(i);try{o.removeItem("netAccAdT"),o.removeItem("netAcc"),o.removeItem("netAccCN")}catch(e){}n.target.checked?t.isEdge()?t.analytics(s,e.USE_ACROBAT_IN_EDGE_ENABLED):t.isChrome()&&t.analytics(s,e.USE_ACROBAT_IN_CHROME_ENABLED):t.isEdge()?t.analytics(s,e.USE_ACROBAT_IN_EDGE_DISABLED):t.isChrome()&&t.analytics(s,e.USE_ACROBAT_IN_CHROME_DISABLED),setTimeout(()=>{L?R({panel_op:"viewer_menu",reload_in_native:!0,tabId:S[0].id}):y&&chrome.tabs.reload(),R(s),R({panel_op:"options_page",requestType:m.OPTIONS_UPDATE_TOGGLE,toggleId:u.ViewerOwnershipTitle,toggleVal:n.target.checked}),t.isEdge()&&R({main_op:"pdfViewerChanged",value:`${n.target.checked}`})},20)}function x(){P(e.TREFOIL_SETTINGS_ICON_CLICKED),o.setItem("optionsPageSource",d.EXTENSION_WIDGET_SETTINGS).then(()=>{chrome.runtime.openOptionsPage(()=>{chrome.runtime.lastError&&P(e.TREFOIL_SETTINGS_FAILED_TO_OPEN)})})}function B(){P(e.TREFOIL_ACROBAT_LABEL_CLICKED),R({main_op:"go_to_aonline",verb:"acrobat_label"})}window.addEventListener("message",async t=>{if(!v(t.origin))return;const a={...t.data};switch(a.main_op){case"cdnReady":C(!0);break;case"go_to_aonline":R({...a,locale:I||o.getItem("locale")});break;case"convertToPDFPopupMenu":case"appendToExistingPDFPopupMenu":case"cancelWebpageConversion":case"clearStatus":case"open_converted_file":case"get-frictionless-url":case"timing_info":R(a);break;case"relay_to_content":a.main_op="external_msg",a.data=t.data,a.timeStamp=Date.now(),R(a);break;case"branding-clicked":B();break;case"settings-clicked":x();break;case"viewership-toggle":{const{checked:e}=a;U({target:{checked:e}});break}case"open-ai-assistant":!async function(){const e=await chrome.extension.isAllowedFileSchemeAccess();if(r(S?.[0]?.url)&&!e)return o.setItem("localFileFteData",{tabId:S[0].id,url:S[0].url}),void T("askAIAssistant",p.LOCAL_FILE_COACHMARK);window.close(),R(L?{main_op:"openViewerAIAssistant"}:{type:"open_side_panel",touchpoint:"TrefoilMenu"})}();break;case"add-webpage-to-project":window.close(),R(a);break;case"toggle-ai-assistant":o.setItem("enableGenAIFab",`${a.value}`);break;case"saveVisitorID":if(t.data.visitorID){const e=o.getItem("viewerVisitorID");o.setItem("viewerVisitorID",t.data.visitorID),e&&e!==t.data.visitorID&&P("DCBrowserExt:Analytics:viewerVisitorID:MCMID:Changed")}break;case"openLocalFileThoughFilePicker":const n=document.createElement("input");n.type="file",n.accept=".pdf",n.style.display="none",document.body.appendChild(n),n.click(),n.onchange=async t=>{const a=t?.target?.files[0];if(!a)return void document.body.removeChild(n);const s=URL.createObjectURL(a),i=await a.arrayBuffer();o.getItem("cdnUrl")||R({main_op:"initializeViewerVariables"}),P(e.LOCAL_FILE_OPENED_FROM_FILE_PICKER,{SOURCE:"ExtensionMenu:SelectFile"}),f.storeFileByHash(i,`chrome-extension://${chrome.runtime.id}/${s}`).then(()=>{const e={main_op:"openLocalFileThoughFilePicker"};e.file_name=a.name,e.fileURL=s,e.openLocalFileSource="ExtensionMenu:SelectFile",R(e)}).finally(()=>{document.body.removeChild(n)})}}}),chrome.runtime.onMessage.addListener(e=>{switch(e.panel_op){case"status":{const{action:t}=e,a={type:0===t?"convertToPDFPopupMenu":"appendToExistingPDFPopupMenu",...e};N(a,w);break}case"load-frictionless":{const t=function(e,t){if(e.hide_spinner)return void k.removeClass("loader");const a=e.frictionless_uri;let n=new URL(a);if(t&&(t.locale=I||chrome.i18n.getMessage("@@ui_locale"),Object.keys(t).forEach(e=>{n.searchParams.append(e,t[e])})),"false"===o.getItem("logAnalytics")){let e=n.toString();e=e.concat("&app!analytics=disable");try{n=new URL(e)}catch(e){n=""}}return R({iframe_call_time:Date.now(),main_op:"timing_info"}),n}(e,{verb:e.pdf_action,workflow:e.frictionless_workflow,dropzone2:"true"});t&&N({type:"frictionless-url",url:t.href},w);break}}}),async function(){F();const a=performance.now();s(),P(e.EXT_MENU_ICON_CLICKED),$("#pdfOwnershipExploreAcrobat").text(t.getTranslation("pdfOwnershipExploreAcrobat")),$("#offlineModeTitle").text(t.getTranslation("popupNoConnection")),$("#offlineModeMessage").text(t.getTranslation("popupOfflineMessage"));const c="true"===o.getItem("pdfViewer");c||k.addClass("iframe-with-footer");const l=await R({main_op:"initialise-popup"}),{action:m,current_status:d,hostedURL:u,is_pdf:p,is_extension_url:g}=l;A=u,y=p,L=g,d&&(A=0===m?`${A}#/web-to-pdf`:`${A}#/add-webpage-to-pdf`);const f=new URL(A);w=f.origin;const _="false"!==o.getItem("logAnalytics"),h="false"!==o.getItem("ANALYTICS_OPT_IN_ADMIN");let E=o.getItem("viewer-locale");E||(E=o.getItem("locale")),f.searchParams.append("locale",I||E),f.searchParams.append("la",_&&h),f.searchParams.append("ao",o.getItem("aoem"));const C=o.getItem("installType")||"update",b=o.getItem("installSource");f.searchParams.append("version",`${chrome.runtime.getManifest().version}:${C}`),f.searchParams.append("installSource",b),f.searchParams.append("callingApp",chrome.runtime.id),o.getItem("enableExtMenuDarkMode")&&f.searchParams.append("theme",o.getItem("theme")||"auto");const O=await async function(){let e=!1;try{if(!o.getItem("sidePanelRegistered")||n())e=!1;else if(i(S[0].url))e=await R({main_op:"isGenAIEligibleInCDN",activeTabId:S[0].id});else if(r(S?.[0]?.url)){if(!await chrome.extension.isAllowedFileSchemeAccess()){const e=await R({main_op:"getFloodgateFlag",flag:"dc-cv-show-ask-ai-assistant-local-file",cachePurge:"NO_CALL"}),t="false"!==o.getItem("egaf"),a="true"===o.getItem("genAIEligible"),n="true"===(await chrome.storage.managed.get("DisableGenAI"))?.DisableGenAI;return!(!(e&&t&&a)||n)}e=!1}else e=await chrome.tabs.sendMessage(S[0].id,{main_op:"shouldShowGenAIForWebPagesTPs"})}catch(t){e=!1}return e}();f.searchParams.append("showAskAIAssistant",O),f.searchParams.append("genAIFabEnabled","true"===o.getItem("enableGenAIFab"));const T=await async function(){let e=!1;try{if(i(S[0].url))return!1;e=await chrome.tabs.sendMessage(S[0].id,{main_op:"shouldShowAddWebpageToProjectTouchpoint",tabURL:S[0].url})}catch(t){e=!1}return e}(),M=await async function(){try{return"true"===o.getItem("pdfViewer")&&await R({main_op:"getFloodgateFlag",flag:"dc-cv-show-select-file",cachePurge:"NO_CALL"})}catch(e){return!1}}();f.searchParams.append("showAWPP",T),f.searchParams.append("showSF",M),M&&k.addClass("show-select-file");try{if(!(await fetch(f,{method:"HEAD"})).ok)throw new Error;k.attr("src",f.href),k[0].onload=()=>{const e=(performance.now()-a)/1e3,t=Number.parseFloat(e).toFixed(2);N({...l,isViewerEnabled:c,timeToLoad:t,type:"init"},w)}}catch{!function(){P(e.EXT_MENU_CDN_OFFLINE),k.remove();const t="true"===o.getItem("pdfViewer");$("#toggle-input").prop("checked",t),t||$("#footer").removeClass("hidden"),$(".settings-icon").click(x),$("#toggle-input").click(U),$("#branding").click(B),$("#offline-mode").removeClass("hidden")}()}}();