/*************************************************************************
* 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{dcLocalStorage as t}from"../../common/local-storage.js";import{events as e}from"../../common/analytics.js";import{LOCAL_FILE_PERMISSION_URL as n,LOCAL_FTE_WINDOW as i,validFrictionlessLocales as o,APP_LOCALES_TO_BROWSER_LOCALES as r,PIN_TOOLBAR_URL as s,POPUP_CONTEXT as a}from"../../common/constant.js";import{dcTabStorage as l}from"./tab-storage.js";import{SETTINGS as c}from"../../sw_modules/settings.js";await t.init();export const util={getFrictionlessLocale:t=>o[t]||o.en,analytics:function(t,e,n){t.analytics||(t.analytics=[]),t.analytics.push([e,n])},messageToMain:function(t,e){chrome.runtime.sendMessage(t,e)},addMainListener:function(t){chrome.runtime.onMessage.addListener(t)},isChrome:function(){return!0},isEdge:function(){try{if("true"===t.getItem("IsRunningInEdge"))return!0}catch(t){}let e=window.navigator.userAgent.toLowerCase();return-1!==e.indexOf("chrome")&&-1!==e.indexOf("edg/")},isChromeOnlyMessage:function(t){return-1!==["web2pdfMissingMac","web2pdfFrictionlessUrl","web2pdfBadVersion","pdfOwnershipExploreAcrobat","pdfOwnershipPromptContent","LearnMoreURL"].indexOf(t)},consoleLog:function(...t){c.DEBUG_MODE&&console.log(...t)},consoleLogDir:function(...t){c.DEBUG_MODE&&console.dir(...t)},consoleError:function(...t){c.DEBUG_MODE&&console.error(...t)},getTranslation:function(t,e){if(t)return util&&util.isChromeOnlyMessage(t)&&util.isEdge()&&(t+="Edge"),e?chrome.i18n.getMessage(t,e):chrome.i18n.getMessage(t)},getTranslationByAppLocale:async function(e){if(!e)throw new Error("Key string is required");const n=t.getItem("appLocale")||util.getFrictionlessLocale(chrome.i18n.getMessage("@@ui_locale")),i=r[n]||r["en-US"];try{const t=chrome.runtime.getURL(i),n=await fetch(t);if(!n.ok)throw new Error(`Failed to fetch ${i}`);const o=await n.json();return o[e]?.message}catch(t){return console.error(`Error fetching translation for ${e} in ${n}:`,t),null}},translateElements:function(t){$(t).each(function(){"INPUT"===this.tagName?$(this).val(util.getTranslation(this.id)):$(this).text(util.getTranslation(this.id))})},translateElementsByAppLocale:function(t){$(t).each(function(){util.getTranslationByAppLocale(this.id).then(t=>{"INPUT"===this.tagName?$(this).val(t):$(this).text(t)})})},getSearchParamFromURL:function(t,e){const n=new URL(e);return new URLSearchParams(n.search).get(t)},isPDFForm:function(t){let e=/.+?\:\/\/.+?(\/.+?)(?:#|\?|$)/.exec(t),n="";if(null===e||e.length<2)return!1;if(n=e[1].endsWith("/")?e[1].slice(0,-1):e[1],void 0===n||0==n.length)return!1;n=n.toLowerCase();let i=n.split("/"),o=i[i.length-1];function r(t){return o.indexOf(t)>-1}return!["forms","guide","summary","process","sample","procedure","requirement","example","instr","format","formul","reform","forming","former","formed"].some(r)&&(!!(i.length>1&&(i.pop(),i.includes("form")||i.includes("forms")))||["form","application.pdf"].some(r))},logSharePointAnalytics:function(t,n){c.FILL_N_SIGN_ENABLED&&"FillnSign"===t.paramName?n?t.version===c.READER_VER?util.analytics(t,e.TREFOIL_FILLSIGN_READER_SHAREPOINT):util.analytics(t,e.TREFOIL_FILLSIGN_ACROBAT_SHAREPOINT):t.version===c.READER_VER?util.analytics(t,e.PERSIST_FILLSIGN_READER_SHAREPOINT):util.analytics(t,e.PERSIST_FILLSIGN_ACROBAT_SHAREPOINT):n?t.version===c.READER_VER?util.analytics(t,e.TREFOIL_PDF_READER_SHAREPOINT):util.analytics(t,e.TREFOIL_PDF_ACROBAT_SHAREPOINT):t.version===c.READER_VER?util.analytics(t,e.PERSIST_PDF_READER_SHAREPOINT):util.analytics(t,e.PERSIST_PDF_ACROBAT_SHAREPOINT)},logOpenInAcrobatAnalytics:function(t,n){let i=e.PERSIST_PDF_ACROBAT;i=c.FILL_N_SIGN_ENABLED&&"FillnSign"===t.paramName?n?t.version===c.READER_VER?e.TREFOIL_PDF_READER_FS:e.TREFOIL_PDF_ACROBAT_FS:t.version===c.READER_VER?e.PERSIST_PDF_READER_FS:e.PERSIST_PDF_ACROBAT_FS:n?t.version===c.READER_VER?e.TREFOIL_PDF_READER:e.TREFOIL_PDF_ACROBAT:t.version===c.READER_VER?e.PERSIST_PDF_READER:e.PERSIST_PDF_ACROBAT,util.analytics(t,i)},handleXHRRequest:function(t,e,n,i){let o=new XMLHttpRequest;o.onreadystatechange=function(){o.readyState===XMLHttpRequest.DONE&&(200===o.status?i(null,o):i(o.status,null))},o.ontimeout=function(t){i(t,null)},o.onerror=function(t){i(t,null)},o.open(t,e,!0),o.send(n)},handlePDFURL:async function(t,e=!0){if(!0===c.SHAREPOINT_ENABLED){if(t.isSharePointURL)return util.logSharePointAnalytics(t,e),t;{const n=await util.checkForSharePointURL(t.url);return t.isSharePointURL=n,n?util.logSharePointAnalytics(t,e):util.logOpenInAcrobatAnalytics(t,e),t}}return t.isSharePointURL=!1,util.logOpenInAcrobatAnalytics(t,e),t},checkForSharePointURL:function(t){return new Promise(e=>{util.handleXHRRequest("OPTIONS",t,null,(n,i)=>{if(!n&&i){let n=i.getResponseHeader("MicrosoftSharepointTeamServices"),o=i.getResponseHeader("MS-Author-Via");if(n&&o&&o.includes("MS-FP/4.0")){const n=new URL(t),i=n.protocol+"//"+n.hostname+":"+n.port+"/_vti_inf.html";return void util.handleXHRRequest("GET",i,null,(t,n)=>{if(!t&&n){let t=n.response;if(t.includes("FPAuthorScriptUrl")&&t.includes("FPAdminScriptUrl"))return void e(!0)}e(!1)})}}e(!1)})})},uuid:function(){try{let t=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){let n=(t+16*Math.random())%16|0;return t=Math.floor(t/16),("x"===e?n:3&n|8).toString(16)})}catch(t){return Math.random()}},sendAnalytics:t=>chrome.runtime.sendMessage({main_op:"analytics",analytics:[t]}),getAppCode:()=>util.isEdge()?"adobe.com_acrobatextension_edge_login":"adobe.com_acrobatextension_chrome_login",generateStateCSRF:()=>{const t=util.uuid(),e={csrf:t};return l.setItem("csrf",t),e},constructUrlWithParams(t,e={}){const n=t.split("#"),i=n[0],o=n[1],r=new URL(i);return Object.entries(e).forEach(([t,e])=>{r.searchParams.set(t,e)}),o?`${r.toString()}#${o}`:r.toString()},openExtensionSettingsInWindow:({tab:e,action:o},r)=>{let l="",c="popup";"pinToolbar"===o?l=s:(c="normal",l=util.constructUrlWithParams(n,{context:a.LOCAL_FILE_COACHMARK,autoDismiss:!0})),chrome.windows.get(e.windowId,function(e){const{height:n}=i,s=Math.round(1.2*i.width),a=Math.round(.5*(e.height-n)+e.top),u=Math.round(.5*(e.width-s)+e.left);chrome.windows.create({height:n,width:s,left:u,top:a,focused:!0,type:c,url:l},e=>{"pinToolbar"===o?t.setItem("pinToolbarSettingsWindowId",e.id):(t.setItem("settingsWindow",{id:e?.tabs[0]?.id}),chrome.action.openPopup().catch(t=>console.error(t))),r&&r(e)})})}};