File manager - Edit - /usr/local/CyberCP/public/snappymail/snappymail/v/2.38.2/static/js/min/app.min.js
Back
!function(){"use strict";const e="MessageList",t="FolderList",s="MessageView",i="Settings",r={Normal:0,FileIsTooBig:1,FilePartiallyUploaded:3,NoFileUploaded:4,MissingTempFolder:6,OnSavingFile:7,FileType:98,Unknown:99},a=-2,o=-1,n=1,l=0,c={RequestError:1,RequestAborted:2,RequestTimeout:3,InvalidToken:101,AuthError:102,ConnectionError:104,DomainNotAllowed:109,AccountNotAllowed:110,CryptKeyError:111,ContactsSyncError:140,CantGetMessageList:201,CantGetMessage:202,CantDeleteMessage:203,CantMoveMessage:204,CantCopyMessage:205,CantSaveMessage:301,CantSendMessage:302,InvalidRecipients:303,CantSaveFilters:351,CantGetFilters:352,CantActivateFiltersScript:353,CantDeleteFiltersScript:354,CantCreateFolder:400,CantRenameFolder:401,CantDeleteFolder:402,CantSubscribeFolder:403,CantUnsubscribeFolder:404,CantDeleteNonEmptyFolder:405,DomainAlreadyExists:601,DemoSendMessageError:750,DemoAccountError:751,AccountAlreadyExists:801,AccountDoesNotExist:802,AccountSwitchFailed:803,MailServerError:901,ClientViewError:902,InvalidInputArgument:903,JsonFalse:950,JsonParse:952,UnknownError:999,CantInstallPackage:701,CantDeletePackage:702,InvalidPluginPackage:703,UnsupportedPluginPackage:704,CantSavePluginSettings:705},d=Array.isArray,h=e=>d(e)&&e.length,u=e=>"function"==typeof e,m=e=>null!=e?""+e:"",p=(e,t)=>Object.values(e).forEach(t),g=(e,t)=>Object.entries(e).forEach((([e,s])=>t(e,s))),f=(e,t=0)=>(e=parseInt(e,10),isFinite(e)?e:t),b=(e,t)=>t&&void 0!==t.disabled&&e?.classList.toggle("disabled",e.disabled=t.disabled),y=e=>btoa(unescape(encodeURIComponent(e))),v=e=>(e=>y(JSON.stringify(e)))(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),S=(e,t)=>Object.keys(e).find((s=>e[s]===t));let w="all";const E="Menu",k=document,C=k.documentElement.classList,A=e=>k.getElementById(e),T=A("rl-app"),F=rl.settings,M=F.get,P=e=>(M("Admin")||{})[e],L=e=>e&&!!(M("Capa")||{})[e],I=[],x=ko.observable(!1).extend({rateLimit:0}),N=ko.observable(!1),R=()=>N(!N()),D=(e,t)=>{let s=k.createElement(e);return t&&Object.entries(t).forEach((([e,t])=>s.setAttribute(e,t))),s},O=(e,t,s)=>dispatchEvent(new CustomEvent(e,{detail:t,cancelable:!!s})),_=e=>{e.preventDefault(),e.stopPropagation()},U=()=>k.activeElement?.matches("input,textarea"),V=(...e)=>shortcuts.add(...e),q=(e,t,s,i)=>V(e,t,s,(e=>!!U()||i(e))),K=(e,t,s,i)=>t.forEach((t=>e.addEventListener(t,s,i))),B=(e,t)=>Object.entries(t).forEach((([t,s])=>e.addEventListener(t,s))),H=ko.observable("all"),G=e=>{if(!e)return w;E!==e&&(w=e,x()&&(e=E)),H(e),shortcuts.setScope(e)};x.subscribe((e=>{e?G(E):E===shortcuts.getScope()&&G(w)})),N.subscribe((e=>C.toggle("rl-left-panel-disabled",e)));const j=k.location.pathname.replace(/\/+$/,"")+"/",W="#/",$=()=>rl.adminArea()&&!P("host"),J=()=>j+"?"+($()?P("path"):""),z="&q[]=",Y=(e,t)=>j+"?/Raw/"+z+"/0/"+(e?e+"/"+(t?z+"/"+t:""):""),Z=e=>Y("Download",e),X=e=>j+"?/ProxyExternal/"+btoa(e.replace(/ /g,"%20")).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),Q=e=>J()+"/"+e+"/"+z+"/0/",ee=e=>F.app("webVersionPath")+"static/"+e,te=e=>{if(e.endsWith("@nextcloud"))return e=e.slice(0,e.length-10).trim(),parent.OC.webroot+"/themes/"+encodeURI(e)+"/snappymail/preview.png";let t="webVersionPath";return e.endsWith("@custom")&&(e=e.slice(0,e.length-7).trim(),t="webPath"),F.app(t)+"themes/"+encodeURI(e)+"/images/preview.png"},se=(e="")=>"#/settings"+(e?"/"+e:""),ie=(e,t,s,i,r)=>{let a=["#/mailbox"];return e&&a.push(e+(i?"~"+i:"")),r?a.push("m"+r):(1<(t=f(t,1))&&a.push("p"+t),s&&a.push(encodeURI(s))),a.join("/")},re={language:ko.observable(""),languages:ko.observableArray(),userLanguage:ko.observable(""),hourCycle:ko.observable(""),populate:function(){const e=F.app("languages");this.languages(d(e)?e:[]),this.language(M("language")),this.userLanguage(M("clientLanguage")),this.hourCycle(M("hourCycle"))}};let ae={};const oe=()=>{if(rl.I18N)return ae=rl.I18N,rl.I18N=null,k.documentElement.dir=ae.LANG_DIR,1},ne=e=>{let t=S(c,e);return t?ae.NOTIFICATIONS[t]:""},le=e=>de(Math.round((e.getTime()-Date.now())/1e3)),ce=ko.observable(!1),de=e=>{let t="second",s=[[60,"minute"],[3600,"hour"],[86400,"day"],[2628e3,"month"],[31536e3,"year"]],i=5,r=Math.abs(e);for(;i--;)if(s[i][0]<=r){e=Math.round(e/s[i][0]),t=s[i][1];break}if(Intl.RelativeTimeFormat)return new Intl.RelativeTimeFormat(k.documentElement.lang).format(e,t);r=Math.abs(e);let a=rl.relativeTime.long[t][0>e?"past":"future"];return(a[rl.relativeTime.plural(r)]||a).replace("{0}",r)},he=(e,t,s)=>{let i=s??e,r=e.split("/");return ae[r[0]]&&r[1]&&(i=ae[r[0]][r[1]]||i),t&&g(t,((e,t)=>{i=i.replace("%"+e+"%",t)})),i},ue=e=>setTimeout((()=>e.querySelectorAll("[data-i18n]").forEach((e=>{const t=e.dataset.i18n;if("["===t[0])switch(t.slice(1,6)){case"html]":e.innerHTML=he(t.slice(6));break;case"place":e.placeholder=he(t.slice(13));break;case"title":e.title=he(t.slice(7))}else e.textContent=he(t)}))),1),me=(e,t)=>{const s=Date.now(),i=0<e?1e3*e:0===e?s:0;if(31536e6<i){const e=new Date(i),r=re.hourCycle();switch(t){case"FROMNOW":return le(e);case"AUTO":{if(144e5>=s-i)return le(e);const t=new Date,a=t.setHours(0,0,0,0);return i>a-864e5?he(i>a?"MESSAGE_LIST/TODAY_AT":"MESSAGE_LIST/YESTERDAY_AT",{TIME:e.format("LT",0,r)}):e.format(t.getFullYear()===e.getFullYear()?{day:"2-digit",month:"short",hour:"numeric",minute:"numeric"}:{dateStyle:"medium",timeStyle:"short"},0,r)}case"FULL":return e.format("LLL",0,r);default:return e.format(t,0,r)}}return""},pe=(e,t)=>{try{t?e.dateTime=new Date(1e3*t).toISOString():t=Date.parse(e.dateTime)/1e3;let s=e.dataset.timeFormat;s&&(e.textContent=me(t,s),"FULL"!==s&&"FROMNOW"!==s&&(e.title=me(t,"FULL")))}catch(e){}},ge=()=>k.querySelectorAll("time").forEach((e=>pe(e))),fe=(e,t)=>{e?.(),e&&ce.subscribe(e),t&&ce.subscribe(t)},be=(e,t="",s=0)=>(e=f(e),c.ClientViewError===e&&t?t:ne(e)||ne(f(s))||""),ye=(e,t)=>be(e)||t?.messageAdditional||t?.message||t,ve=e=>{let t=S(r,parseInt(e,10));return he("UPLOAD/ERROR_"+(t?(e=>e.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase())(t):"UNKNOWN"))},Se=(e,t)=>new Promise(((s,i)=>{const r=D("script");r.onload=()=>{oe()&&(ue(k),ce(!ce())),r.remove(),s()},r.onerror=()=>i(Error("Language "+e+" failed")),r.src=j+"?/Lang/0/"+(t?"Admin":"App")+"/"+encodeURI(e)+"/"+F.app("version")+"/",k.head.append(r)})),we=(e,t=!1)=>he("LANGS_NAMES"+(!0===t?"_EN":"")+"/"+e,null,e),Ee=e=>new Intl.Collator(k.documentElement.lang,{numeric:!!e,sensitivity:"base"});oe();const ke=(e,t)=>t?setTimeout((()=>e.setAttribute("data-rainloopErrorTip",t)),100):e.removeAttribute("data-rainloopErrorTip"),Ce=e=>ko.computed(e,{pure:!0}),Ae=(e,t)=>g(t,((t,s)=>e[t]||(e[t]=ko.observable(s)))),Te=(e,t)=>g(t,((t,s)=>e[t]=Ce(s))),Fe=(e,t)=>g(t,((t,s)=>e[t].subscribe(s))),Me=e=>u(e?.dispose)&&e.dispose(),Pe=(e,t,s)=>{e.addEventListener(t,s),ko.utils.domNodeDisposal.addDisposeCallback(e,(()=>e.removeEventListener(t,s)))},Le=(e,t,s,i,r)=>{Pe(t,"keydown",(t=>{e==t.key&&s().call(r)}))},Ie=e=>((e=ko.observableArray(e)).subscribe((e=>e.forEach((e=>"deleted"===e.status&&null==e.moved&&e.value.onDestroy?.()))),e,"arrayChange"),e);Object.assign(ko.bindingHandlers,{tooltipErrorTip:{init:(e,t)=>{k.addEventListener("click",(()=>{let s=t();ko.isObservable(s)&&!ko.isComputed(s)&&s(""),ke(e)}))},update:(e,t)=>{let s=ko.unwrap(t());ke(e,u(s)?s():s)}},onEnter:{init:(e,t,s,i)=>Le("Enter",e,t,0,i)},onEsc:{init:(e,t,s,i)=>Le("Escape",e,t,0,i)},onSpace:{init:(e,t,s,i)=>Le(" ",e,t,0,i)},toggle:{init:(e,t)=>{let s=t(),i=()=>s(!s());Pe(e,"click",i),Pe(e,"keydown",(e=>" "==e.key&&i()))}},i18nUpdate:{update:(e,t)=>{ko.unwrap(t()),ue(e)}},command:{init:(e,t,s,i,r)=>{const a=t();if(!a||!a.canExecute)throw Error("Value should be a command");ko.bindingHandlers["FORM"==e.nodeName?"submit":"click"].init(e,t,s,i,r)},update:(e,t)=>{let s=!t().canExecute();e.classList.toggle("disabled",s),e.matches("INPUT,TEXTAREA,BUTTON")&&(e.disabled=s)}},saveTrigger:{init:e=>{let t=e;e.matches("input,select,textarea")&&(e.classList.add("settings-save-trigger-input"),e.after(e.saveTriggerIcon=t=D("span"))),t.classList.add("settings-save-trigger")},update:(e,t)=>{const s=parseInt(ko.unwrap(t()),10);let i=(e.saveTriggerIcon||e).classList;e.saveTriggerIcon&&(i.toggle("saving",s===a),i.toggle("success",s===n),i.toggle("error",s===l)),i=e.classList,i.toggle("success",s===n),i.toggle("error",s===l)}}}),ko.extenders.toggleSubscribeProperty=(e,t)=>{const s=t[1];return s&&(e.subscribe((e=>e?.[s]?.(!1)),t[0],"beforeChange"),e.subscribe((e=>e?.[s]?.(!0)),t[0])),e},ko.extenders.falseTimeout=(e,t)=>(e.subscribe((()=>e(!1)).debounce(parseInt(t,10)||0)),e),ko.observable.fn.askDeleteHelper=function(){return this.extend({falseTimeout:3e3,toggleSubscribeProperty:[this,"askDelete"]})};const xe="message/rfc822",Ne={},Re="application/",De=Re+"vnd.openxmlformats-officedocument.",Oe=Re+"vnd.oasis.opendocument.",_e=["B","KiB","MiB","GiB","TiB"],Ue=e=>e.toLowerCase().trim(),Ve={eml:xe,mime:xe,vcard:"text/vcard",vcf:"text/vcard",htm:"text/html",html:"text/html",csv:"text/csv",ics:"text/calendar",xml:"text/xml",json:Re+"json",p10:Re+"pkcs10",p7c:Re+"pkcs7-mime",p7m:Re+"pkcs7-mime",p7s:Re+"pkcs7-signature",p12:Re+"pkcs12",pfx:Re+"x-pkcs12",torrent:Re+"x-bittorrent",js:Re+"javascript",pl:"text/perl",css:"text/css",asp:"text/asp",php:Re+"x-php",jpg:"image/jpeg",ico:"image/x-icon",tif:"image/tiff",svg:"image/svg+xml",svgz:"image/svg+xml",zip:Re+"zip","7z":Re+"x-7z-compressed",rar:Re+"x-rar-compressed",cab:Re+"vnd.ms-cab-compressed",gz:Re+"x-gzip",tgz:Re+"x-gzip",bz:Re+"x-bzip",bz2:Re+"x-bzip2",deb:Re+"x-debian-package",mp3:"audio/mpeg",wav:"audio/x-wav",mp4a:"audio/mp4",weba:"audio/webm",m3u:"audio/x-mpegurl",qt:"video/quicktime",mov:"video/quicktime",wmv:"video/windows-media",avi:"video/x-msvideo","3gp":"video/3gpp","3g2":"video/3gpp2",mp4v:"video/mp4",mpg4:"video/mp4",ogv:"video/ogg",m4v:"video/x-m4v",asf:"video/x-ms-asf",asx:"video/x-ms-asf",wm:"video/x-ms-wm",wmx:"video/x-ms-wmx",wvx:"video/x-ms-wvx",movie:"video/x-sgi-movie",pdf:Re+"pdf",psd:"image/vnd.adobe.photoshop",ai:Re+"postscript",eps:Re+"postscript",ps:Re+"postscript",doc:Re+"msword",rtf:Re+"rtf",xls:Re+"vnd.ms-excel",ppt:Re+"vnd.ms-powerpoint",docx:De+"wordprocessingml.document",xlsx:De+"spreadsheetml.sheet",dotx:De+"wordprocessingml.template",pptx:De+"presentationml.presentation",odt:Oe+"text",ods:Oe+"spreadsheet",odp:Oe+"presentation"},qe="unknown",Ke="text",Be="code",He="eml",Ge="word",je="pdf",We="image",$e="audio",Je="video",ze="spreadsheet",Ye="presentation",Ze="certificate",Xe="archive",Qe="calendar",et={getExtension:e=>{const t=(e=Ue(e)).split(".").pop();return t===e?"":t},getContentType:e=>{if("winmail.dat"===(e=Ue(e)))return Re+"vnd.ms-tnef";let t=e.split(".").pop();return/^(txt|text|def|list|in|ini|log|sql|cfg|conf)$/.test(t)?"text/plain":/^(mpe?g|mpe|m1v|m2v)$/.test(t)?"video/mpeg":/^aif[cf]?$/.test(t)?"audio/aiff":/^(aac|flac|midi|ogg)$/.test(t)?"audio/"+t:/^(h26[134]|jpgv|mp4|webm)$/.test(t)?"video/"+t:/^(otf|sfnt|ttf|woff2?)$/.test(t)?"font/"+t:/^(png|jpeg|gif|tiff|webp)$/.test(t)?"image/"+t:Ve[t]||Re+"octet-stream"},getType:(e,t)=>{let s=(e=Ue(e))+(t=Ue(t).replace("csv/plain","text/csv").replace("x-",""));if(Ne[s])return Ne[s];let i=qe;const r=t.split("/"),a=r[1].replace("-compressed",""),o=e=>t.includes(e),n=/^(zip|7z|tar|rar|gzip|bzip|bzip2)$/;switch(!0){case"image"==r[0]||["png","jpg","jpeg","gif","webp"].includes(e):i=We;break;case"audio"==r[0]||["mp3","ogg","oga","wav"].includes(e):i=$e;break;case"video"==r[0]||"mkv"==e||"avi"==e:i=Je;break;case["php","js","css","xml","html"].includes(e)||"text/html"==t:i=Be;break;case"eml"==e||["message/delivery-status",xe].includes(t):i=He;break;case"ics"==e||"text/calendar"==t:i=Qe;break;case"text"==r[0]||"txt"==e||"log"==e:i=Ke;break;case n.test(a)||n.test(e):i=Xe;break;case"pdf"==a||"pdf"==e:i=je;break;case[Re+"pgp-signature",Re+"pgp-keys",Ve.p7m,Ve.p7s,Ve.p12,Ve.pfx].includes(t)||["asc","pem","ppk","p7s","p7m","p12","pfx"].includes(e):i=Ze;break;case o(De+".wordprocessingml")||o(Oe+".text")||o("vnd.ms-word")||["rtf","msword","vnd.msword"].includes(a):i=Ge;break;case o(De+".spreadsheetml")||o(Oe+".spreadsheet")||o("ms-excel"):i=ze;break;case o(De+".presentationml")||o(Oe+".presentation")||o("ms-powerpoint"):i=Ye}return Ne[s]=i},getTypeIconClass:e=>{let t="icon-file";switch(e){case Ke:case He:case je:case Ge:return t+"-text";case Be:case We:case $e:case Je:case Xe:case Ze:case ze:case Ye:case Qe:return t+"-"+e}return t},getIconClass:(e,t)=>et.getTypeIconClass(et.getType(e,t)),getAttachmentsIconClass:e=>{if(h(e)){let t=e.map((e=>e?et.getIconClass(et.getExtension(e.fileName),e.mimeType):"")).validUnique();return 1===t?.length&&"icon-file"!==t[0]?t[0]:"icon-attachment"}return""},friendlySize:e=>{let t=(e=f(e))?Math.floor(Math.log(e)/Math.log(1024)):0;return(e/Math.pow(1024,t)).toFixed(2>t?0:1)+" "+_e[t]}},tt={Inbox:1,Sent:2,Drafts:3,Junk:4,Trash:5,Archive:6},st="/private/vendor/kolab/folder-type",it="/shared/vendor/kolab/folder-type",rt={Empty:0,Reply:1,ReplyAll:2,Forward:3,ForwardAsAttachment:4,Draft:5,EditAsNew:6},at=0,ot=1,nt=2,lt=3,ct=4,dt=5;let ht=0;const ut=matchMedia("(max-width: 799px)"),mt={theme:ko.observable(""),themes:ko.observableArray(),userBackgroundName:ko.observable(""),userBackgroundHash:ko.observable(""),fontSansSerif:ko.observable(""),fontSerif:ko.observable(""),fontMono:ko.observable(""),isMobile:ko.observable(!1)},pt=()=>{const e=M("Theme"),t=F.app("themes");mt.themes(d(t)?t:[]),mt.theme(e),gt(e),mt.isMobile()||(mt.userBackgroundName(M("userBackgroundName")),mt.userBackgroundHash(M("userBackgroundHash"))),mt.fontSansSerif(M("fontSansSerif")),mt.fontSerif(M("fontSerif")),mt.fontMono(M("fontMono")),N(mt.isMobile())},gt=(e,t=(()=>0))=>{const s=A("app-theme-style"),i=()=>{ht=setTimeout((()=>t(o)),1e3)},r=j+"?/Css/0/User/-/"+encodeURI(e)+"/-/"+Date.now()+"/Hash/-/Json/";s.dataset.name!=e&&(clearTimeout(ht),t(a),rl.app.Remote.abort("theme").get("theme",r).then((r=>{2===h(r)&&(s.textContent=r[1],s.dataset.name=e,t(n)),i()}),i))},ft=e=>e.replace(/@[a-z]+$/,"").replace(/([A-Z])/g," $1").trim();Fe(mt,{fontSansSerif:e=>{if(null!=e){let t=T.classList;t.forEach((e=>{e.startsWith("font")&&!/font(Serif|Mono)/.test(e)&&t.remove(e)})),e&&t.add("font"+e)}},fontSerif:e=>{if(null!=e){let t=T.classList;t.forEach((e=>e.startsWith("fontSerif")&&t.remove(e))),e&&t.add("fontSerif"+e)}},fontMono:e=>{if(null!=e){let t=T.classList;t.forEach((e=>e.startsWith("fontMono")&&t.remove(e))),e&&t.add("fontMono"+e)}},userBackgroundHash:e=>{T.classList.toggle("UserBackground",!!e),T.style.backgroundImage=e?"url("+Y("UserBackground",e)+")":null}}),ut.onchange=e=>{mt.isMobile(e.matches),C.toggle("rl-mobile",e.matches),N(e.matches)},ut.onchange(ut);const bt=new class{constructor(){const e=this;e.messagesPerPage=ko.observable(25).extend({debounce:999}),e.checkMailInterval=ko.observable(15).extend({debounce:999}),e.messageReadDelay=ko.observable(5).extend({debounce:999}),Ae(e,{viewHTML:1,viewImages:0,viewImagesWhitelist:"",removeColors:0,allowStyles:0,collapseBlockquotes:1,maxBlockquotesLevel:0,listInlineAttachments:0,simpleAttachmentsList:0,useCheckboxesInList:1,listGrouped:0,showNextMessage:0,allowDraftAutosave:1,useThreads:0,threadAlgorithm:"",replySameFolder:0,hideUnsubscribed:0,hideDeleted:1,unhideKolabFolders:0,autoLogout:0,keyPassForget:15,showUnreadCount:0,messageNewWindow:0,messageReadAuto:0,requestReadReceipt:0,requestDsn:0,requireTLS:0,pgpSign:0,pgpEncrypt:0,allowSpellcheck:0,layout:1,editorDefaultType:"Html",editorWysiwyg:"Squire",markdown:0,msgDefaultAction:1}),e.init(),e.usePreviewPane=Ce((()=>mt.isMobile()?0:e.layout()));const t=()=>{const t=e.usePreviewPane();C.toggle("sm-msgView-side",1===t),C.toggle("sm-msgView-bottom",2===t),O("rl-layout",t)};let s;e.layout.subscribe(t),mt.isMobile.subscribe(t),t(),e.delayLogout=(()=>{clearTimeout(s),0<e.autoLogout()&&!M("accountSignMe")&&(s=setTimeout(rl.app.logout,6e4*e.autoLogout()))}).throttle(5e3)}init(){const e=this;["EditorDefaultType","editorWysiwyg","messageNewWindow","messageReadAuto","MsgDefaultAction","ViewHTML","ViewImages","ViewImagesWhitelist","RemoveColors","AllowStyles","CollapseBlockquotes","MaxBlockquotesLevel","ListInlineAttachments","simpleAttachmentsList","UseCheckboxesInList","listGrouped","showNextMessage","AllowDraftAutosave","useThreads","threadAlgorithm","ReplySameFolder","HideUnsubscribed","HideDeleted","ShowUnreadCount","UnhideKolabFolders","requestReadReceipt","requestDsn","requireTLS","pgpSign","pgpEncrypt","allowSpellcheck","markdown"].forEach((t=>{let s=M(t);t=t[0].toLowerCase()+t.slice(1),e[t](s)})),e.layout(f(M("Layout"))),e.messagesPerPage(f(M("MessagesPerPage"))),e.checkMailInterval(f(M("CheckMailInterval"))),e.messageReadDelay(f(M("MessageReadDelay"))),e.autoLogout(f(M("AutoLogout"))),e.keyPassForget(f(M("keyPassForget")))}},yt=ko.observableArray();yt.push({name:"Squire",construct:(e,t,s)=>s(new SquireUI(t))}),rl.registerWYSIWYG=(e,t)=>yt.push({name:e,construct:t});class HtmlEditor{constructor(e,t=null,s=null,i=null){if(this.blurTimer=0,this.onBlur=i,this.onModeChange=s,e){t=t?[t]:[],this.onReady=e=>t.push(e);const s=bt.editorWysiwyg();(yt.find((e=>s==e.name))||yt.find((e=>"Squire"==e.name))).construct(this,e,(e=>setTimeout((()=>{this.editor=e,e.on("blur",(()=>this.blurTrigger())),e.on("focus",(()=>clearTimeout(this.blurTimer))),e.on("mode",(()=>{this.blurTrigger(),this.onModeChange?.(!this.isPlain())})),this.onReady=e=>e(),t.forEach((e=>e()))}),1)))}}blurTrigger(){this.onBlur&&(clearTimeout(this.blurTimer),this.blurTimer=setTimeout((()=>this.onBlur?.()),200))}isHtml(){return!!this.editor&&!this.isPlain()}isPlain(){return!!this.editor&&"plain"===this.editor.mode}clearCachedSignature(){this.onReady((()=>this.editor.execCommand("insertSignature",{clearCache:!0})))}setSignature(e,t,s=!1){this.onReady((()=>this.editor.execCommand("insertSignature",{isHtml:t,insertBefore:s,signature:e})))}getData(){let e="";if(this.editor)try{e=this.isPlain()?this.editor.getPlainData():this.editor.getData()}catch(e){}return e}getDataWithHtmlMark(){return(this.isHtml()?":HTML:":"")+this.getData()}modeWysiwyg(){this.onReady((()=>this.editor.setMode("wysiwyg")))}modePlain(){this.onReady((()=>this.editor.setMode("plain")))}setHtmlOrPlain(e){e.startsWith(":HTML:")?this.setHtml(e.slice(6)):this.setPlain(e)}setData(e,t){this.onReady((()=>{const s=this.editor;this.clearCachedSignature();try{s.setMode(e),this.isPlain()?s.setPlainData(t):s.setData(t)}catch(e){}}))}setHtml(e){this.setData("wysiwyg",e)}setPlain(e){this.setData("plain",e)}focus(){this.onReady((()=>this.editor.focus()))}blur(){this.onReady((()=>this.editor.blur()))}clear(){this.onReady((()=>this.isPlain()?this.setPlain(""):this.setHtml("")))}}const vt=D("template"),St=new TurndownService,wt=/[&<>"']/g,Et=/^(https?:)?\/\//i,kt={"&":"&","<":"<",">":">",'"':""","'":"'"},Ct=["blockquote","br","div","figcaption","figure","h1","h2","h3","h4","h5","h6","hgroup","hr","p","wbr","article","aside","header","footer","main","section","details","summary","nav","dd","dl","dt","li","ol","ul","a","abbr","address","b","bdi","bdo","cite","code","del","dfn","em","i","ins","kbd","mark","pre","q","rp","rt","ruby","s","samp","small","span","strong","sub","sup","time","u","var","acronym","big","center","dir","font","marquee","nobr","plaintext","rb","rtc","strike","tt","img","caption","col","colgroup","table","tbody","td","tfoot","th","thead","tr","style","xmp"].join(","),At=["A","B","EM","I","SPAN","STRONG"],Tt=()=>{bt.collapseBlockquotes()&&[...vt.content.querySelectorAll("blockquote")].reverse().forEach((e=>{const t=D("details",{class:"sm-bq-switcher"});t.innerHTML="<summary>•••</summary>",e.replaceWith(t),t.append(e)}))},Ft=e=>e.replaceWith(...e.childNodes),Mt=/https?:\/\/[^\p{C}\p{Z}]+[^\p{C}\p{Z}.]/gu,Pt=/(^|\r|\n|\p{C}\p{Z})((?:[^"(),.:;<>@[\]\\\p{C}\p{Z}]+(?:\.[^"(),.:;<>@[\]\\\p{C}\p{Z}]+)*|"(?:\\?[^"\\\p{C}\p{Z}])*")@[^@\p{C}\p{Z}]+[^@\p{C}\p{Z}.])/giu,Lt=/(tel:(\+[0-9().-]+|[0-9*#().-]+(;phone-context=\+[0-9+().-]+)?))/g,It=/^(utm_|ec_|fbclid|mc_eid|mkt_tok|_hsenc|vero_id|oly_enc_id|oly_anon_id|__s|Referrer|mailing|elq|bch|trc|ref|correlation_id|pd_|pf_|email_hash)$/i,xt=(e,t)=>new URL(e).searchParams.get(t)||e,Nt=e=>atob(e.replace(/_/g,"/").replace(/-/g,"+")),Rt=decodeURIComponent,Dt=e=>{try{let t=e.replace(/^.+\/(https%253A[^/?&]+).*$/i,((...e)=>Rt(Rt(e[1])))).replace(/tracking\.(printabout\.nl[^?]+)\?.*/i,((...e)=>e[1])).replace(/(zalando\.nl[^?]+)\?.*/i,((...e)=>e[1])).replace(/^.+(awstrack\.me|redditmail\.com)\/.+(https:%2F%2F[^/]+).*/i,((...e)=>Rt(e[2]))).replace(/^.+(www\.google|safelinks\.protection\.outlook\.com|mailchimp\.com).+url=.+$/i,(()=>xt(e,"url"))).replace(/^.+click\.godaddy\.com.+$/i,(()=>xt(e,"redir"))).replace(/^.+delivery-status\.com.+$/i,(()=>xt(e,"fb"))).replace(/^.+go\.dhlparcel\.nl.+\/([A-Za-z0-9_-]+)$/i,((...e)=>Nt(e[1]))).replace(/^(.+mopinion\.com.+)\?.*$/i,((...e)=>e[1])).replace(/^.+sellercentral\.amazon\.com\/nms\/redirect.+$/i,(()=>Nt(xt(e,"u")))).replace(/^.+amazon\.com\/gp\/r\.html.+$/i,(()=>xt(e,"U"))).replace(/^.+\/track\/click\/.+\?p=.+$/i,(()=>{let t=xt(e,"p");try{t=JSON.parse(Nt(t)),t?.p&&(t=JSON.parse(t.p))}catch(e){}return t?.url||e})).replace(/[\s<>]+/gi,"");t=new URL(t);let s=t.searchParams;return[...s.keys()].forEach((e=>It.test(e)&&s.delete(e))),t.toString()}catch(e){}return e},Ot=e=>e.trim().replace(/;\s*-[^;]+/g,"").replace(/^\s*-[^;]+(;|$)/g,"").replace(/white-space[^;]+/g,""),_t=e=>{const t=[];if(t.toString=()=>t.reduce(((e,t)=>e+t.selector+" {\n"+("media"===t.type?t.subStyles.toString():t.rules)+"}\n"),""),t.applyNamespace=e=>t.forEach((t=>{"media"===t.type?t.subStyles.applyNamespace(e):t.selector=t.selector.split(",").map((t=>(e+" .mail-body "+t.replace(/\./g,".msg-")).replace(/\sbody/gi,""))).join(",")})),e){e=e.replace(/\/\*[\s\S]*?\*\//gi,"").replace(/<!--[\s\S]*?-->/gi,"").replace(/<[\s\S]*/gi,"");let s,i=/(?:(\s*?@(?:media)[\s\S]*?){([\s\S]*?)}\s*?})|(?:([\s\S]*?){([\s\S]*?)})/gi;for(;s=i.exec(e),null!==s;){let e=s[void 0===s[2]?3:1].split("\r\n").join("\n").trim().replace(/\n+/,"\n").split(/\s+/g).map((e=>e.replace(/^(:root|html)$/,""))).join(" ").trim();e.includes("@media")?t.push({selector:e,type:"media",subStyles:_t(s[2]+"\n}")}):e&&!e.includes("@")&&t.push({selector:e,rules:Ot(s[4])})}}return t},Ut=e=>(e?.toString?.()||""+e).replace(wt,(e=>kt[e])),Vt=(e,t,s)=>{let i;const r=parseInt(bt.maxBlockquotesLevel()),a={hasExternals:!1,tracking:!1,linkedData:[]},o=!!s,n=e=>t.findByCid(e),l={link:e=>i=e,text:(e,t)=>t.style.color=e,topmargin:(e,t)=>t.style.marginTop=f(e)+"px",leftmargin:(e,t)=>t.style.marginLeft=f(e)+"px",bottommargin:(e,t)=>t.style.marginBottom=f(e)+"px",rightmargin:(e,t)=>t.style.marginRight=f(e)+"px"},c=["name","dir","lang","style","title","background","bgcolor","alt","height","width","src","href","border","bordercolor","charset","direction","download","hreflang","alink","bottommargin","leftmargin","link","rightmargin","text","topmargin","vlink","align","valign","color","face","size","noshade","hspace","sizes","srcset","vspace","low","high","optimum","value","reversed","start","cols","rows","frame","rules","summary","cellpadding","cellspacing","abbr","scope","colspan","rowspan","headers"];bt.allowStyles()?c.push("class"):s=0,vt.innerHTML=e.replace(/<(\/?)head(\s[^>]*)?>/gi,"").replace(/<(\/?)body(\s[^>]*)?>/gi,'<$1div class="mail-body"$2>').replace(/<span class="preview-text"[\s\S]+?<\/span>/,"").replace(/\u2028/g," ").replace(/<br>\s*<\/p>/gi,"</p>").trim(),e="";const h=document.createNodeIterator(vt.content,NodeFilter.SHOW_COMMENT);for(;h.nextNode();)h.referenceNode.remove();vt.content.querySelectorAll('script[type="application/ld+json"]').forEach((e=>{try{const t=JSON.parse(e.textContent);(d(t)?t:[t]).forEach((e=>a.linkedData.push(e)))}catch(e){}})),vt.content.querySelectorAll("form,button,data").forEach((e=>Ft(e))),vt.content.querySelectorAll(":not("+Ct+"),a:empty,span:empty"+(0<r?","+new Array(1+r).fill("blockquote").join(" "):"")).forEach((e=>e.remove()));let u=vt.content.querySelector(".mail-body");return[...vt.content.querySelectorAll(".mail-body + .mail-body")].forEach((e=>u.append(...e.childNodes))),[...vt.content.querySelectorAll("*")].forEach((e=>{const t=e.tagName,r=e.style;if("STYLE"===t){let t=s?_t(e.textContent):[];return void(t.length?(t.applyNamespace(s),t=t.toString(),bt.removeColors()&&(t=t.replace(/(background-)?color:[^};]+;?/g,"")),e.textContent=t):e.remove())}if("XMP"===t){const t=D("pre");return t.innerHTML=Ut(e.innerHTML),void e.replaceWith(t)}if("none"==r.display||"hidden"==r.visibility)return void e.remove();const d=e.className,h=t=>e.hasAttribute(t),u=(t,s)=>e.setAttribute(t,s),m=t=>{let s=(t=>h(t)?e.getAttribute(t).trim():"")(t);return e.removeAttribute(t),s};if("mail-body"===d?g(l,((t,s)=>h(t)&&s(m(t),e))):s&&d&&(e.className=d.replace(/(^|\s+)/g,"$1msg-")),e.hasAttributes()){let t=e.attributes.length;for(;t--;){let s=e.attributes[t].name.toLowerCase();c.includes(s)||"class"===s&&"mail-body"===d||m(s)}}let p;if(r.backgroundImage||"TD"!==t&&"TH"!==t&&(["width","height"].forEach((e=>{h(e)&&(p=m(e),r[e]||(r[e]=p.includes("%")?p:p+"px"))})),p=r.width,100<parseInt(p,10)&&!r.maxWidth&&(r.maxWidth=p,r.width="100%"),p=r.removeProperty("height"),p&&!r.maxHeight&&(r.maxHeight=p)),"A"===t&&(p=e.href,/^([a-z]+):/i.test(p)?(e.href=Dt(p),e.href!=p&&(a.tracking=!0,u("data-x-href-tracking",p)),u("target","_blank")):(u("data-x-href-broken",p),m("href")),u("tabindex","-1"),i&&!e.style.color&&(e.style.color=i)),At.includes(t)&&""==e.textContent.trim())return void(("A"!==t||!e.querySelector("IMG"))&&Ft(e));let b=!1;if(o&&(p=o&&m("src"),p))if("IMG"===t){let t;if(e.loading="lazy",p.startsWith("cid:"))p=p.slice(4),u("data-x-src-cid",p),t=n(p),t?.download&&(e.src=t.linkPreview(),e.title+=" ("+t.fileName+")",t.isInline(!0),t.isLinked(!0));else if(t=(e=>{const t=n(e);return t?.contentLocation?t:0})(p))t.download&&(e.src=t.linkPreview(),t.isLinked(!0));else if(r.maxHeight&&3>f(r.maxHeight)||r.maxWidth&&3>f(r.maxWidth)||r.width&&2>f(r.width)||["email.microsoftemail.com/open","github.com/notifications/beacon/","/track/open","google-analytics.com"].filter((e=>p.toLowerCase().includes(e))).length)b=!0,r.display="none",u("data-x-src-hidden",p);else if(Et.test(p)){let t=Dt(p);t!=p&&(a.tracking=!0,u("data-x-src-tracking",p)),u("data-x-src",t),a.hasExternals=!0,e.alt||(e.alt=t.replace(/^.+\/([^/?]+).*$/,"$1").slice(-20))}else p.startsWith("data:image/")?e.src=p:u("data-x-src-broken",p)}else u("data-x-src-broken",p);if(h("background")&&(r.backgroundImage='url("'+m("background")+'")'),h("bgcolor")&&(r.backgroundColor=m("bgcolor")),h("color")&&(r.color=m("color")),!b){r.removeProperty("behavior"),r.removeProperty("cursor"),r.removeProperty("min-width");const e=[],s=[];["backgroundImage","listStyleImage","content"].forEach((i=>{if(r[i]){let o=r[i],l=o.match(/url\s*\(([^)]+)\)/i);if(l){r[i]=null,l=l[1].replace(/^["'\s]+|["'\s]+$/g,"");let c=l.toLowerCase();if(c.startsWith("cid:")){const e=n(l);e?.linkPreview&&t&&(r[i]="url('"+e.linkPreview()+"')",e.isInline(!0),e.isLinked(!0))}else Et.test(c)?(a.hasExternals=!0,e.push([i,l])):c.startsWith("data:image/")?r[i]=o:s.push([i,l])}}})),e.length&&u("data-x-style-url",JSON.stringify(e)),s.length&&u("data-x-style-broken-urls",JSON.stringify(s)),bt.removeColors()&&(r.removeProperty("background-color"),r.removeProperty("background-image"),r.removeProperty("color")),r.cssText&&(r.cssText=Ot(r.cssText))}})),o&&Tt(),a.html=vt.innerHTML.trim(),a},qt=e=>{if(bt.markdown())return Kt(e);const t="⎯".repeat(64),s=(e,t)=>vt.content.querySelectorAll(e).forEach(t),i=e=>{let t;for(;t=e.querySelector("blockquote");)i(t),t.replaceWith("\n"+("\n"+t.textContent.replace(/\n{3,}/g,"\n\n").trim()+"\n").replace(/^/gm,"> "))};for(e=e.replace(/<pre[^>]*>([\s\S]*?)<\/pre>/gim,((...e)=>1<e.length?e[1].toString().replace(/\n/g,"<br>"):"")).replace(/<br><\/div>/gi,"</div>").replace(/\r?\n/g,"").replace(/\s+/gm," ");/<(div|tr)[\s>]/i.test(e);)e=e.replace(/\n*<(div|tr)(\s[\s\S]*?)?>\n*/gi,"\n");for(;/<\/(div|tr)[\s>]/i.test(e);)e=e.replace(/\n*<\/(div|tr)(\s[\s\S]*?)?>\n*/gi,"\n");return vt.innerHTML=e.replace(/<t[dh](\s[\s\S]*?)?>/gi,"\t").replace(/<\/tr(\s[\s\S]*?)?>/gi,"\n"),s("style",(e=>e.remove())),s("hr",(e=>e.replaceWith(`\n\n${t}\n\n`))),s("h1,h2,h3,h4,h5,h6",(e=>e.replaceWith(`\n\n${"#".repeat(e.tagName[1])} ${e.textContent}\n\n`))),s("p",(e=>{e.prepend("\n\n"),""==e.textContent.trim()?e.remove():e.after("\n\n")})),s("ol,ul",(e=>{let t="",s=e,i="OL"==e.tagName,r=0;for(;s=s?.parentNode?.closest?.("ol,ul");)t=" "+t;e.querySelectorAll(":scope > li").forEach((e=>{e.prepend("\n"+t+(i?++r+". ":" * "))})),e.prepend("\n\n"),e.after("\n\n")})),s("a",(e=>{let t=e.textContent,s=e.href;return e.replaceWith(t.replace(/[\s()-]+/g,"").includes(s.replace(/^[a-z]:/,"").replace(/[\s()-]+/g,""))?t:t+" "+s+" ")})),s("b,strong",(e=>e.replaceWith(`**${e.textContent}**`))),s("i,em",(e=>e.replaceWith(`*${e.textContent}*`))),vt.innerHTML=vt.innerHTML.replace(/\n{3,}/gm,"\n\n").replace(/\n<br[^>]*>/g,"\n").replace(/<br[^>]*>\n/g,"\n"),s("br",(e=>e.replaceWith("\n"))),i(vt.content),(vt.content.textContent||"").trim()},Kt=e=>(vt.innerHTML=e,St.turndown(vt.content)),Bt=e=>{e=e.toString().replace(/\r/g,"").replace(/^>[> ]>+/gm,(([e])=>e?e.replace(/[ ]+/g,""):e)).replace(/\u2028/g," ");let t=!1,s=!0,i=!0,r=[],a=e.split("\n");do{s=!1,r=[],a.forEach((e=>{i=">"===e.slice(0,1),i&&!t?(s=!0,t=!0,r.push("~~~blockquote~~~"),r.push(e.slice(1))):!i&&t?e?(t=!1,r.push("~~~/blockquote~~~"),r.push(e)):r.push(e):i&&t?r.push(e.slice(1)):r.push(e)})),t&&(t=!1,r.push("~~~/blockquote~~~")),a=r}while(s);return vt.innerHTML=a.join("\n").replace(/&/g,"&").replace(/>/g,">").replace(/</g,"<").replace(Mt,((...e)=>(e[0]=Dt(e[0]),`<a href="${e[0]}" target="_blank">${e[0]}</a>`))).replace(Pt,'$1<a href="mailto:$2">$2</a>').replace(Lt,'<a href="$1">$1</a>').replace(/~~~blockquote~~~\s*/g,"<blockquote>").replace(/\s*~~~\/blockquote~~~/g,"</blockquote>").replace(/\n/g,"<br>"),Tt(),vt.innerHTML.trim()};function Ht(e,t){if(null!=e)switch(typeof e){case"boolean":return 0!=t&&!!t;case"number":return t=parseFloat(t),isFinite(t)?t:0;case"string":return null!=t?""+t:"";case"object":if(e.constructor.reviveFromJson)return e.constructor.reviveFromJson(t);if(d(e)&&!d(t))return[]}return t}rl.Utils={cleanHtml:Vt,htmlToPlain:qt,plainToHtml:Bt,htmlToMarkdown:Kt};class AbstractModel{constructor(){Object.defineProperty(this,"disposables",{value:[]})}addObservables(e){Ae(this,e)}addComputables(e){Te(this,e)}addSubscribables(e){g(e,((e,t)=>this.disposables.push(this[e].subscribe(t))))}onDestroy(){this.disposables.forEach(Me),p(this,(e=>{(ko.isObservableArray(e)?e():e)?.onDestroy?.()}))}static validJson(e){return!(!e||"Object/"+this.name.replace("Model","")!==e["@Object"])}static reviveFromJson(e){let t=this.validJson(e)?new this:null;return t?.revivePropertiesFromJson(e),t}revivePropertiesFromJson(e){const t=this.constructor.validJson(e);return t&&g(e,((e,t)=>{if("@"!==e[0])try{switch(typeof this[e]){case"function":ko.isObservable(this[e])&&this[e](Ht(this[e](),t));break;case"boolean":case"number":case"object":case"string":this[e]=Ht(this[e],t);break;case"undefined":this[e]=t}}catch(e){}})),t}}class EmailModel extends AbstractModel{constructor(e,t,s="none"){super(),this.email=e||"",this.name=t||"",this.dkimStatus=s,this.cleanup()}static reviveFromJson(e){const t=super.reviveFromJson(e);return t?.cleanup(),t?.valid()?t:null}valid(){return this.name||this.email}cleanup(){this.name===this.email&&(this.name="")}toLine(e,t){let s=this.name,i=this.email,r=e=>'<a href="mailto:'+Ut(i)+(s?"?to="+encodeURIComponent('"'+s+'" <'+i+">"):"")+'" target="_blank" tabindex="-1">'+Ut(e||i)+"</a>";return i&&(s?i=e?t?r(s):s:t?Ut('"'+s+'" <')+r()+Ut(">"):'"'+s+'" <'+i+">":t&&(i=r())),i||s}}const Gt=[/=([0-9A-F]{2})/g,(...e)=>String.fromCharCode(parseInt(e[1],16))],jt=atob,Wt=e=>btoa(unescape(encodeURIComponent(e))),$t=e=>e.replace(/=\r?\n/g,"").replace(...Gt),Jt=e=>e.replace(/=\?([^?]+)\?(B|Q)\?(.+?)\?=/g,((e,t,s,i)=>zt(t,"B"==s?jt(i):$t(i)))),zt=(e,t)=>{try{return new TextDecoder(e).decode(Uint8Array.from(t,(e=>e.charCodeAt(0))))}catch(e){}};function Yt(e){e=(e||"").toString();let t="",s={type:"text",value:""},i=!1,r=[],a=[];const o={'"':'"',"(":")","<":">",",":"",":":";",";":""},n=e=>{e.value=(e.value||"").toString().trim(),e.value.length&&r.push(e),s={type:"text",value:""},i=!1},l=()=>{r.length&&(r=function(e){let t=!1,s={},i=[],r={email:[],comment:[],group:[],text:[]};e.forEach((e=>{t=t||"group"===e.type,r[e.type].push(e.value)})),!r.text.length&&r.comment.length&&(r.text=r.comment,r.comment=[]);if(t)i=i.concat(Yt(r.group.join(",")));else{if(!r.email.length&&r.text.length){for(var a=r.text.length;a--;)if(r.text[a].match(/^[^@\s]+@[^@\s]+$/)){r.email=r.text.splice(a,1);break}if(!r.email.length)for(a=r.text.length;a--&&(r.text[a]=r.text[a].replace(/\s*\b[^@\s]+@[^@\s]+\b\s*/,(e=>r.email.length?e.trim():(r.email=[e.trim()],""))),!r.email.length););}!r.text.length&&r.comment.length&&(r.text=r.comment,r.comment=[]),r.email.length>1&&(r.text=r.text.concat(r.email.splice(1))),s={email:Jt(r.email.join(" ").trim()),name:Jt(r.text.join(" ").trim())},s.email===s.name&&(s.email.includes("@")?s.name="":s.email=""),i.push(s)}return i}(r),r.length&&(a=a.concat(r))),r=[]};return[...e].forEach((e=>{i||e!==t&&(t||!(e in o))?(s.value+=e,i=!i&&"\\"===e):(n(s),","===e||";"===e?l():(t=t?"":o[e],"<"===e?s.type="email":"("===e?s.type="comment":":"===e&&(s.type="group")))})),n(s),l(),a}const Zt=e=>e?.emailaddress?.key;let Xt,Qt;class EmailAddressesComponent{constructor(e,t){Qt||(Qt=D("datalist",{id:"emailaddresses-datalist"}),k.body.append(Qt));const s=this,i=D("input",{type:"text",list:Qt.id,autocomplete:"off",autocorrect:"off",autocapitalize:"off"}),r=()=>Xt?.li.parentNode!==s.ul,a=e=>r()&&e.preventDefault();s.element=e,s.options=Object.assign({focusCallback:null,autoCompleteSource:"",onChange:null},t),s._chosenValues=[],s._lastEdit="",s.ul=D("ul",{class:"emailaddresses"}),B(s.ul,{click:e=>s._focus(e),dblclick:e=>s._editTag(e),dragenter:a,dragover:a,drop:e=>{r()&&Xt.value&&(e.preventDefault(),Xt.source._removeDraggedTag(Xt.li),s._parseValue(Xt.value))}}),s.input=i,B(i,{focus:()=>{s._focusTrigger(!0),i.value||s._resetDatalist()},blur:()=>{s._parseInput(!0),s._focusTrigger(!1)},keydown:e=>{if("Backspace"===e.key||"ArrowLeft"===e.key){var t=s.inputCont.previousElementSibling;t&&(!i.value||"selectionStart"in i&&0===i.selectionStart&&0===i.selectionEnd)&&(e.preventDefault(),t.querySelector("a").focus()),s._updateDatalist()}else"Enter"==e.key&&(e.preventDefault(),s._parseInput(!0))},input:()=>{s._parseInput(),s._updateDatalist()}}),e.placeholder&&(i.placeholder=e.placeholder),s.inputCont=D("li",{class:"emailaddresses-input"}),s.inputCont.append(i),s.ul.append(s.inputCont),e.replaceWith(s.ul),e.value.trim()&&s._parseValue(e.value),s._updateDatalist=s.options.autoCompleteSource?(()=>{let e=i.value.trim();Qt.inputValue!==e&&(Qt.inputValue=e,e.length&&s.options.autoCompleteSource(e,(t=>{s._resetDatalist();let r=e.length;t?.forEach((e=>{Qt.append(new Option(e)),r=Math.max(r,e.length)})),r*=8,i.clientWidth<r&&(i.style.width=r+"px")})))}).throttle(500):()=>0}_focusTrigger(e){this.ul.classList.toggle("emailaddresses-focused",e),this.options.focusCallback(e)}_resetDatalist(){Qt.textContent=""}_parseInput(e){let t=this.input.value;(e||t.includes(",")||t.includes(";")||" "===t.charAt(t.length-1)&&this._simpleEmailMatch(t))&&this._parseValue(t)&&(this.input.value=""),this._resizeInput()}_parseValue(e){if(e){const t=this,s=e.trim(),i=((s&&[",",";","\n"].includes(s.slice(-1))?(e=>{const t=[];let s=!1;return Yt(e).forEach((e=>{const i=e.name||e.email?new EmailModel(e.email,e.name):null;i?.email&&(s=!0),t.push(i?i.toLine():e.name)})),s?t:null})(e):null)||[e]).map((e=>Yt(e).map((e=>e.name||e.email?new EmailModel(e.email,e.name):null)).filter((e=>e)))).flat(1/0).map((e=>e.toLine?[e.toLine(),e]:[e,null]));if(i.length)return i.forEach((e=>{var s=e[0].trim(),i=!1,r=-1,a={key:"",obj:null,value:""};t._chosenValues.forEach(((e,a)=>{e.value===t._lastEdit&&(r=a),i|=e.value===s})),""!==s&&e[1]&&!i&&(a.key="mi_"+Math.random().toString(16).slice(2,10),a.value=s,a.obj=e[1],-1<r?t._chosenValues.splice(r,0,a):t._chosenValues.push(a),t._lastEdit="",t._renderTags())})),1===i.length&&""===i[0]&&""!==t._lastEdit&&(t._lastEdit="",t._renderTags()),t._setValue(t._buildValue()),!0}}_resizeInput(){let e=this.input;e.clientWidth<e.scrollWidth&&(e.style.width=e.scrollWidth+20+"px")}_editTag(e){var t=e.target.closest("li"),s=Zt(t);if(!s)return!0;var i=this,r="",a=null,o=!1;i._chosenValues.forEach((e=>{e.key===s?(r=e.value,o=!0):o&&!a&&(a=e)})),a&&(i._lastEdit=a.value),t.after(i.inputCont),i.input.value=r,setTimeout((()=>i.input.select()),100),i._removeTag(e,t),i._resizeInput(e)}_buildValue(){return this._chosenValues.map((e=>e.value)).join(",")}_setValue(e){this.element.value!==e&&(this.element.value=e,this.options.onChange(e))}_simpleEmailMatch(e){const t=e.trim();return/^[^@]*<[^\s@]{1,128}@[^\s@]{1,256}\.[\w]{2,32}>$/g.test(t)||/^[^\s@]{1,128}@[^\s@]{1,256}\.[\w]{2,32}$/g.test(t)}_renderTags(){let e=this;[...e.ul.children].forEach((t=>t!==e.inputCont&&t.remove())),e._chosenValues.forEach((t=>{if(t.obj){let s=D("li",{title:t.obj.toLine(),draggable:"true"}),i=D("span");i.append(t.obj.toLine(!0)),s.append(i),i=D("a",{href:"#",class:"ficon"}),i.append("✖"),B(i,{click:t=>e._removeTag(t,s),focus:()=>s.className="emailaddresses-selected",blur:()=>s.className=null,keydown:t=>{switch(t.key){case"Delete":case"Backspace":e._removeTag(t,s);break;case"e":case"Enter":e._editTag(t);break;case"ArrowLeft":var r=i.closest("li").previousElementSibling;r.matches("li")?r.querySelector("a").focus():e.focus();break;case"ArrowRight":var a=i.closest("li").nextElementSibling;a!==this.inputCont?a.querySelector("a").focus():this.focus();break;case"ArrowDown":e._focus(t)}}}),s.append(i),s.emailaddress=t,B(s,{dragstart:t=>{Xt={source:e,li:s,value:s.emailaddress.obj.toLine()},t.dataTransfer.setData("text/plain","snappymail/emailaddress"),t.dataTransfer.effectAllowed="move",s.style.opacity=.25},dragend:()=>{Xt=null,s.style.cssText=""}}),e.inputCont.before(s)}}))}_removeTag(e,t){e.preventDefault();var s=Zt(t),i=this,r=i._chosenValues.findIndex((e=>s===e.key));r>-1&&i._chosenValues.splice(r,1),i._setValue(i._buildValue()),t.remove(),setTimeout((()=>i.input.focus()),100)}_removeDraggedTag(e){var t=Zt(e),s=this,i=s._chosenValues.findIndex((e=>t===e.key));-1<i&&(s._chosenValues.splice(i,1),s._setValue(s._buildValue())),e.remove()}focus(){this.input.focus()}blur(){this.input.blur()}_focus(e){var t=e.target.closest("li");Zt(t)?t.querySelector("a").focus():this.focus()}set value(e){var t=this;t.element.value!==e&&(t._chosenValues=[],t._renderTags(),t._parseValue(t.element.value=e))}}let es=new Map,ts=new Map,ss="INBOX";const is=()=>ss,rs=e=>{e.etag="",es.set(e.fullName,e),ts.set(e.fullNameHash,e.fullName)},as=(e,t)=>es.has(e)&&(es.get(e).etag=t),os=e=>es.get(e),ns=e=>es.delete(e),ls="__UNUSE__",cs=["$forwarded","$mdnsent","$submitpending","$submitted","$junk","$notjunk","$phishing","sent","$encrypted","$error","$ignored","$invitation","$queued","$sent","$signed","$todo","$watched","$notphishing","junk","nonjunk","$attachment","$replied","$readreceipt","$notdelivered"],ds=e=>"\\"!=e[0]&&!cs.includes(e.toLowerCase()),hs=new class{constructor(){const e=this;Ae(e,{displaySpecSetting:!1,sortMode:"",quotaLimit:0,quotaUsage:0,sentFolder:"",draftsFolder:"",spamFolder:"",trashFolder:"",archiveFolder:"",optimized:!1,error:"",foldersLoading:!1,foldersCreating:!1,foldersDeleting:!1,foldersRenaming:!1,foldersInboxUnreadCount:0}),e.namespace="",e.folderList=ko.observableArray(),e.capabilities=ko.observableArray(),e.currentFolder=ko.observable(null).extend({toggleSubscribeProperty:[e,"selected"]}),Te(e,{draftsFolderNotEnabled:()=>!e.draftsFolder()||ls===e.draftsFolder(),currentFolderFullName:()=>e.currentFolder()?e.currentFolder().fullName:"",currentFolderFullNameHash:()=>e.currentFolder()?e.currentFolder().fullNameHash:"",foldersChanging:()=>e.foldersLoading()|e.foldersCreating()|e.foldersDeleting()|e.foldersRenaming(),systemFoldersNames:()=>{const t=[is()],s=[e.sentFolder(),e.draftsFolder(),e.spamFolder(),e.trashFolder(),e.archiveFolder()];return e.folderList().length&&s.forEach((e=>e&&ls!==e&&t.push(e))),t},systemFolders:()=>e.systemFoldersNames().map((e=>os(e))).filter((e=>e))});const t=t=>{t.subscribe((()=>os(t())?.type(0)),e,"beforeChange")},s=e=>t=>os(t)?.type(e);t(e.sentFolder),t(e.draftsFolder),t(e.spamFolder),t(e.trashFolder),t(e.archiveFolder),Fe(e,{sentFolder:s(tt.Sent),draftsFolder:s(tt.Drafts),spamFolder:s(tt.Junk),trashFolder:s(tt.Trash),archiveFolder:s(tt.Archive)}),e.quotaPercentage=Ce((()=>{const t=e.quotaLimit(),s=e.quotaUsage();return 0<t?Math.ceil(s/t*100):0}))}hasCapability(e){return this.capabilities().includes(e)}allowKolab(){return hs.hasCapability("METADATA")&&L("Kolab")}getNextFolderNames(e){const t=[],s=Date.now(),i=s-e,r=[],a=this.displaySpecSetting(),o=e=>{e.forEach((e=>{e?.selectable()&&e.exists&&i>e.expires&&(e.isSystemFolder()||e.isSubscribed()&&(e.checkable()||!a))&&r.push([e.expires,e.fullName]),e?.subFolders.length&&o(e.subFolders())}))};return o(this.folderList()),r.sort(((e,t)=>e[0]<t[0]?-1:e[0]>t[0]?1:0)),r.find((e=>{const i=os(e[1]);return i&&(i.expires=s,t.push(e[1])),10<=t.length})),t}saveSystemFolders(e){e=e||{sent:hs.sentFolder(),drafts:hs.draftsFolder(),junk:hs.spamFolder(),trash:hs.trashFolder(),archive:hs.archiveFolder()},g(e,((e,t)=>F.set(e+"Folder",t))),rl.app.Remote.request("SystemFoldersUpdate",null,e)}};let us=null,ms=null,ps=e=>!!ms?.canPlayType(e).replace("no",""),gs=window.AudioContext||window.webkitAudioContext,fs=(e,t)=>{ms&&(ms.src=e,ms.play(),t=t.trim(),O("audio.start",t.replace(/\.([a-z0-9]{3})$/,"")||"audio"))},bs=()=>{try{const e=new Audio;if(e.canPlayType&&e.pause&&e.play)return e.preload="none",e.loop=!1,e.autoplay=!1,e.muted=!1,e}catch(e){}return null},ys=["click","dblclick","contextmenu","auxclick","mousedown","mouseup","pointerup","touchstart","touchend","keydown","keyup"],vs=()=>{ys.forEach((e=>k.removeEventListener(e,vs,!0))),gs&&gs.resume()};gs&&(gs=gs?new gs:null,gs.onstatechange=vs),ys.forEach((e=>k.addEventListener(e,vs,!0)));const Ss=new class{constructor(){if(ms||(ms=bs()),this.supported=!!ms,this.supportedMp3=ps("audio/mpeg;"),this.supportedWav=ps('audio/wav; codecs="1"'),this.supportedOgg=ps('audio/ogg; codecs="vorbis"'),ms){const e=()=>this.pause();K(ms,["ended","error"],e),addEventListener("audio.api.stop",e)}Ae(this,{notifications:!1})}paused(){return!ms||ms.paused}stop(){this.pause()}pause(){ms?.pause(),O("audio.stop")}playMp3(e,t){this.supportedMp3&&fs(e,t)}playOgg(e,t){this.supportedOgg&&fs(e,t)}playWav(e,t){this.supportedWav&&fs(e,t)}playNotification(e,t){(e||this.notifications())&&"running"==gs.state&&(this.supportedMp3||this.supportedOgg)&&(us=us||bs(),us&&(us.src=ee("sounds/"+M("NotificationSound")+(this.supportedMp3?".mp3":".ogg")),us.volume=t?.01:1,us.play()))}};class AbstractCollectionModel extends Array{constructor(){super()}onDestroy(){this.forEach((e=>e.onDestroy?.()))}static reviveFromJson(e,t){const s=new this;return e&&("Collection/"+this.name.replace("Model","")===e["@Object"]&&(g(e,((e,t)=>"@"!==e[0]&&(s[e]=t))),e=e["@Collection"]),d(e)&&e.forEach((e=>{e&&t&&(e=t(e,s)),e&&s.push(e)}))),s}}class EmailCollectionModel extends AbstractCollectionModel{static reviveFromJson(e){return super.reviveFromJson(e,(e=>EmailModel.reviveFromJson(e)))}static fromString(e){let t=new this;return t.fromString(e),t}toString(e,t){return this.map((s=>s.toLine(e,t))).join(", ")}fromString(e){if(e){let t,s={};Yt(e).forEach((e=>{e=new EmailModel(e.email,e.name),t=e.email||e.name,!t||!e.name&&s[t]||(s[t]=e)})),p(s,(e=>this.push(e)))}}}class AttachmentModel extends AbstractModel{constructor(){super(),this.checked=ko.observable(!0),this.mimeType="",this.fileName="",this.fileNameExt="",this.fileType=qe,this.cId="",this.contentLocation="",this.folder="",this.uid="",this.url="",this.mimeIndex="",this.estimatedSize=0,Ae(this,{isInline:!1,isLinked:!1})}static reviveFromJson(e){const t=super.reviveFromJson(e);return t&&(t.fileNameExt=et.getExtension(t.fileName),t.fileType=et.getType(t.fileNameExt,t.mimeType)),t}toggleChecked(e,t){_(t),e.checked(!e.checked())}friendlySize(){return et.friendlySize(this.estimatedSize)+(this.isLinked()?" 🔗":"")}contentId(){return this.cId.replace(/^<+|>+$/g,"")}isImage(){return We===this.fileType}isMp3(){return $e===this.fileType&&"mp3"===this.fileNameExt}isOgg(){return $e===this.fileType&&("oga"===this.fileNameExt||"ogg"===this.fileNameExt)}isWav(){return $e===this.fileType&&"wav"===this.fileNameExt}isText(){return Ke===this.fileType||He===this.fileType}pdfPreview(){return null!=navigator.mimeTypes["application/pdf"]&&je===this.fileType}hasPreview(){return this.isImage()||this.pdfPreview()||this.isText()}hasPreplay(){return Ss.supportedMp3&&this.isMp3()||Ss.supportedOgg&&this.isOgg()||Ss.supportedWav&&this.isWav()}get download(){return v(this.url?{fileName:this.fileName,data:this.url.replace(/^.+,/,"")}:{folder:this.folder,uid:this.uid,mimeIndex:this.mimeIndex,mimeType:this.mimeType,fileName:this.fileName,accountHash:M("accountHash")})}linkDownload(){return this.url||Z(this.download)}linkPreview(){return this.url||Y("View",this.download)}hasThumbnail(){return L("AttachmentThumbnails")&&this.isImage()&&!this.isLinked()}thumbnailStyle(){return this.hasThumbnail()?"background:url("+Y("ViewThumbnail",this.download)+")":null}linkPreviewMain(){let e="";switch(!0){case this.isImage():case this.pdfPreview():e=this.linkPreview();break;case this.isText():e=Y("ViewAsPlain",this.download)}return e}eventDragStart(e,t){const s=t.originalEvent||t;if(e&&s&&s.dataTransfer&&s.dataTransfer.setData){let e=this.linkDownload();e.startsWith("http")||(e=location.protocol+"//"+location.host+location.pathname+e),s.dataTransfer.setData("DownloadURL",this.mimeType+":"+this.fileName+":"+e)}return!0}iconClass(){return et.getTypeIconClass(this.fileType)}}class AttachmentCollectionModel extends AbstractCollectionModel{static reviveFromJson(e){const t=super.reviveFromJson(e,(e=>AttachmentModel.reviveFromJson(e)));let s=Ee(!0);return t.sort(((e,t)=>{if(e.isInline()){if(!t.isInline())return 1}else if(!t.isInline())return-1;return s.compare(e.fileName,t.fileName)})),t}findByCid(e){return e=e.replace(/^<+|>+$/g,""),this.find((t=>e===t.contentId()))}}class MimeHeaderModel extends AbstractModel{constructor(){super(),this.name="",this.value="",this.parameters=ko.observableArray()}}class MimeHeaderCollectionModel extends AbstractCollectionModel{static reviveFromJson(e){return super.reviveFromJson(e,(e=>MimeHeaderModel.reviveFromJson(e)))}getByName(e){return e=e.toLowerCase(),this.find((t=>t.name.toLowerCase()===e))}valueByName(e){const t=this.getByName(e);return t?t.value:""}valuesByName(e){return e=e.toLowerCase(),this.filter((t=>t.name.toLowerCase()===e)).map((e=>e.value))}}let ws=null,Es="";const ks=new Map,Cs=e=>e.querySelector("[autofocus]")?.focus(),As=new Set,Ts=e=>e&&ks.get(e)||null,Fs=(e,t)=>{if(e&&!e.__vm){const s=new e(t),i=s.viewModelTemplateID,r="rl-"+s.viewType,a=Is===s.viewType,o=k.getElementById(r);if(o){e.__vm=s;let t=a?D("dialog",{id:"V-"+i}):D("div",{id:"V-"+i,hidden:""});if(o.append(t),s.viewModelDom=t,a){t.showModal||(t.className="polyfill",t.showModal=()=>{t.backdrop||t.before(t.backdrop=D("div",{class:"dialog-backdrop"})),t.setAttribute("open",""),t.open=!0,t.backdrop.hidden=!1},t.close=()=>{t.backdrop.hidden=!0,t.removeAttribute("open",null),t.open=!1});const e=e=>{e.target===t&&"opacity"===e.propertyName&&(t.classList.contains("animate")?(s.afterShow?.(),O("rl-vm-visible",s)):(t.close(),s.afterHide?.()))};s.modalVisible.subscribe((e=>{e?(ue(t),As.add(s),t.style.zIndex=3001+2*As.size,t.showModal(),t.backdrop&&(t.backdrop.style.zIndex=3e3+2*As.size),s.keyScope.set(),setTimeout((()=>Cs(t)),1),requestAnimationFrame((()=>{t.offsetHeight,t.classList.add("animate")}))):(As.delete(s),s.onHide?.(),s.keyScope.unset(),t.classList.remove("animate")),Ns(0<As.size)})),t.addEventListener("transitionend",e)}O("rl-view-model.create",s),ko.applyBindingAccessorsToNode(t,{template:()=>({name:i})},s),s.onBuild?.(t),O("rl-view-model",s)}}return e?.__vm},Ms=(e,t)=>{e.viewModels.forEach((e=>{e.__vm&&Is!==e.__vm.viewType&&t(e.__vm,e.__vm.viewModelDom)}))},Ps=(e,t)=>{e.onHide?.(),Ms(e,((e,s)=>{s.hidden=!0,e.onHide?.(),t&&s.remove()})),mt.isMobile()&&N(!0)},Ls=(e,t)=>{if((e=e||Es)&&O("sm-show-screen",e+(t?"/"+t:""),1)){for(let e of As)e.tryToClose();let s=Ts(e);if(s||(s=Ts(Es),s&&(t=e+"/"+t,e=Es)),s?.__started){let e=ws&&s===ws;s.__builded||(s.__builded=!0,s.viewModels.forEach((e=>Fs(e,s))),s.onBuild?.()),setTimeout((()=>{ws&&!e&&Ps(ws),ws=s,e||(s.onShow?.(),Ms(s,((e,t)=>{e.beforeShow?.(),ue(t),t.hidden=!1,e.onShow?.(),Cs(t)}))),s.__cross?.parse(t)}),1)}}},Is="popups",xs=(e,t=[])=>{const s=Fs(e);s&&(t=t||[],s.beforeShow?.(...t),s.modalVisible(!0),s.onShow?.(...t))},Ns=ko.observable(!1),Rs=e=>{hasher.clear(),ks.forEach((e=>Ps(e,1))),ks.clear(),ws=null,Es="",e.forEach((e=>{const t=new e,s=t.screenName;Es||(Es=s),ks.set(s,t)})),ks.forEach((e=>{e.__started||(e.onStart(),e.__started=!0)}));const t=new Crossroads;t.addRoute(/^([^/]*)\/?(.*)$/,Ls),hasher.add(t.parse.bind(t)),hasher.init(),setTimeout((()=>C.remove("rl-started-trigger")),100);const s=A("rl-content"),i=A("rl-loading");s&&(s.hidden=!1),i?.remove()},Ds=(e,t)=>g(t,((t,s)=>{let i=e[t],r=(...t)=>r.canExecute()&&i.apply(e,t);r.canExecute=Ce((()=>s.call(e,e))),e[t]=r}));ko.decorateCommands=Ds;const Os={allowContacts:()=>!!M("contactsAllowed")};Ae(Os,{focusedState:"none",threadsAllowed:!1}),Os.focusedState.subscribe((e=>{["FolderList","MessageList","MessageView"].forEach((t=>{t===e&&(Ns()||G(e),mt.isMobile()&&N("FolderList"!==e)),A("V-Mail"+t).classList.toggle("focused",t===e)}))}));let _s=0;const Us=(e="")=>Q("Json")+m(e),Vs=e=>{const t=e?e.code:null;c.InvalidToken===t?setTimeout(rl.logoutReload,5e3):[c.AuthError,c.ConnectionError,c.DomainNotAllowed,c.AccountNotAllowed,c.MailServerError,c.UnknownError].includes(t)&&7<++_s&&rl.logoutReload()},qs={},Ks=(e,t,s)=>{let i=qs[e];qs[e]=null,i&&(clearTimeout(i.timeoutId),s||i.abort(new DOMException(e,t||"AbortError")))},Bs=(e,t,s,i,r)=>{s&&(s instanceof FormData?s.set("Action",e):s.Action=e);const a=new AbortController,o=a.signal;return qs[e]=a,a.timeoutId=i&&setTimeout((()=>Ks(e,"TimeoutError")),i),rl.fetchJSON(t,{signal:o},s).then((t=>(Ks(e,0,1),r?r(t):Promise.resolve(t)))).catch((e=>(clearTimeout(a.timeoutId),e.aborted=o.aborted,Promise.reject(e))))};class FetchError extends Error{constructor(e,t){super(t),this.code=e||c.JsonFalse}}class AbstractFetchRemote{abort(e,t){return Ks(e,t),this}streamPerLine(e,t,s){rl.fetch(Us(t),{},s).then((e=>e.body)).then((t=>{let s="";const i=t.getReader(),r=/\r\n|\n|\r/gm,a=new TextDecoder,o=({done:t,value:n})=>{for(s+=n?a.decode(n,{stream:!0}):"";;){let a=r.exec(s);if(!a){if(t)break;return void i.read().then(o)}e(s.slice(0,a.index)),s=s.slice(a.index+1),r.lastIndex=0}s.length&&e(s)};i.read().then(o)}))}request(e,t,s,i,r){s=s||{};const a=Date.now();Bs(e,Us(r),r?null:s||{},f(i??3e4),(async o=>{let n=0;if(o&&(o.Result?_s=0:(Vs(o),n=o.code||c.UnknownError)),111===n&&rl.app.ask&&await rl.app.ask.cryptkey())return this.request(e,t,s,i,r);t&&t(n,o,o?.epoch&&o.epoch<Math.floor(a/1e3)-60)})).catch((e=>{t&&t("TimeoutError"==e.name?3:"AbortError"==e.name?2:1,e)}))}setTrigger(e,t){e&&(t=!!t,(d(e)?e:[e]).forEach((e=>{e?.(t)})))}get(e,t){return Bs(e,t)}post(e,t,s,i){return this.setTrigger(t,!0),Bs(e,Us(),s||{},f(i,3e4),(async r=>(Ks(e,0,1),r?111===r?.code&&rl.app.ask&&await rl.app.ask.cryptkey()?this.post(e,t,s,i):(this.setTrigger(t,!1),r.Result&&e===r.Action?r:(Vs(r),Promise.reject(new FetchError(r?r.code:0,r?r.messageAdditional||r.message:"")))):Promise.reject(new FetchError(c.JsonParse)))))}}Object.assign(AbstractFetchRemote.prototype,{SUCCESS:0,ERROR:1,ABORT:2});var Hs=new class RemoteUserFetch extends AbstractFetchRemote{message(e,t,s){return t=m(t),s=f(s),!!(os(t)&&0<s)&&(this.abort("Message").request("Message",e,{},null,"Message/&q[]=/"+v([t,s,Os.threadsAllowed()&&bt.useThreads()?1:0,M("accountHash")])),!0)}saveSettings(e,t){this.request("SettingsUpdate",e,t)}saveSetting(e,t,s){this.saveSettings(s,{[e]:t})}};class AbstractView{constructor(e,t){this.viewModelTemplateID=e||this.constructor.name.replace("UserView",""),this.viewType=t,this.viewModelDom=null,this.keyScope={scope:"none",previous:"none",set:function(){this.previous=G(),G(this.scope)},unset:function(){G(this.previous)}}}querySelector(e){return this.viewModelDom.querySelector(e)}addObservables(e){Ae(this,e)}addComputables(e){Te(this,e)}addSubscribables(e){Fe(this,e)}}class AbstractViewPopup extends AbstractView{constructor(e){super("Popups"+e,Is),this.keyScope.scope=e,this.modalVisible=ko.observable(!1).extend({rateLimit:0}),this.close=()=>this.modalVisible(!1),this.tryToClose=()=>!1===this.onClose()||this.close(),V("escape,close","",e,(()=>(this.modalVisible()&&this.tryToClose(),!1)))}onClose(){}}AbstractViewPopup.showModal=function(e=[]){xs(this,e)},AbstractViewPopup.hidden=function(){return!this.__vm||!this.__vm.modalVisible()};class AbstractViewLeft extends AbstractView{constructor(e){super(e,"left"),this.toggleLeftPanel=R}}class AbstractViewRight extends AbstractView{constructor(e){super(e,"right")}}class AbstractViewSettings{addSetting(e,t){let s=e[0].toLowerCase()+e.slice(1),i=s+"Trigger";Ae(this,{[s]:M(e),[i]:o}),Fe(this,{[s]:(s=>{this[i](a),t?.(s),rl.app.Remote.saveSetting(e,s,(e=>{this[i](e?l:n),setTimeout((()=>this[i](o)),1e3)}))}).debounce(999)})}addSettings(e){e.forEach((e=>{let t=e[0].toLowerCase()+e.slice(1);this[t]||(this[t]=ko.observable(M(e))),this[t].subscribe((t=>rl.app.Remote.saveSetting(e,t)))}))}}class AbstractViewLogin extends AbstractView{constructor(e){super(e,"content"),this.formError=ko.observable(!1).extend({falseTimeout:500})}onBuild(e){e.classList.add("LoginView")}onShow(){A("rl-left").hidden=!0,A("rl-right").hidden=!0,rl.route.off()}onHide(){A("rl-left").hidden=!1,A("rl-right").hidden=!1}submitForm(){}}class OpenPgpKeyPopupView extends AbstractViewPopup{constructor(){super("OpenPgpKey"),Ae(this,{key:"",keyDom:null})}selectKey(){const e=this.keyDom();if(e){let t=getSelection(),s=k.createRange();t.removeAllRanges(),s.selectNodeContents(e),t.addRange(s)}navigator.clipboard&&navigator.clipboard.writeText(this.key()).then((()=>{}),(e=>{}))}onShow(e){this.key(e?e.armor:"")}onBuild(){V("a","meta","OpenPgpKey",(()=>(this.selectKey(),!1)))}}class AskPopupView extends AbstractViewPopup{constructor(){super("Ask"),Ae(this,{askDesc:"",yesButton:"",noButton:"",username:"",askUsername:!1,passphrase:"",askPass:!1,remember:!0,askRemeber:!1}),this.fYesAction=null,this.fNoAction=null,this.focusOnShow=!0}yesClick(){this.close(),u(this.fYesAction)&&this.fYesAction(this)}noClick(){this.close(),u(this.fNoAction)&&this.fNoAction(this)}onShow(e,t=null,s=null,i=!0,r=0,a=""){this.askDesc(e||""),this.askUsername(2&r),this.askPass(1&r),this.askRemeber(4&r),this.username(""),this.passphrase(""),this.remember(!0),this.yesButton(he(a||"GLOBAL/YES")),this.noButton(he(r?"GLOBAL/CANCEL":"GLOBAL/NO")),this.fYesAction=t,this.fNoAction=s,this.focusOnShow=i?r?'input[type="'+(2&r?"text":"password")+'"]':".buttonYes":""}afterShow(){this.focusOnShow&&this.querySelector(this.focusOnShow).focus()}onClose(){return this.noClick(),!1}onBuild(){shortcuts.add("tab,arrowright,arrowleft","","Ask",(()=>{let e=this.querySelector(".buttonYes"),t=this.querySelector(".buttonNo");return e.matches(":focus")?(t.focus(),!1):t.matches(":focus")?(e.focus(),!1):void 0}))}}const Gs=new WeakMap;Gs.ask=async(e,t,s)=>Gs.has(e)?{password:Gs.handle(e)}:await AskPopupView.password(t,s,5);const js={};Gs.handle=(e,t)=>{const s=bt.keyPassForget();return s&&!js[e]&&(js[e]=(()=>Gs.delete(e)).debounce(1e3*s)),t&&Gs.set(e,t),s&&js[e](),Gs.get(e)};const Ws=(e,t)=>e.find((e=>(e.can_sign||e.can_decrypt)&&(e.for(t)||e.subkeys.find((e=>t==e.keyid||t==e.fingerprint))))),$s=new class{constructor(){this.keyring,this.publicKeys=ko.observableArray(),this.privateKeys=ko.observableArray()}loadKeyrings(){this.keyring=null,this.publicKeys([]),this.privateKeys([]),L("GnuPG")&&Hs.request("GnupgGetKeys",((e,t)=>{if(t?.Result){this.keyring=t.Result;const e=(e,t)=>{const s=[];return e.id=e.subkeys[0].keyid,e.fingerprint=e.subkeys[0].fingerprint,e.uids.forEach((e=>e.email&&s.push(e.email))),e.emails=s,e.for=e=>s.includes(IDN.toASCII(e)),e.askDelete=ko.observable(!1),e.openForDeletion=ko.observable(null).askDeleteHelper(),e.remove=()=>{e.askDelete()&&Hs.request("GnupgDeleteKey",((s,i)=>{i&&(s?alert(i.message):i.Result&&(t?this.privateKeys.remove(e):this.publicKeys.remove(e)))}),{keyId:e.id,isPrivate:t})},t&&(e.password=async t=>{const s=await Gs.ask(e,"GnuPG key<br>"+e.id+" "+e.emails[0],t);return s&&s.remember&&Gs.handle(e,s.password),s?.password}),e.fetch=async s=>{if(e.armor)s&&s();else{let i=t?await e.password("OPENPGP/POPUP_VIEW_TITLE"):"";if(null!=i)try{const r=await Hs.post("GnupgExportKey",null,{keyId:e.id,isPrivate:t,passphrase:i});r?.Result?(e.armor=r.Result,s&&s()):Gs.delete(e)}catch(t){Gs.delete(e),alert(t.message)}}return e.armor},e.view=()=>e.fetch((()=>xs(OpenPgpKeyPopupView,[e]))),e},s=Ee(),i=e=>e.sort(((e,t)=>s.compare(e.emails[0],t.emails[0])||s.compare(e.id,t.id)));this.publicKeys(i(t.Result.public.map((t=>e(t,0))))),this.privateKeys(i(t.Result.private.map((t=>e(t,1)))))}}))}isSupported(){return L("GnuPG")}storeKeyPair(e,t){Hs.request("PgpStoreKeyPair",((e,s)=>{t?.(e,s)}),e)}hasPublicKeyForEmails(e){const t=e.length,s=t?e.filter((e=>this.publicKeys.find((t=>t.for(e))))).length:0;return s&&s===t}getPublicKeyFingerprints(e){const t=[];return e.forEach((e=>{t.push(this.publicKeys.find((t=>t.for(e))).fingerprint)})),t}getPrivateKeyFor(e){return Ws(this.privateKeys,e)}async decrypt(e){const t=e.pgpEncrypted();if(t){let s,i=[e.to[0].email].concat(t.keyIds),r=i.length;for(;r--&&(s=Ws(this.privateKeys,i[r]),!s););if(s){let i={folder:e.folder,uid:e.uid,partId:t.partId,keyId:s.id,passphrase:await s.password("CRYPTO/DECRYPT"),data:""};if(null!=i.passphrase)try{const e=await Hs.post("GnupgDecrypt",null,i);if(e?.Result?.data)return e.Result;throw e}catch(e){throw Gs.delete(s),e}}}}async verify(e){let t=e.pgpSigned();if(t){t={...t},t.folder=e.folder,t.uid=e.uid,t.bodyPart&&(t.bodyPart=t.bodyPart.raw,t.sigPart=t.sigPart.body);let s=await Hs.post("PgpVerifyMessage",null,t);if(s?.Result)return{fingerprint:s.Result.fingerprint,success:0==s.Result.status,error:s.Result.message}}}async sign(e){return await e.password("CRYPTO/SIGN")}},Js=()=>!!window.openpgp,zs=(e,t)=>e.find((e=>e.for(t)||t==e.id||t==e.fingerprint)),Ys=async(e,t="SIGN")=>{if(e.key.isDecrypted())return e.key;const s=e.id,i=await Gs.ask(e,"OpenPGP.js key<br>"+s+" "+e.emails[0],"CRYPTO/"+t);if(i){const t=i.password,s=await openpgp.decryptKey({privateKey:e.key,passphrase:t});return s&&i.remember&&Gs.handle(e,t),s}},Zs=Ee(),Xs=e=>e.sort(((e,t)=>Zs.compare(e.emails[0],t.emails[0])||Zs.compare(e.id,t.id))),Qs=e=>Xs((e||[]).filter(((e,t,s)=>s.findIndex((t=>t.fingerprint==e.fingerprint))===t))),ei="openpgp-public-keys",ti="openpgp-private-keys",si=window.localStorage,ii=async e=>{let t,s=[],i=JSON.parse(si.getItem(e)),r=h(i);for(;r--;)try{t=await openpgp.readKey({armoredKey:i[r]}),t.err||s.push(new OpenPgpKeyModel(i[r],t))}catch(e){}return s},ri=(e,t)=>{let s=e.map((e=>e.armor));s.length?si.setItem(t,JSON.stringify(s)):si.removeItem(t)};class OpenPgpKeyModel{constructor(e,t){this.key=t,this.id=t.getKeyID().toHex().toUpperCase(),this.fingerprint=t.getFingerprint(),this.can_encrypt=!!t.getEncryptionKey(),this.can_sign=!!t.getSigningKey(),this.emails=t.users.map((e=>IDN.toASCII(e.userID.email))).filter((e=>e)),this.armor=e,this.askDelete=ko.observable(!1),this.openForDeletion=ko.observable(null).askDeleteHelper()}for(e){return this.emails.includes(IDN.toASCII(e))}view(){xs(OpenPgpKeyPopupView,[this])}remove(){this.askDelete()&&(this.key.isPrivate()?(ai.privateKeys.remove(this),ri(ai.privateKeys,ti)):(ai.publicKeys.remove(this),ri(ai.publicKeys,ei)))}}const ai=new class{constructor(){this.publicKeys=ko.observableArray(),this.privateKeys=ko.observableArray()}loadKeyrings(){Js()&&ii(ei).then((e=>{this.publicKeys(Qs(e))})).finally((()=>{ii(ti).then((e=>{this.privateKeys(Qs(e))})).finally((()=>{this.loadBackupKeys()}))}))}loadBackupKeys(){Hs.request("GetPGPKeys",((e,t)=>!e&&t.Result&&this.importKeys(t.Result)))}isSupported(){return Js()}importKey(e){this.importKeys([e])}async importKeys(e){if(Js()){const t=this.privateKeys(),s=this.publicKeys();for(const i of e)try{let e=await openpgp.readKey({armoredKey:i});if(!e.err){e=new OpenPgpKeyModel(i,e);const r=e.key.isPrivate()?t:s;r.find((t=>t.fingerprint==e.fingerprint))||r.push(e)}}catch(e){}this.privateKeys(Xs(t)),this.publicKeys(Xs(s)),ri(t,ti),ri(s,ei)}}storeKeyPair(e){Js()&&(openpgp.readKey({armoredKey:e.publicKey}).then((t=>{this.publicKeys.push(new OpenPgpKeyModel(e.publicKey,t)),ri(this.publicKeys,ei)})),openpgp.readKey({armoredKey:e.privateKey}).then((t=>{this.privateKeys.push(new OpenPgpKeyModel(e.privateKey,t)),ri(this.privateKeys,ti)})))}hasPublicKeyForEmails(e){const t=e.length,s=t?e.filter((e=>this.publicKeys().find((t=>t.for(e))))).length:0;return s&&s===t}getPrivateKeyFor(e){return zs(this.privateKeys,e)}async decrypt(e,t){const s=await openpgp.readMessage({armoredMessage:e}),i=this.privateKeys(),r=s.getEncryptionKeyIDs().map((e=>e.bytes));let a,o=i.length;for(;o--;)if((await i[o].key.getDecryptionKeys()).find((e=>r.includes(e.getKeyID().bytes)))){a=i[o];break}if(a)try{const e=await Ys(a,"DECRYPT");if(e){const i=zs(this.publicKeys,t);return await openpgp.decrypt({message:s,verificationKeys:i?.key,decryptionKeys:e})}}catch(e){alert(e)}}async verify(e){const t=e.pgpSigned(),s=this.publicKeys().find((t=>t.for(e.from[0].email)));if(t&&s){let i;if(t.folder=e.folder,t.uid=e.uid,t.tryGnuPG=0,i=t.sigPartId?await Hs.post("PgpVerifyMessage",null,t):t.bodyPart?{Result:{text:t.bodyPart.raw,signature:t.sigPart.body}}:{Result:{text:e.plain(),signature:null}},i){const e=i.Result.signature?await openpgp.readSignature({armoredSignature:i.Result.signature}):null,t=e?await openpgp.createMessage({text:i.Result.text}):await openpgp.readCleartextMessage({cleartextMessage:i.Result.text});let r=await openpgp.verify({message:t,verificationKeys:s.key,signature:e});return{fingerprint:s.fingerprint,success:r&&!!r.signatures.length}}}}async sign(e,t,s){const i=await Ys(t);if(i){const t=s?await openpgp.createMessage({text:e}):await openpgp.createCleartextMessage({text:e});return await openpgp.sign({message:t,signingKeys:i,detached:!!s})}throw"Sign cancelled"}async encrypt(e,t,s){const i=t.length;if(t=t.map((e=>this.publicKeys().find((t=>t.for(e))))).filter((e=>e)),i===t.length){if(s&&!(s=await Ys(s)))return;return await openpgp.encrypt({message:await openpgp.createMessage({text:e}),encryptionKeys:t.map((e=>e.key)),signingKeys:s})}throw"Encrypt failed"}};let oi=null;const ni={keyring:null,loadKeyring(e){if(e=e||M("Email"),window.mailvelope){const t=e=>{oi=e};mailvelope.getKeyring().then(t,(s=>{e&&mailvelope.createKeyring(e).then(t,(e=>{}))})),addEventListener("mailvelope-disconnect",(e=>{alert("Mailvelope is updated to version "+e.detail.version+". Reload page")}),!1)}else addEventListener("mailvelope",(()=>this.loadKeyring(e)))},async hasPublicKeyForEmails(e){const t=oi&&await oi.validKeyForAddress(e),s=t&&Object.entries(t);return s&&s.filter((e=>e[1])).length===e.length},getPrivateKeyFor:async e=>!(!oi||!await oi.hasPrivateKey({email:e}))&&["mailvelope",e],async decrypt(e){if(oi){const t=e.from[0].email,s=e.plain();try{let i=[...e.from,...e.to,...e.cc].validUnique(),r=i.length;for(;r--;)if(await this.getPrivateKeyFor(i[r].email)){const i=e.body;i.textContent="";let r=await mailvelope.createDisplayContainer("#"+i.id,s,oi,{senderAddress:t});if(r){if(!r.error?.message)return i.classList.add("mailvelope"),!0;"PWD_DIALOG_CANCEL"!==r.error.code&&alert(r.error.code+": "+r.error.message)}break}}catch(e){}}}},li="-----BEGIN PGP MESSAGE-----",ci=new class{init(){L("OpenPGP")&&window.crypto&&crypto.getRandomValues?rl.loadScript(M("StaticLibsJs").replace("/libs.","/openpgp.")).then((()=>this.loadKeyrings())).catch((e=>{this.loadKeyrings()})):this.loadKeyrings()}loadKeyrings(e){ni.loadKeyring(e),ai.loadKeyrings(),$s.loadKeyrings()}isSupported(){return!!(ai.isSupported()||$s.isSupported()||window.mailvelope)}isEncrypted(e){return 0===e.trim().indexOf(li)}importKey(e,t,s){(t||s)&&Hs.request("PgpImportKey",((e,s)=>{t&&s?.Result&&$s.loadKeyrings(),e&&alert(s.message)}),{key:e,gnuPG:t,backup:s}),ai.importKey(e)}hasPublicKeyForEmails(e){if(e.length){if($s.hasPublicKeyForEmails(e))return"gnupg";if(ai.hasPublicKeyForEmails(e))return"openpgp"}return!1}async decrypt(e){const t=e.plain();if(!this.isEncrypted(t))throw Error("Not armored text");if(ai.isSupported()){const s=e.from[0].email;let i=await ai.decrypt(t,s);if(i)return i}return await ni.decrypt(e)||$s.decrypt(e)}async verify(e){const t=e.pgpSigned(),s=e.from[0].email;if(t){if(!t.sigPartId&&ai.hasPublicKeyForEmails([s]))return ai.verify(e);if($s.hasPublicKeyForEmails([s]))return $s.verify(e)}}getPublicKeyOfEmails(e){if(e.length){let t={};return e.forEach((e=>{ai.publicKeys().forEach((s=>{s.for(e)&&(t[e]=s.armor)})),$s.publicKeys.map((async s=>{!t[e]&&s.for(e)&&(t[e]=await s.fetch())}))})),t}return!1}};function di(e,t){const s=function(e){class MimePart{header(e){return this.headers?.[e]}headerValue(e){return this.header(e)?.value}get raw(){return e.slice(this.start,this.end)}get bodyRaw(){return e.slice(this.bodyStart,this.bodyEnd)}get body(){let e=this.bodyRaw,t=this.header("content-type")?.params.charset,s=this.headerValue("content-transfer-encoding")?.toLowerCase();return"quoted-printable"==s?e=$t(e):"base64"==s&&(e=jt(e.replace(/\r?\n/g,""))),zt(t,e)}get dataUrl(){let e=this.bodyRaw,t=this.headerValue("content-transfer-encoding")?.toLowerCase();return"base64"==t?e=e.replace(/\r?\n/g,""):("quoted-printable"==t&&(e=$t(e)),e=Wt(e)),"data:"+this.headerValue("content-type")+";base64,"+e}forEach(e){e(this),this.parts.forEach((t=>t.forEach(e)))}getByContentType(e){if(e==this.headerValue("content-type")?.toLowerCase())return this;let t,s=0,i=this.parts;for(;s<i.length;++s)if(t=i[s].getByContentType(e))return t}}const t=["from","reply-to","to","cc","bcc"],s=(e,i=0,r="")=>{let a=new MimePart,o=e.match(/^[\s\S]+?\r?\n\r?\n/)?.[0],n={};if(r&&(a.id=r,a.start=i,a.end=i+e.length),a.parts=[],o){o.replace(/\r?\n\s+/g," ").split(/\r?\n/).forEach((e=>{let s=e.match(/^([^:]+):\s*([^;]+)/),i={};if(s){[...e.matchAll(/;\s*([^;=]+)=\s*"?([^;"]+)"?/g)].forEach((e=>i[e[1].trim().toLowerCase()]=e[2].trim()));let r=s[1].trim().toLowerCase();t.includes(r)?s[2]=Yt(s[2]):"keywords"===r?(s[2]=s[2].split(",").forEach((e=>Jt(e.trim()))),s[2]=(n[r]?.value||[]).concat(s[2])):(s[2]=Jt(s[2].trim()),"comments"===r&&(s[2]=(n[r]?.value||[]).push(s[2]))),n[r]={value:s[2],params:i}}})),a.bodyStart=i+o.length,a.bodyEnd=i+e.length;let l=n["content-type"]?.params.boundary;if(l){a.boundary=l;let t=new RegExp("(?:^|\r?\n)--"+RegExp.escape(l)+"(?:--)?(?:\r?\n|$)","g"),i=e.slice(o.length),n=i.split(t),c=a.bodyStart;[...i.matchAll(t)].forEach((([e],t)=>{t||(a.bodyText=n[0]),"--"!=e.trim().slice(-2)&&(c+=n[t].length+e.length,a.parts.push(s(n[1+t],c,(r?r+".":"")+(1+t))))}))}a.headers=n}return a};return s(e)}(e);if(s.headers){let e=s.getByContentType("text/html"),i=s.headerValue("subject");e=e?e.body:"",i&&t.subject(i),["from","to"].forEach((e=>{const i=t[e];s.headerValue(e)?.forEach((e=>{((e=new EmailModel(e.email,e.name)).email&&e.name||!i.find((t=>t.email==e.email)))&&i.push(e)}))})),s.forEach((s=>{let i=s.header("content-disposition"),r=s.header("content-id"),a=s.header("content-type");if(r||i){let o=new AttachmentModel;if(o.mimeType=a.value,o.fileName=a.name||i&&i.params.filename||"",o.fileNameExt=o.fileName.replace(/^.+(\.[a-z]+)$/,"$1"),o.fileType=et.getType("",a.value),o.url=s.dataUrl,o.estimatedSize=s.body.length,o.cId=r?r.value:"",r&&e){let t="cid:"+o.contentId(),s=e.includes(t);o.isInline(s),o.isLinked(s),s&&(e=e.replace('src="'+t+'"','src="'+o.url+'"').replace("src='"+t+"'","src='"+o.url+"'"))}else t.attachments.push(o)}else if("multipart/signed"===a.value){let e=a.params.protocol;"application/pgp-signature"===e?t.pgpSigned({micAlg:a.micalg,bodyPart:s.parts[0],sigPart:s.parts[1]}):"application/pkcs7-signature"===e.replace("x-")&&t.smimeSigned({micAlg:a.micalg,bodyPart:s,sigPart:s.parts[1],detached:!0})}else"application/pkcs7-mime"===a.value&&t.smimeSigned({micAlg:a.micalg,bodyPart:s,detached:!1})}));const r=s.getByContentType("text/plain");t.plain(r?r.body:""),t.html(e)}else t.plain(e);t.plain().includes(li)&&t.pgpSigned(!0)}const hi="<html>\n<head>\n\t<meta charset=\"utf-8\">\n\t<title></title>\n\t<style>\nhtml, body {\n\tmargin: 0;\n\tpadding: 0;\n}\n\nheader {\n\tbackground: rgba(125,128,128,0.3);\n\tborder-bottom: 1px solid #888;\n}\n\nheader h1 {\n\tfont-size: 120%;\n}\n\nheader * {\n\tmargin: 5px 0;\n}\n\nheader time {\n\tfloat: right;\n}\n\nblockquote {\n\tborder-left: 2px solid rgba(125,128,128,0.5);\n\tmargin: 0;\n\tpadding: 0 0 0 10px;\n}\n\npre {\n\twhite-space: pre-wrap;\n\tword-wrap: break-word;\n\tword-break: normal;\n}\n\nbody > * {\n\tpadding: 0.5em 1em;\n}\n\n#attachments > * {\n\tborder: 1px solid rgba(125,128,128,0.5);\n\tpadding: 0.25em;\n\tmargin-right: 1em;\n}\n#attachments > *::before {\n\tcontent: '📎 ';\n}\n\t</style>\n</head>\n<body></body>\n</html>",ui=e=>Vt(e.html(),e.attachments(),"#rl-msg-"+e.hash),mi=(e,t)=>{const s=t.toLowerCase(),i=e.flags,r=i.includes(s);Hs.request("MessageSetKeyword",(e=>{e||(r?i.remove(s):i.push(s))}),{folder:e.folder,uids:e.uid,keyword:t,setAction:r?0:1})},pi=(e,t,s)=>e.forEach((e=>t[e.email]||s.has(e.email)||s.set(e.email,e)));class MessageModel extends AbstractModel{constructor(){super(),Object.assign(this,{folder:"",uid:0,hash:"",from:new EmailCollectionModel,to:new EmailCollectionModel,cc:new EmailCollectionModel,bcc:new EmailCollectionModel,sender:new EmailCollectionModel,replyTo:new EmailCollectionModel,deliveredTo:new EmailCollectionModel,body:null,draftInfo:[],dkim:[],spf:[],dmarc:[],messageId:"",inReplyTo:"",references:"",hasVirus:null,priority:3,senderEmailsString:"",senderClearEmailsString:"",isSpam:!1,spamScore:0,spamResult:"",size:0,readReceipt:"",preview:null,attachments:ko.observableArray(new AttachmentCollectionModel),threads:ko.observableArray(),threadUnseen:ko.observableArray(),unsubsribeLinks:ko.observableArray(),flags:ko.observableArray(),headers:ko.observableArray(new MimeHeaderCollectionModel)}),Ae(this,{subject:"",plain:"",html:"",dateTimestamp:0,dateTimestampSource:0,focused:!1,selected:!1,checked:!1,isHtml:!1,hasImages:!1,hasExternals:!1,hasTracking:!1,encrypted:!1,pgpSigned:null,pgpEncrypted:null,pgpDecrypted:!1,smimeSigned:null,smimeEncrypted:null,smimeDecrypted:!1,id:"",linkedData:[]}),Te(this,{attachmentIconClass:()=>this.encrypted()?"icon-lock":et.getAttachmentsIconClass(this.attachments()),threadsLen:()=>rl.app.messageList.threadUid()?0:this.threads().length,threadUnseenLen:()=>rl.app.messageList.threadUid()?0:this.threadUnseen().length,threadsLenText:()=>{const e=this.threadUnseenLen();return this.threadsLen()+(e>0?"/"+e:"")},isUnseen:()=>!this.flags().includes("\\seen"),isFlagged:()=>this.flags().includes("\\flagged"),isDeleted:()=>this.flags().includes("\\deleted"),tagOptions:()=>{const e=[];return hs.currentFolder().optionalTags().forEach((t=>{let s=t.toLowerCase();e.push({css:"msgflag-"+s,value:t,checked:this.flags().includes(s),label:he("MESSAGE_TAGS/"+s,0,t),toggle:()=>mi(this,t)})})),e},whitelistOptions:()=>{let e=[];if("match"===bt.viewImages()){let t=this.from[0],s=bt.viewImagesWhitelist(),i={};this.html().match(/src=["'][^"']+/g)?.forEach((t=>{t=t.replace(/^.+(:\/\/[^/]+).+$/,"$1"),i[t]?++i[t]:(i[t]=1,e.push(t))})),e=e.filter((e=>!s.includes(e))).sort(((e,t)=>i[e]<i[t]?1:i[e]>i[t]?-1:e.localeCompare(t))),t&&e.unshift(t.email)}return e}}),this.smimeSigned.subscribe((e=>e?.body&&di(e.body,this)))}get requestHash(){return v({folder:this.folder,uid:this.uid,mimeType:xe,fileName:(this.subject()||"message")+"-"+this.hash+".eml",accountHash:M("accountHash")})}toggleTag(e){mi(this,e)}spamStatus(){let e=this.spamResult;return e?he(this.isSpam?"GLOBAL/SPAM":"GLOBAL/NOT_SPAM")+": "+e:""}friendlySize(){return et.friendlySize(this.size)}computeSenderEmail(){const e=this[[hs.sentFolder(),hs.draftsFolder()].includes(this.folder)?"to":"from"];this.senderEmailsString=e.toString(!0),this.senderClearEmailsString=e.map((e=>e?.email)).filter((e=>e)).join(", ")}revivePropertiesFromJson(e){if(super.revivePropertiesFromJson(e)){this.computeSenderEmail();let e,t=this.headers();return e=t.valueByName("X-MSMail-Priority")||t.valueByName("Importance")||t.valueByName("X-Priority"),e&&(/[h12]/.test(e[0])?this.priority=1:/[l45]/.test(e[0])&&(this.priority=5)),(e=t.valueByName("List-Unsubscribe"))&&this.unsubsribeLinks(e.split(",").map((e=>e.replace(/^[ <>]+|[ <>]+$/g,"")))),t.valueByName("X-Virus")&&(this.hasVirus=!0),(e=t.valueByName("X-Virus-Status"))&&(e.includes("infected")?this.hasVirus=!0:e.includes("clean")&&(this.hasVirus=!1)),!0}}lineAsCss(e=1){let t=[];return g({selected:this.selected(),checked:this.checked(),unseen:this.isUnseen(),focused:this.focused(),priorityHigh:1===this.priority,withAttachments:!!this.attachments().length},((e,s)=>s&&t.push(e))),e&&this.flags().forEach((e=>t.push("msgflag-"+e))),t.join(" ")}indent(){return this.level?"margin-left:"+this.level+"em":null}viewRaw(){return Y("ViewAsPlain",this.requestHash)}downloadLink(){return Y("Download",this.requestHash)}replyEmails(e){const t=new Map,s=e||{};return pi(this.replyTo,s,t),t.size||pi(this.from,s,t),t.size?[...t.values()]:[this.to[0]]}replyAllEmails(e){const t=new Map,s=new Map,i=e||{};return pi(this.replyTo,i,t),t.size||pi(this.from,i,t),pi(this.to,i,t),pi(this.cc,i,s),[[...t.values()],[...s.values()]]}viewBody(e){const t=this.body;if(t){if(e){let e=ui(this);this.hasExternals(e.hasExternals),this.hasImages(!!e.hasExternals),this.hasTracking(!!e.tracking),this.linkedData(e.linkedData),t.innerHTML=e.html,this.isSpam||hs.spamFolder()==this.folder||("always"===bt.viewImages()&&this.showExternalImages(),"match"===bt.viewImages()&&this.showExternalImages(1))}else t.innerHTML=Bt(this.plain()?this.plain().replace(/-----BEGIN PGP (SIGNED MESSAGE-----(\r?\n[^\r\n]+)+|SIGNATURE-----[\s\S]*)/gs,"").trim():qt(t.innerHTML||ui(this).html)),this.hasImages(!1);return t.classList.toggle("html",e),t.classList.toggle("plain",!e),this.isHtml(e),!0}}viewHtml(){return this.html()&&this.viewBody(!0)}viewPlain(){return this.viewBody(!1)}swapColors(){const e=this.body?.classList;e&&e.toggle("swapColors")}popupMessage(e){const t=this.dateTimestamp()||0,s=this.cc.toString(),i=this.bcc.toString(),r=0<t?new Date(1e3*t):null,a=open("","sm-msg-"+this.requestHash,bt.messageNewWindow()?"innerWidth="+A("V-MailMessageView").clientWidth:""),o=a.document,n=Ut(this.subject()),l=this.isHtml()?"div":"pre",c=`<div>${Ut(he("GLOBAL/TO"))}: ${Ut(this.to)}</div>`+(s?`<div>${Ut(he("GLOBAL/CC"))}: ${Ut(s)}</div>`:"")+(i?`<div>${Ut(he("GLOBAL/BCC"))}: ${Ut(i)}</div>`:""),d=getComputedStyle(k.querySelector(".messageView")),h=e=>d.getPropertyValue(e);let u="";this.attachments.forEach((e=>{u+=`<a href="${e.linkDownload()}">${e.fileName}</a>`})),o.write(hi.replace("<title>","<title>"+n).replace("<body>",`<body style="background-color:${h("background-color")};color:${h("color")}"><header><h1>${n}</h1><time>${Ut(r?r.format("LLL",0,re.hourCycle()):"")}</time><div>${Ut(this.from)}</div>${c}</header><${l}>${this.bodyAsHTML()}</${l}>`).replace("</body>",`<div id="attachments">${u}</div></body>`)),o.close(),!0===e&&setTimeout((()=>a.print()),100)}printMessage(){this.popupMessage(!0)}showExternalImages(e){const t=this.body;if(t&&this.hasImages()){e&&(e=[],bt.viewImagesWhitelist().trim().split(/[\s\r\n,;]+/g).forEach((t=>{(t=t.split("+"))[0]=t[0].trim(),!t[0]||t.includes("spf")&&"pass"!==this.spf[0]?.[0]||t.includes("dkim")&&"pass"!==this.dkim[0]?.[0]||t.includes("dmarc")&&"pass"!==this.dmarc[0]?.[0]||e.push(t[0].replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&"))})),(e=e.join("|").replace(/\|+/g,"|"))&&(e=new RegExp(e),this.from[0]?.email.match(e)&&(e=null)));let s,i=!1,r=t=>{if(null==e||e&&t.match(e))return!0;i=!0},a="data-x-src",o=!!M("proxyExternalImages");t.querySelectorAll("img["+a+"]").forEach((e=>{s=e.getAttribute(a),r(s)&&(e.src=o?X(s):s)})),t.querySelectorAll("[data-x-style-url]").forEach((e=>{JSON.parse(e.dataset.xStyleUrl).forEach((t=>{r(t[1])&&(e.style[t[0]]="url('"+(o?X(t[1]):t[1])+"')")}))})),this.hasImages(i)}}bodyAsHTML(){if(this.body){let e=this.body.cloneNode(!0);return e.querySelectorAll(".sm-bq-switcher").forEach((e=>e.replaceWith(e.lastElementChild))),(e.querySelector(".mail-body")||e).innerHTML}return ui(this).html||Bt(this.plain())}}const gi=()=>(k.fullscreenElement||k.webkitFullscreenElement)===T,fi=()=>gi()&&(k.exitFullscreen||k.webkitExitFullscreen).call(k),bi=ko.observable(!1),yi=()=>bi()?fi():T.requestFullscreen();if(T){let e="fullscreenchange";!T.requestFullscreen&&T.webkitRequestFullscreen&&(T.requestFullscreen=T.webkitRequestFullscreen,e="webkit"+e),T.requestFullscreen&&k.addEventListener(e,(()=>{bi(gi()),C.toggle("rl-fullscreen",gi())}))}const vi=new class{constructor(){Ae(this,{message:null,error:"",loading:!1,bodiesDom:null}),Fe(this,{message:t=>{clearTimeout(this.MessageSeenTimer),A("rl-right").classList.toggle("message-selected",!!t),t?bt.usePreviewPane()||Os.focusedState(s):(Os.focusedState(e),fi()),[...this.bodiesDom()?.children||[]].forEach((e=>e.hidden=!0))}}),this.purgeCache=this.purgeCache.throttle(3e4)}purgeCache(e){const t=this.bodiesDom()?.children||[];let s=Math.max(0,t.length-(e?0:15));for(;s--;)t[s].remove(),t[s].message&&(t[s].message.body=null)}};class MessageCollectionModel extends AbstractCollectionModel{static reviveFromJson(e){let t=vi.message();return super.reviveFromJson(e,(e=>(t&&t.hash===e.hash?(t.revivePropertiesFromJson(e),e=t):e=MessageModel.reviveFromJson(e),e)))}}const Si=Ie();Ae(Si,{email:"",loading:!1});const wi=window.Notification,Ei=()=>wi?.permission||"denied",ki=()=>"denied"===Ei(),Ci=()=>"granted"===Ei(),Ai=e=>{focus(),e.folder&&e.uid?O("mailbox.message.show",e):e.Url&&hasher.setHash(e.Url)};let Ti=!1,Fi=navigator.serviceWorker;Fi&&(ServiceWorkerRegistration&&ServiceWorkerRegistration.prototype.showNotification?Fi.addEventListener("message",(e=>{const t=JSON.parse(e.data);"notificationclick"===t?.action&&Ai(t.data)})):Fi=null);const Mi=new class{constructor(){Ae(this,{enabled:!1,allowed:!ki()}),this.enabled.subscribe((e=>{Ti=!!e,e&&wi&&!Ci()&&wi.requestPermission((()=>this.allowed(!ki())))}))}display(e,t,s,i){if(Ti&&Ci()){const r={body:t,icon:i||ee("images/icon-message-notification.png"),data:s};if(s?.uid&&(r.tag=s.uid),Fi)Fi.register(ee("js/serviceworker.js"),{scope:"/"}).then((()=>Fi.ready.then((t=>t.showNotification(e,r).then((()=>t.getNotifications().then((()=>{t.active.postMessage("")})))))))).catch((e=>{Fi=null}));else{const t=new wi(e,r);t.show?.(),t.onclick=s?()=>Ai(s):null,setTimeout((()=>t.close()),7e3)}}}},Pi=e=>e.checked(),Li=e=>e.isDeleted(),Ii=e=>{rl.route.off(),hasher.replaceHash(e),rl.route.on()},xi=ko.observable(!1).extend({falseTimeout:500}),Ni=ko.observableArray().extend({debounce:0});let Ri;Ae(Ni,{count:0,listSearch:"",listLimited:0,threadUid:0,page:1,pageBeforeThread:1,error:"",endHash:"",endThreadUid:0,loading:!1,isIncomplete:!1,selectedMessage:null,focusedMessage:null}),Te(Ni,{isLoading:()=>{const e=Ni.loading()|Ni.isIncomplete();return C.toggle("list-loading",e),e},isArchiveFolder:()=>hs.archiveFolder()===Ni().folder,isDraftFolder:()=>hs.draftsFolder()===Ni().folder,isSentFolder:()=>hs.sentFolder()===Ni().folder,isSpamFolder:()=>hs.spamFolder()===Ni().folder,isTrashFolder:()=>hs.trashFolder()===Ni().folder,archiveAllowed:()=>![ls,Ni().folder].includes(hs.archiveFolder())&&!Ni.isDraftFolder(),canMarkAsSpam:()=>!(ls===hs.spamFolder()|Ni.isSentFolder()|Ni.isDraftFolder()|Ni.isSpamFolder()),pageCount:()=>Math.max(1,Math.ceil(Ni.count()/bt.messagesPerPage())),mainSearch:{read:Ni.listSearch,write:e=>hasher.setHash(ie(hs.currentFolderFullNameHash(),1,e.toString().trim(),Ni.threadUid()))},listCheckedOrSelected:()=>{const e=Ni.selectedMessage(),t=Ni.filter((e=>Pi(e)));return t.length?t:e?[e]:[]},listCheckedOrSelectedUidsWithSubMails:()=>{let e=new Set;return Ni.listCheckedOrSelected().forEach((t=>{e.add(t.uid),e.folder=t.folder,1<t.threadsLen()&&t.threads().forEach(e.add,e)})),e}}),Ni.listChecked=Ce((()=>Ni.filter(Pi))).extend({rateLimit:0}),Ni.hasChecked=Ce((()=>!!Ni.find(Pi))).extend({rateLimit:0}),Ni.hasCheckedOrSelected=Ce((()=>!!Ni.selectedMessage()|!!Ni.find(Pi))).extend({rateLimit:50}),Ni.hasCheckedOrSelectedAndDeleted=Ce((()=>!!Ni.listCheckedOrSelected().find(Li))).extend({rateLimit:50}),Ni.hasCheckedOrSelectedAndUndeleted=Ce((()=>!!Ni.listCheckedOrSelected().find((e=>!e?.isDeleted())))).extend({rateLimit:50}),Ni.notifyNewMessages=(e,t)=>{if(is()===e&&h(t)){Ss.playNotification();const e=t.length;3<e?Mi.display(Si.email(),he("MESSAGE_LIST/NEW_MESSAGE_NOTIFICATION",{COUNT:e}),{Url:ie(t[0].folder)}):t.forEach((e=>{Mi.display(EmailCollectionModel.reviveFromJson(e.from).toString(),e.subject,{folder:e.folder,uid:e.uid})}))}},Ni.canSelect=()=>!xi()&&bt.usePreviewPane(),Ni.reload=(e=!1,t=!1)=>{let s=(Ni.page()-1)*bt.messagesPerPage(),i=hs.currentFolderFullName();t&&as(i,""),e&&(Ni.page(1),Ni.pageBeforeThread(1),s=0,Ii(ie(hs.currentFolderFullNameHash(),Ni.page(),Ni.listSearch(),Ni.threadUid()))),Ri!=i&&(Ri=i,Ni([])),Ni.loading(!0);let r="",a=os(i),o=a?.etag||"",n={folder:i,offset:s,limit:bt.messagesPerPage(),uidNext:a?.uidNext||0,sort:hs.sortMode(),search:Ni.listSearch()};Os.threadsAllowed()&&bt.useThreads()?(n.useThreads=1,n.threadAlgorithm=bt.threadAlgorithm(),n.threadUid=Ni.threadUid()):n.threadUid=0,o&&(n.hash=o+"-"+M("accountHash"),r="MessageList/&q[]=/"+v(n),n={}),Hs.abort("MessageList","reload").request("MessageList",((e,t,s)=>{let i="";if(e)"reload"!=t?.name&&(i=be(e),Ni.loading(!1));else{const e=MessageCollectionModel.reviveFromJson(t.Result,s);if(e){const t=e.folder,i=os(t.name);if(e.folder=t.name,i&&!s){i.expires=Date.now(),i.uidNext=t.uidNext,i.etag=t.etag,null!=t.totalEmails&&i.totalEmails(t.totalEmails),null!=t.unreadEmails&&i.unreadEmails(t.unreadEmails);let s=t.permanentFlags||[];if(s.includes("\\*")){let e=6;for(;--e;)s.includes("$label"+e)||s.push("$label"+e)}i.permanentFlags(s.sort(Ee().compare)),Ni.notifyNewMessages(i.fullName,e.newMessages)}Ni.count(e.totalEmails),Ni.listSearch(m(e.search)),Ni.listLimited(!!e.limited),Ni.page(Math.ceil(e.offset/bt.messagesPerPage()+1)),Ni.threadUid(e.threadUid),Ni.endHash(t.name+"|"+e.search+"|"+Ni.threadUid()+"|"+Ni.page()),Ni.endThreadUid(e.threadUid);const r=vi.message();if(r&&t.name!==r.folder&&vi.message(null),xi(!0),e.threadUid){let t={};e.forEach((e=>{e.level=0,e.inReplyTo&&t[e.inReplyTo]&&(e.level=1+t[e.inReplyTo].level),t[e.messageId]=e}))}Ni(e),Ni.isIncomplete(!1)}else Ni.count(0),Ni([]),i=be(c.CantGetMessageList);Ni.loading(!1)}Ni.error(i)}),n,6e4,r)},Ni.setAction=(e,t,s)=>{s=s||Ni.listChecked();let i,r,a=[];if(t==at?s.forEach((e=>{e.isUnseen()&&a.push(e.uid)&&(e.flags.push("\\seen"),e.threads().length>0&&e.threadUnseen().includes(e.uid)&&e.threadUnseen.remove(e.uid))})):t==ot?s.forEach((e=>{!e.isUnseen()&&a.push(e.uid)&&(e.flags.remove("\\seen"),e.threads().length>0&&!e.threadUnseen().includes(e.uid)&&e.threadUnseen.push(e.uid))})):t==nt?s.forEach((e=>!e.isFlagged()&&a.push(e.uid)&&e.flags.push("\\flagged"))):t==lt?s.forEach((e=>e.isFlagged()&&a.push(e.uid)&&e.flags.remove("\\flagged"))):t==ct?s.forEach((e=>!e.isDeleted()&&a.push(e.uid)&&e.flags.push("\\deleted"))):t==dt&&s.forEach((e=>e.isDeleted()&&a.push(e.uid)&&e.flags.remove("\\deleted"))),a=a.validUnique(),r=a.length,e&&r)switch(t){case at:r=-r;case ot:i=os(e),i&&i.unreadEmails(Math.max(0,i.unreadEmails()+r)),Hs.request("MessageSetSeen",null,{folder:e,uids:a.join(","),setAction:t==at?1:0});break;case nt:case lt:Hs.request("MessageSetFlagged",null,{folder:e,uids:a.join(","),setAction:t==nt?1:0});break;case ct:case dt:Hs.request("MessageSetDeleted",null,{folder:e,uids:a.join(","),setAction:t==ct?1:0})}},Ni.moveMessages=(e,t,s="",i=!1)=>{const r=os(e);if(!r||!t?.size)return;let a=0,o=0,n=vi.message();const l=s?os(s):null,c=hs.trashFolder(),d=hs.spamFolder(),u=Ni.page(),m=hs.currentFolderFullName()===e?Ni.filter((e=>e&&t.has(e.uid))):[],p=(e,s)=>{e?(as(hs.currentFolderFullName(),""),alert(be(e))):hs.currentFolder()&&(2===h(s.Result)?as(s.Result[0],s.Result[1]):as(hs.currentFolderFullName(),""),Ni.count(Ni.count()-t.size),u>Ni.pageCount()&&(o=Ni.pageCount()),o&&(Ni.page(o),Ii(ie(hs.currentFolderFullNameHash(),o,Ni.listSearch(),Ni.threadUid()))),Ni.reload(!Ni.count()))};if(m.forEach((e=>e?.isUnseen()&&++a)),i||(r.etag="",r.totalEmails(Math.max(0,r.totalEmails()-t.size)),r.unreadEmails(Math.max(0,r.unreadEmails()-a))),l&&(l.etag="",l.totalEmails(l.totalEmails()+t.size),c!==l.fullName&&d!==l.fullName&&l.unreadEmails(l.unreadEmails()+a),l.actionBlink(!0)),m.length)if(xi(!0),i)m.forEach((e=>e.checked(!1)));else{if(Ni.isIncomplete(!0),n&&1==m.length&&bt.showNextMessage()){let e=Ni.indexOf(n)+1;0<e&&(e=Ni()[e])&&(n=null,O("mailbox.message.show",{folder:e.folder,uid:e.uid}))}m.forEach((e=>{n&&n.hash===e.hash&&(n=null,vi.message(null)),Ni.remove(e)}))}if(s){if(l&&e!=s){const r={fromFolder:e,toFolder:s,uids:[...t].join(",")};if(i)Hs.request("MessageCopy",null,r);else{const t=d===s,i=!t&&d===e&&is()===s;r.markAsRead=t||hs.trashFolder()===s?1:0,r.learning=t?"SPAM":i?"HAM":"",Hs.abort("MessageList","reload").request("MessageMove",p,r)}}}else Hs.abort("MessageList","reload").request("MessageDelete",p,{folder:e,uids:[...t].join(",")})};let Di,Oi=9e5;const _i=e=>{Oi=6e4*Math.max(1,f(M("minRefreshInterval")),f(e)),clearInterval(Di),Di=setInterval((()=>{const e=hs.currentFolderFullName(),t=is();qi(t),t===e||qi(e),Ki()}),Oi)},Ui=e=>{try{let t=Ee(!0);e.sort(((e,s)=>e.isInbox()?-1:s.isInbox()?1:t.compare(e.fullName,s.fullName)))}catch(e){}},Vi=(e,t,s,i)=>{const r=[],a=!s||!bt.hideUnsubscribed(),o=i||(t=>!t.selectable()||e.includes(t.fullName)),n=e=>{e.forEach((e=>{(a||e.hasSubscriptions()||!e.exists)&&r.push({id:e.fullName,name:" ".repeat(e.deep)+s(e),system:!1,disabled:o(e)}),n(e.subFolders())}))};return i=i||(()=>!1),s=s||(e=>e.name()),d(e)||(e=[]),d(t)&&t.forEach((e=>r.push({id:e[0],name:e[1],system:!1,disabled:!1}))),n(hs.folderList()),r},qi=(e,t)=>{if(e?.trim()){let s=1;const i=[];h(t)&&(t.forEach((e=>{i.push(e.uid),e.threads.forEach((e=>i.push(e)))})),s=i.length),s&&Hs.request("FolderInformation",((e,t)=>{if(!e&&t.Result){const e=t.Result,s=os(e.name);if(s){const t=s.etag,i=s.unreadEmails()!==e.unreadEmails;s.expires=Date.now(),s.uidNext=e.uidNext,s.etag=e.etag,s.totalEmails(e.totalEmails),s.unreadEmails(e.unreadEmails),Ni.notifyNewMessages(s.fullName,e.newMessages),t&&!i&&e.etag===t||s.fullName===hs.currentFolderFullName()&&Ni.reload()}}}),{folder:e,flagsUids:i,uidNext:os(e)?.uidNext||0})}},Ki=(e=!1)=>{const t=hs.getNextFolderNames(Oi);h(t)&&Hs.request("FolderInformationMultiply",((t,s)=>{if(!t&&h(s.Result)){const t=Date.now();s.Result.forEach((e=>{const s=os(e.name);if(s){const i=s.etag,r=s.unreadEmails()!==e.unreadEmails;s.expires=t,s.etag=e.etag,s.totalEmails(e.totalEmails),s.unreadEmails(e.unreadEmails),i&&e.etag===i?r&&s.fullName===hs.currentFolderFullName()&&Ni.length&&qi(s.fullName,Ni()):s.fullName===hs.currentFolderFullName()&&Ni.reload()}})),e&&setTimeout((()=>Ki(!0)),2e3)}}),{folders:t})},Bi=(e,t)=>{let s=t.length;for(const i of t)if(xe===i.type){let t=new FormData;t.append("folder",e),t.append("appendFile",i),Hs.request("FolderAppend",((t,i)=>{0==--s&&hs.currentFolderFullName()==e&&Ni.reload(!0,!0)}),t)}else--s},Hi=window,Gi="rlcsc",ji="localStorage",Wi=()=>{try{const e=localStorage.getItem(Gi);return e?JSON.parse(e):null}catch(e){return null}};try{Hi[ji].setItem(ji,""),Hi[ji].getItem(ji),Hi[ji].removeItem(ji)}catch(e){let t=document.cookie.match(/(^|;) ?localStorage=([^;]+)/);t=t?decodeURIComponent(t[2]):null,t=t?JSON.parse(t):{},Hi[ji]={getItem:e=>t[e]??null,setItem:(e,s)=>{t[e]=""+s,document.cookie=ji+"="+encodeURIComponent(JSON.stringify(t))+";expires="+new Date(Date.now()+31536e6).toGMTString()+";path=/;samesite=strict"}}}function $i(e,t){const s=Wi()||{};s["p"+e]=t;try{return localStorage.setItem(Gi,JSON.stringify(s)),!0}catch(e){return!1}}function Ji(e){try{return(Wi()||{})["p"+e]}catch(e){return null}}class FolderACLPopupView extends AbstractViewPopup{constructor(){super("FolderACL"),Ae(this,{create:!1,mine:!1,folderName:"",identifier:""}),this.rights=ko.observableArray()}submitForm(){if(!this.mine()){const e=this.rights();Hs.request("FolderSetACL",((t,s)=>{if(!t&&s.Result){const t=this.acl;t.identifier||this.folder.ACL.push(t),t.rights=e}}),{folder:this.folderName(),identifier:this.identifier(),rights:e.join("")})}this.close()}beforeShow(e,t){this.folder=e,this.create(!t.identifier()),this.mine(t.mine()),this.acl=t,this.folderName(e.fullName),this.identifier(t.identifier()),this.rights(t.rights())}}class FolderACLModel extends AbstractCollectionModel{static reviveFromJson(e){return super.reviveFromJson(e,(e=>FolderACLRightsModel.reviveFromJson(e)))}}class FolderACLRightsModel extends AbstractModel{constructor(){super(),Ae(this,{identifier:"",mine:!1}),this.rights=ko.observableArray()}static reviveFromJson(e){return e.rights=e.rights.split(""),super.reviveFromJson(e)}}class FolderPopupView extends AbstractViewPopup{constructor(){super("Folder"),Ae(this,{folder:null,parentFolder:"",name:"",editing:!1,adminACL:!1}),this.ACLAllowed=hs.hasCapability("ACL"),this.parentFolderSelectList=Ce((()=>Vi([],[["",""]],(e=>e?e.detailedName():""),(e=>!e.subFolders.allow||hs.namespace&&!e.fullName.startsWith(hs.namespace))))),this.displaySpecSetting=hs.displaySpecSetting,this.showKolab=hs.allowKolab(),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.defaultOptionsAfterRender=b,this.editACL=this.editACL.bind(this),this.deleteACL=this.deleteACL.bind(this)}afterHide(){this.editing(!1)}submitForm(){const e=this.folder(),t=this.name().trim(),s=this.parentFolder(),i=os(e.parentName),r=os(s),a=hs.folderList,o=r?r.subFolders:a,n=(r||e).delimiter,l=e.fullName,d=(r?s+n:"")+t;t&&d!=l?Hs.abort("Folders").post("FolderRename",hs.foldersRenaming,{oldName:l,newName:d,subscribe:e.isSubscribed()?1:0,checkable:e.checkable()?1:0,kolab:{type:st,value:e.kolabType()}}).then((()=>{const s=(e,t)=>{ns(e.fullName),e.parentName=t?t.fullName:"",e.fullName=(t?t.fullName+n:"")+e.name(),e.delimiter=n,e.deep=(t?t.deep:-1)+1,rs(e)},l=e=>{e.subFolders.forEach((t=>{s(t,e),l(t)}))};e.name(t),s(e,r),(e.subFolders.length||r!=i)&&l(e),(i?i.subFolders:a).remove(e),o.push(e),Ui(o)})).catch((e=>{hs.error(be(e.code,"",c.CantRenameFolder)+".\n"+e.message)})):Hs.request("FolderSettings",null,{folder:e.fullName,subscribe:e.isSubscribed()?1:0,checkable:e.checkable()?1:0,kolab:{type:st,value:e.kolabType()}}),this.close()}createACL(){xs(FolderACLPopupView,[this.folder(),new FolderACLRightsModel])}editACL(e){xs(FolderACLPopupView,[this.folder(),e])}deleteACL(e){Hs.request("FolderDeleteACL",((t,s)=>!t&&s.Result&&this.folder().ACL.remove(e)),{folder:this.folder().fullName,identifier:e.identifier})}beforeShow(e){e.ACL||(e.ACL=ko.observableArray()),this.adminACL(!1),this.ACLAllowed&&Hs.request("FolderACL",((t,s)=>{!t&&s.Result&&(e.ACL(FolderACLModel.reviveFromJson(s.Result)),this.adminACL(e.ACL()[0].rights.includes("a")))}),{folder:e.fullName}),this.editing(!e.type()&&e.exists&&e.selectable()),this.name(e.name()),this.parentFolder(e.parentName),this.folder(e)}}const zi=e=>""===e||ls===e||null!==os(e)?e:"",Yi={Inbox:0,Sent:0,Drafts:0,Junk:0,Trash:0,Archive:0},Zi={configuration:"CONFIGURATION",event:"CALENDAR",contact:"CONTACTS",task:"TASKS",note:"NOTES",file:"FILES",journal:"JOURNAL"},Xi=(e,t)=>{switch(e){case tt.Inbox:case tt.Sent:case tt.Drafts:case tt.Trash:case tt.Archive:return he("FOLDER_LIST/"+S(tt,e).toUpperCase()+"_NAME");case tt.Junk:return he("GLOBAL/SPAM")}return t},Qi=(e,t)=>{let s=Ji(3);s=new Set(d(s)?s:[]),t?s.add(e):s.delete(e),$i(3,[...s])},er=ko.observable(""),tr=e=>{Hs.abort("Folders").post("Folders",hs.foldersLoading).then((t=>{es.clear(),ts.clear(),FolderCollectionModel.reviveFromJson(t.Result)?.storeIt(),e?.(!0)})).catch((t=>e&&setTimeout(e,1,!1,t)))};class FolderCollectionModel extends AbstractCollectionModel{static reviveFromJson(e){const t=Ji(3);g(Yi,((e,t)=>t||(Yi[e]=M(e+"Folder"))));const s=super.reviveFromJson(e,(e=>{let s=os(e.fullName);if(s)e.etag&&(s.etag=e.etag),null!=e.totalEmails&&s.totalEmails(e.totalEmails),null!=e.unreadEmails&&s.unreadEmails(e.unreadEmails);else{if(s=FolderModel.reviveFromJson(e),!s)return null;rs(s)}let i=e.role;return i&&(i=i[0].toUpperCase()+i.slice(1),Yi[i]||(Yi[i]=e.fullName)),s.type(tt[S(Yi,e.fullName)]||0),s.collapsed(!t||!d(t)||!t.includes(s.fullName)),s}));var i;s.CountRec=s.length,i=Yi.Inbox,ss=i;let r=s.length;if(r){Ui(s);try{for(;r--;){let e=s[r],t=os(e.parentName);if(!t){let i=e.delimiter;if(i){let a=e.fullName.split(i);for(a.pop();a.length;){let e=a.join(i),t=a.pop(),o=os(e);o||(o=FolderModel.reviveFromJson({"@Object":"Object/Folder",name:t,fullName:e,delimiter:i,attributes:["\\nonexistent"]}),rs(o),s.splice(r,0,o),++r)}t=os(e.parentName)}}t&&(t.subFolders.unshift(e),s.splice(r,1))}}catch(e){}}return s}visible(){return this.filter((e=>e.visible()))}storeIt(){hs.displaySpecSetting(F.app("folderSpecLimit")<this.CountRec),M("SentFolder")+M("DraftsFolder")+M("JunkFolder")+M("TrashFolder")+M("ArchiveFolder")||hs.saveSystemFolders(Yi),hs.folderList(this),hs.namespace=this.namespace,Os.threadsAllowed(!!this.capabilities.some((e=>e.startsWith("THREAD=")))),hs.quotaUsage(this.quotaUsage),hs.quotaLimit(this.quotaLimit),hs.capabilities(this.capabilities),hs.sentFolder(zi(Yi.Sent)),hs.draftsFolder(zi(Yi.Drafts)),hs.spamFolder(zi(Yi.Junk)),hs.trashFolder(zi(Yi.Trash)),hs.archiveFolder(zi(Yi.Archive))}}class FolderModel extends AbstractModel{constructor(){super(),this.fullName="",this.parentName="",this.delimiter="",this.deep=0,this.expires=0,this.metadata={},this.exists=!0,this.etag="",this.id=0,this.uidNext=0,this.size=0,Ae(this,{name:"",type:0,role:null,selectable:!1,focused:!1,selected:!1,isSubscribed:!0,checkable:!1,askDelete:!1,errorMsg:"",totalEmails:0,unreadEmails:0,kolabType:null,collapsed:!0,tagsAllowed:!1}),this.attributes=ko.observableArray(),this.permanentFlags=ko.observableArray(),this.addSubscribables({kolabType:e=>this.metadata[st]=e,permanentFlags:e=>this.tagsAllowed(e.includes("\\*")),unreadEmails:e=>tt.Inbox===this.type()&&O("mailbox.inbox-unread-count",e)}),this.subFolders=ko.observableArray(new FolderCollectionModel),this.actionBlink=ko.observable(!1).extend({falseTimeout:1e3}),this.addComputables({isInbox:()=>tt.Inbox===this.type(),isFlagged:()=>hs.currentFolder()===this&&Ni.listSearch().includes("flagged"),hasVisibleSubfolders:()=>!!this.subFolders().find((e=>e.visible())),visibleSubfolders:()=>this.subFolders().visible(),hasSubscriptions:()=>this.isSubscribed()|!!this.subFolders().find((e=>{const t=e.hasSubscriptions();return!e.isSystemFolder()&&t})),isSystemFolder:()=>this.type()|(hs.allowKolab()&&!!this.kolabType()&!bt.unhideKolabFolders()),canBeSelected:()=>this.selectable()&&!this.isSystemFolder(),canBeDeleted:()=>this.canBeSelected()&&this.exists,canBeSubscribed:()=>this.selectable()&&!(this.isSystemFolder()|!bt.hideUnsubscribed()),optionalTags:()=>this.permanentFlags.filter(ds),visible:()=>{const e=this.canBeSelected(),t=this.name(),s=er(),i=this.isSubscribed()|!bt.hideUnsubscribed()&&e&&(!s||t.toLowerCase().includes(s.toLowerCase()));return this.hasVisibleSubfolders()|i},unreadCount:()=>this.unreadEmails()||null,localName:()=>{let e=this.name();return this.isSystemFolder()&&(ce(),e=Xi(this.type(),e)),e},nameInfo:()=>{if(this.isSystemFolder()){ce();let t=Xi(this.type(),(e=this.kolabType(),Zi[e]?"Kolab "+he("SETTINGS_FOLDERS/TYPE_"+Zi[e]):""));if(this.name()!==t&&"inbox"!==t.toLowerCase())return" ("+t+")"}var e;return""},friendlySize:()=>et.friendlySize(this.size),detailedName:()=>this.name()+" "+this.nameInfo(),icon:()=>{switch(this.type()){case 1:return"📥";case 2:return"📧";case 3:return"🗎";case 4:return"⚠";case 5:return"🗑";case 6:return"🗄"}return null},hasUnreadInSub:()=>this.subFolders().some((e=>e.unreadEmails()|e.hasUnreadInSub())),href:()=>this.canBeSelected()&&ie(this.fullNameHash)})}edit(){xs(FolderPopupView,[this])}get fullNameHash(){return this.fullName.replace(/[^a-z0-9._-]+/giu,v)}static reviveFromJson(e){const t=super.reviveFromJson(e);if(t){const e=t.fullName.split(t.delimiter),s=e=>t.attributes.includes(e),i=(t.metadata[st]||t.metadata[it]||"").split(".")[0];t.deep=e.length-1,e.pop(),t.parentName=e.join(t.delimiter),t.isSubscribed(s("\\subscribed")),t.exists=!s("\\nonexistent"),t.subFolders.allow=!s("\\noinferiors"),t.selectable(t.exists&&!s("\\noselect")),i&&"mail"!=i&&t.kolabType(i)}return t}collapsedCss(){return"e-collapsed-sign "+(this.hasVisibleSubfolders()?this.collapsed()?"icon-right-mini":"icon-down-mini":"icon-none")}}const sr=()=>"messages"===cr?.action,ir=()=>"sortable"===cr?.action,rr=(e,t,s,i,r)=>{cr={action:t,data:i},e.dataTransfer.setData("text/plain","snappymail/action/"+t),e.dataTransfer.setDragImage(r,0,0),e.dataTransfer.effectAllowed=s},ar={id:0},or=(e,t)=>{e.preventDefault(),t?.classList.remove("droppableHover"),ar.node==t&&(ar.node=null,clearTimeout(ar.id))},nr=(e,t)=>pe(e,ko.unwrap(t()));let lr,cr;Object.assign(ko.bindingHandlers,{editor:{init:(e,t)=>{let s=null;const i=t(),r=()=>i.__editor?.setHtmlOrPlain(i()),a=()=>i.__editor&&i(i.__editor.getDataWithHtmlMark()),o=()=>{i.__editor=s,r()};ko.isObservable(i)&&(s=new HtmlEditor(e,o,a,a),i.__fetchEditorValue=a,i.subscribe(r))}},time:{init:nr,update:nr},emailsTags:{init:(e,t,s)=>{const i=t(),r=i.focused;e.addresses=new EmailAddressesComponent(e,{focusCallback:e=>r?.(!!e),autoCompleteSource:s.get("autoCompleteSource"),onChange:e=>i(e)}),r?.subscribe((t=>e.addresses[t?"focus":"blur"]()))},update:(e,t)=>{e.addresses.value=ko.unwrap(t())}},dragmessages:{init:e=>{e.addEventListener("dragstart",(e=>{if(lr||(lr=A("messagesDragImage")),lr&&!mt.isMobile()){ko.dataFor(k.elementFromPoint(e.clientX,e.clientY))?.checked?.(!0);const t=Ni.listCheckedOrSelectedUidsWithSubMails();lr.querySelector(".text").textContent=t.size,lr.style.left=e.clientX+"px",lr.style.top=e.clientY+"px",lr.style.right="auto",rr(e,"messages","copyMove",t,lr),lr.style.cssText="",N(!1)}else e.preventDefault()}),!1),e.addEventListener("dragend",(()=>cr=null))}},dropmessages:{init:(e,t)=>{const s=t();s&&B(e,{dragenter:t=>((e,t,s)=>{let i=!1;for(const t of e.dataTransfer.items)i|="file"===t.kind&&xe===t.type;(i||sr())&&(e.stopPropagation(),or(e,ar.node),e.dataTransfer.dropEffect=i||e.ctrlKey?"copy":"move",t.classList.add("droppableHover"),s.collapsed()&&(ar.node=t,ar.id=setTimeout((()=>{s.collapsed(!1),Qi(s.fullName,!0)}),500)))})(t,e,s),dragover:e=>e.preventDefault(),dragleave:t=>or(t,e),drop:t=>((e,t,s,i)=>{or(e,t),sr()&&"copyMove"==e.dataTransfer.effectAllowed?Ni.moveMessages(hs.currentFolderFullName(),i.data,s.fullName,e.ctrlKey):e.dataTransfer.types.includes("Files")&&Bi(s.fullName,e.dataTransfer.files)})(t,e,s,cr)})}},sortableItem:{init:(e,t)=>{let s=ko.unwrap(t())||{},i=e.parentNode,r=e=>{if(ir()){e.preventDefault();let t=(e.target.closest?e.target:e.target.parentNode).closest("[draggable]");if(t&&t!==cr.data&&i.contains(t)){let s=t.getBoundingClientRect();s.top+s.height/2<=e.clientY?t.nextElementSibling!==cr.data&&t.after(cr.data):t.previousElementSibling!==cr.data&&t.before(cr.data)}}};B(e,{dragstart:t=>{rr(t,"sortable","move",e,e),e.style.opacity=.25},dragend:()=>{if(e.style.opacity=null,ir()){cr.data.style.cssText="";let t=i.rows[s.list.indexOf(ko.dataFor(e))];t!=cr.data&&t.before(cr.data),cr=null}}}),i.sortable||(i.sortable=!0,B(i,{dragenter:r,dragover:r,drop:e=>{if(ir()){e.preventDefault();let t=ko.dataFor(cr.data),r=s.list.indexOf(t),a=[...i.children].indexOf(cr.data);if(r!=a){let e=s.list();e.splice(a,0,...e.splice(r,1)),s.list(e)}cr=null,s.afterMove?.()}}}))}},initDom:{init:(e,t)=>t()(e)},registerBootstrapDropdown:{init:e=>{I.push(e),e.ddBtn=new BSN.Dropdown(e.querySelector(".dropdown-toggle"))}}});class AccountModel extends AbstractModel{constructor(e,t,s=!0){super(),this.name=t,this.email=e,this.displayName=t?t+" <"+e+">":e,Ae(this,{unreadEmails:null,askDelete:!1,isAdditional:s}),bt.showUnreadCount()&&s&&setTimeout((()=>this.fetchUnread()),3e3*Math.ceil(10*Math.random()))}label(){return this.name||IDN.toUnicode(this.email)}fetchUnread(){Hs.request("AccountUnread",((e,t)=>{e||this.unreadEmails(t?.Result?.unreadEmails||null)}),{email:this.email})}}class IdentityModel extends AbstractModel{constructor(){super(),Ae(this,{id:"",label:"",email:"",name:"",replyTo:"",bcc:"",sentFolder:"",signature:"",signatureInsertBefore:!1,pgpSign:!1,pgpEncrypt:!1,smimeKey:"",smimeCertificate:"",askDelete:!1,exists:!1}),Te(this,{smimeKeyEncrypted:()=>this.smimeKey().includes("-----BEGIN ENCRYPTED PRIVATE KEY-----"),smimeKeyValid:()=>/^-----BEGIN (ENCRYPTED |RSA )?PRIVATE KEY-----/.test(this.smimeKey()),smimeCertificateValid:()=>/^-----BEGIN CERTIFICATE-----/.test(this.smimeCertificate())})}formattedName(){const e=this.name(),t=this.email(),s=this.label();return(e?`${e} `:"")+`<${t}>`+(s?` (${s})`:"")}}const dr=Ie();dr.loading=ko.observable(!1).extend({debounce:100}),dr.main=Ce((()=>{const e=dr();return d(e)?e.find((e=>e&&!e.id())):null}));class IdentityPopupView extends AbstractViewPopup{constructor(){super("Identity"),Ae(this,{identity:null,edit:!1,labelFocused:!1,nameFocused:!1,submitRequest:!1,submitError:""}),this.folderSelectList=Ce((()=>Vi([],[["","("+he("GLOBAL/DEFAULT")+")"]]))),this.defaultOptionsAfterRender=b,this.createSelfSigned=this.createSelfSigned.bind(this),this.setSMimeKeyPass=this.setSMimeKeyPass.bind(this)}createSelfSigned(){AskPopupView.password("","CRYPTO/CREATE_SELF_SIGNED").then((e=>{if(e){const t=this.identity();Hs.request("SMimeCreateCertificate",((e,s)=>{s.Result.x509?(t.smimeKey(s.Result.pkey),t.smimeCertificate(s.Result.x509)):this.submitError(s.message)}),{name:t.name(),email:t.email(),privateKey:t.smimeKey(),passphrase:e.password})}}))}async setSMimeKeyPass(){const e=this.identity();let t=null;e.smimeKeyEncrypted()&&(t=await AskPopupView.password(he("CRYPTO/CURRENT_PASS"),"CRYPTO/DECRYPT"),!t)||AskPopupView.password(he("CRYPTO/NEW_PASS"),"GLOBAL/SAVE").then((s=>{s&&Hs.request("SMimeExportPrivateKey",((t,s)=>{s.Result?e.smimeKey(s.Result):this.submitError(s.message)}),{privateKey:e.smimeKey(),oldPassphrase:t?.password,newPassphrase:s.password})}))}submitForm(e){if(!this.submitRequest()&&e.reportValidity()){let t=this.identity();t.signature?.__fetchEditorValue?.(),this.submitRequest(!0);const s=new FormData(e);s.set("Id",t.id()),s.set("Signature",t.signature()),Hs.request("IdentityUpdate",(e=>{this.submitRequest(!1),e?this.submitError(be(e)):(rl.app.loadAccountsAndIdentities(),this.close())}),s)}}onShow(e){this.submitRequest(!1),this.submitError(""),e?this.edit(!0):(this.edit(!1),(e=new IdentityModel).id(Jua.randomId())),this.identity(e)}afterShow(){this.identity().id()?this.labelFocused(!0):this.nameFocused(!0)}onClose(){if(!this.identity().exists())return xs(AskPopupView,[he("POPUPS_ASK/DESC_WANT_CLOSE_THIS_WINDOW"),()=>this.close()]),!1}}const hr=ko.observable(0),ur=(()=>x(!!I.find((e=>e.classList.contains("show"))))).debounce(50),mr=e=>xs(IdentityPopupView,[e]),pr=()=>{Si.loading(!0),dr.loading(!0),Hs.request("AccountsAndIdentities",((e,t)=>{if(Si.loading(!1),dr.loading(!1),!e){let e=t.Result.Accounts;Si(d(e)?e.map((e=>new AccountModel(e.email,e.name))):[]),Si.unshift(new AccountModel(M("mainEmail"),"",!1)),e=t.Result.Identities,dr(d(e)?e.map((e=>IdentityModel.reviveFromJson(e))):[]);const s=dr.main();s&&!s.exists()&&setTimeout((()=>mr(s)),1e3)}}))},gr=(e,t="")=>{if(mt.isMobile()||/firefox/i.test(navigator.userAgent))open(e,"_blank"),focus();else{const s=D("a",{href:e,target:"_blank",download:t});k.body.appendChild(s).click(),s.remove()}},fr=(e,t,s,i,r)=>{if(t.length){let a={target:"zip",filename:e,hashes:t};s||(s=()=>alert("Download failed")),r&&(a.folder=r),Hs.post("AttachmentsActions",i||null,a).then((e=>{let t=e?.Result?.fileHash;t?gr(Z(t),t+".zip"):s()})).catch(s)}},br=(e,t)=>()=>{const s=e(),i=t(),r=[],a=k.documentElement.lang,o=(e,t=!0,i="")=>{const o=e.toLocaleString(a),n={current:e===s,name:i||o,title:i?o:"",value:e};t?r.push(n):r.unshift(n)};let n=0,l=0,c=2;if(1<i){for(i<s?(o(i),n=i,l=i):((3>=s||i-2<=s)&&(c+=2),o(s),n=s,l=s);0<c;)if(--n,++l,0<n&&(o(n,!1),--c),i>=l)o(l,!0),--c;else if(0>=n)break;3===n?o(2,!1):3<n&&o(Math.round((n-1)/2),!1,"…"),i-2===l?o(i-1,!0):i-2>l&&o(Math.round((i+l)/2),!0,"…"),1<n&&o(1,!1),i>l&&o(i,!0)}return r},yr=e=>{if("mailto:"===e?.slice(0,7).toLowerCase()){e=e.slice(7).split("?");const t=decodeURIComponent(e[0]),s=new URLSearchParams(e[1]),i=s.get("to"),r=e=>EmailCollectionModel.fromString(e);return vr([rt.Empty,null,r(i?t+","+i:t),r(s.get("cc")),r(s.get("bcc")),s.get("subject"),Bt(s.get("body")||"")]),!0}return!1},vr=(e=[])=>{rl.app.showMessageComposer(e)},Sr=(e,t,s)=>{if(e.layoutResizer&&e.layoutResizer.mode!=s&&e.removeAttribute("style"),e.observer?.disconnect(),s){const i=Ji(t+s)||M("Resizer"+t+s);if(i&&(e.style[s.toLowerCase()]=i+"px"),!e.layoutResizer){const t=D("div",{class:"resizer"}),s=(e=>Hs.saveSettings(0,e)).debounce(500),i={},r=()=>{const i="Width"==t.mode?e.offsetWidth:e.offsetHeight,r=t.key+t.mode;i==Ji(r)||$i(r,i),i==M("Resizer"+r)||s({["Resizer"+r]:i})},a=s=>{let i=getComputedStyle(e,null)[s].replace("px","");return i.includes("%")&&(i=e.parentElement["offset"+t.mode]*i.replace("%","")/100),parseFloat(i)};e.layoutResizer=t,e.append(t),t.addEventListener("mousedown",{handleEvent:function(s){if("mousedown"==s.type){const e=t.mode.toLowerCase();s.preventDefault(),i.pos="width"==e?s.pageX:s.pageY,i.min=a("min-"+e),i.max=a("max-"+e),i.org=a(e),addEventListener("mousemove",this),addEventListener("mouseup",this)}else if("mousemove"==s.type){const a=t.mode.toLowerCase(),o=i.org+(("width"==a?s.pageX:s.pageY)-i.pos);o>=i.min&&o<=i.max&&(e.style[a]=o+"px",e.observer||r())}else"mouseup"==s.type&&(removeEventListener("mousemove",this),removeEventListener("mouseup",this))}}),e.observer=window.ResizeObserver?new ResizeObserver(r):null}e.layoutResizer.mode=s,e.layoutResizer.key=t,e.observer?.observe(e,{box:"border-box"})}},wr=(e,t)=>{if(t)e.popupMessage();else{vi.error("");let t="rl-msg-"+e.hash,s=e.body||A(t);s||(s=D("div",{id:t,hidden:"",class:"b-text-part"+(e.pgpSigned()?" openpgp-signed":"")+(e.pgpEncrypted()?" openpgp-encrypted":"")+(e.smimeSigned()?" smime-signed":"")+(e.smimeEncrypted()?" smime-encrypted":"")}),vi.purgeCache()),s.message=e,e.body=s,bt.viewHTML()&&e.viewHtml()||e.viewPlain(),vi.bodiesDom().append(s),vi.loading(!1),e.body.hidden=!1,e.isUnseen()&&bt.messageReadAuto()&&(vi.MessageSeenTimer=setTimeout((()=>Ni.setAction(e.folder,at,[e])),1e3*bt.messageReadDelay()))}},Er=(e,t)=>{e&&(t||vi.message(e),e.body?wr(e,t):(t||vi.loading(!0),Hs.message(((s,i)=>{if(s)c.RequestAborted===s||t||(vi.message(null),vi.error(be(s)));else{let s=i?.Result;s&&(e.hash&&e.hash===s.hash||!e.hash&&e.folder===s.folder&&e.uid==s.uid)&&e.revivePropertiesFromJson(s)&&wr(e,t)}t||vi.loading(!1)}),e.folder,e.uid)))};N.subscribe((e=>e&&hr(0))),hr.subscribe((e=>e&&N(!1)));const kr=Ie();kr.loading=ko.observable(!1).extend({debounce:200}),kr.importing=ko.observable(!1).extend({debounce:200}),kr.syncing=ko.observable(!1).extend({debounce:200}),Ae(kr,{allowSync:!1,syncMode:0,syncUrl:"",syncUser:"",syncPass:""}),kr.hasChecked=Ce((()=>!!kr.find((e=>e.checked())))),kr.sync=e=>{!kr.syncMode()||kr.importing()||kr.syncing()||(kr.syncing(!0),Hs.streamPerLine((t=>{try{"ContactsSync"===(t=JSON.parse(t)).Action&&(kr.syncing(!1),e?.(t.code,t))}catch(t){kr.syncing(!1),e?.(c.UnknownError)}}),"ContactsSync"))},kr.init=()=>{let e=M("ContactsSync");kr.allowSync(!!e),e&&(kr.syncMode(e.Mode),kr.syncUrl(e.Url),kr.syncUser(e.User),kr.syncPass(e.Password),setTimeout(kr.sync,1e4),setInterval(kr.sync,6e4*e.Interval+5e3))};const Cr=Ie();Ae(Cr,{loading:!1}),Cr.loadCertificates=()=>{Cr([]),Cr.loading(!0),Hs.request("SMimeGetCertificates",((e,t)=>{Cr.loading(!1);const s=Ee();e||Cr(t.Result.sort(((e,t)=>s.compare(e.emailAddress,t.emailAddress)||t.validTo_time_t-e.validTo_time_t)))}))};class AbstractScreen{constructor(e,t=[]){this.__cross=null,this.screenName=e,this.viewModels=d(t)?t:[]}routes(){return null}onStart(){const e=this.routes();if(h(e)){let t=new Crossroads,s=(this.onRoute||(()=>0)).bind(this);e.forEach((e=>e&&(t.addRoute(e[0],s).rules=e[1]))),this.__cross=t}}}class LanguagesPopupView extends AbstractViewPopup{constructor(){super("Languages"),this.fLang=null,this.languages=ko.observableArray()}onShow(e,t,s){this.fLang=e,this.languages(t.map((t=>({key:t,user:s===t,selected:e?.()===t,fullName:we(t),title:we(t,!0)}))))}changeLanguage(e){this.fLang?.(e),this.close()}}class LoginUserView extends AbstractViewLogin{constructor(){super(),Ae(this,{loadingDesc:M("loadingDescription"),email:M("DevEmail"),password:M("DevPassword"),signMe:!1,emailError:!1,passwordError:!1,submitRequest:!1,submitError:"",submitErrorAdditional:"",langRequest:!1,signMeType:2}),this.allowLanguagesOnLogin=!!M("allowLanguagesOnLogin"),this.language=re.language,this.languages=re.languages,this.bSendLanguage=!1,Te(this,{languageFullName:()=>we(this.language()),signMeVisibility:()=>2!==this.signMeType()}),Fe(this,{email:()=>this.emailError(!1),password:()=>this.passwordError(!1),submitError:e=>e||this.submitErrorAdditional(""),signMeType:e=>this.signMe(1===e),language:e=>{this.langRequest(!0),Se(e).then((()=>{this.langRequest(!1),this.bSendLanguage=!0}),(()=>this.langRequest(!1)))}}),M("AdditionalLoginError")&&!this.submitError()&&this.submitError(M("AdditionalLoginError")),Ds(this,{submitCommand:e=>!e.submitRequest()})}hideError(){this.submitError("")}submitCommand(e,t){const s=this.email().trim();this.email(s);let i=t.target.form,r=new FormData(i),a=i.reportValidity()&&O("sm-user-login",r,1);return this.emailError(!s),this.passwordError(!this.password()),this.formError(!a),a&&(this.submitRequest(!0),r.set("language",this.bSendLanguage?this.language():""),r.set("signMe",this.signMe()?1:0),Hs.request("Login",((e,t)=>{O("sm-user-login-response",{error:e,data:t}),e?(this.submitRequest(!1),c.InvalidInputArgument==e&&(e=c.AuthError),this.submitError(be(e,t?.message,c.UnknownError)),this.submitErrorAdditional(t?.messageAdditional||t?.message)):rl.setData(t.Result)}),r),$i(7,this.signMe()?"-1-":"-0-")),a}onBuild(e){super.onBuild(e);let t=M("signMe");switch(t){case 0:case 1:switch(Ji(7)){case"-1-":t=1;break;case"-0-":t=0}this.signMeType(t);break;default:this.signMeType(2)}}selectLanguage(){xs(LanguagesPopupView,[this.language,this.languages(),re.userLanguage()])}}class LoginUserScreen extends AbstractScreen{constructor(){super("login",[LoginUserView])}onShow(){rl.setTitle()}}class KeyboardShortcutsHelpPopupView extends AbstractViewPopup{constructor(){super("KeyboardShortcutsHelp"),this.metaKey=shortcuts.getMetaKey()}onBuild(e){const t=e.querySelectorAll(".tabs input"),s=t.length-1;V("tab,arrowleft,arrowright","","KeyboardShortcutsHelp",(e=>{let i=0;return t.forEach(((t,r)=>{t.matches(":checked")&&(i=["Tab","ArrowRight"].includes(e.key)?r<s?r+1:0:r?r-1:s)})),t[i].checked=!0,!1}))}}class AccountPopupView extends AbstractViewPopup{constructor(){super("Account"),Ae(this,{isNew:!0,name:"",email:"",password:"",submitRequest:!1,submitError:"",submitErrorAdditional:""})}hideError(){this.submitError("")}submitForm(e){if(!this.submitRequest()&&e.reportValidity()){const t=new FormData(e);t.set("new",this.isNew()?1:0),this.submitRequest(!0),Hs.request("AccountSetup",((e,t)=>{this.submitRequest(!1),e?(this.submitError(be(e)),this.submitErrorAdditional(t?.messageAdditional)):(pr(),this.close())}),t)}}onHide(){this.password(""),this.submitRequest(!1),this.submitError(""),this.submitErrorAdditional("")}onShow(e){let t=e?.isAdditional();this.isNew(!t),this.name(t?e.name:""),this.email(t?e.email:"")}}let Ar;class Selector{constructor(e,t,s,i,r){s=(s||ko.observable(null)).extend({toggleSubscribeProperty:[this,"focused"]}),t=(t||ko.observable(null)).extend({toggleSubscribeProperty:[null,"selected"]}),this.list=e,this.listChecked=Ce((()=>e.filter((e=>e.checked())))).extend({rateLimit:0}),this.focusedItem=s,this.selectedItem=t,this.iSelectNextHelper=0,this.iFocusedNextHelper=0,this.sItemSelector=i,this.sItemCheckedSelector=r,this.sItemFocusedSelector=i+".focused",this.sLastUid="",this.oCallbacks={};const a=t=>{e.hasChecked()?t||this.oCallbacks.ItemSelect?.(null):t&&this.oCallbacks.ItemSelect?.(t)},o=(e=>a(e)).debounce(300);this.listChecked.subscribe((e=>{e.length?t()?t(null):t.valueHasMutated?.():this.autoSelect()}));let n=!0;t.subscribe((e=>{e?n&&o(e):n&&a()})),s.subscribe((e=>e&&(this.sLastUid=this.getItemUid(e))));let l=[],c=null,h=null;e.subscribe((e=>{d(e)&&e.forEach((e=>{const t=this.getItemUid(e);t&&(e.checked()&&l.push(t),!c&&e.focused()&&(c=t),!h&&e.selected()&&(h=t))}))}),this,"beforeChange"),e.subscribe((e=>{if(n=!1,this.unselect(),d(e)){let i,r,a=this.iFocusedNextHelper||this.iSelectNextHelper;e.forEach((e=>{const i=this.getItemUid(e);i&&(c===i&&(s(e),c=null),l.includes(i)&&(e.checked(!0),r=!0),r||h!==i||(t(e),h=null))})),n=!0,a&&e.length&&!s()&&(i=e[-1===a?e.length-1:0],i&&(this.iSelectNextHelper&&t(i),s(i),this.scrollToFocused(),setTimeout(this.scrollToFocused,100)),this.iSelectNextHelper=0,this.iFocusedNextHelper=0),!r&&!t()&&this.autoSelect()}l=[],c=null,h=null,n=!0}))}unselect(){this.selectedItem(null),this.focusedItem(null)}init(e,t="all"){if(this.oContentScrollable=e,e){let s=t=>{let s=event.target.closestWithin(t,e);return s?ko.dataFor(s):null};B(e,{click:t=>{const i=t.target.closestWithin(this.sItemSelector,e);let r=i&&ko.dataFor(i);i&&(this.oCallbacks.click||(()=>1))(t,r)&&this.actionClick(r,t),r=s(this.sItemCheckedSelector),r&&(t.shiftKey?this.actionClick(r,t):(this.focusedItem(r),r.checked(!r.checked())))},auxclick:e=>{if(1==e.button){const e=s(this.sItemSelector);e&&(this.focusedItem(e),this.oCallbacks.MiddleClick?.(e))}}}),q("enter,open","",t,(()=>{const e=this.focusedItem();if(e&&!e.selected())return this.actionClick(e),!1})),V("arrowup,arrowdown","meta",t,(()=>!1)),V("arrowup,arrowdown","shift",t,(e=>(this.newSelectPosition(e.key,!0),!1))),q("arrowup,arrowdown,home,end,pageup,pagedown,space","",t,(e=>(this.newSelectPosition(e.key,!1),!1)))}}autoSelect(e){(e||(this.oCallbacks.canSelect||(()=>1))())&&this.focusedItem()&&this.selectedItem(this.focusedItem())}getItemUid(e){return e&&this.oCallbacks.ItemGetUid?.(e)?.toString()||""}newSelectPosition(e,t,s){let i;const r="ArrowUp"===e,a=r||"ArrowDown"===e,o=this.list(),n=o.length,l=this.focusedItem();if(t||(Ar=-1)," "===e)l?.checked(!l.checked());else if(n){if(l){if(a){let e=o.indexOf(l);t&&(Ar=-1<Ar?Ar:e,Ar==e?l.checked(!0):(r?Ar<e:Ar>e)&&l.checked(!1)),r?e>0&&(i=o[--e]):++e<n&&(i=o[e]),t&&i?.checked(!0),i||this.oCallbacks.UpOrDown?.(r)}else if("Home"===e)i=o[0];else if("End"===e)i=o[o.length-1];else if("PageDown"===e){let e=o.indexOf(l);e<n-1&&(i=o[Math.min(e+10,n-1)])}else if("PageUp"===e){let e=o.indexOf(l);e>0&&(i=o[Math.max(0,e-10)])}}else"Home"==e||"PageUp"==e?i=o[0]:"End"!==e&&"PageDown"!==e||(i=o[o.length-1]);i&&(this.focusedItem(i),!this.list.hasChecked()&&this.autoSelect(s),this.scrollToFocused())}}scrollToFocused(){const e=this.oContentScrollable;if(e){let t=e.querySelector(this.sItemFocusedSelector);if(t){const s=t.getBoundingClientRect(),i=e.getBoundingClientRect();s.top<i.top?t.scrollIntoView(!0):s.bottom>i.bottom&&t.scrollIntoView(!1)}else e.scrollTop=0}}scrollToTop(){this.oContentScrollable&&(this.oContentScrollable.scrollTop=0)}actionClick(e,t){if(e){let s=!0;if(t&&!t.altKey){if(t.shiftKey&&!t.ctrlKey&&!t.metaKey){const t=this.getItemUid(e);if(t&&this.sLastUid&&t!==this.sLastUid){let s=!1,i=!1,r=!e.checked(),a="";this.list().forEach((e=>{a=this.getItemUid(e),s=a===this.sLastUid||a===t,(i||s)&&(s&&(i=!i),e.checked(r))}))}return this.sLastUid=t,void this.focusedItem(e)}if(!t.shiftKey&&(t.ctrlKey||t.metaKey)){s=!1,this.focusedItem(e);const t=this.selectedItem();t&&e!==t&&t.checked(!0)}}s?this.selectMessageItem(e):e.checked(!e.checked())}}on(e,t){this.oCallbacks[e]=t}selectMessageItem(e){this.focusedItem(e),this.selectedItem(e),this.scrollToFocused()}}class VCardProperty{constructor(e,t,s,i="text"){if(this.field="",this.value="",this.type="",this.params={},void 0!==t&&"string"==typeof e)this.field=e,this.value=t,this.params=s||{},this.type=i;else{if(void 0!==t||void 0!==s||"object"!=typeof e)throw Error("invalid Property constructor");this.parseFromJCardProperty(e)}}parseFromJCardProperty(e){e=JSON.parse(JSON.stringify(e)),this.field=e[0].toLowerCase(),this.params=e[1],this.type=e[2],this.value=e[3]}addParam(e,t){Array.isArray(this.params[e])?this.params[e].push(t):null!=this.params[e]?this.params[e]=[this.params[e],t]:this.params[e]=t}getValue(){return""+this.value}pref(){return this.params.pref||100}tags(){return this.params.type||[]}isEmpty(){return!(null!=this.value&&/[^;]+/.test(this.value)||Object.keys(this.params).length)}notEmpty(){return!this.isEmpty()}getField(){return""+this.field}toString(){return JSON.stringify(this)}toJSON(){return[this.field,this.params,this.type||"text",this.value]}}class JCard{constructor(e){if(this.props=new Map,this.version="4.0",e){if("object"!=typeof e)throw Error("error reading vcard");this.parseFromJCard(e)}}parseFromJCard(e){if(e=JSON.parse(JSON.stringify(e)),!/vcard/i.test(e[0]))throw new SyntaxError("Incorrect jCard format");e[1].forEach((e=>this.add(new VCardProperty(e))))}get(e,t){if(t){let s=this.props.get(e);return s?s.filter((e=>{let s=e.type;return(Array.isArray(s)?s:[s]).includes(t)})):[]}return this.props.get(e)||[]}getOne(e,t){return this.get(e,t||"pref")[0]||this.get(e)[0]}set(e,t,s,i){if("string"==typeof e&&(e=new VCardProperty(String(e),t,s,i)),!(e instanceof VCardProperty))throw Error("invalid argument of VCard.set(), expects string arguments or a VCardProperty");let r=e.getField();return this.props.set(r,[e]),e}add(e,t,s,i){if("string"==typeof e&&(e=new VCardProperty(String(e),t,s,i)),!(e instanceof VCardProperty))throw Error("invalid argument of VCard.add(), expects string arguments or a VCardProperty");let r=e.getField();return this.props.get(r)?this.props.get(r)?.push(e):this.props.set(r,[e]),e}remove(e){if("string"==typeof e)this.props.delete(e);else{if(!(e instanceof VCardProperty))throw Error("invalid argument of VCard.remove(), expects string and optional param filter or a VCardProperty");{let t=this.props.get(e.getField());if(!t?.includes(e))throw Error("Attempted to remove VCardProperty VCard does not have: ".concat(e));t.splice(t.indexOf(e),1),0===t.length&&this.props.delete(e.getField())}}}has(e){return!!this.props.get(e)&&this.props.get(e).length>0}toString(){return JSON.stringify(this)}toJSON(){let e=[["version",{},"text","4.0"]];for(const[t,s]of this.props.entries())if("version"!==t)for(const t of s)t.isEmpty()||e.push(t.toJSON());return["vcard",e]}parseFullName(e){let t=this.getOne("n");if(void 0===t)throw Error("'fn' VCardProperty not present in card, cannot parse full name");let s="";[3,1,2,0,4].forEach((e=>{let i=t.value[e];i&&(s+=" "+i.replace(","," "))})),s=s.trim();let i=new VCardProperty("fn",s);return e?.set&&(e.append?this.add(i):this.set(i)),i}}const Tr=["surName","givenName","middleName","namePrefix","nameSuffix"];class ContactModel extends AbstractModel{constructor(){super(),this.jCard=["vcard",[]],Ae(this,{focused:!1,selected:!1,checked:!1,sendToAll:!0,deleted:!1,readOnly:!1,id:0,givenName:"",surName:"",middleName:"",namePrefix:"",nameSuffix:"",nickname:null,note:null,org:"",department:"",title:"",encryptpref:"",signpref:""}),this.email=ko.observableArray(),this.tel=ko.observableArray(),this.url=ko.observableArray(),this.adr=ko.observableArray(),Te(this,{fullName:()=>[this.namePrefix(),this.givenName(),this.middleName(),this.surName()].join(" ").trim(),display:()=>{let e=this.fullName(),t=this.email()[0]?.value(),s=this.nickname();return e||t||s}})}static reviveFromJson(e){const t=super.reviveFromJson(e);if(t){let s=new JCard(e.jCard),i=s.getOne("n")?.value;i&&i.forEach(((e,s)=>e&&t[Tr[s]](e))),["nickname","note","title"].forEach((e=>{i=s.getOne(e),i&&t[e](i.value)})),(i=s.getOne("org")?.value)&&(t.org(i[0]),t.department(i[1]||"")),["email","tel","url"].forEach((e=>{i=s.get(e),i&&i.forEach((s=>{t[e].push({value:ko.observable(s.value)})}))})),i=s.get("adr"),i&&i.forEach((e=>{t.adr.push({street:ko.observable(e.value[2]),street_ext:ko.observable(e.value[1]),locality:ko.observable(e.value[3]),region:ko.observable(e.value[4]),postcode:ko.observable(e.value[5]),pobox:ko.observable(e.value[0]),country:ko.observable(e.value[6]),preferred:ko.observable(e.params.pref),type:ko.observable(e.params.type)})})),i=s.getOne("x-crypto"),t.signpref(i?.params.signpref||"Ask"),t.encryptpref(i?.params.encryptpref||"Ask"),t.jCard=e.jCard}return t}addEmail(){this.email.push({value:ko.observable("")}),this.sendToAllDisplayStatus()&&(document.getElementById("send-to-all").style.display="block")}addTel(){this.tel.push({value:ko.observable("")})}addUrl(){this.url.push({value:ko.observable("")})}addNickname(){this.nickname()||this.nickname("")}addNote(){this.note()||this.note("")}hasChanges(){return this.email().filter((e=>e.length)).length&&this.toJSON().jCard!=JSON.stringify(this.jCard)}toJSON(){let e=new JCard(this.jCard);if(e.set("n",[this.surName(),this.givenName(),this.middleName(),this.namePrefix(),this.nameSuffix()]),e.parseFullName({set:!0}),["nickname","note","title"].forEach((t=>this[t]()?e.set(t,this[t]()):e.remove(t))),this.org()){let t=[this.org()];this.department()&&t.push(this.department());let s=e.getOne("org");s?s.value=t:e.set("org",t)}else e.remove("");return["email","tel","url"].forEach((t=>{let s=this[t].map((e=>e.value()));e.get(t).forEach((t=>{let i=s.indexOf(t.value);0>i||!t.value?e.remove(t):s.splice(i,1)})),s.forEach((s=>s&&e.add(t,s)))})),e.set("x-crypto","",{allowed:"PGP/INLINE,PGP/MIME,S/MIME,S/MIMEOpaque",signpref:this.signpref(),encryptpref:this.encryptpref()},"x-crypto"),{uid:this.id,jCard:JSON.stringify(e)}}lineAsCss(){return(this.selected()?"selected":"")+(this.deleted()?" deleted":"")+(this.checked()?" checked":"")+(this.focused()?" focused":"")}sendToAllDisplayStatus(){return this.email.length>1}}const Fr="Contacts";let Mr,Pr=!1,Lr="";class ContactsPopupView extends AbstractViewPopup{constructor(){super("Contacts"),Ae(this,{search:"",contactsCount:0,selectorContact:null,importButton:null,contactsPage:1,isSaving:!1,contact:null}),this.contacts=kr,this.useCheckboxesInList=bt.useCheckboxesInList,this.selector=new Selector(kr,this.selectorContact,null,".e-contact-item",".e-contact-item .checkboxItem"),this.selector.on("ItemSelect",(e=>this.populateViewContact(e))),this.selector.on("ItemGetUid",(e=>e?e.id():"")),Te(this,{contactsPaginator:br(this.contactsPage,(()=>Math.max(1,Math.ceil(this.contactsCount()/50)))),contactsCheckedOrSelected:()=>{const e=kr.filter((e=>e.checked())),t=this.selectorContact();return e.length?e:t?[t]:[]},contactsSyncEnabled:()=>kr.allowSync()&&kr.syncMode(),isBusy:()=>kr.syncing()|kr.importing()|kr.loading()|this.isSaving()}),this.search.subscribe((()=>this.reloadContactList())),this.saveCommand=this.saveCommand.bind(this),Ds(this,{deleteCommand:e=>!e.isBusy()&&0<e.contactsCheckedOrSelected().length,newMessageCommand:e=>!e.isBusy()&&0<e.contactsCheckedOrSelected().length,saveCommand:e=>!e.isBusy(),syncCommand:e=>!e.isBusy()})}newContact(){this.populateViewContact(new ContactModel),this.selectorContact(null)}deleteCommand(){const e=this.contactsCheckedOrSelected();if(e.length){let t=this.selectorContact(),s=[],i=0;e.forEach((e=>{s.push(e.id()),t&&t.id()===e.id()&&this.selectorContact(t=null),e.deleted(!0),++i})),Hs.request("ContactsDelete",((e,t)=>{if(e)alert(t?.message||be(e));else{const e=this.contactsPage();e>Math.max(1,Math.ceil((this.contactsCount()-i)/50))&&this.contactsPage(e-1)}this.reloadContactList()}),{uids:s.join(",")})}}newMessageCommand(){let e=[],t={to:null,cc:null,bcc:null};this.contactsCheckedOrSelected().forEach((t=>{if(t){let s,i=(t.givenName()+" "+t.surName()).trim(),r=t.email();t.sendToAll()||(r=r.slice(0,1)),r.forEach((t=>{s=new EmailModel(t.value(),i),s.valid()&&e.push(s)}))}})),h(e)&&(Pr=!1,this.close(),t[Lr]=e,vr([rt.Empty,null,t.to,t.cc,t.bcc]))}clearSearch(){this.search("")}saveCommand(){this.saveContact(this.contact())}saveContact(e){const t=e.toJSON();t.jCard!=JSON.stringify(e.jCard)&&(this.isSaving(!0),Hs.request("ContactSave",((s,i)=>{s?alert(i?.message||be(s)):i.Result.ResultID&&(e.id()?(e.id(i.Result.ResultID),e.jCard=JSON.parse(t.jCard)):this.reloadContactList()),this.isSaving(!1)}),t))}syncCommand(){kr.sync((e=>{e&&alert(be(e)),this.reloadContactList(!0)}))}exportVcf(){gr(Y("ContactsVcf"),"contacts.vcf")}exportCsv(){gr(Y("ContactsCsv"),"contacts.csv")}populateViewContact(e){const t=this.contact(),s=()=>this.contact(e);t?.hasChanges()?AskPopupView.showModal([he("GLOBAL/SAVE_CHANGES"),()=>this.saveContact(t)|s(),s]):s()}reloadContactList(e=!1){let t=50*(this.contactsPage()-1);e&&(this.contactsPage(1),t=0),kr.loading(!0),Hs.abort("Contacts").request("Contacts",((e,t)=>{let s=0,i=[];e?alert(t?.message||be(e)):h(t.Result.List)&&(t.Result.List.forEach((e=>{(e=ContactModel.reviveFromJson(e))&&i.push(e)})),s=f(t.Result.Count)),this.contactsCount(0<s?s:0),kr(i),kr.loading(!1)}),{Offset:t,Limit:50,Search:this.search()})}onBuild(e){this.selector.init(e.querySelector(".b-list-content"),Fr),q("delete","",Fr,(()=>(this.deleteCommand(),!1))),q("c,w","",Fr,(()=>(this.newMessageCommand(),!1)));const t=this;if(e.addEventListener("click",(s=>{let i=s.target.closestWithin(".e-paginator a",e);i&&(i=f(ko.dataFor(i)?.value))&&(t.contactsPage(i),t.reloadContactList())})),this.importButton()){const e=new Jua({action:Q("UploadContacts"),limit:1,clickElement:this.importButton()});e&&e.on("onStart",(()=>{kr.importing(!0)})).on("onComplete",((e,t,s)=>{kr.importing(!1),this.reloadContactList(),e&&t&&s&&s.Result||alert(he("CONTACTS/ERROR_IMPORT_FILE"))}))}}onClose(){const e=this.contact();if(AskPopupView.hidden()&&e?.hasChanges())return AskPopupView.showModal([he("GLOBAL/SAVE_CHANGES"),()=>this.close()|this.saveContact(e),()=>this.close()]),!1}onShow(e,t){Pr=!!e,Lr=["to","cc","bcc"].includes(t)?t:"to",this.reloadContactList(!0)}onHide(){this.contact(null),this.selectorContact(null),this.search(""),this.contactsCount(0),kr([]),Pr&&vr()}}class SystemDropDownUserView extends AbstractViewRight{constructor(){super(),this.allowAccounts=L("AdditionalAccounts"),this.accountEmail=Si.email,this.accounts=Si,this.accountsLoading=Si.loading,Ae(this,{currentAudio:"",accountMenu:null}),this.allowContacts=Os.allowContacts(),addEventListener("audio.stop",(()=>this.currentAudio(""))),addEventListener("audio.start",(e=>this.currentAudio(e.detail)))}stopPlay(){O("audio.api.stop")}accountClick(e,t){let s=e?.email;return s&&0===t.button&&Si.email()!=s&&(Si.loading(!0),_(t),Hs.request("AccountSwitch",(t=>{t?(Si.loading(!1),alert("Account error: "+be(t).replace("%EMAIL%",s)),e.isAdditional()&&xs(AccountPopupView,[e])):rl.route.reload()}),{Email:s})),!0}accountName(){const e=Si.email();return Si.find((t=>t.email==e))?.label()||IDN.toUnicode(e)}settingsClick(){hasher.setHash(se())}settingsHelp(){xs(KeyboardShortcutsHelpPopupView)}addAccountClick(){this.allowAccounts&&xs(AccountPopupView)}contactsClick(){this.allowContacts&&xs(ContactsPopupView)}logoutClick(){rl.app.logout()}onBuild(){q("m","",[e,s,i],(()=>{if(!this.viewModelDom.hidden)return this.accountMenu().ddBtn.toggle(),!1})),q("?,f1,help","",[e,s,i],(()=>{if(!this.viewModelDom.hidden)return xs(KeyboardShortcutsHelpPopupView),!1}))}}class FolderCreatePopupView extends AbstractViewPopup{constructor(){super("FolderCreate"),Ae(this,{name:"",subscribe:!0,parentFolder:""}),this.parentFolderSelectList=Ce((()=>Vi([],[["",""]],(e=>e?e.detailedName():""),(e=>!e.subFolders.allow||hs.namespace&&!e.fullName.startsWith(hs.namespace))))),this.defaultOptionsAfterRender=b}submitForm(e){if(e.reportValidity()){const t=new FormData(e);let s=this.parentFolder();!s&&1<hs.namespace.length&&t.set("parent",hs.namespace.slice(0,hs.namespace.length-1)),Hs.abort("Folders").post("FolderCreate",hs.foldersCreating,t).then((e=>{const t=os(s),i=FolderModel.reviveFromJson(e.Result),r=t?t.subFolders:hs.folderList;rs(i),r.push(i),Ui(r)}),(e=>{hs.error(be(e.code,"",c.CantCreateFolder)+".\n"+e.message)})),this.close()}}onShow(){this.name(""),this.subscribe(!0),this.parentFolder("")}}class ComposeAttachmentModel extends AbstractModel{constructor(e,t,s=null,i=!1,r=!1,a="",o=""){super(),this.id=e,this.isInline=!!i,this.isLinked=!!r,this.cId=a,this.contentLocation=o,this.fromMessage=!1,Ae(this,{fileName:t,size:s,tempName:"",type:"",progress:0,error:"",waiting:!0,uploading:!1,enabled:!0,complete:!1}),Te(this,{progressText:()=>{const e=this.progress();return 1>e?"":(100<e?100:e)+"%"},progressStyle:()=>{const e=this.progress();return 1>e?"":"width:"+(100<e?100:e)+"%"},title:()=>this.error()||this.fileName(),friendlySize:()=>{const e=this.size();return null===e?"":et.friendlySize(e)},mimeType:()=>this.type()||et.getContentType(this.fileName()),fileExt:()=>et.getExtension(this.fileName()),iconClass:()=>et.getIconClass(this.fileExt(),this.mimeType())})}}class MimeHeaderAutocryptModel{constructor(e){this.addr="",this.prefer_encrypt="nopreference",this.keydata="",e&&(e.split(";").forEach((e=>{const t=e=>(e||"").trim().replace(/^["']|["']+$/g,"");this[t((e=e.match(/^([^=]+)=(.*)$/))[1]).replace("-","_")]=t(e[2])})),this.keydata=this.keydata.replace(/\s+/g,"\n"))}toString(){let e=`addr=${this.addr}; `;return"mutual"===this.prefer_encrypt&&(e+="prefer-encrypt=mutual; "),e+"keydata="+this.keydata.replace(/\n/g,"\n ")}pem(){return"-----BEGIN PGP PUBLIC KEY BLOCK-----\n\n"+this.keydata+"\n-----END PGP PUBLIC KEY BLOCK-----"}}class FolderSystemPopupView extends AbstractViewPopup{constructor(){super("FolderSystem"),this.notification=ko.observable(""),this.folderSelectList=Ce((()=>Vi(hs.systemFoldersNames(),[["",he("POPUPS_SYSTEM_FOLDERS/SELECT_CHOOSE_ONE")],[ls,he("POPUPS_SYSTEM_FOLDERS/SELECT_UNUSE_NAME")]]))),this.sentFolder=hs.sentFolder,this.draftsFolder=hs.draftsFolder,this.spamFolder=hs.spamFolder,this.trashFolder=hs.trashFolder,this.archiveFolder=hs.archiveFolder;const e=(()=>hs.saveSystemFolders()).debounce(1e3);Fe(hs,{sentFolder:e,draftsFolder:e,spamFolder:e,trashFolder:e,archiveFolder:e}),this.defaultOptionsAfterRender=b}onShow(e=0){let t="",s="POPUPS_SYSTEM_FOLDERS/NOTIFICATION_";switch(e){case tt.Sent:t=he(s+"SENT");break;case tt.Drafts:t=he(s+"DRAFTS");break;case tt.Junk:t=he(s+"SPAM");break;case tt.Trash:t=he(s+"TRASH");break;case tt.Archive:t=he(s+"ARCHIVE")}this.notification(t)}}const Ir="Compose",xr=D("template"),Nr=e=>e?y(e).match(/.{1,76}/g).join("\r\n"):"",Rr=e=>Yt(e)[0]?.email||!1,Dr=(e,t)=>e.filter((e=>e.email)).map((e=>e.toLine(t))).join(", "),Or=()=>{const e=hs.draftsFolder();e&&ls!==e&&(as(e,""),hs.currentFolderFullName()===e?Ni.reload(!0):qi(e))},_r=e=>(e=e.map((e=>e.email)),dr.find((t=>e.includes(t.email())))),Ur=(e,t)=>{if(h(t)){const s=e().trim();e(s+(s?", ":"")+t.map((e=>e?e.toLine():null)).validUnique().join(", ").trim())}},Vr=()=>"Plain"===bt.editorDefaultType(),qr=(e,t)=>{e=e.toUpperCase().trim(),t=t.replace(/\s+/g," ").trim();let s=!1,i="RE"===e,r="FWD"===e;const a=[],o=!r;return t&&t.split(":").forEach((e=>{const t=e.trim();s||!/^(RE|FWD)$/i.test(t)&&!/^(RE|FWD)[[(][\d]+[\])]$/i.test(t)?(a.push(e),s=!0):(i||(i=!!/^RE/i.test(t)),r||(r=!!/^FWD/i.test(t)))})),o?i=!1:r=!1,((o?"Re: ":"Fwd: ")+(i?"Re: ":"")+(r?"Fwd: ":"")+a.join(":").trim()).trim()};ko.extenders.toggleSubscribe=(e,t)=>(e.subscribe(t[1],t[0],"beforeChange"),e.subscribe(t[2],t[0]),e);class MimePart{constructor(){this.headers={},this.body="",this.boundary="",this.children=[]}toString(){const e=this.children.length,t=this.boundary||(this.boundary="part"+Jua.randomId()),s=this.headers;e&&!s["Content-Type"].includes(t)&&(s["Content-Type"]+=`; boundary="${t}"`);let i=Object.entries(s).map((([e,t])=>`${e}: ${t}`)).join("\r\n")+"\r\n";return this.body&&(i+="\r\n"+this.body.replace(/\r?\n/g,"\r\n")),e&&(this.children.forEach((e=>i+="\r\n--"+t+"\r\n"+e)),i+="\r\n--"+t+"--\r\n"),i}}class ComposePopupView extends AbstractViewPopup{constructor(){super("Compose");const e=(e,t,s,i)=>{const r=e&&t?.[s]();if(r&&(i||e[s]())){let t=e[s]().trim().split(",");t=t.filter((e=>(e=e.trim())&&r.trim()!==e)),i&&t.push(r),e[s](t.join(","))}};this.oEditor=null,this.sLastFocusedField="to",this.allowContacts=Os.allowContacts(),this.allowIdentities=L("Identities"),this.allowSpellcheck=bt.allowSpellcheck,Ae(this,{identitiesMenu:null,from:"",to:"",cc:"",bcc:"",replyTo:"",subject:"",isHtml:!1,requestDsn:!1,requestReadReceipt:!1,requireTLS:!1,markAsImportant:!1,sendError:!1,sendSuccessButSaveError:!1,savedError:!1,sendErrorDesc:"",savedErrorDesc:"",savedTime:0,emptyToError:!1,attachmentsInProcessError:!1,attachmentsInErrorError:!1,showCc:!1,showBcc:!1,showReplyTo:!1,doSign:!1,doEncrypt:!1,draftsFolder:"",draftUid:0,sending:!1,saving:!1,viewArea:"body",attacheMultipleAllowed:!1,addAttachmentEnabled:!1,editorArea:null,currentIdentity:dr()[0]}),["to","cc","bcc"].forEach((e=>{this[e].focused=ko.observable(!1),this[e].focused.subscribe((t=>t&&(this.sLastFocusedField=e)))})),this.attachments=Ie(),this.encryptOptions=Ie(),this.signOptions=Ie(),this.dragAndDropOver=ko.observable(!1).extend({debounce:1}),this.dragAndDropVisible=ko.observable(!1).extend({debounce:1}),this.currentIdentity.extend({toggleSubscribe:[this,t=>{e(this,t,"bcc"),e(this,t,"replyTo")},t=>{e(this,t,"bcc",!0),e(this,t,"replyTo",!0)}]}),this.doClose=this.doClose.debounce(200),this.iTimer=0,Te(this,{sendButtonSuccess:()=>!this.sendError()&&!this.sendSuccessButSaveError(),savedTimeText:()=>this.savedTime()?he("COMPOSE/SAVED_TIME",{TIME:this.savedTime().format("LT")}):"",emptyToErrorTooltip:()=>this.emptyToError()?he("COMPOSE/EMPTY_TO_ERROR_DESC"):"",attachmentsErrorTooltip:()=>{let e="";switch(!0){case this.attachmentsInProcessError():e=he("COMPOSE/ATTACHMENTS_UPLOAD_ERROR_DESC");break;case this.attachmentsInErrorError():e=he("COMPOSE/ATTACHMENTS_ERROR_DESC")}return e},attachmentsInProcess:()=>this.attachments.filter((e=>e&&!e.complete())),attachmentsInError:()=>this.attachments.filter((e=>e?.error())),attachmentsCount:()=>this.attachments().length,attachmentsInErrorCount:()=>this.attachmentsInError.length,attachmentsInProcessCount:()=>this.attachmentsInProcess.length,isDraft:()=>this.draftsFolder()&&this.draftUid(),canEncrypt:()=>this.encryptOptions().length,canMailvelope:()=>this.encryptOptions.includes("Mailvelope"),canSign:()=>this.signOptions().length,encryptOptionsText:()=>this.encryptOptions().join(", "),signOptionsText:()=>this.signOptions().map((e=>e[0])).join(", "),identitiesOptions:()=>dr.map((e=>({item:e,optValue:e.id(),optText:e.formattedName()}))),canBeSentOrSaved:()=>!this.sending()&&!this.saving()}),Fe(this,{sendError:e=>!e&&this.sendErrorDesc(""),savedError:e=>!e&&this.savedErrorDesc(""),sendSuccessButSaveError:e=>!e&&this.savedErrorDesc(""),currentIdentity:e=>{e&&(this.from(e.formattedName()),this.doEncrypt(e.pgpEncrypt()||bt.pgpEncrypt()),this.doSign(e.pgpSign()||bt.pgpSign()))},from:()=>{this.initSign(),this.initEncrypt()},cc:e=>{!1===this.showCc()&&e.length&&this.showCc(!0),this.initEncrypt()},bcc:e=>{!1===this.showBcc()&&e.length&&this.showBcc(!0),this.initEncrypt()},replyTo:e=>{!1===this.showReplyTo()&&e.length&&this.showReplyTo(!0)},attachmentsInErrorCount:e=>{0===e&&this.attachmentsInErrorError(!1)},to:e=>{this.emptyToError()&&e.length&&this.emptyToError(!1),this.initEncrypt()},attachmentsInProcess:e=>{this.attachmentsInProcessError()&&h(e)&&this.attachmentsInProcessError(!1)},viewArea:e=>{if(!this.mailvelope&&"mailvelope"==e){let e=Mr&&Mr.body.classList.contains("mailvelope")?Mr.plain():this.oEditor.getData(),t=this.isDraft(),s=ci.isEncrypted(e),i=M("phpUploadSizes").post_max_size,r=f(i);switch(i.slice(-1)){case"G":r*=1024;case"M":r*=1024;case"K":r*=1024}mailvelope.createEditorContainer("#mailvelope-editor",ci.mailvelopeKeyring,{quota:Math.max(2048,r/1024)-48,armoredDraft:s&&t?e:"",predefinedText:s?"":this.oEditor.isHtml()?qt(e):e,quotedMail:s&&!t?e:""}).then((e=>this.mailvelope=e))}}}),Ds(this,{sendCommand:e=>e.canBeSentOrSaved(),saveCommand:e=>e.canBeSentOrSaved(),deleteCommand:e=>e.isDraft(),skipCommand:e=>e.canBeSentOrSaved(),contactsCommand:e=>e.allowContacts}),this.from(dr()[0].formattedName())}sentFolder(){let e=this.currentIdentity()?.sentFolder?.()||hs.sentFolder();return bt.replySameFolder()&&3===h(this.aDraftInfo)&&this.aDraftInfo[2]?.length&&(e=this.aDraftInfo[2]),ls===e?null:e}sendCommand(){if(this.attachmentsInProcessError(!1),this.attachmentsInErrorError(!1),this.emptyToError(!1),this.attachmentsInProcess().length?(this.attachmentsInProcessError(!0),this.attachmentsArea()):this.attachmentsInError().length&&(this.attachmentsInErrorError(!0),this.attachmentsArea()),this.to().trim()||this.cc().trim()||this.bcc().trim()||this.emptyToError(!0),!this.emptyToError()&&!this.attachmentsInErrorError()&&!this.attachmentsInProcessError()){const e=this.sentFolder();if(""===e)xs(FolderSystemPopupView,[tt.Sent]);else{const t=e=>{this.sendError(!0),this.sendErrorDesc(e),this.sending(!1)},s=(e,t)=>{this.sendError(!0),this.sendErrorDesc(be(e,t?.message,c.CantSendMessage)+"\n"+(t?.messageAdditional||t?.message))};try{this.sendError(!1),this.sending(!0);const i=e=>{Hs.request("SendMessage",((t,i)=>{if(this.sending(!1),t)if(c.CantSaveMessage===t){this.sendSuccessButSaveError(!0);let e=he("COMPOSE/SAVED_ERROR_ON_SEND");i?.messageAdditional&&(e=e+"\n"+i?.messageAdditional),this.savedErrorDesc(e)}else{this.sendError(!0),s(t,i);let r="S/MIME"===e.sign?this.currentIdentity():null;e.signFingerprint&&this.signOptions.forEach((e=>"GnuPG"===e[0]&&(r=e[1]))),r&&Gs.delete(r)}else{if(h(this.aDraftInfo)>0){const e={reply:"\\answered",forward:"$forwarded"}[this.aDraftInfo[0]];if(e){const t=Mr.flags();-1===t.indexOf(e)&&(t.push(e),Mr.flags(t))}}this.close()}as(this.draftsFolder(),""),as(e.saveFolder,""),3===h(this.aDraftInfo)&&as(this.aDraftInfo[2],""),Or()}),e,3e4)};this.getMessageRequestParams(e).then(i).catch(t)}catch(e){t(e)}}}}saveCommand(){this.saving()||this.sending()||(hs.draftsFolderNotEnabled()?xs(FolderSystemPopupView,[tt.Drafts]):(this.savedError(!1),this.saving(!0),this.autosaveStart(),this.getMessageRequestParams(hs.draftsFolder(),1).then((e=>{Hs.request("SaveMessage",((e,t)=>{let s=!1;if(this.saving(!1),!e&&t.Result.folder&&t.Result.uid){if(s=!0,this.bFromDraft){const e=vi.message();e&&this.draftsFolder()===e.folder&&this.draftUid()==e.uid&&vi.message(null)}this.draftsFolder(t.Result.folder),this.draftUid(t.Result.uid),this.savedTime(new Date),this.bFromDraft&&as(this.draftsFolder(),""),as(hs.draftsFolder(),"")}s||(this.savedError(!0),this.savedErrorDesc(be(c.CantSaveMessage))),Or()}),e,2e5)})).catch((e=>{this.saving(!1),this.savedError(!0),this.savedErrorDesc(be(c.CantSaveMessage)+": "+e)}))))}deleteCommand(){AskPopupView.hidden()&&xs(AskPopupView,[he("POPUPS_ASK/DESC_WANT_DELETE_MESSAGES"),()=>{const e=this.draftsFolder(),t=new Set([this.draftUid()]);Ni.moveMessages(e,t),this.close()}])}onClose(){return this.skipCommand(),!1}skipCommand(){ComposePopupView.inEdit(!0),!hs.draftsFolderNotEnabled()&&bt.allowDraftAutosave()&&this.saveCommand(),this.doClose()}contactsCommand(){this.allowContacts&&(this.skipCommand(),setTimeout((()=>{xs(ContactsPopupView,[!0,this.sLastFocusedField])}),200))}autosaveStart(){clearTimeout(this.iTimer),this.iTimer=setTimeout((()=>{!this.modalVisible()||hs.draftsFolderNotEnabled()||!bt.allowDraftAutosave()||this.isEmptyForm(!1)||this.savedError()||this.saveCommand(),this.autosaveStart()}),6e4)}emailsSource(e,t){Hs.abort("Suggestions").request("Suggestions",((e,s)=>{!e&&d(s.Result)?t(s.Result.map((e=>e?.[0]?new EmailModel(e[0],e[1]).toLine():null)).filter((e=>e))):c.RequestAborted!==e&&t([])}),{Query:e})}selectIdentity(e){e=e?.item,e&&(this.currentIdentity(e),this.setSignature(e))}onHide(){clearTimeout(this.iTimer),ComposePopupView.inEdit()||this.reset(),this.to.focused(!1)}dropMailvelope(){this.mailvelope&&(A("mailvelope-editor").textContent="",this.mailvelope=null)}editor(e){e&&this.editorArea()&&(this.oEditor?e(this.oEditor):this.oEditor=new HtmlEditor(this.editorArea(),(()=>e(this.oEditor)),(e=>this.isHtml(!!e))))}setSignature(e,t){e&&rt.Draft!==t&&rt.EditAsNew!==t&&this.editor((t=>{let s=e.signature()||"",i=s.startsWith(":HTML:"),r=Mr?Dr(Mr.from,!0):"";r&&(s=s.replace(/{{FROM-FULL}}/g,r),!r.includes(" ")&&0<r.indexOf("@")&&(r=r.replace(/@\S+/,"")),s=s.replace(/{{FROM}}/g,r)),s=(i?s.slice(6):s).replace(/\r/g,"").replace(/\s{1,2}?{{FROM}}/g,"").replace(/\s{1,2}?{{FROM-FULL}}/g,"").replace(/{{DATE}}/g,(new Date).format({dateStyle:"full",timeStyle:"short"})).replace(/{{TIME}}/g,(new Date).format("LT")).replace(/{{MOMENT:[^}]+}}/g,""),s.length&&t.setSignature(s,i,!!e.signatureInsertBefore())}))}onShow(e,t,s,i,r,a,o){this.autosaveStart(),this.viewModelDom.dataset.wysiwyg=bt.editorDefaultType();let n={mode:e||rt.Empty,to:s,cc:i,bcc:r,subject:a,text:o};1<h(t)?n.messages=t:n.message=d(t)?t[0]:t,ComposePopupView.inEdit()?rt.Empty!==n.mode?xs(AskPopupView,[he("COMPOSE/DISCARD_UNSAVED_DATA"),()=>this.initOnShow(n),null,!1]):(Ur(this.to,s),Ur(this.cc,i),Ur(this.bcc,r),a&&!this.subject()&&this.subject(a)):this.initOnShow(n),ComposePopupView.inEdit(!1)}initOnShow(e){const t={},s=Si.email();Mr=e.message,s&&(t[s]=!0),this.reset();let i=null;if(Mr)switch(e.mode){case rt.Reply:case rt.ReplyAll:case rt.Forward:case rt.ForwardAsAttachment:i=_r(Mr.to.concat(Mr.cc,Mr.bcc));break;case rt.Draft:i=_r(Mr.from.concat(Mr.replyTo))}if(i=i||dr()[0],i&&(t[i.email()]=!0),h(e.to)&&this.to(Dr(e.to)),h(e.cc)&&this.cc(Dr(e.cc)),h(e.bcc)&&this.bcc(Dr(e.bcc)),e.mode&&Mr){let s,r="",a=me(Mr.dateTimestamp(),"FULL"),o=Mr.subject(),n="",l=Mr.draftInfo;switch(e.mode){case rt.Reply:case rt.ReplyAll:if(rt.Reply===e.mode)this.to(Dr(Mr.replyEmails(t)));else{let e=Mr.replyAllEmails(t);this.to(Dr(e[0])),this.cc(Dr(e[1]))}this.subject(qr("Re",o)),this.prepareMessageAttachments(Mr,e.mode),this.aDraftInfo=["reply",Mr.uid,Mr.folder],this.sInReplyTo=Mr.messageId,this.sReferences=(Mr.references+" "+Mr.messageId).trim(),Mr.headers().valuesByName("autocrypt").forEach((e=>{let t=new MimeHeaderAutocryptModel(e);t.addr&&t.keydata&&(ci.hasPublicKeyForEmails([t.addr])||ci.importKey(t.pem(),!0,!0))}));break;case rt.Forward:case rt.ForwardAsAttachment:this.subject(qr("Fwd",o)),this.prepareMessageAttachments(Mr,e.mode),this.aDraftInfo=["forward",Mr.uid,Mr.folder],this.sInReplyTo=Mr.messageId,this.sReferences=(Mr.references+" "+Mr.messageId).trim();break;case rt.Draft:this.bFromDraft=!0,this.draftsFolder(Mr.folder),this.draftUid(Mr.uid);case rt.EditAsNew:this.to(Dr(Mr.to)),this.cc(Dr(Mr.cc)),this.bcc(Dr(Mr.bcc)),this.replyTo(Dr(Mr.replyTo)),this.subject(o),this.prepareMessageAttachments(Mr,e.mode),this.aDraftInfo=3===h(l)?l:null,this.sInReplyTo=Mr.inReplyTo,this.sReferences=Mr.references}switch(xr.innerHTML=Mr.bodyAsHTML(),xr.content.querySelectorAll("img").forEach((e=>{e.src||e.dataset.xSrcCid||e.dataset.xSrc||e.replaceWith(e.alt||e.title)})),n=xr.innerHTML.trim(),e.mode){case rt.Reply:case rt.ReplyAll:n="<br><br><p>"+he("COMPOSE/REPLY_MESSAGE_TITLE",{DATETIME:a,EMAIL:Mr.from.toString(!1,!0)})+":</p><blockquote>"+n.trim()+"</blockquote>";break;case rt.Forward:r=Mr.cc.toString(!1,!0),n="<br><br><p>"+he("COMPOSE/FORWARD_MESSAGE_TOP_TITLE")+"</p><div>"+he("GLOBAL/FROM")+": "+Mr.from.toString(!1,!0)+"<br>"+he("GLOBAL/TO")+": "+Mr.to.toString(!1,!0)+(r.length?"<br>"+he("GLOBAL/CC")+": "+r:"")+"<br>"+he("COMPOSE/FORWARD_MESSAGE_TOP_SENT")+": "+Ut(a)+"<br>"+he("GLOBAL/SUBJECT")+": "+Ut(o)+"<br><br>"+n.trim()+"</div>";break;case rt.ForwardAsAttachment:n="";break;default:s=ci.isEncrypted(n)||Vr()||!Mr.isHtml(),s&&(n=Mr.plain())}this.editor((t=>{s?(t.modePlain(),t.setPlain(n)):t.setHtml(n),this.setSignature(i,e.mode),this.setFocusInPopup()}))}else rt.Empty===e.mode?(this.subject(null!=e.subject?""+e.subject:""),this.editor((t=>{t.setHtml(e.text?""+e.text:""),Vr()&&t.modePlain(),this.setSignature(i),this.setFocusInPopup()}))):e.messages?(e.messages.forEach((e=>this.addMessageAsAttachment(e))),this.editor((t=>{Vr()?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)&&Hs.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(ve(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():xs(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(M("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<r&&0<s&&s<r)||(a.waiting(!1).uploading(!0).complete(!0).error(he("UPLOAD/ERROR_FILE_IS_TOO_BIG")),!1)})).on("onStart",(e=>{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.code,o=t&&r.Attachment;let n="";null!=a?n=ve(a):o||(n=he("UPLOAD/ERROR_UNKNOWN")),i&&(n?i.waiting(!1).uploading(!1).complete(!0).error(n+"\n"+r.message):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",Ir,(()=>!1)),V("w","meta",Ir,(()=>!1)),V("m","meta",Ir,(()=>(this.identitiesMenu().ddBtn.toggle(),!1))),V("arrowdown","meta",Ir,(()=>(this.skipCommand(),!1))),V("s","meta",Ir,(()=>(this.saveCommand(),!1))),V("save","",Ir,(()=>(this.saveCommand(),!1))),V("enter","meta",Ir,(()=>(this.sendCommand(),!1))),V("mailsend","",Ir,(()=>(this.sendCommand(),!1))),V("escape,close","shift",Ir,(()=>(this.doClose(),!1))),this.editor((e=>e[Vr()?"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=[rt.Reply,rt.ReplyAll].includes(t);s||[rt.Forward,rt.Draft,rt.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)}})):rt.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(bt.requestDsn()),this.requestReadReceipt(bt.requestReadReceipt()),this.requireTLS(bt.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(bt.pgpSign()),this.doEncrypt(bt.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=>Rr(e.trim()))).validUnique()}initSign(){let e=[],t=this.currentIdentity(),s=Rr(this.from()),i=ai.getPrivateKeyFor(s,1);i&&e.push(["OpenPGP",i]),i=$s.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){$s.hasPublicKeyForEmails(e)&&t.push("GnuPG"),ai.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||Cr.find((t=>e==t.emailAddress&&t.smimeencrypt)))).length&&t.push("S/MIME"),await ni.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=qt(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=Nr(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=Nr(n.plain),t.children.push(s),t.children.push(e),e=t}let s=!1;for(let t=0;t<c.length;++t)if("OpenPGP"==c[t][0])try{let i=new MimePart;i.headers["Content-Type"]='multipart/signed; micalg="pgp-sha256"; protocol="application/pgp-signature"',i.headers["Content-Transfer-Encoding"]="7Bit",i.children.push(e);let r=new MimePart;r.headers["Content-Type"]='application/pgp-signature; name="signature.asc"',r.headers["Content-Transfer-Encoding"]="7Bit",r.body=await ai.sign(e.toString(),c[t][1],1),i.children.push(r),s=!0,n.html=n.plain="",n.signed=i.toString(),n.boundary=i.boundary,e=i;break}catch(e){}else if("GnuPG"==c[t][0]){let e=await $s.sign(c[t][1]);if(null!=e){n.signFingerprint=c[t][1].fingerprint,n.signPassphrase=e,s=!0;break}}else if("S/MIME"==c[t][0]&&(n.sign="S/MIME",o.smimeKeyEncrypted())){const e=await Gs.ask(o,he("SMIME/PRIVATE_KEY_OF",{EMAIL:o.email()}),"CRYPTO/SIGN");null!=e&&(n.signPassphrase=e.password,e.remember&&Gs.handle(o,e.password),s=!0)}if(c.length&&!s)throw"Signing failed";if(d.length){const t=()=>Object.entries(ci.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<d.length;++s){if("OpenPGP"==d[s]){n.encrypted=await ai.encrypt(e.toString(),l),n.signed="",t();break}if("GnuPG"==d[s]){n.encryptFingerprints=JSON.stringify($s.getPublicKeyFingerprints(l)),t();break}if("S/MIME"==d[s]){n.encryptCertificates=[o.smimeCertificate()],Cr.forEach((e=>{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=hs.systemFolders,this.moveAction=hr,this.allowContacts=Os.allowContacts(),this.foldersFilter=er,this.filterUnseen=ko.observable(!1),Te(this,{foldersFilterVisible:()=>20<hs.folderList().CountRec,folderListVisible:()=>{let e=hs.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 Qi(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(hr()){const e=t.ctrlKey||2===hr(),s=Ni.listCheckedOrSelectedUidsWithSubMails();hr(0),s.size&&Ni.moveMessages(s.folder,s,i.fullName,e)}else{bt.usePreviewPane()||vi.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)),mt.isMobile()&&N(!0)}Os.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<t.length-1&&++i,t[i].classList.add("focused"),this.scrollToFocused()),!1})),V("enter,open","",t,(()=>{const t=i("li a.focused");return t&&(Os.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();Qi(t.fullName,e),t.collapsed(!e)}return!1})),V("escape,tab,arrowright","",t,(()=>(Os.focusedState(e),hr(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.top<r.top?t="start":i.bottom>r.bottom&&(t="end"),t&&s.scrollIntoView("start"===t)}}}composeClick(){vr()}clearFolderSearch(){er("")}createFolder(){xs(FolderCreatePopupView)}configureFolders(){hasher.setHash(se("folders"))}contactsClick(){this.allowContacts&&xs(ContactsPopupView)}}class FolderClearPopupView extends AbstractViewPopup{constructor(){super("FolderClear"),Ae(this,{folder:null,clearing:!1}),Te(this,{dangerDescHtml:()=>he("POPUPS_CLEAR_FOLDER/DANGER_DESC_HTML_1",{FOLDER:this.folder()?.localName()})}),Ds(this,{clearCommand:e=>!e.clearing()})}clearCommand(){const e=this.folder();e&&(this.clearing(!0),Hs.request("FolderClear",(t=>{e.totalEmails(0),e.unreadEmails(0),vi.message(null),Ni.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"),Ae(this,{from:"",to:"",subject:"",text:"",keyword:"",repliedValue:-1,selectedDateValue:0,selectedTreeValue:"",hasAttachment:!1,starred:!1,unseen:!1}),Te(this,{showMultisearch:()=>hs.hasCapability("MULTISEARCH"),keywords:()=>{const e=[{value:"",label:""}];return hs.currentFolder().optionalTags().forEach((t=>{let s=t.toLowerCase();e.push({value:t,label:he("MESSAGE_TAGS/"+s,0,s)})})),e},showKeywords:()=>hs.currentFolder().permanentFlags().some(ds),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&&Ni.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()),0<e.selectedDateValue()){let t=new Date;t.setDate(t.getDate()-e.selectedDateValue()),s("since",t.toISOString().split("T")[0])}else if(-1>e.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 Kr=()=>Ni.hasCheckedOrSelected(),Br=(...e)=>Ni.setAction(...e),Hr=(e,t)=>{let s=Ni.listCheckedOrSelectedUidsWithSubMails();s.size&&rl.app.moveMessagesToFolderType(e,s.folder,s,t)},Gr=e=>10>e?"0"+e:""+e,jr=e=>e.getFullYear()+Gr(1+e.getMonth())+Gr(e.getDate()),Wr=e=>{Er(e)};let $r="";class MailMessageList extends AbstractViewRight{constructor(){super(),this.allowDangerousActions=L("DangerousActions"),this.messageList=Ni,this.archiveAllowed=Ni.archiveAllowed,this.canMarkAsSpam=Ni.canMarkAsSpam,this.isSpamFolder=Ni.isSpamFolder,this.composeInEdit=ComposePopupView.inEdit,this.isMobile=mt.isMobile,this.popupVisibility=Ns,this.useCheckboxesInList=bt.useCheckboxesInList,this.userUsageProc=hs.quotaPercentage,this.hideDeleted=bt.hideDeleted,Ae(this,{focusSearch:!1}),this.dragOver=ko.observable(!1).extend({throttle:1}),this.dragOverEnter=ko.observable(!1).extend({throttle:1});const e=F.app("attachmentsActions");this.attachmentsActions=ko.observableArray(h(e)?e:[]),Te(this,{sortSupported:()=>hs.hasCapability("SORT")&&!Ni.threadUid(),messageListSearchDesc:()=>{const e=Ni().search;return e?he("MESSAGE_LIST/SEARCH_RESULT_FOR",{SEARCH:e}):""},messageListPaginator:br(Ni.page,Ni.pageCount),checkAll:{read:()=>Ni.hasChecked(),write:e=>{e=!!e,Ni.forEach((t=>t.checked(e)))}},inputSearch:{read:Ni.mainSearch,write:e=>$r=e},isIncompleteChecked:()=>{const e=Ni.listChecked().length;return e&&Ni().length>e},listGrouped:()=>{let e=Ni.threadUid(),t=hs.sortMode()||"DATE";return bt.listGrouped()&&(t.includes("DATE")||t.includes("FROM"))&&!e},timeFormat:()=>(hs.sortMode()||"").includes("FROM")?"AUTO":"LT",groupedList:()=>{let e,t=[],s=hs.sortMode()||"DATE";if(s.includes("FROM"))Ni.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=jr(new Date),i=Intl.RelativeTimeFormat?new Intl.RelativeTimeFormat(k.documentElement.lang,{numeric:"auto"}):0;Ni.forEach((r=>{let a,o=new Date(1e3*r.dateTimestamp()),n=jr(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()+"-"+Gr(1+o.getMonth())+"-"+Gr(o.getDate()),messages:[]},t.push(e)),e.messages.push(r)}))}return t},sortText:()=>{let e=hs.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(Ni,Ni.selectedMessage,Ni.focusedMessage,".messageListItem",".messageListItem .messageCheckbox"),this.selector.on("ItemSelect",(e=>{e?Wr(e):vi.message(null)})),this.selector.on("MiddleClick",(e=>Er(e,!0))),this.selector.on("ItemGetUid",(e=>e?e.folder+"/"+e.uid:"")),this.selector.on("canSelect",(()=>Ni.canSelect())),this.selector.on("click",((e,t)=>{const s=e.target;if(s.closest(".flagParent")){if(t){const e=Ni.listCheckedOrSelected();Br(t.folder,t.isFlagged()?lt:nt,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(!Ni.hasChecked()){e=e?-1:1;const t=Ni.page()+e;t>0&&t<=Ni.pageCount()&&(bt.usePreviewPane()||vi.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=Ni.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,Wr(e)}else vi.message(null)})),Ni.endHash.subscribe((()=>this.selector.scrollToFocused()).throttle(50)),Ds(this,{downloadAttachCommand:Kr,downloadZipCommand:Kr,forwardCommand:Kr,deleteWithoutMoveCommand:Kr,deleteCommand:()=>Ni.hasCheckedOrSelectedAndUndeleted(),undeleteCommand:()=>Ni.hasCheckedOrSelectedAndDeleted(),archiveCommand:Kr,spamCommand:Kr,notSpamCommand:Kr,moveCommand:Kr,copyCommand:Kr})}changeSort(e,t){hs.sortMode(t.target.closest("li").dataset.sort),this.reload()}clearListIsVisible(){return!this.messageListSearchDesc()&&!Ni.error()&&!Ni.endThreadUid()&&Ni().length&&(Ni.isSpamFolder()||Ni.isTrashFolder())&&L("DangerousActions")}clear(){L("DangerousActions")&&xs(FolderClearPopupView,[hs.currentFolder()])}reload(){Ni.isLoading()||Ni.reload(!1,!0)}forwardCommand(){vr([rt.ForwardAsAttachment,Ni.listCheckedOrSelected()])}downloadZipCommand(){let e=[];Ni.forEach((t=>t.checked()&&e.push(t.requestHash))),fr(null,e,null,null,Ni().folder)}downloadAttachCommand(){let e=[];Ni.forEach((t=>{t.checked()&&t.attachments.forEach((t=>{!t.isLinked()&&t.download&&e.push(t.download)}))})),fr(null,e)}deleteWithoutMoveCommand(){L("DangerousActions")&&Hr(tt.Trash,!0)}deleteCommand(){ls===hs.trashFolder()?Br(hs.currentFolderFullName(),ct,Ni.listCheckedOrSelected()):Hr(tt.Trash)}undeleteCommand(){Br(hs.currentFolderFullName(),dt,Ni.listCheckedOrSelected())}archiveCommand(){Hr(tt.Archive)}spamCommand(){Hr(tt.Junk)}notSpamCommand(){Hr(tt.Inbox)}moveOrCopy(s,i,r){if(Kr()){s&&i?.preventDefault&&_(i);let a=hr();Os.focusedState(a?e:t),hr(a?0:r)}}moveCommand(e,t){this.moveOrCopy(e,t,1)}copyCommand(e,t){this.moveOrCopy(e,t,2)}composeClick(){vr()}cancelSearch(){Ni.mainSearch(""),this.focusSearch(!1)}cancelThreadUid(){hasher.setHash(ie(hs.currentFolderFullNameHash(),Ni.pageBeforeThread(),Ni.listSearch()))}listSetSeen(){Br(hs.currentFolderFullName(),at,Ni.listCheckedOrSelected())}listSetAllSeen(){let e=hs.currentFolderFullName(),t=Ni.endThreadUid();if(e){let s=0;const i=[];let r=os(e);r&&(Ni.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),Hs.request("MessageSetSeenToAll",null,{folder:e,setAction:1,threadUids:i.join(",")}))}}listUnsetSeen(){Br(hs.currentFolderFullName(),ot,Ni.listCheckedOrSelected())}listSetFlags(){Br(hs.currentFolderFullName(),nt,Ni.listCheckedOrSelected())}listUnsetFlags(){Br(hs.currentFolderFullName(),lt,Ni.listCheckedOrSelected())}seenMessagesFast(e){const t=Ni.listCheckedOrSelected();t.length&&Br(t[0].folder,e?at:ot,t)}gotoPage(e){e&&hasher.setHash(ie(hs.currentFolderFullNameHash(),e,Ni.listSearch(),Ni.threadUid()))}gotoThread(e){e?.threadsLen()&&(Ni.pageBeforeThread(Ni.page()),hasher.setHash(ie(hs.currentFolderFullNameHash(),1,Ni.listSearch(),e.uid)))}listEmptyMessage(){return this.dragOver()||Ni().length||Ni.isLoading()||Ni.error()?"":he("MESSAGE_LIST/EMPTY_"+(Ni.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=bt.usePreviewPane();Sr(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{mt.isMobile()&&N(!0),a(t,".messageList")&&s===Os.focusedState()&&Os.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=ko.dataFor(a(e,".messageListItem"));t&&(t.threadsLen()?this.gotoThread(t):yi())}}),F.app("allowAppendMessage")){const e=i.querySelector(".listDragOver"),t=e=>{for(const t of e.dataTransfer.items)if("file"===t.kind&&xe===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)&&(Ni.loading(!0),Bi(hs.currentFolderFullName(),s.dataTransfer.files)),this.dragOverEnter(!1),this.dragOver(!1)}})}V("enter,open","",e,(()=>U()?(Ni.mainSearch($r),!1):vi.message()&&Ni.canSelect()?(bi()||yi(),!1):void 0)),q("z","",[e,s],(()=>(this.archiveCommand(),!1))),q("delete","shift",e,(()=>(Ni.listCheckedOrSelected().length&&this.deleteWithoutMoveCommand(),!1))),q("delete","",e,(()=>(Ni.listCheckedOrSelected().length&&this.deleteCommand(),!1))),V("r","meta",[t,e,s],(()=>(this.reload(),!1))),q("a","meta",e,(()=>(this.checkAll(!(this.checkAll()&&!this.isIncompleteChecked())),!1))),q("w,c,new","",[e,s],(()=>(vr(),!1))),q("i","",[e,s],(()=>{const e=Ni.listCheckedOrSelected();return e.length&&Br(e[0].folder,e.every((e=>e.isFlagged()))?lt:nt,e),!1})),q("t","",[e],(()=>{let e=Ni.selectedMessage()||Ni.focusedMessage();return 0<e?.threadsLen()&&this.gotoThread(e),!1})),q("insert","",e,(()=>(this.moveCommand(),!1))),q("q","",[e,s],(()=>(this.seenMessagesFast(!0),!1))),q("u","",[e,s],(()=>(this.seenMessagesFast(!1),!1))),q("f,mailforward","shift",[e,s],(()=>(this.forwardCommand(),!1))),L("Search")&&V("/","",[e,s],(()=>(this.focusSearch(!0),!1))),V("escape","",e,(()=>this.messageListSearchDesc()?(this.cancelSearch(),!1):Ni.endThreadUid()?(this.cancelThreadUid(),!1):void 0)),V("tab","shift",e,(()=>(Os.focusedState(t),!1))),V("arrowleft","",e,(()=>(Os.focusedState(t),!1))),V("tab,arrowright","",e,(()=>{if(vi.message())return Os.focusedState(s),!1})),V("arrowleft","meta",s,(()=>!1)),V("arrowright","meta",s,(()=>!1)),V("f","meta",e,this.advancedSearchClick)}advancedSearchClick(){xs(AdvancedSearchPopupView,[Ni.mainSearch()])}groupSearch(e){e.search&&Ni.mainSearch(e.search)}groupCheck(e){e.messages.forEach((e=>e.checked(!e.checked())))}quotaTooltip(){return he("MESSAGE_LIST/QUOTA_SIZE",{SIZE:et.friendlySize(hs.quotaUsage()),PROC:hs.quotaPercentage(),LIMIT:et.friendlySize(hs.quotaLimit())}).replace(/<[^>]+>/g,"")}}class OpenPgpImportPopupView extends AbstractViewPopup{constructor(){super("OpenPgpImport"),Ae(this,{search:"",key:"",keyError:!1,keyErrorMessage:"",saveGnuPG:!0,saveServer:!0}),this.canGnuPG=$s.isSupported(),this.key.subscribe((()=>{this.keyError(!1),this.keyErrorMessage("")}))}searchPGP(){this.key(he("SUGGESTIONS/SEARCHING_DESC"));const e=()=>Hs.request("PgpSearchKey",((e,t)=>{e?this.key(t.message):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()&&$s.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&&0<s?(t[0]&&t[1]&&t[2]&&t[1]===t[2]&&ci.importKey(this.key(),r,a),--s,i=!1):i=!0}while(!i);this.close()}}onShow(e){this.key(e||""),this.keyError(!1),this.keyErrorMessage("")}}const Jr=()=>A("messageItem")||{},zr=vi.message,Yr=e=>{const t=zr();t&&Ni.setAction(t.folder,e,[t])},Zr=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=zr();e&&(zr(null),rl.app.moveMessagesToFolderType(t,e.folder,new Set([e.uid]),s))}),this.messageVisible);this.msgDefaultAction=bt.msgDefaultAction,this.simpleAttachmentsList=bt.simpleAttachmentsList,Ae(this,{showAttachmentControls:!!Ji(10),downloadAsZipLoading:!1,showFullInfo:"1"===Ji(9),actionsMenu:null,viewFromShort:"",dkimData:["none","",""],nowTracking:!1}),this.moveAction=hr;const i=F.app("attachmentsActions");this.attachmentsActions=ko.observableArray(h(i)?i:[]),this.hasCheckedMessages=Ni.hasChecked,this.archiveAllowed=Ni.archiveAllowed,this.canMarkAsSpam=Ni.canMarkAsSpam,this.isDraftFolder=Ni.isDraftFolder,this.isSpamFolder=Ni.isSpamFolder,this.message=zr,this.messageLoadingThrottle=vi.loading,this.messageError=vi.error,this.fullScreenMode=bi,this.toggleFullScreen=yi,this.downloadAsZipError=ko.observable(!1).extend({falseTimeout:7e3}),this.messageDomFocused=ko.observable(!1).extend({rateLimit:0}),this.viewHash="",Te(this,{allowAttachmentControls:()=>h(i)&&L("AttachmentsActions"),downloadAsZipAllowed:()=>this.attachmentsActions.includes("zip")&&(zr()?.attachments||[]).filter((e=>e?.checked()&&e?.download)).length,tagsAllowed:()=>hs.currentFolder()?.tagsAllowed(),messageVisible:()=>!vi.loading()&&!!zr(),tagsToHTML:()=>zr()?.flags().map((e=>ds(e)?'<span class="focused msgflag-'+e+'">'+he("MESSAGE_TAGS/"+e,0,e)+"</span>":"")).join(" "),askReadReceipt:()=>zr()?.readReceipt&&!(Ni.isDraftFolder()||Ni.isSentFolder())&&!zr()?.flags().includes("$mdnsent")&&!zr()?.flags().includes("\\answered"),listAttachments:()=>zr()?.attachments().filter((e=>bt.listInlineAttachments()||!e.isLinked())),hasAttachments:()=>zr()?.attachments().some((e=>bt.listInlineAttachments()||!e.isLinked())),canBeRepliedOrForwarded:()=>!Ni.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"===bt.viewImages(),firstUnsubsribeLink:()=>zr()?.unsubsribeLinks()[0]||"",pgpSupported:()=>zr()&&ci.isSupported(),canBeUndeleted:()=>zr()?.isDeleted(),messageListOrViewLoading:()=>Ni.isLoading()|vi.loading()}),Fe(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)):(Ni.selectedMessage(null),this.viewHash="",this.scrollMessageToTop())},showFullInfo:e=>$i(9,e?"1":"0")}),this.replyCommand=t(rt.Reply),this.replyAllCommand=t(rt.ReplyAll),this.forwardCommand=t(rt.Forward),this.forwardAsAttachmentCommand=t(rt.ForwardAsAttachment),this.editAsNewCommand=t(rt.EditAsNew),this.deleteCommand=(()=>e((()=>{if(ls===hs.trashFolder())Yr(ct);else{const e=zr();e&&(zr(null),rl.app.moveMessagesToFolderType(tt.Trash,e.folder,new Set([e.uid])))}}),this.messageVisible))(),this.undeleteCommand=(t=>e((()=>Yr(t)),this.messageVisible))(dt),this.deleteWithoutMoveCommand=s(tt.Trash,!0),this.archiveCommand=s(tt.Archive),this.spamCommand=s(tt.Junk),this.notSpamCommand=s(tt.Inbox),Ds(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(){zr(null)}editCommand(){zr()&&vr([rt.Draft,zr()])}moveOrCopy(e,s,i){e&&s?.preventDefault&&_(s),this.actionsMenu().ddBtn.hide(),Os.focusedState(t),hr(i)}moveCommand(e,t){this.moveOrCopy(e,t,1)}copyCommand(e,t){this.moveOrCopy(e,t,2)}setUnseen(){Yr(ot),zr(null)}goUpCommand(){O("mailbox.message-list.selector.go-up",!!zr())}goDownCommand(){O("mailbox.message-list.selector.go-down",!!zr())}replyOrforward(e){vr([e,zr()])}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&&yr(t.href))_(e);else if(t=i(e,".attachmentsPlace .showPreview"),t){const s=ko.dataFor(t),i=s?.linkDownload();i&&xe==s.mimeType&&(_(e),Zr(i).then((e=>{const t=new MessageModel;di(e,t),t.popupMessage()})))}else if(t=i(e,".attachmentsPlace .showPreplay"),t){_(e);const s=ko.dataFor(t);if(s&&Ss.supported)switch(!0){case Ss.supportedMp3&&s.isMp3():Ss.playMp3(s.linkDownload(),s.fileName);break;case Ss.supportedOgg&&s.isOgg():Ss.playOgg(s.linkDownload(),s.fileName);break;case Ss.supportedWav&&s.isWav():Ss.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&&(ai.isSupported()||$s.isSupported())?Zr(s).then((e=>xs(OpenPgpImportPopupView,[e]))):gr(s,e.fileName))}i(e,".messageItemHeader .subjectParent .flagParent")&&Yr(zr()?.isFlagged()?lt:nt)}})),H.subscribe((e=>this.messageDomFocused(s===e))),V("escape","",s,(()=>{if(!this.viewModelDom.hidden&&zr()){const t=bt.usePreviewPane();return bi()?(fi(),t&&Os.focusedState(e)):t?Os.focusedState(e):zr(null),!1}})),V("enter,open","",s,(()=>(bi()||yi(),!1))),q("r,mailreply","",[e,s],(()=>!zr()||(this.replyCommand(),!1))),q("a","",[e,s],(()=>{if(zr())return this.replyAllCommand(),!1})),q("mailreply","shift",[e,s],(()=>{if(zr())return this.replyAllCommand(),!1})),q("f,mailforward","",[e,s],(()=>{if(zr())return this.forwardCommand(),!1})),q("i","meta",[e,s],(()=>(zr()&&this.toggleFullInfo(),!1))),q("b","",[e,s],(()=>{const e=zr();if(e?.body)return e.body.querySelectorAll("details").forEach((e=>e.open=!e.open)),!1})),V("b","shift",[e,s],(()=>{if(!U())return zr()?.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(!bi()&&zr()&&bt.usePreviewPane()&&!Jr().scrollLeft)return Os.focusedState(e),!1})),V("tab","shift",s,(()=>(!bi()&&zr()&&bt.usePreviewPane()&&Os.focusedState(e),!1))),vi.bodiesDom(t.querySelector(".bodyText"))}scrollMessageToTop(){Jr().scrollTop=0}scrollMessageToLeft(){Jr().scrollLeft=0}toggleAttachmentControls(){const e=!this.showAttachmentControls();this.showAttachmentControls(e),$i(10,e)}downloadAsZip(){const e=(zr()?.attachments||[]).map((e=>e?.checked()?e.download:"")).filter((e=>e));fr(zr().subject(),e,(()=>this.downloadAsZipError(!0)),this.downloadAsZipLoading)}showImages(){zr().showExternalImages()}showTracking(){const e=zr(),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=(bt.viewImagesWhitelist().trim()+"\n"+e).trim();bt.viewImagesWhitelist(t),Hs.saveSetting("ViewImagesWhitelist",t),zr().showExternalImages(1)}printableCheckedMessageCount(){const e=Ni.listCheckedOrSelectedUidsWithSubMails().size;return 0<e?100>e?e:"99+":""}readReceipt(){let e=zr();e.readReceipt&&(e.flags.push("$mdnsent"),Hs.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":Si.email()})}))}newTag(){let e=zr();if(e){let t=prompt(he("MESSAGE/NEW_TAG"),"")?.replace(/[\s\\]+/g,"");t.length&&ds(t)&&(e.toggleTag(t),hs.currentFolder().permanentFlags.push(t))}}pgpDecrypt(){const e=zr(),t=e.pgpEncrypted();delete t.error,ci.decrypt(e).then((t=>{if(!t)throw Error("Decryption failed, canceled or not possible");e.pgpDecrypted(!0),t.data&&(di(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=zr();ci.verify(e).then((t=>{t?e.pgpSigned(t):alert("Verification failed or no valid public key found")}))}async smimeDecrypt(){const e=zr(),t=e.from.concat(e.to,e.cc,e.bcc).map((e=>e.email)),s=dr.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 Gs.ask(s,he("SMIME/PRIVATE_KEY_OF",{EMAIL:s.email()}),"CRYPTO/DECRYPT"),!t)return;r.passphrase=t?.password}Hs.post("SMimeDecryptMessage",null,r).then((i=>{i?.Result?.data&&(e.smimeDecrypted(!0),di(i.Result.data,e),e.html()?e.viewHtml():e.viewPlain(),t&&t.remember&&Gs.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=zr(),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,Hs.post("SMimeVerifyMessage",null,s).then((s=>{s?.Result&&(s.Result.body&&(di(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=F.app("listPermanentFiltered")?0:hs.foldersInboxUnreadCount(),t=Si.email();rl.setTitle((t?(0<e?"("+e+") ":" ")+t+" - ":"")+he("TITLES/MAILBOX"))}onShow(){this.updateWindowTitle(),Os.focusedState("none"),Os.focusedState(e)}onRoute(e,t,s,i){const r=(a=e.replace(/~([\d]+)$/,""),os(ts.get(a)));var a;if(r){if(hs.currentFolder(r),Ni.page(1>t?1:t),Ni.listSearch(s),i){let t=new MessageModel;t.folder=e,t.uid=i,Er(t)}else{let t=e.replace(/^.+~(\d+)$/,"$1");Ni.threadUid(e===t?0:f(t))}Ni.reload()}}onStart(){super.onStart(),addEventListener("mailbox.inbox-unread-count",(e=>{hs.foldersInboxUnreadCount(e.detail),this.updateWindowTitle()}))}onBuild(){k.addEventListener("click",(e=>e.target.closest("#rl-right")&&hr(0)))}routes(){const e=(e,t)=>e?m(t[0]):is(),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 Xr=[];class AbstractSettingsScreen extends AbstractScreen{constructor(e){super("settings",e),this.menu=ko.observableArray(),this.oCurrentSubScreen=null}onRoute(e){let t=null,s=null,i=Xr.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(){Xr.forEach((e=>this.menu.push(e)))}routes(){const e=Xr.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 Qr(e,t,s,i,r=!1){let a=e.name.replace(/(User|Admin)Settings/,"");Xr.push({vmc:e,label:s||"SETTINGS_LABELS/"+a.toUpperCase(),route:i||a.toLowerCase(),selected:ko.observable(!1),template:t||e.name,isDefault:!!r})}const ea=[],ta=[];rl.pluginRemoteRequest=(e,t,s,i)=>{rl.app.Remote.request("Plugin"+t,e,s,i)},rl.addSettingsViewModel=(e,t,s,i)=>{ea.push([e,t,s,i])},rl.addSettingsViewModelForAdmin=(e,t,s,i)=>{ta.push([e,t,s,i])},rl.pluginSettingsGet=(e,t)=>M("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=Ss.notifications,this.notificationSound=ko.observable(M("NotificationSound")),this.notificationSounds=ko.observableArray(M("newMailSounds")),this.minRefreshInterval=M("minRefreshInterval"),this.desktopNotifications=Mi.enabled,this.isDesktopNotificationAllowed=Mi.allowed,this.threadsAllowed=Os.threadsAllowed,this.threadAlgorithms=ko.observableArray(),hs.capabilities.forEach((e=>e.startsWith("THREAD=")&&this.threadAlgorithms.push(e.slice(7)))),this.threadAlgorithms.sort(((e,t)=>e.length-t.length)),this.threadAlgorithm=bt.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","markdown"].forEach((e=>this[e]=bt[e])),this.allowLanguagesOnSettings=!!M("allowLanguagesOnSettings"),this.languageTrigger=ko.observable(o),this.identities=dr,this.wysiwygs=yt,Te(this,{languageFullName:()=>we(this.language()),identityMainDesc:()=>{const e=dr.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<yt().length,msgDefaultActions:()=>(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","markdown","DesktopNotifications","SoundNotification"]);const e=e=>()=>{this.languageTrigger(e),setTimeout((()=>this.languageTrigger(o)),1e3)};Fe(this,{language:t=>{this.languageTrigger(a),Se(t).then(e(n),e(l)).then((()=>Hs.saveSetting("language",t)))},hourCycle:e=>Hs.saveSetting("hourCycle",e),notificationSound:e=>{Hs.saveSetting("NotificationSound",e),F.set("NotificationSound",e)},useThreads:e=>{Ni([]),Hs.saveSetting("UseThreads",e)},threadAlgorithm:e=>{Ni([]),Hs.saveSetting("threadAlgorithm",e)},checkMailInterval:()=>{_i(bt.checkMailInterval())}})}editMainIdentity(){mr(dr.main())}testSoundNotification(){Ss.playNotification(!0)}testSystemNotification(){Mi.display("SnappyMail","Test notification")}selectLanguage(){xs(LanguagesPopupView,[this.language,this.languages(),re.userLanguage()])}registerMailto(){navigator.registerProtocolHandler("mailto",`${location.protocol}//${location.host}${location.pathname}?mailto&to=%s`,M("title")||"SnappyMail"),alert(he("GLOBAL/DONE")),this.mailto(0)}}class UserSettingsContacts{constructor(){this.contactsAutosave=ko.observable(!!M("ContactsAutosave")),this.allowContactsSync=kr.allowSync,this.syncMode=kr.syncMode,this.syncUrl=kr.syncUrl,this.syncUser=kr.syncUser,this.syncPass=kr.syncPass,this.syncModeOptions=Ce((()=>(ce(),[{id:0,name:he("GLOBAL/NO")},{id:1,name:he("GLOBAL/YES")},{id:2,name:he("SETTINGS_CONTACTS/SYNC_READ")}]))),this.saveTrigger=Ce((()=>[kr.syncMode(),kr.syncUrl(),kr.syncUser(),kr.syncPass()].join("|"))).extend({debounce:500}),this.contactsAutosave.subscribe((e=>Hs.saveSettings(null,{ContactsAutosave:e}))),this.saveTrigger.subscribe((()=>Hs.request("SaveContactsSyncData",null,{Mode:kr.syncMode(),Url:kr.syncUrl(),User:kr.syncUser(),Password:kr.syncPass()})))}}class UserSettingsAccounts{constructor(){this.allowAdditionalAccount=L("AdditionalAccounts"),this.allowIdentities=L("Identities"),this.accounts=Si,this.loading=Si.loading,this.identities=dr,this.mainEmail=M("mainEmail"),this.accountForDeletion=ko.observable(null).askDeleteHelper(),this.identityForDeletion=ko.observable(null).askDeleteHelper(),this.showUnread=bt.showUnreadCount,bt.showUnreadCount.subscribe((e=>Hs.saveSetting("ShowUnreadCount",e)))}addNewAccount(){xs(AccountPopupView)}editAccount(e){e?.isAdditional()&&xs(AccountPopupView,[e])}addNewIdentity(){mr()}editIdentity(e){mr(e)}deleteAccount(e){e?.askDelete()&&(this.accountForDeletion(null),this.accounts.remove((t=>e===t)),Hs.request("AccountDelete",((e,t)=>{!e&&t.Reload?(rl.route.root(),setTimeout((()=>location.reload()),1)):pr()}),{emailToDelete:e.email}))}deleteIdentity(e){e?.askDelete()&&(this.identityForDeletion(null),dr.remove((t=>e===t)),Hs.request("IdentityDelete",(()=>rl.app.accountsAndIdentities()),{idToDelete:e.id()}))}accountsAndIdentitiesAfterMove(){Hs.request("AccountsAndIdentitiesSortOrder",null,{Accounts:Si.filter((e=>e.isAdditional())).map((e=>e.email)),Identities:dr.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}),Ae(this,{serverError:!1,serverErrorDesc:""}),rl.loadScript(M("StaticLibsJs").replace("/libs.","/sieve.")).then((()=>{const e=window.Sieve;e.folderList=hs.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=Ce((()=>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=dr,Ae(this,{email:"",emailError:!1,name:"",password:"",keyType:"ECC",submitRequest:!1,submitError:"",backupPublicKey:!0,backupPrivateKey:!1,saveGnuPGPublic:!0,saveGnuPGPrivate:!1}),this.canGnuPG=L("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()};ai.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,$s.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"),Ae(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()?Hs.request("SMimeImportCertificate",((e,t)=>{e?(this.pemError(!0),this.pemErrorMessage(be(e,t?.message))):this.close()}),{pem:this.pem()}):this.pemError(!0)}onShow(){this.pem(""),this.pemError(!1),this.pemErrorMessage("")}}class UserSettingsSecurity extends AbstractViewSettings{constructor(){super(),this.autoLogout=bt.autoLogout,this.autoLogoutOptions=Ce((()=>(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=bt.keyPassForget,this.addSetting("keyPassForget"),this.gnupgPublicKeys=$s.publicKeys,this.gnupgPrivateKeys=$s.privateKeys,this.openpgpkeysPublic=ai.publicKeys,this.openpgpkeysPrivate=ai.privateKeys,this.smimeCertificates=Cr,this.canOpenPGP=L("OpenPGP"),this.canGnuPG=$s.isSupported(),this.canMailvelope=!!window.mailvelope}addOpenPgpKey(){xs(OpenPgpImportPopupView)}generateOpenPgpKey(){xs(OpenPgpGeneratePopupView)}importToOpenPGP(){ai.loadBackupKeys()}importToSMime(){xs(SMimeImportPopupView)}onBuild(){window.mailvelope&&mailvelope.createSettingsContainer("#mailvelope-settings")}}const sa=ko.observable(null).askDeleteHelper();class UserSettingsFolders{constructor(){this.showKolab=hs.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=hs.displaySpecSetting,this.folderList=hs.folderList,this.folderListOptimized=hs.optimized,this.folderListError=hs.error,this.hideUnsubscribed=bt.hideUnsubscribed,this.unhideKolabFolders=bt.unhideKolabFolders,this.loading=hs.foldersChanging,this.folderForDeletion=sa,bt.hideUnsubscribed.subscribe((e=>Hs.saveSetting("HideUnsubscribed",e))),bt.unhideKolabFolders.subscribe((e=>Hs.saveSetting("UnhideKolabFolders",e)))}onShow(){hs.error("")}createFolder(){xs(FolderCreatePopupView)}systemFolder(){xs(FolderSystemPopupView)}deleteFolder(e){e&&e.canBeDeleted()&&e.askDelete()&&(0<e.totalEmails()?e.errorMsg(be(c.CantDeleteNonEmptyFolder)):(sa(null),e&&Hs.abort("Folders").post("FolderDelete",hs.foldersDeleting,{folder:e.fullName}).then((()=>{if(e.selectable(!1),!e.subFolders.length){ns(e.fullName);const t=os(e.parentName);(t?t.subFolders:hs.folderList).remove(e)}}),(e=>{hs.error(be(e.code,"",c.CantDeleteFolder)+".\n"+e.message)}))))}hideError(){hs.error("")}toggleFolderKolabType(e,t){let s=t.target.value;Hs.request("FolderSetMetadata",null,{folder:e.fullName,key:st,value:s}),e.kolabType(s)}toggleFolderSubscription(e){let t=!e.isSubscribed();Hs.request("FolderSubscribe",null,{folder:e.fullName,subscribe:t?1:0}),e.isSubscribed(t)}toggleFolderCheckable(e){let t=!e.checkable();Hs.request("FolderCheckable",null,{folder:e.fullName,checkable:t?1:0}),e.checkable(t)}}const ia={name:mt.userBackgroundName,hash:mt.userBackgroundHash};Ae(ia,{uploaderButton:null,loading:!1,error:""});class UserSettingsThemes{constructor(){this.fontSansSerif=mt.fontSansSerif,this.fontSerif=mt.fontSerif,this.fontMono=mt.fontMono,Fe(mt,{fontSansSerif:e=>{Hs.saveSettings(null,{fontSansSerif:e})},fontSerif:e=>{Hs.saveSettings(null,{fontSerif:e})},fontMono:e=>{Hs.saveSettings(null,{fontMono:e})}}),this.theme=mt.theme,this.themes=mt.themes,this.themesObjects=ko.observableArray(),ia.enabled=L("UserBackground"),this.background=ia,this.themeTrigger=ko.observable(o).extend({debounce:100}),mt.theme.subscribe((e=>{this.themesObjects.forEach((t=>t.selected(e===t.name))),gt(e,this.themeTrigger),Hs.saveSettings(null,{Theme:e})}))}setTheme(e){mt.theme(e.name)}onBuild(){const e=mt.theme();if(this.themesObjects(mt.themes.map((t=>({name:t,nameDisplay:ft(t),selected:ko.observable(t===e),themePreviewSrc:te(t)})))),ia.uploaderButton()&&ia.enabled){new Jua({action:Q("UploadBackground"),limit:1,clickElement:ia.uploaderButton()}).on("onStart",(()=>{ia.loading(!0),ia.error("")})).on("onComplete",((e,t,s)=>{if(ia.loading(!1),ia.name(s?.Result?.name||""),ia.hash(s?.Result?.hash||""),!ia.name()||!ia.hash()){let e="";if(s.code)switch(s.code){case r.FileIsTooBig:e=he("SETTINGS_THEMES/ERROR_FILE_IS_TOO_BIG");break;case r.FileType:e=he("SETTINGS_THEMES/ERROR_FILE_TYPE_ERROR")}ia.error(e||s.message||he("SETTINGS_THEMES/ERROR_UNKNOWN"))}}))}}onShow(){ia.error("")}clearBackground(){ia.enabled&&Hs.request("ClearUserBackground",(()=>{ia.name(""),ia.hash("")}))}}class SettingsMenuUserView extends AbstractViewLeft{constructor(e){super(),this.menu=e.menu}link(e){return se(e)}backToInbox(){hasher.setHash(((e="INBOX")=>"#/mailbox/"+e)(is()))}}class SettingsPaneUserView extends AbstractViewRight{constructor(){super()}onShow(){vi.message(null)}onBuild(e){e.addEventListener("click",(()=>{event.target.closestWithin(".toggleLeft",e)?R():mt.isMobile()&&N(!0)}))}}class SettingsUserScreen extends AbstractSettingsScreen{constructor(){super([SettingsMenuUserView,SettingsPaneUserView,SystemDropDownUserView]);const e=[UserSettingsGeneral];Os.allowContacts()&&e.push(UserSettingsContacts),(L("AdditionalAccounts")||L("Identities"))&&e.push(UserSettingsAccounts),L("Sieve")&&e.push(UserSettingsFilters),e.push(UserSettingsSecurity),e.push(UserSettingsFolders),L("Themes")&&e.push(UserSettingsThemes),e.forEach(((e,t)=>Qr(e,e.name.replace("User",""),e!==UserSettingsAccounts||L("AdditionalAccounts")?0:"SETTINGS_ACCOUNTS/LEGEND_IDENTITIES",0,0===t))),(!1?ta:ea).forEach((e=>Qr(...e))),fe((()=>this.sSettingsTitle=he("TITLES/SETTINGS")),(()=>this.setSettingsTitle()))}onShow(){this.setSettingsTitle(),G(i)}setSettingsTitle(){const e=Si.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<e.size?"span"+e.size:"";if(this.trigger){const e=ko.observable(""),s=t=>{switch(t){case n:e("success");break;case l:e("error");break;default:e("")}};s(this.trigger()),this.className=Ce((()=>(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){Ns(!1),e=e||($()?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(),pt(),this.start()}}var ra;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?Hs.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()})),ra=new class AppUser extends AbstractApp{constructor(){super(Hs);const e=36e5;let t=Date.now();setInterval((()=>{const s=Date.now();s>t+e+1e3&&Hs.request("Version",(e=>100<e&&location.reload()),{version:F.app("version")}),t=s}),e),K(k,["keydown","keyup"],(e=>C.toggle("rl-ctrl-key-pressed",e.ctrlKey)).debounce(500)),V("escape,enter","",ur),addEventListener("click",ur),this.folderList=hs.folderList,this.messageList=Ni,this.ask=AskPopupView,this.loadAccountsAndIdentities=pr}moveMessagesToFolderType(e,t,s,i){let r=null,a=0;switch(e){case tt.Junk:r=os(hs.spamFolder()),a=e,i=i||ls===hs.spamFolder();break;case tt.Inbox:r=os(is());break;case tt.Trash:r=os(hs.trashFolder()),a=e,i=i||t===hs.spamFolder()||t===hs.trashFolder();break;case tt.Archive:r=os(hs.archiveFolder()),a=e,i=i||ls===hs.archiveFolder()}i?xs(AskPopupView,[he("POPUPS_ASK/DESC_WANT_DELETE_MESSAGES"),()=>{Ni.moveMessages(t,s)}]):r?Ni.moveMessages(t,s,r.fullName):xs(FolderSystemPopupView,[a])}folderInformation(e,t){qi(e,t)}logout(){Hs.request("Logout",((e,t)=>e?alert("Logout error: "+ye(e,t)):rl.logoutReload(F.app("customLogoutLink"))))}bootstart(){super.bootstart(),addEventListener("beforeunload",(e=>{if(Ns()||!bt.usePreviewPane()&&vi.message())return e.preventDefault(),e.returnValue=he("POPUPS_ASK/EXIT_ARE_YOU_SURE")}),{capture:!0})}refresh(){pt(),re.language(M("language")),this.start()}start(){M("Auth")?(rl.setTitle(he("GLOBAL/LOADING")),Ss.notifications(!!M("SoundNotification")),Mi.enabled(!!M("DesktopNotifications")),Si.email(M("Email")),bt.init(),kr.init(),tr(((e,t)=>{try{e?(Rs([MailBoxUserScreen,SettingsUserScreen]),_i(M("CheckMailInterval")),pr(),setTimeout((()=>{const e=hs.currentFolderFullName();is()===e||qi(e),hs.hasCapability("LIST-STATUS")||Ki(!0)}),1e3),setTimeout((()=>Hs.request("AppDelayStart")),35e3),K(k,["touchstart","mousemove","keydown"],bt.delayLogout,{passive:!0}),bt.delayLogout(),setTimeout((()=>{const e=A("rl-left"),t=()=>Sr(e,4,mt.isMobile()||N()?0:"Width");e&&(t(),N.subscribe(t))}),1),setInterval(ge,6e4),ci.init(),Cr.loadCertificates(),setTimeout((()=>yr(M("mailToEmail"))),500)):(this.logout(),alert("Folders error: "+ye(0,t)))}catch(e){}}))):Rs([LoginUserScreen])}showMessageComposer(e=[]){xs(ComposePopupView,e)}},rl.app=ra,rl.logoutReload=ra.logoutReload,rl.i18n=he,rl.Enums={StorageResultType:{Success:0,Error:1,Abort:2}},rl.route={root:()=>{rl.route.off(),hasher.setHash(W)},reload:()=>{rl.route.root(),setTimeout((()=>location.reload()),100)},off:()=>hasher.active=!1,on:()=>hasher.active=!0}}();
| ver. 1.4 |
Github
|
.
| PHP 8.2.28 | Generation time: 0.05 |
proxy
|
phpinfo
|
Settings