/*************************************************************************
* 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}from"../common/analytics.js";import{common as t}from"./common.js";import{communicate as s}from"./communicate.js";import{util as o}from"./util.js";import{Proxy as i}from"./proxy.js";import{SETTINGS as n}from"./settings.js";import{dcLocalStorage as r,dcSessionStorage as a}from"../common/local-storage.js";var h,c,l=null,g=!1,m=2,T=13,d=[0,1,m,T,14],u=[m=2,11,12,T=13];let p=null;const E={"data:image/png":0,"data:image/jpeg":2,"data:image/jpg":1,"data:image/webp":3,"data:image/svg+xml":4,"data:text/css":5},_={".png":0,".jpeg":2,".jpg":1,".webp":3,".svg":4,".css":5};function S(){return s.getModule("acro-gstate")}l||(l=new function(){var r=[],a=[],l=[];function f(e){var t;for(t=0;t<r.length;t+=1)if(r[t].tabId===e)return r[t];return null}function A(e){return(e=e||chrome.i18n.getMessage("web2pdfUntitledFileName")).replace(/[<>?:|\*"\/\\'&\.]/g,"")}this.proxy=i.proxy.bind(this),this.LOG=(...e)=>t.LOG(...e),this.UNSET=0,this.OPEN_IN_ACROBAT=1,this.APPEND=2,this.CONVERT_PAGE=4,this.CONVERT_LINK=8,this.CONVERT_SELECTION=16,this.PRINT=32,this.EMAIL=64,this.CALLER_TOOLBAR=128,this.CLEAN_FILE_ON_FAILURE=256,this.STATUS_WAITING=1e4,this.STATUS_DOWNLOADING=10001,this.STATUS_CONVERTING=10002,this.STATUS_SUCCESS=10003,this.STATUS_ERROR=10004,this.STATUS_NOINSTANCE=10005,this.STATUS_FILELOCKED=10006,this.STATUS_NOACROBAT=10007,this.STATUS_CANCELLED=10008,this.STATUS_FILE_OPENED=10100,this.STATUS_FILE_OPEN_FAILED=10101,this.STATUS_ERROR_JS=10110,this.STATUS_ERROR_HOST=10111,this.STATUS_ERROR_TRY=11e3,this.STATUS_ERROR_DOM=11001,this.imagePromise=null,this.adobeYoloJumpInProgress=!1,this.adobeYoloUserInfoInProgress=!1,this.errorHandler=function(){try{if(0===r.length)return;this.Done(r[0].tabId,this.STATUS_ERROR_JS,null,o.getTranslation("web2pdfHTMLJSError"))}catch(e){}},i.handlers(this.errorHandler.bind(this)),this.Done=function(e,t,s,o){if(-1===e){if(0===r.length)return;e=r[0].tabId}this.setStatus(e,t,s,o),this.nextConversion(e)},this.nextConversion=function(e){var t;for(t=0;t<r.length;t+=1)r[t].tabId===e&&r.splice(t,1);r.length>0&&r[0].start.resolve(r[0]),this.exitShim()},this.cancelConversion=function(e){var t;for(t=0;t<r.length;t+=1)r[t].tabId===e&&(r[t].start&&r[t].start.reject(),r.splice(t,1))},this.addConversion=function(e,t){return e.start=o.Deferred(),r.push(e),1===r.length?e.start.resolve(e):t&&t(),e.start},this.setStatus=function(t,i,r,a){var h,c=f(t)||this.openPDFRequest,l=new Date;o.consoleLog("setStatus: "+t+" status: "+i),c?(c.timing||(c.timing=[]),i===this.STATUS_WAITING?(h="waiting",e.event(e.e.TREFOIL_HTML_CONVERT_WAITING),c.timing.push({stage:"WAIT",start_time:l.getTime()})):i===this.STATUS_DOWNLOADING?(e.event(e.e.TREFOIL_HTML_CONVERT_DOWNLOADING),h="downloading",this.logTiming(c.timing,"WAIT")):i===this.STATUS_CONVERTING?(e.event(e.e.TREFOIL_HTML_CONVERT_IN_PROGRESS),h="in_progress",this.logTiming(c.timing,"USER_PROMPT"),c.timing.push({stage:"CONVERT",start_time:l.getTime()})):i===this.STATUS_SUCCESS?(e.event(e.e.TREFOIL_HTML_CONVERT_COMPLETE),h="complete",this.logTiming(c.timing,"CONVERT")):i===this.STATUS_ERROR?(e.event(e.e.TREFOIL_HTML_CONVERT_FAILED),h="failure"):i===this.STATUS_ERROR_JS?(e.event(e.e.TREFOIL_HTML_CONVERT_FAILED_JS),h="failure"):i===this.STATUS_ERROR_TRY?(e.event(e.e.TREFOIL_HTML_CONVERT_FAILED_TRY),h="failure"):i===this.STATUS_ERROR_DOM?(e.event(e.e.TREFOIL_HTML_CONVERT_FAILED_DOM),h="failure"):i===this.STATUS_ERROR_HOST?(e.event(e.e.TREFOIL_HTML_CONVERT_FAILED_HOST),h="failure"):i===this.STATUS_CANCELLED?(e.event(e.e.TREFOIL_HTML_CONVERT_CANCELLED),h="cancelled",this.logTiming(c.timing,"USER_PROMPT")):i===this.STATUS_NOACROBAT?(e.event(e.e.TREFOIL_HTML_CONVERT_NO_ACROBAT),h="noacrobat"):i===this.STATUS_FILELOCKED?h="filelocked":i===this.STATUS_FILE_OPENED?("pdfviewer"!==c.click_context&&(c.version===n.READER_VER?c.newUI?e.event(e.e.PERSIST_PDF_DOWNLOAD_OPENED_READER):e.event(e.e.TREFOIL_PDF_DOWNLOAD_OPENED_READER):c.newUI?e.event(e.e.PERSIST_PDF_DOWNLOAD_OPENED):e.event(e.e.TREFOIL_PDF_DOWNLOAD_OPENED)),h="pdf_opened"):i===this.STATUS_FILE_OPEN_FAILED?("pdfviewer"!==c.click_context&&(c.version===n.READER_VER?e.event(e.e.TREFOIL_PDF_DOWNLOAD_OPEN_FAILED_READER):e.event(e.e.TREFOIL_PDF_DOWNLOAD_OPEN_FAILED)),h="pdf_open_failed"):(o.consoleLog("Unexpected status: "+i),h="unknown"),c.panel_op="status",c.current_status=h,r&&(c.file_path=r),a&&(c.message=a),"pdfviewer"!==c.click_context&&s.sendMessageToPopup(c)):o.consoleLog("failed to find conversion for tabId: "+t)},this.setNcPort=function(e){this.ncPort=e},this.nativeMessageCallback=function(e){var t,s;"setStateCallback"===e.messageType?this.setStatus(+e.conversionID,+e.state):"doneCallback"===e.messageType?(e.filePath&&(t=o.atob16(e.filePath)),this.Done(+e.conversionID,+e.state,t)):"userInfoCallback"===e.messageType?(this.exitShim(),this.adobeYoloUserInfoInProgress&&(clearTimeout(c),l.forEach(t=>{t(e)}),l=[],this.adobeYoloUserInfoInProgress=!1)):"jumpUrlCallback"===e.messageType||"jumpUrlCallback"===e.message?(this.exitShim(),this.adobeYoloJumpInProgress&&(clearTimeout(h),a.forEach(t=>{t(e)}),a=[],this.adobeYoloJumpInProgress=!1)):"getMessageCallback"===e.messageType?this.sendMessageToNative({message:(s=e.msgIDStr,o&&o.isChromeOnlyMessage(s)&&o.isEdge()&&(s+="Edge"),chrome.i18n.getMessage(s)||chrome.i18n.getMessage("web2pdfStatusError"))}):"saveSuccessCallback"===e.messageType?(t=o.atob16(e.path),this.imagePromise.resolve(t)):"saveFailureCallback"===e.messageType?(o.consoleLogDir("failed to save image"),this.imagePromise.reject()):"shimVersionInfo"===e.messageType?this.versionCallback&&(this.versionCallback(e),delete this.versionCallback):"fileOpenCallback"===e.messageType&&(0===+e.state?this.setStatus(0,this.STATUS_FILE_OPENED):this.setStatus(0,this.STATUS_FILE_OPEN_FAILED),this.openPDFRequest&&(this.nextConversion(this.openPDFRequest.tabId),delete this.openPDFRequest))},this.nativeOnDisconnect=function(){var e=this.STATUS_ERROR;"Specified native messaging host not found."===chrome.runtime.lastError.message&&(this.versionCallback&&(this.versionCallback({messageType:"shimVersionInfo",majorVersion:"0",minorVersion:"0"}),delete this.versionCallback),e=this.STATUS_NOACROBAT),"Native host has exited"===chrome.runtime.lastError.message&&(e=this.STATUS_ERROR_HOST),this.ncPort=null,this.Done(-1,e)},this.init=function(){this.ncPort=chrome.runtime.connectNative("com.adobe.acrobat.chrome_webcapture"),this.ncPort.onMessage.addListener(this.proxy(this.nativeMessageCallback)),this.ncPort.onDisconnect.addListener(this.proxy(this.nativeOnDisconnect))},this.getConversationDir=function(){if(!p){const e=`${Date.now().toString(36)}${Math.random().toString(36).substring(2,5)}`;p=`EXTN${e}`,console.log("Conversation Dir set to",p)}return p},this.sendMessageToNative=function(e){s.legacyShim()&&e.task&&-1===d.indexOf(e.task)?o.consoleLog("Skipping task: "+e.task+" in legacy shim"):(this.ncPort||this.init(),e.browser=o.getBrowser(),this.ncPort.postMessage(e),-1!==u.indexOf(e.task)&&setTimeout(this.proxy(function(){this.exitShim()}),1e3))},this.exitShim=function(){0===r.length&&this.sendMessageToNative({task:14})},this.getVersion=function(e){this.versionCallback=e,this.sendMessageToNative({task:T})},this.openInAcrobat=function(t){t.newUI&&s.resetPersistPrefCount(),this.addConversion(t).then(this.proxy(function(t){this.openPDFRequest=t;const s=o.removeQueryParams(t.url);!0===t.isSharePointURL?this.sendMessageToNative({task:16,url:s}):(this.sendMessageToNative({task:12,pdfData:t.base64PDF.split(",")[1],fileName:t.filename,paramName:t.paramName}),e.checkAndLogPDFSize(t.base64PDF.length/1048576),delete t.base64PDF)}))},this.getUserInfoFromAcrobat=function(e){l.push(e),this.adobeYoloUserInfoInProgress||(this.sendMessageToNative({task:100}),this.adobeYoloUserInfoInProgress=!0,c=setTimeout(()=>{this.exitShim();var e={};l.forEach(t=>{t(e)}),l=[],this.adobeYoloUserInfoInProgress=!1},1e4))},this.launchJumpUrl=function(e,t){a.push(t),this.adobeYoloJumpInProgress||(this.sendMessageToNative({task:101,userGuid:e,extensionId:chrome.runtime.id}),this.adobeYoloJumpInProgress=!0,h=setTimeout(()=>{this.exitShim();var e={success:"false",errorCode:"4"};a.forEach(t=>{t(e)}),a=[],this.adobeYoloJumpInProgress=!1},14e3))},this.fetchResource=function(e,t,s){try{const o=new URL(e.url,t.tab.url);if(!["http:","https:"].includes(o.protocol))return s({success:!1,error:"Unsupported protocol"}),!0;const i=o.href;fetch(i).then(t=>{if(!t.ok||!t.headers)throw new Error(`HTTP error ${t.status}`);const s=t.headers.get("content-type");if(s.startsWith("image/")&&e.isBlob)return t.blob().then(e=>new Promise((t,s)=>{const o=new FileReader;o.onloadend=()=>t(o.result),o.onerror=s,o.readAsDataURL(e)}));if(s.startsWith("text/css"))return t.text();throw new Error("Unsupported resource type")}).then(e=>{s({success:!0,data:e})}).catch(e=>{console.error("Error fetching resource:",e),s({success:!1,error:e.message})})}catch(e){console.error("Error fetching resource:",e),s({success:!1,error:e.message})}return!0},this.openFile=function(e){0===r.length&&this.sendMessageToNative({task:11,filePath:e.file_path})},this.SendForConversion=function(e,t){try{var o,i=new Date;o=0!==(e.conversionSettings&this.APPEND)?1:0,t.timing||(t.timing=[]),t.timing.push({stage:"USER_PROMPT",start_time:i.getTime()}),t.outputPath?0===t.action?this.sendMessageToNative({task:3,conversionID:t.tabId,domData:e.domData,conversionSettings:e.conversionSettings,charset:e.charset,url:e.url,docTitle:e.domtitle,outputPath:t.outputPath}):1===t.action&&this.sendMessageToNative({task:4,conversionID:t.tabId,domData:e.domData,conversionSettings:e.conversionSettings,charset:e.charset,url:e.url,docTitle:e.domtitle,outputPath:t.outputPath}):this.sendMessageToNative({task:o,conversionID:t.tabId,domData:e.domData,conversionSettings:e.conversionSettings,charset:e.charset,url:e.url,docTitle:e.domtitle}),s.sendMessageToPopup({...t,current_status:"file-picker"})}catch(e){this.Done(t.tabId,this.STATUS_ERROR_TRY)}},this.showConversionSettingsDialog=function(){0===r.length&&this.sendMessageToNative({task:m})},this.convertToPDF=function(e,t){e.conversionSettings=this.UNSET,S().getViewResultsPreferenceState()&&(e.conversionSettings|=this.OPEN_IN_ACROBAT),e.action===S().web2pdfAction.APPEND?e.conversionSettings|=this.APPEND:e.conversionSettings|=this.CLEAN_FILE_ON_FAILURE,e.context===S().web2pdfContext.PAGE&&(e.conversionSettings|=this.CONVERT_PAGE),e.caller===S().web2pdfCaller.TOOLBAR?e.conversionSettings|=this.CALLER_TOOLBAR:e.context===S().web2pdfContext.LINK&&(e.conversionSettings|=this.CONVERT_LINK),this.SendForConversion(e,t)},this.processImages=function(e,t,s){n.ENHANCED_WEBCAPTURE_ENABLED?this.processImagesEnhanced(e,t,s):this.processImagesNormal(e,t,s)},this.processImagesNormal=function(e,t,s){var i=e.blob.refs[t],n=new Date;return e.timing||(e.timing=[]),e.imagesComplete||(e.imagesComplete=o.Deferred()),this.imagePromise=o.Deferred(),t>=e.blob.refs.length?(this.imagePromise.resolve(),e.imagesComplete.resolve(),this.imagePromise):(i.data&&"data:"!==i.data?"image"===i.type?(g||(e.timing.push({stage:"SEND_IMAGES",start_time:n.getTime()}),g=!0),e.blob.refs.splice(t,1),this.sendMessageToNative({task:10,imagedata:i.data.split(",")[1],conversionID:e.tabId}),this.imagePromise.then(this.proxy(function(e){s.push("<AcroexchangeDownloadSeprator AcroexchangeDownloadUrl="+i.placeholder+"><FILEPATH>"+e+"</FILEPATH></AcroexchangeDownloadSeprator>")}),function(){})):(this.imagePromise.resolve(),t+=1):(e.blob.refs.splice(t,1),this.imagePromise.resolve()),this.imagePromise.done(this.proxy(function(){this.processImages(e,t,s)})),this.imagePromise)},this.processImagesEnhanced=function(e,t,s){var i=e.blob.refs[t],n=new Date;if(e.timing||(e.timing=[]),e.imagesComplete||(e.imagesComplete=o.Deferred()),this.imagePromise=o.Deferred(),t>=e.blob.refs.length)return this.imagePromise.resolve(),e.imagesComplete.resolve(),this.imagePromise;const r=(e,t=null)=>{if("string"==typeof e)for(const[t,s]of Object.entries(E))if(e.startsWith(t))return s;if("string"==typeof t)for(const e in _)if(t.toLowerCase().endsWith(e))return _[e];return 6};return i.data?i.data&&"data:"!==i.data?"image"===i.type||"svg_image"===i.type?(()=>{g||(e.timing.push({stage:"SEND_IMAGES",start_time:n.getTime()}),g=!0),e.blob.refs.splice(t,1),this.sendMessageToNative({task:10,imagedata:i.data.split(",")[1],mimetype:r(i.data.split(",")[0],i.placeholder),conversationDir:this.getConversationDir(),conversionID:e.tabId}),this.imagePromise.then(this.proxy(function(e){s.push("<AcroexchangeDownloadSeprator AcroexchangeDownloadUrl="+i.placeholder+"><FILEPATH>"+e+"</FILEPATH></AcroexchangeDownloadSeprator>")}),function(){})})():"css"===i.type?(()=>{g||(e.timing.push({stage:"SEND_CSS",start_time:n.getTime()}),g=!0),e.blob.refs.splice(t,1),this.sendMessageToNative({task:10,imagedata:i.data,mimetype:5,conversationDir:this.getConversationDir(),conversionID:e.tabId}),this.imagePromise.then(this.proxy(function(e){s.push("<AcroexchangeDownloadSeprator AcroexchangeDownloadUrl="+i.placeholder+"><FILEPATH>"+e+"</FILEPATH></AcroexchangeDownloadSeprator>")}),function(){})})():(this.imagePromise.resolve(),t+=1):(e.blob.refs.splice(t,1),this.imagePromise.resolve()):(t+=1,this.imagePromise.resolve()),this.imagePromise.done(this.proxy(function(){this.processImages(e,t,s)})),this.imagePromise},this.acro_html=function(t,s){var i,r,a;if(t.error)o.consoleError(t.error),e.logError(t.error_analytics),this.Done(t.tabId,this.STATUS_ERROR_DOM,null,o.getTranslation(t.error));else{if(e.checkAndLogHTMLBlobSize(t.blob.currentSize/1048576),p=null,e.logContents(t),t.analytics&&e.setParamsAndLogAnalytics(t.analytics,e.e.HTML_SOURCE_CONTENT,"content"),e.setArg("stage","CLONE"),e.checkAndLogTimingRange(t.cloneTiming),(a=f(t.tabId)).blob=t.blob,r=[],g=!1,n.ENHANCED_WEBCAPTURE_ENABLED){var h=this.getConversationDir();r.push("<AcroExchangeConversationDir>"+h+"</AcroExchangeConversationDir>")}this.processImages(a,0,r),a.imagesComplete.then(this.proxy(function(){for(delete a.imagesComplete,this.logTiming(a.timing,"SEND_IMAGES"),r.push("<AcroexchangeDownloadSeprator AcroexchangeDownloadUrl="+s.tab.url+">"+a.blob.html+"</AcroexchangeDownloadSeprator>"),i=0;i<a.blob.refs.length;i+=1)a.blob.refs[i].data&&r.push("<AcroexchangeDownloadSeprator AcroexchangeDownloadUrl="+a.blob.refs[i].placeholder+">"+a.blob.refs[i].data+"</AcroexchangeDownloadSeprator>");delete a.blob,this.convertToPDF({caller:a.caller,action:a.action,context:S().web2pdfContext.PAGE,domData:r.join("\n"),charset:"UTF-8",domtitle:a.domtitle,url:a.url},a)}))}},this.logTiming=function(t,s){var o,i=new Date;t.forEach(function(t){t.stage===s&&(o=i.getTime()-t.start_time,e.setArg("stage",s),e.checkAndLogTimingRange(o/100))})},this.handleConversionRequest=function(t){if(n.IS_ACROBAT){var o=this.proxy(function(){this.setStatus(t.tabId,this.STATUS_WAITING)});s.legacyShim()||t.context!==S().web2pdfContext.PAGE?(s.legacyShim()||t.context===S().web2pdfContext.LINK)&&this.addConversion(t,o).then(this.proxy(function(e){this.convertToPDF({caller:e.caller,action:e.action,context:e.context,domData:"",charset:"UTF-8",domtitle:e.domtitle,url:e.url},e)})):this.addConversion(t,o).then(this.proxy(function(t){delete t.start,this.setStatus(t.tabId,this.STATUS_DOWNLOADING),e.logSiteAndProtocolAnalytics(t.url),chrome.scripting.executeScript({target:{tabId:t.tabId},injectImmediately:!0,func:(e,t,s)=>{window.maxSize=t,window.DEBUG=s,window.TABID=e,window.OP="acro-html",window.EXCLUDE=["font","svg_image"],window.EXCLUDE_ENHANCED=["font"]},args:[t.tabId,n.MAX_HTML_SIZE,n.DEBUG_MODE]},this.proxy(function(){if(chrome.runtime.lastError)throw new Error(chrome.runtime.lastError.message);chrome.scripting.executeScript({target:{tabId:t.tabId},files:n.ENHANCED_WEBCAPTURE_ENABLED?["content_scripts/get-html-enhanced.js"]:["content_scripts/get-html.js"]})}))}))}},this.convertToPDFPopupMenu=function(e,t){var s={tabId:t.tab.id,caller:S().web2pdfCaller.TOOLBAR,action:S().web2pdfAction.CONVERT,context:S().web2pdfContext.PAGE,url:t.tab.url,domtitle:A(t.tab.title)};e.outputPath&&(s.outputPath=e.outputPath),this.handleConversionRequest(s)},this.appendToExistingPDFPopupMenu=function(e,t){var s={tabId:t.tab.id,caller:S().web2pdfCaller.TOOLBAR,action:S().web2pdfAction.APPEND,context:S().web2pdfContext.PAGE,url:t.tab.url,domtitle:A(t.tab.title)};e.outputPath&&(s.outputPath=e.outputPath),this.handleConversionRequest(s)}},s.registerModule("acro-web2pdf",l),n.IS_ACROBAT&&s.registerHandlers({"acro-html":l.proxy(l.acro_html),appendToExistingPDFPopupMenu:l.proxy(l.appendToExistingPDFPopupMenu),convertToPDFPopupMenu:l.proxy(l.convertToPDFPopupMenu),showConversionSettingsDialog:l.proxy(l.showConversionSettingsDialog),fetch_resource:l.proxy(l.fetchResource)}));export const acroweb2pdf=l;