/*************************************************************************
* 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 e}from"../common/local-storage.js";import{communicate as t}from"./communicate.js";import{privateApi as s}from"./private-api.js";import{Proxy as r}from"./proxy.js";import{util as i}from"./util.js";import{SETTINGS as n}from"./settings.js";import{EDGE_USER_STATE as a,ACROBAT_USER_STATE as o,DECLARATIVE_IMS_REFERER_HEADER as l}from"./constant.js";import{hydrateWithStorage as c}from"./hydrate.js";import{common as m}from"./common.js";import{analytics as p}from"../common/analytics.js";import{OFFSCREEN_DOCUMENT_PATH as u}from"../common/constant.js";let d=null;const h=n?n.POLLING_INTERVAL_IN_MINUTES:1440;class g{constructor(){this.alarmName="userSubscription",this.scopes=["AdobeID","openid","DCAPI","sign_user_read","sign_user_write","sign_user_login","sign_library_read","sign_library_write","agreement_send","agreement_read","agreement_write","ab.manage","additional_info.account_type","sao.ACOM_ESIGN_TRIAL","widget_read","widget_write","workflow_read","workflow_write"],this.proxy=r.proxy.bind(this),i.isEdge()&&this.initiateUserPolling(),this.msgReplyForCheckSignIn=null}initiateUserPolling(){s.isMimeHandlerAvailable().then(c(t=>{const s="true"===e.getItem("pdfViewer");t&&s?this.startUserPolling():this.stopUserPolling()}))}async getUninstallPopupSettingsFromSchema(){try{const e=await chrome.storage.managed.get("UninstallPopup");return!e||"false"!==e.UninstallPopup}catch(e){return!0}}getUserSubscription(e=[]){let t=e.find(this.checkIfPaidUser);return t||e[0]}async updateBrowserUserState(t={}){const r=e.getItem("pdfViewer");let i="enabled";if((r&&"false"===r||!1===r)&&(i="disabled"),t&&t.level){this.checkIfUserIsFree(t)?s.setEdgeUserState({userState:a.free,viewerState:i}):s.setEdgeUserState({userState:a.subscribed,viewerState:i})}else s.setEdgeUserState({userState:a.pending,viewerState:i})}checkIfUserIsFree(e={}){return["ESign","SendNow","FillAndSign","Files"].includes(e.name)||e.level===o.free}checkIfPaidUser(e={}){return e.level!==o.free&&["DCGlobal","DCEnterprise","AcrobatPlus","AcrobatStd","PDFPack","ExportPDF","CreatePDF","GenAIServices"].includes(e.name)}async checkIfUninstallRequired(t={}){const r=await s.isInstalledViaUpsell(),i=this.checkIfUserIsFree(t);if(r)return i;{if("admin"===e.getItem("installSource"))return!1;const t=await s.getEdgeUserState();return!(!t||t.userState!==a.subscribed||!i)}}pollUserData(e){chrome.alarms.create(this.alarmName,{delayInMinutes:e||h,periodInMinutes:h})}async startUserPolling(){const t=e.getItem("userDetailsFetchedTimeStamp");if(t){const e=h-Math.floor((Date.now()-t)/6e4);e<0?this.pollUserData(1):this.pollUserData(e)}else{e.setItem("userDetailsFetchedTimeStamp",Date.now());if(await s.isInstalledViaUpsell())return void this.pollUserData();this.pollUserData(1)}}userSubscriptionhandler(t,r,i){return s.isMimeHandlerAvailable().then(async r=>{if(r){const r={...t,main_op:""},n=!await this.getUninstallPopupSettingsFromSchema()&&"sideload"===e.getItem("installSource")||!await s.isInstalledViaUpsell();r.main_op=n?"do-not-show-pop-up":"showUninstallPopUp";const{userSubscriptionData:a=[]}=t,o=this.getUserSubscription(a),l=this.checkIfUserIsFree(o||{}),c=this.checkIfPaidUser(o||{}),m=e.getItem("userEligibleForUninstall");e.setItem("userDetailsFetchedTimeStamp",Date.now()),this.pollUserData(h),l&&"true"===m?(i&&i(r),this.updateBrowserUserState(o||{})):this.checkIfUninstallRequired(o||{}).then(t=>{p.event(p.e.UNINSTALL_USER_STATE_FROM_VIEWER,{ISPAID:c,VALUE:t}),t?(e.setItem("userEligibleForUninstall","true"),i&&i(r)):(c&&e.removeItem("userEligibleForUninstall"),i&&i({main_op:"do-not-show-pop-up"})),this.updateBrowserUserState(o)})}else i({main_op:"do-not-show-pop-up"})}),!0}stopUserPolling(){chrome.permissions.contains({permissions:["alarms"]},e=>{e&&chrome.alarms.clear(this.alarmName)})}pdfViewerValueChanged(t={}){s.isMimeHandlerAvailable().then(s=>{s&&"true"===t.value?this.startUserPolling():(e.removeItem("userDetailsFetchedTimeStamp"),this.stopUserPolling())})}checkUserIsSignedIn(e,t,s){this.msgReplyForCheckSignIn=s,this.fetchUserSubscriptions()}async fetchUserSubscriptions(){try{await i.setupOffscreenDocument(u);const t=e.getItem("cdnUrl")||m.deriveCDNURL(m.getEnv());if(t){const s=new URL(t),r=e.getItem("installType")||"update";s.searchParams.append("version",`${chrome.runtime.getManifest().version}:${r}`),s.searchParams.append("callingApp",chrome.runtime.id),chrome.runtime.sendMessage({main_op:"getUserSubscriptions",target:"offscreen",cdnURL:s,signInURL:m.getSignInUrl(),isCDNSignInEnabled:e.getItem("csi")})}}catch(e){return i.consoleLog("Errored while fetching user details",e),{}}}async updateUserDetails(t){try{const s=t?.userSubscriptionData??[];if(e.setItem("userDetailsFetchedTimeStamp",Date.now()),s?.length){const t=this.getUserSubscription(s),r=this.checkIfPaidUser(t);this.checkIfUninstallRequired(t).then(s=>{s?e.setItem("userEligibleForUninstall","true"):r&&e.removeItem("userEligibleForUninstall"),p.event(p.e.UNINSTALL_USER_STATE,{ISPAID:r,VALUE:s}),this.updateBrowserUserState(t)})}else p.event(p.e.UNINSTALL_USER_STATE_PENDING),this.updateBrowserUserState({});chrome.runtime.sendMessage({main_op:"closeIframeOfUserSubscription",target:"offscreen"})}catch(e){i.consoleLog("Errored while updating user details",e)}}updateSignInStatus(e){if(this.msgReplyForCheckSignIn)return this.msgReplyForCheckSignIn({signInStatus:!!e?.value}),chrome.runtime.sendMessage({main_op:"closeIframeOfUserSubscription",target:"offscreen"}),void(this.msgReplyForCheckSignIn=null)}}d||(d=new g);const S=d,U=e=>{e&&e.name===S.alarmName&&S.fetchUserSubscriptions()};t.registerHandlers({userSubscriptionData:d.proxy(d.userSubscriptionhandler),pdfViewerChanged:d.proxy(d.pdfViewerValueChanged),userSubscriptions:d.proxy(d.updateUserDetails),checkUserIsSignedIn:d.proxy(d.checkUserIsSignedIn),updateSignInStatus:d.proxy(d.updateSignInStatus)});export{S as userSubscription,U as userSubscriptionAlarmHandler};