/*************************************************************************
* 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{sendAnalytics,sendAnalyticsOncePerMonth,getParsedJSON}from"../utils/util.js";import{shouldProcessForListView,shouldProcessForConvertToPDF,getMimeTypeFromAttachmentName,getUserId,updateDrivePDFUrl}from"./util.js";import{processForListView}from"./list-view-touch-point-service.js";import state from"./state.js";import{addTouchpointToNativeViewerViaListView}from"./gmail-verb-list-view.js";const PDF_MIME_TYPE="application/pdf";let NON_PDF_MIME_TYPES=[],FILE_EXTENSION_TO_MIME_TYPE_MAP={};const getAttachmentURL=e=>{let t=e.replace("&disp=safe","")+"&disp=inline";return getUserId()&&(t=t.replace("/mail/?",`/mail/u/${getUserId()}/?`)),t},sendAnalyticsIfNoFileExtension=e=>{-1===e.lastIndexOf(".")&&sendAnalyticsOncePerMonth("DCBrowserExt:Gmail:Attachment:No:FileExtension")},processAttachmentByMimeType=(e,t,s,a,r)=>{try{if(e===PDF_MIME_TYPE){const e=getAttachmentURL(s);return void a.push({name:t,url:e})}if(!s||!e||!t)return;if(!NON_PDF_MIME_TYPES.includes(e))return void sendAnalyticsIfImageMimeTye(e);r.has(e)||r.set(e,{});const n=r.get(e);n[t]||(n[t]=[]);const i=getAttachmentURL(s);n[t].push({url:i})}catch(e){}},acrobatMailDataHandler=e=>{let t;e?.detail?.url?.includes("/fd")?t=parseFDResponse(e?.detail?.responseData):e?.detail?.url?.includes("/i/s")?t=parseISResponse(e?.detail?.responseData):e?.detail?.url?.includes("/bv")?t=parseBVResponse(e?.detail?.responseData):e?.detail?.url?.includes("gmSetData")&&(t=parseGMSetData(e?.detail?.responseData,e?.detail?.key)),updateExistingThreadData(t,!0),shouldProcessForListView(state?.gmailConfig,state?.gmailImplicitDefaultViewershipConfig)&&processForListView(),shouldProcessForConvertToPDF(state?.gmailConvertToPdfConfig,state?.gmailConfig)&&addTouchpointToNativeViewerViaListView()},addMailDataEventListener=()=>{document.addEventListener("acrobat-mail-data",e=>{setTimeout(()=>{acrobatMailDataHandler(e)},0)},{signal:state?.eventControllerSignal})},injectResponseListenerScript=()=>{if(state?.gmailResponseListenerAdded)return;const e=document.createElement("script");e.setAttribute("id","acrobat-response-interceptor"),e.src=chrome.runtime.getURL("content_scripts/gmail/gmail-inject.js"),e.onload=function(){this.remove()},(document.head||document.documentElement).appendChild(e),state.gmailResponseListenerAdded=!0},updateExistingThreadData=(e,t)=>{e&&Object.keys(e).forEach(s=>{const a=e[s].messages,r={id:s,messages:{...state.getMessagesForThreadId(s)||{},...a}};t?state.setDataForThread(r):e[e]=r})},parseISAttachments=e=>{try{const t=new Map,s=[];if(Array.isArray(e))for(const a of e){const[e,r,,,,n]=a;processAttachmentByMimeType(e,r,n,s,t)}return{nonPDFAttachments:t,pdfAttachments:s}}catch(e){return{}}},processDriveAttachmentsByMimeType=(e,t,s,a,r)=>{const n=updateDrivePDFUrl(e);if(!n)return;const i={url:n,isDriveAsset:!0};if(r===PDF_MIME_TYPE)s.push({...i,name:t});else{a.has(r)||a.set(r,{});const e=a.get(r);e[t]||(e[t]=[]),e[t].push(i)}},parseISDriveAttachments=e=>{try{const t=new Map,s=[],a=e[12]?.[28];if(Array.isArray(a))for(let e of a)if(PDF_MIME_TYPE===e[4]&&e[1]?.toLowerCase().endsWith(".pdf"))processDriveAttachmentsByMimeType(e[3],e[1],s,t,e[4]);else{const a=getMimeTypeFromAttachmentName(e[1],FILE_EXTENSION_TO_MIME_TYPE_MAP);a?processDriveAttachmentsByMimeType(e[3],e[1],s,t,a):sendAnalyticsIfNoFileExtension(e[1])}return{nonPDFDriveAttachments:t,driveAttachments:s}}catch(e){return sendAnalytics([["DCBrowserExt:Gmail:ISDAParsingFailed"]]),{}}},sendAnalyticsIfMimeTypeNotSupported=e=>{},parseFDAttachments=e=>{try{const t=new Map,s=[];if(Array.isArray(e))for(const a of e){const e=a[0]?.[3]||"";e?.length>0&&processAttachmentByMimeType(e[3],e[2],e[1],s,t)}return{nonPDFAttachments:t,pdfAttachments:s}}catch(e){return sendAnalytics([["DCBrowserExt:Gmail:FDAParsingFailed"]]),{}}},parseISEmailAndUpdateThreadData=(e,t,s)=>{if(e?.length>0)try{for(let a of e){const e=a[0],r=a[6],{nonPDFAttachments:n,pdfAttachments:i}=parseISAttachments(a[11]),{nonPDFDriveAttachments:o,driveAttachments:c}=parseISDriveAttachments(a);if(i?.length>0||n?.size>0||c?.length>0||o?.size>0){const l=a[71]&&9===a[71][0];t[s]||(t[s]={messages:{}}),t[s].messages[e]={id:e,timestamp:r,deleted:l,attachments:i,nonPDFAttachments:n,driveAttachments:c,nonPDFDriveAttachments:o}}}}catch(e){}},parseGMSetData=(e,t)=>{try{const s=getParsedJSON(e);if(!Array.isArray(s))return null;const a="Cl6csf"===t?s[1]:s[0]?.[0];if(!a||!Array.isArray(a))return null;const r={};for(let e of a)if("Cl6csf"===t){const t=e[1]?.[3],s=e[1]?.[4];parseISEmailAndUpdateThreadData(s,r,t)}else{const t=e[1],s=e[4]?.[4];parseGMSetDataA6JDVEmails(s,r,t)}return r}catch(e){return sendAnalytics([["DCBrowserExt:Gmail:GMResponseParsingFailed"]]),null}},parseBVResponse=e=>{try{const t=getParsedJSON(e);if(!Array.isArray(t))return null;const s={},a=t[2];if(!a||!Array.isArray(a))return null;for(let e of a){const t=e[0][3],a=e[0]?.[4];parseISEmailAndUpdateThreadData(a,s,t)}return s}catch(e){return sendAnalytics([["DCBrowserExt:Gmail:BVResponseParsingFailed"]]),null}},parseISResponse=e=>{try{const t=getParsedJSON(e);if(!Array.isArray(t))return null;const s=t[1]?.[5];if(!s||!Array.isArray(s))return null;const a={};for(let e of s){const t=e[0]?.[0],s=e[0]?.[2]?.[6]?.[0]?.[4];parseISEmailAndUpdateThreadData(s,a,t)}return a}catch(e){return sendAnalytics([["DCBrowserExt:Gmail:ISResponseParsingFailed"]]),null}},domParser="undefined"!=typeof DOMParser&&new DOMParser,parseFDDriveAttachments=e=>{try{const t=[],s=new Map,a=e[1]?.[5]?.[1]?.[0]?.[2]?.[1];if(a&&a.includes("drive.google.com")){const e=domParser?.parseFromString(a,"text/html"),r=e?.querySelectorAll(".gmail_chip.gmail_drive_chip>a");if(r?.length>0)for(let e of r){const a=e.getAttribute("href"),r=e.querySelector("span")?.textContent;if(r?.toLowerCase().endsWith(".pdf"))processDriveAttachmentsByMimeType(a,r,t,s,PDF_MIME_TYPE);else{const e=getMimeTypeFromAttachmentName(r,FILE_EXTENSION_TO_MIME_TYPE_MAP);e?processDriveAttachmentsByMimeType(a,r,t,s,e):sendAnalyticsIfNoFileExtension(r)}}}return{driveAttachments:t,nonPDFDriveAttachments:s}}catch(e){return sendAnalytics([["DCBrowserExt:Gmail:FDDAParsingFailed"]]),{}}},parseA6JDVDriveAttachments=e=>{try{let t=new Map,s=[];const a=e[12]?.[28];if(Array.isArray(a))for(let e of a)if(e[4]===PDF_MIME_TYPE&&e[1]?.toLowerCase().endsWith(".pdf"))processDriveAttachmentsByMimeType(e[3],e[1],s,t,e[4]);else{const a=getMimeTypeFromAttachmentName(e[1],FILE_EXTENSION_TO_MIME_TYPE_MAP);a?processDriveAttachmentsByMimeType(e[3],e[1],s,t,a):(sendAnalyticsIfNoFileExtension(e[1]),sendAnalyticsIfMimeTypeNotSupported(e[4]))}return{nonPDFDriveAttachments:t,driveAttachments:s}}catch(e){return sendAnalytics([["DCBrowserExt:Gmail:A6JDVDriveAttParsingFailed"]]),{}}},parseA6JDVAttachments=e=>{try{let t=new Map,s=[];if(Array.isArray(e[11]))for(const[a,r,,,,n]of e[11])processAttachmentByMimeType(a,r,n,s,t);return{nonPDFAttachments:t,pdfAttachments:s}}catch(e){return{}}},parseGMSetDataA6JDVEmails=(e,t,s)=>{if(e&&Array.isArray(e))try{for(let a of e){const e=a[0],r=a[6],{nonPDFAttachments:n,pdfAttachments:i}=parseA6JDVAttachments(a),{nonPDFDriveAttachments:o,driveAttachments:c}=parseA6JDVDriveAttachments(a);if(i?.length>0||n?.size>0||c?.length>0||o?.size>0){const l=9===a[71]?.[0];t[s]||(t[s]={messages:{}}),t[s].messages[e]={id:e,attachments:i,nonPDFAttachments:n,driveAttachments:c,nonPDFDriveAttachments:o,timestamp:r,deleted:l}}}}catch(e){}},parseFDEmailAndUpdateThreadData=(e,t,s)=>{if(Array.isArray(e))try{for(let a of e){const e=a[0],{nonPDFAttachments:r,pdfAttachments:n}=parseFDAttachments(a[1]?.[13]),{nonPDFDriveAttachments:i,driveAttachments:o}=parseFDDriveAttachments(a);if(n?.length>0||r?.size>0||o?.length>0||i?.size>0){const c=a[1]&&a[1][38]&&9===a[1][38][0];t[s]||(t[s]={messages:{}}),t[s].messages[e]={id:e,attachments:n,nonPDFAttachments:r,driveAttachments:o,nonPDFDriveAttachments:i,timestamp:a[1]?.[16],deleted:c}}}}catch(e){sendAnalytics([["DCBrowserExt:Gmail:FDEmailsParsingFailed"]])}},parseFDResponse=e=>{try{const t={},s=getParsedJSON(e);if(!Array.isArray(s))return null;const a=s[1];if(!a||!Array.isArray(a))return null;for(let e of a){const s=e[0],a=e[2];parseFDEmailAndUpdateThreadData(a,t,s)}return t}catch(e){return sendAnalytics([["DCBrowserExt:Gmail:FDResponseParsingFailed"]]),null}},init=()=>{const{gmailConfig:e,gmailConvertToPdfConfig:t,gmailImplicitDefaultViewershipConfig:s}=state,a=e.enableGmailTouchPoint,r=t.enableConvertToPdfTouchpointInGmail,n=s.enableImplicitDefaultViewershipFeature;if(r){const e=t.metadata.fileExtToMimeTypeMap;NON_PDF_MIME_TYPES=Object.values(e),FILE_EXTENSION_TO_MIME_TYPE_MAP=e}(a||r||n)&&(injectResponseListenerScript(),addMailDataEventListener())};export{init};