From fd13fd632ca70c4fac3a251b6dffea83784cea54 Mon Sep 17 00:00:00 2001 From: InverseBot Date: Sat, 18 Feb 2017 01:21:42 -0500 Subject: [PATCH] (js/css) Update generated files --- UI/WebServerResources/js/Mailer.services.js | 2 +- UI/WebServerResources/js/Mailer.services.js.map | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/UI/WebServerResources/js/Mailer.services.js b/UI/WebServerResources/js/Mailer.services.js index 88e57c1e1..828d19fe1 100644 --- a/UI/WebServerResources/js/Mailer.services.js +++ b/UI/WebServerResources/js/Mailer.services.js @@ -1,3 +1,3 @@ !function(){"use strict";function a(b){"function"!=typeof b.then&&(angular.extend(this,b),_.forEach(this.identities,function(a){a.fullName?a.full=a.fullName+" <"+a.email+">":a.full="<"+a.email+">"}),a.$log.debug("Account: "+JSON.stringify(b,void 0,2)))}a.$factory=["$q","$timeout","$log","sgSettings","Resource","Preferences","Mailbox","Message",function(b,c,d,e,f,g,h,i){return angular.extend(a,{$q:b,$timeout:c,$log:d,$$resource:new f(e.activeUser("folderURL")+"Mail",e.activeUser()),$Preferences:g,$Mailbox:h,$Message:i}),a}];try{angular.module("SOGo.MailerUI")}catch(a){angular.module("SOGo.MailerUI",["SOGo.Common"])}angular.module("SOGo.MailerUI").factory("Account",a.$factory),a.$findAll=function(b){return b?a.$unwrapCollection(b):a.$$resource.fetch("","mailAccounts").then(function(b){return a.$unwrapCollection(b)})},a.$unwrapCollection=function(b){var c=[];return angular.forEach(b,function(b,d){b.id=d,c[d]=new a(b)}),a.$accounts=c,c},a.prototype.getLength=function(){return this.$flattenMailboxes().length},a.prototype.getItemAtIndex=function(a){var b;return b=this.$flattenMailboxes(),a>=0&&a=0,a.children&&a.children.length>0&&d(a.children)})};a.$Preferences.settings.Mail.ExpandedFolders&&(b=angular.isString(a.$Preferences.settings.Mail.ExpandedFolders)?angular.fromJson(a.$Preferences.settings.Mail.ExpandedFolders):a.$Preferences.settings.Mail.ExpandedFolders,c.$expanded=b.indexOf("/"+c.id)>=0,b.length>0&&d(c.$mailboxes)),a.$accounts&&(c.$expanded|=1==a.$accounts.length),c.$flattenMailboxes({reload:!0})}),c.$mailboxes}):a.$q.when(this.$mailboxes)},a.prototype.$flattenMailboxes=function(b){var c=this,d=[],e=[],f=function(a){_.forEach(a,function(a){d.push(a),(b&&b.all||a.$expanded)&&a.children&&a.children.length>0&&f(a.children)})};return!this.$$flattenMailboxes||b&&(b.reload||b.all)?(f(this.$mailboxes),b&&b.all||(c.$$flattenMailboxes=d,b&&b.saveState&&(_.forEach(a.$accounts,function(a){a.$expanded&&e.push("/"+a.id),_.reduce(a.$$flattenMailboxes,function(a,b){return b.$expanded&&a.push("/"+b.id),a},e)}),a.$$resource.post(null,"saveFoldersState",e)))):d=this.$$flattenMailboxes,d},a.prototype.$getMailboxByType=function(a){var b,c=function(b){var d=_.find(b,function(b){return b.type==a});return d||angular.forEach(b,function(a){!d&&a.children&&a.children.length>0&&(d=c(a.children))}),d};return b=c(this.$mailboxes)},a.prototype.$getMailboxByPath=function(a){var b=null,c=function(b){var d=_.find(b,function(b){return b.path==a});return d||angular.forEach(b,function(a){!d&&a.children&&a.children.length>0&&(d=c(a.children))}),d};return b=c(this.$mailboxes)},a.prototype.$newMailbox=function(b,c){var d=this;return a.$$resource.post(b.toString(),"createFolder",{name:c}).then(function(){d.$getMailboxes({reload:!0})})},a.prototype.updateQuota=function(a){var b,c,d;b=Math.round(1e4*a.usedSpace/a.maxQuota)/100,c=l("quotasFormat"),d=c.formatted(b,Math.round(a.maxQuota/10.24)/100),this.$quota={percent:b,description:d}},a.prototype.$newMessage=function(){var b=this;return a.$$resource.fetch(this.id.toString(),"compose").then(function(c){a.$log.debug("New message (compose): "+JSON.stringify(c,void 0,2));var d=new a.$Message(c.accountId,b.$getMailboxByPath(c.mailboxPath),c);return d}).then(function(b){return a.$$resource.fetch(b.$absolutePath({asDraft:!0}),"edit").then(function(c){return a.$log.debug("New message (edit): "+JSON.stringify(c,void 0,2)),angular.extend(b.editable,c),b.isNew=!0,b})})},a.prototype.$addDelegate=function(b){var c=this,d=a.$q.defer(),e={uid:b.uid};return!b.uid||_.indexOf(_.map(this.delegates,"uid"),b.uid)>-1?d.resolve():a.$$resource.fetch(this.id.toString(),"addDelegate",e).then(function(){c.delegates.push(b),d.resolve(c.users)},function(a,b){d.reject(l("An error occured please try again."))}),d.promise},a.prototype.$removeDelegate=function(b){var c=this,d={uid:b};return a.$$resource.fetch(this.id.toString(),"removeDelegate",d).then(function(){var a=_.indexOf(_.map(c.delegates,"uid"),b);a>=0&&c.delegates.splice(a,1)})}}(),function(){"use strict";function a(b,c){if(this.$account=b,"function"!=typeof c.then){if(this.init(c),this.name&&!this.path){var d=a.$$resource.create("createFolder",this.name);this.$unwrap(d)}}else this.$unwrap(c)}a.$factory=["$q","$timeout","$log","sgSettings","Resource","Message","Acl","Preferences","sgMailbox_PRELOAD",function(b,c,d,e,f,g,h,i,j){return angular.extend(a,{$q:b,$timeout:c,$log:d,$$resource:new f(e.activeUser("folderURL")+"Mail",e.activeUser()),$Message:g,$$Acl:h,$Preferences:i,$query:{sort:"arrival",asc:0},selectedFolder:null,$refreshTimeout:null,$virtualMode:!1,PRELOAD:j}),i.ready().then(function(){i.settings.Mail.SortingState&&(a.$query.sort=i.settings.Mail.SortingState[0],a.$query.asc=parseInt(i.settings.Mail.SortingState[1]))}),a}];try{angular.module("SOGo.MailerUI")}catch(a){angular.module("SOGo.MailerUI",["SOGo.Common"])}angular.module("SOGo.MailerUI").constant("sgMailbox_PRELOAD",{LOOKAHEAD:50,SIZE:100}).factory("Mailbox",a.$factory),a.$find=function(b,c){var d;return d=c&&c.all?this.$$resource.fetch(b.id.toString(),"viewAll"):this.$$resource.fetch(b.id.toString(),"view"),a.$unwrapCollection(b,d)},a.$unwrapCollection=function(b,c){var d=[],e=function(c,d){for(var f=0;f=0&&a=0},a.prototype.isNoSelect=function(){return this.flags.indexOf("noselect")>=0},a.prototype.$rename=function(){var b,c,d,e,f=this;return this.name==this.$shadowData.name?a.$q.when():(b=function(a,c){var d=null,e=_.find(c,function(a){return a.path==f.path});return e?d=a:angular.forEach(c,function(a){!d&&a.children&&a.children.length>0&&(d=b(a,a.children))}),d},c=b(null,this.$account.$mailboxes),d=null===c?this.$account.$mailboxes:c.children,e=_.indexOf(_.map(d,"id"),this.id),this.$save().then(function(b){var c;angular.extend(f,b),f.id=f.$id(),d.splice(e,1),c=_.find(d,function(b){return a.$log.debug(b.name+" ? "+f.name),"folder"==b.type&&b.name.localeCompare(f.name)>0}),e=c?_.indexOf(_.map(d,"id"),c.id):d.length,d.splice(e,0,f)}))},a.prototype.$compact=function(){var b=this;return a.$$resource.post(this.id,"expunge").then(function(a){a.quotas&&b.$account.updateQuota(a.quotas)})},a.prototype.$setFolderAs=function(b){return a.$$resource.post(this.id,"setAs"+b+"Folder")},a.prototype.$emptyTrash=function(){var b=this;return a.$$resource.post(this.id,"emptyTrash").then(function(a){b.$messages=[],b.uidsMap={},b.unseenCount=0,angular.isDefined(b.children)&&b.children.length&&b.$account.$getMailboxes({reload:!0}),a.quotas&&b.$account.updateQuota(a.quotas)})},a.prototype.$markAsRead=function(){return a.$$resource.post(this.id,"markRead")},a.prototype.$flagMessages=function(b,c,d){var e={msgUIDs:_.map(b,"uid"),flags:c,operation:d};return a.$$resource.post(this.id,"addOrRemoveLabel",e).then(function(){return b})},a.prototype.saveSelectedMessages=function(){var b,c,d,e;return d=_.filter(this.$messages,function(a){return a.selected}),e=_.map(d,"uid"),b={uids:e},c={filename:l("Saved Messages.zip")},a.$$resource.download(this.id,"saveMessages",{uids:e})},a.prototype.exportFolder=function(){var b;return b={filename:this.name+".zip"},a.$$resource.download(this.id,"exportFolder",null,b)},a.prototype.$delete=function(b){var c=this;return a.$$resource.post(this.id,"delete",b).then(function(){return c.$account.$getMailboxes({reload:!0}),!0})},a.prototype.$_deleteMessages=function(a,b){var c,d=this,e=this.$messages.length;return c=_.filter(b,function(a,b){return!a.isread}),this.unseenCount-=c.length,_.forEachRight(this.$messages,function(b,c){var f=_.findIndex(a,function(a){return b.uid==a});f>-1?(a.splice(f,1),delete d.uidsMap[b.uid],b.uid==d.selectedMessage&&delete d.selectedMessage,d.$messages.splice(c,1),cb.uids.length-1)&&(c.$topIndex=0),c.init(b),c.uids&&(a.$log.debug("unwrapping "+b.uids.length+" messages"),f=_.invokeMap(c.headers[0],"toLowerCase"),c.headers.splice(0,1),c.threaded&&(e=c.uids[0],c.uids.splice(0,1)),_.reduce(c.uids,function(b,d,f){var g;return g=c.threaded?_.zipObject(e,d):{uid:d.toString()},c.uidsMap[g.uid]=f,b.push(new a.$Message(c.$account.id,c,g,!0)),b},c.$messages),_.forEach(c.headers,function(a){var b=_.zipObject(f,a),d=c.uidsMap[b.uid.toString()];_.extend(c.$messages[d],b)})),a.$log.debug("mailbox "+c.id+" ready"),c.$isLoading=!1,d.resolve(c.$messages)})},function(a){angular.extend(c,a),c.isError=!0,d.reject()}),d.promise},a.prototype.$unwrapHeaders=function(b){var c=this;b.then(function(b){a.$timeout(function(){var a,d;b.length>0&&(a=_.invokeMap(b[0],"toLowerCase"),b.splice(0,1),_.forEach(b,function(b){b=_.zipObject(a,b),d=c.uidsMap[b.uid.toString()],angular.isDefined(d)&&_.extend(c.$messages[d],b)}))})})},a.prototype.$updateSubscribe=function(){var b=this.subscribed?"subscribe":"unsubscribe";a.$$resource.post(this.id,b)}}(),function(){"use strict";function a(a,b,c,d){this.accountId=a,this.$mailbox=b,this.$hasUnsafeContent=!1,this.$loadUnsafeContent=!1,this.editable={to:[],cc:[],bcc:[]},this.selected=!1,"function"!=typeof c.then?(!angular.isUndefined(d)&&d||(angular.extend(this,c),this.$formatFullAddresses()),this.uid=parseInt(c.uid)):this.$unwrap(c)}a.$factory=["$q","$timeout","$log","sgSettings","sgMessage_STATUS","Resource","Preferences",function(b,c,d,e,f,g,h){return angular.extend(a,{STATUS:f,$q:b,$timeout:c,$log:d,$$resource:new g(e.activeUser("folderURL")+"Mail",e.activeUser()),$avatar:angular.bind(h,h.avatar)}),h.ready().then(function(){h.defaults.SOGoMailLabelsColors&&(a.$tags=h.defaults.SOGoMailLabelsColors),h.defaults.SOGoMailDisplayRemoteInlineImages&&"always"==h.defaults.SOGoMailDisplayRemoteInlineImages&&(a.$displayRemoteInlineImages=!0)}),a}];try{angular.module("SOGo.MailerUI")}catch(a){angular.module("SOGo.MailerUI",["SOGo.Common"])}angular.module("SOGo.MailerUI").constant("sgMessage_STATUS",{NOT_LOADED:0,DELAYED_LOADING:1,LOADING:2,LOADED:3,DELAYED_MS:300}).factory("Message",a.$factory),a.filterTags=function(b,c){var d=new RegExp(b,"i"),e=[];return _.forEach(_.keys(a.$tags),function(b){var f=a.$tags[b];f[0].search(d)!=-1&&(_.includes(c,b)||e.push({name:b,description:f[0],color:f[1]}))}),e},a.prototype.$absolutePath=function(a){function b(){var a;return a=_.map(c.$mailbox.path.split("/"),function(a){return"folder"+a.asCSSIdentifier()}),a.splice(0,0,c.accountId),a.join("/")}var c=this,d=this.id;return(angular.isUndefined(this.id)||a&&a.nocache)&&(this.id=b()+"/"+this.uid,d=this.id),a&&a.asDraft&&this.draftId&&(d=b()+"/"+this.draftId),d},a.prototype.$setUID=function(a){var b,c=this.uid||-1,d=this;c!=parseInt(a)&&(this.uid=parseInt(a),this.$absolutePath({nocache:!0}),c>-1?(c=c.toString(),angular.isDefined(this.$mailbox.uidsMap[c])&&(b=this.$mailbox.uidsMap[c],this.$mailbox.uidsMap[a]=b,delete this.$mailbox.uidsMap[c],_.forEach(["from","to","subject"],function(a){d.$mailbox.$messages[b][a]=d[a]}))):this.$mailbox.constructor.selectedFolder&&"draft"==this.$mailbox.constructor.selectedFolder.type&&this.$mailbox.constructor.selectedFolder.$filter())},a.prototype.$formatFullAddresses=function(){var b=this,c=_.map(b.$mailbox.$account.identities,"email");_.forEach(["from","to","cc","bcc","reply-to"],function(d){_.forEach(b[d],function(b){b.name&&b.name!=b.email?(b.full=b.name+" <"+b.email+">",b.name.length<10?b.shortname=b.name:b.name.split(" ").length&&(b.shortname=_.first(_.last(b.name.split(/, */)).split(/ +/)).replace("'",""))):b.email&&(b.full="<"+b.email+">",b.shortname=b.email.split("@")[0]),b.image=a.$avatar(b.email,32),_.indexOf(c,b.email)>=0&&(b.shortname=l("me"))})})},a.prototype.$shortRecipients=function(a){var b=this,c=[],d=0,e=0;return _.forEach(["to","cc","bcc"],function(f){e+=b[f]?b[f].length:0,_.forEach(b[f],function(b,e){da&&c.push(l("and %{0} more...",e-a)),c.join(", ")},a.prototype.$shortAddress=function(a){var b="";return this[a]&&this[a].length>0&&(b=this[a][0].name||this[a][0].email||""),b},a.prototype.allowReplyAll=function(){var a=0;return a=_.reduce(["to","cc"],_.bind(function(a,b){return this[b]?a+this[b].length:a},this),a),!this.isDraft&&a>1},a.prototype.loadUnsafeContent=function(){this.$loadUnsafeContent=!0},a.prototype.$content=function(){var b=this,c=[],d=function(e){if(e.msgclass="msg-attachment-other","UIxMailPartAlternativeViewer"==e.type)d(_.find(e.content,function(a){return e.preferredPart==a.contentType}));else if(angular.isArray(e.content)){if("UIxMailPartSignedViewer"==e.type&&1===e["supports-smime"]){var f="

"+e.error.replace(/\n/,'

');f=f.replace(/\n/g,'

')+"

",b.$smime={validSignature:e.valid,message:f}}_.forEach(e.content,function(a){d(a)})}else angular.isUndefined(e.safeContent)&&(e.safeContent=e.content,b.$hasUnsafeContent|=e.safeContent.indexOf(" unsafe-")>-1),"UIxMailPartHTMLViewer"==e.type?(e.html=!0,b.$loadUnsafeContent||a.$displayRemoteInlineImages?(angular.isUndefined(e.unsafeContent)&&(e.unsafeContent=document.createElement("div"),e.unsafeContent.innerHTML=e.safeContent,angular.forEach(["src","data","classid","background","style"],function(a){var b,c,d,f=e.unsafeContent.querySelectorAll("[unsafe-"+a+"]");for(d=0;d=0)for(b=0,c=0;c0){var d=_.map(b,"uid");f.push(b);var h=a.$$resource.post(c,"addOrRemoveLabel",_.assign(e,{msgUIDs:d}));g.push(h)}}),a.$q.all(g).then(function(){return _.flatten(f)})},a.prototype.$deleteMessages=function(b){var c=[];return _.forEach(b,function(a,b){if(a.length>0){var d=a[0].$mailbox,e=d.$deleteMessages(a);c.push(e)}}),a.$q.all(c)},a.prototype.$markOrUnMarkMessagesAsJunk=function(b){var c=[];return _.forEach(b,function(a,b){if(a.length>0){var d=a[0].$mailbox,e=d.$markOrUnMarkMessagesAsJunk(a);c.push(e)}}),a.$q.all(c)},a.prototype.$copyMessages=function(b,c){var d=[];return _.forEach(b,function(a,b){if(a.length>0){var e=a[0].$mailbox,f=e.$copyMessages(a,c);d.push(f)}}),a.$q.all(d)},a.prototype.$moveMessages=function(b,c){var d=[];return _.forEach(b,function(a,b){if(a.length>0){var e=a[0].$mailbox,f=e.$moveMessages(a,c);d.push(f)}}),a.$q.all(d)}}(),function(){"use strict";function a(a,b,c,d,e,f,g,h,i,j,k,m,n,o,p,q,r){function s(a){a.push(k.createHotkey({key:l("hotkey_search"),description:l("Search"),callback:w})),a.push(k.createHotkey({key:l("hotkey_compose"),description:l("Write a new message"),callback:function(a){null===R.messageDialog&&y(a)}})),a.push(k.createHotkey({key:l("hotkey_junk"),description:l("Mark the selected messages as junk"),callback:J})),a.push(k.createHotkey({key:"space",description:l("Toggle item"),callback:F})),a.push(k.createHotkey({key:"shift+space",description:l("Toggle range of items"),callback:F})),a.push(k.createHotkey({key:"up",description:l("View next item"),callback:A,preventInClass:["sg-mail-part"]})),a.push(k.createHotkey({key:"down",description:l("View previous item"),callback:B,preventInClass:["sg-mail-part"]})),a.push(k.createHotkey({key:"shift+up",description:l("Add next item to selection"),callback:C,preventInClass:["sg-mail-part"]})),a.push(k.createHotkey({key:"shift+down",description:l("Add previous item to selection"),callback:D,preventInClass:["sg-mail-part"]})),a.push(k.createHotkey({key:"backspace",description:l("Delete selected message or folder"),callback:I})),_.forEach(a,function(a){k.registerHotkey(a)})}function t(a){return R.selectedFolder.$compact()}function u(a){R.selectedFolder.$filter({sort:a})}function v(a){return r.$query.sort==a}function w(){R.mode.search=!0,o("search")}function x(){R.mode.search=!1,R.selectedFolder.$filter().then(function(){R.selectedFolder.selectedMessage&&c(function(){R.selectedFolder.$topIndex=R.selectedFolder.uidsMap[R.selectedFolder.selectedMessage]})})}function y(a,b){var c;null===R.messageDialog&&(b?z():(c=R.account.$newMessage(),R.messageDialog=f.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!1,escapeToClose:!1,templateUrl:"UIxMailEditor",controller:"MessageEditorController",controllerAs:"editor",locals:{stateAccount:R.account,stateMessage:c}}).finally(function(){R.messageDialog=null})))}function z(){var b=[n.baseURL(),"UIxMailPopupView#!/Mail",R.account.id,m(m(R.selectedFolder.path)),"new"].join("/"),c=R.selectedFolder.$id()+"/"+Math.random(0,1e3);console.debug(b),a.open(b,c,["width=680","height=520","resizable=1","scrollbars=1","toolbar=0","location=0","directories=0","status=0","menubar=0","copyhistory=0"].join(","))}function A(a){var b=R.selectedFolder.$selectedMessageIndex();return angular.isDefined(b)?(b--,R.selectedFolder.$topIndex>0&&R.selectedFolder.$topIndex--):(b=R.selectedFolder.getLength()-1,R.selectedFolder.$topIndex=R.selectedFolder.getLength()),b>-1&&E(R.selectedFolder.$messages[b]),a.preventDefault(),b}function B(a){var b=R.selectedFolder.$selectedMessageIndex();return angular.isDefined(b)?(b++,R.selectedFolder.$topIndex=0&&F(a,R.selectedFolder.$messages[b]))}function D(a){var b;R.selectedFolder.hasSelectedMessage()&&(b=B(a),b>=0&&F(a,R.selectedFolder.$messages[b]))}function E(a){r.$virtualMode?e.go("mail.account.virtualMailbox.message",{mailboxId:m(a.$mailbox.path),messageId:a.uid}):e.go("mail.account.mailbox.message",{messageId:a.uid})}function F(a,b){var c,d,e,f=R.selectedFolder;if(b||(b=f.$selectedMessage()),b.selected=!b.selected,R.mode.multiple+=b.selected?1:-1,a.shiftKey&&f.$selectedCount()>1){for(c=f.uidsMap[b.uid],d=c-2;d>=0&&!f.$messages[d].selected;)d--;if(d<0)for(d=c+2;d=0&&d0&&(g-=1,d=R.selectedFolder.$messages[g]),b0&&(R.messageDialog=p.confirm(l("Confirmation"),l("Are you sure you want to delete the selected messages?"),{ok:l("Delete")}).then(function(){var a=R.selectedFolder.hasSelectedMessage();R.selectedFolder.$deleteMessages(b).then(function(b){r.$virtualMode?a&&e.go("mail.account.virtualMailbox"):H(a,b)},function(c){R.messageDialog=p.confirm(l("Warning"),l("The messages could not be moved to the trash folder. Would you like to delete them immediately?"),{ok:l("Delete")}).then(function(){R.selectedFolder.$deleteMessages(b,{withoutTrash:!0}).then(function(b){ -r.$virtualMode?a&&e.go("mail.account.virtualMailbox"):H(a,b)})})})}).finally(function(){R.messageDialog=null})),a.preventDefault()}function J(){var a=R.selectedFolder.hasSelectedMessage(),b=R.selectedFolder.$selectedMessages();0===_.size(b)&&a&&(b=[R.selectedFolder.$selectedMessage()]),_.size(b)>0&&R.selectedFolder.$markOrUnMarkMessagesAsJunk(b).then(function(){var c="/"+R.account.id+"/folderINBOX";"junk"!=R.selectedFolder.type&&(c="/"+R.account.$getMailboxByType("junk").id),R.selectedFolder.$moveMessages(b,c).then(function(b){r.$virtualMode?a&&e.go("mail.account.virtualMailbox"):H(a,b)})})}function K(a){var b=R.selectedFolder.$selectedMessages();_.size(b)>0&&R.selectedFolder.$copyMessages(b,"/"+a).then(function(){g.show(g.simple().content(l("%{0} message(s) copied",R.selectedFolder.$selectedCount())).position("top right").hideDelay(2e3))})}function L(a){var b=R.selectedFolder.hasSelectedMessage(),c=R.selectedFolder.$selectedMessages(),d=R.selectedFolder.$selectedCount();_.size(c)>0&&R.selectedFolder.$moveMessages(c,"/"+a).then(function(a){g.show(g.simple().content(l("%{0} message(s) moved",d)).position("top right").hideDelay(2e3)),r.$virtualMode?b&&e.go("mail.account.virtualMailbox"):H(b,a)})}function M(){var a=0;_.forEach(G(),function(b){for(var c=0,d=b.$messages.length;c0&&R.selectedFolder.$flagMessages(a,"\\Flagged","add").then(function(a){_.forEach(a,function(a){a.isflagged=!0})})}function P(){var a=R.selectedFolder.$selectedMessages();_.size(a)>0&&R.selectedFolder.$flagMessages(a,"seen","remove").then(function(a){_.forEach(a,function(a){a.isread&&a.$mailbox.unseenCount++,a.isread=!1})})}function Q(){var a=R.selectedFolder.$selectedMessages();_.size(a)>0&&R.selectedFolder.$flagMessages(a,"seen","add").then(function(a){_.forEach(a,function(a){a.isread||a.$mailbox.unseenCount--,a.isread=!0})})}var R=this,S=angular.element(a.document).find("title").attr("sg-default")||"SOGo",T=[];a.$mailboxController=R,R.service=r,R.accounts=h,R.account=i,R.selectedFolder=j,R.selectMessage=E,R.messageDialog=null,R.toggleMessageSelection=F,R.sort=u,R.sortedBy=v,R.searchMode=w,R.cancelSearch=x,R.newMessage=y,R.mode={search:!1,multiple:0},R.confirmDeleteSelectedMessages=I,R.markOrUnMarkMessagesAsJunk=J,R.copySelectedMessages=K,R.moveSelectedMessages=L,R.markSelectedMessagesAsFlagged=O,R.markSelectedMessagesAsUnread=P,R.markSelectedMessagesAsRead=Q,R.selectAll=M,R.unselectMessages=N,j.selectFolder(),s(T),angular.element(a).on("beforeunload",t),b.$on("$destroy",function(){angular.element(a).off("beforeunload",t),_.forEach(T,function(a){k.deregisterHotkey(a)})}),b.$watch(function(){return R.selectedFolder.unseenCount},function(b){var c=S+" - ";b&&(c+="("+b+") "),c+=R.selectedFolder.name,a.document.title=c})}function b(a){return a[0].controller.prototype.resetScroll=function(){"messagesList"==this.$element.parent().attr("id")?this.updateSize():this.scrollTo(0)},a}a.$inject=["$window","$scope","$timeout","$q","$state","$mdDialog","$mdToast","stateAccounts","stateAccount","stateMailbox","sgHotkeys","encodeUriFilter","sgSettings","sgFocus","Dialog","Account","Mailbox"],angular.module("material.components.virtualRepeat").decorator("mdVirtualRepeatContainerDirective",b),b.$inject=["$delegate"],angular.module("SOGo.MailerUI").controller("MailboxController",a)}(),function(){"use strict";function a(a,b,c,d,e,f,g,h,i,j,k,m,n,o,p,q,r,s,t,u){function v(a){a.push(o.createHotkey({key:"backspace",description:l("Delete selected message or folder"),callback:function(){q.selectedFolder&&!q.selectedFolder.hasSelectedMessage()&&L(q.selectedFolder)}})),_.forEach(a,function(a){o.registerHotkey(a)})}function w(a){V.showingAdvancedSearch=!0,V.search.mailbox=a,g(i["gt-md"])||h("left").close()}function x(){V.showingAdvancedSearch=!1,V.service.$virtualMode=!1,T=V.accounts[0],U=V.searchPreviousMailbox,b.go("mail.account.mailbox",{accountId:T.id,mailboxId:k(U.path)})}function y(){if(q.selectedFolder.$isLoading)V.virtualMailbox.stopSearch();else{var a,c=[],d=function(a){_.forEach(a,function(a){c.push(a),a.children&&a.children.length>0&&d(a.children)})};V.virtualMailbox=new r(V.accounts[0]),q.$virtualMode||(V.searchPreviousMailbox=q.selectedFolder),q.selectedFolder=V.virtualMailbox,q.$virtualMode=!0,angular.isDefined(V.search.mailbox)?(a=V.accounts[0].$getMailboxByPath(V.search.mailbox),c.push(a),V.search.subfolders&&a.children.length&&d(a.children)):c=V.accounts[0].$flattenMailboxes(),V.virtualMailbox.setMailboxes(c),V.virtualMailbox.startSearch(V.search.match,V.search.params),b.go("mail.account.virtualMailbox",{accountId:V.accounts[0].id})}}function z(a){return V.currentSearchParam=a,j("advancedSearch"),!1}function A(a){if(a.length&&V.currentSearchParam.length){var b=0,c=V.currentSearchParam;return a.startsWith("!")&&(b=1,a=a.substring(1).trim()),V.currentSearchParam="",{searchBy:c,searchInput:a,negative:b}}}function B(a){a.$expanded=!a.$expanded,a.$flattenMailboxes({reload:!0,saveState:!0}),c(function(){angular.element(d).triggerHandler("resize")},150)}function C(a){function b(a,b,c,d){function e(){b.cancel()}var f=this;f.loading=!0,f.filter={name:""},f.metadataForFolder=c,f.account=new p({id:d.id,name:d.name}),f.close=e,f.account.$getMailboxes({reload:!0,all:!0}).then(function(){f.loading=!1})}e.show({templateUrl:a.id+"/subscribe",controller:b,controllerAs:"subscriptions",clickOutsideToClose:!0,escapeToClose:!0,locals:{metadataForFolder:O,srcAccount:a}}).finally(function(){a.$getMailboxes({reload:!0})}),b.$inject=["$scope","$mdDialog","metadataForFolder","srcAccount"]}function D(a){m.prompt(l("New Folder..."),l("Enter the new name of your folder")).then(function(b){a.$newMailbox(a.id,b).then(function(){},function(a,c){m.alert(l('An error occured while creating the mailbox "%{0}".',b),l(a.error))})})}function E(a){function b(a,b,c,d){function e(a){return c.$filter(a,d.delegates)}function f(){b.hide()}function g(a){d.$removeDelegate(a.uid).catch(function(a,b){m.alert(l("Warning"),l("An error occured please try again."))})}function h(a){a&&d.$addDelegate(a).then(function(){i.userToAdd="",i.searchText=""},function(a){m.alert(l("Warning"),a)})}var i=this;i.users=d.delegates,i.account=d,i.userToAdd="",i.searchText="",i.userFilter=e,i.closeModal=f,i.removeUser=g,i.addUser=h}e.show({templateUrl:a.id+"/delegation",controller:b,controllerAs:"delegate",clickOutsideToClose:!0,escapeToClose:!0,locals:{User:s,account:a}}),b.$inject=["$scope","$mdDialog","User","account"]}function F(a){V.editMode=a.path,j("mailboxName_"+a.path)}function G(a){a.$reset(),V.editMode=!1}function H(a,c,d){V.editMode!=d.path&&(V.editMode=!1,V.showingAdvancedSearch=!1,V.service.$virtualMode=!1,g(i["gt-md"])||h("left").close(),b.go("mail.account.mailbox",{accountId:c.id,mailboxId:k(d.path)}),a.stopPropagation(),a.preventDefault())}function I(a){a.$rename().then(function(a){V.editMode=!1})}function J(a){a.$compact().then(function(){f.show(f.simple().content(l("Folder compacted")).position("top right").hideDelay(3e3))})}function K(a){a.$emptyTrash().then(function(){f.show(f.simple().content(l("Trash emptied")).position("top right").hideDelay(3e3))})}function L(a){m.confirm(l("Warning"),l("Do you really want to move this folder into the trash ?"),{ok:l("Delete")}).then(function(){a.$delete().then(function(){b.go("mail.account.inbox")},function(c){m.confirm(l("Warning"),l("The mailbox could not be moved to the trash folder. Would you like to delete it immediately?"),{ok:l("Delete")}).then(function(){a.$delete({withoutTrash:!0}).then(function(){b.go("mail.account.inbox")},function(b){m.alert(l('An error occured while deleting the mailbox "%{0}".',a.name),l(b.error))})})})})}function M(a){a.$markAsRead()}function N(a){a.$acl.$users().then(function(){e.show({templateUrl:a.id+"/UIxAclEditor",controller:"AclController",controllerAs:"acl",clickOutsideToClose:!0,escapeToClose:!0,locals:{usersWithACL:a.$acl.users,User:s,folder:a}})})}function O(a){return"inbox"==a.type?{name:a.name,icon:"inbox",special:!0}:"draft"==a.type?{name:l("DraftsFolderName"),icon:"drafts",special:!0}:"sent"==a.type?{name:l("SentFolderName"),icon:"send",special:!0}:"trash"==a.type?{name:l("TrashFolderName"),icon:"delete",special:!0}:"junk"==a.type?{name:l("JunkFolderName"),icon:"thumb_down",special:!0}:"additional"==a.type?{name:a.name,icon:"folder_shared",special:!0}:{name:a.name,icon:"folder_open",special:!1}}function P(a,b){a.$setFolderAs(b).then(function(){a.$account.$getMailboxes({reload:!0})})}function Q(){var a=d.unseenCountFolders;_.forEach(V.accounts,function(b){_.includes(a,b.id+"/folderINBOX")||a.push(b.id+"/folderINBOX"),_.forEach(b.$$flattenMailboxes,function(b){angular.isDefined(b.unseenCount)&&!_.includes(a,b.id)&&a.push(b.id)})}),p.$$resource.post("","unseenCount",{mailboxes:a}).then(function(a){_.forEach(V.accounts,function(b){_.forEach(b.$$flattenMailboxes,function(b){a[b.id]&&(b.unseenCount=a[b.id])})})}),t.ready().then(function(){var a=t.defaults.SOGoRefreshViewCheck;a&&"manually"!=a&&c(V.refreshUnseenCount,1e3*a.timeInterval())})}function R(a,b){return b.id!=a.id&&!b.isNoSelect()}function S(a,c,d){var e,g,h,i,j,k;e="/"+c.id,g=a.$selectedMessages(),0===g.length&&(g=[a.$selectedMessage()]),h=_.map(g,"uid"),i=a.selectedMessage&&h.indexOf(a.selectedMessage)>=0,"copy"==d?(j=a.$copyMessages(g,e),k=l("%{0} message(s) copied",g.length)):(j=a.$moveMessages(g,e),k=l("%{0} message(s) moved",g.length)),j.then(function(){i&&b.go("mail.account.mailbox"),f.show(f.simple().content(k).position("top right").hideDelay(2e3))})}var T,U,V=this,W=[];V.service=q,V.accounts=u,V.toggleAccountState=B,V.subscribe=C,V.newFolder=D,V.delegate=E,V.editFolder=F,V.revertEditing=G,V.selectFolder=H,V.saveFolder=I,V.compactFolder=J,V.emptyTrashFolder=K,V.confirmDelete=L,V.markFolderRead=M,V.share=N,V.metadataForFolder=O,V.setFolderAs=P,V.refreshUnseenCount=Q,V.isDroppableFolder=R,V.dragSelectedMessages=S,V.showingAdvancedSearch=!1,V.currentSearchParam="",V.addSearchParam=z,V.newSearchParam=A,V.showAdvancedSearch=w,V.hideAdvancedSearch=x,V.toggleAdvancedSearch=y,V.search={options:{"":"",subject:l("Enter Subject"),from:l("Enter From"),to:l("Enter To"),cc:l("Enter Cc"),body:l("Enter Body")},mailbox:"INBOX",subfolders:1,match:"AND",params:[]},t.ready().then(function(){V.showSubscribedOnly=t.defaults.SOGoMailShowSubscribedFoldersOnly}),V.refreshUnseenCount(),v(W),a.$on("$destroy",function(){_.forEach(W,function(a){o.deregisterHotkey(a)})})}a.$inject=["$scope","$state","$timeout","$window","$mdDialog","$mdToast","$mdMedia","$mdSidenav","sgConstant","sgFocus","encodeUriFilter","Dialog","sgSettings","sgHotkeys","Account","Mailbox","VirtualMailbox","User","Preferences","stateAccounts"],angular.module("SOGo.MailerUI").controller("MailboxesController",a)}(),function(){"use strict";function a(a,b,c,d,e,f,g,h,i,j,k,m,n,o,p,q,r,s,t,u){function v(){return b.mailbox?(arguments.length>0&&(b.mailbox.messageDialog=arguments[0]),b.mailbox.messageDialog):null}function w(a){return function(){if(null===v())return a.apply(Q,arguments)}}function x(a){a.push(k.createHotkey({key:l("hotkey_reply"),description:l("Reply to the message"),callback:w(E)})),a.push(k.createHotkey({key:l("hotkey_replyall"),description:l("Reply to sender and all recipients"),callback:w(F)})),a.push(k.createHotkey({key:l("hotkey_forward"),description:l("Forward selected message"),callback:w(G)})),a.push(k.createHotkey({key:l("hotkey_flag"),description:l("Flagged"),callback:w(angular.bind(j,j.toggleFlag))})),a.push(k.createHotkey({key:"backspace",callback:w(function(a){0===Q.mailbox.$selectedCount()&&B(),a.preventDefault()})})),_.forEach(a,function(a){k.registerHotkey(a)})}function y(){var b,c,d={};return a.opener&&a.opener.$mailboxController&&a.opener.$mailboxController.selectedFolder.$id()==i.$id()&&(c=a.opener.$mailboxController,d.mailboxCtrl=c,a.opener.$messageController&&a.opener.$messageController.message.uid==j.uid&&(b=a.opener.$messageController,d.messageCtrl=b)),d}function z(a){Q.$showDetailedRecipients=!Q.$showDetailedRecipients,a.stopPropagation(),a.preventDefault()}function A(a){var b,c,d,e;"A"==a.target.tagName&&"href"in a.target.attributes&&(b=a.target.attributes.href.value,c=/^mailto:([^\?]+)/.exec(b),c&&(d=_.map(decodeURIComponent(c[1]).split(","),function(a){return"<"+a+">"}),e={to:d},_.forEach(["subject","body"],function(a){var d=new RegExp(a+"=([^&]+)");a="body"==a?"text":a,c=d.exec(b),c&&(e[a]=[decodeURIComponent(c[1])])}),_.forEach(["cc","bcc"],function(a){var d=new RegExp(a+"=([^&]+)");c=d.exec(b),c&&(e[a]=[decodeURIComponent(c[1])])}),K(a,e)))}function B(){var a,b,e,g,h,k=y();k.messageCtrl?(a=k.mailboxCtrl.selectedFolder,b=k.messageCtrl.message,e=k.messageCtrl.$state):(a=i,b=j,e=c),a.$deleteMessages([b]).then(function(c){var i=c;if(b=null,angular.isDefined(e)){c>0&&(i-=1,g=a.$messages[i]),ca.$lastVisibleIndex&&(a.$topIndex=i-(a.$lastVisibleIndex-a.$topIndex))):e.go("mail.account.mailbox").then(function(){b=null,delete a.selectedMessage})}catch(a){}}J()})}function C(a,b){null===v()&&v(e.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!1,escapeToClose:!1,templateUrl:"UIxMailEditor",controller:"MessageEditorController",controllerAs:"editor",locals:{stateAccount:Q.account,stateMessage:b}}).finally(function(){v(null),J()}))}function D(){c.go("mail.account.mailbox").then(function(){Q.message=null,delete i.selectedMessage})}function E(a){var b=Q.message.$reply();C(a,b)}function F(a){var b=Q.message.$replyAll();C(a,b)}function G(a){var b=Q.message.$forward();C(a,b)}function H(a){Q.message.$editableContent().then(function(){C(a,Q.message)})}function I(){var b=[n.baseURL(),"UIxMailPopupView#!/Mail",Q.message.accountId,m(m(Q.message.$mailbox.path)),Q.message.uid].join("/"),c=Q.message.$absolutePath();R=a.open(b,c,["width=680","height=520","resizable=1","scrollbars=1","toolbar=0","location=0","directories=0","status=0","menubar=0","copyhistory=0"].join(","))}function J(){a.opener&&a.close()}function K(a,b){Q.account.$newMessage().then(function(c){angular.extend(c.editable,b),C(a,c)}),a.stopPropagation(),a.preventDefault()}function L(a){Q.showRawSource||Q.message.$rawSource?Q.showRawSource=!Q.showRawSource:u.$$resource.post(Q.message.id,"viewsource").then(function(a){Q.message.$rawSource=a,Q.showRawSource=!0})}function M(b){a.print()}function N(a){return P(a,"appointment")}function O(a){return P(a,"task")}function P(a,b){Q.message.$plainContent().then(function(c){var d={pid:q.$defaultCalendar(),type:b,summary:c.subject,comment:c.content},f=new r(d),g=[n.activeUser("folderURL"),"Calendar","UIx"+b.capitalize()+"EditorTemplate"].join("/");return e.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!0,escapeToClose:!0,templateUrl:g,controller:"ComponentEditorController",controllerAs:"editor",locals:{stateComponent:f}})})}var Q=this,R=null,S=[];a.$messageController=Q,Q.$state=c,Q.accounts=g,Q.account=h,Q.mailbox=i,Q.message=j,Q.service=u,Q.tags={searchText:"",selected:""},Q.showFlags=j.flags&&j.flags.length>0,Q.$showDetailedRecipients=!1,Q.toggleDetailedRecipients=z,Q.filterMailtoLinks=A,Q.deleteMessage=B,Q.close=D,Q.reply=E,Q.replyAll=F,Q.forward=G,Q.edit=H,Q.openPopup=I,Q.closePopup=J,Q.newMessage=K,Q.toggleRawSource=L,Q.showRawSource=!1,Q.print=M,Q.convertToEvent=N,Q.convertToTask=O,x(S),a.opener?(b.$watchCollection(function(){return Q.message.flags},function(a,b){var c;(a||b)&&(c=y(),c.messageCtrl&&c.messageCtrl.service.$timeout(function(){c.messageCtrl.showFlags=!0,c.messageCtrl.message.flags=a}))}),b.$watch(function(){return Q.message.isflagged},function(a,b){var c=y();c.mailboxCtrl&&c.mailboxCtrl.service.$timeout(function(){var b=_.find(c.mailboxCtrl.selectedFolder.$messages,{uid:Q.message.uid});b.isflagged=a})})):b.$watchCollection(function(){return Q.message.flags},function(a,b){var c,d,e;(a||b)&&(c=a||[],d=b||[],_.forEach(c,function(a,b){angular.isObject(a)&&(c[b]=a.name)}),c.length>d.length?(e=_.difference(c,d),_.forEach(e,function(a){Q.message.addTag(a)})):c.length0&&R.selectedFolder.$markOrUnMarkMessagesAsJunk(b).then(function(){var c="/"+R.account.id+"/folderINBOX";"junk"!=R.selectedFolder.type&&(c="/"+R.account.$getMailboxByType("junk").id),R.selectedFolder.$moveMessages(b,c).then(function(b){r.$virtualMode?a&&e.go("mail.account.virtualMailbox"):H(a,b)})})}function K(a){var b=R.selectedFolder.$selectedMessages();_.size(b)>0&&R.selectedFolder.$copyMessages(b,"/"+a).then(function(){g.show(g.simple().content(l("%{0} message(s) copied",R.selectedFolder.$selectedCount())).position("top right").hideDelay(2e3))})}function L(a){var b=R.selectedFolder.hasSelectedMessage(),c=R.selectedFolder.$selectedMessages(),d=R.selectedFolder.$selectedCount();_.size(c)>0&&R.selectedFolder.$moveMessages(c,"/"+a).then(function(a){g.show(g.simple().content(l("%{0} message(s) moved",d)).position("top right").hideDelay(2e3)),r.$virtualMode?b&&e.go("mail.account.virtualMailbox"):H(b,a)})}function M(){var a=0;_.forEach(G(),function(b){for(var c=0,d=b.$messages.length;c0&&R.selectedFolder.$flagMessages(a,"\\Flagged","add").then(function(a){_.forEach(a,function(a){a.isflagged=!0})})}function P(){var a=R.selectedFolder.$selectedMessages();_.size(a)>0&&R.selectedFolder.$flagMessages(a,"seen","remove").then(function(a){_.forEach(a,function(a){a.isread&&a.$mailbox.unseenCount++,a.isread=!1})})}function Q(){var a=R.selectedFolder.$selectedMessages();_.size(a)>0&&R.selectedFolder.$flagMessages(a,"seen","add").then(function(a){_.forEach(a,function(a){a.isread||a.$mailbox.unseenCount--,a.isread=!0})})}var R=this,S=angular.element(a.document).find("title").attr("sg-default")||"SOGo",T=[];a.$mailboxController=R,R.service=r,R.accounts=h,R.account=i,R.selectedFolder=j,R.selectMessage=E,R.messageDialog=null,R.toggleMessageSelection=F,R.sort=u,R.sortedBy=v,R.searchMode=w,R.cancelSearch=x,R.newMessage=y,R.mode={search:!1,multiple:0},R.confirmDeleteSelectedMessages=I,R.markOrUnMarkMessagesAsJunk=J,R.copySelectedMessages=K,R.moveSelectedMessages=L,R.markSelectedMessagesAsFlagged=O,R.markSelectedMessagesAsUnread=P,R.markSelectedMessagesAsRead=Q,R.selectAll=M,R.unselectMessages=N,j.selectFolder(),s(T),angular.element(a).on("beforeunload",t),b.$on("$destroy",function(){angular.element(a).off("beforeunload",t),_.forEach(T,function(a){k.deregisterHotkey(a)})}),b.$watch(function(){return R.selectedFolder.unseenCount},function(b){var c=S+" - ";b&&(c+="("+b+") "),c+=R.selectedFolder.name,a.document.title=c})}function b(a){return a[0].controller.prototype.resetScroll=function(){"messagesList"==this.$element.parent().attr("id")?this.updateSize():this.scrollTo(0)},a}a.$inject=["$window","$scope","$timeout","$q","$state","$mdDialog","$mdToast","stateAccounts","stateAccount","stateMailbox","sgHotkeys","encodeUriFilter","sgSettings","sgFocus","Dialog","Account","Mailbox"],angular.module("material.components.virtualRepeat").decorator("mdVirtualRepeatContainerDirective",b),b.$inject=["$delegate"],angular.module("SOGo.MailerUI").controller("MailboxController",a)}(),function(){"use strict";function a(a,b,c,d,e,f,g,h,i,j,k,m,n,o,p,q,r,s,t,u){function v(a){a.push(o.createHotkey({key:"backspace",description:l("Delete selected message or folder"),callback:function(){q.selectedFolder&&!q.selectedFolder.hasSelectedMessage()&&L(q.selectedFolder)}})),_.forEach(a,function(a){o.registerHotkey(a)})}function w(a){V.showingAdvancedSearch=!0,V.search.mailbox=a,g(i["gt-md"])||h("left").close()}function x(){V.showingAdvancedSearch=!1,V.service.$virtualMode=!1,T=V.accounts[0],U=V.searchPreviousMailbox,b.go("mail.account.mailbox",{accountId:T.id,mailboxId:k(U.path)})}function y(){if(q.selectedFolder.$isLoading)V.virtualMailbox.stopSearch();else{var a,c=[],d=function(a){_.forEach(a,function(a){c.push(a),a.children&&a.children.length>0&&d(a.children)})};V.virtualMailbox=new r(V.accounts[0]),q.$virtualMode||(V.searchPreviousMailbox=q.selectedFolder),q.selectedFolder=V.virtualMailbox,q.$virtualMode=!0,angular.isDefined(V.search.mailbox)?(a=V.accounts[0].$getMailboxByPath(V.search.mailbox),c.push(a),V.search.subfolders&&a.children.length&&d(a.children)):c=V.accounts[0].$flattenMailboxes(),V.virtualMailbox.setMailboxes(c),V.virtualMailbox.startSearch(V.search.match,V.search.params),b.go("mail.account.virtualMailbox",{accountId:V.accounts[0].id})}}function z(a){return V.currentSearchParam=a,j("advancedSearch"),!1}function A(a){if(a.length&&V.currentSearchParam.length){var b=0,c=V.currentSearchParam;return a.startsWith("!")&&(b=1,a=a.substring(1).trim()),V.currentSearchParam="",{searchBy:c,searchInput:a,negative:b}}}function B(a){a.$expanded=!a.$expanded,a.$flattenMailboxes({reload:!0,saveState:!0}),c(function(){angular.element(d).triggerHandler("resize")},150)}function C(a){function b(a,b,c,d){function e(){b.cancel()}var f=this;f.loading=!0,f.filter={name:""},f.metadataForFolder=c,f.account=new p({id:d.id,name:d.name}),f.close=e,f.account.$getMailboxes({reload:!0,all:!0}).then(function(){f.loading=!1})}e.show({templateUrl:a.id+"/subscribe",controller:b,controllerAs:"subscriptions",clickOutsideToClose:!0,escapeToClose:!0,locals:{metadataForFolder:O,srcAccount:a}}).finally(function(){a.$getMailboxes({reload:!0})}),b.$inject=["$scope","$mdDialog","metadataForFolder","srcAccount"]}function D(a){m.prompt(l("New Folder..."),l("Enter the new name of your folder")).then(function(b){a.$newMailbox(a.id,b).then(function(){},function(a,c){m.alert(l('An error occured while creating the mailbox "%{0}".',b),l(a.error))})})}function E(a){function b(a,b,c,d){function e(a){return c.$filter(a,d.delegates)}function f(){b.hide()}function g(a){d.$removeDelegate(a.uid).catch(function(a,b){m.alert(l("Warning"),l("An error occured please try again."))})}function h(a){a&&d.$addDelegate(a).then(function(){i.userToAdd="",i.searchText=""},function(a){m.alert(l("Warning"),a)})}var i=this;i.users=d.delegates,i.account=d,i.userToAdd="",i.searchText="",i.userFilter=e,i.closeModal=f,i.removeUser=g,i.addUser=h}e.show({templateUrl:a.id+"/delegation",controller:b,controllerAs:"delegate",clickOutsideToClose:!0,escapeToClose:!0,locals:{User:s,account:a}}),b.$inject=["$scope","$mdDialog","User","account"]}function F(a){V.editMode=a.path,j("mailboxName_"+a.path)}function G(a){a.$reset(),V.editMode=!1}function H(a,c,d){V.editMode!=d.path&&(V.editMode=!1,V.showingAdvancedSearch=!1,V.service.$virtualMode=!1,g(i["gt-md"])||h("left").close(),b.go("mail.account.mailbox",{accountId:c.id,mailboxId:k(d.path)}),a.stopPropagation(),a.preventDefault())}function I(a){a.$rename().then(function(a){V.editMode=!1})}function J(a){a.$compact().then(function(){f.show(f.simple().content(l("Folder compacted")).position("top right").hideDelay(3e3))})}function K(a){a.$emptyTrash().then(function(){f.show(f.simple().content(l("Trash emptied")).position("top right").hideDelay(3e3))})}function L(a){m.confirm(l("Warning"),l("Do you really want to move this folder into the trash ?"),{ok:l("Delete")}).then(function(){a.$delete().then(function(){b.go("mail.account.inbox")},function(c){m.confirm(l("Warning"),l("The mailbox could not be moved to the trash folder. Would you like to delete it immediately?"),{ok:l("Delete")}).then(function(){a.$delete({withoutTrash:!0}).then(function(){b.go("mail.account.inbox")},function(b){m.alert(l('An error occured while deleting the mailbox "%{0}".',a.name),l(b.error))})})})})}function M(a){a.$markAsRead()}function N(a){a.$acl.$users().then(function(){e.show({templateUrl:a.id+"/UIxAclEditor",controller:"AclController",controllerAs:"acl",clickOutsideToClose:!0,escapeToClose:!0,locals:{usersWithACL:a.$acl.users,User:s,folder:a}})})}function O(a){return"inbox"==a.type?{name:l("InboxFolderName"),icon:"inbox",special:!0}:"draft"==a.type?{name:l("DraftsFolderName"),icon:"drafts",special:!0}:"sent"==a.type?{name:l("SentFolderName"),icon:"send",special:!0}:"trash"==a.type?{name:l("TrashFolderName"),icon:"delete",special:!0}:"junk"==a.type?{name:l("JunkFolderName"),icon:"thumb_down",special:!0}:"additional"==a.type?{name:a.name,icon:"folder_shared",special:!0}:{name:a.name,icon:"folder_open",special:!1}}function P(a,b){a.$setFolderAs(b).then(function(){a.$account.$getMailboxes({reload:!0})})}function Q(){var a=d.unseenCountFolders;_.forEach(V.accounts,function(b){_.includes(a,b.id+"/folderINBOX")||a.push(b.id+"/folderINBOX"),_.forEach(b.$$flattenMailboxes,function(b){angular.isDefined(b.unseenCount)&&!_.includes(a,b.id)&&a.push(b.id)})}),p.$$resource.post("","unseenCount",{mailboxes:a}).then(function(a){_.forEach(V.accounts,function(b){_.forEach(b.$$flattenMailboxes,function(b){a[b.id]&&(b.unseenCount=a[b.id])})})}),t.ready().then(function(){var a=t.defaults.SOGoRefreshViewCheck;a&&"manually"!=a&&c(V.refreshUnseenCount,1e3*a.timeInterval())})}function R(a,b){return b.id!=a.id&&!b.isNoSelect()}function S(a,c,d){var e,g,h,i,j,k;e="/"+c.id,g=a.$selectedMessages(),0===g.length&&(g=[a.$selectedMessage()]),h=_.map(g,"uid"),i=a.selectedMessage&&h.indexOf(a.selectedMessage)>=0,"copy"==d?(j=a.$copyMessages(g,e),k=l("%{0} message(s) copied",g.length)):(j=a.$moveMessages(g,e),k=l("%{0} message(s) moved",g.length)),j.then(function(){i&&b.go("mail.account.mailbox"),f.show(f.simple().content(k).position("top right").hideDelay(2e3))})}var T,U,V=this,W=[];V.service=q,V.accounts=u,V.toggleAccountState=B,V.subscribe=C,V.newFolder=D,V.delegate=E,V.editFolder=F,V.revertEditing=G,V.selectFolder=H,V.saveFolder=I,V.compactFolder=J,V.emptyTrashFolder=K,V.confirmDelete=L,V.markFolderRead=M,V.share=N,V.metadataForFolder=O,V.setFolderAs=P,V.refreshUnseenCount=Q,V.isDroppableFolder=R,V.dragSelectedMessages=S,V.showingAdvancedSearch=!1,V.currentSearchParam="",V.addSearchParam=z,V.newSearchParam=A,V.showAdvancedSearch=w,V.hideAdvancedSearch=x,V.toggleAdvancedSearch=y,V.search={options:{"":"",subject:l("Enter Subject"),from:l("Enter From"),to:l("Enter To"),cc:l("Enter Cc"),body:l("Enter Body")},mailbox:"INBOX",subfolders:1,match:"AND",params:[]},t.ready().then(function(){V.showSubscribedOnly=t.defaults.SOGoMailShowSubscribedFoldersOnly}),V.refreshUnseenCount(),v(W),a.$on("$destroy",function(){_.forEach(W,function(a){o.deregisterHotkey(a)})})}a.$inject=["$scope","$state","$timeout","$window","$mdDialog","$mdToast","$mdMedia","$mdSidenav","sgConstant","sgFocus","encodeUriFilter","Dialog","sgSettings","sgHotkeys","Account","Mailbox","VirtualMailbox","User","Preferences","stateAccounts"],angular.module("SOGo.MailerUI").controller("MailboxesController",a)}(),function(){"use strict";function a(a,b,c,d,e,f,g,h,i,j,k,m,n,o,p,q,r,s,t,u){function v(){return b.mailbox?(arguments.length>0&&(b.mailbox.messageDialog=arguments[0]),b.mailbox.messageDialog):null}function w(a){return function(){if(null===v())return a.apply(Q,arguments)}}function x(a){a.push(k.createHotkey({key:l("hotkey_reply"),description:l("Reply to the message"),callback:w(E)})),a.push(k.createHotkey({key:l("hotkey_replyall"),description:l("Reply to sender and all recipients"),callback:w(F)})),a.push(k.createHotkey({key:l("hotkey_forward"),description:l("Forward selected message"),callback:w(G)})),a.push(k.createHotkey({key:l("hotkey_flag"),description:l("Flagged"),callback:w(angular.bind(j,j.toggleFlag))})),a.push(k.createHotkey({key:"backspace",callback:w(function(a){0===Q.mailbox.$selectedCount()&&B(),a.preventDefault()})})),_.forEach(a,function(a){k.registerHotkey(a)})}function y(){var b,c,d={};return a.opener&&a.opener.$mailboxController&&a.opener.$mailboxController.selectedFolder.$id()==i.$id()&&(c=a.opener.$mailboxController,d.mailboxCtrl=c,a.opener.$messageController&&a.opener.$messageController.message.uid==j.uid&&(b=a.opener.$messageController,d.messageCtrl=b)),d}function z(a){Q.$showDetailedRecipients=!Q.$showDetailedRecipients,a.stopPropagation(),a.preventDefault()}function A(a){var b,c,d,e;"A"==a.target.tagName&&"href"in a.target.attributes&&(b=a.target.attributes.href.value,c=/^mailto:([^\?]+)/.exec(b),c&&(d=_.map(decodeURIComponent(c[1]).split(","),function(a){return"<"+a+">"}),e={to:d},_.forEach(["subject","body"],function(a){var d=new RegExp(a+"=([^&]+)");a="body"==a?"text":a,c=d.exec(b),c&&(e[a]=[decodeURIComponent(c[1])])}),_.forEach(["cc","bcc"],function(a){var d=new RegExp(a+"=([^&]+)");c=d.exec(b),c&&(e[a]=[decodeURIComponent(c[1])])}),K(a,e)))}function B(){var a,b,e,g,h,k=y();k.messageCtrl?(a=k.mailboxCtrl.selectedFolder,b=k.messageCtrl.message,e=k.messageCtrl.$state):(a=i,b=j,e=c),a.$deleteMessages([b]).then(function(c){var i=c;if(b=null,angular.isDefined(e)){c>0&&(i-=1,g=a.$messages[i]),ca.$lastVisibleIndex&&(a.$topIndex=i-(a.$lastVisibleIndex-a.$topIndex))):e.go("mail.account.mailbox").then(function(){b=null,delete a.selectedMessage})}catch(a){}}J()})}function C(a,b){null===v()&&v(e.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!1,escapeToClose:!1,templateUrl:"UIxMailEditor",controller:"MessageEditorController",controllerAs:"editor",locals:{stateAccount:Q.account,stateMessage:b}}).finally(function(){v(null),J()}))}function D(){c.go("mail.account.mailbox").then(function(){Q.message=null,delete i.selectedMessage})}function E(a){var b=Q.message.$reply();C(a,b)}function F(a){var b=Q.message.$replyAll();C(a,b)}function G(a){var b=Q.message.$forward();C(a,b)}function H(a){Q.message.$editableContent().then(function(){C(a,Q.message)})}function I(){var b=[n.baseURL(),"UIxMailPopupView#!/Mail",Q.message.accountId,m(m(Q.message.$mailbox.path)),Q.message.uid].join("/"),c=Q.message.$absolutePath();R=a.open(b,c,["width=680","height=520","resizable=1","scrollbars=1","toolbar=0","location=0","directories=0","status=0","menubar=0","copyhistory=0"].join(","))}function J(){a.opener&&a.close()}function K(a,b){Q.account.$newMessage().then(function(c){angular.extend(c.editable,b),C(a,c)}),a.stopPropagation(),a.preventDefault()}function L(a){Q.showRawSource||Q.message.$rawSource?Q.showRawSource=!Q.showRawSource:u.$$resource.post(Q.message.id,"viewsource").then(function(a){Q.message.$rawSource=a,Q.showRawSource=!0})}function M(b){a.print()}function N(a){return P(a,"appointment")}function O(a){return P(a,"task")}function P(a,b){Q.message.$plainContent().then(function(c){var d={pid:q.$defaultCalendar(),type:b,summary:c.subject,comment:c.content},f=new r(d),g=[n.activeUser("folderURL"),"Calendar","UIx"+b.capitalize()+"EditorTemplate"].join("/");return e.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!0,escapeToClose:!0,templateUrl:g,controller:"ComponentEditorController",controllerAs:"editor",locals:{stateComponent:f}})})}var Q=this,R=null,S=[];a.$messageController=Q,Q.$state=c,Q.accounts=g,Q.account=h,Q.mailbox=i,Q.message=j,Q.service=u,Q.tags={searchText:"",selected:""},Q.showFlags=j.flags&&j.flags.length>0,Q.$showDetailedRecipients=!1,Q.toggleDetailedRecipients=z,Q.filterMailtoLinks=A,Q.deleteMessage=B,Q.close=D,Q.reply=E,Q.replyAll=F,Q.forward=G,Q.edit=H,Q.openPopup=I,Q.closePopup=J,Q.newMessage=K,Q.toggleRawSource=L,Q.showRawSource=!1,Q.print=M,Q.convertToEvent=N,Q.convertToTask=O,x(S),a.opener?(b.$watchCollection(function(){return Q.message.flags},function(a,b){var c;(a||b)&&(c=y(),c.messageCtrl&&c.messageCtrl.service.$timeout(function(){c.messageCtrl.showFlags=!0,c.messageCtrl.message.flags=a}))}),b.$watch(function(){return Q.message.isflagged},function(a,b){var c=y();c.mailboxCtrl&&c.mailboxCtrl.service.$timeout(function(){var b=_.find(c.mailboxCtrl.selectedFolder.$messages,{uid:Q.message.uid});b.isflagged=a})})):b.$watchCollection(function(){return Q.message.flags},function(a,b){var c,d,e;(a||b)&&(c=a||[],d=b||[],_.forEach(c,function(a,b){angular.isObject(a)&&(c[b]=a.name)}),c.length>d.length?(e=_.difference(c,d),_.forEach(e,function(a){Q.message.addTag(a)})):c.length';\n else\n identity.full = '<' + identity.email + '>';\n });\n Account.$log.debug('Account: ' + JSON.stringify(futureAccountData, undefined, 2));\n }\n else {\n // The promise will be unwrapped first\n //this.$unwrap(futureAccountData);\n }\n }\n\n /**\n * @memberof Account\n * @desc The factory we'll use to register with Angular\n * @returns the Account constructor\n */\n Account.$factory = ['$q', '$timeout', '$log', 'sgSettings', 'Resource', 'Preferences', 'Mailbox', 'Message', function($q, $timeout, $log, Settings, Resource, Preferences, Mailbox, Message) {\n angular.extend(Account, {\n $q: $q,\n $timeout: $timeout,\n $log: $log,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Mail', Settings.activeUser()),\n $Preferences: Preferences,\n $Mailbox: Mailbox,\n $Message: Message\n });\n\n return Account; // return constructor\n }];\n\n /**\n * @module SOGo.MailerUI\n * @desc Factory registration of Account in Angular module.\n */\n try {\n angular.module('SOGo.MailerUI');\n }\n catch(e) {\n angular.module('SOGo.MailerUI', ['SOGo.Common']);\n }\n angular.module('SOGo.MailerUI')\n .factory('Account', Account.$factory);\n\n /**\n * @memberof Account\n * @desc Set the list of accounts and instanciate a new Account object for each item.\n * @param {array} [data] - the metadata of the accounts\n * @returns the list of accounts\n */\n Account.$findAll = function(data) {\n if (!data) {\n return Account.$$resource.fetch('', 'mailAccounts').then(function(o) {\n return Account.$unwrapCollection(o);\n });\n }\n return Account.$unwrapCollection(data);\n };\n\n /**\n * @memberof Account\n * @desc Unwrap to a collection of Account instances.\n * @param {object} data - the accounts information\n * @returns a collection of Account objects\n */\n Account.$unwrapCollection = function(data) {\n var collection = [];\n\n angular.forEach(data, function(o, i) {\n o.id = i;\n collection[i] = new Account(o);\n });\n Account.$accounts = collection;\n\n return collection;\n };\n\n /**\n * @function getLength\n * @memberof Account.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the number of mailboxes in the account\n */\n Account.prototype.getLength = function() {\n return this.$flattenMailboxes().length;\n };\n\n /**\n * @function getItemAtIndex\n * @memberof Account.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the mailbox at the specified index\n */\n Account.prototype.getItemAtIndex = function(index) {\n var expandedMailboxes;\n\n expandedMailboxes = this.$flattenMailboxes();\n if (index >= 0 && index < expandedMailboxes.length)\n return expandedMailboxes[index];\n\n return null;\n };\n\n /**\n * @function $getMailboxes\n * @memberof Account.prototype\n * @desc Fetch the list of mailboxes for the current account.\n * @param {object} [options] - force a reload by setting 'reload' to true\n * @returns a promise of the HTTP operation\n */\n Account.prototype.$getMailboxes = function(options) {\n var _this = this;\n\n if (this.$mailboxes && !(options && options.reload)) {\n return Account.$q.when(this.$mailboxes);\n }\n else {\n return Account.$Mailbox.$find(this, options).then(function(data) {\n _this.$mailboxes = data;\n _this.$expanded = false;\n\n // Set expanded folders from user's settings\n Account.$Preferences.ready().then(function() {\n var expandedFolders,\n _visit = function(mailboxes) {\n _.forEach(mailboxes, function(o) {\n o.$expanded = (expandedFolders.indexOf('/' + o.id) >= 0);\n if (o.children && o.children.length > 0) {\n _visit(o.children);\n }\n });\n };\n if (Account.$Preferences.settings.Mail.ExpandedFolders) {\n if (angular.isString(Account.$Preferences.settings.Mail.ExpandedFolders))\n // Backward compatibility support\n expandedFolders = angular.fromJson(Account.$Preferences.settings.Mail.ExpandedFolders);\n else\n expandedFolders = Account.$Preferences.settings.Mail.ExpandedFolders;\n _this.$expanded = (expandedFolders.indexOf('/' + _this.id) >= 0);\n if (expandedFolders.length > 0) {\n _visit(_this.$mailboxes);\n }\n }\n if (Account.$accounts)\n _this.$expanded |= (Account.$accounts.length == 1); // Always expand single account\n _this.$flattenMailboxes({reload: true});\n });\n\n return _this.$mailboxes;\n });\n }\n };\n\n /**\n * @function $flattenMailboxes\n * @memberof Account.prototype\n * @desc Get a flatten array of the mailboxes.\n * @param {object} [options] - the following boolean attributes are available:\n * - reload: rebuild the flatten array of mailboxes from the original tree representation (this.$mailboxes)\n * - all: return all mailboxes, ignoring their expanstion state\n * - saveState: save expansion state of mailboxes to the server\n * @returns an array of Mailbox instances\n */\n Account.prototype.$flattenMailboxes = function(options) {\n var _this = this,\n allMailboxes = [],\n expandedMailboxes = [],\n _visit = function(mailboxes) {\n _.forEach(mailboxes, function(o) {\n allMailboxes.push(o);\n if ((options && options.all || o.$expanded) && o.children && o.children.length > 0) {\n _visit(o.children);\n }\n });\n };\n\n if (this.$$flattenMailboxes && !(options && (options.reload || options.all))) {\n allMailboxes = this.$$flattenMailboxes;\n }\n else {\n _visit(this.$mailboxes);\n if (!options || !options.all) {\n _this.$$flattenMailboxes = allMailboxes;\n if (options && options.saveState) {\n // Save expansion state of mailboxes to the server\n _.forEach(Account.$accounts, function(account) {\n if (account.$expanded) {\n expandedMailboxes.push('/' + account.id);\n }\n _.reduce(account.$$flattenMailboxes, function(expandedFolders, mailbox) {\n if (mailbox.$expanded) {\n expandedFolders.push('/' + mailbox.id);\n }\n return expandedFolders;\n }, expandedMailboxes);\n });\n Account.$$resource.post(null, 'saveFoldersState', expandedMailboxes);\n }\n }\n }\n\n return allMailboxes;\n };\n\n Account.prototype.$getMailboxByType = function(type) {\n var mailbox,\n // Recursive find function\n _find = function(mailboxes) {\n var mailbox = _.find(mailboxes, function(o) {\n return o.type == type;\n });\n if (!mailbox) {\n angular.forEach(mailboxes, function(o) {\n if (!mailbox && o.children && o.children.length > 0) {\n mailbox = _find(o.children);\n }\n });\n }\n return mailbox;\n };\n mailbox = _find(this.$mailboxes);\n\n return mailbox;\n };\n\n /**\n * @function $getMailboxByPath\n * @memberof Account.prototype\n * @desc Recursively find a mailbox using its path\n * @returns a promise of the HTTP operation\n */\n Account.prototype.$getMailboxByPath = function(path) {\n var mailbox = null,\n // Recursive find function\n _find = function(mailboxes) {\n var mailbox = _.find(mailboxes, function(o) {\n return o.path == path;\n });\n if (!mailbox) {\n angular.forEach(mailboxes, function(o) {\n if (!mailbox && o.children && o.children.length > 0) {\n mailbox = _find(o.children);\n }\n });\n }\n return mailbox;\n };\n mailbox = _find(this.$mailboxes);\n\n return mailbox;\n };\n\n /**\n * @function $newMailbox\n * @memberof Account.prototype\n * @desc Create a new mailbox on the server and refresh the list of mailboxes.\n * @returns a promise of the HTTP operations\n */\n Account.prototype.$newMailbox = function(path, name) {\n var _this = this;\n\n return Account.$$resource.post(path.toString(), 'createFolder', {name: name}).then(function() {\n _this.$getMailboxes({reload: true});\n });\n };\n\n /**\n * @function updateQuota\n * @memberof Account.prototype\n * @param {Object} data - the inbox quota information returned by the server\n * @desc Update the quota definition associated to the account\n */\n Account.prototype.updateQuota = function(data) {\n var percent, format, description;\n\n percent = (Math.round(data.usedSpace * 10000 / data.maxQuota) / 100);\n format = l(\"quotasFormat\");\n description = format.formatted(percent, Math.round(data.maxQuota/10.24)/100);\n\n this.$quota = { percent: percent, description: description };\n };\n\n /**\n * @function $newMessage\n * @memberof Account.prototype\n * @desc Prepare a new Message object associated to the appropriate mailbox.\n * @returns a promise of the HTTP operations\n */\n Account.prototype.$newMessage = function() {\n var _this = this;\n\n // Query account for draft folder and draft UID\n return Account.$$resource.fetch(this.id.toString(), 'compose').then(function(data) {\n Account.$log.debug('New message (compose): ' + JSON.stringify(data, undefined, 2));\n var message = new Account.$Message(data.accountId, _this.$getMailboxByPath(data.mailboxPath), data);\n return message;\n }).then(function(message) {\n // Fetch draft initial data\n return Account.$$resource.fetch(message.$absolutePath({asDraft: true}), 'edit').then(function(data) {\n Account.$log.debug('New message (edit): ' + JSON.stringify(data, undefined, 2));\n angular.extend(message.editable, data);\n message.isNew = true;\n return message;\n });\n });\n };\n\n /**\n * @function $addDelegate\n * @memberof Account.prototype\n * @param {Object} user - a User object with minimal set of attributes (uid, isGroup, cn, c_email)\n * @desc Remove a user from the account's delegates\n * @see {@link User.$filter}\n */\n Account.prototype.$addDelegate = function(user) {\n var _this = this,\n deferred = Account.$q.defer(),\n param = {uid: user.uid};\n if (!user.uid || _.indexOf(_.map(this.delegates, 'uid'), user.uid) > -1) {\n // No UID specified or user already in delegates\n deferred.resolve();\n }\n else {\n Account.$$resource.fetch(this.id.toString(), 'addDelegate', param).then(function() {\n _this.delegates.push(user);\n deferred.resolve(_this.users);\n }, function(data, status) {\n deferred.reject(l('An error occured please try again.'));\n });\n }\n return deferred.promise;\n };\n\n /**\n * @function $removeDelegate\n * @memberof Account.prototype\n * @param {Object} user - a User object with minimal set of attributes (uid, isGroup, cn, c_email)\n * @desc Remove a user from the account's delegates\n * @return a promise of the server call to remove the user from the account's delegates\n */\n Account.prototype.$removeDelegate = function(uid) {\n var _this = this,\n param = {uid: uid};\n return Account.$$resource.fetch(this.id.toString(), 'removeDelegate', param).then(function() {\n var i = _.indexOf(_.map(_this.delegates, 'uid'), uid);\n if (i >= 0) {\n _this.delegates.splice(i, 1);\n }\n });\n };\n \n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @name Mailbox\n * @constructor\n * @param {object} futureMailboxData - either an object literal or a promise\n */\n function Mailbox(account, futureMailboxData) {\n this.$account = account;\n // Data is immediately available\n if (typeof futureMailboxData.then !== 'function') {\n this.init(futureMailboxData);\n if (this.name && !this.path) {\n // Create a new mailbox on the server\n var newMailboxData = Mailbox.$$resource.create('createFolder', this.name);\n this.$unwrap(newMailboxData);\n }\n }\n else {\n // The promise will be unwrapped first\n // NOTE: this condition never happen for the moment\n this.$unwrap(futureMailboxData);\n }\n }\n\n /**\n * @memberof Mailbox\n * @desc The factory we'll use to register with Angular\n * @returns the Mailbox constructor\n */\n Mailbox.$factory = ['$q', '$timeout', '$log', 'sgSettings', 'Resource', 'Message', 'Acl', 'Preferences', 'sgMailbox_PRELOAD', function($q, $timeout, $log, Settings, Resource, Message, Acl, Preferences, PRELOAD) {\n angular.extend(Mailbox, {\n $q: $q,\n $timeout: $timeout,\n $log: $log,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Mail', Settings.activeUser()),\n $Message: Message,\n $$Acl: Acl,\n $Preferences: Preferences,\n $query: { sort: 'arrival', asc: 0 }, // The default sort must match [UIxMailListActions defaultSortKey]\n selectedFolder: null,\n $refreshTimeout: null,\n $virtualMode: false,\n PRELOAD: PRELOAD\n });\n // Initialize sort parameters from user's settings\n Preferences.ready().then(function() {\n if (Preferences.settings.Mail.SortingState) {\n Mailbox.$query.sort = Preferences.settings.Mail.SortingState[0];\n Mailbox.$query.asc = parseInt(Preferences.settings.Mail.SortingState[1]);\n }\n });\n\n return Mailbox; // return constructor\n }];\n\n /**\n * @module SOGo.MailerUI\n * @desc Factory registration of Mailbox in Angular module.\n */\n try {\n angular.module('SOGo.MailerUI');\n }\n catch(e) {\n angular.module('SOGo.MailerUI', ['SOGo.Common']);\n }\n angular.module('SOGo.MailerUI')\n .constant('sgMailbox_PRELOAD', {\n LOOKAHEAD: 50,\n SIZE: 100\n })\n .factory('Mailbox', Mailbox.$factory);\n\n /**\n * @memberof Mailbox\n * @desc Fetch list of mailboxes of a specific account\n * @param {string} accountId - the account\n * @return a promise of the HTTP operation\n * @see {@link Account.$getMailboxes}\n */\n Mailbox.$find = function(account, options) {\n var path, futureMailboxData;\n\n if (options && options.all)\n futureMailboxData = this.$$resource.fetch(account.id.toString(), 'viewAll');\n else\n futureMailboxData = this.$$resource.fetch(account.id.toString(), 'view');\n\n return Mailbox.$unwrapCollection(account, futureMailboxData); // a collection of mailboxes\n };\n\n /**\n * @memberof Mailbox\n * @desc Unwrap to a collection of Mailbox instances.\n * @param {string} account - the account\n * @param {promise} futureMailboxData - a promise of the mailboxes metadata\n * @returns a promise of a collection of Mailbox objects\n */\n Mailbox.$unwrapCollection = function(account, futureMailboxData) {\n var collection = [],\n // Local recursive function\n createMailboxes = function(level, mailbox) {\n for (var i = 0; i < mailbox.children.length; i++) {\n mailbox.children[i].level = level;\n mailbox.children[i] = new Mailbox(account, mailbox.children[i]);\n createMailboxes(level+1, mailbox.children[i]);\n }\n };\n //collection.$futureMailboxData = futureMailboxData;\n\n return futureMailboxData.then(function(data) {\n return Mailbox.$timeout(function() {\n // Each entry is spun up as a Mailbox instance\n angular.forEach(data.mailboxes, function(data, index) {\n data.level = 0;\n var mailbox = new Mailbox(account, data);\n createMailboxes(1, mailbox); // recursively create all sub-mailboxes\n collection.push(mailbox);\n });\n // Update inbox quota\n if (data.quotas)\n account.updateQuota(data.quotas);\n return collection;\n });\n });\n };\n\n /**\n * @memberof Mailbox\n * @desc Build the path of the mailbox (or account only).\n * @param {string} accountId - the account ID\n * @param {string} [mailboxPath] - the mailbox path\n * @returns a string representing the path relative to the mail module\n */\n Mailbox.$absolutePath = function(accountId, mailboxPath) {\n var path = [];\n\n if (mailboxPath) {\n path = _.map(mailboxPath.split('/'), function(component) {\n return 'folder' + component.asCSSIdentifier();\n });\n }\n\n path.splice(0, 0, accountId); // insert account ID\n\n return path.join('/');\n };\n\n /**\n * @function init\n * @memberof Mailbox.prototype\n * @desc Extend instance with new data and compute additional attributes.\n * @param {object} data - attributes of mailbox\n */\n Mailbox.prototype.init = function(data) {\n var _this = this;\n this.$isLoading = true;\n this.$messages = [];\n this.uidsMap = {};\n angular.extend(this, data);\n if (this.path) {\n this.id = this.$id();\n this.$acl = new Mailbox.$$Acl('Mail/' + this.id);\n }\n if (this.type) {\n this.$isEditable = this.isEditable();\n }\n this.$isNoInferiors = this.isNoInferiors();\n if (angular.isUndefined(this.$shadowData)) {\n // Make a copy of the data for an eventual reset\n this.$shadowData = this.$omit();\n }\n };\n\n /**\n * @function selectFolder\n * @memberof Mailbox.prototype\n * @desc Mark the folder as selected in the constructor unless virtual mode is active\n */\n Mailbox.prototype.selectFolder = function() {\n if (!Mailbox.$virtualMode)\n Mailbox.selectedFolder = this;\n };\n\n /**\n * @function getLength\n * @memberof Mailbox.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the number of messages in the mailbox\n */\n Mailbox.prototype.getLength = function() {\n return this.$messages.length;\n };\n\n /**\n * @function getItemAtIndex\n * @memberof Mailbox.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the message at the specified index\n */\n Mailbox.prototype.getItemAtIndex = function(index) {\n var message;\n\n if (index >= 0 && index < this.$messages.length) {\n message = this.$messages[index];\n this.$lastVisibleIndex = Math.max(0, index - 3); // Magic number is NUM_EXTRA from virtual-repeater.js\n\n if (this.$loadMessage(message.uid))\n return message;\n }\n return null;\n };\n\n /**\n * @function $id\n * @memberof Mailbox.prototype\n * @desc Build the unique ID to identified the mailbox.\n * @returns a string representing the path relative to the mail module\n */\n Mailbox.prototype.$id = function() {\n return Mailbox.$absolutePath(this.$account.id, this.path);\n };\n\n /**\n * @function $selectedMessages\n * @memberof Mailbox.prototype\n * @desc Return the messages selected by the user.\n * @returns Message instances\n */\n Mailbox.prototype.$selectedMessages = function() {\n return _.filter(this.$messages, function(message) { return message.selected; });\n };\n\n /**\n * @function $selectedCount\n * @memberof Mailbox.prototype\n * @desc Return the number of messages selected by the user.\n * @returns the number of selected messages\n */\n Mailbox.prototype.$selectedCount = function() {\n return this.$selectedMessages().length;\n };\n\n /**\n * @function isSelectedMessage\n * @memberof Mailbox.prototype\n * @desc Check if the specified message is displayed in the detailed view.\n * @param {string} messageId\n * @returns true if the specified message is displayed\n */\n Mailbox.prototype.isSelectedMessage = function(messageId) {\n return this.selectedMessage == messageId;\n };\n\n /**\n * @function $selectedMessage\n * @memberof Mailbox.prototype\n * @desc Return the currently visible message.\n * @returns a Message instance or undefined if no message is displayed\n */\n Mailbox.prototype.$selectedMessage = function() {\n var _this = this;\n\n return _.find(this.$messages, function(message) { return message.uid == _this.selectedMessage; });\n };\n\n /**\n * @function $selectedMessageIndex\n * @memberof Mailbox.prototype\n * @desc Return the index of the currently visible message.\n * @returns a number or undefined if no message is selected\n */\n Mailbox.prototype.$selectedMessageIndex = function() {\n return this.uidsMap[this.selectedMessage];\n };\n\n /**\n * @function hasSelectedMessage\n * @memberof Mailbox.prototype\n * @desc Check if a message is selected.\n * @returns true if the a message is selected\n */\n Mailbox.prototype.hasSelectedMessage = function() {\n return angular.isDefined(this.selectedMessage);\n };\n\n /**\n * @function $filter\n * @memberof Mailbox.prototype\n * @desc Fetch the messages metadata of the mailbox\n * @param {object} [sort] - sort preferences. Defaults to descendent by date.\n * @param {string} sort.match - either AND or OR\n * @param {string} sort.sort - either arrival, subject, from, to, date, or size\n * @param {boolean} sort.asc - sort is ascendant if true\n * @param {object[]} [filters] - list of filters for the query\n * @param {string} filters.searchBy - either subject, from, to, cc, or body\n * @param {string} filters.searchInput - the search string to match\n * @param {boolean} filters.negative - negate the condition\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$filter = function(sortingAttributes, filters) {\n var _this = this, options = {};\n\n if (!angular.isDefined(this.unseenCount))\n this.unseenCount = 0;\n\n Mailbox.$timeout(function() {\n _this.$isLoading = true;\n });\n\n return Mailbox.$Preferences.ready().then(function() {\n\n if (Mailbox.$refreshTimeout)\n Mailbox.$timeout.cancel(Mailbox.$refreshTimeout);\n\n if (sortingAttributes)\n // Sorting preferences are common to all mailboxes\n angular.extend(Mailbox.$query, sortingAttributes);\n\n angular.extend(options, { sortingAttributes: Mailbox.$query });\n if (angular.isDefined(filters)) {\n options.filters = _.reject(filters, function(filter) {\n return !filter.searchInput || filter.searchInput.length === 0;\n });\n // Decompose filters that match two fields\n _.forEach(options.filters, function(filter) {\n var secondFilter,\n match = filter.searchBy.match(/(\\w+)_or_(\\w+)/);\n if (match) {\n options.sortingAttributes.match = 'OR';\n filter.searchBy = match[1];\n secondFilter = angular.copy(filter);\n secondFilter.searchBy = match[2];\n options.filters.push(secondFilter);\n }\n });\n }\n\n // Restart the refresh timer, if needed\n if (!Mailbox.$virtualMode) {\n var refreshViewCheck = Mailbox.$Preferences.defaults.SOGoRefreshViewCheck;\n if (refreshViewCheck && refreshViewCheck != 'manually') {\n var f = angular.bind(_this, Mailbox.prototype.$filter, null, filters);\n Mailbox.$refreshTimeout = Mailbox.$timeout(f, refreshViewCheck.timeInterval()*1000);\n }\n }\n\n var futureMailboxData = Mailbox.$$resource.post(_this.id, 'view', options);\n return _this.$unwrap(futureMailboxData);\n });\n };\n\n /**\n * @function $loadMessage\n * @memberof Mailbox.prototype\n * @desc Check if the message is loaded and in any case, fetch more messages headers from the server.\n * @returns true if the message metadata are already fetched\n */\n Mailbox.prototype.$loadMessage = function(messageId) {\n var startIndex = this.uidsMap[messageId],\n endIndex,\n index,\n max = this.$messages.length,\n loaded = false,\n uids,\n futureHeadersData;\n if (angular.isDefined(this.uidsMap[messageId]) && startIndex < this.$messages.length) {\n // Index is valid\n if (angular.isDefined(this.$messages[startIndex].subject)) {// || this.$messages[startIndex].loading) {\n // Message headers are loaded or data is coming\n loaded = true;\n }\n\n // Preload more headers if possible\n endIndex = Math.min(startIndex + Mailbox.PRELOAD.LOOKAHEAD, max - 1);\n if (angular.isDefined(this.$messages[endIndex].subject) ||\n angular.isDefined(this.$messages[endIndex].loading)) {\n index = Math.max(startIndex - Mailbox.PRELOAD.LOOKAHEAD, 0);\n if (!angular.isDefined(this.$messages[index].subject) &&\n !angular.isDefined(this.$messages[index].loading)) {\n // Previous messages not loaded; preload more headers further up\n endIndex = startIndex;\n startIndex = Math.max(startIndex - Mailbox.PRELOAD.SIZE, 0);\n }\n }\n else\n // Next messages not load; preload more headers further down\n endIndex = Math.min(startIndex + Mailbox.PRELOAD.SIZE, max - 1);\n\n if (!angular.isDefined(this.$messages[startIndex].subject) &&\n !angular.isDefined(this.$messages[startIndex].loading) ||\n !angular.isDefined(this.$messages[endIndex].subject) &&\n !angular.isDefined(this.$messages[endIndex].loading)) {\n\n for (uids = []; startIndex < endIndex && startIndex < max; startIndex++) {\n if (angular.isDefined(this.$messages[startIndex].subject) || this.$messages[startIndex].loading) {\n // Message at this index is already loaded; increase the end index\n endIndex++;\n }\n else {\n // Message at this index will be loaded\n uids.push(this.$messages[startIndex].uid);\n this.$messages[startIndex].loading = true;\n }\n }\n\n Mailbox.$log.debug('Loading UIDs ' + uids.join(' '));\n futureHeadersData = Mailbox.$$resource.post(this.id, 'headers', {uids: uids});\n this.$unwrapHeaders(futureHeadersData);\n }\n }\n return loaded;\n };\n\n /**\n * @function isEditable\n * @memberof Mailbox.prototype\n * @desc Checks if the mailbox is editable based on its type.\n * @returns true if the mailbox is not a special folder.\n */\n Mailbox.prototype.isEditable = function() {\n return this.type == 'folder';\n };\n\n /**\n * @function isNoInferiors\n * @memberof Mailbox.prototype\n * @desc Checks if the mailbox can contain submailboxes\n * @returns true if the mailbox can not contain submailboxes\n */\n Mailbox.prototype.isNoInferiors = function() {\n return this.flags.indexOf('noinferiors') >= 0;\n };\n\n /**\n * @function isNoSelect\n * @memberof Mailbox.prototype\n * @desc Checks if the mailbox can be selected\n * @returns true if the mailbox can not be selected\n */\n Mailbox.prototype.isNoSelect = function() {\n return this.flags.indexOf('noselect') >= 0;\n };\n\n /**\n * @function $rename\n * @memberof AddressBook.prototype\n * @desc Rename the addressbook and keep the list sorted\n * @param {string} name - the new name\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$rename = function() {\n var _this = this,\n findParent,\n parent,\n children,\n i;\n\n if (this.name == this.$shadowData.name) {\n // Name hasn't changed\n return Mailbox.$q.when();\n }\n\n // Local recursive function\n findParent = function(parent, children) {\n var parentMailbox = null,\n mailbox = _.find(children, function(o) {\n return o.path == _this.path;\n });\n if (mailbox) {\n parentMailbox = parent;\n }\n else {\n angular.forEach(children, function(o) {\n if (!parentMailbox && o.children && o.children.length > 0) {\n parentMailbox = findParent(o, o.children);\n }\n });\n }\n return parentMailbox;\n };\n\n // Find mailbox parent\n parent = findParent(null, this.$account.$mailboxes);\n if (parent === null)\n children = this.$account.$mailboxes;\n else\n children = parent.children;\n\n // Find index of mailbox among siblings\n i = _.indexOf(_.map(children, 'id'), this.id);\n\n return this.$save().then(function(data) {\n var sibling;\n angular.extend(_this, data); // update the path attribute\n _this.id = _this.$id();\n\n // Move mailbox among its siblings according to its new name\n children.splice(i, 1);\n sibling = _.find(children, function(o) {\n Mailbox.$log.debug(o.name + ' ? ' + _this.name);\n return (o.type == 'folder' && o.name.localeCompare(_this.name) > 0);\n });\n if (sibling) {\n i = _.indexOf(_.map(children, 'id'), sibling.id);\n }\n else {\n i = children.length;\n }\n children.splice(i, 0, _this);\n });\n };\n\n /**\n * @function $compact\n * @memberof Mailbox.prototype\n * @desc Compact the mailbox\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$compact = function() {\n var _this = this;\n return Mailbox.$$resource.post(this.id, 'expunge')\n .then(function(data) {\n // Update inbox quota\n if (data.quotas)\n _this.$account.updateQuota(data.quotas);\n });\n };\n\n /**\n * @function $setFolderAs\n * @memberof Mailbox.prototype\n * @desc Set a folder as Drafts/Sent/Trash\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$setFolderAs = function(type) {\n return Mailbox.$$resource.post(this.id, 'setAs' + type + 'Folder');\n };\n\n /**\n * @function $emptyTrash\n * @memberof Mailbox.prototype\n * @desc Empty the Trash folder.\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$emptyTrash = function() {\n var _this = this;\n\n return Mailbox.$$resource.post(this.id, 'emptyTrash').then(function(data) {\n // Remove all messages from the mailbox\n _this.$messages = [];\n _this.uidsMap = {};\n _this.unseenCount = 0;\n\n // If we had any submailboxes, lets do a refresh of the mailboxes list\n if (angular.isDefined(_this.children) && _this.children.length)\n _this.$account.$getMailboxes({reload: true});\n\n // Update inbox quota\n if (data.quotas)\n _this.$account.updateQuota(data.quotas);\n });\n };\n\n /**\n * @function $markAsRead\n * @memberof Mailbox.prototype\n * @desc Mark all messages from folder as read\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$markAsRead = function() {\n return Mailbox.$$resource.post(this.id, 'markRead');\n };\n\n /**\n * @function $flagMessages\n * @memberof Mailbox.prototype\n * @desc Add or remove a flag on a message set\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$flagMessages = function(messages, flags, operation) {\n var data = {msgUIDs: _.map(messages, 'uid'),\n flags: flags,\n operation: operation};\n\n return Mailbox.$$resource.post(this.id, 'addOrRemoveLabel', data).then(function() {\n return messages;\n });\n };\n\n /**\n * @function saveSelectedMessages\n * @memberof Mailbox.prototype\n * @desc Download the selected messages\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.saveSelectedMessages = function() {\n var data, options, selectedMessages, selectedUIDs;\n\n selectedMessages = _.filter(this.$messages, function(message) { return message.selected; });\n selectedUIDs = _.map(selectedMessages, 'uid');\n data = { uids: selectedUIDs };\n options = { filename: l('Saved Messages.zip') };\n\n return Mailbox.$$resource.download(this.id, 'saveMessages', {uids: selectedUIDs});\n };\n\n /**\n * @function exportFolder\n * @memberof Mailbox.prototype\n * @desc Export this mailbox\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.exportFolder = function() {\n var options;\n\n options = { filename: this.name + '.zip' };\n\n return Mailbox.$$resource.download(this.id, 'exportFolder', null, options);\n };\n\n /**\n * @function $delete\n * @memberof Mailbox.prototype\n * @desc Delete the mailbox from the server\n * @param {object} [options] - additional options (use {withoutTrash: true} to delete immediately)\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$delete = function(options) {\n var _this = this;\n\n return Mailbox.$$resource.post(this.id, 'delete', options)\n .then(function() {\n _this.$account.$getMailboxes({reload: true});\n return true;\n });\n };\n\n /**\n * @function $_deleteMessages\n * @memberof Mailbox.prototype\n * @desc Delete multiple messages from Mailbox object.\n * @param {string[]} uids - the messages uids\n * @param {object[]} messages - the Message instances\n * @return the index of the first deleted message\n */\n Mailbox.prototype.$_deleteMessages = function(uids, messages) {\n var _this = this, selectedUIDs, _$messages, unseen, firstIndex = this.$messages.length;\n\n // Decrement the unseen count\n unseen = _.filter(messages, function(message, i) { return !message.isread; });\n this.unseenCount -= unseen.length;\n\n // Remove messages from $messages and uidsMap\n _.forEachRight(this.$messages, function(message, index) {\n var selectedIndex = _.findIndex(uids, function(uid) {\n return message.uid == uid;\n });\n if (selectedIndex > -1) {\n uids.splice(selectedIndex, 1);\n delete _this.uidsMap[message.uid];\n if (message.uid == _this.selectedMessage)\n delete _this.selectedMessage;\n _this.$messages.splice(index, 1);\n if (index < firstIndex)\n firstIndex = index;\n }\n else {\n _this.uidsMap[message.uid] -= uids.length;\n }\n });\n\n // Return the index of the first deleted message\n return firstIndex;\n };\n\n /**\n * @function $deleteMessages\n * @memberof Mailbox.prototype\n * @desc Delete multiple messages from mailbox.\n * @param {object} [options] - additional options (use {withoutTrash: true} to delete immediately)\n * @return a promise of the HTTP operation\n */\n Mailbox.prototype.$deleteMessages = function(messages, options) {\n var _this = this, uids, data;\n\n uids = _.map(messages, 'uid');\n data = { uids: uids };\n if (options) angular.extend(data, options);\n\n return Mailbox.$$resource.post(this.id, 'batchDelete', data)\n .then(function(data) {\n // Update inbox quota\n if (data.quotas)\n _this.$account.updateQuota(data.quotas);\n\n return _this.$_deleteMessages(uids, messages);\n });\n };\n\n /**\n * @function $markOrUnMarkMessagesAsJunk\n * @memberof Mailbox.prototype\n * @desc Mark messages as junk/not junk\n * @return a promise of the HTTP operation\n */\n Mailbox.prototype.$markOrUnMarkMessagesAsJunk = function(messages) {\n var _this = this,\n uids = _.map(messages, 'uid'),\n method = (this.type == 'junk' ? 'markMessagesAsNotJunk' : 'markMessagesAsJunk');\n\n return Mailbox.$$resource.post(this.id, method, {uids: uids});\n };\n\n /**\n * @function $copyMessages\n * @memberof Mailbox.prototype\n * @desc Copy multiple messages from the current mailbox to a target one\n * @return a promise of the HTTP operation\n */\n Mailbox.prototype.$copyMessages = function(messages, folder) {\n var _this = this,\n uids = _.map(messages, 'uid');\n\n return Mailbox.$$resource.post(this.id, 'copyMessages', {uids: uids, folder: folder})\n .then(function(data) {\n // Update inbox quota\n if (data.quotas)\n _this.$account.updateQuota(data.quotas);\n });\n };\n\n /**\n * @function $moveMessages\n * @memberof Mailbox.prototype\n * @desc Move multiple messages from the current mailbox to a target one\n * @return a promise of the HTTP operation\n */\n Mailbox.prototype.$moveMessages = function(messages, folder) {\n var _this = this, uids;\n\n uids = _.map(messages, 'uid');\n return Mailbox.$$resource.post(this.id, 'moveMessages', {uids: uids, folder: folder})\n .then(function() {\n return _this.$_deleteMessages(uids, messages);\n });\n };\n\n /**\n * @function $reset\n * @memberof Mailbox.prototype\n * @desc Reset the original state the mailbox's data.\n */\n Mailbox.prototype.$reset = function() {\n var _this = this;\n angular.forEach(this.$shadowData, function(value, key) {\n delete _this[key];\n });\n angular.extend(this, this.$shadowData);\n this.$shadowData = this.$omit();\n };\n\n /**\n * @function $save\n * @memberof Mailbox.prototype\n * @desc Save the mailbox to the server. This currently can only affect the name of the mailbox.\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$save = function() {\n var _this = this;\n\n return Mailbox.$$resource.save(this.id, this.$omit()).then(function(data) {\n // Make a copy of the data for an eventual reset\n _this.$shadowData = _this.$omit();\n Mailbox.$log.debug(JSON.stringify(data, undefined, 2));\n return data;\n }, function(response) {\n Mailbox.$log.error(JSON.stringify(response.data, undefined, 2));\n // Restore previous version\n _this.$reset();\n return response.data;\n });\n };\n\n /**\n * @function $newMailbox\n * @memberof Mailbox.prototype\n * @desc Create a new mailbox on the server and refresh the list of mailboxes.\n * @returns a promise of the HTTP operations\n */\n Mailbox.prototype.$newMailbox = function(path, name) {\n return this.$account.$newMailbox(path, name);\n };\n\n /**\n * @function $omit\n * @memberof Mailbox.prototype\n * @desc Return a sanitized object used to send to the server.\n * @return an object literal copy of the Mailbox instance\n */\n Mailbox.prototype.$omit = function() {\n var mailbox = {};\n angular.forEach(this, function(value, key) {\n if (key != 'constructor' &&\n key != 'children' &&\n key != 'headers' &&\n key != 'uids' &&\n key != 'uidsMap' &&\n key[0] != '$') {\n mailbox[key] = value;\n }\n });\n return mailbox;\n };\n\n /**\n * @function $unwrap\n * @memberof Mailbox.prototype\n * @desc Unwrap a promise and instanciate new Message objects using received data.\n * @param {promise} futureMailboxData - a promise of the Mailbox's metadata\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$unwrap = function(futureMailboxData) {\n var _this = this,\n deferred = Mailbox.$q.defer();\n\n this.$futureMailboxData = futureMailboxData;\n this.$futureMailboxData.then(function(data) {\n Mailbox.$timeout(function() {\n var uids, headers;\n\n if (!data.uids || _this.$topIndex > data.uids.length - 1)\n _this.$topIndex = 0;\n\n _this.init(data);\n\n if (_this.uids) {\n Mailbox.$log.debug('unwrapping ' + data.uids.length + ' messages');\n\n // First entry of 'headers' are keys\n headers = _.invokeMap(_this.headers[0], 'toLowerCase');\n _this.headers.splice(0, 1);\n\n // First entry of 'uids' are keys when threaded view is enabled\n if (_this.threaded) {\n uids = _this.uids[0];\n _this.uids.splice(0, 1);\n }\n\n // Instanciate Message objects\n _.reduce(_this.uids, function(msgs, msg, i) {\n var data;\n if (_this.threaded)\n data = _.zipObject(uids, msg);\n else\n data = {uid: msg.toString()};\n\n // Build map of UID <=> index\n _this.uidsMap[data.uid] = i;\n\n msgs.push(new Mailbox.$Message(_this.$account.id, _this, data, true));\n\n return msgs;\n }, _this.$messages);\n\n // Extend Message objects with received headers\n _.forEach(_this.headers, function(data) {\n var msg = _.zipObject(headers, data),\n i = _this.uidsMap[msg.uid.toString()];\n _.extend(_this.$messages[i], msg);\n });\n }\n Mailbox.$log.debug('mailbox ' + _this.id + ' ready');\n _this.$isLoading = false;\n deferred.resolve(_this.$messages);\n });\n }, function(data) {\n angular.extend(_this, data);\n _this.isError = true;\n deferred.reject();\n });\n\n return deferred.promise;\n };\n\n /**\n * @function $unwrapHeaders\n * @memberof Mailbox.prototype\n * @desc Unwrap a promise and extend matching Message objects using received data.\n * @param {promise} futureHeadersData - a promise of some messages metadata\n */\n Mailbox.prototype.$unwrapHeaders = function(futureHeadersData) {\n var _this = this;\n\n futureHeadersData.then(function(data) {\n Mailbox.$timeout(function() {\n var headers, j;\n if (data.length > 0) {\n // First entry of 'headers' are keys\n headers = _.invokeMap(data[0], 'toLowerCase');\n data.splice(0, 1);\n _.forEach(data, function(messageHeaders) {\n messageHeaders = _.zipObject(headers, messageHeaders);\n j = _this.uidsMap[messageHeaders.uid.toString()];\n if (angular.isDefined(j)) {\n _.extend(_this.$messages[j], messageHeaders);\n }\n });\n }\n });\n });\n };\n\n /**\n * @function $updateSubscribe\n * @memberof Mailbox.prototype\n * @desc Update mailbox subscription state with server.\n */\n Mailbox.prototype.$updateSubscribe = function() {\n var action = this.subscribed? 'subscribe' : 'unsubscribe';\n\n Mailbox.$$resource.post(this.id, action);\n };\n\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @name Message\n * @constructor\n * @param {string} accountId - the account ID\n * @param {string} mailboxPath - an array of the mailbox path components\n * @param {object} futureAddressBookData - either an object literal or a promise\n * @param {bool} lazy - do \"lazy loading\" so we are very quick at initializing message instances\n */\n function Message(accountId, mailbox, futureMessageData, lazy) {\n this.accountId = accountId;\n this.$mailbox = mailbox;\n this.$hasUnsafeContent = false;\n this.$loadUnsafeContent = false;\n this.editable = {to: [], cc: [], bcc: []};\n this.selected = false;\n\n // Data is immediately available\n if (typeof futureMessageData.then !== 'function') {\n //console.debug(JSON.stringify(futureMessageData, undefined, 2));\n if (angular.isUndefined(lazy) || !lazy) {\n angular.extend(this, futureMessageData);\n this.$formatFullAddresses();\n }\n this.uid = parseInt(futureMessageData.uid);\n }\n else {\n // The promise will be unwrapped first\n this.$unwrap(futureMessageData);\n }\n }\n\n /**\n * @memberof Message\n * @desc The factory we'll use to register with Angular\n * @returns the Message constructor\n */\n Message.$factory = ['$q', '$timeout', '$log', 'sgSettings', 'sgMessage_STATUS', 'Resource', 'Preferences', function($q, $timeout, $log, Settings, Message_STATUS, Resource, Preferences) {\n angular.extend(Message, {\n STATUS: Message_STATUS,\n $q: $q,\n $timeout: $timeout,\n $log: $log,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Mail', Settings.activeUser()),\n $avatar: angular.bind(Preferences, Preferences.avatar)\n });\n // Initialize tags form user's defaults\n Preferences.ready().then(function() {\n if (Preferences.defaults.SOGoMailLabelsColors) {\n Message.$tags = Preferences.defaults.SOGoMailLabelsColors;\n }\n if (Preferences.defaults.SOGoMailDisplayRemoteInlineImages &&\n Preferences.defaults.SOGoMailDisplayRemoteInlineImages == 'always') {\n Message.$displayRemoteInlineImages = true;\n }\n });\n\n return Message; // return constructor\n }];\n\n /**\n * @module SOGo.MailerUI\n * @desc Factory registration of Message in Angular module.\n */\n try {\n angular.module('SOGo.MailerUI');\n }\n catch(e) {\n angular.module('SOGo.MailerUI', ['SOGo.Common']);\n }\n angular.module('SOGo.MailerUI')\n .constant('sgMessage_STATUS', {\n NOT_LOADED: 0,\n DELAYED_LOADING: 1,\n LOADING: 2,\n LOADED: 3,\n DELAYED_MS: 300\n })\n .factory('Message', Message.$factory);\n\n /**\n * @function filterTags\n * @memberof Message.prototype\n * @desc Search for tags (ie., mail labels) matching some criterias\n * @param {string} search - the search string to match\n * @returns a collection of strings\n */\n Message.filterTags = function(query, excludedTags) {\n var re = new RegExp(query, 'i'),\n results = [];\n\n _.forEach(_.keys(Message.$tags), function(tag) {\n var pair = Message.$tags[tag];\n if (pair[0].search(re) != -1) {\n if (!_.includes(excludedTags, tag))\n results.push({ name: tag, description: pair[0], color: pair[1] });\n }\n });\n\n return results;\n };\n\n /**\n * @function $absolutePath\n * @memberof Message.prototype\n * @desc Build the path of the message\n * @returns a string representing the path relative to the mail module\n */\n Message.prototype.$absolutePath = function(options) {\n var _this = this, id = this.id;\n\n function buildPath() {\n var path;\n path = _.map(_this.$mailbox.path.split('/'), function(component) {\n return 'folder' + component.asCSSIdentifier();\n });\n path.splice(0, 0, _this.accountId); // insert account ID\n return path.join('/');\n }\n\n if (angular.isUndefined(this.id) || options && options.nocache) {\n this.id = buildPath() + '/' + this.uid; // add message UID\n id = this.id;\n }\n if (options && options.asDraft && this.draftId) {\n id = buildPath() + '/' + this.draftId; // add draft ID\n }\n\n return id;\n };\n\n /**\n * @function $setUID\n * @memberof Message.prototype\n * @desc Change the UID of the message. This happens when saving a draft.\n * @param {number} uid - the new message UID\n */\n Message.prototype.$setUID = function(uid) {\n var oldUID = (this.uid || -1), _this = this, index;\n\n if (oldUID != parseInt(uid)) {\n this.uid = parseInt(uid);\n this.$absolutePath({nocache: true});\n if (oldUID > -1) {\n oldUID = oldUID.toString();\n if (angular.isDefined(this.$mailbox.uidsMap[oldUID])) {\n index = this.$mailbox.uidsMap[oldUID];\n this.$mailbox.uidsMap[uid] = index;\n delete this.$mailbox.uidsMap[oldUID];\n\n // Update messages list of mailbox\n _.forEach(['from', 'to', 'subject'], function(attr) {\n _this.$mailbox.$messages[index][attr] = _this[attr];\n });\n }\n }\n else {\n // Refresh selected folder if it's the drafts mailbox\n if (this.$mailbox.constructor.selectedFolder &&\n this.$mailbox.constructor.selectedFolder.type == 'draft') {\n this.$mailbox.constructor.selectedFolder.$filter();\n }\n }\n }\n };\n\n /**\n * @function $formatFullAddresses\n * @memberof Message.prototype\n * @desc Format all sender and recipients addresses with a complete description (name ).\n * This function also generates the avatar URL for each email address and a short name\n */\n Message.prototype.$formatFullAddresses = function() {\n var _this = this;\n var identities = _.map(_this.$mailbox.$account.identities, 'email');\n\n // Build long representation of email addresses\n _.forEach(['from', 'to', 'cc', 'bcc', 'reply-to'], function(type) {\n _.forEach(_this[type], function(data) {\n if (data.name && data.name != data.email) {\n data.full = data.name + ' <' + data.email + '>';\n\n if (data.name.length < 10)\n // Name is already short\n data.shortname = data.name;\n else if (data.name.split(' ').length)\n // If we have \"Alice Foo\" or \"Foo, Alice\" as name, we grab \"Alice\"\n data.shortname = _.first(_.last(data.name.split(/, */)).split(/ +/)).replace('\\'','');\n }\n else if (data.email) {\n data.full = '<' + data.email + '>';\n data.shortname = data.email.split('@')[0];\n }\n\n data.image = Message.$avatar(data.email, 32);\n\n // If the current user is the recepient, overwrite\n // the short name with 'me'\n if (_.indexOf(identities, data.email) >= 0)\n data.shortname = l('me');\n });\n });\n };\n\n /**\n * @function $shortRecipients\n * @memberof Message.prototype\n * @desc Format all recipients into a very compact string\n * @returns a compacted string of all recipients\n */\n Message.prototype.$shortRecipients = function(max) {\n var _this = this, result = [], count = 0, total = 0;\n\n // Build short representation of email addresses\n _.forEach(['to', 'cc', 'bcc'], function(type) {\n total += _this[type]? _this[type].length : 0;\n _.forEach(_this[type], function(data, i) {\n if (count < max)\n result.push(data.shortname);\n count++;\n });\n });\n\n if (total > max)\n result.push(l('and %{0} more...', (total - max)));\n\n return result.join(', ');\n };\n\n /**\n * @function $shortAddress\n * @memberof Message.prototype\n * @desc Format the first address of a specific type with a short description.\n * @returns a string of the name or the email of the envelope address type\n */\n Message.prototype.$shortAddress = function(type) {\n var address = '';\n if (this[type] && this[type].length > 0) {\n address = this[type][0].name || this[type][0].email || '';\n }\n\n return address;\n };\n\n /**\n * @function allowReplyAll\n * @memberof Message.prototype\n * @desc Check if 'Reply to All' is an appropriate action on the message.\n * @returns true if the message is not a draft and has more than one recipient\n */\n Message.prototype.allowReplyAll = function() {\n var recipientsCount = 0;\n recipientsCount = _.reduce(['to', 'cc'], _.bind(function(count, type) {\n if (this[type])\n return count + this[type].length;\n else\n return count;\n }, this), recipientsCount);\n\n return !this.isDraft && recipientsCount > 1;\n };\n\n /**\n * @function loadUnsafeContent\n * @memberof Message.prototype\n * @desc Mark the message to load unsafe resources when calling $content().\n */\n Message.prototype.loadUnsafeContent = function() {\n this.$loadUnsafeContent = true;\n };\n\n /**\n * @function $content\n * @memberof Message.prototype\n * @desc Get the message body as accepted by SCE (Angular Strict Contextual Escaping).\n * @returns the HTML representation of the body\n */\n Message.prototype.$content = function() {\n var _this = this,\n parts = [],\n _visit = function(part) {\n part.msgclass = 'msg-attachment-other';\n if (part.type == 'UIxMailPartAlternativeViewer') {\n _visit(_.find(part.content, function(alternatePart) {\n return part.preferredPart == alternatePart.contentType;\n }));\n }\n // Can be used for UIxMailPartMixedViewer, UIxMailPartMessageViewer, and UIxMailPartSignedViewer\n else if (angular.isArray(part.content)) {\n if (part.type == 'UIxMailPartSignedViewer' && part['supports-smime'] === 1) {\n // First line in a h1, others each in a p\n var formattedMessage = \"

\" + part.error.replace(/\\n/, \"

\");\n formattedMessage = formattedMessage.replace(/\\n/g, \"

\") + \"

\";\n _this.$smime = {\n validSignature: part.valid,\n message: formattedMessage\n };\n }\n _.forEach(part.content, function(mixedPart) {\n _visit(mixedPart);\n });\n }\n else {\n if (angular.isUndefined(part.safeContent)) {\n // Keep a copy of the original content\n part.safeContent = part.content;\n _this.$hasUnsafeContent |= (part.safeContent.indexOf(' unsafe-') > -1);\n }\n if (part.type == 'UIxMailPartHTMLViewer') {\n part.html = true;\n if (_this.$loadUnsafeContent || Message.$displayRemoteInlineImages) {\n if (angular.isUndefined(part.unsafeContent)) {\n part.unsafeContent = document.createElement('div');\n part.unsafeContent.innerHTML = part.safeContent;\n angular.forEach(['src', 'data', 'classid', 'background', 'style'], function(suffix) {\n var elements = part.unsafeContent.querySelectorAll('[unsafe-' + suffix + ']'),\n element,\n value,\n i;\n for (i = 0; i < elements.length; i++) {\n element = angular.element(elements[i]);\n value = element.attr('unsafe-' + suffix);\n element.attr(suffix, value);\n element.removeAttr('unsafe-' + suffix);\n }\n });\n _this.$hasUnsafeContent = false;\n }\n part.content = part.unsafeContent.innerHTML;\n }\n else {\n part.content = part.safeContent;\n }\n parts.push(part);\n }\n else if (part.type == 'UIxMailPartICalViewer' ||\n part.type == 'UIxMailPartImageViewer' ||\n part.type == 'UIxMailPartLinkViewer') {\n\n if (part.type == 'UIxMailPartImageViewer')\n part.msgclass = 'msg-attachment-image';\n else if (part.type == 'UIxMailPartLinkViewer')\n part.msgclass = 'msg-attachment-link';\n\n // Trusted content that can be compiled (Angularly-speaking)\n part.compile = true;\n parts.push(part);\n }\n else {\n part.html = true;\n part.content = part.safeContent;\n parts.push(part);\n }\n }\n };\n\n if (this.parts)\n _visit(this.parts);\n\n return parts;\n };\n\n /**\n * @function $editableContent\n * @memberof Message.prototype\n * @desc First, fetch the draft ID that corresponds to the temporary draft object on the SOGo server.\n * Secondly, fetch the editable message body along with other metadata such as the recipients.\n * @returns the HTML representation of the body\n */\n Message.prototype.$editableContent = function() {\n var _this = this;\n\n return Message.$$resource.fetch(this.$absolutePath(), 'edit').then(function(data) {\n angular.extend(_this, data);\n return Message.$$resource.fetch(_this.$absolutePath({asDraft: true}), 'edit').then(function(data) {\n // Try to match a known account identity from the specified \"from\" address\n var identity = _.find(_this.$mailbox.$account.identities, function(identity) {\n return data.from.toLowerCase().indexOf(identity.email) !== -1;\n });\n if (identity)\n data.from = identity.full;\n Message.$log.debug('editable = ' + JSON.stringify(data, undefined, 2));\n angular.extend(_this.editable, data);\n return data.text;\n });\n });\n };\n\n /**\n * @function $plainContent\n * @memberof Message.prototype\n * @returns the a plain text representation of the subject and body\n */\n Message.prototype.$plainContent = function() {\n return Message.$$resource.fetch(this.$absolutePath(), 'viewplain');\n };\n\n /**\n * @function addTag\n * @memberof Message.prototype\n * @desc Add a mail tag on the current message.\n * @param {string} tag - the tag name\n * @returns a promise of the HTTP operation\n */\n Message.prototype.addTag = function(tag) {\n return this.$addOrRemoveTag('add', tag);\n };\n\n /**\n * @function removeTag\n * @memberof Message.prototype\n * @desc Remove a mail tag from the current message.\n * @param {string} tag - the tag name\n * @returns a promise of the HTTP operation\n */\n Message.prototype.removeTag = function(tag) {\n return this.$addOrRemoveTag('remove', tag);\n };\n\n /**\n * @function $addOrRemoveTag\n * @memberof Message.prototype\n * @desc Add or remove a mail tag on the current message.\n * @param {string} operation - the operation name to perform\n * @param {string} tag - the tag name\n * @returns a promise of the HTTP operation\n */\n Message.prototype.$addOrRemoveTag = function(operation, tag) {\n var data = {\n operation: operation,\n msgUIDs: [this.uid],\n flags: tag\n };\n\n if (tag)\n return Message.$$resource.post(this.$mailbox.$id(), 'addOrRemoveLabel', data);\n };\n\n /**\n * @function $imipAction\n * @memberof Message.prototype\n * @desc Perform IMIP actions on the current message.\n * @param {string} path - the path of the IMIP calendar part\n * @param {string} action - the the IMIP action to perform\n * @param {object} data - the delegation info\n */\n Message.prototype.$imipAction = function(path, action, data) {\n var _this = this;\n Message.$$resource.post([this.$absolutePath(), path].join('/'), action, data).then(function(data) {\n Message.$timeout(function() {\n _this.$reload();\n });\n });\n };\n\n /**\n * @function $sendMDN\n * @memberof Message.prototype\n * @desc Send MDN response for current email message\n */\n Message.prototype.$sendMDN = function() {\n this.shouldAskReceipt = 0;\n return Message.$$resource.post(this.$absolutePath(), 'sendMDN');\n };\n\n /**\n * @function $deleteAttachment\n * @memberof Message.prototype\n * @desc Delete an attachment from a message being composed\n * @param {string} filename - the filename of the attachment to delete\n */\n Message.prototype.$deleteAttachment = function(filename) {\n var action = 'deleteAttachment?filename=' + filename;\n var _this = this;\n Message.$$resource.post(this.$absolutePath({asDraft: true}), action).then(function(data) {\n Message.$timeout(function() {\n _this.editable.attachmentAttrs = _.filter(_this.editable.attachmentAttrs, function(attachment) {\n return attachment.filename != filename;\n });\n });\n });\n };\n\n /**\n * @function $markAsFlaggedOrUnflagged\n * @memberof Message.prototype\n * @desc Add or remove a the \\\\Flagged flag on the current message.\n * @returns a promise of the HTTP operation\n */\n Message.prototype.toggleFlag = function() {\n var _this = this,\n action = 'markMessageFlagged';\n\n if (this.isflagged)\n action = 'markMessageUnflagged';\n\n return Message.$$resource.post(this.$absolutePath(), action).then(function(data) {\n Message.$timeout(function() {\n _this.isflagged = !_this.isflagged;\n });\n });\n };\n\n /**\n * @function $isLoading\n * @memberof Message.prototype\n * @returns true if the Message content is still being retrieved from server after a specific delay\n * @see sgMessage_STATUS\n */\n Message.prototype.$isLoading = function() {\n return this.$loaded == Message.STATUS.LOADING;\n };\n\n /**\n * @function $reload\n * @memberof Message.prototype\n * @desc Fetch the viewable message body along with other metadata such as the list of attachments.\n * @param {object} [options] - set {useCache: true} to use already fetched data\n * @returns a promise of the HTTP operation\n */\n Message.prototype.$reload = function(options) {\n var _this = this, futureMessageData;\n\n if (options && options.useCache && this.$futureMessageData) {\n if (!this.isread) {\n Message.$$resource.fetch(this.$absolutePath(), 'markMessageRead').then(function() {\n Message.$timeout(function() {\n _this.isread = true;\n _this.$mailbox.unseenCount--;\n });\n });\n }\n return this;\n }\n\n futureMessageData = Message.$$resource.fetch(this.$absolutePath(options), 'view');\n\n return this.$unwrap(futureMessageData);\n };\n\n /**\n * @function $reply\n * @memberof Message.prototype\n * @desc Prepare a new Message object as a reply to the sender.\n * @returns a promise of the HTTP operations\n */\n Message.prototype.$reply = function() {\n return this.$newDraft('reply');\n };\n\n /**\n * @function $replyAll\n * @memberof Message.prototype\n * @desc Prepare a new Message object as a reply to the sender and all recipients.\n * @returns a promise of the HTTP operations\n */\n Message.prototype.$replyAll = function() {\n return this.$newDraft('replyall');\n };\n\n /**\n * @function $forward\n * @memberof Message.prototype\n * @desc Prepare a new Message object as a forward.\n * @returns a promise of the HTTP operations\n */\n Message.prototype.$forward = function() {\n return this.$newDraft('forward');\n };\n\n /**\n * @function $newDraft\n * @memberof Message.prototype\n * @desc Prepare a new Message object as a reply or a forward of the current message and associated\n * to the draft mailbox.\n * @see {@link Account.$newMessage}\n * @see {@link Message.$editableContent}\n * @see {@link Message.$reply}\n * @see {@link Message.$replyAll}\n * @see {@link Message.$forwad}\n * @param {string} action - the HTTP action to perform on the message\n * @returns a promise of the HTTP operations\n */\n Message.prototype.$newDraft = function(action) {\n var _this = this;\n\n // Query server for draft folder and draft UID\n return Message.$$resource.fetch(this.$absolutePath(), action).then(function(data) {\n var mailbox, message;\n Message.$log.debug('New ' + action + ': ' + JSON.stringify(data, undefined, 2));\n mailbox = _this.$mailbox.$account.$getMailboxByPath(data.mailboxPath);\n message = new Message(data.accountId, mailbox, data);\n // Fetch draft initial data\n return Message.$$resource.fetch(message.$absolutePath({asDraft: true}), 'edit').then(function(data) {\n Message.$log.debug('New ' + action + ': ' + JSON.stringify(data, undefined, 2) + ' original UID: ' + _this.uid);\n angular.extend(message.editable, data);\n\n // We keep a reference to our original message in order to update the flags\n message.origin = {message: _this, action: action};\n return message;\n });\n });\n };\n\n /**\n * @function $save\n * @memberof Message.prototype\n * @desc Save the message to the server.\n * @returns a promise of the HTTP operation\n */\n Message.prototype.$save = function() {\n var _this = this,\n data = this.editable;\n\n Message.$log.debug('save = ' + JSON.stringify(data, undefined, 2));\n\n return Message.$$resource.save(this.$absolutePath({asDraft: true}), data).then(function(response) {\n Message.$log.debug('save = ' + JSON.stringify(response, undefined, 2));\n _this.$setUID(response.uid);\n _this.$reload(); // fetch a new viewable version of the message\n _this.isNew = false;\n });\n };\n\n /**\n * @function $send\n * @memberof Message.prototype\n * @desc Send the message.\n * @returns a promise of the HTTP operation\n */\n Message.prototype.$send = function() {\n var _this = this,\n data = angular.copy(this.editable);\n\n Message.$log.debug('send = ' + JSON.stringify(data, undefined, 2));\n\n return Message.$$resource.post(this.$absolutePath({asDraft: true}), 'send', data).then(function(response) {\n if (response.status == 'success') {\n if (angular.isDefined(_this.origin)) {\n if (_this.origin.action.startsWith('reply'))\n _this.origin.message.isanswered = true;\n else if (_this.origin.action == 'forward')\n _this.origin.message.isforwarded = true;\n }\n return response;\n }\n else {\n return Message.$q.reject(response.data);\n }\n });\n };\n\n /**\n * @function $unwrap\n * @memberof Message.prototype\n * @desc Unwrap a promise.\n * @param {promise} futureMessageData - a promise of some of the Message's data\n */\n Message.prototype.$unwrap = function(futureMessageData) {\n var _this = this;\n\n // Message is not loaded yet\n this.$loaded = Message.STATUS.DELAYED_LOADING;\n Message.$timeout(function() {\n if (_this.$loaded != Message.STATUS.LOADED)\n _this.$loaded = Message.STATUS.LOADING;\n }, Message.STATUS.DELAYED_MS);\n\n // Resolve and expose the promise\n this.$futureMessageData = futureMessageData.then(function(data) {\n // Calling $timeout will force Angular to refresh the view\n if (_this.isread === 0) {\n _this.isread = true;\n _this.$mailbox.unseenCount--;\n }\n return Message.$timeout(function() {\n angular.extend(_this, data);\n _this.$formatFullAddresses();\n _this.$loadUnsafeContent = false;\n _this.$loaded = Message.STATUS.LOADED;\n return _this;\n });\n });\n\n return this.$futureMessageData;\n };\n\n /**\n * @function $omit\n * @memberof Message.prototype\n * @desc Return a sanitized object used to send to the server.\n * @return an object literal copy of the Message instance\n */\n Message.prototype.$omit = function(options) {\n var message = {},\n privateAttributes = options && options.privateAttributes;\n angular.forEach(this, function(value, key) {\n if (key != 'constructor' && key[0] != '$' || privateAttributes) {\n message[key] = value;\n }\n });\n\n return message;\n };\n\n /**\n * @function download\n * @memberof Message.prototype\n * @desc Download the current message\n * @returns a promise of the HTTP operation\n */\n Message.prototype.download = function() {\n var data, options;\n\n data = { uids: [this.uid] };\n options = { filename: this.subject + '.zip' };\n\n return Message.$$resource.download(this.$mailbox.id, 'saveMessages', data, options);\n };\n\n /**\n * @function downloadAttachments\n * @memberof Message.prototype\n * @desc Download an archive of all attachments\n * @returns a promise of the HTTP operation\n */\n Message.prototype.downloadAttachments = function() {\n var options;\n\n options = { filename: l('attachments') + \"-\" + this.uid + \".zip\" };\n\n return Message.$$resource.download(this.$absolutePath(), 'archiveAttachments', null, options);\n };\n\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @name VirtualMailbox\n * @constructor\n * @param {object} account - the mail account associated with the virtual search\n */\n function VirtualMailbox(account) {\n this.$account = account;\n }\n\n /**\n * @memberof VirtualMailbox\n * @desc The factory we'll use to register with Angular\n * @returns the VirtualMailbox constructor\n */\n VirtualMailbox.$factory = ['$q', '$timeout', '$log', 'sgSettings', 'Resource', 'Message', 'Mailbox', 'sgMailbox_PRELOAD', function($q, $timeout, $log, Settings, Resource, Mailbox, Message, PRELOAD) {\n angular.extend(VirtualMailbox, {\n $q: $q,\n $timeout: $timeout,\n $log: $log,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Mail', Settings.activeUser()),\n $Message: Message,\n selectedFolder: null,\n PRELOAD: PRELOAD\n });\n\n return VirtualMailbox; // return constructor\n }];\n\n /**\n * @module SOGo.MailerUI\n * @desc Factory registration of VirtualMailbox in Angular module.\n */\n try {\n angular.module('SOGo.MailerUI');\n }\n catch(e) {\n angular.module('SOGo.MailerUI', ['SOGo.Common']);\n }\n angular.module('SOGo.MailerUI')\n .constant('sgMailbox_PRELOAD', {\n LOOKAHEAD: 50,\n SIZE: 100\n })\n .factory('VirtualMailbox', VirtualMailbox.$factory);\n\n /**\n * @memberof VirtualMailbox\n * @desc Build the path of the virtual mailbox (or account only).\n * @param {string} accountId - the account ID\n * @returns a string representing the path relative to the mail module\n */\n VirtualMailbox.$absolutePath = function(accountId) {\n return [accountId, \"virtual\"].join('/');\n };\n\n /**\n * @function init\n * @memberof VirtualMailbox.prototype\n * @desc Extend instance with new data and compute additional attributes.\n * @param {object} data - attributes of mailbox\n */\n VirtualMailbox.prototype.init = function(data) {\n this.$isLoading = false;\n this.$mailboxes = [];\n this.uidsMap = {};\n angular.extend(this, data);\n this.id = this.$id();\n };\n\n VirtualMailbox.prototype.setMailboxes = function(data) {\n this.$mailboxes = data;\n\n _.forEach(this.$mailboxes, function(mailbox) {\n mailbox.$messages = [];\n mailbox.uidsMap = {};\n });\n };\n\n VirtualMailbox.prototype.startSearch = function(match, params) {\n var _this = this,\n search = VirtualMailbox.$q.when();\n\n this.$isLoading = true;\n\n _.forEach(this.$mailboxes, function(mailbox) {\n search = search.then(function() {\n if (_this.$isLoading) {\n VirtualMailbox.$log.debug(\"searching mailbox \" + mailbox.path);\n return mailbox.$filter( {sort: \"date\", asc: false, match: match}, params);\n }\n });\n });\n\n search.finally(function() {\n _this.$isLoading = false;\n });\n };\n\n VirtualMailbox.prototype.stopSearch = function() {\n VirtualMailbox.$log.debug(\"stopping search...\");\n this.$isLoading = false;\n };\n\n /**\n * @function selectFolder\n * @memberof VirtualMailbox.prototype\n * @desc A no-op for virtual mailbox\n */\n VirtualMailbox.prototype.selectFolder = function() {\n return;\n };\n\n /**\n * @function resetSelectedMessage\n * @memberof VirtualMailbox.prototype\n * @desc Delete 'selectedMessage' attribute of all submailboxes.\n */\n VirtualMailbox.prototype.resetSelectedMessage = function() {\n _.forEach(this.$mailboxes, function(mailbox) {\n delete mailbox.selectedMessage;\n });\n };\n\n /**\n * @function hasSelectedMessage\n * @memberof VirtualMailbox.prototype\n * @desc Check if a message is selected among the resulting mailboxes\n * @returns true if one message is selected\n */\n VirtualMailbox.prototype.hasSelectedMessage = function() {\n return angular.isDefined(_.find(this.$mailboxes, function(mailbox) {\n return angular.isDefined(mailbox.selectedMessage);\n }));\n };\n\n /**\n * @function isSelectedMessage\n * @memberof VirtualMailbox.prototype\n * @desc Check if the message of the specified mailbox is selected.\n * @param {string} messageId\n * @param {string} mailboxPath\n * @returns true if the specified message is selected\n */\n VirtualMailbox.prototype.isSelectedMessage = function(messageId, mailboxPath) {\n return angular.isDefined(_.find(this.$mailboxes, function(mailbox) {\n return mailbox.path == mailboxPath && mailbox.selectedMessage == messageId;\n }));\n };\n\n /**\n * @function getLength\n * @memberof VirtualMailbox.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the number of items in the mailbox\n */\n VirtualMailbox.prototype.getLength = function() {\n var len = 0;\n\n if (!angular.isDefined(this.$mailboxes))\n return len;\n\n _.forEach(this.$mailboxes, function(mailbox) {\n len += mailbox.$messages.length;\n });\n\n return len;\n };\n\n /**\n * @function getItemAtIndex\n * @memberof VirtualMailbox.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the message as the specified index\n */\n VirtualMailbox.prototype.getItemAtIndex = function(index) {\n var i, j, k, mailbox, message;\n\n if (angular.isDefined(this.$mailboxes) && index >= 0) {\n i = 0;\n for (j = 0; j < this.$mailboxes.length; j++) {\n mailbox = this.$mailboxes[j];\n for (k = 0; k < mailbox.$messages.length; i++, k++) {\n message = mailbox.$messages[k];\n if (i == index) {\n if (mailbox.$loadMessage(message.uid))\n return message;\n }\n }\n }\n }\n\n return null;\n };\n\n /**\n * @function $id\n * @memberof VirtualMailbox.prototype\n * @desc Build the unique ID to identified the mailbox.\n * @returns a string representing the path relative to the mail module\n */\n VirtualMailbox.prototype.$id = function() {\n return VirtualMailbox.$absolutePath(this.$account.id);\n };\n\n /**\n * @function $selectedMessages\n * @memberof VirtualMailbox.prototype\n * @desc Return an associative array of the selected messages for each mailbox. Keys are the mailboxes ids.\n * @returns an associative array\n */\n VirtualMailbox.prototype.$selectedMessages = function() {\n var messagesMap = {};\n return _.transform(this.$mailboxes, function(messagesMap, mailbox) {\n messagesMap[mailbox.id] = mailbox.$selectedMessages();\n }, {});\n };\n\n /**\n * @function $selectedCount\n * @memberof VirtualMailbox.prototype\n * @desc Return the number of messages selected by the user.\n * @returns the number of selected messages\n */\n VirtualMailbox.prototype.$selectedCount = function() {\n return _.sum(_.invokeMap(this.$mailboxes, '$selectedCount'));\n };\n\n /**\n * @function $flagMessages\n * @memberof VirtualMailbox.prototype\n * @desc Add or remove a flag on a message set\n * @param {object} messagesMap\n * @param {array} flags\n * @param {string} operation\n * @returns a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$flagMessages = function(messagesMap, flags, operation) {\n var data = {\n flags: flags,\n operation: operation\n };\n var allMessages = [];\n var promises = [];\n\n _.forEach(messagesMap, function(messages, id) {\n if (messages.length > 0) {\n var uids = _.map(messages, 'uid');\n allMessages.push(messages);\n var promise = VirtualMailbox.$$resource.post(id, 'addOrRemoveLabel', _.assign(data, {msgUIDs: uids}));\n promises.push(promise);\n }\n });\n\n return VirtualMailbox.$q.all(promises).then(function() {\n return _.flatten(allMessages);\n });\n };\n\n /**\n * @function $deleteMessages\n * @memberof VirtualMailbox.prototype\n * @desc Delete multiple messages from mailbox.\n * @param {object} messagesMap\n * @return a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$deleteMessages = function(messagesMap) {\n var promises = [];\n\n _.forEach(messagesMap, function(messages, id) {\n if (messages.length > 0) {\n var mailbox = messages[0].$mailbox;\n var promise = mailbox.$deleteMessages(messages);\n promises.push(promise);\n }\n });\n\n return VirtualMailbox.$q.all(promises);\n };\n\n /**\n * @function $markOrUnMarkMessagesAsJunk\n * @memberof VirtualMailbox.prototype\n * @desc Mark messages as junk/not junk\n * @param {object} messagesMap\n * @return a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$markOrUnMarkMessagesAsJunk = function(messagesMap) {\n var promises = [];\n\n _.forEach(messagesMap, function(messages, id) {\n if (messages.length > 0) {\n var mailbox = messages[0].$mailbox;\n var promise = mailbox.$markOrUnMarkMessagesAsJunk(messages);\n promises.push(promise);\n }\n });\n\n return VirtualMailbox.$q.all(promises);\n };\n\n /**\n * @function $copyMessages\n * @memberof VirtualMailbox.prototype\n * @desc Copy multiple messages from the current mailbox to a target one\n * @param {object} messagesMap\n * @param {string} folder\n * @return a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$copyMessages = function(messagesMap, folder) {\n var promises = [];\n\n _.forEach(messagesMap, function(messages, id) {\n if (messages.length > 0) {\n var mailbox = messages[0].$mailbox;\n var promise = mailbox.$copyMessages(messages, folder);\n promises.push(promise);\n }\n });\n\n return VirtualMailbox.$q.all(promises);\n };\n\n /**\n * @function $moveMessages\n * @memberof VirtualMailbox.prototype\n * @desc Move multiple messages from the current mailbox to a target one\n * @param {object} messagesMap\n * @param {string} folder\n * @return a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$moveMessages = function(messagesMap, folder) {\n var promises = [];\n\n _.forEach(messagesMap, function(messages, id) {\n if (messages.length > 0) {\n var mailbox = messages[0].$mailbox;\n var promise = mailbox.$moveMessages(messages, folder);\n promises.push(promise);\n }\n });\n\n return VirtualMailbox.$q.all(promises);\n };\n\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n MailboxController.$inject = ['$window', '$scope', '$timeout', '$q', '$state', '$mdDialog', '$mdToast', 'stateAccounts', 'stateAccount', 'stateMailbox', 'sgHotkeys', 'encodeUriFilter', 'sgSettings', 'sgFocus', 'Dialog', 'Account', 'Mailbox'];\n function MailboxController($window, $scope, $timeout, $q, $state, $mdDialog, $mdToast, stateAccounts, stateAccount, stateMailbox, sgHotkeys, encodeUriFilter, sgSettings, focus, Dialog, Account, Mailbox) {\n var vm = this,\n defaultWindowTitle = angular.element($window.document).find('title').attr('sg-default') || \"SOGo\",\n hotkeys = [];\n\n // Expose controller for eventual popup windows\n $window.$mailboxController = vm;\n\n vm.service = Mailbox;\n vm.accounts = stateAccounts;\n vm.account = stateAccount;\n vm.selectedFolder = stateMailbox;\n vm.selectMessage = selectMessage;\n vm.messageDialog = null; // also access from Message controller\n vm.toggleMessageSelection = toggleMessageSelection;\n vm.sort = sort;\n vm.sortedBy = sortedBy;\n vm.searchMode = searchMode;\n vm.cancelSearch = cancelSearch;\n vm.newMessage = newMessage;\n vm.mode = { search: false, multiple: 0 };\n vm.confirmDeleteSelectedMessages = confirmDeleteSelectedMessages;\n vm.markOrUnMarkMessagesAsJunk = markOrUnMarkMessagesAsJunk;\n vm.copySelectedMessages = copySelectedMessages;\n vm.moveSelectedMessages = moveSelectedMessages;\n vm.markSelectedMessagesAsFlagged = markSelectedMessagesAsFlagged;\n vm.markSelectedMessagesAsUnread = markSelectedMessagesAsUnread;\n vm.markSelectedMessagesAsRead = markSelectedMessagesAsRead;\n vm.selectAll = selectAll;\n vm.unselectMessages = unselectMessages;\n\n\n stateMailbox.selectFolder();\n\n _registerHotkeys(hotkeys);\n\n // Expunge mailbox when leaving the Mail module\n angular.element($window).on('beforeunload', _compactBeforeUnload);\n $scope.$on('$destroy', function() {\n angular.element($window).off('beforeunload', _compactBeforeUnload);\n // Deregister hotkeys\n _.forEach(hotkeys, function(key) {\n sgHotkeys.deregisterHotkey(key);\n });\n });\n\n // Update window's title with unseen messages count of selected mailbox\n $scope.$watch(function() { return vm.selectedFolder.unseenCount; }, function(unseenCount) {\n var title = defaultWindowTitle + ' - ';\n if (unseenCount)\n title += '(' + unseenCount + ') ';\n title += vm.selectedFolder.name;\n $window.document.title = title;\n });\n\n\n function _registerHotkeys(keys) {\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_search'),\n description: l('Search'),\n callback: searchMode\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_compose'),\n description: l('Write a new message'),\n callback: function($event) {\n if (vm.messageDialog === null)\n newMessage($event);\n }\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_junk'),\n description: l('Mark the selected messages as junk'),\n callback: markOrUnMarkMessagesAsJunk\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'space',\n description: l('Toggle item'),\n callback: toggleMessageSelection\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'shift+space',\n description: l('Toggle range of items'),\n callback: toggleMessageSelection\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'up',\n description: l('View next item'),\n callback: _nextMessage,\n preventInClass: ['sg-mail-part']\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'down',\n description: l('View previous item'),\n callback: _previousMessage,\n preventInClass: ['sg-mail-part']\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'shift+up',\n description: l('Add next item to selection'),\n callback: _addNextMessageToSelection,\n preventInClass: ['sg-mail-part']\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'shift+down',\n description: l('Add previous item to selection'),\n callback: _addPreviousMessageToSelection,\n preventInClass: ['sg-mail-part']\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'backspace',\n description: l('Delete selected message or folder'),\n callback: confirmDeleteSelectedMessages\n }));\n\n // Register the hotkeys\n _.forEach(keys, function(key) {\n sgHotkeys.registerHotkey(key);\n });\n }\n\n function _compactBeforeUnload(event) {\n return vm.selectedFolder.$compact();\n }\n\n function sort(field) {\n vm.selectedFolder.$filter({ sort: field });\n }\n\n function sortedBy(field) {\n return Mailbox.$query.sort == field;\n }\n\n function searchMode() {\n vm.mode.search = true;\n focus('search');\n }\n\n function cancelSearch() {\n vm.mode.search = false;\n vm.selectedFolder.$filter().then(function() {\n if (vm.selectedFolder.selectedMessage) {\n $timeout(function() {\n vm.selectedFolder.$topIndex = vm.selectedFolder.uidsMap[vm.selectedFolder.selectedMessage];\n });\n }\n });\n }\n\n function newMessage($event, inPopup) {\n var message;\n\n if (vm.messageDialog === null) {\n if (inPopup)\n _newMessageInPopup();\n else {\n message = vm.account.$newMessage();\n vm.messageDialog = $mdDialog\n .show({\n parent: angular.element(document.body),\n targetEvent: $event,\n clickOutsideToClose: false,\n escapeToClose: false,\n templateUrl: 'UIxMailEditor',\n controller: 'MessageEditorController',\n controllerAs: 'editor',\n locals: {\n stateAccount: vm.account,\n stateMessage: message\n }\n })\n .finally(function() {\n vm.messageDialog = null;\n });\n }\n }\n }\n\n function _newMessageInPopup() {\n var url = [sgSettings.baseURL(),\n 'UIxMailPopupView#!/Mail',\n vm.account.id,\n // The double-encoding is necessary\n encodeUriFilter(encodeUriFilter(vm.selectedFolder.path)),\n 'new']\n .join('/'),\n wId = vm.selectedFolder.$id() + '/' + Math.random(0, 1000);\n console.debug(url);\n $window.open(url, wId,\n [\"width=680\",\n \"height=520\",\n \"resizable=1\",\n \"scrollbars=1\",\n \"toolbar=0\",\n \"location=0\",\n \"directories=0\",\n \"status=0\",\n \"menubar=0\",\n \"copyhistory=0\"]\n .join(','));\n }\n\n /**\n * User has pressed up arrow key\n */\n function _nextMessage($event) {\n var index = vm.selectedFolder.$selectedMessageIndex();\n\n if (angular.isDefined(index)) {\n index--;\n if (vm.selectedFolder.$topIndex > 0)\n vm.selectedFolder.$topIndex--;\n }\n else {\n // No message is selected, show oldest message\n index = vm.selectedFolder.getLength() - 1;\n vm.selectedFolder.$topIndex = vm.selectedFolder.getLength();\n }\n\n if (index > -1)\n selectMessage(vm.selectedFolder.$messages[index]);\n\n $event.preventDefault();\n\n return index;\n }\n\n /**\n * User has pressed the down arrow key\n */\n function _previousMessage($event) {\n var index = vm.selectedFolder.$selectedMessageIndex();\n\n if (angular.isDefined(index)) {\n index++;\n if (vm.selectedFolder.$topIndex < vm.selectedFolder.getLength())\n vm.selectedFolder.$topIndex++;\n }\n else\n // No message is selected, show newest\n index = 0;\n\n if (index < vm.selectedFolder.getLength())\n selectMessage(vm.selectedFolder.$messages[index]);\n else\n index = -1;\n\n $event.preventDefault();\n\n return index;\n }\n\n function _addNextMessageToSelection($event) {\n var index;\n\n if (vm.selectedFolder.hasSelectedMessage()) {\n index = _nextMessage($event);\n if (index >= 0)\n toggleMessageSelection($event, vm.selectedFolder.$messages[index]);\n }\n }\n\n function _addPreviousMessageToSelection($event) {\n var index;\n\n if (vm.selectedFolder.hasSelectedMessage()) {\n index = _previousMessage($event);\n if (index >= 0)\n toggleMessageSelection($event, vm.selectedFolder.$messages[index]);\n }\n }\n\n function selectMessage(message) {\n if (Mailbox.$virtualMode)\n $state.go('mail.account.virtualMailbox.message', {mailboxId: encodeUriFilter(message.$mailbox.path), messageId: message.uid});\n else\n $state.go('mail.account.mailbox.message', {messageId: message.uid});\n }\n\n function toggleMessageSelection($event, message) {\n var folder = vm.selectedFolder,\n selectedIndex, nextSelectedIndex, i;\n\n if (!message)\n message = folder.$selectedMessage();\n message.selected = !message.selected;\n vm.mode.multiple += message.selected? 1 : -1;\n\n // Select closest range of messages when shift key is pressed\n if ($event.shiftKey && folder.$selectedCount() > 1) {\n selectedIndex = folder.uidsMap[message.uid];\n // Search for next selected message above\n nextSelectedIndex = selectedIndex - 2;\n while (nextSelectedIndex >= 0 &&\n !folder.$messages[nextSelectedIndex].selected)\n nextSelectedIndex--;\n if (nextSelectedIndex < 0) {\n // Search for next selected message bellow\n nextSelectedIndex = selectedIndex + 2;\n while (nextSelectedIndex < folder.getLength() &&\n !folder.$messages[nextSelectedIndex].selected)\n nextSelectedIndex++;\n }\n if (nextSelectedIndex >= 0 && nextSelectedIndex < folder.getLength()) {\n for (i = Math.min(selectedIndex, nextSelectedIndex);\n i <= Math.max(selectedIndex, nextSelectedIndex);\n i++)\n folder.$messages[i].selected = true;\n }\n }\n\n $event.preventDefault();\n $event.stopPropagation();\n }\n\n /**\n * Batch operations\n */\n\n function _currentMailboxes() {\n if (Mailbox.$virtualMode)\n return vm.selectedFolder.$mailboxes;\n else\n return [vm.selectedFolder];\n }\n\n // Unselect current message and cleverly load the next message.\n // This function must not be called in virtual mode.\n function _unselectMessage(message, index) {\n var nextMessage, previousMessage, nextIndex = index;\n vm.mode.multiple = vm.selectedFolder.$selectedCount();\n if (message) {\n // Select either the next or previous message\n if (index > 0) {\n nextIndex -= 1;\n nextMessage = vm.selectedFolder.$messages[nextIndex];\n }\n if (index < vm.selectedFolder.$messages.length)\n previousMessage = vm.selectedFolder.$messages[index];\n if (nextMessage) {\n if (nextMessage.isread && previousMessage && !previousMessage.isread) {\n nextIndex = index;\n nextMessage = previousMessage;\n }\n }\n else if (previousMessage) {\n nextIndex = index;\n nextMessage = previousMessage;\n }\n if (nextMessage) {\n vm.selectedFolder.$topIndex = nextIndex;\n $state.go('mail.account.mailbox.message', { messageId: nextMessage.uid });\n }\n else {\n $state.go('mail.account.mailbox');\n }\n }\n else {\n $timeout(function() {\n console.warn('go to mailbox');\n $state.go('mail.account.mailbox');\n });\n }\n }\n\n function confirmDeleteSelectedMessages($event) {\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n\n if (vm.messageDialog === null && _.size(selectedMessages) > 0)\n vm.messageDialog = Dialog.confirm(l('Confirmation'),\n l('Are you sure you want to delete the selected messages?'),\n { ok: l('Delete') })\n .then(function() {\n var deleteSelectedMessage = vm.selectedFolder.hasSelectedMessage();\n vm.selectedFolder.$deleteMessages(selectedMessages).then(function(index) {\n if (Mailbox.$virtualMode) {\n // When performing an advanced search, we refresh the view if the selected message\n // was deleted, but only once all promises have completed.\n if (deleteSelectedMessage)\n $state.go('mail.account.virtualMailbox');\n }\n else {\n // In normal mode, we immediately unselect the selected message.\n _unselectMessage(deleteSelectedMessage, index);\n }\n }, function(response) {\n vm.messageDialog = Dialog.confirm(l('Warning'),\n l('The messages could not be moved to the trash folder. Would you like to delete them immediately?'),\n { ok: l('Delete') })\n .then(function() {\n vm.selectedFolder.$deleteMessages(selectedMessages, { withoutTrash: true }).then(function(index) {\n if (Mailbox.$virtualMode) {\n // When performing an advanced search, we refresh the view if the selected message\n // was deleted, but only once all promises have completed.\n if (deleteSelectedMessage)\n $state.go('mail.account.virtualMailbox');\n }\n else {\n // In normal mode, we immediately unselect the selected message.\n _unselectMessage(deleteSelectedMessage, index);\n }\n });\n });\n });\n })\n .finally(function() {\n vm.messageDialog = null;\n });\n\n $event.preventDefault();\n }\n\n function markOrUnMarkMessagesAsJunk() {\n var moveSelectedMessage = vm.selectedFolder.hasSelectedMessage();\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n if (_.size(selectedMessages) === 0 && moveSelectedMessage)\n selectedMessages = [vm.selectedFolder.$selectedMessage()];\n if (_.size(selectedMessages) > 0)\n vm.selectedFolder.$markOrUnMarkMessagesAsJunk(selectedMessages).then(function() {\n var dstFolder = '/' + vm.account.id + '/folderINBOX';\n if (vm.selectedFolder.type != 'junk') {\n dstFolder = '/' + vm.account.$getMailboxByType('junk').id;\n }\n vm.selectedFolder.$moveMessages(selectedMessages, dstFolder).then(function(index) {\n if (Mailbox.$virtualMode) {\n // When performing an advanced search, we refresh the view if the selected message\n // was deleted, but only once all promises have completed.\n if (moveSelectedMessage)\n $state.go('mail.account.virtualMailbox');\n }\n else {\n // In normal mode, we immediately unselect the selected message.\n _unselectMessage(moveSelectedMessage, index);\n }\n });\n });\n }\n\n function copySelectedMessages(dstFolder) {\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n if (_.size(selectedMessages) > 0)\n vm.selectedFolder.$copyMessages(selectedMessages, '/' + dstFolder).then(function() {\n $mdToast.show(\n $mdToast.simple()\n .content(l('%{0} message(s) copied', vm.selectedFolder.$selectedCount()))\n .position('top right')\n .hideDelay(2000));\n });\n }\n\n function moveSelectedMessages(dstFolder) {\n var moveSelectedMessage = vm.selectedFolder.hasSelectedMessage();\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n var count = vm.selectedFolder.$selectedCount();\n if (_.size(selectedMessages) > 0)\n vm.selectedFolder.$moveMessages(selectedMessages, '/' + dstFolder).then(function(index) {\n $mdToast.show(\n $mdToast.simple()\n .content(l('%{0} message(s) moved', count))\n .position('top right')\n .hideDelay(2000));\n if (Mailbox.$virtualMode) {\n // When performing an advanced search, we refresh the view if the selected message\n // was moved, but only once all promises have completed.\n if (moveSelectedMessage)\n $state.go('mail.account.virtualMailbox');\n }\n else {\n // In normal mode, we immediately unselect the selected message.\n _unselectMessage(moveSelectedMessage, index);\n }\n });\n }\n\n function selectAll() {\n var count = 0;\n _.forEach(_currentMailboxes(), function(folder) {\n var i = 0, length = folder.$messages.length;\n for (; i < length; i++)\n folder.$messages[i].selected = true;\n count += length;\n });\n vm.mode.multiple = count;\n }\n\n function unselectMessages() {\n _.forEach(_currentMailboxes(), function(folder) {\n _.forEach(folder.$messages, function(message) {\n message.selected = false;\n });\n });\n vm.mode.multiple = 0;\n }\n\n function markSelectedMessagesAsFlagged() {\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n if (_.size(selectedMessages) > 0)\n vm.selectedFolder.$flagMessages(selectedMessages, '\\\\Flagged', 'add').then(function(messages) {\n _.forEach(messages, function(message) {\n message.isflagged = true;\n });\n });\n }\n\n function markSelectedMessagesAsUnread() {\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n if (_.size(selectedMessages) > 0) {\n vm.selectedFolder.$flagMessages(selectedMessages, 'seen', 'remove').then(function(messages) {\n _.forEach(messages, function(message) {\n if (message.isread)\n message.$mailbox.unseenCount++;\n message.isread = false;\n });\n });\n }\n }\n\n function markSelectedMessagesAsRead() {\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n if (_.size(selectedMessages) > 0) {\n vm.selectedFolder.$flagMessages(selectedMessages, 'seen', 'add').then(function(messages) {\n _.forEach(messages, function(message) {\n if (!message.isread)\n message.$mailbox.unseenCount--;\n message.isread = true;\n });\n });\n }\n }\n\n }\n\n angular\n .module('material.components.virtualRepeat')\n .decorator('mdVirtualRepeatContainerDirective', mdVirtualRepeatContainerDirectiveDecorator);\n\n /**\n * @ngInject\n */\n mdVirtualRepeatContainerDirectiveDecorator.$inject = ['$delegate'];\n function mdVirtualRepeatContainerDirectiveDecorator($delegate) {\n $delegate[0].controller.prototype.resetScroll = function() {\n // Don't scroll to top if current virtual repeater is the messages list\n // but do update the container size\n if (this.$element.parent().attr('id') == 'messagesList')\n this.updateSize();\n else\n this.scrollTo(0);\n };\n return $delegate;\n }\n\n angular\n .module('SOGo.MailerUI')\n .controller('MailboxController', MailboxController);\n})();\n\n","/* -*- Mode: js; indent-tabs-mode: nil; js-indent-level: 2; -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n MailboxesController.$inject = ['$scope', '$state', '$timeout', '$window', '$mdDialog', '$mdToast', '$mdMedia', '$mdSidenav', 'sgConstant', 'sgFocus', 'encodeUriFilter', 'Dialog', 'sgSettings', 'sgHotkeys', 'Account', 'Mailbox', 'VirtualMailbox', 'User', 'Preferences', 'stateAccounts'];\n function MailboxesController($scope, $state, $timeout, $window, $mdDialog, $mdToast, $mdMedia, $mdSidenav, sgConstant, focus, encodeUriFilter, Dialog, Settings, sgHotkeys, Account, Mailbox, VirtualMailbox, User, Preferences, stateAccounts) {\n var vm = this,\n account,\n mailbox,\n hotkeys = [];\n\n vm.service = Mailbox;\n vm.accounts = stateAccounts;\n vm.toggleAccountState = toggleAccountState;\n vm.subscribe = subscribe;\n vm.newFolder = newFolder;\n vm.delegate = delegate;\n vm.editFolder = editFolder;\n vm.revertEditing = revertEditing;\n vm.selectFolder = selectFolder;\n vm.saveFolder = saveFolder;\n vm.compactFolder = compactFolder;\n vm.emptyTrashFolder = emptyTrashFolder;\n vm.confirmDelete = confirmDelete;\n vm.markFolderRead = markFolderRead;\n vm.share = share;\n vm.metadataForFolder = metadataForFolder;\n vm.setFolderAs = setFolderAs;\n vm.refreshUnseenCount = refreshUnseenCount;\n vm.isDroppableFolder = isDroppableFolder;\n vm.dragSelectedMessages = dragSelectedMessages;\n\n // Advanced search options\n vm.showingAdvancedSearch = false;\n vm.currentSearchParam = '';\n vm.addSearchParam = addSearchParam;\n vm.newSearchParam = newSearchParam;\n vm.showAdvancedSearch = showAdvancedSearch;\n vm.hideAdvancedSearch = hideAdvancedSearch;\n vm.toggleAdvancedSearch = toggleAdvancedSearch;\n vm.search = {\n options: {'': '', // no placeholder when no criteria is active\n subject: l('Enter Subject'),\n from: l('Enter From'),\n to: l('Enter To'),\n cc: l('Enter Cc'),\n body: l('Enter Body')\n },\n mailbox: 'INBOX',\n subfolders: 1,\n match: 'AND',\n params: []\n };\n\n\n Preferences.ready().then(function() {\n vm.showSubscribedOnly = Preferences.defaults.SOGoMailShowSubscribedFoldersOnly;\n });\n\n vm.refreshUnseenCount();\n\n _registerHotkeys(hotkeys);\n\n $scope.$on('$destroy', function() {\n // Deregister hotkeys\n _.forEach(hotkeys, function(key) {\n sgHotkeys.deregisterHotkey(key);\n });\n });\n\n\n function _registerHotkeys(keys) {\n keys.push(sgHotkeys.createHotkey({\n key: 'backspace',\n description: l('Delete selected message or folder'),\n callback: function() {\n if (Mailbox.selectedFolder && !Mailbox.selectedFolder.hasSelectedMessage())\n confirmDelete(Mailbox.selectedFolder);\n }\n }));\n\n // Register the hotkeys\n _.forEach(keys, function(key) {\n sgHotkeys.registerHotkey(key);\n });\n }\n\n function showAdvancedSearch(path) {\n vm.showingAdvancedSearch = true;\n vm.search.mailbox = path;\n // Close sidenav on small devices\n if (!$mdMedia(sgConstant['gt-md']))\n $mdSidenav('left').close();\n }\n\n function hideAdvancedSearch() {\n vm.showingAdvancedSearch = false;\n vm.service.$virtualMode = false;\n\n account = vm.accounts[0];\n mailbox = vm.searchPreviousMailbox;\n $state.go('mail.account.mailbox', { accountId: account.id, mailboxId: encodeUriFilter(mailbox.path) });\n }\n\n function toggleAdvancedSearch() {\n if (Mailbox.selectedFolder.$isLoading) {\n // Stop search\n vm.virtualMailbox.stopSearch();\n }\n else {\n // Start search\n var root, mailboxes = [],\n _visit = function(folders) {\n _.forEach(folders, function(o) {\n mailboxes.push(o);\n if (o.children && o.children.length > 0) {\n _visit(o.children);\n }\n });\n };\n\n vm.virtualMailbox = new VirtualMailbox(vm.accounts[0]);\n\n // Don't set the previous selected mailbox if we're in virtual mode\n // That allows users to do multiple advanced search but return\n // correctly to the previously selected mailbox once done.\n if (!Mailbox.$virtualMode)\n vm.searchPreviousMailbox = Mailbox.selectedFolder;\n\n Mailbox.selectedFolder = vm.virtualMailbox;\n Mailbox.$virtualMode = true;\n\n if (angular.isDefined(vm.search.mailbox)) {\n root = vm.accounts[0].$getMailboxByPath(vm.search.mailbox);\n mailboxes.push(root);\n if (vm.search.subfolders && root.children.length)\n _visit(root.children);\n }\n else {\n mailboxes = vm.accounts[0].$flattenMailboxes();\n }\n\n vm.virtualMailbox.setMailboxes(mailboxes);\n vm.virtualMailbox.startSearch(vm.search.match, vm.search.params);\n $state.go('mail.account.virtualMailbox', { accountId: vm.accounts[0].id });\n }\n }\n\n function addSearchParam(v) {\n vm.currentSearchParam = v;\n focus('advancedSearch');\n return false;\n }\n\n function newSearchParam(pattern) {\n if (pattern.length && vm.currentSearchParam.length) {\n var n = 0, searchParam = vm.currentSearchParam;\n if (pattern.startsWith(\"!\")) {\n n = 1;\n pattern = pattern.substring(1).trim();\n }\n vm.currentSearchParam = '';\n return { searchBy: searchParam, searchInput: pattern, negative: n };\n }\n }\n\n function toggleAccountState(account) {\n account.$expanded = !account.$expanded;\n account.$flattenMailboxes({ reload: true, saveState: true });\n // Fire a window resize to recompute the virtual-repeater.\n // This is a fix until the following issue is officially resolved:\n // https://github.com/angular/material/issues/7309\n $timeout(function() {\n angular.element($window).triggerHandler('resize');\n }, 150);\n }\n\n function subscribe(account) {\n $mdDialog.show({\n templateUrl: account.id + '/subscribe',\n controller: SubscriptionsDialogController,\n controllerAs: 'subscriptions',\n clickOutsideToClose: true,\n escapeToClose: true,\n locals: {\n metadataForFolder: metadataForFolder,\n srcAccount: account\n }\n }).finally(function() {\n account.$getMailboxes({reload: true});\n });\n\n /**\n * @ngInject\n */\n SubscriptionsDialogController.$inject = ['$scope', '$mdDialog', 'metadataForFolder', 'srcAccount'];\n function SubscriptionsDialogController($scope, $mdDialog, metadataForFolder, srcAccount) {\n var vm = this;\n\n vm.loading = true;\n vm.filter = { name: '' };\n vm.metadataForFolder = metadataForFolder;\n vm.account = new Account({\n id: srcAccount.id,\n name: srcAccount.name\n });\n vm.close = close;\n\n vm.account.$getMailboxes({ reload: true, all: true }).then(function() {\n vm.loading = false;\n });\n\n function close() {\n $mdDialog.cancel();\n }\n }\n }\n\n function newFolder(parentFolder) {\n Dialog.prompt(l('New Folder...'),\n l('Enter the new name of your folder'))\n .then(function(name) {\n parentFolder.$newMailbox(parentFolder.id, name)\n .then(function() {\n // success\n }, function(data, status) {\n Dialog.alert(l('An error occured while creating the mailbox \"%{0}\".', name),\n l(data.error));\n });\n });\n }\n\n function delegate(account) {\n $mdDialog.show({\n templateUrl: account.id + '/delegation', // UI/Templates/MailerUI/UIxMailUserDelegation.wox\n controller: MailboxDelegationController,\n controllerAs: 'delegate',\n clickOutsideToClose: true,\n escapeToClose: true,\n locals: {\n User: User,\n account: account\n }\n });\n\n /**\n * @ngInject\n */\n MailboxDelegationController.$inject = ['$scope', '$mdDialog', 'User', 'account'];\n function MailboxDelegationController($scope, $mdDialog, User, account) {\n var vm = this;\n\n vm.users = account.delegates;\n vm.account = account;\n vm.userToAdd = '';\n vm.searchText = '';\n vm.userFilter = userFilter;\n vm.closeModal = closeModal;\n vm.removeUser = removeUser;\n vm.addUser = addUser;\n\n function userFilter($query) {\n return User.$filter($query, account.delegates);\n }\n\n function closeModal() {\n $mdDialog.hide();\n }\n\n function removeUser(user) {\n account.$removeDelegate(user.uid).catch(function(data, status) {\n Dialog.alert(l('Warning'), l('An error occured please try again.'));\n });\n }\n\n function addUser(data) {\n if (data) {\n account.$addDelegate(data).then(function() {\n vm.userToAdd = '';\n vm.searchText = '';\n }, function(error) {\n Dialog.alert(l('Warning'), error);\n });\n }\n }\n }\n } // delegate\n\n function editFolder(folder) {\n vm.editMode = folder.path;\n focus('mailboxName_' + folder.path);\n }\n\n function revertEditing(folder) {\n folder.$reset();\n vm.editMode = false;\n }\n\n function selectFolder($event, account, folder) {\n if (vm.editMode == folder.path)\n return;\n vm.editMode = false;\n vm.showingAdvancedSearch = false;\n vm.service.$virtualMode = false;\n // Close sidenav on small devices\n if (!$mdMedia(sgConstant['gt-md']))\n $mdSidenav('left').close();\n $state.go('mail.account.mailbox', { accountId: account.id, mailboxId: encodeUriFilter(folder.path) });\n $event.stopPropagation();\n $event.preventDefault();\n }\n\n function saveFolder(folder) {\n folder.$rename()\n .then(function(data) {\n vm.editMode = false;\n });\n }\n\n function compactFolder(folder) {\n folder.$compact().then(function() {\n $mdToast.show(\n $mdToast.simple()\n .content(l('Folder compacted'))\n .position('top right')\n .hideDelay(3000));\n });\n }\n\n function emptyTrashFolder(folder) {\n folder.$emptyTrash().then(function() {\n $mdToast.show(\n $mdToast.simple()\n .content(l('Trash emptied'))\n .position('top right')\n .hideDelay(3000));\n });\n }\n\n function confirmDelete(folder) {\n Dialog.confirm(l('Warning'),\n l('Do you really want to move this folder into the trash ?'),\n { ok: l('Delete') })\n .then(function() {\n folder.$delete()\n .then(function() {\n $state.go('mail.account.inbox');\n }, function(response) {\n Dialog.confirm(l('Warning'),\n l('The mailbox could not be moved to the trash folder. Would you like to delete it immediately?'),\n { ok: l('Delete') })\n .then(function() {\n folder.$delete({ withoutTrash: true })\n .then(function() {\n $state.go('mail.account.inbox');\n }, function(response) {\n Dialog.alert(l('An error occured while deleting the mailbox \"%{0}\".', folder.name),\n l(response.error));\n });\n });\n });\n });\n }\n\n function markFolderRead(folder) {\n folder.$markAsRead();\n }\n\n function share(folder) {\n // Fetch list of ACL users\n folder.$acl.$users().then(function() {\n // Show ACL editor\n $mdDialog.show({\n templateUrl: folder.id + '/UIxAclEditor', // UI/Templates/UIxAclEditor.wox\n controller: 'AclController', // from the ng module SOGo.Common\n controllerAs: 'acl',\n clickOutsideToClose: true,\n escapeToClose: true,\n locals: {\n usersWithACL: folder.$acl.users,\n User: User,\n folder: folder\n }\n });\n });\n } // share\n\n function metadataForFolder(folder) {\n if (folder.type == 'inbox')\n return {name: folder.name, icon:'inbox', special: true};\n else if (folder.type == 'draft')\n return {name: l('DraftsFolderName'), icon: 'drafts', special: true};\n else if (folder.type == 'sent')\n return {name: l('SentFolderName'), icon: 'send', special: true};\n else if (folder.type == 'trash')\n return {name: l('TrashFolderName'), icon: 'delete', special: true};\n else if (folder.type == 'junk')\n return {name: l('JunkFolderName'), icon: 'thumb_down', special: true};\n else if (folder.type == 'additional')\n return {name: folder.name, icon: 'folder_shared', special: true};\n\n return {name: folder.name, icon: 'folder_open', special: false};\n }\n\n function setFolderAs(folder, type) {\n folder.$setFolderAs(type).then(function() {\n folder.$account.$getMailboxes({reload: true});\n });\n }\n\n function refreshUnseenCount() {\n var unseenCountFolders = $window.unseenCountFolders;\n\n _.forEach(vm.accounts, function(account) {\n\n // Always include the INBOX\n if (!_.includes(unseenCountFolders, account.id + '/folderINBOX'))\n unseenCountFolders.push(account.id + '/folderINBOX');\n\n _.forEach(account.$$flattenMailboxes, function(mailbox) {\n if (angular.isDefined(mailbox.unseenCount) &&\n !_.includes(unseenCountFolders, mailbox.id))\n unseenCountFolders.push(mailbox.id);\n });\n });\n\n Account.$$resource.post('', 'unseenCount', {mailboxes: unseenCountFolders}).then(function(data) {\n _.forEach(vm.accounts, function(account) {\n _.forEach(account.$$flattenMailboxes, function(mailbox) {\n if (data[mailbox.id])\n mailbox.unseenCount = data[mailbox.id];\n });\n });\n });\n\n Preferences.ready().then(function() {\n var refreshViewCheck = Preferences.defaults.SOGoRefreshViewCheck;\n if (refreshViewCheck && refreshViewCheck != 'manually')\n $timeout(vm.refreshUnseenCount, refreshViewCheck.timeInterval()*1000);\n });\n }\n\n function isDroppableFolder(srcFolder, dstFolder) {\n return (dstFolder.id != srcFolder.id) && !dstFolder.isNoSelect();\n }\n\n function dragSelectedMessages(srcFolder, dstFolder, mode) {\n var dstId, messages, uids, clearMessageView, promise, success;\n\n dstId = '/' + dstFolder.id;\n messages = srcFolder.$selectedMessages();\n if (messages.length === 0)\n messages = [srcFolder.$selectedMessage()];\n uids = _.map(messages, 'uid');\n clearMessageView = (srcFolder.selectedMessage && uids.indexOf(srcFolder.selectedMessage) >= 0);\n\n if (mode == 'copy') {\n promise = srcFolder.$copyMessages(messages, dstId);\n success = l('%{0} message(s) copied', messages.length);\n }\n else {\n promise = srcFolder.$moveMessages(messages, dstId);\n success = l('%{0} message(s) moved', messages.length);\n }\n\n promise.then(function() {\n if (clearMessageView)\n $state.go('mail.account.mailbox');\n $mdToast.show(\n $mdToast.simple()\n .content(success)\n .position('top right')\n .hideDelay(2000));\n });\n }\n\n }\n\n angular\n .module('SOGo.MailerUI')\n .controller('MailboxesController', MailboxesController);\n})();\n\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n MessageController.$inject = ['$window', '$scope', '$state', '$mdMedia', '$mdDialog', 'sgConstant', 'stateAccounts', 'stateAccount', 'stateMailbox', 'stateMessage', 'sgHotkeys', 'encodeUriFilter', 'sgSettings', 'sgFocus', 'Dialog', 'Calendar', 'Component', 'Account', 'Mailbox', 'Message'];\n function MessageController($window, $scope, $state, $mdMedia, $mdDialog, sgConstant, stateAccounts, stateAccount, stateMailbox, stateMessage, sgHotkeys, encodeUriFilter, sgSettings, focus, Dialog, Calendar, Component, Account, Mailbox, Message) {\n var vm = this, popupWindow = null, hotkeys = [];\n\n // Expose controller\n $window.$messageController = vm;\n\n vm.$state = $state;\n vm.accounts = stateAccounts;\n vm.account = stateAccount;\n vm.mailbox = stateMailbox;\n vm.message = stateMessage;\n vm.service = Message;\n vm.tags = { searchText: '', selected: '' };\n vm.showFlags = stateMessage.flags && stateMessage.flags.length > 0;\n vm.$showDetailedRecipients = false;\n vm.toggleDetailedRecipients = toggleDetailedRecipients;\n vm.filterMailtoLinks = filterMailtoLinks;\n vm.deleteMessage = deleteMessage;\n vm.close = close;\n vm.reply = reply;\n vm.replyAll = replyAll;\n vm.forward = forward;\n vm.edit = edit;\n vm.openPopup = openPopup;\n vm.closePopup = closePopup;\n vm.newMessage = newMessage;\n vm.toggleRawSource = toggleRawSource;\n vm.showRawSource = false;\n vm.print = print;\n vm.convertToEvent = convertToEvent;\n vm.convertToTask = convertToTask;\n\n _registerHotkeys(hotkeys);\n\n // One-way refresh of the parent window when modifying the message from a popup window.\n if ($window.opener) {\n // Update the message flags. The message must be displayed in the parent window.\n $scope.$watchCollection(function() { return vm.message.flags; }, function(newTags, oldTags) {\n var ctrls;\n if (newTags || oldTags) {\n ctrls = $parentControllers();\n if (ctrls.messageCtrl) {\n ctrls.messageCtrl.service.$timeout(function() {\n ctrls.messageCtrl.showFlags = true;\n ctrls.messageCtrl.message.flags = newTags;\n });\n }\n }\n });\n // Update the \"isflagged\" (star icon) of the message. The mailbox must be displayed in the parent window.\n $scope.$watch(function() { return vm.message.isflagged; }, function(isflagged, wasflagged) {\n var ctrls = $parentControllers();\n if (ctrls.mailboxCtrl) {\n ctrls.mailboxCtrl.service.$timeout(function() {\n var message = _.find(ctrls.mailboxCtrl.selectedFolder.$messages, { uid: vm.message.uid });\n message.isflagged = isflagged;\n });\n }\n });\n }\n else {\n // Flatten new tags when coming from the predefined list of tags (Message.$tags) and\n // sync tags with server when adding or removing a tag.\n $scope.$watchCollection(function() { return vm.message.flags; }, function(_newTags, _oldTags) {\n var newTags, oldTags, tags;\n if (_newTags || _oldTags) {\n newTags = _newTags || [];\n oldTags = _oldTags || [];\n _.forEach(newTags, function(tag, i) {\n if (angular.isObject(tag))\n newTags[i] = tag.name;\n });\n if (newTags.length > oldTags.length) {\n tags = _.difference(newTags, oldTags);\n _.forEach(tags, function(tag) {\n vm.message.addTag(tag);\n });\n }\n else if (newTags.length < oldTags.length) {\n tags = _.difference(oldTags, newTags);\n _.forEach(tags, function(tag) {\n vm.message.removeTag(tag);\n });\n }\n }\n });\n }\n\n $scope.$on('$destroy', function() {\n // Deregister hotkeys\n _.forEach(hotkeys, function(key) {\n sgHotkeys.deregisterHotkey(key);\n });\n });\n\n\n /**\n * To keep track of the currently active dialog, we share a common variable with the parent controller.\n */\n function _messageDialog() {\n if ($scope.mailbox) {\n if (arguments.length > 0)\n $scope.mailbox.messageDialog = arguments[0];\n return $scope.mailbox.messageDialog;\n }\n return null;\n }\n\n function _unlessInDialog(callback) {\n return function() {\n // Check if a dialog is opened either from the current controller or the parent controller\n if (_messageDialog() === null)\n return callback.apply(vm, arguments);\n };\n }\n\n function _registerHotkeys(keys) {\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_reply'),\n description: l('Reply to the message'),\n callback: _unlessInDialog(reply)\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_replyall'),\n description: l('Reply to sender and all recipients'),\n callback: _unlessInDialog(replyAll)\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_forward'),\n description: l('Forward selected message'),\n callback: _unlessInDialog(forward)\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_flag'),\n description: l('Flagged'),\n callback: _unlessInDialog(angular.bind(stateMessage, stateMessage.toggleFlag))\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'backspace',\n callback: _unlessInDialog(function($event) {\n if (vm.mailbox.$selectedCount() === 0)\n deleteMessage();\n $event.preventDefault();\n })\n }));\n\n // Register the hotkeys\n _.forEach(keys, function(key) {\n sgHotkeys.registerHotkey(key);\n });\n }\n\n /**\n * If this is a popup window, retrieve the matching controllers (mailbox and message) of the parent window.\n */\n function $parentControllers() {\n var message, mailbox, ctrls = {};\n if ($window.opener) {\n // Deleting the message from a popup window\n if ($window.opener.$mailboxController &&\n $window.opener.$mailboxController.selectedFolder.$id() == stateMailbox.$id()) {\n // The message mailbox is opened in the parent window\n mailbox = $window.opener.$mailboxController;\n ctrls.mailboxCtrl = mailbox;\n if ($window.opener.$messageController &&\n $window.opener.$messageController.message.uid == stateMessage.uid) {\n // The message is opened in the parent window\n message = $window.opener.$messageController;\n ctrls.messageCtrl = message;\n }\n }\n }\n return ctrls;\n }\n\n function toggleDetailedRecipients($event) {\n vm.$showDetailedRecipients = !vm.$showDetailedRecipients;\n $event.stopPropagation();\n $event.preventDefault();\n }\n\n function filterMailtoLinks($event) {\n var href, match, to, cc, bcc, subject, body, data;\n if ($event.target.tagName == 'A' && 'href' in $event.target.attributes) {\n href = $event.target.attributes.href.value;\n match = /^mailto:([^\\?]+)/.exec(href);\n if (match) {\n // Recipients\n to = _.map(decodeURIComponent(match[1]).split(','), function(email) {\n return '<' + email + '>';\n });\n data = { to: to };\n // Subject & body\n _.forEach(['subject', 'body'], function(param) {\n var re = new RegExp(param + '=([^&]+)');\n param = (param == 'body')? 'text' : param;\n match = re.exec(href);\n if (match)\n data[param] = [decodeURIComponent(match[1])];\n });\n // Recipients\n _.forEach(['cc', 'bcc'], function(param) {\n var re = new RegExp(param + '=([^&]+)');\n match = re.exec(href);\n if (match)\n data[param] = [decodeURIComponent(match[1])];\n });\n newMessage($event, data); // will stop event propagation\n }\n }\n }\n\n function deleteMessage() {\n var mailbox, message, state, nextMessage, previousMessage,\n parentCtrls = $parentControllers();\n\n if (parentCtrls.messageCtrl) {\n mailbox = parentCtrls.mailboxCtrl.selectedFolder;\n message = parentCtrls.messageCtrl.message;\n state = parentCtrls.messageCtrl.$state;\n }\n else {\n mailbox = stateMailbox;\n message = stateMessage;\n state = $state;\n }\n\n mailbox.$deleteMessages([message]).then(function(index) {\n var nextIndex = index;\n // Remove message object from scope\n message = null;\n if (angular.isDefined(state)) {\n // Select either the next or previous message\n if (index > 0) {\n nextIndex -= 1;\n nextMessage = mailbox.$messages[nextIndex];\n }\n if (index < mailbox.$messages.length)\n previousMessage = mailbox.$messages[index];\n\n if (nextMessage) {\n if (nextMessage.isread && previousMessage && !previousMessage.isread) {\n nextIndex = index;\n nextMessage = previousMessage;\n }\n }\n else if (previousMessage) {\n nextIndex = index;\n nextMessage = previousMessage;\n }\n\n try {\n if (nextMessage && $mdMedia(sgConstant['gt-md'])) {\n state.go('mail.account.mailbox.message', { messageId: nextMessage.uid });\n if (nextIndex < mailbox.$topIndex)\n mailbox.$topIndex = nextIndex;\n else if (nextIndex > mailbox.$lastVisibleIndex)\n mailbox.$topIndex = nextIndex - (mailbox.$lastVisibleIndex - mailbox.$topIndex);\n }\n else {\n state.go('mail.account.mailbox').then(function() {\n message = null;\n delete mailbox.selectedMessage;\n });\n }\n }\n catch (error) {}\n }\n closePopup();\n });\n }\n\n function showMailEditor($event, message) {\n if (_messageDialog() === null) {\n _messageDialog(\n $mdDialog\n .show({\n parent: angular.element(document.body),\n targetEvent: $event,\n clickOutsideToClose: false,\n escapeToClose: false,\n templateUrl: 'UIxMailEditor',\n controller: 'MessageEditorController',\n controllerAs: 'editor',\n locals: {\n stateAccount: vm.account,\n stateMessage: message\n }\n })\n .finally(function() {\n _messageDialog(null);\n closePopup();\n })\n );\n }\n }\n\n function close() {\n $state.go('mail.account.mailbox').then(function() {\n vm.message = null;\n delete stateMailbox.selectedMessage;\n });\n }\n\n function reply($event) {\n var message = vm.message.$reply();\n showMailEditor($event, message);\n }\n\n function replyAll($event) {\n var message = vm.message.$replyAll();\n showMailEditor($event, message);\n }\n\n function forward($event) {\n var message = vm.message.$forward();\n showMailEditor($event, message);\n }\n\n function edit($event) {\n vm.message.$editableContent().then(function() {\n showMailEditor($event, vm.message);\n });\n }\n\n function openPopup() {\n var url = [sgSettings.baseURL(),\n 'UIxMailPopupView#!/Mail',\n vm.message.accountId,\n // The double-encoding is necessary\n encodeUriFilter(encodeUriFilter(vm.message.$mailbox.path)),\n vm.message.uid]\n .join('/'),\n wId = vm.message.$absolutePath();\n popupWindow = $window.open(url, wId,\n [\"width=680\",\n \"height=520\",\n \"resizable=1\",\n \"scrollbars=1\",\n \"toolbar=0\",\n \"location=0\",\n \"directories=0\",\n \"status=0\",\n \"menubar=0\",\n \"copyhistory=0\"]\n .join(','));\n }\n\n function closePopup() {\n if ($window.opener)\n $window.close();\n }\n\n function newMessage($event, editableContent) {\n vm.account.$newMessage().then(function(message) {\n angular.extend(message.editable, editableContent);\n showMailEditor($event, message);\n });\n $event.stopPropagation();\n $event.preventDefault();\n }\n\n function toggleRawSource($event) {\n if (!vm.showRawSource && !vm.message.$rawSource) {\n Message.$$resource.post(vm.message.id, \"viewsource\").then(function(data) {\n vm.message.$rawSource = data;\n vm.showRawSource = true;\n });\n }\n else {\n vm.showRawSource = !vm.showRawSource;\n }\n }\n\n function print($event) {\n $window.print();\n }\n\n function convertToEvent($event) {\n return convertToComponent($event, 'appointment');\n }\n\n function convertToTask($event) {\n return convertToComponent($event, 'task');\n }\n\n function convertToComponent($event, type) {\n vm.message.$plainContent().then(function(data) {\n var componentData = {\n pid: Calendar.$defaultCalendar(),\n type: type,\n summary: data.subject,\n comment: data.content\n };\n var component = new Component(componentData);\n // UI/Templates/SchedulerUI/UIxAppointmentEditorTemplate.wox or\n // UI/Templates/SchedulerUI/UIxTaskEditorTemplate.wox\n var templateUrl = [\n sgSettings.activeUser('folderURL'),\n 'Calendar',\n 'UIx' + type.capitalize() + 'EditorTemplate'\n ].join('/');\n return $mdDialog.show({\n parent: angular.element(document.body),\n targetEvent: $event,\n clickOutsideToClose: true,\n escapeToClose: true,\n templateUrl: templateUrl,\n controller: 'ComponentEditorController',\n controllerAs: 'editor',\n locals: {\n stateComponent: component\n }\n });\n });\n }\n }\n \n angular\n .module('SOGo.MailerUI') \n .controller('MessageController', MessageController); \n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n MessageEditorController.$inject = ['$scope', '$window', '$stateParams', '$mdConstant', '$mdDialog', '$mdToast', 'FileUploader', 'stateAccount', 'stateMessage', 'encodeUriFilter', '$timeout', 'Dialog', 'AddressBook', 'Card', 'Preferences'];\n function MessageEditorController($scope, $window, $stateParams, $mdConstant, $mdDialog, $mdToast, FileUploader, stateAccount, stateMessage, encodeUriFilter, $timeout, Dialog, AddressBook, Card, Preferences) {\n var vm = this, hotkeys = [];\n\n vm.addRecipient = addRecipient;\n vm.autocomplete = {to: {}, cc: {}, bcc: {}};\n vm.autosave = null;\n vm.autosaveDrafts = autosaveDrafts;\n vm.cancel = cancel;\n vm.contactFilter = contactFilter;\n vm.isFullscreen = false;\n vm.hideBcc = (stateMessage.editable.bcc.length === 0);\n vm.hideCc = (stateMessage.editable.cc.length === 0);\n vm.identities = _.map(stateAccount.identities, 'full');\n vm.message = stateMessage;\n vm.recipientSeparatorKeys = [\n $mdConstant.KEY_CODE.ENTER,\n $mdConstant.KEY_CODE.TAB,\n $mdConstant.KEY_CODE.COMMA,\n $mdConstant.KEY_CODE.SEMICOLON\n ];\n vm.removeAttachment = removeAttachment;\n vm.save = save;\n vm.send = send;\n vm.sendState = false;\n vm.toggleFullscreen = toggleFullscreen;\n vm.uploader = new FileUploader({\n url: stateMessage.$absolutePath({asDraft: true}) + '/save',\n autoUpload: true,\n alias: 'attachments',\n removeAfterUpload: false,\n // onProgressItem: function(item, progress) {\n // console.debug(item); console.debug(progress);\n // },\n onSuccessItem: function(item, response, status, headers) {\n stateMessage.$setUID(response.uid);\n stateMessage.$reload({asDraft: false});\n item.inlineUrl = response.lastAttachmentAttrs[0].url;\n //console.debug(item); console.debug('success = ' + JSON.stringify(response, undefined, 2));\n },\n onCancelItem: function(item, response, status, headers) {\n //console.debug(item); console.debug('cancel = ' + JSON.stringify(response, undefined, 2));\n // We remove the attachment\n stateMessage.$deleteAttachment(item.file.name);\n this.removeFromQueue(item);\n },\n onErrorItem: function(item, response, status, headers) {\n $mdToast.show(\n $mdToast.simple()\n .content(l('Error while uploading the file \\\"%{0}\\\":', item.file.name) +\n ' ' + (response.message? l(response.message) : ''))\n .position('top right')\n .action(l('OK'))\n .hideDelay(false));\n this.removeFromQueue(item);\n //console.debug(item); console.debug('error = ' + JSON.stringify(response, undefined, 2));\n }\n });\n\n // Destroy file uploader when the controller is being deactivated\n $scope.$on('$destroy', function() { vm.uploader.destroy(); });\n\n if ($stateParams.actionName == 'reply') {\n stateMessage.$reply().then(function(msgObject) {\n vm.message = msgObject;\n vm.hideCc = (!msgObject.editable.cc || msgObject.editable.cc.length === 0);\n vm.hideBcc = (!msgObject.editable.bcc || msgObject.editable.bcc.length === 0);\n });\n }\n else if ($stateParams.actionName == 'replyall') {\n stateMessage.$replyAll().then(function(msgObject) {\n vm.message = msgObject;\n vm.hideCc = (!msgObject.editable.cc || msgObject.editable.cc.length === 0);\n vm.hideBcc = (!msgObject.editable.bcc || msgObject.editable.bcc.length === 0);\n });\n }\n else if ($stateParams.actionName == 'forward') {\n stateMessage.$forward().then(function(msgObject) {\n vm.message = msgObject;\n addAttachments();\n });\n }\n else if (angular.isDefined(stateMessage)) {\n vm.message = stateMessage;\n addAttachments();\n }\n\n /**\n * If this is a popup window, retrieve the mailbox controller of the parent window.\n */\n function $parentControllers() {\n var originMessage, ctrls = {};\n\n try {\n if ($window.opener) {\n if ('$mailboxController' in $window.opener &&\n 'selectedFolder' in $window.opener.$mailboxController) {\n if ($window.opener.$mailboxController.selectedFolder.type == 'draft') {\n ctrls.draftMailboxCtrl = $window.opener.$mailboxController;\n if ('$messageController' in $window.opener &&\n $window.opener.$messageController.message.uid == stateMessage.uid) {\n // The draft is opened in the parent window\n ctrls.draftMessageCtrl = $window.opener.$messageController;\n }\n }\n else if (stateMessage.origin) {\n originMessage = stateMessage.origin.message;\n if ($window.opener.$mailboxController.selectedFolder.$id() == originMessage.$mailbox.$id()) {\n // The message mailbox is opened in the parent window\n ctrls.originMailboxCtrl = $window.opener.$mailboxController;\n }\n }\n }\n }\n }\n catch (e) {}\n\n return ctrls;\n }\n\n function addAttachments() {\n // Add existing attached files to uploader\n var i, data, fileItem, attrs = vm.message.editable.attachmentAttrs;\n if (attrs)\n for (i = 0; i < attrs.length; i++) {\n data = {\n name: attrs[i].filename,\n type: attrs[i].mimetype,\n size: parseInt(attrs[i].size)\n };\n fileItem = new FileUploader.FileItem(vm.uploader, data);\n fileItem.progress = 100;\n fileItem.isUploaded = true;\n fileItem.isSuccess = true;\n fileItem.inlineUrl = attrs[i].url;\n vm.uploader.queue.push(fileItem);\n }\n }\n\n function removeAttachment(item, id) {\n if (item.isUploading)\n vm.uploader.cancelItem(item);\n else {\n vm.message.$deleteAttachment(item.file.name);\n item.remove();\n }\n // Hack to allow adding the same file again\n // See https://github.com/nervgh/angular-file-upload/issues/671\n var element = $window.document.getElementById(id);\n if (element)\n angular.element(element).prop('value', null);\n }\n\n function cancel() {\n if (vm.autosave)\n $timeout.cancel(vm.autosave);\n\n if (vm.message.isNew && vm.message.attachmentAttrs)\n vm.message.$mailbox.$deleteMessages([vm.message]);\n\n $mdDialog.cancel();\n }\n\n function save() {\n var ctrls = $parentControllers();\n vm.message.$save().then(function(data) {\n vm.message.$rawSource = null;\n if (ctrls.draftMailboxCtrl) {\n // We're saving a draft from a popup window.\n // Reload draft mailbox\n ctrls.draftMailboxCtrl.selectedFolder.$filter().then(function() {\n if (ctrls.draftMessageCtrl) {\n // Reload selected message\n ctrls.draftMessageCtrl.$state.go('mail.account.mailbox.message', { messageId: vm.message.uid });\n }\n });\n }\n $mdToast.show(\n $mdToast.simple()\n .content(l('Your email has been saved'))\n .position('top right')\n .hideDelay(3000));\n });\n }\n\n function send() {\n var ctrls = $parentControllers();\n\n vm.sendState = 'sending';\n if (vm.autosave)\n $timeout.cancel(vm.autosave);\n\n vm.message.$send().then(function(data) {\n vm.sendState = 'sent';\n if (ctrls.draftMailboxCtrl) {\n // We're sending a draft from a popup window and the draft mailbox is opened.\n // Reload draft mailbox\n ctrls.draftMailboxCtrl.selectedFolder.$filter().then(function() {\n if (ctrls.draftMessageCtrl) {\n // Close draft\n ctrls.draftMessageCtrl.close();\n }\n });\n }\n if (ctrls.originMailboxCtrl) {\n // We're sending a draft from a popup window and the original mailbox is opened.\n // Reload mailbox\n ctrls.originMailboxCtrl.selectedFolder.$filter();\n }\n $mdToast.show(\n $mdToast.simple()\n .content(l('Your email has been sent'))\n .position('top right')\n .hideDelay(3000));\n\n // Let the user see the succesfull message before closing the dialog\n $timeout($mdDialog.hide, 1000);\n }, function(response) {\n vm.sendState = 'error';\n vm.errorMessage = response.data? response.data.message : response.statusText;\n });\n }\n\n function toggleFullscreen() {\n vm.isFullscreen = !vm.isFullscreen;\n }\n\n function contactFilter($query) {\n return AddressBook.$filterAll($query).then(function(cards) {\n // Divide the matching cards by email addresses so the user can select\n // the recipient address of her choice\n var explodedCards = [];\n _.forEach(_.invokeMap(cards, 'explode'), function(manyCards) {\n _.forEach(manyCards, function(card) {\n explodedCards.push(card);\n });\n });\n // Remove duplicates\n return _.uniqBy(explodedCards, function(card) {\n return card.$$fullname + ' ' + card.$$email;\n });\n });\n }\n\n function addRecipient(contact, field) {\n var recipients, recipient, list;\n\n if (angular.isString(contact))\n return contact;\n\n recipients = vm.message.editable[field];\n\n if (contact.$isList({expandable: true})) {\n // If the list's members were already fetch, use them\n if (angular.isDefined(contact.refs) && contact.refs.length) {\n _.forEach(contact.refs, function(ref) {\n if (ref.email.length)\n recipients.push(ref.$shortFormat());\n });\n }\n else {\n list = Card.$find(contact.container, contact.c_name);\n list.$id().then(function(listId) {\n _.forEach(list.refs, function(ref) {\n if (ref.email.length)\n recipients.push(ref.$shortFormat());\n });\n });\n }\n }\n else {\n recipient = contact.$shortFormat();\n }\n\n if (recipient)\n return recipient;\n else\n return null;\n }\n\n // Drafts autosaving\n function autosaveDrafts() {\n vm.message.$save();\n if (Preferences.defaults.SOGoMailAutoSave)\n vm.autosave = $timeout(vm.autosaveDrafts, Preferences.defaults.SOGoMailAutoSave*1000*60);\n }\n\n // Read user's defaults\n Preferences.ready().then(function() {\n if (Preferences.defaults.SOGoMailAutoSave)\n // Enable auto-save of draft\n vm.autosave = $timeout(vm.autosaveDrafts, Preferences.defaults.SOGoMailAutoSave*1000*60);\n // Set the locale of CKEditor\n vm.localeCode = Preferences.defaults.LocaleCode;\n });\n }\n\n SendMessageToastController.$inject = ['$scope', '$mdToast'];\n function SendMessageToastController($scope, $mdToast) {\n $scope.closeToast = function() {\n $mdToast.hide();\n };\n }\n\n angular\n .module('SOGo.MailerUI')\n .controller('SendMessageToastController', SendMessageToastController)\n .controller('MessageEditorController', MessageEditorController);\n\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n /* jshint validthis: true */\n 'use strict';\n\n /**\n * sgIMIP - A directive to handle IMIP actions on emails\n * @memberof SOGo.MailerUI\n * @example:\n\n */\n function sgImip() {\n return {\n restrict: 'A',\n link: link,\n controller: 'sgImipController'\n };\n\n function link(scope, iElement, attrs, ctrl) {\n ctrl.pathToAttachment = attrs.sgImipPath;\n }\n }\n\n /**\n * @ngInject\n */\n sgImipController.$inject = ['$scope', 'User'];\n function sgImipController($scope, User) {\n var vm = this;\n\n $scope.delegateInvitation = false;\n $scope.delegatedTo = '';\n $scope.searchText = '';\n\n $scope.userFilter = function($query) {\n return User.$filter($query);\n };\n\n $scope.iCalendarAction = function(action) {\n var data;\n\n if (action == 'delegate') {\n data = {\n receiveUpdates: false,\n delegatedTo: $scope.delegatedTo.c_email\n };\n }\n\n $scope.viewer.message.$imipAction(vm.pathToAttachment, action, data);\n };\n }\n\n angular\n .module('SOGo.MailerUI')\n .controller('sgImipController', sgImipController)\n .directive('sgImip', sgImip);\n})();\n\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /*\n * sgZoomableImage - Toggle the 'sg-zoom' class when clicking on the image inside the container.\n * @memberof SOGo.MailerUI\n * @restrict attribute\n * @ngInject\n * @example:\n\n
\n \n \n \n
\n */\n function sgZoomableImage() {\n return {\n restrict: 'A',\n link: link\n };\n\n function link(scope, iElement, attrs, ctrl) {\n var parentNode = iElement.parent(),\n toggleClass;\n\n toggleClass = function(event) {\n if (event.target.tagName == 'IMG')\n parentNode.toggleClass('sg-zoom');\n };\n\n iElement.on('click', toggleClass);\n }\n }\n\n angular\n .module('SOGo.MailerUI')\n .directive('sgZoomableImage', sgZoomableImage);\n})();\n"]} \ No newline at end of file +{"version":3,"sources":["Mailer/Account.service.js","Mailer/Mailbox.service.js","Mailer/Message.service.js","Mailer/VirtualMailbox.service.js","Mailer/MailboxController.js","Mailer/MailboxesController.js","Mailer/MessageController.js","Mailer/MessageEditorController.js","Mailer/sgIMIP.directive.js","Mailer/sgZoomableImage.directive.js"],"names":["Account","futureAccountData","then","angular","extend","this","_","forEach","identities","identity","fullName","full","email","$log","debug","JSON","stringify","undefined","$factory","$q","$timeout","Settings","Resource","Preferences","Mailbox","Message","$$resource","activeUser","$Preferences","$Mailbox","$Message","module","e","factory","$findAll","data","$unwrapCollection","fetch","o","collection","i","id","$accounts","prototype","getLength","$flattenMailboxes","length","getItemAtIndex","index","expandedMailboxes","$getMailboxes","options","_this","$mailboxes","reload","$find","$expanded","ready","expandedFolders","_visit","mailboxes","indexOf","children","settings","Mail","ExpandedFolders","isString","fromJson","when","allMailboxes","push","all","$$flattenMailboxes","saveState","account","reduce","mailbox","post","$getMailboxByType","type","_find","find","$getMailboxByPath","path","$newMailbox","name","toString","updateQuota","percent","format","description","Math","round","usedSpace","maxQuota","l","formatted","$quota","$newMessage","message","accountId","mailboxPath","$absolutePath","asDraft","editable","isNew","$addDelegate","user","deferred","defer","param","uid","map","delegates","resolve","users","status","reject","promise","$removeDelegate","splice","futureMailboxData","$account","init","newMailboxData","create","$unwrap","Acl","PRELOAD","$$Acl","$query","sort","asc","selectedFolder","$refreshTimeout","$virtualMode","SortingState","parseInt","constant","LOOKAHEAD","SIZE","createMailboxes","level","quotas","split","component","asCSSIdentifier","join","$isLoading","$messages","uidsMap","$id","$acl","$isEditable","isEditable","$isNoInferiors","isNoInferiors","isUndefined","$shadowData","$omit","selectFolder","$lastVisibleIndex","max","$loadMessage","$selectedMessages","filter","selected","$selectedCount","isSelectedMessage","messageId","selectedMessage","$selectedMessage","$selectedMessageIndex","hasSelectedMessage","isDefined","$filter","sortingAttributes","filters","unseenCount","cancel","searchInput","secondFilter","match","searchBy","copy","refreshViewCheck","defaults","SOGoRefreshViewCheck","f","bind","timeInterval","endIndex","uids","futureHeadersData","startIndex","loaded","subject","min","loading","$unwrapHeaders","flags","isNoSelect","$rename","findParent","parent","parentMailbox","$save","sibling","localeCompare","$compact","$setFolderAs","$emptyTrash","$markAsRead","$flagMessages","messages","operation","msgUIDs","saveSelectedMessages","selectedMessages","selectedUIDs","filename","download","exportFolder","$delete","$_deleteMessages","unseen","firstIndex","isread","forEachRight","selectedIndex","findIndex","$deleteMessages","$markOrUnMarkMessagesAsJunk","method","$copyMessages","folder","$moveMessages","$reset","value","key","save","response","error","$futureMailboxData","headers","$topIndex","invokeMap","threaded","msgs","msg","zipObject","isError","j","messageHeaders","$updateSubscribe","action","subscribed","futureMessageData","lazy","$mailbox","$hasUnsafeContent","$loadUnsafeContent","to","cc","bcc","$formatFullAddresses","Message_STATUS","STATUS","$avatar","avatar","SOGoMailLabelsColors","$tags","SOGoMailDisplayRemoteInlineImages","$displayRemoteInlineImages","NOT_LOADED","DELAYED_LOADING","LOADING","LOADED","DELAYED_MS","filterTags","query","excludedTags","re","RegExp","results","keys","tag","pair","search","includes","color","buildPath","nocache","draftId","$setUID","oldUID","attr","constructor","shortname","first","last","replace","image","$shortRecipients","result","count","total","$shortAddress","address","allowReplyAll","recipientsCount","isDraft","loadUnsafeContent","$content","parts","part","msgclass","content","alternatePart","preferredPart","contentType","isArray","formattedMessage","$smime","validSignature","valid","mixedPart","safeContent","html","unsafeContent","document","createElement","innerHTML","suffix","element","elements","querySelectorAll","removeAttr","compile","$editableContent","from","toLowerCase","text","$plainContent","addTag","$addOrRemoveTag","removeTag","$imipAction","$reload","$sendMDN","shouldAskReceipt","$deleteAttachment","attachmentAttrs","attachment","toggleFlag","isflagged","$loaded","useCache","$futureMessageData","$reply","$newDraft","$replyAll","$forward","origin","$send","startsWith","isanswered","isforwarded","privateAttributes","downloadAttachments","VirtualMailbox","setMailboxes","startSearch","params","finally","stopSearch","resetSelectedMessage","len","k","transform","messagesMap","sum","allMessages","promises","assign","flatten","MailboxController","$window","$scope","$state","$mdDialog","$mdToast","stateAccounts","stateAccount","stateMailbox","sgHotkeys","encodeUriFilter","sgSettings","focus","Dialog","_registerHotkeys","createHotkey","callback","searchMode","$event","vm","messageDialog","newMessage","markOrUnMarkMessagesAsJunk","toggleMessageSelection","_nextMessage","preventInClass","_previousMessage","_addNextMessageToSelection","_addPreviousMessageToSelection","confirmDeleteSelectedMessages","registerHotkey","_compactBeforeUnload","event","field","sortedBy","mode","cancelSearch","inPopup","_newMessageInPopup","show","body","targetEvent","clickOutsideToClose","escapeToClose","templateUrl","controller","controllerAs","locals","stateMessage","url","baseURL","wId","random","console","open","selectMessage","preventDefault","go","mailboxId","nextSelectedIndex","multiple","shiftKey","stopPropagation","_currentMailboxes","_unselectMessage","nextMessage","previousMessage","nextIndex","warn","size","confirm","ok","deleteSelectedMessage","withoutTrash","moveSelectedMessage","dstFolder","copySelectedMessages","simple","position","hideDelay","moveSelectedMessages","selectAll","unselectMessages","markSelectedMessagesAsFlagged","markSelectedMessagesAsUnread","markSelectedMessagesAsRead","defaultWindowTitle","hotkeys","$mailboxController","service","accounts","on","$on","off","deregisterHotkey","$watch","title","mdVirtualRepeatContainerDirectiveDecorator","$delegate","resetScroll","$element","updateSize","scrollTo","$inject","decorator","MailboxesController","$mdMedia","$mdSidenav","sgConstant","User","confirmDelete","showAdvancedSearch","showingAdvancedSearch","close","hideAdvancedSearch","searchPreviousMailbox","toggleAdvancedSearch","virtualMailbox","root","folders","subfolders","addSearchParam","v","currentSearchParam","newSearchParam","pattern","n","searchParam","substring","trim","negative","toggleAccountState","triggerHandler","subscribe","SubscriptionsDialogController","metadataForFolder","srcAccount","newFolder","parentFolder","prompt","alert","delegate","MailboxDelegationController","userFilter","closeModal","hide","removeUser","catch","addUser","userToAdd","searchText","editFolder","editMode","revertEditing","saveFolder","compactFolder","emptyTrashFolder","markFolderRead","share","$users","usersWithACL","icon","special","setFolderAs","refreshUnseenCount","unseenCountFolders","isDroppableFolder","srcFolder","dragSelectedMessages","dstId","clearMessageView","success","","showSubscribedOnly","SOGoMailShowSubscribedFoldersOnly","MessageController","Calendar","Component","_messageDialog","arguments","_unlessInDialog","apply","reply","replyAll","forward","deleteMessage","$parentControllers","ctrls","opener","mailboxCtrl","$messageController","messageCtrl","toggleDetailedRecipients","$showDetailedRecipients","filterMailtoLinks","href","target","tagName","attributes","exec","decodeURIComponent","state","parentCtrls","closePopup","showMailEditor","edit","openPopup","popupWindow","editableContent","toggleRawSource","showRawSource","$rawSource","print","convertToEvent","convertToComponent","convertToTask","componentData","pid","$defaultCalendar","summary","comment","capitalize","stateComponent","tags","showFlags","$watchCollection","newTags","oldTags","wasflagged","_newTags","_oldTags","isObject","difference","MessageEditorController","$stateParams","$mdConstant","FileUploader","AddressBook","Card","originMessage","draftMailboxCtrl","draftMessageCtrl","originMailboxCtrl","addAttachments","fileItem","attrs","mimetype","FileItem","uploader","progress","isUploaded","isSuccess","inlineUrl","queue","removeAttachment","item","isUploading","cancelItem","file","remove","getElementById","prop","autosave","send","sendState","errorMessage","statusText","toggleFullscreen","isFullscreen","contactFilter","$filterAll","cards","explodedCards","manyCards","card","uniqBy","$$fullname","$$email","addRecipient","contact","recipients","recipient","list","$isList","expandable","refs","ref","$shortFormat","container","c_name","listId","autosaveDrafts","SOGoMailAutoSave","autocomplete","hideBcc","hideCc","recipientSeparatorKeys","KEY_CODE","ENTER","TAB","COMMA","SEMICOLON","autoUpload","alias","removeAfterUpload","onSuccessItem","lastAttachmentAttrs","onCancelItem","removeFromQueue","onErrorItem","destroy","actionName","msgObject","localeCode","LocaleCode","SendMessageToastController","closeToast","sgImip","link","scope","iElement","ctrl","pathToAttachment","sgImipPath","restrict","sgImipController","delegateInvitation","delegatedTo","iCalendarAction","receiveUpdates","c_email","viewer","directive","sgZoomableImage","toggleClass","parentNode"],"mappings":"CAEA,WACE,YAOE,SAASA,GAAQC,GAEqB,kBAA3BA,GAAkBC,OAC3BC,QAAQC,OAAOC,KAAMJ,GACrBK,EAAEC,QAAQF,KAAKG,WAAY,SAASC,GAC9BA,EAASC,SACXD,EAASE,KAAOF,EAASC,SAAW,KAAOD,EAASG,MAAQ,IAE5DH,EAASE,KAAO,IAAMF,EAASG,MAAQ,MAE3CZ,EAAQa,KAAKC,MAAM,YAAcC,KAAKC,UAAUf,EAAmBgB,OAAW,KAalFjB,EAAQkB,UAAY,KAAM,WAAY,OAAQ,aAAc,WAAY,cAAe,UAAW,UAAW,SAASC,EAAIC,EAAUP,EAAMQ,EAAUC,EAAUC,EAAaC,EAASC,GAWlL,MAVAtB,SAAQC,OAAOJ,GACbmB,GAAIA,EACJC,SAAUA,EACVP,KAAMA,EACNa,WAAY,GAAIJ,GAASD,EAASM,WAAW,aAAe,OAAQN,EAASM,cAC7EC,aAAcL,EACdM,SAAUL,EACVM,SAAUL,IAGLzB,GAOT,KACEG,QAAQ4B,OAAO,iBAEjB,MAAMC,GACJ7B,QAAQ4B,OAAO,iBAAkB,gBAEnC5B,QAAQ4B,OAAO,iBACZE,QAAQ,UAAWjC,EAAQkB,UAQ9BlB,EAAQkC,SAAW,SAASC,GAC1B,MAAKA,GAKEnC,EAAQoC,kBAAkBD,GAJxBnC,EAAQ0B,WAAWW,MAAM,GAAI,gBAAgBnC,KAAK,SAASoC,GAChE,MAAOtC,GAAQoC,kBAAkBE,MAYvCtC,EAAQoC,kBAAoB,SAASD,GACnC,GAAII,KAQJ,OANApC,SAAQI,QAAQ4B,EAAM,SAASG,EAAGE,GAChCF,EAAEG,GAA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rO,GAAG,QAASmP,GAdvB,OACEV,SAAU,IACVN,KAAMA,GAgBV7rB,QACG4B,OAAO,iBACP+qB,UAAU,kBAAmBC","file":"Mailer.services.js","sourcesContent":["/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @name Account\n * @constructor\n * @param {object} futureAccountData\n */\n function Account(futureAccountData) {\n // Data is immediately available\n if (typeof futureAccountData.then !== 'function') {\n angular.extend(this, futureAccountData);\n _.forEach(this.identities, function(identity) {\n if (identity.fullName)\n identity.full = identity.fullName + ' <' + identity.email + '>';\n else\n identity.full = '<' + identity.email + '>';\n });\n Account.$log.debug('Account: ' + JSON.stringify(futureAccountData, undefined, 2));\n }\n else {\n // The promise will be unwrapped first\n //this.$unwrap(futureAccountData);\n }\n }\n\n /**\n * @memberof Account\n * @desc The factory we'll use to register with Angular\n * @returns the Account constructor\n */\n Account.$factory = ['$q', '$timeout', '$log', 'sgSettings', 'Resource', 'Preferences', 'Mailbox', 'Message', function($q, $timeout, $log, Settings, Resource, Preferences, Mailbox, Message) {\n angular.extend(Account, {\n $q: $q,\n $timeout: $timeout,\n $log: $log,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Mail', Settings.activeUser()),\n $Preferences: Preferences,\n $Mailbox: Mailbox,\n $Message: Message\n });\n\n return Account; // return constructor\n }];\n\n /**\n * @module SOGo.MailerUI\n * @desc Factory registration of Account in Angular module.\n */\n try {\n angular.module('SOGo.MailerUI');\n }\n catch(e) {\n angular.module('SOGo.MailerUI', ['SOGo.Common']);\n }\n angular.module('SOGo.MailerUI')\n .factory('Account', Account.$factory);\n\n /**\n * @memberof Account\n * @desc Set the list of accounts and instanciate a new Account object for each item.\n * @param {array} [data] - the metadata of the accounts\n * @returns the list of accounts\n */\n Account.$findAll = function(data) {\n if (!data) {\n return Account.$$resource.fetch('', 'mailAccounts').then(function(o) {\n return Account.$unwrapCollection(o);\n });\n }\n return Account.$unwrapCollection(data);\n };\n\n /**\n * @memberof Account\n * @desc Unwrap to a collection of Account instances.\n * @param {object} data - the accounts information\n * @returns a collection of Account objects\n */\n Account.$unwrapCollection = function(data) {\n var collection = [];\n\n angular.forEach(data, function(o, i) {\n o.id = i;\n collection[i] = new Account(o);\n });\n Account.$accounts = collection;\n\n return collection;\n };\n\n /**\n * @function getLength\n * @memberof Account.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the number of mailboxes in the account\n */\n Account.prototype.getLength = function() {\n return this.$flattenMailboxes().length;\n };\n\n /**\n * @function getItemAtIndex\n * @memberof Account.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the mailbox at the specified index\n */\n Account.prototype.getItemAtIndex = function(index) {\n var expandedMailboxes;\n\n expandedMailboxes = this.$flattenMailboxes();\n if (index >= 0 && index < expandedMailboxes.length)\n return expandedMailboxes[index];\n\n return null;\n };\n\n /**\n * @function $getMailboxes\n * @memberof Account.prototype\n * @desc Fetch the list of mailboxes for the current account.\n * @param {object} [options] - force a reload by setting 'reload' to true\n * @returns a promise of the HTTP operation\n */\n Account.prototype.$getMailboxes = function(options) {\n var _this = this;\n\n if (this.$mailboxes && !(options && options.reload)) {\n return Account.$q.when(this.$mailboxes);\n }\n else {\n return Account.$Mailbox.$find(this, options).then(function(data) {\n _this.$mailboxes = data;\n _this.$expanded = false;\n\n // Set expanded folders from user's settings\n Account.$Preferences.ready().then(function() {\n var expandedFolders,\n _visit = function(mailboxes) {\n _.forEach(mailboxes, function(o) {\n o.$expanded = (expandedFolders.indexOf('/' + o.id) >= 0);\n if (o.children && o.children.length > 0) {\n _visit(o.children);\n }\n });\n };\n if (Account.$Preferences.settings.Mail.ExpandedFolders) {\n if (angular.isString(Account.$Preferences.settings.Mail.ExpandedFolders))\n // Backward compatibility support\n expandedFolders = angular.fromJson(Account.$Preferences.settings.Mail.ExpandedFolders);\n else\n expandedFolders = Account.$Preferences.settings.Mail.ExpandedFolders;\n _this.$expanded = (expandedFolders.indexOf('/' + _this.id) >= 0);\n if (expandedFolders.length > 0) {\n _visit(_this.$mailboxes);\n }\n }\n if (Account.$accounts)\n _this.$expanded |= (Account.$accounts.length == 1); // Always expand single account\n _this.$flattenMailboxes({reload: true});\n });\n\n return _this.$mailboxes;\n });\n }\n };\n\n /**\n * @function $flattenMailboxes\n * @memberof Account.prototype\n * @desc Get a flatten array of the mailboxes.\n * @param {object} [options] - the following boolean attributes are available:\n * - reload: rebuild the flatten array of mailboxes from the original tree representation (this.$mailboxes)\n * - all: return all mailboxes, ignoring their expanstion state\n * - saveState: save expansion state of mailboxes to the server\n * @returns an array of Mailbox instances\n */\n Account.prototype.$flattenMailboxes = function(options) {\n var _this = this,\n allMailboxes = [],\n expandedMailboxes = [],\n _visit = function(mailboxes) {\n _.forEach(mailboxes, function(o) {\n allMailboxes.push(o);\n if ((options && options.all || o.$expanded) && o.children && o.children.length > 0) {\n _visit(o.children);\n }\n });\n };\n\n if (this.$$flattenMailboxes && !(options && (options.reload || options.all))) {\n allMailboxes = this.$$flattenMailboxes;\n }\n else {\n _visit(this.$mailboxes);\n if (!options || !options.all) {\n _this.$$flattenMailboxes = allMailboxes;\n if (options && options.saveState) {\n // Save expansion state of mailboxes to the server\n _.forEach(Account.$accounts, function(account) {\n if (account.$expanded) {\n expandedMailboxes.push('/' + account.id);\n }\n _.reduce(account.$$flattenMailboxes, function(expandedFolders, mailbox) {\n if (mailbox.$expanded) {\n expandedFolders.push('/' + mailbox.id);\n }\n return expandedFolders;\n }, expandedMailboxes);\n });\n Account.$$resource.post(null, 'saveFoldersState', expandedMailboxes);\n }\n }\n }\n\n return allMailboxes;\n };\n\n Account.prototype.$getMailboxByType = function(type) {\n var mailbox,\n // Recursive find function\n _find = function(mailboxes) {\n var mailbox = _.find(mailboxes, function(o) {\n return o.type == type;\n });\n if (!mailbox) {\n angular.forEach(mailboxes, function(o) {\n if (!mailbox && o.children && o.children.length > 0) {\n mailbox = _find(o.children);\n }\n });\n }\n return mailbox;\n };\n mailbox = _find(this.$mailboxes);\n\n return mailbox;\n };\n\n /**\n * @function $getMailboxByPath\n * @memberof Account.prototype\n * @desc Recursively find a mailbox using its path\n * @returns a promise of the HTTP operation\n */\n Account.prototype.$getMailboxByPath = function(path) {\n var mailbox = null,\n // Recursive find function\n _find = function(mailboxes) {\n var mailbox = _.find(mailboxes, function(o) {\n return o.path == path;\n });\n if (!mailbox) {\n angular.forEach(mailboxes, function(o) {\n if (!mailbox && o.children && o.children.length > 0) {\n mailbox = _find(o.children);\n }\n });\n }\n return mailbox;\n };\n mailbox = _find(this.$mailboxes);\n\n return mailbox;\n };\n\n /**\n * @function $newMailbox\n * @memberof Account.prototype\n * @desc Create a new mailbox on the server and refresh the list of mailboxes.\n * @returns a promise of the HTTP operations\n */\n Account.prototype.$newMailbox = function(path, name) {\n var _this = this;\n\n return Account.$$resource.post(path.toString(), 'createFolder', {name: name}).then(function() {\n _this.$getMailboxes({reload: true});\n });\n };\n\n /**\n * @function updateQuota\n * @memberof Account.prototype\n * @param {Object} data - the inbox quota information returned by the server\n * @desc Update the quota definition associated to the account\n */\n Account.prototype.updateQuota = function(data) {\n var percent, format, description;\n\n percent = (Math.round(data.usedSpace * 10000 / data.maxQuota) / 100);\n format = l(\"quotasFormat\");\n description = format.formatted(percent, Math.round(data.maxQuota/10.24)/100);\n\n this.$quota = { percent: percent, description: description };\n };\n\n /**\n * @function $newMessage\n * @memberof Account.prototype\n * @desc Prepare a new Message object associated to the appropriate mailbox.\n * @returns a promise of the HTTP operations\n */\n Account.prototype.$newMessage = function() {\n var _this = this;\n\n // Query account for draft folder and draft UID\n return Account.$$resource.fetch(this.id.toString(), 'compose').then(function(data) {\n Account.$log.debug('New message (compose): ' + JSON.stringify(data, undefined, 2));\n var message = new Account.$Message(data.accountId, _this.$getMailboxByPath(data.mailboxPath), data);\n return message;\n }).then(function(message) {\n // Fetch draft initial data\n return Account.$$resource.fetch(message.$absolutePath({asDraft: true}), 'edit').then(function(data) {\n Account.$log.debug('New message (edit): ' + JSON.stringify(data, undefined, 2));\n angular.extend(message.editable, data);\n message.isNew = true;\n return message;\n });\n });\n };\n\n /**\n * @function $addDelegate\n * @memberof Account.prototype\n * @param {Object} user - a User object with minimal set of attributes (uid, isGroup, cn, c_email)\n * @desc Remove a user from the account's delegates\n * @see {@link User.$filter}\n */\n Account.prototype.$addDelegate = function(user) {\n var _this = this,\n deferred = Account.$q.defer(),\n param = {uid: user.uid};\n if (!user.uid || _.indexOf(_.map(this.delegates, 'uid'), user.uid) > -1) {\n // No UID specified or user already in delegates\n deferred.resolve();\n }\n else {\n Account.$$resource.fetch(this.id.toString(), 'addDelegate', param).then(function() {\n _this.delegates.push(user);\n deferred.resolve(_this.users);\n }, function(data, status) {\n deferred.reject(l('An error occured please try again.'));\n });\n }\n return deferred.promise;\n };\n\n /**\n * @function $removeDelegate\n * @memberof Account.prototype\n * @param {Object} user - a User object with minimal set of attributes (uid, isGroup, cn, c_email)\n * @desc Remove a user from the account's delegates\n * @return a promise of the server call to remove the user from the account's delegates\n */\n Account.prototype.$removeDelegate = function(uid) {\n var _this = this,\n param = {uid: uid};\n return Account.$$resource.fetch(this.id.toString(), 'removeDelegate', param).then(function() {\n var i = _.indexOf(_.map(_this.delegates, 'uid'), uid);\n if (i >= 0) {\n _this.delegates.splice(i, 1);\n }\n });\n };\n \n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @name Mailbox\n * @constructor\n * @param {object} futureMailboxData - either an object literal or a promise\n */\n function Mailbox(account, futureMailboxData) {\n this.$account = account;\n // Data is immediately available\n if (typeof futureMailboxData.then !== 'function') {\n this.init(futureMailboxData);\n if (this.name && !this.path) {\n // Create a new mailbox on the server\n var newMailboxData = Mailbox.$$resource.create('createFolder', this.name);\n this.$unwrap(newMailboxData);\n }\n }\n else {\n // The promise will be unwrapped first\n // NOTE: this condition never happen for the moment\n this.$unwrap(futureMailboxData);\n }\n }\n\n /**\n * @memberof Mailbox\n * @desc The factory we'll use to register with Angular\n * @returns the Mailbox constructor\n */\n Mailbox.$factory = ['$q', '$timeout', '$log', 'sgSettings', 'Resource', 'Message', 'Acl', 'Preferences', 'sgMailbox_PRELOAD', function($q, $timeout, $log, Settings, Resource, Message, Acl, Preferences, PRELOAD) {\n angular.extend(Mailbox, {\n $q: $q,\n $timeout: $timeout,\n $log: $log,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Mail', Settings.activeUser()),\n $Message: Message,\n $$Acl: Acl,\n $Preferences: Preferences,\n $query: { sort: 'arrival', asc: 0 }, // The default sort must match [UIxMailListActions defaultSortKey]\n selectedFolder: null,\n $refreshTimeout: null,\n $virtualMode: false,\n PRELOAD: PRELOAD\n });\n // Initialize sort parameters from user's settings\n Preferences.ready().then(function() {\n if (Preferences.settings.Mail.SortingState) {\n Mailbox.$query.sort = Preferences.settings.Mail.SortingState[0];\n Mailbox.$query.asc = parseInt(Preferences.settings.Mail.SortingState[1]);\n }\n });\n\n return Mailbox; // return constructor\n }];\n\n /**\n * @module SOGo.MailerUI\n * @desc Factory registration of Mailbox in Angular module.\n */\n try {\n angular.module('SOGo.MailerUI');\n }\n catch(e) {\n angular.module('SOGo.MailerUI', ['SOGo.Common']);\n }\n angular.module('SOGo.MailerUI')\n .constant('sgMailbox_PRELOAD', {\n LOOKAHEAD: 50,\n SIZE: 100\n })\n .factory('Mailbox', Mailbox.$factory);\n\n /**\n * @memberof Mailbox\n * @desc Fetch list of mailboxes of a specific account\n * @param {string} accountId - the account\n * @return a promise of the HTTP operation\n * @see {@link Account.$getMailboxes}\n */\n Mailbox.$find = function(account, options) {\n var path, futureMailboxData;\n\n if (options && options.all)\n futureMailboxData = this.$$resource.fetch(account.id.toString(), 'viewAll');\n else\n futureMailboxData = this.$$resource.fetch(account.id.toString(), 'view');\n\n return Mailbox.$unwrapCollection(account, futureMailboxData); // a collection of mailboxes\n };\n\n /**\n * @memberof Mailbox\n * @desc Unwrap to a collection of Mailbox instances.\n * @param {string} account - the account\n * @param {promise} futureMailboxData - a promise of the mailboxes metadata\n * @returns a promise of a collection of Mailbox objects\n */\n Mailbox.$unwrapCollection = function(account, futureMailboxData) {\n var collection = [],\n // Local recursive function\n createMailboxes = function(level, mailbox) {\n for (var i = 0; i < mailbox.children.length; i++) {\n mailbox.children[i].level = level;\n mailbox.children[i] = new Mailbox(account, mailbox.children[i]);\n createMailboxes(level+1, mailbox.children[i]);\n }\n };\n //collection.$futureMailboxData = futureMailboxData;\n\n return futureMailboxData.then(function(data) {\n return Mailbox.$timeout(function() {\n // Each entry is spun up as a Mailbox instance\n angular.forEach(data.mailboxes, function(data, index) {\n data.level = 0;\n var mailbox = new Mailbox(account, data);\n createMailboxes(1, mailbox); // recursively create all sub-mailboxes\n collection.push(mailbox);\n });\n // Update inbox quota\n if (data.quotas)\n account.updateQuota(data.quotas);\n return collection;\n });\n });\n };\n\n /**\n * @memberof Mailbox\n * @desc Build the path of the mailbox (or account only).\n * @param {string} accountId - the account ID\n * @param {string} [mailboxPath] - the mailbox path\n * @returns a string representing the path relative to the mail module\n */\n Mailbox.$absolutePath = function(accountId, mailboxPath) {\n var path = [];\n\n if (mailboxPath) {\n path = _.map(mailboxPath.split('/'), function(component) {\n return 'folder' + component.asCSSIdentifier();\n });\n }\n\n path.splice(0, 0, accountId); // insert account ID\n\n return path.join('/');\n };\n\n /**\n * @function init\n * @memberof Mailbox.prototype\n * @desc Extend instance with new data and compute additional attributes.\n * @param {object} data - attributes of mailbox\n */\n Mailbox.prototype.init = function(data) {\n var _this = this;\n this.$isLoading = true;\n this.$messages = [];\n this.uidsMap = {};\n angular.extend(this, data);\n if (this.path) {\n this.id = this.$id();\n this.$acl = new Mailbox.$$Acl('Mail/' + this.id);\n }\n if (this.type) {\n this.$isEditable = this.isEditable();\n }\n this.$isNoInferiors = this.isNoInferiors();\n if (angular.isUndefined(this.$shadowData)) {\n // Make a copy of the data for an eventual reset\n this.$shadowData = this.$omit();\n }\n };\n\n /**\n * @function selectFolder\n * @memberof Mailbox.prototype\n * @desc Mark the folder as selected in the constructor unless virtual mode is active\n */\n Mailbox.prototype.selectFolder = function() {\n if (!Mailbox.$virtualMode)\n Mailbox.selectedFolder = this;\n };\n\n /**\n * @function getLength\n * @memberof Mailbox.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the number of messages in the mailbox\n */\n Mailbox.prototype.getLength = function() {\n return this.$messages.length;\n };\n\n /**\n * @function getItemAtIndex\n * @memberof Mailbox.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the message at the specified index\n */\n Mailbox.prototype.getItemAtIndex = function(index) {\n var message;\n\n if (index >= 0 && index < this.$messages.length) {\n message = this.$messages[index];\n this.$lastVisibleIndex = Math.max(0, index - 3); // Magic number is NUM_EXTRA from virtual-repeater.js\n\n if (this.$loadMessage(message.uid))\n return message;\n }\n return null;\n };\n\n /**\n * @function $id\n * @memberof Mailbox.prototype\n * @desc Build the unique ID to identified the mailbox.\n * @returns a string representing the path relative to the mail module\n */\n Mailbox.prototype.$id = function() {\n return Mailbox.$absolutePath(this.$account.id, this.path);\n };\n\n /**\n * @function $selectedMessages\n * @memberof Mailbox.prototype\n * @desc Return the messages selected by the user.\n * @returns Message instances\n */\n Mailbox.prototype.$selectedMessages = function() {\n return _.filter(this.$messages, function(message) { return message.selected; });\n };\n\n /**\n * @function $selectedCount\n * @memberof Mailbox.prototype\n * @desc Return the number of messages selected by the user.\n * @returns the number of selected messages\n */\n Mailbox.prototype.$selectedCount = function() {\n return this.$selectedMessages().length;\n };\n\n /**\n * @function isSelectedMessage\n * @memberof Mailbox.prototype\n * @desc Check if the specified message is displayed in the detailed view.\n * @param {string} messageId\n * @returns true if the specified message is displayed\n */\n Mailbox.prototype.isSelectedMessage = function(messageId) {\n return this.selectedMessage == messageId;\n };\n\n /**\n * @function $selectedMessage\n * @memberof Mailbox.prototype\n * @desc Return the currently visible message.\n * @returns a Message instance or undefined if no message is displayed\n */\n Mailbox.prototype.$selectedMessage = function() {\n var _this = this;\n\n return _.find(this.$messages, function(message) { return message.uid == _this.selectedMessage; });\n };\n\n /**\n * @function $selectedMessageIndex\n * @memberof Mailbox.prototype\n * @desc Return the index of the currently visible message.\n * @returns a number or undefined if no message is selected\n */\n Mailbox.prototype.$selectedMessageIndex = function() {\n return this.uidsMap[this.selectedMessage];\n };\n\n /**\n * @function hasSelectedMessage\n * @memberof Mailbox.prototype\n * @desc Check if a message is selected.\n * @returns true if the a message is selected\n */\n Mailbox.prototype.hasSelectedMessage = function() {\n return angular.isDefined(this.selectedMessage);\n };\n\n /**\n * @function $filter\n * @memberof Mailbox.prototype\n * @desc Fetch the messages metadata of the mailbox\n * @param {object} [sort] - sort preferences. Defaults to descendent by date.\n * @param {string} sort.match - either AND or OR\n * @param {string} sort.sort - either arrival, subject, from, to, date, or size\n * @param {boolean} sort.asc - sort is ascendant if true\n * @param {object[]} [filters] - list of filters for the query\n * @param {string} filters.searchBy - either subject, from, to, cc, or body\n * @param {string} filters.searchInput - the search string to match\n * @param {boolean} filters.negative - negate the condition\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$filter = function(sortingAttributes, filters) {\n var _this = this, options = {};\n\n if (!angular.isDefined(this.unseenCount))\n this.unseenCount = 0;\n\n Mailbox.$timeout(function() {\n _this.$isLoading = true;\n });\n\n return Mailbox.$Preferences.ready().then(function() {\n\n if (Mailbox.$refreshTimeout)\n Mailbox.$timeout.cancel(Mailbox.$refreshTimeout);\n\n if (sortingAttributes)\n // Sorting preferences are common to all mailboxes\n angular.extend(Mailbox.$query, sortingAttributes);\n\n angular.extend(options, { sortingAttributes: Mailbox.$query });\n if (angular.isDefined(filters)) {\n options.filters = _.reject(filters, function(filter) {\n return !filter.searchInput || filter.searchInput.length === 0;\n });\n // Decompose filters that match two fields\n _.forEach(options.filters, function(filter) {\n var secondFilter,\n match = filter.searchBy.match(/(\\w+)_or_(\\w+)/);\n if (match) {\n options.sortingAttributes.match = 'OR';\n filter.searchBy = match[1];\n secondFilter = angular.copy(filter);\n secondFilter.searchBy = match[2];\n options.filters.push(secondFilter);\n }\n });\n }\n\n // Restart the refresh timer, if needed\n if (!Mailbox.$virtualMode) {\n var refreshViewCheck = Mailbox.$Preferences.defaults.SOGoRefreshViewCheck;\n if (refreshViewCheck && refreshViewCheck != 'manually') {\n var f = angular.bind(_this, Mailbox.prototype.$filter, null, filters);\n Mailbox.$refreshTimeout = Mailbox.$timeout(f, refreshViewCheck.timeInterval()*1000);\n }\n }\n\n var futureMailboxData = Mailbox.$$resource.post(_this.id, 'view', options);\n return _this.$unwrap(futureMailboxData);\n });\n };\n\n /**\n * @function $loadMessage\n * @memberof Mailbox.prototype\n * @desc Check if the message is loaded and in any case, fetch more messages headers from the server.\n * @returns true if the message metadata are already fetched\n */\n Mailbox.prototype.$loadMessage = function(messageId) {\n var startIndex = this.uidsMap[messageId],\n endIndex,\n index,\n max = this.$messages.length,\n loaded = false,\n uids,\n futureHeadersData;\n if (angular.isDefined(this.uidsMap[messageId]) && startIndex < this.$messages.length) {\n // Index is valid\n if (angular.isDefined(this.$messages[startIndex].subject)) {// || this.$messages[startIndex].loading) {\n // Message headers are loaded or data is coming\n loaded = true;\n }\n\n // Preload more headers if possible\n endIndex = Math.min(startIndex + Mailbox.PRELOAD.LOOKAHEAD, max - 1);\n if (angular.isDefined(this.$messages[endIndex].subject) ||\n angular.isDefined(this.$messages[endIndex].loading)) {\n index = Math.max(startIndex - Mailbox.PRELOAD.LOOKAHEAD, 0);\n if (!angular.isDefined(this.$messages[index].subject) &&\n !angular.isDefined(this.$messages[index].loading)) {\n // Previous messages not loaded; preload more headers further up\n endIndex = startIndex;\n startIndex = Math.max(startIndex - Mailbox.PRELOAD.SIZE, 0);\n }\n }\n else\n // Next messages not load; preload more headers further down\n endIndex = Math.min(startIndex + Mailbox.PRELOAD.SIZE, max - 1);\n\n if (!angular.isDefined(this.$messages[startIndex].subject) &&\n !angular.isDefined(this.$messages[startIndex].loading) ||\n !angular.isDefined(this.$messages[endIndex].subject) &&\n !angular.isDefined(this.$messages[endIndex].loading)) {\n\n for (uids = []; startIndex < endIndex && startIndex < max; startIndex++) {\n if (angular.isDefined(this.$messages[startIndex].subject) || this.$messages[startIndex].loading) {\n // Message at this index is already loaded; increase the end index\n endIndex++;\n }\n else {\n // Message at this index will be loaded\n uids.push(this.$messages[startIndex].uid);\n this.$messages[startIndex].loading = true;\n }\n }\n\n Mailbox.$log.debug('Loading UIDs ' + uids.join(' '));\n futureHeadersData = Mailbox.$$resource.post(this.id, 'headers', {uids: uids});\n this.$unwrapHeaders(futureHeadersData);\n }\n }\n return loaded;\n };\n\n /**\n * @function isEditable\n * @memberof Mailbox.prototype\n * @desc Checks if the mailbox is editable based on its type.\n * @returns true if the mailbox is not a special folder.\n */\n Mailbox.prototype.isEditable = function() {\n return this.type == 'folder';\n };\n\n /**\n * @function isNoInferiors\n * @memberof Mailbox.prototype\n * @desc Checks if the mailbox can contain submailboxes\n * @returns true if the mailbox can not contain submailboxes\n */\n Mailbox.prototype.isNoInferiors = function() {\n return this.flags.indexOf('noinferiors') >= 0;\n };\n\n /**\n * @function isNoSelect\n * @memberof Mailbox.prototype\n * @desc Checks if the mailbox can be selected\n * @returns true if the mailbox can not be selected\n */\n Mailbox.prototype.isNoSelect = function() {\n return this.flags.indexOf('noselect') >= 0;\n };\n\n /**\n * @function $rename\n * @memberof AddressBook.prototype\n * @desc Rename the addressbook and keep the list sorted\n * @param {string} name - the new name\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$rename = function() {\n var _this = this,\n findParent,\n parent,\n children,\n i;\n\n if (this.name == this.$shadowData.name) {\n // Name hasn't changed\n return Mailbox.$q.when();\n }\n\n // Local recursive function\n findParent = function(parent, children) {\n var parentMailbox = null,\n mailbox = _.find(children, function(o) {\n return o.path == _this.path;\n });\n if (mailbox) {\n parentMailbox = parent;\n }\n else {\n angular.forEach(children, function(o) {\n if (!parentMailbox && o.children && o.children.length > 0) {\n parentMailbox = findParent(o, o.children);\n }\n });\n }\n return parentMailbox;\n };\n\n // Find mailbox parent\n parent = findParent(null, this.$account.$mailboxes);\n if (parent === null)\n children = this.$account.$mailboxes;\n else\n children = parent.children;\n\n // Find index of mailbox among siblings\n i = _.indexOf(_.map(children, 'id'), this.id);\n\n return this.$save().then(function(data) {\n var sibling;\n angular.extend(_this, data); // update the path attribute\n _this.id = _this.$id();\n\n // Move mailbox among its siblings according to its new name\n children.splice(i, 1);\n sibling = _.find(children, function(o) {\n Mailbox.$log.debug(o.name + ' ? ' + _this.name);\n return (o.type == 'folder' && o.name.localeCompare(_this.name) > 0);\n });\n if (sibling) {\n i = _.indexOf(_.map(children, 'id'), sibling.id);\n }\n else {\n i = children.length;\n }\n children.splice(i, 0, _this);\n });\n };\n\n /**\n * @function $compact\n * @memberof Mailbox.prototype\n * @desc Compact the mailbox\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$compact = function() {\n var _this = this;\n return Mailbox.$$resource.post(this.id, 'expunge')\n .then(function(data) {\n // Update inbox quota\n if (data.quotas)\n _this.$account.updateQuota(data.quotas);\n });\n };\n\n /**\n * @function $setFolderAs\n * @memberof Mailbox.prototype\n * @desc Set a folder as Drafts/Sent/Trash\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$setFolderAs = function(type) {\n return Mailbox.$$resource.post(this.id, 'setAs' + type + 'Folder');\n };\n\n /**\n * @function $emptyTrash\n * @memberof Mailbox.prototype\n * @desc Empty the Trash folder.\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$emptyTrash = function() {\n var _this = this;\n\n return Mailbox.$$resource.post(this.id, 'emptyTrash').then(function(data) {\n // Remove all messages from the mailbox\n _this.$messages = [];\n _this.uidsMap = {};\n _this.unseenCount = 0;\n\n // If we had any submailboxes, lets do a refresh of the mailboxes list\n if (angular.isDefined(_this.children) && _this.children.length)\n _this.$account.$getMailboxes({reload: true});\n\n // Update inbox quota\n if (data.quotas)\n _this.$account.updateQuota(data.quotas);\n });\n };\n\n /**\n * @function $markAsRead\n * @memberof Mailbox.prototype\n * @desc Mark all messages from folder as read\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$markAsRead = function() {\n return Mailbox.$$resource.post(this.id, 'markRead');\n };\n\n /**\n * @function $flagMessages\n * @memberof Mailbox.prototype\n * @desc Add or remove a flag on a message set\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$flagMessages = function(messages, flags, operation) {\n var data = {msgUIDs: _.map(messages, 'uid'),\n flags: flags,\n operation: operation};\n\n return Mailbox.$$resource.post(this.id, 'addOrRemoveLabel', data).then(function() {\n return messages;\n });\n };\n\n /**\n * @function saveSelectedMessages\n * @memberof Mailbox.prototype\n * @desc Download the selected messages\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.saveSelectedMessages = function() {\n var data, options, selectedMessages, selectedUIDs;\n\n selectedMessages = _.filter(this.$messages, function(message) { return message.selected; });\n selectedUIDs = _.map(selectedMessages, 'uid');\n data = { uids: selectedUIDs };\n options = { filename: l('Saved Messages.zip') };\n\n return Mailbox.$$resource.download(this.id, 'saveMessages', {uids: selectedUIDs});\n };\n\n /**\n * @function exportFolder\n * @memberof Mailbox.prototype\n * @desc Export this mailbox\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.exportFolder = function() {\n var options;\n\n options = { filename: this.name + '.zip' };\n\n return Mailbox.$$resource.download(this.id, 'exportFolder', null, options);\n };\n\n /**\n * @function $delete\n * @memberof Mailbox.prototype\n * @desc Delete the mailbox from the server\n * @param {object} [options] - additional options (use {withoutTrash: true} to delete immediately)\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$delete = function(options) {\n var _this = this;\n\n return Mailbox.$$resource.post(this.id, 'delete', options)\n .then(function() {\n _this.$account.$getMailboxes({reload: true});\n return true;\n });\n };\n\n /**\n * @function $_deleteMessages\n * @memberof Mailbox.prototype\n * @desc Delete multiple messages from Mailbox object.\n * @param {string[]} uids - the messages uids\n * @param {object[]} messages - the Message instances\n * @return the index of the first deleted message\n */\n Mailbox.prototype.$_deleteMessages = function(uids, messages) {\n var _this = this, selectedUIDs, _$messages, unseen, firstIndex = this.$messages.length;\n\n // Decrement the unseen count\n unseen = _.filter(messages, function(message, i) { return !message.isread; });\n this.unseenCount -= unseen.length;\n\n // Remove messages from $messages and uidsMap\n _.forEachRight(this.$messages, function(message, index) {\n var selectedIndex = _.findIndex(uids, function(uid) {\n return message.uid == uid;\n });\n if (selectedIndex > -1) {\n uids.splice(selectedIndex, 1);\n delete _this.uidsMap[message.uid];\n if (message.uid == _this.selectedMessage)\n delete _this.selectedMessage;\n _this.$messages.splice(index, 1);\n if (index < firstIndex)\n firstIndex = index;\n }\n else {\n _this.uidsMap[message.uid] -= uids.length;\n }\n });\n\n // Return the index of the first deleted message\n return firstIndex;\n };\n\n /**\n * @function $deleteMessages\n * @memberof Mailbox.prototype\n * @desc Delete multiple messages from mailbox.\n * @param {object} [options] - additional options (use {withoutTrash: true} to delete immediately)\n * @return a promise of the HTTP operation\n */\n Mailbox.prototype.$deleteMessages = function(messages, options) {\n var _this = this, uids, data;\n\n uids = _.map(messages, 'uid');\n data = { uids: uids };\n if (options) angular.extend(data, options);\n\n return Mailbox.$$resource.post(this.id, 'batchDelete', data)\n .then(function(data) {\n // Update inbox quota\n if (data.quotas)\n _this.$account.updateQuota(data.quotas);\n\n return _this.$_deleteMessages(uids, messages);\n });\n };\n\n /**\n * @function $markOrUnMarkMessagesAsJunk\n * @memberof Mailbox.prototype\n * @desc Mark messages as junk/not junk\n * @return a promise of the HTTP operation\n */\n Mailbox.prototype.$markOrUnMarkMessagesAsJunk = function(messages) {\n var _this = this,\n uids = _.map(messages, 'uid'),\n method = (this.type == 'junk' ? 'markMessagesAsNotJunk' : 'markMessagesAsJunk');\n\n return Mailbox.$$resource.post(this.id, method, {uids: uids});\n };\n\n /**\n * @function $copyMessages\n * @memberof Mailbox.prototype\n * @desc Copy multiple messages from the current mailbox to a target one\n * @return a promise of the HTTP operation\n */\n Mailbox.prototype.$copyMessages = function(messages, folder) {\n var _this = this,\n uids = _.map(messages, 'uid');\n\n return Mailbox.$$resource.post(this.id, 'copyMessages', {uids: uids, folder: folder})\n .then(function(data) {\n // Update inbox quota\n if (data.quotas)\n _this.$account.updateQuota(data.quotas);\n });\n };\n\n /**\n * @function $moveMessages\n * @memberof Mailbox.prototype\n * @desc Move multiple messages from the current mailbox to a target one\n * @return a promise of the HTTP operation\n */\n Mailbox.prototype.$moveMessages = function(messages, folder) {\n var _this = this, uids;\n\n uids = _.map(messages, 'uid');\n return Mailbox.$$resource.post(this.id, 'moveMessages', {uids: uids, folder: folder})\n .then(function() {\n return _this.$_deleteMessages(uids, messages);\n });\n };\n\n /**\n * @function $reset\n * @memberof Mailbox.prototype\n * @desc Reset the original state the mailbox's data.\n */\n Mailbox.prototype.$reset = function() {\n var _this = this;\n angular.forEach(this.$shadowData, function(value, key) {\n delete _this[key];\n });\n angular.extend(this, this.$shadowData);\n this.$shadowData = this.$omit();\n };\n\n /**\n * @function $save\n * @memberof Mailbox.prototype\n * @desc Save the mailbox to the server. This currently can only affect the name of the mailbox.\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$save = function() {\n var _this = this;\n\n return Mailbox.$$resource.save(this.id, this.$omit()).then(function(data) {\n // Make a copy of the data for an eventual reset\n _this.$shadowData = _this.$omit();\n Mailbox.$log.debug(JSON.stringify(data, undefined, 2));\n return data;\n }, function(response) {\n Mailbox.$log.error(JSON.stringify(response.data, undefined, 2));\n // Restore previous version\n _this.$reset();\n return response.data;\n });\n };\n\n /**\n * @function $newMailbox\n * @memberof Mailbox.prototype\n * @desc Create a new mailbox on the server and refresh the list of mailboxes.\n * @returns a promise of the HTTP operations\n */\n Mailbox.prototype.$newMailbox = function(path, name) {\n return this.$account.$newMailbox(path, name);\n };\n\n /**\n * @function $omit\n * @memberof Mailbox.prototype\n * @desc Return a sanitized object used to send to the server.\n * @return an object literal copy of the Mailbox instance\n */\n Mailbox.prototype.$omit = function() {\n var mailbox = {};\n angular.forEach(this, function(value, key) {\n if (key != 'constructor' &&\n key != 'children' &&\n key != 'headers' &&\n key != 'uids' &&\n key != 'uidsMap' &&\n key[0] != '$') {\n mailbox[key] = value;\n }\n });\n return mailbox;\n };\n\n /**\n * @function $unwrap\n * @memberof Mailbox.prototype\n * @desc Unwrap a promise and instanciate new Message objects using received data.\n * @param {promise} futureMailboxData - a promise of the Mailbox's metadata\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$unwrap = function(futureMailboxData) {\n var _this = this,\n deferred = Mailbox.$q.defer();\n\n this.$futureMailboxData = futureMailboxData;\n this.$futureMailboxData.then(function(data) {\n Mailbox.$timeout(function() {\n var uids, headers;\n\n if (!data.uids || _this.$topIndex > data.uids.length - 1)\n _this.$topIndex = 0;\n\n _this.init(data);\n\n if (_this.uids) {\n Mailbox.$log.debug('unwrapping ' + data.uids.length + ' messages');\n\n // First entry of 'headers' are keys\n headers = _.invokeMap(_this.headers[0], 'toLowerCase');\n _this.headers.splice(0, 1);\n\n // First entry of 'uids' are keys when threaded view is enabled\n if (_this.threaded) {\n uids = _this.uids[0];\n _this.uids.splice(0, 1);\n }\n\n // Instanciate Message objects\n _.reduce(_this.uids, function(msgs, msg, i) {\n var data;\n if (_this.threaded)\n data = _.zipObject(uids, msg);\n else\n data = {uid: msg.toString()};\n\n // Build map of UID <=> index\n _this.uidsMap[data.uid] = i;\n\n msgs.push(new Mailbox.$Message(_this.$account.id, _this, data, true));\n\n return msgs;\n }, _this.$messages);\n\n // Extend Message objects with received headers\n _.forEach(_this.headers, function(data) {\n var msg = _.zipObject(headers, data),\n i = _this.uidsMap[msg.uid.toString()];\n _.extend(_this.$messages[i], msg);\n });\n }\n Mailbox.$log.debug('mailbox ' + _this.id + ' ready');\n _this.$isLoading = false;\n deferred.resolve(_this.$messages);\n });\n }, function(data) {\n angular.extend(_this, data);\n _this.isError = true;\n deferred.reject();\n });\n\n return deferred.promise;\n };\n\n /**\n * @function $unwrapHeaders\n * @memberof Mailbox.prototype\n * @desc Unwrap a promise and extend matching Message objects using received data.\n * @param {promise} futureHeadersData - a promise of some messages metadata\n */\n Mailbox.prototype.$unwrapHeaders = function(futureHeadersData) {\n var _this = this;\n\n futureHeadersData.then(function(data) {\n Mailbox.$timeout(function() {\n var headers, j;\n if (data.length > 0) {\n // First entry of 'headers' are keys\n headers = _.invokeMap(data[0], 'toLowerCase');\n data.splice(0, 1);\n _.forEach(data, function(messageHeaders) {\n messageHeaders = _.zipObject(headers, messageHeaders);\n j = _this.uidsMap[messageHeaders.uid.toString()];\n if (angular.isDefined(j)) {\n _.extend(_this.$messages[j], messageHeaders);\n }\n });\n }\n });\n });\n };\n\n /**\n * @function $updateSubscribe\n * @memberof Mailbox.prototype\n * @desc Update mailbox subscription state with server.\n */\n Mailbox.prototype.$updateSubscribe = function() {\n var action = this.subscribed? 'subscribe' : 'unsubscribe';\n\n Mailbox.$$resource.post(this.id, action);\n };\n\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @name Message\n * @constructor\n * @param {string} accountId - the account ID\n * @param {string} mailboxPath - an array of the mailbox path components\n * @param {object} futureAddressBookData - either an object literal or a promise\n * @param {bool} lazy - do \"lazy loading\" so we are very quick at initializing message instances\n */\n function Message(accountId, mailbox, futureMessageData, lazy) {\n this.accountId = accountId;\n this.$mailbox = mailbox;\n this.$hasUnsafeContent = false;\n this.$loadUnsafeContent = false;\n this.editable = {to: [], cc: [], bcc: []};\n this.selected = false;\n\n // Data is immediately available\n if (typeof futureMessageData.then !== 'function') {\n //console.debug(JSON.stringify(futureMessageData, undefined, 2));\n if (angular.isUndefined(lazy) || !lazy) {\n angular.extend(this, futureMessageData);\n this.$formatFullAddresses();\n }\n this.uid = parseInt(futureMessageData.uid);\n }\n else {\n // The promise will be unwrapped first\n this.$unwrap(futureMessageData);\n }\n }\n\n /**\n * @memberof Message\n * @desc The factory we'll use to register with Angular\n * @returns the Message constructor\n */\n Message.$factory = ['$q', '$timeout', '$log', 'sgSettings', 'sgMessage_STATUS', 'Resource', 'Preferences', function($q, $timeout, $log, Settings, Message_STATUS, Resource, Preferences) {\n angular.extend(Message, {\n STATUS: Message_STATUS,\n $q: $q,\n $timeout: $timeout,\n $log: $log,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Mail', Settings.activeUser()),\n $avatar: angular.bind(Preferences, Preferences.avatar)\n });\n // Initialize tags form user's defaults\n Preferences.ready().then(function() {\n if (Preferences.defaults.SOGoMailLabelsColors) {\n Message.$tags = Preferences.defaults.SOGoMailLabelsColors;\n }\n if (Preferences.defaults.SOGoMailDisplayRemoteInlineImages &&\n Preferences.defaults.SOGoMailDisplayRemoteInlineImages == 'always') {\n Message.$displayRemoteInlineImages = true;\n }\n });\n\n return Message; // return constructor\n }];\n\n /**\n * @module SOGo.MailerUI\n * @desc Factory registration of Message in Angular module.\n */\n try {\n angular.module('SOGo.MailerUI');\n }\n catch(e) {\n angular.module('SOGo.MailerUI', ['SOGo.Common']);\n }\n angular.module('SOGo.MailerUI')\n .constant('sgMessage_STATUS', {\n NOT_LOADED: 0,\n DELAYED_LOADING: 1,\n LOADING: 2,\n LOADED: 3,\n DELAYED_MS: 300\n })\n .factory('Message', Message.$factory);\n\n /**\n * @function filterTags\n * @memberof Message.prototype\n * @desc Search for tags (ie., mail labels) matching some criterias\n * @param {string} search - the search string to match\n * @returns a collection of strings\n */\n Message.filterTags = function(query, excludedTags) {\n var re = new RegExp(query, 'i'),\n results = [];\n\n _.forEach(_.keys(Message.$tags), function(tag) {\n var pair = Message.$tags[tag];\n if (pair[0].search(re) != -1) {\n if (!_.includes(excludedTags, tag))\n results.push({ name: tag, description: pair[0], color: pair[1] });\n }\n });\n\n return results;\n };\n\n /**\n * @function $absolutePath\n * @memberof Message.prototype\n * @desc Build the path of the message\n * @returns a string representing the path relative to the mail module\n */\n Message.prototype.$absolutePath = function(options) {\n var _this = this, id = this.id;\n\n function buildPath() {\n var path;\n path = _.map(_this.$mailbox.path.split('/'), function(component) {\n return 'folder' + component.asCSSIdentifier();\n });\n path.splice(0, 0, _this.accountId); // insert account ID\n return path.join('/');\n }\n\n if (angular.isUndefined(this.id) || options && options.nocache) {\n this.id = buildPath() + '/' + this.uid; // add message UID\n id = this.id;\n }\n if (options && options.asDraft && this.draftId) {\n id = buildPath() + '/' + this.draftId; // add draft ID\n }\n\n return id;\n };\n\n /**\n * @function $setUID\n * @memberof Message.prototype\n * @desc Change the UID of the message. This happens when saving a draft.\n * @param {number} uid - the new message UID\n */\n Message.prototype.$setUID = function(uid) {\n var oldUID = (this.uid || -1), _this = this, index;\n\n if (oldUID != parseInt(uid)) {\n this.uid = parseInt(uid);\n this.$absolutePath({nocache: true});\n if (oldUID > -1) {\n oldUID = oldUID.toString();\n if (angular.isDefined(this.$mailbox.uidsMap[oldUID])) {\n index = this.$mailbox.uidsMap[oldUID];\n this.$mailbox.uidsMap[uid] = index;\n delete this.$mailbox.uidsMap[oldUID];\n\n // Update messages list of mailbox\n _.forEach(['from', 'to', 'subject'], function(attr) {\n _this.$mailbox.$messages[index][attr] = _this[attr];\n });\n }\n }\n else {\n // Refresh selected folder if it's the drafts mailbox\n if (this.$mailbox.constructor.selectedFolder &&\n this.$mailbox.constructor.selectedFolder.type == 'draft') {\n this.$mailbox.constructor.selectedFolder.$filter();\n }\n }\n }\n };\n\n /**\n * @function $formatFullAddresses\n * @memberof Message.prototype\n * @desc Format all sender and recipients addresses with a complete description (name ).\n * This function also generates the avatar URL for each email address and a short name\n */\n Message.prototype.$formatFullAddresses = function() {\n var _this = this;\n var identities = _.map(_this.$mailbox.$account.identities, 'email');\n\n // Build long representation of email addresses\n _.forEach(['from', 'to', 'cc', 'bcc', 'reply-to'], function(type) {\n _.forEach(_this[type], function(data) {\n if (data.name && data.name != data.email) {\n data.full = data.name + ' <' + data.email + '>';\n\n if (data.name.length < 10)\n // Name is already short\n data.shortname = data.name;\n else if (data.name.split(' ').length)\n // If we have \"Alice Foo\" or \"Foo, Alice\" as name, we grab \"Alice\"\n data.shortname = _.first(_.last(data.name.split(/, */)).split(/ +/)).replace('\\'','');\n }\n else if (data.email) {\n data.full = '<' + data.email + '>';\n data.shortname = data.email.split('@')[0];\n }\n\n data.image = Message.$avatar(data.email, 32);\n\n // If the current user is the recepient, overwrite\n // the short name with 'me'\n if (_.indexOf(identities, data.email) >= 0)\n data.shortname = l('me');\n });\n });\n };\n\n /**\n * @function $shortRecipients\n * @memberof Message.prototype\n * @desc Format all recipients into a very compact string\n * @returns a compacted string of all recipients\n */\n Message.prototype.$shortRecipients = function(max) {\n var _this = this, result = [], count = 0, total = 0;\n\n // Build short representation of email addresses\n _.forEach(['to', 'cc', 'bcc'], function(type) {\n total += _this[type]? _this[type].length : 0;\n _.forEach(_this[type], function(data, i) {\n if (count < max)\n result.push(data.shortname);\n count++;\n });\n });\n\n if (total > max)\n result.push(l('and %{0} more...', (total - max)));\n\n return result.join(', ');\n };\n\n /**\n * @function $shortAddress\n * @memberof Message.prototype\n * @desc Format the first address of a specific type with a short description.\n * @returns a string of the name or the email of the envelope address type\n */\n Message.prototype.$shortAddress = function(type) {\n var address = '';\n if (this[type] && this[type].length > 0) {\n address = this[type][0].name || this[type][0].email || '';\n }\n\n return address;\n };\n\n /**\n * @function allowReplyAll\n * @memberof Message.prototype\n * @desc Check if 'Reply to All' is an appropriate action on the message.\n * @returns true if the message is not a draft and has more than one recipient\n */\n Message.prototype.allowReplyAll = function() {\n var recipientsCount = 0;\n recipientsCount = _.reduce(['to', 'cc'], _.bind(function(count, type) {\n if (this[type])\n return count + this[type].length;\n else\n return count;\n }, this), recipientsCount);\n\n return !this.isDraft && recipientsCount > 1;\n };\n\n /**\n * @function loadUnsafeContent\n * @memberof Message.prototype\n * @desc Mark the message to load unsafe resources when calling $content().\n */\n Message.prototype.loadUnsafeContent = function() {\n this.$loadUnsafeContent = true;\n };\n\n /**\n * @function $content\n * @memberof Message.prototype\n * @desc Get the message body as accepted by SCE (Angular Strict Contextual Escaping).\n * @returns the HTML representation of the body\n */\n Message.prototype.$content = function() {\n var _this = this,\n parts = [],\n _visit = function(part) {\n part.msgclass = 'msg-attachment-other';\n if (part.type == 'UIxMailPartAlternativeViewer') {\n _visit(_.find(part.content, function(alternatePart) {\n return part.preferredPart == alternatePart.contentType;\n }));\n }\n // Can be used for UIxMailPartMixedViewer, UIxMailPartMessageViewer, and UIxMailPartSignedViewer\n else if (angular.isArray(part.content)) {\n if (part.type == 'UIxMailPartSignedViewer' && part['supports-smime'] === 1) {\n // First line in a h1, others each in a p\n var formattedMessage = \"

\" + part.error.replace(/\\n/, \"

\");\n formattedMessage = formattedMessage.replace(/\\n/g, \"

\") + \"

\";\n _this.$smime = {\n validSignature: part.valid,\n message: formattedMessage\n };\n }\n _.forEach(part.content, function(mixedPart) {\n _visit(mixedPart);\n });\n }\n else {\n if (angular.isUndefined(part.safeContent)) {\n // Keep a copy of the original content\n part.safeContent = part.content;\n _this.$hasUnsafeContent |= (part.safeContent.indexOf(' unsafe-') > -1);\n }\n if (part.type == 'UIxMailPartHTMLViewer') {\n part.html = true;\n if (_this.$loadUnsafeContent || Message.$displayRemoteInlineImages) {\n if (angular.isUndefined(part.unsafeContent)) {\n part.unsafeContent = document.createElement('div');\n part.unsafeContent.innerHTML = part.safeContent;\n angular.forEach(['src', 'data', 'classid', 'background', 'style'], function(suffix) {\n var elements = part.unsafeContent.querySelectorAll('[unsafe-' + suffix + ']'),\n element,\n value,\n i;\n for (i = 0; i < elements.length; i++) {\n element = angular.element(elements[i]);\n value = element.attr('unsafe-' + suffix);\n element.attr(suffix, value);\n element.removeAttr('unsafe-' + suffix);\n }\n });\n _this.$hasUnsafeContent = false;\n }\n part.content = part.unsafeContent.innerHTML;\n }\n else {\n part.content = part.safeContent;\n }\n parts.push(part);\n }\n else if (part.type == 'UIxMailPartICalViewer' ||\n part.type == 'UIxMailPartImageViewer' ||\n part.type == 'UIxMailPartLinkViewer') {\n\n if (part.type == 'UIxMailPartImageViewer')\n part.msgclass = 'msg-attachment-image';\n else if (part.type == 'UIxMailPartLinkViewer')\n part.msgclass = 'msg-attachment-link';\n\n // Trusted content that can be compiled (Angularly-speaking)\n part.compile = true;\n parts.push(part);\n }\n else {\n part.html = true;\n part.content = part.safeContent;\n parts.push(part);\n }\n }\n };\n\n if (this.parts)\n _visit(this.parts);\n\n return parts;\n };\n\n /**\n * @function $editableContent\n * @memberof Message.prototype\n * @desc First, fetch the draft ID that corresponds to the temporary draft object on the SOGo server.\n * Secondly, fetch the editable message body along with other metadata such as the recipients.\n * @returns the HTML representation of the body\n */\n Message.prototype.$editableContent = function() {\n var _this = this;\n\n return Message.$$resource.fetch(this.$absolutePath(), 'edit').then(function(data) {\n angular.extend(_this, data);\n return Message.$$resource.fetch(_this.$absolutePath({asDraft: true}), 'edit').then(function(data) {\n // Try to match a known account identity from the specified \"from\" address\n var identity = _.find(_this.$mailbox.$account.identities, function(identity) {\n return data.from.toLowerCase().indexOf(identity.email) !== -1;\n });\n if (identity)\n data.from = identity.full;\n Message.$log.debug('editable = ' + JSON.stringify(data, undefined, 2));\n angular.extend(_this.editable, data);\n return data.text;\n });\n });\n };\n\n /**\n * @function $plainContent\n * @memberof Message.prototype\n * @returns the a plain text representation of the subject and body\n */\n Message.prototype.$plainContent = function() {\n return Message.$$resource.fetch(this.$absolutePath(), 'viewplain');\n };\n\n /**\n * @function addTag\n * @memberof Message.prototype\n * @desc Add a mail tag on the current message.\n * @param {string} tag - the tag name\n * @returns a promise of the HTTP operation\n */\n Message.prototype.addTag = function(tag) {\n return this.$addOrRemoveTag('add', tag);\n };\n\n /**\n * @function removeTag\n * @memberof Message.prototype\n * @desc Remove a mail tag from the current message.\n * @param {string} tag - the tag name\n * @returns a promise of the HTTP operation\n */\n Message.prototype.removeTag = function(tag) {\n return this.$addOrRemoveTag('remove', tag);\n };\n\n /**\n * @function $addOrRemoveTag\n * @memberof Message.prototype\n * @desc Add or remove a mail tag on the current message.\n * @param {string} operation - the operation name to perform\n * @param {string} tag - the tag name\n * @returns a promise of the HTTP operation\n */\n Message.prototype.$addOrRemoveTag = function(operation, tag) {\n var data = {\n operation: operation,\n msgUIDs: [this.uid],\n flags: tag\n };\n\n if (tag)\n return Message.$$resource.post(this.$mailbox.$id(), 'addOrRemoveLabel', data);\n };\n\n /**\n * @function $imipAction\n * @memberof Message.prototype\n * @desc Perform IMIP actions on the current message.\n * @param {string} path - the path of the IMIP calendar part\n * @param {string} action - the the IMIP action to perform\n * @param {object} data - the delegation info\n */\n Message.prototype.$imipAction = function(path, action, data) {\n var _this = this;\n Message.$$resource.post([this.$absolutePath(), path].join('/'), action, data).then(function(data) {\n Message.$timeout(function() {\n _this.$reload();\n });\n });\n };\n\n /**\n * @function $sendMDN\n * @memberof Message.prototype\n * @desc Send MDN response for current email message\n */\n Message.prototype.$sendMDN = function() {\n this.shouldAskReceipt = 0;\n return Message.$$resource.post(this.$absolutePath(), 'sendMDN');\n };\n\n /**\n * @function $deleteAttachment\n * @memberof Message.prototype\n * @desc Delete an attachment from a message being composed\n * @param {string} filename - the filename of the attachment to delete\n */\n Message.prototype.$deleteAttachment = function(filename) {\n var action = 'deleteAttachment?filename=' + filename;\n var _this = this;\n Message.$$resource.post(this.$absolutePath({asDraft: true}), action).then(function(data) {\n Message.$timeout(function() {\n _this.editable.attachmentAttrs = _.filter(_this.editable.attachmentAttrs, function(attachment) {\n return attachment.filename != filename;\n });\n });\n });\n };\n\n /**\n * @function $markAsFlaggedOrUnflagged\n * @memberof Message.prototype\n * @desc Add or remove a the \\\\Flagged flag on the current message.\n * @returns a promise of the HTTP operation\n */\n Message.prototype.toggleFlag = function() {\n var _this = this,\n action = 'markMessageFlagged';\n\n if (this.isflagged)\n action = 'markMessageUnflagged';\n\n return Message.$$resource.post(this.$absolutePath(), action).then(function(data) {\n Message.$timeout(function() {\n _this.isflagged = !_this.isflagged;\n });\n });\n };\n\n /**\n * @function $isLoading\n * @memberof Message.prototype\n * @returns true if the Message content is still being retrieved from server after a specific delay\n * @see sgMessage_STATUS\n */\n Message.prototype.$isLoading = function() {\n return this.$loaded == Message.STATUS.LOADING;\n };\n\n /**\n * @function $reload\n * @memberof Message.prototype\n * @desc Fetch the viewable message body along with other metadata such as the list of attachments.\n * @param {object} [options] - set {useCache: true} to use already fetched data\n * @returns a promise of the HTTP operation\n */\n Message.prototype.$reload = function(options) {\n var _this = this, futureMessageData;\n\n if (options && options.useCache && this.$futureMessageData) {\n if (!this.isread) {\n Message.$$resource.fetch(this.$absolutePath(), 'markMessageRead').then(function() {\n Message.$timeout(function() {\n _this.isread = true;\n _this.$mailbox.unseenCount--;\n });\n });\n }\n return this;\n }\n\n futureMessageData = Message.$$resource.fetch(this.$absolutePath(options), 'view');\n\n return this.$unwrap(futureMessageData);\n };\n\n /**\n * @function $reply\n * @memberof Message.prototype\n * @desc Prepare a new Message object as a reply to the sender.\n * @returns a promise of the HTTP operations\n */\n Message.prototype.$reply = function() {\n return this.$newDraft('reply');\n };\n\n /**\n * @function $replyAll\n * @memberof Message.prototype\n * @desc Prepare a new Message object as a reply to the sender and all recipients.\n * @returns a promise of the HTTP operations\n */\n Message.prototype.$replyAll = function() {\n return this.$newDraft('replyall');\n };\n\n /**\n * @function $forward\n * @memberof Message.prototype\n * @desc Prepare a new Message object as a forward.\n * @returns a promise of the HTTP operations\n */\n Message.prototype.$forward = function() {\n return this.$newDraft('forward');\n };\n\n /**\n * @function $newDraft\n * @memberof Message.prototype\n * @desc Prepare a new Message object as a reply or a forward of the current message and associated\n * to the draft mailbox.\n * @see {@link Account.$newMessage}\n * @see {@link Message.$editableContent}\n * @see {@link Message.$reply}\n * @see {@link Message.$replyAll}\n * @see {@link Message.$forwad}\n * @param {string} action - the HTTP action to perform on the message\n * @returns a promise of the HTTP operations\n */\n Message.prototype.$newDraft = function(action) {\n var _this = this;\n\n // Query server for draft folder and draft UID\n return Message.$$resource.fetch(this.$absolutePath(), action).then(function(data) {\n var mailbox, message;\n Message.$log.debug('New ' + action + ': ' + JSON.stringify(data, undefined, 2));\n mailbox = _this.$mailbox.$account.$getMailboxByPath(data.mailboxPath);\n message = new Message(data.accountId, mailbox, data);\n // Fetch draft initial data\n return Message.$$resource.fetch(message.$absolutePath({asDraft: true}), 'edit').then(function(data) {\n Message.$log.debug('New ' + action + ': ' + JSON.stringify(data, undefined, 2) + ' original UID: ' + _this.uid);\n angular.extend(message.editable, data);\n\n // We keep a reference to our original message in order to update the flags\n message.origin = {message: _this, action: action};\n return message;\n });\n });\n };\n\n /**\n * @function $save\n * @memberof Message.prototype\n * @desc Save the message to the server.\n * @returns a promise of the HTTP operation\n */\n Message.prototype.$save = function() {\n var _this = this,\n data = this.editable;\n\n Message.$log.debug('save = ' + JSON.stringify(data, undefined, 2));\n\n return Message.$$resource.save(this.$absolutePath({asDraft: true}), data).then(function(response) {\n Message.$log.debug('save = ' + JSON.stringify(response, undefined, 2));\n _this.$setUID(response.uid);\n _this.$reload(); // fetch a new viewable version of the message\n _this.isNew = false;\n });\n };\n\n /**\n * @function $send\n * @memberof Message.prototype\n * @desc Send the message.\n * @returns a promise of the HTTP operation\n */\n Message.prototype.$send = function() {\n var _this = this,\n data = angular.copy(this.editable);\n\n Message.$log.debug('send = ' + JSON.stringify(data, undefined, 2));\n\n return Message.$$resource.post(this.$absolutePath({asDraft: true}), 'send', data).then(function(response) {\n if (response.status == 'success') {\n if (angular.isDefined(_this.origin)) {\n if (_this.origin.action.startsWith('reply'))\n _this.origin.message.isanswered = true;\n else if (_this.origin.action == 'forward')\n _this.origin.message.isforwarded = true;\n }\n return response;\n }\n else {\n return Message.$q.reject(response.data);\n }\n });\n };\n\n /**\n * @function $unwrap\n * @memberof Message.prototype\n * @desc Unwrap a promise.\n * @param {promise} futureMessageData - a promise of some of the Message's data\n */\n Message.prototype.$unwrap = function(futureMessageData) {\n var _this = this;\n\n // Message is not loaded yet\n this.$loaded = Message.STATUS.DELAYED_LOADING;\n Message.$timeout(function() {\n if (_this.$loaded != Message.STATUS.LOADED)\n _this.$loaded = Message.STATUS.LOADING;\n }, Message.STATUS.DELAYED_MS);\n\n // Resolve and expose the promise\n this.$futureMessageData = futureMessageData.then(function(data) {\n // Calling $timeout will force Angular to refresh the view\n if (_this.isread === 0) {\n _this.isread = true;\n _this.$mailbox.unseenCount--;\n }\n return Message.$timeout(function() {\n angular.extend(_this, data);\n _this.$formatFullAddresses();\n _this.$loadUnsafeContent = false;\n _this.$loaded = Message.STATUS.LOADED;\n return _this;\n });\n });\n\n return this.$futureMessageData;\n };\n\n /**\n * @function $omit\n * @memberof Message.prototype\n * @desc Return a sanitized object used to send to the server.\n * @return an object literal copy of the Message instance\n */\n Message.prototype.$omit = function(options) {\n var message = {},\n privateAttributes = options && options.privateAttributes;\n angular.forEach(this, function(value, key) {\n if (key != 'constructor' && key[0] != '$' || privateAttributes) {\n message[key] = value;\n }\n });\n\n return message;\n };\n\n /**\n * @function download\n * @memberof Message.prototype\n * @desc Download the current message\n * @returns a promise of the HTTP operation\n */\n Message.prototype.download = function() {\n var data, options;\n\n data = { uids: [this.uid] };\n options = { filename: this.subject + '.zip' };\n\n return Message.$$resource.download(this.$mailbox.id, 'saveMessages', data, options);\n };\n\n /**\n * @function downloadAttachments\n * @memberof Message.prototype\n * @desc Download an archive of all attachments\n * @returns a promise of the HTTP operation\n */\n Message.prototype.downloadAttachments = function() {\n var options;\n\n options = { filename: l('attachments') + \"-\" + this.uid + \".zip\" };\n\n return Message.$$resource.download(this.$absolutePath(), 'archiveAttachments', null, options);\n };\n\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @name VirtualMailbox\n * @constructor\n * @param {object} account - the mail account associated with the virtual search\n */\n function VirtualMailbox(account) {\n this.$account = account;\n }\n\n /**\n * @memberof VirtualMailbox\n * @desc The factory we'll use to register with Angular\n * @returns the VirtualMailbox constructor\n */\n VirtualMailbox.$factory = ['$q', '$timeout', '$log', 'sgSettings', 'Resource', 'Message', 'Mailbox', 'sgMailbox_PRELOAD', function($q, $timeout, $log, Settings, Resource, Mailbox, Message, PRELOAD) {\n angular.extend(VirtualMailbox, {\n $q: $q,\n $timeout: $timeout,\n $log: $log,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Mail', Settings.activeUser()),\n $Message: Message,\n selectedFolder: null,\n PRELOAD: PRELOAD\n });\n\n return VirtualMailbox; // return constructor\n }];\n\n /**\n * @module SOGo.MailerUI\n * @desc Factory registration of VirtualMailbox in Angular module.\n */\n try {\n angular.module('SOGo.MailerUI');\n }\n catch(e) {\n angular.module('SOGo.MailerUI', ['SOGo.Common']);\n }\n angular.module('SOGo.MailerUI')\n .constant('sgMailbox_PRELOAD', {\n LOOKAHEAD: 50,\n SIZE: 100\n })\n .factory('VirtualMailbox', VirtualMailbox.$factory);\n\n /**\n * @memberof VirtualMailbox\n * @desc Build the path of the virtual mailbox (or account only).\n * @param {string} accountId - the account ID\n * @returns a string representing the path relative to the mail module\n */\n VirtualMailbox.$absolutePath = function(accountId) {\n return [accountId, \"virtual\"].join('/');\n };\n\n /**\n * @function init\n * @memberof VirtualMailbox.prototype\n * @desc Extend instance with new data and compute additional attributes.\n * @param {object} data - attributes of mailbox\n */\n VirtualMailbox.prototype.init = function(data) {\n this.$isLoading = false;\n this.$mailboxes = [];\n this.uidsMap = {};\n angular.extend(this, data);\n this.id = this.$id();\n };\n\n VirtualMailbox.prototype.setMailboxes = function(data) {\n this.$mailboxes = data;\n\n _.forEach(this.$mailboxes, function(mailbox) {\n mailbox.$messages = [];\n mailbox.uidsMap = {};\n });\n };\n\n VirtualMailbox.prototype.startSearch = function(match, params) {\n var _this = this,\n search = VirtualMailbox.$q.when();\n\n this.$isLoading = true;\n\n _.forEach(this.$mailboxes, function(mailbox) {\n search = search.then(function() {\n if (_this.$isLoading) {\n VirtualMailbox.$log.debug(\"searching mailbox \" + mailbox.path);\n return mailbox.$filter( {sort: \"date\", asc: false, match: match}, params);\n }\n });\n });\n\n search.finally(function() {\n _this.$isLoading = false;\n });\n };\n\n VirtualMailbox.prototype.stopSearch = function() {\n VirtualMailbox.$log.debug(\"stopping search...\");\n this.$isLoading = false;\n };\n\n /**\n * @function selectFolder\n * @memberof VirtualMailbox.prototype\n * @desc A no-op for virtual mailbox\n */\n VirtualMailbox.prototype.selectFolder = function() {\n return;\n };\n\n /**\n * @function resetSelectedMessage\n * @memberof VirtualMailbox.prototype\n * @desc Delete 'selectedMessage' attribute of all submailboxes.\n */\n VirtualMailbox.prototype.resetSelectedMessage = function() {\n _.forEach(this.$mailboxes, function(mailbox) {\n delete mailbox.selectedMessage;\n });\n };\n\n /**\n * @function hasSelectedMessage\n * @memberof VirtualMailbox.prototype\n * @desc Check if a message is selected among the resulting mailboxes\n * @returns true if one message is selected\n */\n VirtualMailbox.prototype.hasSelectedMessage = function() {\n return angular.isDefined(_.find(this.$mailboxes, function(mailbox) {\n return angular.isDefined(mailbox.selectedMessage);\n }));\n };\n\n /**\n * @function isSelectedMessage\n * @memberof VirtualMailbox.prototype\n * @desc Check if the message of the specified mailbox is selected.\n * @param {string} messageId\n * @param {string} mailboxPath\n * @returns true if the specified message is selected\n */\n VirtualMailbox.prototype.isSelectedMessage = function(messageId, mailboxPath) {\n return angular.isDefined(_.find(this.$mailboxes, function(mailbox) {\n return mailbox.path == mailboxPath && mailbox.selectedMessage == messageId;\n }));\n };\n\n /**\n * @function getLength\n * @memberof VirtualMailbox.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the number of items in the mailbox\n */\n VirtualMailbox.prototype.getLength = function() {\n var len = 0;\n\n if (!angular.isDefined(this.$mailboxes))\n return len;\n\n _.forEach(this.$mailboxes, function(mailbox) {\n len += mailbox.$messages.length;\n });\n\n return len;\n };\n\n /**\n * @function getItemAtIndex\n * @memberof VirtualMailbox.prototype\n * @desc Used by md-virtual-repeat / md-on-demand\n * @returns the message as the specified index\n */\n VirtualMailbox.prototype.getItemAtIndex = function(index) {\n var i, j, k, mailbox, message;\n\n if (angular.isDefined(this.$mailboxes) && index >= 0) {\n i = 0;\n for (j = 0; j < this.$mailboxes.length; j++) {\n mailbox = this.$mailboxes[j];\n for (k = 0; k < mailbox.$messages.length; i++, k++) {\n message = mailbox.$messages[k];\n if (i == index) {\n if (mailbox.$loadMessage(message.uid))\n return message;\n }\n }\n }\n }\n\n return null;\n };\n\n /**\n * @function $id\n * @memberof VirtualMailbox.prototype\n * @desc Build the unique ID to identified the mailbox.\n * @returns a string representing the path relative to the mail module\n */\n VirtualMailbox.prototype.$id = function() {\n return VirtualMailbox.$absolutePath(this.$account.id);\n };\n\n /**\n * @function $selectedMessages\n * @memberof VirtualMailbox.prototype\n * @desc Return an associative array of the selected messages for each mailbox. Keys are the mailboxes ids.\n * @returns an associative array\n */\n VirtualMailbox.prototype.$selectedMessages = function() {\n var messagesMap = {};\n return _.transform(this.$mailboxes, function(messagesMap, mailbox) {\n messagesMap[mailbox.id] = mailbox.$selectedMessages();\n }, {});\n };\n\n /**\n * @function $selectedCount\n * @memberof VirtualMailbox.prototype\n * @desc Return the number of messages selected by the user.\n * @returns the number of selected messages\n */\n VirtualMailbox.prototype.$selectedCount = function() {\n return _.sum(_.invokeMap(this.$mailboxes, '$selectedCount'));\n };\n\n /**\n * @function $flagMessages\n * @memberof VirtualMailbox.prototype\n * @desc Add or remove a flag on a message set\n * @param {object} messagesMap\n * @param {array} flags\n * @param {string} operation\n * @returns a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$flagMessages = function(messagesMap, flags, operation) {\n var data = {\n flags: flags,\n operation: operation\n };\n var allMessages = [];\n var promises = [];\n\n _.forEach(messagesMap, function(messages, id) {\n if (messages.length > 0) {\n var uids = _.map(messages, 'uid');\n allMessages.push(messages);\n var promise = VirtualMailbox.$$resource.post(id, 'addOrRemoveLabel', _.assign(data, {msgUIDs: uids}));\n promises.push(promise);\n }\n });\n\n return VirtualMailbox.$q.all(promises).then(function() {\n return _.flatten(allMessages);\n });\n };\n\n /**\n * @function $deleteMessages\n * @memberof VirtualMailbox.prototype\n * @desc Delete multiple messages from mailbox.\n * @param {object} messagesMap\n * @return a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$deleteMessages = function(messagesMap) {\n var promises = [];\n\n _.forEach(messagesMap, function(messages, id) {\n if (messages.length > 0) {\n var mailbox = messages[0].$mailbox;\n var promise = mailbox.$deleteMessages(messages);\n promises.push(promise);\n }\n });\n\n return VirtualMailbox.$q.all(promises);\n };\n\n /**\n * @function $markOrUnMarkMessagesAsJunk\n * @memberof VirtualMailbox.prototype\n * @desc Mark messages as junk/not junk\n * @param {object} messagesMap\n * @return a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$markOrUnMarkMessagesAsJunk = function(messagesMap) {\n var promises = [];\n\n _.forEach(messagesMap, function(messages, id) {\n if (messages.length > 0) {\n var mailbox = messages[0].$mailbox;\n var promise = mailbox.$markOrUnMarkMessagesAsJunk(messages);\n promises.push(promise);\n }\n });\n\n return VirtualMailbox.$q.all(promises);\n };\n\n /**\n * @function $copyMessages\n * @memberof VirtualMailbox.prototype\n * @desc Copy multiple messages from the current mailbox to a target one\n * @param {object} messagesMap\n * @param {string} folder\n * @return a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$copyMessages = function(messagesMap, folder) {\n var promises = [];\n\n _.forEach(messagesMap, function(messages, id) {\n if (messages.length > 0) {\n var mailbox = messages[0].$mailbox;\n var promise = mailbox.$copyMessages(messages, folder);\n promises.push(promise);\n }\n });\n\n return VirtualMailbox.$q.all(promises);\n };\n\n /**\n * @function $moveMessages\n * @memberof VirtualMailbox.prototype\n * @desc Move multiple messages from the current mailbox to a target one\n * @param {object} messagesMap\n * @param {string} folder\n * @return a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$moveMessages = function(messagesMap, folder) {\n var promises = [];\n\n _.forEach(messagesMap, function(messages, id) {\n if (messages.length > 0) {\n var mailbox = messages[0].$mailbox;\n var promise = mailbox.$moveMessages(messages, folder);\n promises.push(promise);\n }\n });\n\n return VirtualMailbox.$q.all(promises);\n };\n\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n MailboxController.$inject = ['$window', '$scope', '$timeout', '$q', '$state', '$mdDialog', '$mdToast', 'stateAccounts', 'stateAccount', 'stateMailbox', 'sgHotkeys', 'encodeUriFilter', 'sgSettings', 'sgFocus', 'Dialog', 'Account', 'Mailbox'];\n function MailboxController($window, $scope, $timeout, $q, $state, $mdDialog, $mdToast, stateAccounts, stateAccount, stateMailbox, sgHotkeys, encodeUriFilter, sgSettings, focus, Dialog, Account, Mailbox) {\n var vm = this,\n defaultWindowTitle = angular.element($window.document).find('title').attr('sg-default') || \"SOGo\",\n hotkeys = [];\n\n // Expose controller for eventual popup windows\n $window.$mailboxController = vm;\n\n vm.service = Mailbox;\n vm.accounts = stateAccounts;\n vm.account = stateAccount;\n vm.selectedFolder = stateMailbox;\n vm.selectMessage = selectMessage;\n vm.messageDialog = null; // also access from Message controller\n vm.toggleMessageSelection = toggleMessageSelection;\n vm.sort = sort;\n vm.sortedBy = sortedBy;\n vm.searchMode = searchMode;\n vm.cancelSearch = cancelSearch;\n vm.newMessage = newMessage;\n vm.mode = { search: false, multiple: 0 };\n vm.confirmDeleteSelectedMessages = confirmDeleteSelectedMessages;\n vm.markOrUnMarkMessagesAsJunk = markOrUnMarkMessagesAsJunk;\n vm.copySelectedMessages = copySelectedMessages;\n vm.moveSelectedMessages = moveSelectedMessages;\n vm.markSelectedMessagesAsFlagged = markSelectedMessagesAsFlagged;\n vm.markSelectedMessagesAsUnread = markSelectedMessagesAsUnread;\n vm.markSelectedMessagesAsRead = markSelectedMessagesAsRead;\n vm.selectAll = selectAll;\n vm.unselectMessages = unselectMessages;\n\n\n stateMailbox.selectFolder();\n\n _registerHotkeys(hotkeys);\n\n // Expunge mailbox when leaving the Mail module\n angular.element($window).on('beforeunload', _compactBeforeUnload);\n $scope.$on('$destroy', function() {\n angular.element($window).off('beforeunload', _compactBeforeUnload);\n // Deregister hotkeys\n _.forEach(hotkeys, function(key) {\n sgHotkeys.deregisterHotkey(key);\n });\n });\n\n // Update window's title with unseen messages count of selected mailbox\n $scope.$watch(function() { return vm.selectedFolder.unseenCount; }, function(unseenCount) {\n var title = defaultWindowTitle + ' - ';\n if (unseenCount)\n title += '(' + unseenCount + ') ';\n title += vm.selectedFolder.name;\n $window.document.title = title;\n });\n\n\n function _registerHotkeys(keys) {\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_search'),\n description: l('Search'),\n callback: searchMode\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_compose'),\n description: l('Write a new message'),\n callback: function($event) {\n if (vm.messageDialog === null)\n newMessage($event);\n }\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_junk'),\n description: l('Mark the selected messages as junk'),\n callback: markOrUnMarkMessagesAsJunk\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'space',\n description: l('Toggle item'),\n callback: toggleMessageSelection\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'shift+space',\n description: l('Toggle range of items'),\n callback: toggleMessageSelection\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'up',\n description: l('View next item'),\n callback: _nextMessage,\n preventInClass: ['sg-mail-part']\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'down',\n description: l('View previous item'),\n callback: _previousMessage,\n preventInClass: ['sg-mail-part']\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'shift+up',\n description: l('Add next item to selection'),\n callback: _addNextMessageToSelection,\n preventInClass: ['sg-mail-part']\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'shift+down',\n description: l('Add previous item to selection'),\n callback: _addPreviousMessageToSelection,\n preventInClass: ['sg-mail-part']\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'backspace',\n description: l('Delete selected message or folder'),\n callback: confirmDeleteSelectedMessages\n }));\n\n // Register the hotkeys\n _.forEach(keys, function(key) {\n sgHotkeys.registerHotkey(key);\n });\n }\n\n function _compactBeforeUnload(event) {\n return vm.selectedFolder.$compact();\n }\n\n function sort(field) {\n vm.selectedFolder.$filter({ sort: field });\n }\n\n function sortedBy(field) {\n return Mailbox.$query.sort == field;\n }\n\n function searchMode() {\n vm.mode.search = true;\n focus('search');\n }\n\n function cancelSearch() {\n vm.mode.search = false;\n vm.selectedFolder.$filter().then(function() {\n if (vm.selectedFolder.selectedMessage) {\n $timeout(function() {\n vm.selectedFolder.$topIndex = vm.selectedFolder.uidsMap[vm.selectedFolder.selectedMessage];\n });\n }\n });\n }\n\n function newMessage($event, inPopup) {\n var message;\n\n if (vm.messageDialog === null) {\n if (inPopup)\n _newMessageInPopup();\n else {\n message = vm.account.$newMessage();\n vm.messageDialog = $mdDialog\n .show({\n parent: angular.element(document.body),\n targetEvent: $event,\n clickOutsideToClose: false,\n escapeToClose: false,\n templateUrl: 'UIxMailEditor',\n controller: 'MessageEditorController',\n controllerAs: 'editor',\n locals: {\n stateAccount: vm.account,\n stateMessage: message\n }\n })\n .finally(function() {\n vm.messageDialog = null;\n });\n }\n }\n }\n\n function _newMessageInPopup() {\n var url = [sgSettings.baseURL(),\n 'UIxMailPopupView#!/Mail',\n vm.account.id,\n // The double-encoding is necessary\n encodeUriFilter(encodeUriFilter(vm.selectedFolder.path)),\n 'new']\n .join('/'),\n wId = vm.selectedFolder.$id() + '/' + Math.random(0, 1000);\n console.debug(url);\n $window.open(url, wId,\n [\"width=680\",\n \"height=520\",\n \"resizable=1\",\n \"scrollbars=1\",\n \"toolbar=0\",\n \"location=0\",\n \"directories=0\",\n \"status=0\",\n \"menubar=0\",\n \"copyhistory=0\"]\n .join(','));\n }\n\n /**\n * User has pressed up arrow key\n */\n function _nextMessage($event) {\n var index = vm.selectedFolder.$selectedMessageIndex();\n\n if (angular.isDefined(index)) {\n index--;\n if (vm.selectedFolder.$topIndex > 0)\n vm.selectedFolder.$topIndex--;\n }\n else {\n // No message is selected, show oldest message\n index = vm.selectedFolder.getLength() - 1;\n vm.selectedFolder.$topIndex = vm.selectedFolder.getLength();\n }\n\n if (index > -1)\n selectMessage(vm.selectedFolder.$messages[index]);\n\n $event.preventDefault();\n\n return index;\n }\n\n /**\n * User has pressed the down arrow key\n */\n function _previousMessage($event) {\n var index = vm.selectedFolder.$selectedMessageIndex();\n\n if (angular.isDefined(index)) {\n index++;\n if (vm.selectedFolder.$topIndex < vm.selectedFolder.getLength())\n vm.selectedFolder.$topIndex++;\n }\n else\n // No message is selected, show newest\n index = 0;\n\n if (index < vm.selectedFolder.getLength())\n selectMessage(vm.selectedFolder.$messages[index]);\n else\n index = -1;\n\n $event.preventDefault();\n\n return index;\n }\n\n function _addNextMessageToSelection($event) {\n var index;\n\n if (vm.selectedFolder.hasSelectedMessage()) {\n index = _nextMessage($event);\n if (index >= 0)\n toggleMessageSelection($event, vm.selectedFolder.$messages[index]);\n }\n }\n\n function _addPreviousMessageToSelection($event) {\n var index;\n\n if (vm.selectedFolder.hasSelectedMessage()) {\n index = _previousMessage($event);\n if (index >= 0)\n toggleMessageSelection($event, vm.selectedFolder.$messages[index]);\n }\n }\n\n function selectMessage(message) {\n if (Mailbox.$virtualMode)\n $state.go('mail.account.virtualMailbox.message', {mailboxId: encodeUriFilter(message.$mailbox.path), messageId: message.uid});\n else\n $state.go('mail.account.mailbox.message', {messageId: message.uid});\n }\n\n function toggleMessageSelection($event, message) {\n var folder = vm.selectedFolder,\n selectedIndex, nextSelectedIndex, i;\n\n if (!message)\n message = folder.$selectedMessage();\n message.selected = !message.selected;\n vm.mode.multiple += message.selected? 1 : -1;\n\n // Select closest range of messages when shift key is pressed\n if ($event.shiftKey && folder.$selectedCount() > 1) {\n selectedIndex = folder.uidsMap[message.uid];\n // Search for next selected message above\n nextSelectedIndex = selectedIndex - 2;\n while (nextSelectedIndex >= 0 &&\n !folder.$messages[nextSelectedIndex].selected)\n nextSelectedIndex--;\n if (nextSelectedIndex < 0) {\n // Search for next selected message bellow\n nextSelectedIndex = selectedIndex + 2;\n while (nextSelectedIndex < folder.getLength() &&\n !folder.$messages[nextSelectedIndex].selected)\n nextSelectedIndex++;\n }\n if (nextSelectedIndex >= 0 && nextSelectedIndex < folder.getLength()) {\n for (i = Math.min(selectedIndex, nextSelectedIndex);\n i <= Math.max(selectedIndex, nextSelectedIndex);\n i++)\n folder.$messages[i].selected = true;\n }\n }\n\n $event.preventDefault();\n $event.stopPropagation();\n }\n\n /**\n * Batch operations\n */\n\n function _currentMailboxes() {\n if (Mailbox.$virtualMode)\n return vm.selectedFolder.$mailboxes;\n else\n return [vm.selectedFolder];\n }\n\n // Unselect current message and cleverly load the next message.\n // This function must not be called in virtual mode.\n function _unselectMessage(message, index) {\n var nextMessage, previousMessage, nextIndex = index;\n vm.mode.multiple = vm.selectedFolder.$selectedCount();\n if (message) {\n // Select either the next or previous message\n if (index > 0) {\n nextIndex -= 1;\n nextMessage = vm.selectedFolder.$messages[nextIndex];\n }\n if (index < vm.selectedFolder.$messages.length)\n previousMessage = vm.selectedFolder.$messages[index];\n if (nextMessage) {\n if (nextMessage.isread && previousMessage && !previousMessage.isread) {\n nextIndex = index;\n nextMessage = previousMessage;\n }\n }\n else if (previousMessage) {\n nextIndex = index;\n nextMessage = previousMessage;\n }\n if (nextMessage) {\n vm.selectedFolder.$topIndex = nextIndex;\n $state.go('mail.account.mailbox.message', { messageId: nextMessage.uid });\n }\n else {\n $state.go('mail.account.mailbox');\n }\n }\n else {\n $timeout(function() {\n console.warn('go to mailbox');\n $state.go('mail.account.mailbox');\n });\n }\n }\n\n function confirmDeleteSelectedMessages($event) {\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n\n if (vm.messageDialog === null && _.size(selectedMessages) > 0)\n vm.messageDialog = Dialog.confirm(l('Confirmation'),\n l('Are you sure you want to delete the selected messages?'),\n { ok: l('Delete') })\n .then(function() {\n var deleteSelectedMessage = vm.selectedFolder.hasSelectedMessage();\n vm.selectedFolder.$deleteMessages(selectedMessages).then(function(index) {\n if (Mailbox.$virtualMode) {\n // When performing an advanced search, we refresh the view if the selected message\n // was deleted, but only once all promises have completed.\n if (deleteSelectedMessage)\n $state.go('mail.account.virtualMailbox');\n }\n else {\n // In normal mode, we immediately unselect the selected message.\n _unselectMessage(deleteSelectedMessage, index);\n }\n }, function(response) {\n vm.messageDialog = Dialog.confirm(l('Warning'),\n l('The messages could not be moved to the trash folder. Would you like to delete them immediately?'),\n { ok: l('Delete') })\n .then(function() {\n vm.selectedFolder.$deleteMessages(selectedMessages, { withoutTrash: true }).then(function(index) {\n if (Mailbox.$virtualMode) {\n // When performing an advanced search, we refresh the view if the selected message\n // was deleted, but only once all promises have completed.\n if (deleteSelectedMessage)\n $state.go('mail.account.virtualMailbox');\n }\n else {\n // In normal mode, we immediately unselect the selected message.\n _unselectMessage(deleteSelectedMessage, index);\n }\n });\n });\n });\n })\n .finally(function() {\n vm.messageDialog = null;\n });\n\n $event.preventDefault();\n }\n\n function markOrUnMarkMessagesAsJunk() {\n var moveSelectedMessage = vm.selectedFolder.hasSelectedMessage();\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n if (_.size(selectedMessages) === 0 && moveSelectedMessage)\n selectedMessages = [vm.selectedFolder.$selectedMessage()];\n if (_.size(selectedMessages) > 0)\n vm.selectedFolder.$markOrUnMarkMessagesAsJunk(selectedMessages).then(function() {\n var dstFolder = '/' + vm.account.id + '/folderINBOX';\n if (vm.selectedFolder.type != 'junk') {\n dstFolder = '/' + vm.account.$getMailboxByType('junk').id;\n }\n vm.selectedFolder.$moveMessages(selectedMessages, dstFolder).then(function(index) {\n if (Mailbox.$virtualMode) {\n // When performing an advanced search, we refresh the view if the selected message\n // was deleted, but only once all promises have completed.\n if (moveSelectedMessage)\n $state.go('mail.account.virtualMailbox');\n }\n else {\n // In normal mode, we immediately unselect the selected message.\n _unselectMessage(moveSelectedMessage, index);\n }\n });\n });\n }\n\n function copySelectedMessages(dstFolder) {\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n if (_.size(selectedMessages) > 0)\n vm.selectedFolder.$copyMessages(selectedMessages, '/' + dstFolder).then(function() {\n $mdToast.show(\n $mdToast.simple()\n .content(l('%{0} message(s) copied', vm.selectedFolder.$selectedCount()))\n .position('top right')\n .hideDelay(2000));\n });\n }\n\n function moveSelectedMessages(dstFolder) {\n var moveSelectedMessage = vm.selectedFolder.hasSelectedMessage();\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n var count = vm.selectedFolder.$selectedCount();\n if (_.size(selectedMessages) > 0)\n vm.selectedFolder.$moveMessages(selectedMessages, '/' + dstFolder).then(function(index) {\n $mdToast.show(\n $mdToast.simple()\n .content(l('%{0} message(s) moved', count))\n .position('top right')\n .hideDelay(2000));\n if (Mailbox.$virtualMode) {\n // When performing an advanced search, we refresh the view if the selected message\n // was moved, but only once all promises have completed.\n if (moveSelectedMessage)\n $state.go('mail.account.virtualMailbox');\n }\n else {\n // In normal mode, we immediately unselect the selected message.\n _unselectMessage(moveSelectedMessage, index);\n }\n });\n }\n\n function selectAll() {\n var count = 0;\n _.forEach(_currentMailboxes(), function(folder) {\n var i = 0, length = folder.$messages.length;\n for (; i < length; i++)\n folder.$messages[i].selected = true;\n count += length;\n });\n vm.mode.multiple = count;\n }\n\n function unselectMessages() {\n _.forEach(_currentMailboxes(), function(folder) {\n _.forEach(folder.$messages, function(message) {\n message.selected = false;\n });\n });\n vm.mode.multiple = 0;\n }\n\n function markSelectedMessagesAsFlagged() {\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n if (_.size(selectedMessages) > 0)\n vm.selectedFolder.$flagMessages(selectedMessages, '\\\\Flagged', 'add').then(function(messages) {\n _.forEach(messages, function(message) {\n message.isflagged = true;\n });\n });\n }\n\n function markSelectedMessagesAsUnread() {\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n if (_.size(selectedMessages) > 0) {\n vm.selectedFolder.$flagMessages(selectedMessages, 'seen', 'remove').then(function(messages) {\n _.forEach(messages, function(message) {\n if (message.isread)\n message.$mailbox.unseenCount++;\n message.isread = false;\n });\n });\n }\n }\n\n function markSelectedMessagesAsRead() {\n var selectedMessages = vm.selectedFolder.$selectedMessages();\n if (_.size(selectedMessages) > 0) {\n vm.selectedFolder.$flagMessages(selectedMessages, 'seen', 'add').then(function(messages) {\n _.forEach(messages, function(message) {\n if (!message.isread)\n message.$mailbox.unseenCount--;\n message.isread = true;\n });\n });\n }\n }\n\n }\n\n angular\n .module('material.components.virtualRepeat')\n .decorator('mdVirtualRepeatContainerDirective', mdVirtualRepeatContainerDirectiveDecorator);\n\n /**\n * @ngInject\n */\n mdVirtualRepeatContainerDirectiveDecorator.$inject = ['$delegate'];\n function mdVirtualRepeatContainerDirectiveDecorator($delegate) {\n $delegate[0].controller.prototype.resetScroll = function() {\n // Don't scroll to top if current virtual repeater is the messages list\n // but do update the container size\n if (this.$element.parent().attr('id') == 'messagesList')\n this.updateSize();\n else\n this.scrollTo(0);\n };\n return $delegate;\n }\n\n angular\n .module('SOGo.MailerUI')\n .controller('MailboxController', MailboxController);\n})();\n\n","/* -*- Mode: js; indent-tabs-mode: nil; js-indent-level: 2; -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n MailboxesController.$inject = ['$scope', '$state', '$timeout', '$window', '$mdDialog', '$mdToast', '$mdMedia', '$mdSidenav', 'sgConstant', 'sgFocus', 'encodeUriFilter', 'Dialog', 'sgSettings', 'sgHotkeys', 'Account', 'Mailbox', 'VirtualMailbox', 'User', 'Preferences', 'stateAccounts'];\n function MailboxesController($scope, $state, $timeout, $window, $mdDialog, $mdToast, $mdMedia, $mdSidenav, sgConstant, focus, encodeUriFilter, Dialog, Settings, sgHotkeys, Account, Mailbox, VirtualMailbox, User, Preferences, stateAccounts) {\n var vm = this,\n account,\n mailbox,\n hotkeys = [];\n\n vm.service = Mailbox;\n vm.accounts = stateAccounts;\n vm.toggleAccountState = toggleAccountState;\n vm.subscribe = subscribe;\n vm.newFolder = newFolder;\n vm.delegate = delegate;\n vm.editFolder = editFolder;\n vm.revertEditing = revertEditing;\n vm.selectFolder = selectFolder;\n vm.saveFolder = saveFolder;\n vm.compactFolder = compactFolder;\n vm.emptyTrashFolder = emptyTrashFolder;\n vm.confirmDelete = confirmDelete;\n vm.markFolderRead = markFolderRead;\n vm.share = share;\n vm.metadataForFolder = metadataForFolder;\n vm.setFolderAs = setFolderAs;\n vm.refreshUnseenCount = refreshUnseenCount;\n vm.isDroppableFolder = isDroppableFolder;\n vm.dragSelectedMessages = dragSelectedMessages;\n\n // Advanced search options\n vm.showingAdvancedSearch = false;\n vm.currentSearchParam = '';\n vm.addSearchParam = addSearchParam;\n vm.newSearchParam = newSearchParam;\n vm.showAdvancedSearch = showAdvancedSearch;\n vm.hideAdvancedSearch = hideAdvancedSearch;\n vm.toggleAdvancedSearch = toggleAdvancedSearch;\n vm.search = {\n options: {'': '', // no placeholder when no criteria is active\n subject: l('Enter Subject'),\n from: l('Enter From'),\n to: l('Enter To'),\n cc: l('Enter Cc'),\n body: l('Enter Body')\n },\n mailbox: 'INBOX',\n subfolders: 1,\n match: 'AND',\n params: []\n };\n\n\n Preferences.ready().then(function() {\n vm.showSubscribedOnly = Preferences.defaults.SOGoMailShowSubscribedFoldersOnly;\n });\n\n vm.refreshUnseenCount();\n\n _registerHotkeys(hotkeys);\n\n $scope.$on('$destroy', function() {\n // Deregister hotkeys\n _.forEach(hotkeys, function(key) {\n sgHotkeys.deregisterHotkey(key);\n });\n });\n\n\n function _registerHotkeys(keys) {\n keys.push(sgHotkeys.createHotkey({\n key: 'backspace',\n description: l('Delete selected message or folder'),\n callback: function() {\n if (Mailbox.selectedFolder && !Mailbox.selectedFolder.hasSelectedMessage())\n confirmDelete(Mailbox.selectedFolder);\n }\n }));\n\n // Register the hotkeys\n _.forEach(keys, function(key) {\n sgHotkeys.registerHotkey(key);\n });\n }\n\n function showAdvancedSearch(path) {\n vm.showingAdvancedSearch = true;\n vm.search.mailbox = path;\n // Close sidenav on small devices\n if (!$mdMedia(sgConstant['gt-md']))\n $mdSidenav('left').close();\n }\n\n function hideAdvancedSearch() {\n vm.showingAdvancedSearch = false;\n vm.service.$virtualMode = false;\n\n account = vm.accounts[0];\n mailbox = vm.searchPreviousMailbox;\n $state.go('mail.account.mailbox', { accountId: account.id, mailboxId: encodeUriFilter(mailbox.path) });\n }\n\n function toggleAdvancedSearch() {\n if (Mailbox.selectedFolder.$isLoading) {\n // Stop search\n vm.virtualMailbox.stopSearch();\n }\n else {\n // Start search\n var root, mailboxes = [],\n _visit = function(folders) {\n _.forEach(folders, function(o) {\n mailboxes.push(o);\n if (o.children && o.children.length > 0) {\n _visit(o.children);\n }\n });\n };\n\n vm.virtualMailbox = new VirtualMailbox(vm.accounts[0]);\n\n // Don't set the previous selected mailbox if we're in virtual mode\n // That allows users to do multiple advanced search but return\n // correctly to the previously selected mailbox once done.\n if (!Mailbox.$virtualMode)\n vm.searchPreviousMailbox = Mailbox.selectedFolder;\n\n Mailbox.selectedFolder = vm.virtualMailbox;\n Mailbox.$virtualMode = true;\n\n if (angular.isDefined(vm.search.mailbox)) {\n root = vm.accounts[0].$getMailboxByPath(vm.search.mailbox);\n mailboxes.push(root);\n if (vm.search.subfolders && root.children.length)\n _visit(root.children);\n }\n else {\n mailboxes = vm.accounts[0].$flattenMailboxes();\n }\n\n vm.virtualMailbox.setMailboxes(mailboxes);\n vm.virtualMailbox.startSearch(vm.search.match, vm.search.params);\n $state.go('mail.account.virtualMailbox', { accountId: vm.accounts[0].id });\n }\n }\n\n function addSearchParam(v) {\n vm.currentSearchParam = v;\n focus('advancedSearch');\n return false;\n }\n\n function newSearchParam(pattern) {\n if (pattern.length && vm.currentSearchParam.length) {\n var n = 0, searchParam = vm.currentSearchParam;\n if (pattern.startsWith(\"!\")) {\n n = 1;\n pattern = pattern.substring(1).trim();\n }\n vm.currentSearchParam = '';\n return { searchBy: searchParam, searchInput: pattern, negative: n };\n }\n }\n\n function toggleAccountState(account) {\n account.$expanded = !account.$expanded;\n account.$flattenMailboxes({ reload: true, saveState: true });\n // Fire a window resize to recompute the virtual-repeater.\n // This is a fix until the following issue is officially resolved:\n // https://github.com/angular/material/issues/7309\n $timeout(function() {\n angular.element($window).triggerHandler('resize');\n }, 150);\n }\n\n function subscribe(account) {\n $mdDialog.show({\n templateUrl: account.id + '/subscribe',\n controller: SubscriptionsDialogController,\n controllerAs: 'subscriptions',\n clickOutsideToClose: true,\n escapeToClose: true,\n locals: {\n metadataForFolder: metadataForFolder,\n srcAccount: account\n }\n }).finally(function() {\n account.$getMailboxes({reload: true});\n });\n\n /**\n * @ngInject\n */\n SubscriptionsDialogController.$inject = ['$scope', '$mdDialog', 'metadataForFolder', 'srcAccount'];\n function SubscriptionsDialogController($scope, $mdDialog, metadataForFolder, srcAccount) {\n var vm = this;\n\n vm.loading = true;\n vm.filter = { name: '' };\n vm.metadataForFolder = metadataForFolder;\n vm.account = new Account({\n id: srcAccount.id,\n name: srcAccount.name\n });\n vm.close = close;\n\n vm.account.$getMailboxes({ reload: true, all: true }).then(function() {\n vm.loading = false;\n });\n\n function close() {\n $mdDialog.cancel();\n }\n }\n }\n\n function newFolder(parentFolder) {\n Dialog.prompt(l('New Folder...'),\n l('Enter the new name of your folder'))\n .then(function(name) {\n parentFolder.$newMailbox(parentFolder.id, name)\n .then(function() {\n // success\n }, function(data, status) {\n Dialog.alert(l('An error occured while creating the mailbox \"%{0}\".', name),\n l(data.error));\n });\n });\n }\n\n function delegate(account) {\n $mdDialog.show({\n templateUrl: account.id + '/delegation', // UI/Templates/MailerUI/UIxMailUserDelegation.wox\n controller: MailboxDelegationController,\n controllerAs: 'delegate',\n clickOutsideToClose: true,\n escapeToClose: true,\n locals: {\n User: User,\n account: account\n }\n });\n\n /**\n * @ngInject\n */\n MailboxDelegationController.$inject = ['$scope', '$mdDialog', 'User', 'account'];\n function MailboxDelegationController($scope, $mdDialog, User, account) {\n var vm = this;\n\n vm.users = account.delegates;\n vm.account = account;\n vm.userToAdd = '';\n vm.searchText = '';\n vm.userFilter = userFilter;\n vm.closeModal = closeModal;\n vm.removeUser = removeUser;\n vm.addUser = addUser;\n\n function userFilter($query) {\n return User.$filter($query, account.delegates);\n }\n\n function closeModal() {\n $mdDialog.hide();\n }\n\n function removeUser(user) {\n account.$removeDelegate(user.uid).catch(function(data, status) {\n Dialog.alert(l('Warning'), l('An error occured please try again.'));\n });\n }\n\n function addUser(data) {\n if (data) {\n account.$addDelegate(data).then(function() {\n vm.userToAdd = '';\n vm.searchText = '';\n }, function(error) {\n Dialog.alert(l('Warning'), error);\n });\n }\n }\n }\n } // delegate\n\n function editFolder(folder) {\n vm.editMode = folder.path;\n focus('mailboxName_' + folder.path);\n }\n\n function revertEditing(folder) {\n folder.$reset();\n vm.editMode = false;\n }\n\n function selectFolder($event, account, folder) {\n if (vm.editMode == folder.path)\n return;\n vm.editMode = false;\n vm.showingAdvancedSearch = false;\n vm.service.$virtualMode = false;\n // Close sidenav on small devices\n if (!$mdMedia(sgConstant['gt-md']))\n $mdSidenav('left').close();\n $state.go('mail.account.mailbox', { accountId: account.id, mailboxId: encodeUriFilter(folder.path) });\n $event.stopPropagation();\n $event.preventDefault();\n }\n\n function saveFolder(folder) {\n folder.$rename()\n .then(function(data) {\n vm.editMode = false;\n });\n }\n\n function compactFolder(folder) {\n folder.$compact().then(function() {\n $mdToast.show(\n $mdToast.simple()\n .content(l('Folder compacted'))\n .position('top right')\n .hideDelay(3000));\n });\n }\n\n function emptyTrashFolder(folder) {\n folder.$emptyTrash().then(function() {\n $mdToast.show(\n $mdToast.simple()\n .content(l('Trash emptied'))\n .position('top right')\n .hideDelay(3000));\n });\n }\n\n function confirmDelete(folder) {\n Dialog.confirm(l('Warning'),\n l('Do you really want to move this folder into the trash ?'),\n { ok: l('Delete') })\n .then(function() {\n folder.$delete()\n .then(function() {\n $state.go('mail.account.inbox');\n }, function(response) {\n Dialog.confirm(l('Warning'),\n l('The mailbox could not be moved to the trash folder. Would you like to delete it immediately?'),\n { ok: l('Delete') })\n .then(function() {\n folder.$delete({ withoutTrash: true })\n .then(function() {\n $state.go('mail.account.inbox');\n }, function(response) {\n Dialog.alert(l('An error occured while deleting the mailbox \"%{0}\".', folder.name),\n l(response.error));\n });\n });\n });\n });\n }\n\n function markFolderRead(folder) {\n folder.$markAsRead();\n }\n\n function share(folder) {\n // Fetch list of ACL users\n folder.$acl.$users().then(function() {\n // Show ACL editor\n $mdDialog.show({\n templateUrl: folder.id + '/UIxAclEditor', // UI/Templates/UIxAclEditor.wox\n controller: 'AclController', // from the ng module SOGo.Common\n controllerAs: 'acl',\n clickOutsideToClose: true,\n escapeToClose: true,\n locals: {\n usersWithACL: folder.$acl.users,\n User: User,\n folder: folder\n }\n });\n });\n } // share\n\n function metadataForFolder(folder) {\n if (folder.type == 'inbox')\n return {name: l('InboxFolderName'), icon:'inbox', special: true};\n else if (folder.type == 'draft')\n return {name: l('DraftsFolderName'), icon: 'drafts', special: true};\n else if (folder.type == 'sent')\n return {name: l('SentFolderName'), icon: 'send', special: true};\n else if (folder.type == 'trash')\n return {name: l('TrashFolderName'), icon: 'delete', special: true};\n else if (folder.type == 'junk')\n return {name: l('JunkFolderName'), icon: 'thumb_down', special: true};\n else if (folder.type == 'additional')\n return {name: folder.name, icon: 'folder_shared', special: true};\n\n return {name: folder.name, icon: 'folder_open', special: false};\n }\n\n function setFolderAs(folder, type) {\n folder.$setFolderAs(type).then(function() {\n folder.$account.$getMailboxes({reload: true});\n });\n }\n\n function refreshUnseenCount() {\n var unseenCountFolders = $window.unseenCountFolders;\n\n _.forEach(vm.accounts, function(account) {\n\n // Always include the INBOX\n if (!_.includes(unseenCountFolders, account.id + '/folderINBOX'))\n unseenCountFolders.push(account.id + '/folderINBOX');\n\n _.forEach(account.$$flattenMailboxes, function(mailbox) {\n if (angular.isDefined(mailbox.unseenCount) &&\n !_.includes(unseenCountFolders, mailbox.id))\n unseenCountFolders.push(mailbox.id);\n });\n });\n\n Account.$$resource.post('', 'unseenCount', {mailboxes: unseenCountFolders}).then(function(data) {\n _.forEach(vm.accounts, function(account) {\n _.forEach(account.$$flattenMailboxes, function(mailbox) {\n if (data[mailbox.id])\n mailbox.unseenCount = data[mailbox.id];\n });\n });\n });\n\n Preferences.ready().then(function() {\n var refreshViewCheck = Preferences.defaults.SOGoRefreshViewCheck;\n if (refreshViewCheck && refreshViewCheck != 'manually')\n $timeout(vm.refreshUnseenCount, refreshViewCheck.timeInterval()*1000);\n });\n }\n\n function isDroppableFolder(srcFolder, dstFolder) {\n return (dstFolder.id != srcFolder.id) && !dstFolder.isNoSelect();\n }\n\n function dragSelectedMessages(srcFolder, dstFolder, mode) {\n var dstId, messages, uids, clearMessageView, promise, success;\n\n dstId = '/' + dstFolder.id;\n messages = srcFolder.$selectedMessages();\n if (messages.length === 0)\n messages = [srcFolder.$selectedMessage()];\n uids = _.map(messages, 'uid');\n clearMessageView = (srcFolder.selectedMessage && uids.indexOf(srcFolder.selectedMessage) >= 0);\n\n if (mode == 'copy') {\n promise = srcFolder.$copyMessages(messages, dstId);\n success = l('%{0} message(s) copied', messages.length);\n }\n else {\n promise = srcFolder.$moveMessages(messages, dstId);\n success = l('%{0} message(s) moved', messages.length);\n }\n\n promise.then(function() {\n if (clearMessageView)\n $state.go('mail.account.mailbox');\n $mdToast.show(\n $mdToast.simple()\n .content(success)\n .position('top right')\n .hideDelay(2000));\n });\n }\n\n }\n\n angular\n .module('SOGo.MailerUI')\n .controller('MailboxesController', MailboxesController);\n})();\n\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n MessageController.$inject = ['$window', '$scope', '$state', '$mdMedia', '$mdDialog', 'sgConstant', 'stateAccounts', 'stateAccount', 'stateMailbox', 'stateMessage', 'sgHotkeys', 'encodeUriFilter', 'sgSettings', 'sgFocus', 'Dialog', 'Calendar', 'Component', 'Account', 'Mailbox', 'Message'];\n function MessageController($window, $scope, $state, $mdMedia, $mdDialog, sgConstant, stateAccounts, stateAccount, stateMailbox, stateMessage, sgHotkeys, encodeUriFilter, sgSettings, focus, Dialog, Calendar, Component, Account, Mailbox, Message) {\n var vm = this, popupWindow = null, hotkeys = [];\n\n // Expose controller\n $window.$messageController = vm;\n\n vm.$state = $state;\n vm.accounts = stateAccounts;\n vm.account = stateAccount;\n vm.mailbox = stateMailbox;\n vm.message = stateMessage;\n vm.service = Message;\n vm.tags = { searchText: '', selected: '' };\n vm.showFlags = stateMessage.flags && stateMessage.flags.length > 0;\n vm.$showDetailedRecipients = false;\n vm.toggleDetailedRecipients = toggleDetailedRecipients;\n vm.filterMailtoLinks = filterMailtoLinks;\n vm.deleteMessage = deleteMessage;\n vm.close = close;\n vm.reply = reply;\n vm.replyAll = replyAll;\n vm.forward = forward;\n vm.edit = edit;\n vm.openPopup = openPopup;\n vm.closePopup = closePopup;\n vm.newMessage = newMessage;\n vm.toggleRawSource = toggleRawSource;\n vm.showRawSource = false;\n vm.print = print;\n vm.convertToEvent = convertToEvent;\n vm.convertToTask = convertToTask;\n\n _registerHotkeys(hotkeys);\n\n // One-way refresh of the parent window when modifying the message from a popup window.\n if ($window.opener) {\n // Update the message flags. The message must be displayed in the parent window.\n $scope.$watchCollection(function() { return vm.message.flags; }, function(newTags, oldTags) {\n var ctrls;\n if (newTags || oldTags) {\n ctrls = $parentControllers();\n if (ctrls.messageCtrl) {\n ctrls.messageCtrl.service.$timeout(function() {\n ctrls.messageCtrl.showFlags = true;\n ctrls.messageCtrl.message.flags = newTags;\n });\n }\n }\n });\n // Update the \"isflagged\" (star icon) of the message. The mailbox must be displayed in the parent window.\n $scope.$watch(function() { return vm.message.isflagged; }, function(isflagged, wasflagged) {\n var ctrls = $parentControllers();\n if (ctrls.mailboxCtrl) {\n ctrls.mailboxCtrl.service.$timeout(function() {\n var message = _.find(ctrls.mailboxCtrl.selectedFolder.$messages, { uid: vm.message.uid });\n message.isflagged = isflagged;\n });\n }\n });\n }\n else {\n // Flatten new tags when coming from the predefined list of tags (Message.$tags) and\n // sync tags with server when adding or removing a tag.\n $scope.$watchCollection(function() { return vm.message.flags; }, function(_newTags, _oldTags) {\n var newTags, oldTags, tags;\n if (_newTags || _oldTags) {\n newTags = _newTags || [];\n oldTags = _oldTags || [];\n _.forEach(newTags, function(tag, i) {\n if (angular.isObject(tag))\n newTags[i] = tag.name;\n });\n if (newTags.length > oldTags.length) {\n tags = _.difference(newTags, oldTags);\n _.forEach(tags, function(tag) {\n vm.message.addTag(tag);\n });\n }\n else if (newTags.length < oldTags.length) {\n tags = _.difference(oldTags, newTags);\n _.forEach(tags, function(tag) {\n vm.message.removeTag(tag);\n });\n }\n }\n });\n }\n\n $scope.$on('$destroy', function() {\n // Deregister hotkeys\n _.forEach(hotkeys, function(key) {\n sgHotkeys.deregisterHotkey(key);\n });\n });\n\n\n /**\n * To keep track of the currently active dialog, we share a common variable with the parent controller.\n */\n function _messageDialog() {\n if ($scope.mailbox) {\n if (arguments.length > 0)\n $scope.mailbox.messageDialog = arguments[0];\n return $scope.mailbox.messageDialog;\n }\n return null;\n }\n\n function _unlessInDialog(callback) {\n return function() {\n // Check if a dialog is opened either from the current controller or the parent controller\n if (_messageDialog() === null)\n return callback.apply(vm, arguments);\n };\n }\n\n function _registerHotkeys(keys) {\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_reply'),\n description: l('Reply to the message'),\n callback: _unlessInDialog(reply)\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_replyall'),\n description: l('Reply to sender and all recipients'),\n callback: _unlessInDialog(replyAll)\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_forward'),\n description: l('Forward selected message'),\n callback: _unlessInDialog(forward)\n }));\n keys.push(sgHotkeys.createHotkey({\n key: l('hotkey_flag'),\n description: l('Flagged'),\n callback: _unlessInDialog(angular.bind(stateMessage, stateMessage.toggleFlag))\n }));\n keys.push(sgHotkeys.createHotkey({\n key: 'backspace',\n callback: _unlessInDialog(function($event) {\n if (vm.mailbox.$selectedCount() === 0)\n deleteMessage();\n $event.preventDefault();\n })\n }));\n\n // Register the hotkeys\n _.forEach(keys, function(key) {\n sgHotkeys.registerHotkey(key);\n });\n }\n\n /**\n * If this is a popup window, retrieve the matching controllers (mailbox and message) of the parent window.\n */\n function $parentControllers() {\n var message, mailbox, ctrls = {};\n if ($window.opener) {\n // Deleting the message from a popup window\n if ($window.opener.$mailboxController &&\n $window.opener.$mailboxController.selectedFolder.$id() == stateMailbox.$id()) {\n // The message mailbox is opened in the parent window\n mailbox = $window.opener.$mailboxController;\n ctrls.mailboxCtrl = mailbox;\n if ($window.opener.$messageController &&\n $window.opener.$messageController.message.uid == stateMessage.uid) {\n // The message is opened in the parent window\n message = $window.opener.$messageController;\n ctrls.messageCtrl = message;\n }\n }\n }\n return ctrls;\n }\n\n function toggleDetailedRecipients($event) {\n vm.$showDetailedRecipients = !vm.$showDetailedRecipients;\n $event.stopPropagation();\n $event.preventDefault();\n }\n\n function filterMailtoLinks($event) {\n var href, match, to, cc, bcc, subject, body, data;\n if ($event.target.tagName == 'A' && 'href' in $event.target.attributes) {\n href = $event.target.attributes.href.value;\n match = /^mailto:([^\\?]+)/.exec(href);\n if (match) {\n // Recipients\n to = _.map(decodeURIComponent(match[1]).split(','), function(email) {\n return '<' + email + '>';\n });\n data = { to: to };\n // Subject & body\n _.forEach(['subject', 'body'], function(param) {\n var re = new RegExp(param + '=([^&]+)');\n param = (param == 'body')? 'text' : param;\n match = re.exec(href);\n if (match)\n data[param] = [decodeURIComponent(match[1])];\n });\n // Recipients\n _.forEach(['cc', 'bcc'], function(param) {\n var re = new RegExp(param + '=([^&]+)');\n match = re.exec(href);\n if (match)\n data[param] = [decodeURIComponent(match[1])];\n });\n newMessage($event, data); // will stop event propagation\n }\n }\n }\n\n function deleteMessage() {\n var mailbox, message, state, nextMessage, previousMessage,\n parentCtrls = $parentControllers();\n\n if (parentCtrls.messageCtrl) {\n mailbox = parentCtrls.mailboxCtrl.selectedFolder;\n message = parentCtrls.messageCtrl.message;\n state = parentCtrls.messageCtrl.$state;\n }\n else {\n mailbox = stateMailbox;\n message = stateMessage;\n state = $state;\n }\n\n mailbox.$deleteMessages([message]).then(function(index) {\n var nextIndex = index;\n // Remove message object from scope\n message = null;\n if (angular.isDefined(state)) {\n // Select either the next or previous message\n if (index > 0) {\n nextIndex -= 1;\n nextMessage = mailbox.$messages[nextIndex];\n }\n if (index < mailbox.$messages.length)\n previousMessage = mailbox.$messages[index];\n\n if (nextMessage) {\n if (nextMessage.isread && previousMessage && !previousMessage.isread) {\n nextIndex = index;\n nextMessage = previousMessage;\n }\n }\n else if (previousMessage) {\n nextIndex = index;\n nextMessage = previousMessage;\n }\n\n try {\n if (nextMessage && $mdMedia(sgConstant['gt-md'])) {\n state.go('mail.account.mailbox.message', { messageId: nextMessage.uid });\n if (nextIndex < mailbox.$topIndex)\n mailbox.$topIndex = nextIndex;\n else if (nextIndex > mailbox.$lastVisibleIndex)\n mailbox.$topIndex = nextIndex - (mailbox.$lastVisibleIndex - mailbox.$topIndex);\n }\n else {\n state.go('mail.account.mailbox').then(function() {\n message = null;\n delete mailbox.selectedMessage;\n });\n }\n }\n catch (error) {}\n }\n closePopup();\n });\n }\n\n function showMailEditor($event, message) {\n if (_messageDialog() === null) {\n _messageDialog(\n $mdDialog\n .show({\n parent: angular.element(document.body),\n targetEvent: $event,\n clickOutsideToClose: false,\n escapeToClose: false,\n templateUrl: 'UIxMailEditor',\n controller: 'MessageEditorController',\n controllerAs: 'editor',\n locals: {\n stateAccount: vm.account,\n stateMessage: message\n }\n })\n .finally(function() {\n _messageDialog(null);\n closePopup();\n })\n );\n }\n }\n\n function close() {\n $state.go('mail.account.mailbox').then(function() {\n vm.message = null;\n delete stateMailbox.selectedMessage;\n });\n }\n\n function reply($event) {\n var message = vm.message.$reply();\n showMailEditor($event, message);\n }\n\n function replyAll($event) {\n var message = vm.message.$replyAll();\n showMailEditor($event, message);\n }\n\n function forward($event) {\n var message = vm.message.$forward();\n showMailEditor($event, message);\n }\n\n function edit($event) {\n vm.message.$editableContent().then(function() {\n showMailEditor($event, vm.message);\n });\n }\n\n function openPopup() {\n var url = [sgSettings.baseURL(),\n 'UIxMailPopupView#!/Mail',\n vm.message.accountId,\n // The double-encoding is necessary\n encodeUriFilter(encodeUriFilter(vm.message.$mailbox.path)),\n vm.message.uid]\n .join('/'),\n wId = vm.message.$absolutePath();\n popupWindow = $window.open(url, wId,\n [\"width=680\",\n \"height=520\",\n \"resizable=1\",\n \"scrollbars=1\",\n \"toolbar=0\",\n \"location=0\",\n \"directories=0\",\n \"status=0\",\n \"menubar=0\",\n \"copyhistory=0\"]\n .join(','));\n }\n\n function closePopup() {\n if ($window.opener)\n $window.close();\n }\n\n function newMessage($event, editableContent) {\n vm.account.$newMessage().then(function(message) {\n angular.extend(message.editable, editableContent);\n showMailEditor($event, message);\n });\n $event.stopPropagation();\n $event.preventDefault();\n }\n\n function toggleRawSource($event) {\n if (!vm.showRawSource && !vm.message.$rawSource) {\n Message.$$resource.post(vm.message.id, \"viewsource\").then(function(data) {\n vm.message.$rawSource = data;\n vm.showRawSource = true;\n });\n }\n else {\n vm.showRawSource = !vm.showRawSource;\n }\n }\n\n function print($event) {\n $window.print();\n }\n\n function convertToEvent($event) {\n return convertToComponent($event, 'appointment');\n }\n\n function convertToTask($event) {\n return convertToComponent($event, 'task');\n }\n\n function convertToComponent($event, type) {\n vm.message.$plainContent().then(function(data) {\n var componentData = {\n pid: Calendar.$defaultCalendar(),\n type: type,\n summary: data.subject,\n comment: data.content\n };\n var component = new Component(componentData);\n // UI/Templates/SchedulerUI/UIxAppointmentEditorTemplate.wox or\n // UI/Templates/SchedulerUI/UIxTaskEditorTemplate.wox\n var templateUrl = [\n sgSettings.activeUser('folderURL'),\n 'Calendar',\n 'UIx' + type.capitalize() + 'EditorTemplate'\n ].join('/');\n return $mdDialog.show({\n parent: angular.element(document.body),\n targetEvent: $event,\n clickOutsideToClose: true,\n escapeToClose: true,\n templateUrl: templateUrl,\n controller: 'ComponentEditorController',\n controllerAs: 'editor',\n locals: {\n stateComponent: component\n }\n });\n });\n }\n }\n \n angular\n .module('SOGo.MailerUI') \n .controller('MessageController', MessageController); \n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n MessageEditorController.$inject = ['$scope', '$window', '$stateParams', '$mdConstant', '$mdDialog', '$mdToast', 'FileUploader', 'stateAccount', 'stateMessage', 'encodeUriFilter', '$timeout', 'Dialog', 'AddressBook', 'Card', 'Preferences'];\n function MessageEditorController($scope, $window, $stateParams, $mdConstant, $mdDialog, $mdToast, FileUploader, stateAccount, stateMessage, encodeUriFilter, $timeout, Dialog, AddressBook, Card, Preferences) {\n var vm = this, hotkeys = [];\n\n vm.addRecipient = addRecipient;\n vm.autocomplete = {to: {}, cc: {}, bcc: {}};\n vm.autosave = null;\n vm.autosaveDrafts = autosaveDrafts;\n vm.cancel = cancel;\n vm.contactFilter = contactFilter;\n vm.isFullscreen = false;\n vm.hideBcc = (stateMessage.editable.bcc.length === 0);\n vm.hideCc = (stateMessage.editable.cc.length === 0);\n vm.identities = _.map(stateAccount.identities, 'full');\n vm.message = stateMessage;\n vm.recipientSeparatorKeys = [\n $mdConstant.KEY_CODE.ENTER,\n $mdConstant.KEY_CODE.TAB,\n $mdConstant.KEY_CODE.COMMA,\n $mdConstant.KEY_CODE.SEMICOLON\n ];\n vm.removeAttachment = removeAttachment;\n vm.save = save;\n vm.send = send;\n vm.sendState = false;\n vm.toggleFullscreen = toggleFullscreen;\n vm.uploader = new FileUploader({\n url: stateMessage.$absolutePath({asDraft: true}) + '/save',\n autoUpload: true,\n alias: 'attachments',\n removeAfterUpload: false,\n // onProgressItem: function(item, progress) {\n // console.debug(item); console.debug(progress);\n // },\n onSuccessItem: function(item, response, status, headers) {\n stateMessage.$setUID(response.uid);\n stateMessage.$reload({asDraft: false});\n item.inlineUrl = response.lastAttachmentAttrs[0].url;\n //console.debug(item); console.debug('success = ' + JSON.stringify(response, undefined, 2));\n },\n onCancelItem: function(item, response, status, headers) {\n //console.debug(item); console.debug('cancel = ' + JSON.stringify(response, undefined, 2));\n // We remove the attachment\n stateMessage.$deleteAttachment(item.file.name);\n this.removeFromQueue(item);\n },\n onErrorItem: function(item, response, status, headers) {\n $mdToast.show(\n $mdToast.simple()\n .content(l('Error while uploading the file \\\"%{0}\\\":', item.file.name) +\n ' ' + (response.message? l(response.message) : ''))\n .position('top right')\n .action(l('OK'))\n .hideDelay(false));\n this.removeFromQueue(item);\n //console.debug(item); console.debug('error = ' + JSON.stringify(response, undefined, 2));\n }\n });\n\n // Destroy file uploader when the controller is being deactivated\n $scope.$on('$destroy', function() { vm.uploader.destroy(); });\n\n if ($stateParams.actionName == 'reply') {\n stateMessage.$reply().then(function(msgObject) {\n vm.message = msgObject;\n vm.hideCc = (!msgObject.editable.cc || msgObject.editable.cc.length === 0);\n vm.hideBcc = (!msgObject.editable.bcc || msgObject.editable.bcc.length === 0);\n });\n }\n else if ($stateParams.actionName == 'replyall') {\n stateMessage.$replyAll().then(function(msgObject) {\n vm.message = msgObject;\n vm.hideCc = (!msgObject.editable.cc || msgObject.editable.cc.length === 0);\n vm.hideBcc = (!msgObject.editable.bcc || msgObject.editable.bcc.length === 0);\n });\n }\n else if ($stateParams.actionName == 'forward') {\n stateMessage.$forward().then(function(msgObject) {\n vm.message = msgObject;\n addAttachments();\n });\n }\n else if (angular.isDefined(stateMessage)) {\n vm.message = stateMessage;\n addAttachments();\n }\n\n /**\n * If this is a popup window, retrieve the mailbox controller of the parent window.\n */\n function $parentControllers() {\n var originMessage, ctrls = {};\n\n try {\n if ($window.opener) {\n if ('$mailboxController' in $window.opener &&\n 'selectedFolder' in $window.opener.$mailboxController) {\n if ($window.opener.$mailboxController.selectedFolder.type == 'draft') {\n ctrls.draftMailboxCtrl = $window.opener.$mailboxController;\n if ('$messageController' in $window.opener &&\n $window.opener.$messageController.message.uid == stateMessage.uid) {\n // The draft is opened in the parent window\n ctrls.draftMessageCtrl = $window.opener.$messageController;\n }\n }\n else if (stateMessage.origin) {\n originMessage = stateMessage.origin.message;\n if ($window.opener.$mailboxController.selectedFolder.$id() == originMessage.$mailbox.$id()) {\n // The message mailbox is opened in the parent window\n ctrls.originMailboxCtrl = $window.opener.$mailboxController;\n }\n }\n }\n }\n }\n catch (e) {}\n\n return ctrls;\n }\n\n function addAttachments() {\n // Add existing attached files to uploader\n var i, data, fileItem, attrs = vm.message.editable.attachmentAttrs;\n if (attrs)\n for (i = 0; i < attrs.length; i++) {\n data = {\n name: attrs[i].filename,\n type: attrs[i].mimetype,\n size: parseInt(attrs[i].size)\n };\n fileItem = new FileUploader.FileItem(vm.uploader, data);\n fileItem.progress = 100;\n fileItem.isUploaded = true;\n fileItem.isSuccess = true;\n fileItem.inlineUrl = attrs[i].url;\n vm.uploader.queue.push(fileItem);\n }\n }\n\n function removeAttachment(item, id) {\n if (item.isUploading)\n vm.uploader.cancelItem(item);\n else {\n vm.message.$deleteAttachment(item.file.name);\n item.remove();\n }\n // Hack to allow adding the same file again\n // See https://github.com/nervgh/angular-file-upload/issues/671\n var element = $window.document.getElementById(id);\n if (element)\n angular.element(element).prop('value', null);\n }\n\n function cancel() {\n if (vm.autosave)\n $timeout.cancel(vm.autosave);\n\n if (vm.message.isNew && vm.message.attachmentAttrs)\n vm.message.$mailbox.$deleteMessages([vm.message]);\n\n $mdDialog.cancel();\n }\n\n function save() {\n var ctrls = $parentControllers();\n vm.message.$save().then(function(data) {\n vm.message.$rawSource = null;\n if (ctrls.draftMailboxCtrl) {\n // We're saving a draft from a popup window.\n // Reload draft mailbox\n ctrls.draftMailboxCtrl.selectedFolder.$filter().then(function() {\n if (ctrls.draftMessageCtrl) {\n // Reload selected message\n ctrls.draftMessageCtrl.$state.go('mail.account.mailbox.message', { messageId: vm.message.uid });\n }\n });\n }\n $mdToast.show(\n $mdToast.simple()\n .content(l('Your email has been saved'))\n .position('top right')\n .hideDelay(3000));\n });\n }\n\n function send() {\n var ctrls = $parentControllers();\n\n vm.sendState = 'sending';\n if (vm.autosave)\n $timeout.cancel(vm.autosave);\n\n vm.message.$send().then(function(data) {\n vm.sendState = 'sent';\n if (ctrls.draftMailboxCtrl) {\n // We're sending a draft from a popup window and the draft mailbox is opened.\n // Reload draft mailbox\n ctrls.draftMailboxCtrl.selectedFolder.$filter().then(function() {\n if (ctrls.draftMessageCtrl) {\n // Close draft\n ctrls.draftMessageCtrl.close();\n }\n });\n }\n if (ctrls.originMailboxCtrl) {\n // We're sending a draft from a popup window and the original mailbox is opened.\n // Reload mailbox\n ctrls.originMailboxCtrl.selectedFolder.$filter();\n }\n $mdToast.show(\n $mdToast.simple()\n .content(l('Your email has been sent'))\n .position('top right')\n .hideDelay(3000));\n\n // Let the user see the succesfull message before closing the dialog\n $timeout($mdDialog.hide, 1000);\n }, function(response) {\n vm.sendState = 'error';\n vm.errorMessage = response.data? response.data.message : response.statusText;\n });\n }\n\n function toggleFullscreen() {\n vm.isFullscreen = !vm.isFullscreen;\n }\n\n function contactFilter($query) {\n return AddressBook.$filterAll($query).then(function(cards) {\n // Divide the matching cards by email addresses so the user can select\n // the recipient address of her choice\n var explodedCards = [];\n _.forEach(_.invokeMap(cards, 'explode'), function(manyCards) {\n _.forEach(manyCards, function(card) {\n explodedCards.push(card);\n });\n });\n // Remove duplicates\n return _.uniqBy(explodedCards, function(card) {\n return card.$$fullname + ' ' + card.$$email;\n });\n });\n }\n\n function addRecipient(contact, field) {\n var recipients, recipient, list;\n\n if (angular.isString(contact))\n return contact;\n\n recipients = vm.message.editable[field];\n\n if (contact.$isList({expandable: true})) {\n // If the list's members were already fetch, use them\n if (angular.isDefined(contact.refs) && contact.refs.length) {\n _.forEach(contact.refs, function(ref) {\n if (ref.email.length)\n recipients.push(ref.$shortFormat());\n });\n }\n else {\n list = Card.$find(contact.container, contact.c_name);\n list.$id().then(function(listId) {\n _.forEach(list.refs, function(ref) {\n if (ref.email.length)\n recipients.push(ref.$shortFormat());\n });\n });\n }\n }\n else {\n recipient = contact.$shortFormat();\n }\n\n if (recipient)\n return recipient;\n else\n return null;\n }\n\n // Drafts autosaving\n function autosaveDrafts() {\n vm.message.$save();\n if (Preferences.defaults.SOGoMailAutoSave)\n vm.autosave = $timeout(vm.autosaveDrafts, Preferences.defaults.SOGoMailAutoSave*1000*60);\n }\n\n // Read user's defaults\n Preferences.ready().then(function() {\n if (Preferences.defaults.SOGoMailAutoSave)\n // Enable auto-save of draft\n vm.autosave = $timeout(vm.autosaveDrafts, Preferences.defaults.SOGoMailAutoSave*1000*60);\n // Set the locale of CKEditor\n vm.localeCode = Preferences.defaults.LocaleCode;\n });\n }\n\n SendMessageToastController.$inject = ['$scope', '$mdToast'];\n function SendMessageToastController($scope, $mdToast) {\n $scope.closeToast = function() {\n $mdToast.hide();\n };\n }\n\n angular\n .module('SOGo.MailerUI')\n .controller('SendMessageToastController', SendMessageToastController)\n .controller('MessageEditorController', MessageEditorController);\n\n})();\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n /* jshint validthis: true */\n 'use strict';\n\n /**\n * sgIMIP - A directive to handle IMIP actions on emails\n * @memberof SOGo.MailerUI\n * @example:\n\n */\n function sgImip() {\n return {\n restrict: 'A',\n link: link,\n controller: 'sgImipController'\n };\n\n function link(scope, iElement, attrs, ctrl) {\n ctrl.pathToAttachment = attrs.sgImipPath;\n }\n }\n\n /**\n * @ngInject\n */\n sgImipController.$inject = ['$scope', 'User'];\n function sgImipController($scope, User) {\n var vm = this;\n\n $scope.delegateInvitation = false;\n $scope.delegatedTo = '';\n $scope.searchText = '';\n\n $scope.userFilter = function($query) {\n return User.$filter($query);\n };\n\n $scope.iCalendarAction = function(action) {\n var data;\n\n if (action == 'delegate') {\n data = {\n receiveUpdates: false,\n delegatedTo: $scope.delegatedTo.c_email\n };\n }\n\n $scope.viewer.message.$imipAction(vm.pathToAttachment, action, data);\n };\n }\n\n angular\n .module('SOGo.MailerUI')\n .controller('sgImipController', sgImipController)\n .directive('sgImip', sgImip);\n})();\n\n","/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /*\n * sgZoomableImage - Toggle the 'sg-zoom' class when clicking on the image inside the container.\n * @memberof SOGo.MailerUI\n * @restrict attribute\n * @ngInject\n * @example:\n\n
\n \n \n \n
\n */\n function sgZoomableImage() {\n return {\n restrict: 'A',\n link: link\n };\n\n function link(scope, iElement, attrs, ctrl) {\n var parentNode = iElement.parent(),\n toggleClass;\n\n toggleClass = function(event) {\n if (event.target.tagName == 'IMG')\n parentNode.toggleClass('sg-zoom');\n };\n\n iElement.on('click', toggleClass);\n }\n }\n\n angular\n .module('SOGo.MailerUI')\n .directive('sgZoomableImage', sgZoomableImage);\n})();\n"]} \ No newline at end of file