this.initOnShow(n),null,!1]):(Rr(this.to,s),Rr(this.cc,i),Rr(this.bcc,r),a&&!this.subject()&&this.subject(a)):this.initOnShow(n),ComposePopupView.inEdit(!1)}initOnShow(e){const t={},s=fi.email();Cr=e.message,s&&(t[s]=!0),this.reset();let i=null;if(Cr)switch(e.mode){case it.Reply:case it.ReplyAll:case it.Forward:case it.ForwardAsAttachment:i=Nr(Cr.to.concat(Cr.cc,Cr.bcc));break;case it.Draft:i=Nr(Cr.from.concat(Cr.replyTo))}if(i=i||or()[0],i&&(t[i.email()]=!0),h(e.to)&&this.to(Lr(e.to)),h(e.cc)&&this.cc(Lr(e.cc)),h(e.bcc)&&this.bcc(Lr(e.bcc)),e.mode&&Cr){let s,r="",a=me(Cr.dateTimestamp(),"FULL"),o=Cr.subject(),n="",l=Cr.draftInfo;switch(e.mode){case it.Reply:case it.ReplyAll:if(it.Reply===e.mode)this.to(Lr(Cr.replyEmails(t)));else{let e=Cr.replyAllEmails(t);this.to(Lr(e[0])),this.cc(Lr(e[1]))}this.subject(Or("Re",o)),this.prepareMessageAttachments(Cr,e.mode),this.aDraftInfo=["reply",Cr.uid,Cr.folder],this.sInReplyTo=Cr.messageId,this.sReferences=(Cr.references+" "+Cr.messageId).trim(),Cr.headers().valuesByName("autocrypt").forEach((e=>{let t=new MimeHeaderAutocryptModel(e);t.addr&&t.keydata&&(ai.hasPublicKeyForEmails([t.addr])||ai.importKey(t.pem(),!0,!0))}));break;case it.Forward:case it.ForwardAsAttachment:this.subject(Or("Fwd",o)),this.prepareMessageAttachments(Cr,e.mode),this.aDraftInfo=["forward",Cr.uid,Cr.folder],this.sInReplyTo=Cr.messageId,this.sReferences=(Cr.references+" "+Cr.messageId).trim();break;case it.Draft:this.bFromDraft=!0,this.draftsFolder(Cr.folder),this.draftUid(Cr.uid);case it.EditAsNew:this.to(Lr(Cr.to)),this.cc(Lr(Cr.cc)),this.bcc(Lr(Cr.bcc)),this.replyTo(Lr(Cr.replyTo)),this.subject(o),this.prepareMessageAttachments(Cr,e.mode),this.aDraftInfo=3===h(l)?l:null,this.sInReplyTo=Cr.inReplyTo,this.sReferences=Cr.references}switch(Fr.innerHTML=Cr.bodyAsHTML(),Fr.content.querySelectorAll("img").forEach((e=>{e.src||e.dataset.xSrcCid||e.dataset.xSrc||e.replaceWith(e.alt||e.title)})),n=Fr.innerHTML.trim(),e.mode){case it.Reply:case it.ReplyAll:n="
"+he("COMPOSE/REPLY_MESSAGE_TITLE",{DATETIME:a,EMAIL:Cr.from.toString(!1,!0)})+":
"+n.trim()+"
";break;case it.Forward:r=Cr.cc.toString(!1,!0),n="
"+he("COMPOSE/FORWARD_MESSAGE_TOP_TITLE")+"
"+he("GLOBAL/FROM")+": "+Cr.from.toString(!1,!0)+"
"+he("GLOBAL/TO")+": "+Cr.to.toString(!1,!0)+(r.length?"
"+he("GLOBAL/CC")+": "+r:"")+"
"+he("COMPOSE/FORWARD_MESSAGE_TOP_SENT")+": "+Dt(a)+"
"+he("GLOBAL/SUBJECT")+": "+Dt(o)+"
"+n.trim()+"
";break;case it.ForwardAsAttachment:n="";break;default:s=ai.isEncrypted(n)||Dr()||!Cr.isHtml(),s&&(n=Cr.plain())}this.editor((t=>{s?(t.modePlain(),t.setPlain(n)):t.setHtml(n),this.setSignature(i,e.mode),this.setFocusInPopup()}))}else it.Empty===e.mode?(this.subject(null!=e.subject?""+e.subject:""),this.editor((t=>{t.setHtml(e.text?""+e.text:""),Dr()&&t.modePlain(),this.setSignature(i),this.setFocusInPopup()}))):e.messages?(e.messages.forEach((e=>this.addMessageAsAttachment(e))),this.editor((t=>{Dr()?t.setPlain(""):t.setHtml(""),this.setSignature(i,e.mode),this.setFocusInPopup()}))):this.setFocusInPopup();const a=this.attachments.filter((e=>e&&!e.tempName())).map((e=>e.id));h(a)&&Vs.request("MessageUploadAttachments",((e,t)=>{const s=t?.Result;a.forEach(((t,i)=>{const a=this.getAttachmentById(t);a&&(a.waiting(!1).uploading(!1).complete(!0),e||!s?.[i]?a.error(ye(r.NoFileUploaded)):(a.tempName(s[i].tempName),a.type(s[i].mimeType)))}))}),{attachments:a},999e3),this.currentIdentity(i)}setFocusInPopup(){setTimeout((()=>{this.to()?this.subject()?this.oEditor?.focus():this.viewModelDom.querySelector('input[name="subject"]').focus():this.to.focused(!0)}),100)}doClose(){AskPopupView.hidden()&&(ComposePopupView.inEdit()||this.isEmptyForm()&&!this.draftUid()?this.close():Fs(AskPopupView,[he("POPUPS_ASK/DESC_WANT_CLOSE_THIS_WINDOW"),()=>this.close()]))}onBuild(e){const t=new Jua({action:Q("Upload"),clickElement:e.querySelector("#composeUploadButton"),dragAndDropElement:e.querySelector(".b-attachment-place")}),s=f(F("attachmentLimit"));t.on("onDragEnter",(()=>{this.dragAndDropOver(!0)})).on("onDragLeave",(()=>{this.dragAndDropOver(!1)})).on("onBodyDragEnter",(()=>{this.attachmentsArea(),this.dragAndDropVisible(!0)})).on("onBodyDragLeave",(()=>{this.dragAndDropVisible(!1)})).on("onProgress",((e,t,s)=>{let i=this.getAttachmentById(e);i&&i.progress(Math.floor(t/s*100))})).on("onSelect",((e,i)=>{this.dragAndDropOver(!1);const r=f(i.size,null),a=new ComposeAttachmentModel(e,i.fileName?i.fileName.toString():"",r);return this.addAttachment(a,1,t),!(0{let t=this.getAttachmentById(e);t&&t.waiting(!1).uploading(!0).complete(!1)})).on("onComplete",((e,t,s)=>{const i=this.getAttachmentById(e),r=s?.Result||{},a=r.ErrorCode,o=t&&r.Attachment;let n="";null!=a?n=ye(a):o||(n=he("UPLOAD/ERROR_UNKNOWN")),i&&(n?i.waiting(!1).uploading(!1).complete(!0).error(n+"\n"+r.ErrorMessage):o&&(i.waiting(!1).uploading(!1).complete(!0),i.fileName(o.name),i.size(o.size?f(o.size):0),i.tempName(o.tempName?o.tempName:""),i.isInline=!1,i.type(o.mimeType)))})),this.addAttachmentEnabled(!0),V("q","meta",Mr,(()=>!1)),V("w","meta",Mr,(()=>!1)),V("m","meta",Mr,(()=>(this.identitiesMenu().ddBtn.toggle(),!1))),V("arrowdown","meta",Mr,(()=>(this.skipCommand(),!1))),V("s","meta",Mr,(()=>(this.saveCommand(),!1))),V("save","",Mr,(()=>(this.saveCommand(),!1))),V("enter","meta",Mr,(()=>(this.sendCommand(),!1))),V("mailsend","",Mr,(()=>(this.sendCommand(),!1))),V("escape,close","shift",Mr,(()=>(this.doClose(),!1))),this.editor((e=>e[Dr()?"modePlain":"modeWysiwyg"]()))}getAttachmentById(e){return this.attachments.find((t=>t&&e===t.id))}addMessageAsAttachment(e){if(e){const t=new ComposeAttachmentModel(e.requestHash,e.subject()+".eml",e.size);t.fromMessage=!0,t.complete(!0),this.addAttachment(t)}}addAttachment(e,t,s){s||e.waiting(!1).uploading(!0),e.cancel=()=>{this.attachments.remove(e),s?.cancel(e.id)},this.attachments.push(e),t&&this.attachmentsArea()}addAttachmentHelper(e,t,s){const i=new ComposeAttachmentModel(e,t,s);return this.addAttachment(i,1),i}prepareMessageAttachments(e,t){if(e){let s=[it.Reply,it.ReplyAll].includes(t);s||[it.Forward,it.Draft,it.EditAsNew].includes(t)?e.attachments.forEach((e=>{if(!s||e.isLinked()){const t=new ComposeAttachmentModel(e.download,e.fileName,e.estimatedSize,e.isInline(),e.isLinked(),e.cId,e.contentLocation);t.fromMessage=!0,t.type(e.mimeType),this.addAttachment(t)}})):it.ForwardAsAttachment===t&&this.addMessageAsAttachment(e)}}isEmptyForm(e=!0){const t=e?!this.attachments.length:!this.attachments.some((e=>e?.complete()));return!this.to.length&&!this.cc.length&&!this.bcc.length&&!this.replyTo.length&&!this.subject.length&&t&&(!this.oEditor||!this.oEditor.getData())}reset(){this.to(""),this.cc(""),this.bcc(""),this.replyTo(""),this.subject(""),this.requestDsn(ft.requestDsn()),this.requestReadReceipt(ft.requestReadReceipt()),this.requireTLS(ft.requireTLS()),this.markAsImportant(!1),this.bodyArea(),this.aDraftInfo=null,this.sInReplyTo="",this.bFromDraft=!1,this.sReferences="",this.sendError(!1),this.sendSuccessButSaveError(!1),this.savedError(!1),this.savedTime(0),this.emptyToError(!1),this.attachmentsInProcessError(!1),this.showCc(!1),this.showBcc(!1),this.showReplyTo(!1),this.doSign(ft.pgpSign()),this.doEncrypt(ft.pgpEncrypt()),this.attachments([]),this.dragAndDropOver(!1),this.dragAndDropVisible(!1),this.draftsFolder(""),this.draftUid(0),this.sending(!1),this.saving(!1),this.oEditor?.clear(),this.dropMailvelope()}attachmentsArea(){this.viewArea("attachments")}bodyArea(){this.viewArea("body")}allRecipients(){return[this.from(),this.to(),this.cc(),this.bcc()].join(",").split(",").map((e=>Ir(e.trim()))).validUnique()}initSign(){let e=[],t=this.currentIdentity(),s=Ir(this.from()),i=ti.getPrivateKeyFor(s,1);i&&e.push(["OpenPGP",i]),i=Hs.getPrivateKeyFor(s,1),i&&e.push(["GnuPG",i]),t.smimeKeyValid()&&t.smimeCertificateValid()&&t.email()===s&&e.push(["S/MIME"]),this.signOptions(e)}async initEncrypt(){const e=this.allRecipients(),t=[];if(e.length){Hs.hasPublicKeyForEmails(e)&&t.push("GnuPG"),ti.hasPublicKeyForEmails(e)&&t.push("OpenPGP");const s=e.length,i=this.currentIdentity(),r=i.smimeKey()&&i.smimeCertificate()?i.email():null;s&&s===e.filter((e=>e==r||vr.find((t=>e==t.emailAddress&&t.smimeencrypt)))).length&&t.push("S/MIME"),await ii.hasPublicKeyForEmails(e)?t.push("Mailvelope"):"mailvelope"===this.viewArea()&&this.bodyArea()}this.encryptOptions(t)}async getMessageRequestParams(e,t){let s,i=this.oEditor.getData().trim(),r=0;const a={};this.attachments.forEach((e=>{e?.complete()&&e?.tempName()&&e?.enabled()&&(++r,a[e.tempName()]={name:e.fileName(),inline:e.isInline,cId:e.cId,location:e.contentLocation,type:e.mimeType()})}));const o=this.currentIdentity(),n={identityID:o.id(),messageFolder:this.draftsFolder(),messageUid:this.draftUid(),saveFolder:e,from:this.from(),to:this.to(),cc:this.cc(),bcc:this.bcc(),replyTo:this.replyTo(),subject:this.subject(),draftInfo:this.aDraftInfo,inReplyTo:this.sInReplyTo,references:this.sReferences,markAsImportant:this.markAsImportant()?1:0,attachments:a,dsn:this.requestDsn()?1:0,requireTLS:this.requireTLS()?1:0,readReceiptRequest:this.requestReadReceipt()?1:0,autocrypt:[],linkedData:[]},l=t?[o.email()]:this.allRecipients(),c=!t&&this.doSign()&&this.signOptions(),d=this.doEncrypt()&&this.encryptOptions(),h=this.oEditor.isHtml();if(h){do{s=i.length,i=i.replace(/(<[^>]+[;"'])\s*mso-[a-z-]+\s*:[^;"']+/gi,"$1").replace(/(<[^>]+)\s+data-hs-[a-z-]+=("[^"]+"|'[^']+')/gi,"$1")}while(s!=i.length);n.html=i,n.plain=_t(i)}else n.plain=i;if(this.mailvelope&&"mailvelope"===this.viewArea())n.encrypted=t?await this.mailvelope.createDraft():await this.mailvelope.encrypt(l);else if(c.length||d.length){if(!t&&!r&&!i.length)throw he("COMPOSE/ERROR_EMPTY_BODY");let e=new MimePart;if(e.headers["Content-Type"]="text/"+(h?"html":"plain")+'; charset="utf-8"',e.headers["Content-Transfer-Encoding"]="base64",e.body=Pr(i),h){const t=new MimePart,s=new MimePart;t.headers["Content-Type"]="multipart/alternative",s.headers["Content-Type"]='text/plain; charset="utf-8"',s.headers["Content-Transfer-Encoding"]="base64",s.body=Pr(n.plain),t.children.push(s),t.children.push(e),e=t}let s=!1;for(let t=0;tObject.entries(ai.getPublicKeyOfEmails(l)||{}).forEach((([e,t])=>n.autocrypt.push({addr:e,keydata:t.replace(/-----(BEGIN|END) PGP PUBLIC KEY BLOCK-----/g,"").trim()})));for(let s=0;s{e.emailAddress!=o.email()&&l.includes(e.emailAddress)&&n.encryptCertificates.push(e.id)}));break}}}}return n}}ComposePopupView.inEdit=ko.observable(!1);class MailFolderList extends AbstractViewLeft{constructor(){super(),this.composeInEdit=ComposePopupView.inEdit,this.systemFolders=ns.systemFolders,this.moveAction=nr,this.allowContacts=xs.allowContacts(),this.foldersFilter=Yi,this.filterUnseen=ko.observable(!1),Ae(this,{foldersFilterVisible:()=>20{let e=ns.folderList().visible();return 1===e.length&&e[0].isInbox()?e[0].visibleSubfolders():e}})}onBuild(s){const i=e=>s.querySelector(e),r=(e,t)=>e.target.closestWithin(t,s);this.oContentScrollable=i(".b-content"),s.addEventListener("click",(t=>{let s=r(t,".e-collapsed-sign");if(s){const e=ko.dataFor(s);if(e){const s=e.collapsed();return zi(e.fullName,s),e.collapsed(!s),void _(t)}}if(s=r(t,"a"),s?.matches(".selectable")){t.preventDefault();const i=ko.dataFor(s);if(i){if(nr()){const e=t.ctrlKey||2===nr(),s=Pi.listCheckedOrSelectedUidsWithSubMails();nr(0),s.size&&Pi.moveMessages(s.folder,s,i.fullName,e)}else{ft.usePreviewPane()||gi.message(null);let e="";t.target.matches(".flag-icon")&&!i.isFlagged()?e="flagged":i.unreadCount()&&t.clientX>s.getBoundingClientRect().right-25&&(e="unseen"),hasher.setHash(ie(i.fullNameHash,1,e)),ut.isMobile()&&N(!0)}xs.focusedState(e)}}})),V("arrowup,arrowdown","",t,(e=>{let t=[],i=0;return s.querySelectorAll("li a").forEach((e=>{(e.offsetHeight||e.getClientRects().length)&&(t.push(e),e.matches(".focused")&&(e.classList.remove("focused"),i=t.length-1))})),t.length&&("ArrowUp"===e.key?i&&--i:i{const t=i("li a.focused");return t&&(xs.focusedState(e),t.click()),!1})),V("space","",t,(()=>{const e=i("li a.focused"),t=e&&ko.dataFor(e);if(t){const e=t.collapsed();zi(t.fullName,e),t.collapsed(!e)}return!1})),V("escape,tab,arrowright","",t,(()=>(xs.focusedState(e),nr(0),!1)))}scrollToFocused(){const e=this.oContentScrollable;if(e){let t,s=e.querySelector("li a.focused");if(s){const i=s.getBoundingClientRect(),r=e.getBoundingClientRect();i.topr.bottom&&(t="end"),t&&s.scrollIntoView("start"===t)}}}composeClick(){gr()}clearFolderSearch(){Yi("")}createFolder(){Fs(FolderCreatePopupView)}configureFolders(){hasher.setHash(se("folders"))}contactsClick(){this.allowContacts&&Fs(ContactsPopupView)}}class FolderClearPopupView extends AbstractViewPopup{constructor(){super("FolderClear"),Ce(this,{folder:null,clearing:!1}),Ae(this,{dangerDescHtml:()=>he("POPUPS_CLEAR_FOLDER/DANGER_DESC_HTML_1",{FOLDER:this.folder()?.localName()})}),Ls(this,{clearCommand:e=>!e.clearing()})}clearCommand(){const e=this.folder();e&&(this.clearing(!0),Vs.request("FolderClear",(t=>{e.totalEmails(0),e.unreadEmails(0),gi.message(null),Pi.reload(!0,!0),this.clearing(!1),t?alert(be(t)):this.close()}),{folder:e.fullName}))}onShow(e){this.clearing(!1),this.folder(e)}}class AdvancedSearchPopupView extends AbstractViewPopup{constructor(){super("AdvancedSearch"),Ce(this,{from:"",to:"",subject:"",text:"",keyword:"",repliedValue:-1,selectedDateValue:0,selectedTreeValue:"",hasAttachment:!1,starred:!1,unseen:!1}),Ae(this,{showMultisearch:()=>ns.hasCapability("MULTISEARCH"),keywords:()=>{const e=[{value:"",label:""}];return ns.currentFolder().optionalTags().forEach((t=>{let s=t.toLowerCase();e.push({value:t,label:he("MESSAGE_TAGS/"+s,0,s)})})),e},showKeywords:()=>ns.currentFolder().permanentFlags().some(os),repliedOptions:()=>(ce(),[{id:-1,name:""},{id:1,name:he("GLOBAL/YES")},{id:0,name:he("GLOBAL/NO")}]),selectedDates:()=>{ce();let e="SEARCH/SINCE_",t="SEARCH/BEFORE_";return[{id:0,name:he("SEARCH/DATE_ALL")},{id:3,name:he(e+"3_DAYS")},{id:7,name:he(e+"7_DAYS")},{id:30,name:he(e+"MONTH")},{id:90,name:he(e+"3_MONTHS")},{id:180,name:he(e+"6_MONTHS")},{id:365,name:he(e+"YEAR")},{id:-3,name:he(t+"3_DAYS")},{id:-7,name:he(t+"7_DAYS")},{id:-30,name:he(t+"MONTH")},{id:-90,name:he(t+"3_MONTHS")},{id:-180,name:he(t+"6_MONTHS")},{id:-365,name:he(t+"YEAR")}]},selectedTree:()=>{ce();let e="SEARCH/SUBFOLDERS_";return[{id:"",name:he(e+"NONE")},{id:"subtree-one",name:he(e+"SUBTREE_ONE")},{id:"subtree",name:he(e+"SUBTREE")}]}})}submitForm(){const e=this.buildSearchString();e&&Pi.mainSearch(e),this.close()}buildSearchString(){const e=this,t=new FormData,s=(e,s)=>s.length&&t.append(e,s);if(s("from",e.from().trim()),s("to",e.to().trim()),s("subject",e.subject().trim()),s("text",e.text().trim()),s("keyword",e.keyword()),s("in",e.selectedTreeValue()),0e.selectedDateValue()){let t=new Date;t.setDate(t.getDate()+e.selectedDateValue()),s("before",t.toISOString().split("T")[0])}let i=decodeURIComponent(new URLSearchParams(t).toString());return e.hasAttachment()&&(i+="&attachment"),e.unseen()&&(i+="&unseen"),e.starred()&&(i+="&flagged"),1==e.repliedValue()&&(i+="&answered"),0==e.repliedValue()&&(i+="&unanswered"),i.replace(/^&+/,"")}onShow(e){const t=this,s=new URLSearchParams("?"+e);t.from(m(s.get("from"))),t.to(m(s.get("to"))),t.subject(m(s.get("subject"))),t.text(m(s.get("text"))),t.keyword(m(s.get("keyword"))),t.selectedTreeValue(m(s.get("in"))),t.selectedDateValue(0),t.hasAttachment(s.has("attachment")),t.starred(s.has("flagged")),t.unseen(s.has("unseen")),s.has("answered")?t.repliedValue(1):s.has("unanswered")&&t.repliedValue(0)}}const _r=()=>Pi.hasCheckedOrSelected(),Ur=(...e)=>Pi.setAction(...e),Vr=(e,t)=>{let s=Pi.listCheckedOrSelectedUidsWithSubMails();s.size&&rl.app.moveMessagesToFolderType(e,s.folder,s,t)},Kr=e=>10>e?"0"+e:""+e,qr=e=>e.getFullYear()+Kr(1+e.getMonth())+Kr(e.getDate()),Br=e=>{yr(e)};let Hr="";class MailMessageList extends AbstractViewRight{constructor(){super(),this.allowDangerousActions=I("DangerousActions"),this.messageList=Pi,this.archiveAllowed=Pi.archiveAllowed,this.canMarkAsSpam=Pi.canMarkAsSpam,this.isSpamFolder=Pi.isSpamFolder,this.composeInEdit=ComposePopupView.inEdit,this.isMobile=ut.isMobile,this.popupVisibility=Ps,this.useCheckboxesInList=ft.useCheckboxesInList,this.userUsageProc=ns.quotaPercentage,this.hideDeleted=ft.hideDeleted,Ce(this,{focusSearch:!1}),this.dragOver=ko.observable(!1).extend({throttle:1}),this.dragOverEnter=ko.observable(!1).extend({throttle:1});const e=M.app("attachmentsActions");this.attachmentsActions=ko.observableArray(h(e)?e:[]),Ae(this,{sortSupported:()=>ns.hasCapability("SORT")&&!Pi.threadUid(),messageListSearchDesc:()=>{const e=Pi().search;return e?he("MESSAGE_LIST/SEARCH_RESULT_FOR",{SEARCH:e}):""},messageListPaginator:mr(Pi.page,Pi.pageCount),checkAll:{read:()=>Pi.hasChecked(),write:e=>{e=!!e,Pi.forEach((t=>t.checked(e)))}},inputSearch:{read:Pi.mainSearch,write:e=>Hr=e},isIncompleteChecked:()=>{const e=Pi.listChecked().length;return e&&Pi().length>e},listGrouped:()=>{let e=Pi.threadUid(),t=ns.sortMode()||"DATE";return ft.listGrouped()&&(t.includes("DATE")||t.includes("FROM"))&&!e},timeFormat:()=>(ns.sortMode()||"").includes("FROM")?"AUTO":"LT",groupedList:()=>{let e,t=[],s=ns.sortMode()||"DATE";if(s.includes("FROM"))Pi.forEach((s=>{let i=s.from[0]?.email;e&&i==e.id||(e={id:i,label:s.from[0]?.toLine(),search:"from="+i,messages:[]},t.push(e)),e.messages.push(s)}));else if(s.includes("DATE")){let s=qr(new Date),i=Intl.RelativeTimeFormat?new Intl.RelativeTimeFormat(k.documentElement.lang,{numeric:"auto"}):0;Pi.forEach((r=>{let a,o=new Date(1e3*r.dateTimestamp()),n=qr(o);e&&n==e.id||(a=i&&s==n?i.format(0,"day"):i&&s-1==n?i.format(-1,"day"):o.format({dateStyle:"full"},0,re.hourCycle()),e={id:n,label:a,search:"on="+o.getFullYear()+"-"+Kr(1+o.getMonth())+"-"+Kr(o.getDate()),messages:[]},t.push(e)),e.messages.push(r)}))}return t},sortText:()=>{let e=ns.sortMode(),t=""===e||e.includes("REVERSE");return e=e.split(/\s+/),e.includes("FROM")?"@"+(t?"⬆":"⬇"):e.includes("SUBJECT")?"𝐒"+(t?"⬆":"⬇"):(e.includes("SIZE")?"✉":"📅")+(t?"⬇":"⬆")},downloadAsZipAllowed:()=>this.attachmentsActions.includes("zip")}),this.selector=new Selector(Pi,Pi.selectedMessage,Pi.focusedMessage,".messageListItem",".messageListItem .messageCheckbox"),this.selector.on("ItemSelect",(e=>{e?Br(e):gi.message(null)})),this.selector.on("MiddleClick",(e=>yr(e,!0))),this.selector.on("ItemGetUid",(e=>e?e.folder+"/"+e.uid:"")),this.selector.on("canSelect",(()=>Pi.canSelect())),this.selector.on("click",((e,t)=>{const s=e.target;if(s.closest(".flagParent")){if(t){const e=Pi.listCheckedOrSelected();Ur(t.folder,t.isFlagged()?nt:ot,e.find((e=>e.uid==t.uid))?e:[t])}}else{if(!s.closest(".threads-len"))return 1;this.gotoThread(t)}})),this.selector.on("UpOrDown",(e=>{if(!Pi.hasChecked()){e=e?-1:1;const t=Pi.page()+e;t>0&&t<=Pi.pageCount()&&(ft.usePreviewPane()||gi.message()?this.selector.iSelectNextHelper=e:this.selector.iFocusedNextHelper=e,this.selector.unselect(),this.gotoPage(t))}})),addEventListener("mailbox.message-list.selector.go-down",(e=>this.selector.newSelectPosition("ArrowDown",!1,e.detail))),addEventListener("mailbox.message-list.selector.go-up",(e=>this.selector.newSelectPosition("ArrowUp",!1,e.detail))),addEventListener("mailbox.message.show",(e=>{const t=e.detail.folder,s=e.detail.uid,i=Pi.find((e=>t===e?.folder&&s==e?.uid));if("INBOX"===t&&hasher.setHash(ie(t)),i)this.selector.selectMessageItem(i);else if("INBOX"!==t&&hasher.setHash(ie(t)),t&&s){let e=new MessageModel;e.folder=t,e.uid=s,Br(e)}else gi.message(null)})),Pi.endHash.subscribe((()=>this.selector.scrollToFocused()).throttle(50)),Ls(this,{downloadAttachCommand:_r,downloadZipCommand:_r,forwardCommand:_r,deleteWithoutMoveCommand:_r,deleteCommand:()=>Pi.hasCheckedOrSelectedAndUndeleted(),undeleteCommand:()=>Pi.hasCheckedOrSelectedAndDeleted(),archiveCommand:_r,spamCommand:_r,notSpamCommand:_r,moveCommand:_r,copyCommand:_r})}changeSort(e,t){ns.sortMode(t.target.closest("li").dataset.sort),this.reload()}clearListIsVisible(){return!this.messageListSearchDesc()&&!Pi.error()&&!Pi.endThreadUid()&&Pi().length&&(Pi.isSpamFolder()||Pi.isTrashFolder())&&I("DangerousActions")}clear(){I("DangerousActions")&&Fs(FolderClearPopupView,[ns.currentFolder()])}reload(){Pi.isLoading()||Pi.reload(!1,!0)}forwardCommand(){gr([it.ForwardAsAttachment,Pi.listCheckedOrSelected()])}downloadZipCommand(){let e=[];Pi.forEach((t=>t.checked()&&e.push(t.requestHash))),ur(null,e,null,null,Pi().folder)}downloadAttachCommand(){let e=[];Pi.forEach((t=>{t.checked()&&t.attachments.forEach((t=>{!t.isLinked()&&t.download&&e.push(t.download)}))})),ur(null,e)}deleteWithoutMoveCommand(){I("DangerousActions")&&Vr(et.Trash,!0)}deleteCommand(){rs===ns.trashFolder()?Ur(ns.currentFolderFullName(),lt,Pi.listCheckedOrSelected()):Vr(et.Trash)}undeleteCommand(){Ur(ns.currentFolderFullName(),ct,Pi.listCheckedOrSelected())}archiveCommand(){Vr(et.Archive)}spamCommand(){Vr(et.Junk)}notSpamCommand(){Vr(et.Inbox)}moveOrCopy(s,i,r){if(_r()){s&&i?.preventDefault&&_(i);let a=nr();xs.focusedState(a?e:t),nr(a?0:r)}}moveCommand(e,t){this.moveOrCopy(e,t,1)}copyCommand(e,t){this.moveOrCopy(e,t,2)}composeClick(){gr()}cancelSearch(){Pi.mainSearch(""),this.focusSearch(!1)}cancelThreadUid(){hasher.setHash(ie(ns.currentFolderFullNameHash(),Pi.pageBeforeThread(),Pi.listSearch()))}listSetSeen(){Ur(ns.currentFolderFullName(),rt,Pi.listCheckedOrSelected())}listSetAllSeen(){let e=ns.currentFolderFullName(),t=Pi.endThreadUid();if(e){let s=0;const i=[];let r=ss(e);r&&(Pi.forEach((e=>{e.isUnseen()&&++s,e.flags.push("\\seen"),t&&i.push(e.uid)})),t?r.unreadEmails(Math.max(0,r.unreadEmails()-s)):r.unreadEmails(0),Vs.request("MessageSetSeenToAll",null,{folder:e,setAction:1,threadUids:i.join(",")}))}}listUnsetSeen(){Ur(ns.currentFolderFullName(),at,Pi.listCheckedOrSelected())}listSetFlags(){Ur(ns.currentFolderFullName(),ot,Pi.listCheckedOrSelected())}listUnsetFlags(){Ur(ns.currentFolderFullName(),nt,Pi.listCheckedOrSelected())}seenMessagesFast(e){const t=Pi.listCheckedOrSelected();t.length&&Ur(t[0].folder,e?rt:at,t)}gotoPage(e){e&&hasher.setHash(ie(ns.currentFolderFullNameHash(),e,Pi.listSearch(),Pi.threadUid()))}gotoThread(e){e?.threadsLen()&&(Pi.pageBeforeThread(Pi.page()),hasher.setHash(ie(ns.currentFolderFullNameHash(),1,Pi.listSearch(),e.uid)))}listEmptyMessage(){return this.dragOver()||Pi().length||Pi.isLoading()||Pi.error()?"":he("MESSAGE_LIST/EMPTY_"+(Pi.listSearch()?"SEARCH_":"")+"LIST")}onBuild(i){const r=i.querySelector(".b-content"),a=(e,t)=>e.target.closestWithin(t,i);if(setTimeout((()=>{const e=i.querySelector(".messageList"),t=()=>{let t=ft.usePreviewPane();fr(e,5,t?1===t?"Width":"Height":0)};e&&(t(),addEventListener("rl-layout",t))}),1),this.selector.init(r,e),B(i,{click:t=>{if(a(t,".toggleLeft"))R();else{ut.isMobile()&&N(!0),a(t,".messageList")&&s===xs.focusedState()&&xs.focusedState(e);let i=a(t,".e-paginator a");i&&this.gotoPage(ko.dataFor(i)?.value),a(t,".checkboxCheckAll")&&this.checkAll(!this.checkAll())}},dblclick:e=>{let t=a(e,".messageListItem");t&&this.gotoThread(ko.dataFor(t))}}),M.app("allowAppendMessage")){const e=i.querySelector(".listDragOver"),t=e=>{for(const t of e.dataTransfer.items)if("file"===t.kind&&Le===t.type)return!0};B(e,{dragover:e=>{t(e)&&(e.dataTransfer.dropEffect="copy",e.preventDefault())}}),B(r,{dragenter:s=>{t(s)&&(r.contains(s.target)&&this.dragOver(!0),s.target==e&&(s.dataTransfer.dropEffect="copy",this.dragOverEnter(!0)))},dragleave:t=>{t.target==e&&this.dragOverEnter(!1);let s=t.relatedTarget;s&&r.contains(s)||this.dragOver(!1)},drop:s=>{s.preventDefault(),s.target==e&&t(s)&&(Pi.loading(!0),Ui(ns.currentFolderFullName(),s.dataTransfer.files)),this.dragOverEnter(!1),this.dragOver(!1)}})}V("enter,open","",e,(()=>U()?(Pi.mainSearch(Hr),!1):gi.message()&&Pi.canSelect()?(mi()||pi(),!1):void 0)),K("z","",[e,s],(()=>(this.archiveCommand(),!1))),K("delete","shift",e,(()=>(Pi.listCheckedOrSelected().length&&this.deleteWithoutMoveCommand(),!1))),K("delete","",e,(()=>(Pi.listCheckedOrSelected().length&&this.deleteCommand(),!1))),V("r","meta",[t,e,s],(()=>(this.reload(),!1))),K("a","meta",e,(()=>(this.checkAll(!(this.checkAll()&&!this.isIncompleteChecked())),!1))),K("w,c,new","",[e,s],(()=>(gr(),!1))),K("i","",[e,s],(()=>{const e=Pi.listCheckedOrSelected();return e.length&&Ur(e[0].folder,e.every((e=>e.isFlagged()))?nt:ot,e),!1})),K("t","",[e],(()=>{let e=Pi.selectedMessage()||Pi.focusedMessage();return 0(this.moveCommand(),!1))),K("q","",[e,s],(()=>(this.seenMessagesFast(!0),!1))),K("u","",[e,s],(()=>(this.seenMessagesFast(!1),!1))),K("f,mailforward","shift",[e,s],(()=>(this.forwardCommand(),!1))),I("Search")&&V("/","",[e,s],(()=>(this.focusSearch(!0),!1))),V("escape","",e,(()=>this.messageListSearchDesc()?(this.cancelSearch(),!1):Pi.endThreadUid()?(this.cancelThreadUid(),!1):void 0)),V("tab","shift",e,(()=>(xs.focusedState(t),!1))),V("arrowleft","",e,(()=>(xs.focusedState(t),!1))),V("tab,arrowright","",e,(()=>{if(gi.message())return xs.focusedState(s),!1})),V("arrowleft","meta",s,(()=>!1)),V("arrowright","meta",s,(()=>!1)),V("f","meta",e,this.advancedSearchClick)}advancedSearchClick(){Fs(AdvancedSearchPopupView,[Pi.mainSearch()])}groupSearch(e){e.search&&Pi.mainSearch(e.search)}groupCheck(e){e.messages.forEach((e=>e.checked(!e.checked())))}quotaTooltip(){return he("MESSAGE_LIST/QUOTA_SIZE",{SIZE:Qe.friendlySize(ns.quotaUsage()),PROC:ns.quotaPercentage(),LIMIT:Qe.friendlySize(ns.quotaLimit())}).replace(/<[^>]+>/g,"")}}class OpenPgpImportPopupView extends AbstractViewPopup{constructor(){super("OpenPgpImport"),Ce(this,{search:"",key:"",keyError:!1,keyErrorMessage:"",saveGnuPG:!0,saveServer:!0}),this.canGnuPG=Hs.isSupported(),this.key.subscribe((()=>{this.keyError(!1),this.keyErrorMessage("")}))}searchPGP(){this.key(he("SUGGESTIONS/SEARCHING_DESC"));const e=()=>Vs.request("PgpSearchKey",((e,t)=>{e?this.key(t.ErrorMessage):this.key(t.Result)}),{query:this.search()});fetch(`https://keys.openpgp.org/pks/lookup?op=get&options=mr&search=${this.search()}`,{method:"GET",mode:"cors",cache:"no-cache",redirect:"error",referrerPolicy:"no-referrer",credentials:"omit"}).then((t=>{"application/pgp-keys"==t.headers.get("Content-Type")?t.text().then((e=>this.key(e))):e()})).catch((t=>{throw this.key("keys.openpgp.org: "+t?.message+"\nTrying local..."),e(),t}))}submitForm(){let e=this.key().trim();if(/\n/.test(e)&&(e=e.replace(/\r+/g,"").replace(/\n{2,}/g,"\n\n")),this.keyError(!e),this.keyErrorMessage(""),e){let t=null,s=30,i=!1;const r=this.saveGnuPG()&&Hs.isSupported(),a=this.saveServer(),o=/[-]{3,6}BEGIN[\s]PGP[\s](PRIVATE|PUBLIC)[\s]KEY[\s]BLOCK[-]{3,6}[\s\S]+?[-]{3,6}END[\s]PGP[\s](PRIVATE|PUBLIC)[\s]KEY[\s]BLOCK[-]{3,6}/gi;do{t=o.exec(e),t&&0A("messageItem")||{},jr=gi.message,$r=e=>{const t=jr();t&&Pi.setAction(t.folder,e,[t])},Wr=e=>rl.fetch(e).then((e=>e.ok&&e.text()));class MailMessageView extends AbstractViewRight{constructor(){super();const e=(e,t)=>{let s=()=>(t()&&e.call(null),!1);return s.canExecute=t,s},t=t=>e((()=>this.replyOrforward(t)),this.canBeRepliedOrForwarded),s=(t,s)=>e((()=>{const e=jr();e&&(jr(null),rl.app.moveMessagesToFolderType(t,e.folder,new Set([e.uid]),s))}),this.messageVisible);this.msgDefaultAction=ft.msgDefaultAction,this.simpleAttachmentsList=ft.simpleAttachmentsList,Ce(this,{showAttachmentControls:!!Gi(10),downloadAsZipLoading:!1,showFullInfo:"1"===Gi(9),actionsMenu:null,viewFromShort:"",dkimData:["none","",""],nowTracking:!1}),this.moveAction=nr;const i=M.app("attachmentsActions");this.attachmentsActions=ko.observableArray(h(i)?i:[]),this.hasCheckedMessages=Pi.hasChecked,this.archiveAllowed=Pi.archiveAllowed,this.canMarkAsSpam=Pi.canMarkAsSpam,this.isDraftFolder=Pi.isDraftFolder,this.isSpamFolder=Pi.isSpamFolder,this.message=jr,this.messageLoadingThrottle=gi.loading,this.messageError=gi.error,this.fullScreenMode=mi,this.toggleFullScreen=pi,this.downloadAsZipError=ko.observable(!1).extend({falseTimeout:7e3}),this.messageDomFocused=ko.observable(!1).extend({rateLimit:0}),this.viewHash="",Ae(this,{allowAttachmentControls:()=>h(i)&&I("AttachmentsActions"),downloadAsZipAllowed:()=>this.attachmentsActions.includes("zip")&&(jr()?.attachments||[]).filter((e=>e?.checked()&&e?.download)).length,tagsAllowed:()=>ns.currentFolder()?.tagsAllowed(),messageVisible:()=>!gi.loading()&&!!jr(),tagsToHTML:()=>jr()?.flags().map((e=>os(e)?''+he("MESSAGE_TAGS/"+e,0,e)+"":"")).join(" "),askReadReceipt:()=>jr()?.readReceipt&&!(Pi.isDraftFolder()||Pi.isSentFolder())&&!jr()?.flags().includes("$mdnsent")&&!jr()?.flags().includes("\\answered"),listAttachments:()=>jr()?.attachments().filter((e=>ft.listInlineAttachments()||!e.isLinked())),hasAttachments:()=>jr()?.attachments().some((e=>ft.listInlineAttachments()||!e.isLinked())),canBeRepliedOrForwarded:()=>!Pi.isDraftFolder()&&this.messageVisible(),dkimIcon:()=>{switch(this.dkimData()[0]){case"none":return"";case"pass":return"✔";default:return"✖"}},dkimIconClass:()=>"pass"===this.dkimData()[0]?"iconcolor-green":"iconcolor-red",dkimTitle:()=>{const e=this.dkimData();return e[0]?e[2]||"DKIM: "+e[0]:""},showWhitelistOptions:()=>"match"===ft.viewImages(),firstUnsubsribeLink:()=>jr()?.unsubsribeLinks()[0]||"",pgpSupported:()=>jr()&&ai.isSupported(),canBeUndeleted:()=>jr()?.isDeleted(),messageListOrViewLoading:()=>Pi.isLoading()|gi.loading()}),Te(this,{message:e=>{e?(this.viewHash!==e.hash&&this.scrollMessageToTop(),this.viewHash=e.hash,this.viewFromShort(e.from.toString(!1,!0)),this.dkimData(e.dkim[0]||["none","",""]),this.nowTracking(!1)):(Pi.selectedMessage(null),this.viewHash="",this.scrollMessageToTop())},showFullInfo:e=>Hi(9,e?"1":"0")}),this.replyCommand=t(it.Reply),this.replyAllCommand=t(it.ReplyAll),this.forwardCommand=t(it.Forward),this.forwardAsAttachmentCommand=t(it.ForwardAsAttachment),this.editAsNewCommand=t(it.EditAsNew),this.deleteCommand=(()=>e((()=>{if(rs===ns.trashFolder())$r(lt);else{const e=jr();e&&(jr(null),rl.app.moveMessagesToFolderType(et.Trash,e.folder,new Set([e.uid])))}}),this.messageVisible))(),this.undeleteCommand=(t=>e((()=>$r(t)),this.messageVisible))(ct),this.deleteWithoutMoveCommand=s(et.Trash,!0),this.archiveCommand=s(et.Archive),this.spamCommand=s(et.Junk),this.notSpamCommand=s(et.Inbox),Ls(this,{editCommand:e=>e.messageVisible(),moveCommand:e=>e.messageVisible(),copyCommand:e=>e.messageVisible(),goUpCommand:e=>!e.messageListOrViewLoading(),goDownCommand:e=>!e.messageListOrViewLoading()})}toggleFullInfo(){this.showFullInfo(!this.showFullInfo())}closeMessage(){jr(null)}editCommand(){jr()&&gr([it.Draft,jr()])}moveOrCopy(e,s,i){e&&s?.preventDefault&&_(s),this.actionsMenu().ddBtn.hide(),xs.focusedState(t),nr(i)}moveCommand(e,t){this.moveOrCopy(e,t,1)}copyCommand(e,t){this.moveOrCopy(e,t,2)}setUnseen(){$r(at),jr(null)}goUpCommand(){O("mailbox.message-list.selector.go-up",!!jr())}goDownCommand(){O("mailbox.message-list.selector.go-down",!!jr())}replyOrforward(e){gr([e,jr()])}onBuild(t){const i=(e,s)=>e.target.closestWithin(s,t);t.addEventListener("click",(e=>{let t=i(e,"a");if(t&&0===e.button&&pr(t.href))_(e);else if(t=i(e,".attachmentsPlace .showPreview"),t){const s=ko.dataFor(t),i=s?.linkDownload();i&&Le==s.mimeType&&(_(e),Wr(i).then((e=>{const t=new MessageModel;oi(e,t),t.popupMessage()})))}else if(t=i(e,".attachmentsPlace .showPreplay"),t){_(e);const s=ko.dataFor(t);if(s&&fs.supported)switch(!0){case fs.supportedMp3&&s.isMp3():fs.playMp3(s.linkDownload(),s.fileName);break;case fs.supportedOgg&&s.isOgg():fs.playOgg(s.linkDownload(),s.fileName);break;case fs.supportedWav&&s.isWav():fs.playWav(s.linkDownload(),s.fileName)}}else{if(t=i(e,".attachmentItem"),t){const e=ko.dataFor(t),s=e?.linkDownload();s&&("application/pgp-keys"==e.mimeType&&(ti.isSupported()||Hs.isSupported())?Wr(s).then((e=>Fs(OpenPgpImportPopupView,[e]))):hr(s,e.fileName))}i(e,".messageItemHeader .subjectParent .flagParent")&&$r(jr()?.isFlagged()?nt:ot)}})),H.subscribe((e=>this.messageDomFocused(s===e))),V("escape","",s,(()=>{if(!this.viewModelDom.hidden&&jr()){const t=ft.usePreviewPane();return mi()?(ui(),t&&xs.focusedState(e)):t?xs.focusedState(e):jr(null),!1}})),V("enter,open","",s,(()=>(mi()||pi(),!1))),K("r,mailreply","",[e,s],(()=>!jr()||(this.replyCommand(),!1))),K("a","",[e,s],(()=>{if(jr())return this.replyAllCommand(),!1})),K("mailreply","shift",[e,s],(()=>{if(jr())return this.replyAllCommand(),!1})),K("f,mailforward","",[e,s],(()=>{if(jr())return this.forwardCommand(),!1})),K("i","meta",[e,s],(()=>(jr()&&this.toggleFullInfo(),!1))),K("b","",[e,s],(()=>{const e=jr();if(e?.body)return e.body.querySelectorAll("details").forEach((e=>e.open=!e.open)),!1})),V("b","shift",[e,s],(()=>(jr()?.swapColors?.(),!1))),V("arrowup,arrowleft","meta",[e,s],(()=>(this.goUpCommand(),!1))),V("arrowdown,arrowright","meta",[e,s],(()=>(this.goDownCommand(),!1))),V("delete","",s,(()=>(this.deleteCommand(),!1))),V("delete","shift",s,(()=>(this.deleteWithoutMoveCommand(),!1))),V("arrowleft","",s,(()=>{if(!mi()&&jr()&&ft.usePreviewPane()&&!Gr().scrollLeft)return xs.focusedState(e),!1})),V("tab","shift",s,(()=>(!mi()&&jr()&&ft.usePreviewPane()&&xs.focusedState(e),!1))),gi.bodiesDom(t.querySelector(".bodyText"))}scrollMessageToTop(){Gr().scrollTop=0}scrollMessageToLeft(){Gr().scrollLeft=0}toggleAttachmentControls(){const e=!this.showAttachmentControls();this.showAttachmentControls(e),Hi(10,e)}downloadAsZip(){const e=(jr()?.attachments||[]).map((e=>e?.checked()?e.download:"")).filter((e=>e));ur(jr().subject(),e,(()=>this.downloadAsZipError(!0)),this.downloadAsZipLoading)}showImages(){jr().showExternalImages()}showTracking(){const e=jr(),t=e?.body;if(t&&e.hasTracking()){let e="data-x-href-tracking";t.querySelectorAll("a["+e+"]").forEach((t=>t.href=t.getAttribute(e))),this.nowTracking(!0)}}whitelistText(e){let t=(ft.viewImagesWhitelist().trim()+"\n"+e).trim();ft.viewImagesWhitelist(t),Vs.saveSetting("ViewImagesWhitelist",t),jr().showExternalImages(1)}printableCheckedMessageCount(){const e=Pi.listCheckedOrSelectedUidsWithSubMails().size;return 0e?e:"99+":""}readReceipt(){let e=jr();e.readReceipt&&(e.flags.push("$mdnsent"),Vs.request("SendReadReceiptMessage",(t=>t&&e.flags.remove("$mdnsent")),{messageFolder:e.folder,messageUid:e.uid,readReceipt:e.readReceipt,subject:he("READ_RECEIPT/SUBJECT",{SUBJECT:e.subject()}),plain:he("READ_RECEIPT/BODY",{"READ-RECEIPT":fi.email()})}))}newTag(){let e=jr();if(e){let t=prompt(he("MESSAGE/NEW_TAG"),"")?.replace(/[\s\\]+/g,"");t.length&&os(t)&&(e.toggleTag(t),ns.currentFolder().permanentFlags.push(t))}}pgpDecrypt(){const e=jr(),t=e.pgpEncrypted();delete t.error,ai.decrypt(e).then((t=>{if(!t)throw Error("Decryption failed, canceled or not possible");e.pgpDecrypted(!0),t.data&&(oi(t.data,e),e.html()?e.viewHtml():e.viewPlain(),t.signatures?.length&&e.pgpSigned({signatures:t.signatures,success:!!t.signatures.length}))})).catch((e=>{t.error=e.message})).finally((()=>{e.pgpEncrypted(t)}))}pgpVerify(){const e=jr();ai.verify(e).then((t=>{t?e.pgpSigned(t):alert("Verification failed or no valid public key found")}))}async smimeDecrypt(){const e=jr(),t=e.from.concat(e.to,e.cc,e.bcc).map((e=>e.email)),s=or.find((e=>t.includes(e.email()))),i=e.smimeEncrypted();if(i&&s){delete i.error;let t,r={...i};if(r.folder=e.folder,r.uid=e.uid,r.certificate=s.smimeCertificate(),r.privateKey=s.smimeKey(),s.smimeKeyEncrypted()){if(t=await Ks.ask(s,he("SMIME/PRIVATE_KEY_OF",{EMAIL:s.email()}),"CRYPTO/DECRYPT"),!t)return;r.passphrase=t?.password}Vs.post("SMimeDecryptMessage",null,r).then((i=>{i?.Result?.data&&(e.smimeDecrypted(!0),oi(i.Result.data,e),e.html()?e.viewHtml():e.viewPlain(),t&&t.remember&&Ks.handle(s,t.password),"signed"in i.Result&&e.smimeSigned(i.Result.signed))})).catch((e=>{i.error=e.message})).finally((()=>{e.smimeEncrypted(i)}))}}smimeVerify(){const e=jr(),t=e.smimeSigned();if(t){const s={...t};s.folder=e.folder,s.uid=e.uid,s.bodyPart=t.bodyPart?.raw,s.sigPart=t.sigPart?.bodyRaw,Vs.post("SMimeVerifyMessage",null,s).then((s=>{s?.Result&&(s.Result.body&&(oi(s.Result.body,e),e.html()?e.viewHtml():e.viewPlain()),t.success=s.Result.success,e.smimeSigned(t))}))}}}class MailBoxUserScreen extends AbstractScreen{constructor(){var e=D("style");k.head.appendChild(e),fe((()=>e.innerText='.subjectParent:empty::after,.subjectParent .subject:empty::after{content:"'+he("MESSAGE/EMPTY_SUBJECT_TEXT")+'"}')),super("mailbox",[SystemDropDownUserView,MailFolderList,MailMessageList,MailMessageView])}updateWindowTitle(){const e=M.app("listPermanentFiltered")?0:ns.foldersInboxUnreadCount(),t=fi.email();rl.setTitle((t?(0t?1:t),Pi.listSearch(s),i){let t=new MessageModel;t.folder=e,t.uid=i,yr(t)}else{let t=e.replace(/^.+~(\d+)$/,"$1");Pi.threadUid(e===t?0:f(t))}Pi.reload()}}onStart(){super.onStart(),addEventListener("mailbox.inbox-unread-count",(e=>{ns.foldersInboxUnreadCount(e.detail),this.updateWindowTitle()}))}onBuild(){k.addEventListener("click",(e=>e.target.closest("#rl-right")&&nr(0)))}routes(){const e=(e,t)=>e?m(t[0]):Qt(),t=(t,s)=>[e(t,s),t?f(s[1]):1,decodeURI(m(s[2]))];return[[/^([^/]*)$/,{normalize_:t}],[/^([a-zA-Z0-9.~_-]+)\/(.+)\/?$/,{normalize_:(t,s)=>[e(t,s),1,decodeURI(m(s[1]))]}],[/^([a-zA-Z0-9.~_-]+)\/m([1-9][0-9]*)(?:\/(.+))?$/,{normalize_:(t,s)=>[e(t,s),1,m(s[2]),m(s[1])]}],[/^([a-zA-Z0-9.~_-]+)\/p([1-9][0-9]*)(?:\/(.+))?$/,{normalize_:t}]]}}const Jr=[];class AbstractSettingsScreen extends AbstractScreen{constructor(e){super("settings",e),this.menu=ko.observableArray(),this.oCurrentSubScreen=null}onRoute(e){let t=null,s=null,i=Jr.find((t=>e===t.route));if(i){const e=this.viewModels[1].__vm.viewModelDom,r=i.vmc;r.__vm?(t=r.__vm,s=t.viewModelDom):e&&(s=D("div",{id:"V-Settings-"+r.name.replace(/(User|Admin)Settings/,""),hidden:""}),e.append(s),t=new r,t.viewModelDom=s,t.viewModelTemplateID=i.template,r.__vm=t,O("rl-view-model.create",t),ko.applyBindingAccessorsToNode(s,{template:()=>({name:i.template})},t),t.onBuild?.(s),O("rl-view-model",t)),t&&setTimeout((()=>{this.onHide(),this.oCurrentSubScreen=t,t.beforeShow?.(),ue(s),s.hidden=!1,t.onShow?.(),this.menu.forEach((e=>{e.selected(e.route===i.route)})),(e||{}).scrollTop=0}),1)}else hasher.replaceHash(se())}onHide(){let e=this.oCurrentSubScreen;e&&(e.onHide?.(),e.viewModelDom.hidden=!0)}onBuild(){Jr.forEach((e=>this.menu.push(e)))}routes(){const e=Jr.find((e=>e.isDefault)),t=e?.route||"general",s={subname:/^(.*)$/,normalize_:(e,s)=>(s.subname=m(s.subname??t),[s.subname])};return[["{subname}/",s],["{subname}",s],["",s]]}}function zr(e,t,s,i,r=!1){let a=e.name.replace(/(User|Admin)Settings/,"");Jr.push({vmc:e,label:s||"SETTINGS_LABELS/"+a.toUpperCase(),route:i||a.toLowerCase(),selected:ko.observable(!1),template:t||e.name,isDefault:!!r})}const Yr=[],Zr=[];rl.pluginRemoteRequest=(e,t,s,i)=>{rl.app.Remote.request("Plugin"+t,e,s,i)},rl.addSettingsViewModel=(e,t,s,i)=>{Yr.push([e,t,s,i])},rl.addSettingsViewModelForAdmin=(e,t,s,i)=>{Zr.push([e,t,s,i])},rl.pluginSettingsGet=(e,t)=>F("Plugins")?.[e]?.[t],rl.pluginPopupView=AbstractViewPopup;class UserSettingsGeneral extends AbstractViewSettings{constructor(){super(),this.mailto=ko.observable(!!navigator.registerProtocolHandler),this.language=re.language,this.languages=re.languages,this.hourCycle=re.hourCycle,this.soundNotification=fs.notifications,this.notificationSound=ko.observable(F("NotificationSound")),this.notificationSounds=ko.observableArray(F("newMailSounds")),this.desktopNotifications=Ci.enabled,this.isDesktopNotificationAllowed=Ci.allowed,this.threadsAllowed=xs.threadsAllowed,this.threadAlgorithms=ko.observableArray(),ns.capabilities.forEach((e=>e.startsWith("THREAD=")&&this.threadAlgorithms.push(e.slice(7)))),this.threadAlgorithms.sort(((e,t)=>e.length-t.length)),this.threadAlgorithm=ft.threadAlgorithm,["useThreads","threadAlgorithm","layout","messageReadDelay","messagesPerPage","checkMailInterval","editorDefaultType","editorWysiwyg","msgDefaultAction","maxBlockquotesLevel","requestReadReceipt","requestDsn","requireTLS","pgpSign","pgpEncrypt","viewHTML","viewImages","viewImagesWhitelist","removeColors","allowStyles","allowDraftAutosave","hideDeleted","listInlineAttachments","simpleAttachmentsList","collapseBlockquotes","useCheckboxesInList","listGrouped","replySameFolder","allowSpellcheck","messageReadAuto","showNextMessage","messageNewWindow"].forEach((e=>this[e]=ft[e])),this.allowLanguagesOnSettings=!!F("allowLanguagesOnSettings"),this.languageTrigger=ko.observable(o),this.identities=or,this.wysiwygs=bt,Ae(this,{languageFullName:()=>ve(this.language()),identityMainDesc:()=>{const e=or.main();return e?e.formattedName():"---"},editorDefaultTypes:()=>(ce(),[{id:"Html",name:he("SETTINGS_GENERAL/EDITOR_HTML")},{id:"Plain",name:he("SETTINGS_GENERAL/EDITOR_PLAIN")}]),hasWysiwygs:()=>1(ce(),[{id:1,name:he("MESSAGE/BUTTON_REPLY")},{id:2,name:he("MESSAGE/BUTTON_REPLY_ALL")}]),layoutTypes:()=>(ce(),[{id:0,name:he("SETTINGS_GENERAL/LAYOUT_NO_SPLIT")},{id:1,name:he("SETTINGS_GENERAL/LAYOUT_VERTICAL_SPLIT")},{id:2,name:he("SETTINGS_GENERAL/LAYOUT_HORIZONTAL_SPLIT")}])}),this.addSetting("EditorDefaultType"),this.addSetting("editorWysiwyg"),this.addSetting("MsgDefaultAction"),this.addSetting("MessageReadDelay"),this.addSetting("MessagesPerPage"),this.addSetting("CheckMailInterval"),this.addSetting("Layout"),this.addSetting("MaxBlockquotesLevel"),this.addSettings(["requestReadReceipt","requestDsn","requireTLS","pgpSign","pgpEncrypt","ViewHTML","ViewImages","ViewImagesWhitelist","RemoveColors","AllowStyles","AllowDraftAutosave","HideDeleted","ListInlineAttachments","simpleAttachmentsList","CollapseBlockquotes","UseCheckboxesInList","listGrouped","ReplySameFolder","allowSpellcheck","messageReadAuto","showNextMessage","messageNewWindow","DesktopNotifications","SoundNotification"]);const e=e=>()=>{this.languageTrigger(e),setTimeout((()=>this.languageTrigger(o)),1e3)};Te(this,{language:t=>{this.languageTrigger(a),Se(t).then(e(n),e(l)).then((()=>Vs.saveSetting("language",t)))},hourCycle:e=>Vs.saveSetting("hourCycle",e),notificationSound:e=>{Vs.saveSetting("NotificationSound",e),M.set("NotificationSound",e)},useThreads:e=>{Pi([]),Vs.saveSetting("UseThreads",e)},threadAlgorithm:e=>{Pi([]),Vs.saveSetting("threadAlgorithm",e)},checkMailInterval:()=>{Ni(ft.checkMailInterval())}})}editMainIdentity(){cr(or.main())}testSoundNotification(){fs.playNotification(!0)}testSystemNotification(){Ci.display("SnappyMail","Test notification")}selectLanguage(){Fs(LanguagesPopupView,[this.language,this.languages(),re.userLanguage()])}registerMailto(){navigator.registerProtocolHandler("mailto",`${location.protocol}//${location.host}${location.pathname}?mailto&to=%s`,F("title")||"SnappyMail"),alert(he("GLOBAL/DONE")),this.mailto(0)}}class UserSettingsContacts{constructor(){this.contactsAutosave=ko.observable(!!F("ContactsAutosave")),this.allowContactsSync=Sr.allowSync,this.syncMode=Sr.syncMode,this.syncUrl=Sr.syncUrl,this.syncUser=Sr.syncUser,this.syncPass=Sr.syncPass,this.syncModeOptions=ke((()=>(ce(),[{id:0,name:he("GLOBAL/NO")},{id:1,name:he("GLOBAL/YES")},{id:2,name:he("SETTINGS_CONTACTS/SYNC_READ")}]))),this.saveTrigger=ke((()=>[Sr.syncMode(),Sr.syncUrl(),Sr.syncUser(),Sr.syncPass()].join("|"))).extend({debounce:500}),this.contactsAutosave.subscribe((e=>Vs.saveSettings(null,{ContactsAutosave:e}))),this.saveTrigger.subscribe((()=>Vs.request("SaveContactsSyncData",null,{Mode:Sr.syncMode(),Url:Sr.syncUrl(),User:Sr.syncUser(),Password:Sr.syncPass()})))}}class UserSettingsAccounts{constructor(){this.allowAdditionalAccount=I("AdditionalAccounts"),this.allowIdentities=I("Identities"),this.accounts=fi,this.loading=fi.loading,this.identities=or,this.mainEmail=F("mainEmail"),this.accountForDeletion=ko.observable(null).askDeleteHelper(),this.identityForDeletion=ko.observable(null).askDeleteHelper(),this.showUnread=ft.showUnreadCount,ft.showUnreadCount.subscribe((e=>Vs.saveSetting("ShowUnreadCount",e)))}addNewAccount(){Fs(AccountPopupView)}editAccount(e){e?.isAdditional()&&Fs(AccountPopupView,[e])}addNewIdentity(){cr()}editIdentity(e){cr(e)}deleteAccount(e){e?.askDelete()&&(this.accountForDeletion(null),this.accounts.remove((t=>e===t)),Vs.request("AccountDelete",((e,t)=>{!e&&t.Reload?(rl.route.root(),setTimeout((()=>location.reload()),1)):dr()}),{emailToDelete:e.email}))}deleteIdentity(e){e?.askDelete()&&(this.identityForDeletion(null),or.remove((t=>e===t)),Vs.request("IdentityDelete",(()=>rl.app.accountsAndIdentities()),{idToDelete:e.id()}))}accountsAndIdentitiesAfterMove(){Vs.request("AccountsAndIdentitiesSortOrder",null,{Accounts:fi.filter((e=>e.isAdditional())).map((e=>e.email)),Identities:or.map((e=>e?e.id():""))})}onBuild(e){e.addEventListener("click",(t=>{let s=t.target.closestWithin(".accounts-list .e-action",e);s&&ko.dataFor(s)&&this.editAccount(ko.dataFor(s)),s=t.target.closestWithin(".identities-list .e-action",e),s&&ko.dataFor(s)&&this.editIdentity(ko.dataFor(s))}))}}class UserSettingsFilters{constructor(){this.scripts=ko.observableArray(),this.loading=ko.observable(!0).extend({debounce:200}),Ce(this,{serverError:!1,serverErrorDesc:""}),rl.loadScript(F("StaticLibsJs").replace("/libs.","/sieve.")).then((()=>{const e=window.Sieve;e.folderList=ns.folderList,e.serverError.subscribe((e=>this.serverError(e))),e.serverErrorDesc.subscribe((e=>this.serverErrorDesc(e))),e.loading.subscribe((e=>this.loading(e))),e.scripts.subscribe((e=>this.scripts(e))),e.updateList()})).catch((e=>{})),this.hasActive=ke((()=>this.scripts().filter((e=>e.active())).length)),this.scriptForDeletion=ko.observable(null).askDeleteHelper()}addScript(){this.editScript()}editScript(e){window.Sieve.ScriptView.showModal(e?[e]:null)}deleteScript(e){window.Sieve.deleteScript(e)}disableScripts(){window.Sieve.setActiveScript("")}enableScript(e){window.Sieve.setActiveScript(e.name())}onBuild(e){e.addEventListener("click",(t=>{const s=t.target.closestWithin(".script-item .script-name",e),i=s&&ko.dataFor(s);i&&this.editScript(i)}))}onShow(){window.Sieve?.updateList()}}class OpenPgpGeneratePopupView extends AbstractViewPopup{constructor(){super("OpenPgpGenerate"),this.identities=or,Ce(this,{email:"",emailError:!1,name:"",password:"",keyType:"ECC",submitRequest:!1,submitError:"",backupPublicKey:!0,backupPrivateKey:!1,saveGnuPGPublic:!0,saveGnuPGPrivate:!1}),this.canGnuPG=I("GnuPG"),this.email.subscribe((()=>this.emailError(!1)))}submitForm(){const e={type:this.keyType().toLowerCase(),userIDs:[{name:this.name(),email:IDN.toASCII(this.email())}],passphrase:this.password().trim()};this.emailError(!this.email().trim()),this.emailError()||(this.submitRequest(!0),this.submitError(""),openpgp.generateKey(e).then((e=>{if(e){const t=()=>{this.submitRequest(!1),this.close()};ti.storeKeyPair(e),e.onServer=(this.backupPublicKey()?1:0)+(this.backupPrivateKey()?2:0),e.inGnuPG=(this.saveGnuPGPublic()?1:0)+(this.saveGnuPGPrivate()?2:0),e.onServer||e.inGnuPG?(this.backupPrivateKey()||this.saveGnuPGPrivate()||delete e.privateKey,Hs.storeKeyPair(e,t)):t()}})).catch((e=>{this.submitRequest(!1),this.showError(e)})))}hideError(){this.submitError("")}showError(e){e?.message&&this.submitError(e.message)}onShow(){this.name(""),this.password(""),this.email(""),this.emailError(!1),this.submitError("")}}class SMimeImportPopupView extends AbstractViewPopup{constructor(){super("SMimeImport"),Ce(this,{pem:"",pemError:!1,pemErrorMessage:"",pemValid:!1}),this.pem.subscribe((e=>{this.pemError(!1),this.pemErrorMessage(""),this.pemValid(e&&e.includes("-----BEGIN CERTIFICATE-----"))}))}submitForm(){this.pemValid()?Vs.request("SMimeImportCertificate",((e,t)=>{e?(this.pemError(!0),this.pemErrorMessage(be(e,t?.ErrorMessage))):this.close()}),{pem:this.pem()}):this.pemError(!0)}onShow(){this.pem(""),this.pemError(!1),this.pemErrorMessage("")}}class UserSettingsSecurity extends AbstractViewSettings{constructor(){super(),this.autoLogout=ft.autoLogout,this.autoLogoutOptions=ke((()=>(ce(),[{id:0,name:he("SETTINGS_SECURITY/NEVER")},{id:5,name:de(300)},{id:15,name:de(900)},{id:30,name:de(1800)},{id:60,name:de(3600)},{id:120,name:de(7200)},{id:300,name:de(18e3)},{id:600,name:de(36e3)}]))),this.addSetting("AutoLogout"),this.keyPassForget=ft.keyPassForget,this.addSetting("keyPassForget"),this.gnupgPublicKeys=Hs.publicKeys,this.gnupgPrivateKeys=Hs.privateKeys,this.openpgpkeysPublic=ti.publicKeys,this.openpgpkeysPrivate=ti.privateKeys,this.smimeCertificates=vr,this.canOpenPGP=I("OpenPGP"),this.canGnuPG=Hs.isSupported(),this.canMailvelope=!!window.mailvelope}addOpenPgpKey(){Fs(OpenPgpImportPopupView)}generateOpenPgpKey(){Fs(OpenPgpGeneratePopupView)}importToOpenPGP(){ti.loadBackupKeys()}importToSMime(){Fs(SMimeImportPopupView)}onBuild(){window.mailvelope&&mailvelope.createSettingsContainer("#mailvelope-settings")}}const Xr=ko.observable(null).askDeleteHelper();class UserSettingsFolders{constructor(){this.showKolab=ns.allowKolab(),this.defaultOptionsAfterRender=b,this.kolabTypeOptions=ko.observableArray();let e=e=>he("SETTINGS_FOLDERS/TYPE_"+e);fe((()=>{this.kolabTypeOptions([{id:"",name:""},{id:"event",name:e("CALENDAR")},{id:"contact",name:e("CONTACTS")},{id:"task",name:e("TASKS")},{id:"note",name:e("NOTES")},{id:"file",name:e("FILES")},{id:"journal",name:e("JOURNAL")},{id:"configuration",name:e("CONFIGURATION")}])})),this.displaySpecSetting=ns.displaySpecSetting,this.folderList=ns.folderList,this.folderListOptimized=ns.optimized,this.folderListError=ns.error,this.hideUnsubscribed=ft.hideUnsubscribed,this.unhideKolabFolders=ft.unhideKolabFolders,this.loading=ns.foldersChanging,this.folderForDeletion=Xr,ft.hideUnsubscribed.subscribe((e=>Vs.saveSetting("HideUnsubscribed",e))),ft.unhideKolabFolders.subscribe((e=>Vs.saveSetting("UnhideKolabFolders",e)))}onShow(){ns.error("")}createFolder(){Fs(FolderCreatePopupView)}systemFolder(){Fs(FolderSystemPopupView)}deleteFolder(e){e&&e.canBeDeleted()&&e.askDelete()&&(0{if(e.selectable(!1),!e.subFolders.length){is(e.fullName);const t=ss(e.parentName);(t?t.subFolders:ns.folderList).remove(e)}}),(e=>{ns.error(be(e.code,"",c.CantDeleteFolder)+".\n"+e.message)}))))}hideError(){ns.error("")}toggleFolderKolabType(e,t){let s=t.target.value;Vs.request("FolderSetMetadata",null,{folder:e.fullName,key:tt,value:s}),e.kolabType(s)}toggleFolderSubscription(e){let t=!e.isSubscribed();Vs.request("FolderSubscribe",null,{folder:e.fullName,subscribe:t?1:0}),e.isSubscribed(t)}toggleFolderCheckable(e){let t=!e.checkable();Vs.request("FolderCheckable",null,{folder:e.fullName,checkable:t?1:0}),e.checkable(t)}}const Qr={name:ut.userBackgroundName,hash:ut.userBackgroundHash};Ce(Qr,{uploaderButton:null,loading:!1,error:""});class UserSettingsThemes{constructor(){this.fontSansSerif=ut.fontSansSerif,this.fontSerif=ut.fontSerif,this.fontMono=ut.fontMono,Te(ut,{fontSansSerif:e=>{Vs.saveSettings(null,{fontSansSerif:e})},fontSerif:e=>{Vs.saveSettings(null,{fontSerif:e})},fontMono:e=>{Vs.saveSettings(null,{fontMono:e})}}),this.theme=ut.theme,this.themes=ut.themes,this.themesObjects=ko.observableArray(),Qr.enabled=I("UserBackground"),this.background=Qr,this.themeTrigger=ko.observable(o).extend({debounce:100}),ut.theme.subscribe((e=>{this.themesObjects.forEach((t=>t.selected(e===t.name))),pt(e,this.themeTrigger),Vs.saveSettings(null,{Theme:e})}))}setTheme(e){ut.theme(e.name)}onBuild(){const e=ut.theme();if(this.themesObjects(ut.themes.map((t=>({name:t,nameDisplay:gt(t),selected:ko.observable(t===e),themePreviewSrc:te(t)})))),Qr.uploaderButton()&&Qr.enabled){new Jua({action:Q("UploadBackground"),limit:1,clickElement:Qr.uploaderButton()}).on("onStart",(()=>{Qr.loading(!0),Qr.error("")})).on("onComplete",((e,t,s)=>{if(Qr.loading(!1),Qr.name(s?.Result?.name||""),Qr.hash(s?.Result?.hash||""),!Qr.name()||!Qr.hash()){let e="";if(s.ErrorCode)switch(s.ErrorCode){case r.FileIsTooBig:e=he("SETTINGS_THEMES/ERROR_FILE_IS_TOO_BIG");break;case r.FileType:e=he("SETTINGS_THEMES/ERROR_FILE_TYPE_ERROR")}Qr.error(e||s.ErrorMessage||he("SETTINGS_THEMES/ERROR_UNKNOWN"))}}))}}onShow(){Qr.error("")}clearBackground(){Qr.enabled&&Vs.request("ClearUserBackground",(()=>{Qr.name(""),Qr.hash("")}))}}class SettingsMenuUserView extends AbstractViewLeft{constructor(e){super(),this.menu=e.menu}link(e){return se(e)}backToInbox(){hasher.setHash(((e="INBOX")=>"#/mailbox/"+e)(Qt()))}}class SettingsPaneUserView extends AbstractViewRight{constructor(){super()}onShow(){gi.message(null)}onBuild(e){e.addEventListener("click",(()=>{event.target.closestWithin(".toggleLeft",e)?R():ut.isMobile()&&N(!0)}))}}class SettingsUserScreen extends AbstractSettingsScreen{constructor(){super([SettingsMenuUserView,SettingsPaneUserView,SystemDropDownUserView]);const e=[UserSettingsGeneral];xs.allowContacts()&&e.push(UserSettingsContacts),(I("AdditionalAccounts")||I("Identities"))&&e.push(UserSettingsAccounts),I("Sieve")&&e.push(UserSettingsFilters),e.push(UserSettingsSecurity),e.push(UserSettingsFolders),I("Themes")&&e.push(UserSettingsThemes),e.forEach(((e,t)=>zr(e,e.name.replace("User",""),e!==UserSettingsAccounts||I("AdditionalAccounts")?0:"SETTINGS_ACCOUNTS/LEGEND_IDENTITIES",0,0===t))),(!1?Zr:Yr).forEach((e=>zr(...e))),fe((()=>this.sSettingsTitle=he("TITLES/SETTINGS")),(()=>this.setSettingsTitle()))}onShow(){this.setSettingsTitle(),G(i)}setSettingsTitle(){const e=fi.email();rl.setTitle((e?e+" - ":"")+this.sSettingsTitle)}}class SelectComponent{constructor(e){this.value=e.value,this.label=e.label,this.trigger=e.trigger?.subscribe?e.trigger:null,this.placeholder=e.placeholder,this.options=e.options,this.optionsText=e.optionsText,this.optionsValue=e.optionsValue;let t=0{switch(t){case n:e("success");break;case l:e("error");break;default:e("")}};s(this.trigger()),this.className=ke((()=>(t+" settings-save-trigger-input "+e()).trim())),this.disposables=[this.trigger.subscribe(s,this),this.className]}else this.className=t;this.defaultOptionsAfterRender=b}dispose(){this.disposables?.forEach(Me)}}class CheckboxComponent{constructor(e={}){this.name=e.name,this.value=ko.isObservable(e.value)?e.value:ko.observable(!!e.value),this.enable=ko.isObservable(e.enable)?e.enable:ko.observable(e.enable??1),this.label=e.label}click(){this.enable()&&this.value(!this.value())}}class AbstractApp{constructor(e){this.Remote=e}logoutReload(e){Ps(!1),e=e||(W()?J():j),location.href!==e?setTimeout((()=>location.href=e),100):rl.route.reload()}bootstart(){const e=(e,t)=>ko.components.register(e,{template:{element:t.name},viewModel:{createViewModel:(e,s)=>(e=e||{},ue(s.element),new t(e))}});e("Select",SelectComponent),e("Checkbox",CheckboxComponent),fe(),re.populate(),mt(),this.start()}}var ea;AskPopupView.password=function(e,t,s){return new Promise((i=>{this.showModal([e,e=>i({password:e.passphrase(),username:e.username(),remember:e.remember()}),()=>i(null),!0,s||1,t])}))},AskPopupView.cryptkey=()=>new Promise((e=>{const t=()=>AskPopupView.showModal([he("CRYPTO/ASK_CRYPTKEY_PASS"),s=>{let i=s.passphrase();i?Vs.post("ResealCryptKey",null,{passphrase:i}).then((t=>{e(t?.Result)})).catch((s=>{111===s.code?t():e(null)})):e(null)},()=>e(null),!0,1,he("CRYPTO/DECRYPT")]);t()})),ea=new class AppUser extends AbstractApp{constructor(){super(Vs);const e=36e5;let t=Date.now();setInterval((()=>{const s=Date.now();s>t+e+1e3&&Vs.request("Version",(e=>100C.toggle("rl-ctrl-key-pressed",e.ctrlKey)).debounce(500)),V("escape,enter","",lr),addEventListener("click",lr),this.folderList=ns.folderList,this.messageList=Pi,this.ask=AskPopupView,this.loadAccountsAndIdentities=dr}moveMessagesToFolderType(e,t,s,i){let r=null,a=0;switch(e){case et.Junk:r=ss(ns.spamFolder()),a=e,i=i||rs===ns.spamFolder();break;case et.Inbox:r=ss(Qt());break;case et.Trash:r=ss(ns.trashFolder()),a=e,i=i||t===ns.spamFolder()||t===ns.trashFolder();break;case et.Archive:r=ss(ns.archiveFolder()),a=e,i=i||rs===ns.archiveFolder()}i?Fs(AskPopupView,[he("POPUPS_ASK/DESC_WANT_DELETE_MESSAGES"),()=>{Pi.moveMessages(t,s)}]):r?Pi.moveMessages(t,s,r.fullName):Fs(FolderSystemPopupView,[a])}folderInformation(e,t){Oi(e,t)}logout(){Vs.request("Logout",(()=>rl.logoutReload(M.app("customLogoutLink"))))}bootstart(){super.bootstart(),addEventListener("beforeunload",(e=>{if(Ps()||!ft.usePreviewPane()&&gi.message())return e.preventDefault(),e.returnValue=he("POPUPS_ASK/EXIT_ARE_YOU_SURE")}),{capture:!0})}refresh(){mt(),re.language(F("language")),this.start()}start(){F("Auth")?(rl.setTitle(he("GLOBAL/LOADING")),fs.notifications(!!F("SoundNotification")),Ci.enabled(!!F("DesktopNotifications")),fi.email(F("Email")),ft.init(),Sr.init(),Zi((e=>{try{e?(Is([MailBoxUserScreen,SettingsUserScreen]),Ni(f(F("CheckMailInterval"))),dr(),setTimeout((()=>{const e=ns.currentFolderFullName();Qt()===e||Oi(e),ns.hasCapability("LIST-STATUS")||_i(!0)}),1e3),setTimeout((()=>Vs.request("AppDelayStart")),35e3),q(k,["touchstart","mousemove","keydown"],ft.delayLogout,{passive:!0}),ft.delayLogout(),setTimeout((()=>{const e=A("rl-left"),t=()=>fr(e,4,ut.isMobile()||N()?0:"Width");e&&(t(),N.subscribe(t))}),1),setInterval(ge,6e4),ai.init(),vr.loadCertificates(),setTimeout((()=>pr(F("mailToEmail"))),500)):this.logout()}catch(e){}}))):Is([LoginUserScreen])}showMessageComposer(e=[]){Fs(ComposePopupView,e)}},rl.app=ea,rl.logoutReload=ea.logoutReload,rl.i18n=he,rl.Enums={StorageResultType:{Success:0,Error:1,Abort:2}},rl.route={root:()=>{rl.route.off(),hasher.setHash($)},reload:()=>{rl.route.root(),setTimeout((()=>location.reload()),100)},off:()=>hasher.active=!1,on:()=>hasher.active=!0}}();