/*************************************************************************
* 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,events as t}from"../common/analytics.js";import{dcLocalStorage as r,dcSessionStorage as o}from"../common/local-storage.js";import{loggingApi as n}from"../common/loggingApi.js";import{EXPRESS as a,COI_HEADERS as s}from"./constant.js";import{floodgate as i}from"./floodgate.js";import{util as c}from"./util.js";import{common as m}from"./common.js";import{OFFSCREEN_DOCUMENT_PATH as E}from"../common/constant.js";import{sendCoiEnabledEvent as S,sendPingEventHandler as p}from"../common/util.js";const d={},l="cleanUpExpressAssetMemoryMap",u="cleanUpExpressIndexedDB",f={beta:["memepcobodlebmohdlfnjiaalggfcpic","hgednelcgbmkdebjhejlmbgigmkcbemg"],release:["efaidnbmnnnibpcajpcglclefindmkaj","elhekieabhbkpmcefcoobjddigjcaadp"]},g={[a.VERBS.EFFECTS_IMAGE]:"add-effects",[a.VERBS.CROP_IMAGE]:"crop-image",[a.VERBS.REMOVE_BACKGROUND_IMAGE]:"remove-background",[a.VERBS.INSERT_OBJECT]:"insert-object",[a.VERBS.REMOVE_OBJECT]:"remove-object"},I="Response not in 2xx range.";async function R(e,t=!1){const r=Date.now();let o,a=e;if(t=t&&c.isBrowserVersionGreaterThan116())try{a=await async function(e){const t=`${E}?env=${m.getEnv()}`;await c.setupOffscreenDocument(t);const r=await chrome.runtime.sendMessage({main_op:"fetchImageBlobURL",target:"offscreen",imgUrl:e});if(r.error)throw new Error(r.error);return r.blobUrl}(e)}catch(e){n.error({message:"Error fetching image blob url from offscreen",error:e.toString()})}try{if(o=await fetch(a),a!==e&&(s=a,chrome.runtime.sendMessage({main_op:"revokeImageBlobURL",target:"offscreen",blobUrl:s})),!o.ok){throw new Error(a!==e?"Blob fetch response not in 2xx range.":I,{cause:{status:o.status}})}}catch(t){if(a===e)throw t;n.error({message:"Error fetching image from offscreen blob url",error:t.toString()});try{o=await fetch(e)}catch(e){throw new Error(I,{cause:{status:o.status}})}}var s;const i=await o.blob();return new Promise((e,t)=>{const o=new FileReader;o.readAsDataURL(i),o.onloadend=()=>{const t=o.result,n=Date.now()-r;e({base64data:t,imageDownloadTime:n})},o.onerror=t})}function h(e){return g[e]??"edit-image"}function _(e){return(o.getItem(a.EXPRESS_SESSIONS)||{})[e]}async function A(e,t){const r=Date.now(),n=new URL(t.url).hostname,m=e.srcUrl,E=t.id,p=e.intent,d=e.touchpoint,l=await async function(){return await i.hasFlag("dc-cv-express-standalone")?a.VARIANT.LOE:a.VARIANT.MODAL}(),u=c.uuid(),f=o.getItem(a.EXPRESS_SESSIONS)||{};let g={};try{g=JSON.parse(i.getFeatureMeta("dc-cv-express-error-handling-optimization"))??{}}catch(e){}const I=(o.getItem(s)||{})[E]||{},R=I["cross-origin-embedder-policy"],h=I["cross-origin-opener-policy"],_=!!R;return S(E,{domain:n,expressTouchpoint:d}),f[u]={pageDomain:n,imageURL:m,tabId:E,intent:p,touchpoint:d,variant:l,clickTimeStamp:r,errorHandlingConfig:g,coiEnabled:_,coepHeaderValue:R,coopHeaderValue:h},o.setItem(a.EXPRESS_SESSIONS,f),u}async function b(e,t){"ContextMenu"!==e.touchpoint&&p();const r=await A(e,t);await O(r)}function x(e){const t=o.getItem(a.EXPRESS_SESSIONS)||{};return Object.keys(t).find(r=>{const n=t[r];return n.tabId===e&&!n.fetchedFromContentScript&&n.variant===a.VARIANT.MODAL&&(t[r].fetchedFromContentScript=!0,o.setItem(a.EXPRESS_SESSIONS,t),!0)})}async function O(s){const i=_(s);let E;const S=i?.pageDomain;try{if(E=i.intent,i.variant===a.VARIANT.LOE){const e=i.clickTimeStamp,t=e+864e5;expressIndexedDBScript.storeExpressAssetInfoInIndexedDB(s,i.imageURL,t,e),chrome.alarms.get(u,e=>{e||chrome.alarms.create(u,{periodInMinutes:720})}),d[s]={bufferPromise:R(i.imageURL),ttl:Date.now()+6e5,clickTimeStamp:e,domain:S},chrome.alarms.get(l,e=>{e||chrome.alarms.create(l,{periodInMinutes:10})});const o=new URL(m.getExpressURLs().webAppUrl);o.searchParams.append("expressSessionId",s),o.searchParams.append("referrer",a.REFERRER);const n=h(i.intent);o.searchParams.append("editAction",n),o.searchParams.append("extId",function(){const e=Object.keys(f).filter(e=>f[e].includes(chrome.runtime.id));return e.length>0?e[0]:"release"}());const E=c.getFrictionlessLocale(chrome.i18n.getMessage("@@ui_locale"));o.searchParams.append("locale",E),"true"===r.getItem("adobeInternal")&&o.searchParams.append("setting-consoleLogLevel-performance","info"),chrome.tabs.create({url:o.href,active:!0})}else!function(e,t,r){let n=o.getItem(a.SESSIONS_WHERE_MODAL_LOADING)||[];n.push({tabId:e,touchpoint:t,domain:r}),o.setItem(a.SESSIONS_WHERE_MODAL_LOADING,n)}(i.tabId,i?.touchpoint,S),await chrome.scripting.executeScript({target:{tabId:i.tabId},files:["content_scripts/express/express-content-script.js"]})}catch(r){w(i?.tabId,i?.touchpoint,S),e.event(t.EXPRESS_EXECUTE_VERB_FAILED,{VERB:E,eventContext:r.toString(),expressTouchpoint:i?.touchpoint,domain:S}),n.error({message:"Error executing express verb",error:"Initiate execute verb from service worker: "+r.toString()})}}async function T(o){if(!d[o])return async function(r){let o,s,i;const c=_(r),m=await expressIndexedDBScript.getExpressAssetInfoFromIndexedDB(r);if(!m)return n.error({message:"Error executing express verb",error:`Asset transfer to LOE failed: ${a.EXTERNAL_MESSAGING_ERROR_CODES.INVALID_REQUEST}`}),{status:a.RESPONSE_STATUS.FAILED,errorCode:a.EXTERNAL_MESSAGING_ERROR_CODES.INVALID_REQUEST};o=m.url,s=m.clickTimeStamp;try{i=(await R(o)).base64data}catch(r){return e.event(t.EXPRESS_EXECUTE_VERB_FAILED,{eventContext:r.toString(),domain:c?.pageDomain,expressTouchpoint:c?.touchpoint}),n.error({message:"Error executing express verb",error:`Asset transfer to LOE failed: ${r.toString()}`}),{status:a.RESPONSE_STATUS.FAILED,errorCode:a.EXTERNAL_MESSAGING_ERROR_CODES.IMAGE_FETCH_FAILED,clickTimeStamp:s}}return{status:a.RESPONSE_STATUS.SUCCESS,buffer:i,clickTimeStamp:s}}(o);{const s=_(o)?.touchpoint,i=d[o]?.domain,c=d[o].clickTimeStamp,m=Date.now()-c;try{const{base64data:e,imageDownloadTime:t}=await d[o].bufferPromise,s=Date.now()-c;"true"===r.getItem("adobeInternal")&&(console.log("Time required to receive request from express webapp "+m),console.log("Image Download Time "+t),console.log("Time required to handover to express "+s));const E={imageDownloadTime:t,timeRequiredToHandoverToExpress:s,expressCommunicationReceivedTime:m,imageSize:e.length};return n.info({message:a.PERF_METRIC_LOG_MESSAGE,...E}),{status:a.RESPONSE_STATUS.SUCCESS,buffer:e,clickTimeStamp:c,domain:i}}catch(r){e.event(t.EXPRESS_EXECUTE_VERB_FAILED,{eventContext:r.toString(),domain:i,expressTouchpoint:s}),n.error({message:"Error executing express verb",error:`Asset transfer to LOE failed: ${r.toString()}`});const o=a.EXTERNAL_MESSAGING_ERROR_CODES.IMAGE_FETCH_FAILED;return{status:a.RESPONSE_STATUS.FAILED,errorCode:o,clickTimeStamp:c,domain:i}}}}function D(e){chrome.scripting.executeScript({target:{tabId:e},func:()=>{!function(e){const t=document.querySelector(`#${e}`);t?.parentElement?.removeChild(t),document.body.style.overflow=overflowStyleBeforeExpressOpened,overflowStyleBeforeExpressOpened=void 0}("expressAcrobatExtension"),dialogToBeReopened&&(dialogToBeReopened.showModal(),dialogToBeReopened=void 0)}})}function L(r){const s=function(e){let t=[],r=o.getItem(a.SESSIONS_WHERE_MODAL_LOADING)||[];r=r.filter(r=>r.tabId!==e||(t.push(r),!1)),t.length>0&&o.setItem(a.SESSIONS_WHERE_MODAL_LOADING,r);return t}(r);s.forEach(r=>{const o="Tab closed before express modal opened";n.error({message:"Error executing express verb",error:o}),e.event(t.EXPRESS_TAB_CLOSED_BEFORE_EXPRESS_LOADED,{eventContext:o,expressTouchpoint:r.touchpoint,domain:r.domain})})}function w(e,t,r){let n=o.getItem(a.SESSIONS_WHERE_MODAL_LOADING)||[];const s=n.findIndex(o=>o.tabId===e&&o.touchpoint===t&&o.domain===r);s>-1&&(n.splice(s,1),o.setItem(a.SESSIONS_WHERE_MODAL_LOADING,n))}chrome.alarms.onAlarm.addListener(function(e){e&&e.name===l&&(Object.keys(d).forEach(e=>{d[e]?.ttl<Date.now()&&delete d[e]}),0===Object.keys(d).length&&chrome.alarms.clear(l))}),chrome.alarms.onAlarm.addListener(function(e){e&&e.name===u&&expressIndexedDBScript.removeExpressAssetInfoFromIndexedDB().then(()=>{expressIndexedDBScript.getExpressAssetCount().then(e=>{0===e&&chrome.alarms.clear(u)})})});export{O as executeExpressVerb,D as closeExpress,T as getExpressAssetResponse,R as imageUrlToBase64,h as verbNameToIntent,w as removeSessionFromUnloadedExpressSessions,L as expressModalTabCloseListener,x as getModalSessionId,_ as getExpressSession,b as launchExpress};