/*************************************************************************
* 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{common as e}from"../sw_modules/common.js";import{util as t}from"../sw_modules/util.js";import{dcLocalStorage as o,dcSessionStorage as n}from"./local-storage.js";import{ADOBE_URL as r,demoFileURL as a,ONBOARDING_DEMO as i}from"./constant.js";import{getActiveExperimentAnalyticsArray as s}from"./experimentUtils.js";import{COI_HEADERS as c}from"../sw_modules/constant.js";import{analytics as m,events as p}from"./analytics.js";import{loggingApi as l}from"./loggingApi.js";import{floodgate as u}from"../sw_modules/floodgate.js";export function isNewUser(){if(!o.getItem("extUserState")){const e=o.getItem("viewerStorage");if(e){return+(0===(parseInt(e.usage)||0))}return-1}return 0}export async function updateExtUserState(){if(!o.getItem("extUserState")){o.setItem("extUserState","ru");const e=await chrome.tabs.query({active:!0,lastFocusedWindow:!0});chrome.runtime.sendMessage({main_op:"reRegisterUninstallUrl",tab:e[0]})}}const d="machine";export function setCookie(e,t,o={}){const n={name:e,value:t,secure:!0,sameSite:"no_restriction"};o.url&&(n.url=o.url),o.path&&(n.path=o.path),o.expiryDate&&(n.expirationDate=o.expiryDate),o.sameSite&&(n.sameSite=o.sameSite),o.secure&&(n.secure=o.secure),o.domain&&(n.domain=o.domain),chrome.cookies.set(n)}async function g(e,t=void 0){const o=new Date,n=o.getMonth(),a=o.getFullYear();let i="mmac";e===d&&(i+="_machine"),t&&(i+=`_${t}`);let s=null;try{s=await chrome.cookies.get({url:r,name:i});const e=!s||function(e,t,o){const n=new Date(e),r=n.getMonth(),a=n.getFullYear();return o>a||o===a&&t>r}(s.value,n,a);return!e}catch(e){return!1}}function h(t){const o=e.getAcroIpmURL(),n=new URL(o);return t.pingType===d&&(n.pathname+="/machine"),t.appPath?n.pathname+=`/${encodeURIComponent(t.appPath)}`:n.pathname+="/overall",Object.keys(t.schema).forEach(e=>{const o=t.schema[e];n.pathname+=o?`/${encodeURIComponent(o)}`:"/unspecified"}),n.pathname+="/mmac.html",n.toString()}async function f(e,t,o=void 0){try{const n=await fetch(e);if(200===n?.status){let e="mmac";t===d&&(e+="_machine"),o&&(e+=`_${o}`);const n=new Date,a=Math.floor(Date.now()/1e3)+2678400;setCookie(e,n.toISOString(),{url:r,expiryDate:a,path:"/",domain:".adobe.com"})}}catch(e){console.error(e)}}async function w(e){if(async function(e){e&&!await g(d)&&f(h({...e,appPath:void 0,pingType:d}),d)}(e),function(e){return!!e&&!(!e.appPath||"string"!=typeof e.appPath||""===e.appPath.trim())}(e)&&!await g(d,e.appPath)){f(h({...e,pingType:d}),d,e.appPath)}}export function sendPingEventHandler(){let e="chrome-extension";t.isEdge()&&(e="edge-extension");const n=o.getItem("appLocale");let r=o.getItem("viewer-locale");r||(r=o.getItem("locale")),w({appPath:e,schema:{appIdentifier:"dc-acrobat-extension",appVersion:chrome.runtime.getManifest().version,appReferrer:o.getItem("installSource"),userType:"unknown",subscriptionType:"unknown",locale:n||r}})}export const isEdgeBrowser=()=>t.isEdge();export const isChromeViewerOpened=e=>{if(!e)return!1;const t=`chrome-extension://${chrome.runtime.id}`;return e.startsWith(`${t}/http`)||e.startsWith(`${t}/https`)||e.startsWith(`${t}/viewer.html`)||e.startsWith(`${t}/file`)};export const isDemoMode=(e,t)=>{if(!e||!t)return!1;const n=new URL(t),r=n.origin+n.pathname,s=o.getItem("od"),c="en"===(o.getItem("appLocale")||o.getItem("viewer-locale")||o.getItem("locale")).toLowerCase().split("-")[0],{name:m,source:p}=((e="")=>{try{if(!e)return{};const t=e.length%4;return JSON.parse(decodeURIComponent(atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(e.length+(0===t?0:4-t),"="))))}catch(e){log("decodeBlobUrl failed",e)}})(e);return!(m!==i||"cdn"!==p||r!==a||!s||!c)};export const getGenAIServiceVariant=()=>{const t=o.getItem("cluster");return t||(e.isAdobeInternalUser()?"beta":"release")};export const verCmp=(e,t)=>e.localeCompare(t,void 0,{numeric:!0,sensitivity:"base"});export const isMigrationCompleted=()=>"true"===o.getItem("migrationOfSyncToAsyncStorage");export const isMigrationCleanupCompleted=()=>"true"===o.getItem("migrationOfSyncToAsyncStorageCleanup");export const getSearchParams=e=>{try{return new URL(e).searchParams}catch{return new URLSearchParams}};export const sendCoiEnabledEvent=(e,t)=>{const o=n.getItem(c)||{},r=o[e]||{},a=r["cross-origin-embedder-policy"];a&&!r.eventSent&&(m.event(p.COEP_STATUS_EVENT,{...t,dvDisableSessionCount:a||"none"}),r.eventSent=!0,o[e]=r,n.setItem(c,o),l.info({message:p.COEP_STATUS_EVENT,...t,coepHeaderValue:a}))};export function removeCoiTab(e){const t=n.getItem(c)||{};t[e]&&(delete t[e],n.setItem(c,t))}export function trackCoiHeaders(e){if("main_frame"===e.type&&e.responseHeaders){const t=e.responseHeaders.filter?.(e=>"cross-origin-embedder-policy"===e.name.toLowerCase()),o=e.responseHeaders.filter?.(e=>"cross-origin-opener-policy"===e.name.toLowerCase()),r=n.getItem(c)||{},a={"cross-origin-embedder-policy":null,"cross-origin-opener-policy":null};if(1===t?.length){const e=t[0].value.toLowerCase().trim(),o=["require-corp","credentialless"].filter(t=>e.includes(t))[0];o&&(a["cross-origin-embedder-policy"]=o)}if(o?.length>0){const e=o[0].value.toLowerCase().trim(),t=["same-origin","same-origin-allow-popups","noopener-allow-popups"].filter(t=>e.includes(t))[0];t&&(a["cross-origin-opener-policy"]=t)}a["cross-origin-embedder-policy"]||a["cross-origin-opener-policy"]?(r[e.tabId]=a,n.setItem(c,r)):removeCoiTab(e.tabId)}}export function getLocalFilePromptDimensions(e){const t=Math.min(Math.round(.8*e.height),900),o=Math.min(Math.round(.9*e.width),1550);return{height:t,width:o,top:Math.round(.5*(e.height-t)+e.top),left:Math.round(.5*(e.width-o)+e.left)}}export const isLocalFileUrl=e=>e.startsWith("file:///")&&(e.endsWith(".pdf")||e.endsWith(".PDF"));export const fetchCombinationOfLocalFilePromptCooldownConfig=async()=>{let e;try{e=await u.getFeatureMeta("dc-cv-combination-of-local-file-prompt"),e=JSON.parse(e)}catch(t){e={promptLimit:6,ignoreCoolDown:30,settingsCoolDown:14,dismissCoolDown:30}}return e};export const fetchLocalFileAccessAndSummaryCoachmarkCooldownConfig=async()=>{let e;try{e=await u.getFeatureMeta("dc-cv-local-file-access-and-summary-coachmark"),e=JSON.parse(e)}catch(t){e={promptLimit:10,ignoreCoolDown:30,settingsCoolDown:14,dismissCoolDown:30}}return e};export const clearOptionPageSource=e=>{const t=n.getItem("optionTabIds")||[];t.includes(e)&&(t.splice(t.indexOf(e),1),n.setItem("optionTabIds",t),0===t.length&&o.removeItem("optionsPageSource"))};export const safeJsonParse=(e,t)=>{try{return JSON.parse(e)}catch(e){const o=(new Error)?.stack,n=o?o.split?.(/\n/)?.[2]?.trim?.():"unknown location";return l.error({message:`Error parsing JSON at ${n}`,error:e?.message}),t}};export async function checkForImsSidCookie(){const e=await chrome.cookies.get({url:"https://www.services.adobe.com/",name:"ims_sid"});let t=!1;if(e?.value){t=1e3*e.expirationDate>(new Date).getTime()}return t}