diff --git a/UI/WebServerResources/js/Mailer.services.js b/UI/WebServerResources/js/Mailer.services.js index e6d6f5f54..106c56240 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(b){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)}),c},a.prototype.$getMailboxes=function(b){var c=this;return!this.$mailboxes||b&&b.reload?a.$Mailbox.$find(this).then(function(b){return c.$mailboxes=b,a.$Preferences.ready().then(function(){var b,d=function(a){_.forEach(a,function(a){a.$expanded=b.indexOf("/"+a.id)>=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,b.length>0&&d(c.$mailboxes)),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&&(_.reduce(d,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:"date",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(b){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){var c;return c=this.$$resource.fetch(b.id.toString(),"view"),a.$unwrapCollection(b,c)},a.$unwrapCollection=function(b,c){var d=[],e=function(c,d){for(var f=0;f=0&&ag&&h>g;g++)angular.isDefined(this.$messages[g].subject)||this.$messages[g].loading?c++:(e.push(this.$messages[g].uid),this.$messages[g].loading=!0);a.$log.debug("Loading UIDs "+e.join(" ")),f=a.$$resource.post(this.id,"headers",{uids:e}),this.$unwrapHeaders(f)}return i},a.prototype.isEditable=function(){return"folder"==this.type},a.prototype.isNoInferiors=function(){return this.flags.indexOf("noinferiors")>=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:b,flags:c,operation:d};return a.$$resource.post(this.id,"addOrRemoveLabel",e)},a.prototype.saveSelectedMessages=function(){var b,c;return b=_.filter(this.$messages,function(a){return a.selected}),c=_.map(b,"uid"),a.$$resource.download(this.id,"saveMessages",{uids:c})},a.prototype["export"]=function(){return a.$$resource.download(this.id,"exportFolder")},a.prototype.$delete=function(){var b=this;return a.$$resource.remove(this.id).then(function(){return b.$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),e>c&&(e=c)):d.uidsMap[b.uid]-=a.length}),e},a.prototype.$deleteMessages=function(b){var c,d=this;return c=_.map(b,"uid"),a.$$resource.post(this.id,"batchDelete",{uids:c}).then(function(a){return a.quotas&&d.$account.updateQuota(a.quotas),d.$_deleteMessages(c,b)})},a.prototype.$markOrUnMarkMessagesAsJunk=function(b){var c,d="junk"==this.type?"markMessagesAsNotJunk":"markMessagesAsJunk";return c=_.map(b,"uid"),a.$$resource.post(this.id,d,{uids:c})},a.prototype.$copyMessages=function(b,c){var d=this;return a.$$resource.post(this.id,"copyMessages",{uids:b,folder:c}).then(function(a){a.quotas&&d.$account.updateQuota(a.quotas)})},a.prototype.$moveMessages=function(b,c){var d,e=this;return d=_.map(b,"uid"),a.$$resource.post(this.id,"moveMessages",{uids:d,folder:c}).then(function(){return e.$_deleteMessages(d,b)})},a.prototype.$reset=function(){var a=this;angular.forEach(this,function(b,c){"constructor"!=c&&"children"!=c&&"$"!=c[0]&&delete a[c]}),angular.extend(this,this.$shadowData),this.$shadowData=this.$omit()},a.prototype.$save=function(){var b=this;return a.$$resource.save(this.id,this.$omit()).then(function(c){return b.$shadowData=b.$omit(),a.$log.debug(JSON.stringify(c,void 0,2)),c},function(c){a.$log.error(JSON.stringify(c,void 0,2)),b.$reset()})},a.prototype.$newMailbox=function(a,b){return this.$account.$newMailbox(a,b)},a.prototype.$omit=function(){var a={};return angular.forEach(this,function(b,c){"constructor"!=c&&"children"!=c&&"$"!=c[0]&&(a[c]=b)}),a},a.prototype.$unwrap=function(b){var c=this,d=a.$q.defer();return this.$futureMailboxData=b,this.$futureMailboxData.then(function(b){a.$timeout(function(){var e,f;(!b.uids||c.$topIndex>b.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)}))})})}}(),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","Gravatar","Resource","Preferences",function(b,c,d,e,f,g,h){return angular.extend(a,{$q:b,$timeout:c,$log:d,$gravatar:f,$$resource:new g(e.activeUser("folderURL")+"Mail",e.activeUser())}),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(b){angular.module("SOGo.MailerUI",["SOGo.Common"])}angular.module("SOGo.MailerUI").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];-1!=f[0].search(d)&&(_.includes(c,b)||e.push({name:b,description:f[0],color:f[1]}))}),e},a.prototype.$absolutePath=function(a){if(angular.isUndefined(this.id)||a){var b;b=_.map(this.$mailbox.path.split("/"),function(a){return"folder"+a.asCSSIdentifier()}),b.splice(0,0,this.accountId),a&&a.asDraft&&this.draftId?b.push(this.draftId):b.push(this.uid),this.id=b.join("/")}return this.id},a.prototype.$setUID=function(a){var b=this.uid||-1;b!=parseInt(a)&&(this.uid=parseInt(a),b>-1?(b=b.toString(),angular.isDefined(this.$mailbox.uidsMap[b])&&(this.$mailbox.uidsMap[a]=this.$mailbox.uidsMap[b],delete this.$mailbox.uidsMap[b])):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=b.name.split(" ")[0].replace("'",""))):b.email&&(b.full="<"+b.email+">",b.shortname=b.email.split("@")[0]),b.image=a.$gravatar(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){a>d&&c.push(b.shortname),d++})}),e>a&&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&&(f-=1,d=B.selectedFolder.$messages[f]),ba;a++)B.selectedFolder.$messages[a].selected=!0;B.mode.multiple=b}function v(){var a=_.filter(B.selectedFolder.$messages,function(a){return a.selected}),b=_.map(a,"uid");B.selectedFolder.$flagMessages(b,"\\Flagged","add").then(function(b){_.forEach(a,function(a){a.isflagged=!0})})}function w(){var a=_.filter(B.selectedFolder.$messages,function(a){return a.selected}),b=_.map(a,"uid");B.selectedFolder.$flagMessages(b,"seen","remove").then(function(b){_.forEach(a,function(a){a.isread=!1,B.selectedFolder.unseenCount++})})}function x(a){B.selectedFolder.$filter({sort:a})}function y(a){return k.$query.sort==a}function z(){B.mode.search=!1,B.selectedFolder.$filter().then(function(){B.selectedFolder.selectedMessage&&b(function(){B.selectedFolder.$topIndex=B.selectedFolder.uidsMap[B.selectedFolder.selectedMessage]})})}function A(a){var b;null===C&&(b=B.account.$newMessage(),C=d.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!1,escapeToClose:!1,templateUrl:"UIxMailEditor",controller:"MessageEditorController",controllerAs:"editor",locals:{stateAccounts:B.accounts,stateMessage:b,stateRecipients:[]}})["finally"](function(){C=null}))}var B=this,C=null;a.$mailboxController=B,k.selectedFolder=g,B.service=k,B.accounts=e,B.account=f,B.selectedFolder=g,B.selectMessage=m,B.toggleMessageSelection=n,B.unselectMessages=o,B.confirmDeleteSelectedMessages=p,B.markOrUnMarkMessagesAsJunk=q,B.copySelectedMessages=s,B.moveSelectedMessages=t,B.markSelectedMessagesAsFlagged=v,B.markSelectedMessagesAsUnread=w,B.selectAll=u,B.sort=x,B.sortedBy=y,B.cancelSearch=z,B.newMessage=A,B.mode={search:!1,multiple:0}}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","$timeout","$state","$mdDialog","stateAccounts","stateAccount","stateMailbox","encodeUriFilter","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){function r(a){M.showingAdvancedSearch=!0,M.search.mailbox=a,e("xs")&&f("left").close()}function s(){M.showingAdvancedSearch=!1,M.service.$virtualMode=!1,K=M.accounts[0],L=M.searchPreviousMailbox,a.go("mail.account.mailbox",{accountId:K.id,mailboxId:h(L.path)})}function t(){if(m.selectedFolder.$isLoading)M.virtualMailbox.stopSearch();else{var b,c=[],d=function(a){_.forEach(a,function(a){c.push(a),a.children&&a.children.length>0&&d(a.children)})};M.virtualMailbox=new n(M.accounts[0]),m.$virtualMode||(M.searchPreviousMailbox=m.selectedFolder),m.selectedFolder=M.virtualMailbox,m.$virtualMode=!0,angular.isDefined(M.search.mailbox)?(b=M.accounts[0].$getMailboxByPath(M.search.mailbox),c.push(b),M.search.subfolders&&b.children.length&&d(b.children)):c=M.accounts[0].$flattenMailboxes(),M.virtualMailbox.setMailboxes(c),M.virtualMailbox.startSearch(M.search.match,M.search.params),a.go("mail.account.virtualMailbox",{accountId:M.accounts[0].id})}}function u(a){return M.currentSearchParam=a,g("advancedSearch"),!1}function v(a){if(a.length&&M.currentSearchParam.length){var b=0,c=M.currentSearchParam;return a.startsWith("!")&&(b=1,a=a.substring(1).trim()),M.currentSearchParam="",{searchBy:c,searchInput:a,negative:b}}}function w(a){i.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){i.alert(l('An error occured while creating the mailbox "%{0}".',b),l(a.error))})})}function x(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){i.alert(l("Warning"),l("An error occured please try again."))})}function h(a){a&&d.$addDelegate(a).then(function(){j.userToAdd="",j.searchText=""},function(a){i.alert(l("Warning"),a)})}var j=this;j.users=d.delegates,j.account=d,j.userToAdd="",j.searchText="",j.userFilter=e,j.closeModal=f,j.removeUser=g,j.addUser=h}c.show({templateUrl:a.id+"/delegation",controller:b,controllerAs:"delegate",clickOutsideToClose:!0,escapeToClose:!0,locals:{User:o,account:a}}),b.$inject=["$scope","$mdDialog","User","account"]}function y(a){M.editMode=a.path,g("mailboxName_"+a.path)}function z(a){a.$reset(),M.editMode=!1}function A(b,c,d){M.editMode!=d.path&&(M.editMode=!1,M.showingAdvancedSearch=!1,M.service.$virtualMode=!1,e("xs")&&f("left").close(),a.go("mail.account.mailbox",{accountId:c.id,mailboxId:h(d.path)}),b.stopPropagation(),b.preventDefault())}function B(a){a.$rename().then(function(a){M.editMode=!1})}function C(a){a.$compact().then(function(){d.show(d.simple().content(l("Folder compacted")).position("top right").hideDelay(3e3))})}function D(a){a.$emptyTrash().then(function(){d.show(d.simple().content(l("Trash emptied")).position("top right").hideDelay(3e3))})}function E(b){i.confirm(l("Confirmation"),l("Do you really want to move this folder into the trash ?")).then(function(){b.$delete().then(function(){a.go("mail.account.inbox")},function(a,c){i.alert(l('An error occured while deleting the mailbox "%{0}".',b.name),l(a.error))})})}function F(a){a.$markAsRead()}function G(a){a.$acl.$users().then(function(){c.show({templateUrl:a.id+"/UIxAclEditor",controller:"AclController",controllerAs:"acl",clickOutsideToClose:!0,escapeToClose:!0,locals:{usersWithACL:a.$acl.users,User:o,folder:a}})})}function H(a){return"inbox"==a.type?{name:a.name,icon:"inbox"}:"draft"==a.type?{name:l("DraftsFolderName"),icon:"drafts"}:"sent"==a.type?{name:l("SentFolderName"),icon:"send"}:"trash"==a.type?{name:l("TrashFolderName"),icon:"delete"}:"junk"==a.type?{name:l("JunkFolderName"),icon:"thumb_down"}:"additional"==a.type?{name:a.name,icon:"folder_shared"}:{name:a.name,icon:"folder_open"}}function I(a,b){a.$setFolderAs(b).then(function(){a.$account.$getMailboxes({reload:!0})})}function J(){var a=window.unseenCountFolders;_.forEach(M.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)})}),k.$$resource.post("","unseenCount",{mailboxes:a}).then(function(a){_.forEach(M.accounts,function(b){ -_.forEach(b.$$flattenMailboxes,function(b){a[b.id]&&(b.unseenCount=a[b.id])})})}),p.ready().then(function(){var a=p.defaults.SOGoRefreshViewCheck;a&&"manually"!=a&&b(M.refreshUnseenCount,1e3*a.timeInterval())})}var K,L,M=this;M.service=m,M.accounts=q,M.newFolder=w,M.delegate=x,M.editFolder=y,M.revertEditing=z,M.selectFolder=A,M.saveFolder=B,M.compactFolder=C,M.emptyTrashFolder=D,M.confirmDelete=E,M.markFolderRead=F,M.share=G,M.metadataForFolder=H,M.setFolderAs=I,M.refreshUnseenCount=J,M.showingAdvancedSearch=!1,M.currentSearchParam="",M.addSearchParam=u,M.newSearchParam=v,M.showAdvancedSearch=r,M.hideAdvancedSearch=s,M.toggleAdvancedSearch=t,M.search={options:{"":l("Select a criteria"),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:[]},M.refreshUnseenCount()}a.$inject=["$state","$timeout","$mdDialog","$mdToast","$mdMedia","$mdSidenav","sgFocus","encodeUriFilter","Dialog","sgSettings","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,l,m,n,o,p,q){function r(){var b,c,d={};return a.opener&&a.opener.$mailboxController&&a.opener.$mailboxController.selectedFolder.$id()==g.$id()&&(c=a.opener.$mailboxController,d.mailboxCtrl=c,a.opener.$messageController&&a.opener.$messageController.message.uid==h.uid&&(b=a.opener.$messageController,d.messageCtrl=b)),d}function s(a){I.$showDetailedRecipients=!I.$showDetailedRecipients,a.stopPropagation(),a.preventDefault()}function t(){var a,b,d,e,f,i=r();i.messageCtrl?(a=i.mailboxCtrl.selectedFolder,b=i.messageCtrl.message,d=i.messageCtrl.$state):(a=g,b=h,d=c),a.$deleteMessages([b]).then(function(c){var g=c;if(b=null,angular.isDefined(d)){c>0&&(g-=1,e=a.$messages[g]),ca.$lastVisibleIndex&&(a.$topIndex=g-(a.$lastVisibleIndex-a.$topIndex))):d.go("mail.account.mailbox")}catch(h){}}B()})}function u(a,b,c){null===J&&(angular.isDefined(c)||(c=[]),J=d.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!1,escapeToClose:!1,templateUrl:"UIxMailEditor",controller:"MessageEditorController",controllerAs:"editor",locals:{stateAccounts:I.accounts,stateAccount:I.account,stateMessage:b,stateRecipients:c}})["finally"](function(){J=null,B()}))}function v(){c.go("mail.account.mailbox").then(function(){I.message=null,delete g.selectedMessage})}function w(a){var b=I.message.$reply();u(a,b)}function x(a){var b=I.message.$replyAll();u(a,b)}function y(a){var b=I.message.$forward();u(a,b)}function z(a){I.message.$editableContent().then(function(){u(a,I.message)})}function A(){var b=[j.baseURL(),"UIxMailPopupView#/Mail",I.message.accountId,i(i(I.message.$mailbox.path)),I.message.uid].join("/"),c=I.message.$absolutePath();K=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 B(){a.opener&&a.close()}function C(a,b){var c=I.account.$newMessage();u(a,c,[b]),a.stopPropagation(),a.preventDefault()}function D(a){I.showRawSource||I.rawSource?I.showRawSource=!I.showRawSource:q.$$resource.post(I.message.id,"viewsource").then(function(a){I.rawSource=a,I.showRawSource=!0})}function E(b){a.print()}function F(a){return H(a,"appointment")}function G(a){return H(a,"task")}function H(a,b){I.message.$plainContent().then(function(c){var e={pid:m.$defaultCalendar(),type:b,summary:c.subject,comment:c.content},f=new n(e),g=[j.activeUser("folderURL"),"Calendar","UIx"+b.capitalize()+"EditorTemplate"].join("/");return d.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!0,escapeToClose:!0,templateUrl:g,controller:"ComponentEditorController",controllerAs:"editor",locals:{stateComponent:f}})})}var I=this,J=null,K=null;a.$messageController=I,I.$state=c,I.accounts=e,I.account=f,I.mailbox=g,I.message=h,I.service=q,I.tags={searchText:"",selected:""},I.showFlags=h.flags&&h.flags.length>0,I.$showDetailedRecipients=!1,I.toggleDetailedRecipients=s,I.doDelete=t,I.close=v,I.reply=w,I.replyAll=x,I.forward=y,I.edit=z,I.openPopup=A,I.closePopup=B,I.newMessage=C,I.toggleRawSource=D,I.showRawSource=!1,I.print=E,I.convertToEvent=F,I.convertToTask=G,a.opener?(b.$watchCollection("viewer.message.flags",function(a,b){var c;(a||b)&&(c=r(),c.messageCtrl&&c.messageCtrl.service.$timeout(function(){c.messageCtrl.message.flags=a}))}),b.$watch("viewer.message.isflagged",function(a,b){var c=r();c.mailboxCtrl&&c.mailboxCtrl.service.$timeout(function(){var b=_.find(c.mailboxCtrl.selectedFolder.$messages,{uid:I.message.uid});b.isflagged=a})})):b.$watchCollection("viewer.message.flags",function(a,b){var c;(a||b)&&(_.forEach(a,function(b,c){angular.isObject(b)&&(a[c]=b.name)}),a.length>b.length?(c=_.difference(a,b),_.forEach(c,function(a){I.message.addTag(a)})):a.length":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(b){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)}),c},a.prototype.$getMailboxes=function(b){var c=this;return!this.$mailboxes||b&&b.reload?a.$Mailbox.$find(this).then(function(b){return c.$mailboxes=b,a.$Preferences.ready().then(function(){var b,d=function(a){_.forEach(a,function(a){a.$expanded=b.indexOf("/"+a.id)>=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,b.length>0&&d(c.$mailboxes)),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&&(_.reduce(d,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:"date",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(b){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){var c;return c=this.$$resource.fetch(b.id.toString(),"view"),a.$unwrapCollection(b,c)},a.$unwrapCollection=function(b,c){var d=[],e=function(c,d){for(var f=0;f=0&&ag&&h>g;g++)angular.isDefined(this.$messages[g].subject)||this.$messages[g].loading?c++:(e.push(this.$messages[g].uid),this.$messages[g].loading=!0);a.$log.debug("Loading UIDs "+e.join(" ")),f=a.$$resource.post(this.id,"headers",{uids:e}),this.$unwrapHeaders(f)}return i},a.prototype.isEditable=function(){return"folder"==this.type},a.prototype.isNoInferiors=function(){return this.flags.indexOf("noinferiors")>=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:b,flags:c,operation:d};return a.$$resource.post(this.id,"addOrRemoveLabel",e)},a.prototype.saveSelectedMessages=function(){var b,c;return b=_.filter(this.$messages,function(a){return a.selected}),c=_.map(b,"uid"),a.$$resource.download(this.id,"saveMessages",{uids:c})},a.prototype["export"]=function(){return a.$$resource.download(this.id,"exportFolder")},a.prototype.$delete=function(){var b=this;return a.$$resource.remove(this.id).then(function(){return b.$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),e>c&&(e=c)):d.uidsMap[b.uid]-=a.length}),e},a.prototype.$deleteMessages=function(b){var c,d=this;return c=_.map(b,"uid"),a.$$resource.post(this.id,"batchDelete",{uids:c}).then(function(a){return a.quotas&&d.$account.updateQuota(a.quotas),d.$_deleteMessages(c,b)})},a.prototype.$markOrUnMarkMessagesAsJunk=function(b){var c,d="junk"==this.type?"markMessagesAsNotJunk":"markMessagesAsJunk";return c=_.map(b,"uid"),a.$$resource.post(this.id,d,{uids:c})},a.prototype.$copyMessages=function(b,c){var d=this;return a.$$resource.post(this.id,"copyMessages",{uids:b,folder:c}).then(function(a){a.quotas&&d.$account.updateQuota(a.quotas)})},a.prototype.$moveMessages=function(b,c){var d,e=this;return d=_.map(b,"uid"),a.$$resource.post(this.id,"moveMessages",{uids:d,folder:c}).then(function(){return e.$_deleteMessages(d,b)})},a.prototype.$reset=function(){var a=this;angular.forEach(this,function(b,c){"constructor"!=c&&"children"!=c&&"$"!=c[0]&&delete a[c]}),angular.extend(this,this.$shadowData),this.$shadowData=this.$omit()},a.prototype.$save=function(){var b=this;return a.$$resource.save(this.id,this.$omit()).then(function(c){return b.$shadowData=b.$omit(),a.$log.debug(JSON.stringify(c,void 0,2)),c},function(c){a.$log.error(JSON.stringify(c,void 0,2)),b.$reset()})},a.prototype.$newMailbox=function(a,b){return this.$account.$newMailbox(a,b)},a.prototype.$omit=function(){var a={};return angular.forEach(this,function(b,c){"constructor"!=c&&"children"!=c&&"$"!=c[0]&&(a[c]=b)}),a},a.prototype.$unwrap=function(b){var c=this,d=a.$q.defer();return this.$futureMailboxData=b,this.$futureMailboxData.then(function(b){a.$timeout(function(){var e,f;(!b.uids||c.$topIndex>b.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)}))})})}}(),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","Gravatar","Resource","Preferences",function(b,c,d,e,f,g,h){return angular.extend(a,{$q:b,$timeout:c,$log:d,$gravatar:f,$$resource:new g(e.activeUser("folderURL")+"Mail",e.activeUser())}),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(b){angular.module("SOGo.MailerUI",["SOGo.Common"])}angular.module("SOGo.MailerUI").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];-1!=f[0].search(d)&&(_.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=b.name.split(" ")[0].replace("'",""))):b.email&&(b.full="<"+b.email+">",b.shortname=b.email.split("@")[0]),b.image=a.$gravatar(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){a>d&&c.push(b.shortname),d++})}),e>a&&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&&(f-=1,d=B.selectedFolder.$messages[f]),ba;a++)B.selectedFolder.$messages[a].selected=!0;B.mode.multiple=b}function v(){var a=_.filter(B.selectedFolder.$messages,function(a){return a.selected}),b=_.map(a,"uid");B.selectedFolder.$flagMessages(b,"\\Flagged","add").then(function(b){_.forEach(a,function(a){a.isflagged=!0})})}function w(){var a=_.filter(B.selectedFolder.$messages,function(a){return a.selected}),b=_.map(a,"uid");B.selectedFolder.$flagMessages(b,"seen","remove").then(function(b){_.forEach(a,function(a){a.isread=!1,B.selectedFolder.unseenCount++})})}function x(a){B.selectedFolder.$filter({sort:a})}function y(a){return k.$query.sort==a}function z(){B.mode.search=!1,B.selectedFolder.$filter().then(function(){B.selectedFolder.selectedMessage&&b(function(){B.selectedFolder.$topIndex=B.selectedFolder.uidsMap[B.selectedFolder.selectedMessage]})})}function A(a){var b;null===C&&(b=B.account.$newMessage(),C=d.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!1,escapeToClose:!1,templateUrl:"UIxMailEditor",controller:"MessageEditorController",controllerAs:"editor",locals:{stateAccount:B.account,stateMessage:b,stateRecipients:[]}})["finally"](function(){C=null}))}var B=this,C=null;a.$mailboxController=B,k.selectedFolder=g,B.service=k,B.accounts=e,B.account=f,B.selectedFolder=g,B.selectMessage=m,B.toggleMessageSelection=n,B.unselectMessages=o,B.confirmDeleteSelectedMessages=p,B.markOrUnMarkMessagesAsJunk=q,B.copySelectedMessages=s,B.moveSelectedMessages=t,B.markSelectedMessagesAsFlagged=v,B.markSelectedMessagesAsUnread=w,B.selectAll=u,B.sort=x,B.sortedBy=y,B.cancelSearch=z,B.newMessage=A,B.mode={search:!1,multiple:0}}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","$timeout","$state","$mdDialog","stateAccounts","stateAccount","stateMailbox","encodeUriFilter","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){function r(a){M.showingAdvancedSearch=!0,M.search.mailbox=a,e("xs")&&f("left").close()}function s(){M.showingAdvancedSearch=!1,M.service.$virtualMode=!1,K=M.accounts[0],L=M.searchPreviousMailbox,a.go("mail.account.mailbox",{accountId:K.id,mailboxId:h(L.path)})}function t(){if(m.selectedFolder.$isLoading)M.virtualMailbox.stopSearch();else{var b,c=[],d=function(a){_.forEach(a,function(a){c.push(a),a.children&&a.children.length>0&&d(a.children)})};M.virtualMailbox=new n(M.accounts[0]),m.$virtualMode||(M.searchPreviousMailbox=m.selectedFolder),m.selectedFolder=M.virtualMailbox,m.$virtualMode=!0,angular.isDefined(M.search.mailbox)?(b=M.accounts[0].$getMailboxByPath(M.search.mailbox),c.push(b),M.search.subfolders&&b.children.length&&d(b.children)):c=M.accounts[0].$flattenMailboxes(),M.virtualMailbox.setMailboxes(c),M.virtualMailbox.startSearch(M.search.match,M.search.params),a.go("mail.account.virtualMailbox",{accountId:M.accounts[0].id})}}function u(a){return M.currentSearchParam=a,g("advancedSearch"),!1}function v(a){if(a.length&&M.currentSearchParam.length){var b=0,c=M.currentSearchParam;return a.startsWith("!")&&(b=1,a=a.substring(1).trim()),M.currentSearchParam="",{searchBy:c,searchInput:a,negative:b}}}function w(a){i.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){i.alert(l('An error occured while creating the mailbox "%{0}".',b),l(a.error))})})}function x(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){i.alert(l("Warning"),l("An error occured please try again."))})}function h(a){a&&d.$addDelegate(a).then(function(){j.userToAdd="",j.searchText=""},function(a){i.alert(l("Warning"),a)})}var j=this;j.users=d.delegates,j.account=d,j.userToAdd="",j.searchText="",j.userFilter=e,j.closeModal=f,j.removeUser=g,j.addUser=h}c.show({templateUrl:a.id+"/delegation",controller:b,controllerAs:"delegate",clickOutsideToClose:!0,escapeToClose:!0,locals:{User:o,account:a}}),b.$inject=["$scope","$mdDialog","User","account"]}function y(a){M.editMode=a.path,g("mailboxName_"+a.path)}function z(a){a.$reset(),M.editMode=!1}function A(b,c,d){M.editMode!=d.path&&(M.editMode=!1,M.showingAdvancedSearch=!1,M.service.$virtualMode=!1,e("xs")&&f("left").close(),a.go("mail.account.mailbox",{accountId:c.id,mailboxId:h(d.path)}),b.stopPropagation(),b.preventDefault())}function B(a){a.$rename().then(function(a){M.editMode=!1})}function C(a){a.$compact().then(function(){d.show(d.simple().content(l("Folder compacted")).position("top right").hideDelay(3e3))})}function D(a){a.$emptyTrash().then(function(){d.show(d.simple().content(l("Trash emptied")).position("top right").hideDelay(3e3))})}function E(b){i.confirm(l("Confirmation"),l("Do you really want to move this folder into the trash ?")).then(function(){b.$delete().then(function(){a.go("mail.account.inbox")},function(a,c){i.alert(l('An error occured while deleting the mailbox "%{0}".',b.name),l(a.error))})})}function F(a){a.$markAsRead()}function G(a){a.$acl.$users().then(function(){c.show({templateUrl:a.id+"/UIxAclEditor",controller:"AclController",controllerAs:"acl",clickOutsideToClose:!0,escapeToClose:!0,locals:{usersWithACL:a.$acl.users,User:o,folder:a}})})}function H(a){return"inbox"==a.type?{name:a.name,icon:"inbox"}:"draft"==a.type?{name:l("DraftsFolderName"),icon:"drafts"}:"sent"==a.type?{name:l("SentFolderName"),icon:"send"}:"trash"==a.type?{name:l("TrashFolderName"),icon:"delete"}:"junk"==a.type?{name:l("JunkFolderName"),icon:"thumb_down"}:"additional"==a.type?{name:a.name,icon:"folder_shared"}:{name:a.name,icon:"folder_open"}}function I(a,b){a.$setFolderAs(b).then(function(){a.$account.$getMailboxes({reload:!0})})}function J(){var a=window.unseenCountFolders;_.forEach(M.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)})}),k.$$resource.post("","unseenCount",{mailboxes:a}).then(function(a){_.forEach(M.accounts,function(b){_.forEach(b.$$flattenMailboxes,function(b){a[b.id]&&(b.unseenCount=a[b.id])})})}),p.ready().then(function(){var a=p.defaults.SOGoRefreshViewCheck;a&&"manually"!=a&&b(M.refreshUnseenCount,1e3*a.timeInterval())})}var K,L,M=this;M.service=m,M.accounts=q,M.newFolder=w,M.delegate=x,M.editFolder=y,M.revertEditing=z,M.selectFolder=A,M.saveFolder=B,M.compactFolder=C,M.emptyTrashFolder=D,M.confirmDelete=E,M.markFolderRead=F,M.share=G,M.metadataForFolder=H,M.setFolderAs=I,M.refreshUnseenCount=J,M.showingAdvancedSearch=!1,M.currentSearchParam="",M.addSearchParam=u,M.newSearchParam=v,M.showAdvancedSearch=r,M.hideAdvancedSearch=s,M.toggleAdvancedSearch=t,M.search={options:{"":l("Select a criteria"),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:[]},M.refreshUnseenCount()}a.$inject=["$state","$timeout","$mdDialog","$mdToast","$mdMedia","$mdSidenav","sgFocus","encodeUriFilter","Dialog","sgSettings","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,l,m,n,o,p,q){function r(){var b,c,d={};return a.opener&&a.opener.$mailboxController&&a.opener.$mailboxController.selectedFolder.$id()==g.$id()&&(c=a.opener.$mailboxController,d.mailboxCtrl=c,a.opener.$messageController&&a.opener.$messageController.message.uid==h.uid&&(b=a.opener.$messageController,d.messageCtrl=b)),d}function s(a){J.$showDetailedRecipients=!J.$showDetailedRecipients,a.stopPropagation(),a.preventDefault()}function t(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])])}),D(a,e)))}function u(){var a,b,d,e,f,i=r();i.messageCtrl?(a=i.mailboxCtrl.selectedFolder,b=i.messageCtrl.message,d=i.messageCtrl.$state):(a=g,b=h,d=c),a.$deleteMessages([b]).then(function(c){var g=c;if(b=null,angular.isDefined(d)){c>0&&(g-=1,e=a.$messages[g]),ca.$lastVisibleIndex&&(a.$topIndex=g-(a.$lastVisibleIndex-a.$topIndex))):d.go("mail.account.mailbox")}catch(h){}}C()})}function v(a,b){null===K&&(K=d.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!1,escapeToClose:!1,templateUrl:"UIxMailEditor",controller:"MessageEditorController",controllerAs:"editor",locals:{stateAccounts:J.accounts,stateAccount:J.account,stateMessage:b}})["finally"](function(){K=null,C()}))}function w(){c.go("mail.account.mailbox").then(function(){J.message=null,delete g.selectedMessage})}function x(a){var b=J.message.$reply();v(a,b)}function y(a){var b=J.message.$replyAll();v(a,b)}function z(a){var b=J.message.$forward();v(a,b)}function A(a){J.message.$editableContent().then(function(){v(a,J.message)})}function B(){var b=[j.baseURL(),"UIxMailPopupView#/Mail",J.message.accountId,i(i(J.message.$mailbox.path)),J.message.uid].join("/"),c=J.message.$absolutePath();L=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 C(){a.opener&&a.close()}function D(a,b){J.account.$newMessage().then(function(c){angular.extend(c.editable,b),v(a,c)}),a.stopPropagation(),a.preventDefault()}function E(a){J.showRawSource||J.message.$rawSource?J.showRawSource=!J.showRawSource:q.$$resource.post(J.message.id,"viewsource").then(function(a){J.message.$rawSource=a,J.showRawSource=!0})}function F(b){a.print()}function G(a){return I(a,"appointment")}function H(a){return I(a,"task")}function I(a,b){J.message.$plainContent().then(function(c){var e={pid:m.$defaultCalendar(),type:b,summary:c.subject,comment:c.content},f=new n(e),g=[j.activeUser("folderURL"),"Calendar","UIx"+b.capitalize()+"EditorTemplate"].join("/");return d.show({parent:angular.element(document.body),targetEvent:a,clickOutsideToClose:!0,escapeToClose:!0,templateUrl:g,controller:"ComponentEditorController",controllerAs:"editor",locals:{stateComponent:f}})})}var J=this,K=null,L=null;a.$messageController=J,J.$state=c,J.accounts=e,J.account=f,J.mailbox=g,J.message=h,J.service=q,J.tags={searchText:"",selected:""},J.showFlags=h.flags&&h.flags.length>0,J.$showDetailedRecipients=!1,J.toggleDetailedRecipients=s,J.filterMailtoLinks=t,J.doDelete=u,J.close=w,J.reply=x,J.replyAll=y,J.forward=z,J.edit=A,J.openPopup=B,J.closePopup=C,J.newMessage=D,J.toggleRawSource=E,J.showRawSource=!1,J.print=F,J.convertToEvent=G,J.convertToTask=H,a.opener?(b.$watchCollection("viewer.message.flags",function(a,b){var c;(a||b)&&(c=r(),c.messageCtrl&&c.messageCtrl.service.$timeout(function(){c.messageCtrl.message.flags=a}))}),b.$watch("viewer.message.isflagged",function(a,b){var c=r();c.mailboxCtrl&&c.mailboxCtrl.service.$timeout(function(){var b=_.find(c.mailboxCtrl.selectedFolder.$messages,{uid:J.message.uid});b.isflagged=a})})):b.$watchCollection("viewer.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){J.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 return collection;\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).then(function(data) {\n _this.$mailboxes = data;\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 if (expandedFolders.length > 0) {\n _visit(_this.$mailboxes);\n }\n }\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] - force a reload\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 _.reduce(allMailboxes, function(expandedFolders, mailbox) {\n if (mailbox.$expanded) {\n expandedFolders.push('/' + mailbox.id);\n }\n return expandedFolders;\n }, expandedMailboxes);\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: 'date', asc: 0 },\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) {\n var path, futureMailboxData;\n\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 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 $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 var count;\n\n count = 0;\n if (this.$messages) {\n count = (_.filter(this.$messages, function(message) { return message.selected; })).length;\n }\n return count;\n };\n\n /**\n * @function isSelectedMessage\n * @memberof Mailbox.prototype\n * @desc Check if the specified message is selected.\n * @param {string} messageId\n * @returns true if the specified message is selected\n */\n Mailbox.prototype.isSelectedMessage = function(messageId) {\n return this.selectedMessage == messageId;\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 $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(uids, flags, operation) {\n var data = {msgUIDs: uids,\n flags: flags,\n operation: operation};\n\n return Mailbox.$$resource.post(this.id, 'addOrRemoveLabel', data);\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 selectedMessages, selectedUIDs;\n\n selectedMessages = _.filter(this.$messages, function(message) { return message.selected; });\n selectedUIDs = _.map(selectedMessages, 'uid');\n\n return Mailbox.$$resource.download(this.id, 'saveMessages', {uids: selectedUIDs});\n };\n\n /**\n * @function export\n * @memberof Mailbox.prototype\n * @desc Export this mailbox\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.export = function() {\n return Mailbox.$$resource.download(this.id, 'exportFolder');\n };\n\n /**\n * @function $delete\n * @memberof Mailbox.prototype\n * @desc Delete the mailbox from the server\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$delete = function() {\n var _this = this;\n\n return Mailbox.$$resource.remove(this.id)\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, selectedMessages, selectedUIDs, 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 * @return a promise of the HTTP operation\n */\n Mailbox.prototype.$deleteMessages = function(messages) {\n var _this = this, uids;\n\n uids = _.map(messages, 'uid');\n return Mailbox.$$resource.post(this.id, 'batchDelete', {uids: uids})\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, uids;\n var method = (this.type == 'junk' ? 'markMessagesAsNotJunk' : 'markMessagesAsJunk');\n uids = _.map(messages, 'uid');\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(uids, folder) {\n var _this = this;\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, function(value, key) {\n if (key != 'constructor' && key != 'children' && key[0] != '$') {\n delete _this[key];\n }\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(data) {\n Mailbox.$log.error(JSON.stringify(data, undefined, 2));\n // Restore previous version\n _this.$reset();\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[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","/* -*- 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', 'Gravatar', 'Resource', 'Preferences', function($q, $timeout, $log, Settings, Gravatar, Resource, Preferences) {\n angular.extend(Message, {\n $q: $q,\n $timeout: $timeout,\n $log: $log,\n $gravatar: Gravatar,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Mail', Settings.activeUser())\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 .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 if (angular.isUndefined(this.id) || options) {\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 if (options && options.asDraft && this.draftId) {\n path.push(this.draftId); // add draft ID\n }\n else {\n path.push(this.uid); // add message UID\n }\n\n this.id = path.join('/');\n }\n\n return this.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);\n\n if (oldUID != parseInt(uid)) {\n this.uid = parseInt(uid);\n if (oldUID > -1) {\n oldUID = oldUID.toString();\n if (angular.isDefined(this.$mailbox.uidsMap[oldUID])) {\n this.$mailbox.uidsMap[uid] = this.$mailbox.uidsMap[oldUID];\n delete this.$mailbox.uidsMap[oldUID];\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 a gravatar 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\" as name, we grab \"Alice\"\n data.shortname = data.name.split(' ')[0].replace('\\'','');\n }\n else if (data.email) {\n data.full = '<' + data.email + '>';\n data.shortname = data.email.split('@')[0];\n }\n\n // Generate the gravatar\n data.image = Message.$gravatar(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 // UIxMailPartICalViewer injects 'participants'\n if (part.participants) {\n _.forEach(part.participants, function(participant) {\n participant.image = Message.$gravatar(participant.email, 32);\n });\n }\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 _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 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 $reload\n * @memberof Message.prototype\n * @desc Fetch the viewable message body along with other metadata such as the list of attachments.\n * @returns a promise of the HTTP operation\n */\n Message.prototype.$reload = function(options) {\n var futureMessageData;\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({asDraft: false}); // 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(data) {\n if (data.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 data;\n }\n else {\n return Message.$q.reject(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 // 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 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 Message.$timeout(function() {\n angular.extend(_this, data);\n _this.$formatFullAddresses();\n _this.$loadUnsafeContent = false;\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 saveMessage\n * @memberof Message.prototype\n * @desc Download the current message\n * @returns a promise of the HTTP operation\n */\n Message.prototype.saveMessage = function() {\n var selectedUIDs;\n\n selectedUIDs = [ this.uid ];\n\n return Message.$$resource.download(this.$mailbox.id, 'saveMessages', {uids: selectedUIDs});\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', 'Message', 'Mailbox', 'sgMailbox_PRELOAD', function($q, $timeout, $log, Settings, Mailbox, Message, PRELOAD) {\n angular.extend(VirtualMailbox, {\n $q: $q,\n $timeout: $timeout,\n $log: $log,\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() { _this.$isLoading = false; });\n };\n\n VirtualMailbox.prototype.stopSearch = function() {\n VirtualMailbox.$log.debug(\"stopping search...\");\n this.$isLoading = false;\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 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 $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 // TODO\n return 0;\n };\n\n /**\n * @function $flagMessages\n * @memberof VirtualMailbox.prototype\n * @desc Add or remove a flag on a message set\n * @returns a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$flagMessages = function(uids, flags, operation) {\n // TODO\n // var data = {msgUIDs: uids,\n // flags: flags,\n // operation: operation};\n\n // return VirtualMailbox.$$resource.post(this.id, 'addOrRemoveLabel', data);\n };\n\n /**\n * @function $deleteMessages\n * @memberof VirtualMailbox.prototype\n * @desc Delete multiple messages from mailbox.\n * @return a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$deleteMessages = function(uids) {\n // TODO\n //return VirtualMailbox.$$resource.post(this.id, 'batchDelete', {uids: uids});\n };\n\n /**\n * @function $copyMessages\n * @memberof VirtualMailbox.prototype\n * @desc Copy multiple messages from the current mailbox to a target one\n * @return a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$copyMessages = function(uids, folder) {\n // TODO\n //return VirtualMailbox.$$resource.post(this.id, 'copyMessages', {uids: uids, folder: folder});\n };\n\n /**\n * @function $moveMessages\n * @memberof VirtualMailbox.prototype\n * @desc Move multiple messages from the current mailbox to a target one\n * @return a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$moveMessages = function(uids, folder) {\n // TODO\n //return VirtualMailbox.$$resource.post(this.id, 'moveMessages', {uids: uids, folder: folder});\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', '$timeout', '$state', '$mdDialog', 'stateAccounts', 'stateAccount', 'stateMailbox', 'encodeUriFilter', 'Dialog', 'Account', 'Mailbox'];\n function MailboxController($window, $timeout, $state, $mdDialog, stateAccounts, stateAccount, stateMailbox, encodeUriFilter, Dialog, Account, Mailbox) {\n var vm = this, messageDialog = null;\n\n // Expose controller\n $window.$mailboxController = vm;\n\n Mailbox.selectedFolder = stateMailbox;\n\n vm.service = Mailbox;\n vm.accounts = stateAccounts;\n vm.account = stateAccount;\n vm.selectedFolder = stateMailbox;\n vm.selectMessage = selectMessage;\n vm.toggleMessageSelection = toggleMessageSelection;\n vm.unselectMessages = unselectMessages;\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.selectAll = selectAll;\n vm.sort = sort;\n vm.sortedBy = sortedBy;\n vm.cancelSearch = cancelSearch;\n vm.newMessage = newMessage;\n vm.mode = { search: false, multiple: 0 };\n\n function selectMessage(message) {\n if (Mailbox.$virtualMode)\n $state.go('mail.account.virtualMailbox.message', {accountId: stateAccount.id, 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 message.selected = !message.selected;\n vm.mode.multiple += message.selected? 1 : -1;\n $event.preventDefault();\n $event.stopPropagation();\n }\n\n function unselectMessages() {\n _.forEach(vm.selectedFolder.$messages, function(message) {\n message.selected = false;\n });\n vm.mode.multiple = 0;\n }\n\n function confirmDeleteSelectedMessages() {\n Dialog.confirm(l('Warning'),\n l('Are you sure you want to delete the selected messages?'),\n { ok: l('Delete') })\n .then(function() {\n var deleteSelectedMessage = false;\n var selectedMessages = _.filter(vm.selectedFolder.$messages, function(message) {\n if (message.selected &&\n message.uid == vm.selectedFolder.selectedMessage)\n deleteSelectedMessage = true;\n return message.selected;\n });\n vm.selectedFolder.$deleteMessages(selectedMessages).then(function(index) {\n unselectMessage(deleteSelectedMessage, index);\n });\n });\n }\n\n function markOrUnMarkMessagesAsJunk() {\n var moveSelectedMessage = false;\n var selectedMessages = _.filter(vm.selectedFolder.$messages, function(message) {\n if (message.selected &&\n message.uid == vm.selectedFolder.selectedMessage)\n moveSelectedMessage = true;\n return message.selected;\n });\n\n vm.selectedFolder.$markOrUnMarkMessagesAsJunk(selectedMessages).then(function() {\n var folder = '/' + vm.account.id + '/folderINBOX';\n\n if (vm.selectedFolder.type != 'junk') {\n folder = '/' + vm.account.$getMailboxByType('junk').id;\n }\n\n vm.selectedFolder.$moveMessages(selectedMessages, folder).then(function(index) {\n unselectMessage(moveSelectedMessage, index);\n });\n });\n }\n\n function unselectMessage(message, index) {\n // Unselect current message and cleverly load the next message\n var nextMessage, previousMessage, nextIndex = index;\n vm.mode.multiple = vm.selectedFolder.$selectedCount();\n if (message) {\n if (Mailbox.$virtualMode) {\n $state.go('mail.account.virtualMailbox');\n }\n else {\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 $state.go('mail.account.mailbox.message', { messageId: nextMessage.uid });\n vm.selectedFolder.$topIndex = nextIndex;\n }\n else {\n $state.go('mail.account.mailbox');\n }\n }\n }\n }\n\n function copySelectedMessages(folder) {\n var selectedMessages = _.filter(vm.selectedFolder.$messages, function(message) { return message.selected; });\n var selectedUIDs = _.map(selectedMessages, 'uid');\n vm.selectedFolder.$copyMessages(selectedUIDs, '/' + folder);\n }\n\n function moveSelectedMessages(folder) {\n var moveSelectedMessage = false;\n var selectedMessages = _.filter(vm.selectedFolder.$messages, function(message) {\n if (message.selected &&\n message.uid == vm.selectedFolder.selectedMessage)\n moveSelectedMessage = true;\n return message.selected;\n });\n vm.selectedFolder.$moveMessages(selectedMessages, '/' + folder).then(function(index) {\n unselectMessage(moveSelectedMessage, index);\n });\n }\n\n function selectAll() {\n var i = 0, length = vm.selectedFolder.$messages.length;\n for (; i < length; i++)\n vm.selectedFolder.$messages[i].selected = true;\n vm.mode.multiple = length;\n }\n\n function markSelectedMessagesAsFlagged() {\n var selectedMessages = _.filter(vm.selectedFolder.$messages, function(message) { return message.selected; });\n var selectedUIDs = _.map(selectedMessages, 'uid');\n\n vm.selectedFolder.$flagMessages(selectedUIDs, '\\\\Flagged', 'add').then(function(d) {\n // Success\n _.forEach(selectedMessages, function(message) {\n message.isflagged = true;\n });\n });\n }\n\n function markSelectedMessagesAsUnread() {\n var selectedMessages = _.filter(vm.selectedFolder.$messages, function(message) { return message.selected; });\n var selectedUIDs = _.map(selectedMessages, 'uid');\n\n vm.selectedFolder.$flagMessages(selectedUIDs, 'seen', 'remove').then(function(d) {\n // Success\n _.forEach(selectedMessages, function(message) {\n message.isread = false;\n vm.selectedFolder.unseenCount++;\n });\n });\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 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) {\n var message;\n\n if (messageDialog === null) {\n message = vm.account.$newMessage();\n 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 stateAccounts: vm.accounts,\n stateMessage: message,\n stateRecipients: []\n }\n })\n .finally(function() {\n messageDialog = null;\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: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n MailboxesController.$inject = ['$state', '$timeout', '$mdDialog', '$mdToast', '$mdMedia', '$mdSidenav', 'sgFocus', 'encodeUriFilter', 'Dialog', 'sgSettings', 'Account', 'Mailbox', 'VirtualMailbox', 'User', 'Preferences', 'stateAccounts'];\n function MailboxesController($state, $timeout, $mdDialog, $mdToast, $mdMedia, $mdSidenav, focus, encodeUriFilter, Dialog, Settings, Account, Mailbox, VirtualMailbox, User, Preferences, stateAccounts) {\n var vm = this,\n account,\n mailbox;\n\n vm.service = Mailbox;\n vm.accounts = stateAccounts;\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\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: {'': l('Select a criteria'),\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 function showAdvancedSearch(path) {\n vm.showingAdvancedSearch = true;\n vm.search.mailbox = path;\n // Close sidenav on small devices\n if ($mdMedia('xs'))\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 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('xs'))\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('Confirmation'), l('Do you really want to move this folder into the trash ?'))\n .then(function() {\n folder.$delete()\n .then(function() {\n $state.go('mail.account.inbox');\n }, function(data, status) {\n Dialog.alert(l('An error occured while deleting the mailbox \"%{0}\".', folder.name),\n l(data.error));\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'};\n else if (folder.type == 'draft')\n return {name: l('DraftsFolderName'), icon: 'drafts'};\n else if (folder.type == 'sent')\n return {name: l('SentFolderName'), icon: 'send'};\n else if (folder.type == 'trash')\n return {name: l('TrashFolderName'), icon: 'delete'};\n else if (folder.type == 'junk')\n return {name: l('JunkFolderName'), icon: 'thumb_down'};\n else if (folder.type == 'additional')\n return {name: folder.name, icon: 'folder_shared'};\n\n return {name: folder.name, icon: 'folder_open'};\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 vm.refreshUnseenCount();\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', '$mdDialog', 'stateAccounts', 'stateAccount', 'stateMailbox', 'stateMessage', 'encodeUriFilter', 'sgSettings', 'sgFocus', 'Dialog', 'Calendar', 'Component', 'Account', 'Mailbox', 'Message'];\n function MessageController($window, $scope, $state, $mdDialog, stateAccounts, stateAccount, stateMailbox, stateMessage, encodeUriFilter, sgSettings, focus, Dialog, Calendar, Component, Account, Mailbox, Message) {\n var vm = this, messageDialog = null, popupWindow = null;\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.doDelete = doDelete;\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 // 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('viewer.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.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('viewer.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('viewer.message.flags', function(newTags, oldTags) {\n var tags;\n if (newTags || 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 /**\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 doDelete() {\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) {\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');\n }\n }\n catch (error) {}\n }\n closePopup();\n });\n }\n\n function showMailEditor($event, message, recipients) {\n if (messageDialog === null) {\n if (!angular.isDefined(recipients))\n recipients = [];\n\n 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 stateAccounts: vm.accounts,\n stateAccount: vm.account,\n stateMessage: message,\n stateRecipients: recipients\n }\n })\n .finally(function() {\n messageDialog = null;\n closePopup();\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, recipient) {\n var message = vm.account.$newMessage();\n showMailEditor($event, message, [recipient]);\n $event.stopPropagation();\n $event.preventDefault();\n }\n\n function toggleRawSource($event) {\n if (!vm.showRawSource && !vm.rawSource) {\n Message.$$resource.post(vm.message.id, \"viewsource\").then(function(data) {\n vm.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 = ['$window', '$stateParams', '$mdConstant', '$mdDialog', '$mdToast', 'FileUploader', 'stateAccounts', 'stateMessage', 'stateRecipients', 'encodeUriFilter', '$timeout', 'Dialog', 'AddressBook', 'Card', 'Preferences'];\n function MessageEditorController($window, $stateParams, $mdConstant, $mdDialog, $mdToast, FileUploader, stateAccounts, stateMessage, stateRecipients, encodeUriFilter, $timeout, Dialog, AddressBook, Card, Preferences) {\n var vm = this, semicolon = 186;\n\n vm.addRecipient = addRecipient;\n vm.autocomplete = {to: {}, cc: {}, bcc: {}};\n vm.autosave = null;\n vm.autosaveDrafts = autosaveDrafts;\n vm.hideCc = (stateMessage.editable.cc.length === 0);\n vm.hideBcc = (stateMessage.editable.bcc.length === 0);\n vm.cancel = cancel;\n vm.save = save;\n vm.send = send;\n vm.removeAttachment = removeAttachment;\n vm.contactFilter = contactFilter;\n vm.identities = _.map(_.flatten(_.map(stateAccounts, 'identities')), 'full');\n vm.recipientSeparatorKeys = [$mdConstant.KEY_CODE.ENTER, $mdConstant.KEY_CODE.TAB, $mdConstant.KEY_CODE.COMMA, semicolon];\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 .position('top right')\n .hideDelay(3000));\n this.removeFromQueue(item);\n //console.debug(item); console.debug('error = ' + JSON.stringify(response, undefined, 2));\n }\n });\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 if (angular.isDefined(stateRecipients)) {\n vm.message.editable.to = _.union(vm.message.editable.to, _.map(stateRecipients, 'full'));\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 if ($window.opener) {\n if ($window.opener.$mailboxController) {\n if ($window.opener.$mailboxController.selectedFolder.type == 'draft') {\n ctrls.draftMailboxCtrl = $window.opener.$mailboxController;\n if ($window.opener.$messageController &&\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 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) {\n if (item.isUploading)\n vm.uploader.cancelItem(item);\n else {\n vm.message.$deleteAttachment(item.file.name);\n item.remove();\n }\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 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 if (vm.autosave)\n $timeout.cancel(vm.autosave);\n\n vm.message.$send().then(function(data) {\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 $mdDialog.hide();\n });\n }\n\n function contactFilter($query) {\n AddressBook.$filterAll($query);\n return AddressBook.$cards;\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()) {\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","prototype","$getMailboxes","options","_this","$mailboxes","reload","$find","ready","expandedFolders","_visit","mailboxes","$expanded","indexOf","children","length","settings","Mail","ExpandedFolders","isString","fromJson","$flattenMailboxes","when","allMailboxes","expandedMailboxes","push","all","$$flattenMailboxes","saveState","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","account","futureMailboxData","$account","init","newMailboxData","create","$unwrap","Acl","PRELOAD","$$Acl","$query","sort","asc","selectedFolder","$refreshTimeout","$virtualMode","SortingState","parseInt","constant","LOOKAHEAD","SIZE","createMailboxes","level","index","quotas","split","component","asCSSIdentifier","join","$isLoading","$messages","uidsMap","$id","$acl","$isEditable","isEditable","$isNoInferiors","isNoInferiors","isUndefined","$shadowData","$omit","getLength","getItemAtIndex","$lastVisibleIndex","max","$loadMessage","$selectedCount","count","filter","selected","isSelectedMessage","messageId","selectedMessage","$filter","sortingAttributes","filters","isDefined","unseenCount","cancel","searchInput","secondFilter","match","searchBy","copy","refreshViewCheck","defaults","SOGoRefreshViewCheck","f","bind","timeInterval","endIndex","uids","futureHeadersData","startIndex","loaded","subject","min","loading","$unwrapHeaders","flags","$rename","findParent","parent","parentMailbox","$save","sibling","localeCompare","$compact","$setFolderAs","$emptyTrash","$markAsRead","$flagMessages","operation","msgUIDs","saveSelectedMessages","selectedMessages","selectedUIDs","download","$delete","remove","$_deleteMessages","messages","unseen","firstIndex","isread","forEachRight","selectedIndex","findIndex","$deleteMessages","$markOrUnMarkMessagesAsJunk","method","$copyMessages","folder","$moveMessages","$reset","value","key","save","error","$futureMailboxData","headers","$topIndex","invokeMap","threaded","msgs","msg","zipObject","isError","j","messageHeaders","futureMessageData","lazy","$mailbox","$hasUnsafeContent","$loadUnsafeContent","to","cc","bcc","$formatFullAddresses","Gravatar","$gravatar","SOGoMailLabelsColors","$tags","SOGoMailDisplayRemoteInlineImages","$displayRemoteInlineImages","filterTags","query","excludedTags","re","RegExp","results","keys","tag","pair","search","includes","color","buildPath","nocache","draftId","$setUID","oldUID","attr","constructor","shortname","replace","image","$shortRecipients","result","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","participants","participant","compile","$editableContent","from","toLowerCase","text","$plainContent","addTag","$addOrRemoveTag","removeTag","$imipAction","action","$reload","$sendMDN","shouldAskReceipt","$deleteAttachment","filename","attachmentAttrs","attachment","toggleFlag","isflagged","$reply","$newDraft","$replyAll","$forward","origin","response","$send","startsWith","isanswered","isforwarded","$futureMessageData","privateAttributes","saveMessage","VirtualMailbox","setMailboxes","startSearch","params","stopSearch","resetSelectedMessage","len","k","MailboxController","$window","$state","$mdDialog","stateAccounts","stateAccount","stateMailbox","encodeUriFilter","Dialog","selectMessage","go","mailboxId","toggleMessageSelection","$event","vm","mode","multiple","preventDefault","stopPropagation","unselectMessages","confirmDeleteSelectedMessages","confirm","ok","deleteSelectedMessage","unselectMessage","markOrUnMarkMessagesAsJunk","moveSelectedMessage","nextMessage","previousMessage","nextIndex","copySelectedMessages","moveSelectedMessages","selectAll","markSelectedMessagesAsFlagged","d","markSelectedMessagesAsUnread","field","sortedBy","cancelSearch","newMessage","messageDialog","show","body","targetEvent","clickOutsideToClose","escapeToClose","templateUrl","controller","controllerAs","locals","stateMessage","stateRecipients","$mailboxController","service","accounts","mdVirtualRepeatContainerDirectiveDecorator","$delegate","resetScroll","$element","updateSize","scrollTo","$inject","decorator","MailboxesController","$mdToast","$mdMedia","$mdSidenav","focus","User","showAdvancedSearch","showingAdvancedSearch","close","hideAdvancedSearch","searchPreviousMailbox","toggleAdvancedSearch","virtualMailbox","root","folders","subfolders","addSearchParam","v","currentSearchParam","newSearchParam","pattern","n","searchParam","substring","trim","negative","newFolder","parentFolder","prompt","alert","delegate","MailboxDelegationController","$scope","userFilter","closeModal","hide","removeUser","addUser","userToAdd","searchText","editFolder","editMode","revertEditing","selectFolder","saveFolder","compactFolder","simple","position","hideDelay","emptyTrashFolder","confirmDelete","markFolderRead","share","$users","usersWithACL","metadataForFolder","icon","setFolderAs","refreshUnseenCount","unseenCountFolders","window","","MessageController","sgSettings","Calendar","Component","$parentControllers","ctrls","opener","mailboxCtrl","$messageController","messageCtrl","toggleDetailedRecipients","$showDetailedRecipients","filterMailtoLinks","href","target","tagName","attributes","exec","decodeURIComponent","doDelete","state","parentCtrls","closePopup","showMailEditor","reply","replyAll","forward","edit","openPopup","url","baseURL","wId","popupWindow","open","editableContent","toggleRawSource","showRawSource","$rawSource","print","convertToEvent","convertToComponent","convertToTask","componentData","pid","$defaultCalendar","summary","comment","capitalize","stateComponent","tags","showFlags","$watchCollection","newTags","oldTags","$watch","wasflagged","_newTags","_oldTags","isObject","difference","MessageEditorController","$stateParams","$mdConstant","FileUploader","AddressBook","Card","originMessage","draftMailboxCtrl","draftMessageCtrl","originMailboxCtrl","addAttachments","fileItem","attrs","mimetype","size","FileItem","uploader","progress","isUploaded","isSuccess","inlineUrl","queue","removeAttachment","item","isUploading","cancelItem","file","autosave","send","contactFilter","$filterAll","$cards","addRecipient","contact","recipients","recipient","list","$isList","refs","ref","$shortFormat","container","c_name","listId","autosaveDrafts","SOGoMailAutoSave","semicolon","autocomplete","hideCc","hideBcc","recipientSeparatorKeys","KEY_CODE","ENTER","TAB","COMMA","autoUpload","alias","removeAfterUpload","onSuccessItem","lastAttachmentAttrs","onCancelItem","removeFromQueue","onErrorItem","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","event","on"],"mappings":"CAEA,WACE,YAOA,SAASA,GAAQC,GAEuB,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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AW,SAAU,QA0BtCla,QACG4B,OAAO,iBACPwX,WAAW,mBAAoBuN,GAC/BO,UAAU,SAAUf,MCtDzB,WACE,YAeA,SAASgB,KAMP,QAASf,GAAKC,EAAOC,EAAU5D,EAAO6D,GACpC,GACIa,GADAC,EAAaf,EAASna,QAG1Bib,GAAc,SAASE,GACO,OAAxBA,EAAMtI,OAAOC,SACfoI,EAAWD,YAAY,YAG3Bd,EAASiB,GAAG,QAASH,GAdvB,OACEV,SAAU,IACVN,KAAMA,GAgBVpmB,QACG4B,OAAO,iBACPslB,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 return collection;\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).then(function(data) {\n _this.$mailboxes = data;\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 if (expandedFolders.length > 0) {\n _visit(_this.$mailboxes);\n }\n }\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] - force a reload\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 _.reduce(allMailboxes, function(expandedFolders, mailbox) {\n if (mailbox.$expanded) {\n expandedFolders.push('/' + mailbox.id);\n }\n return expandedFolders;\n }, expandedMailboxes);\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: 'date', asc: 0 },\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) {\n var path, futureMailboxData;\n\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 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 $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 var count;\n\n count = 0;\n if (this.$messages) {\n count = (_.filter(this.$messages, function(message) { return message.selected; })).length;\n }\n return count;\n };\n\n /**\n * @function isSelectedMessage\n * @memberof Mailbox.prototype\n * @desc Check if the specified message is selected.\n * @param {string} messageId\n * @returns true if the specified message is selected\n */\n Mailbox.prototype.isSelectedMessage = function(messageId) {\n return this.selectedMessage == messageId;\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 $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(uids, flags, operation) {\n var data = {msgUIDs: uids,\n flags: flags,\n operation: operation};\n\n return Mailbox.$$resource.post(this.id, 'addOrRemoveLabel', data);\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 selectedMessages, selectedUIDs;\n\n selectedMessages = _.filter(this.$messages, function(message) { return message.selected; });\n selectedUIDs = _.map(selectedMessages, 'uid');\n\n return Mailbox.$$resource.download(this.id, 'saveMessages', {uids: selectedUIDs});\n };\n\n /**\n * @function export\n * @memberof Mailbox.prototype\n * @desc Export this mailbox\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.export = function() {\n return Mailbox.$$resource.download(this.id, 'exportFolder');\n };\n\n /**\n * @function $delete\n * @memberof Mailbox.prototype\n * @desc Delete the mailbox from the server\n * @returns a promise of the HTTP operation\n */\n Mailbox.prototype.$delete = function() {\n var _this = this;\n\n return Mailbox.$$resource.remove(this.id)\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, selectedMessages, selectedUIDs, 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 * @return a promise of the HTTP operation\n */\n Mailbox.prototype.$deleteMessages = function(messages) {\n var _this = this, uids;\n\n uids = _.map(messages, 'uid');\n return Mailbox.$$resource.post(this.id, 'batchDelete', {uids: uids})\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, uids;\n var method = (this.type == 'junk' ? 'markMessagesAsNotJunk' : 'markMessagesAsJunk');\n uids = _.map(messages, 'uid');\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(uids, folder) {\n var _this = this;\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, function(value, key) {\n if (key != 'constructor' && key != 'children' && key[0] != '$') {\n delete _this[key];\n }\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(data) {\n Mailbox.$log.error(JSON.stringify(data, undefined, 2));\n // Restore previous version\n _this.$reset();\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[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","/* -*- 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', 'Gravatar', 'Resource', 'Preferences', function($q, $timeout, $log, Settings, Gravatar, Resource, Preferences) {\n angular.extend(Message, {\n $q: $q,\n $timeout: $timeout,\n $log: $log,\n $gravatar: Gravatar,\n $$resource: new Resource(Settings.activeUser('folderURL') + 'Mail', Settings.activeUser())\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 .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 a gravatar 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\" as name, we grab \"Alice\"\n data.shortname = data.name.split(' ')[0].replace('\\'','');\n }\n else if (data.email) {\n data.full = '<' + data.email + '>';\n data.shortname = data.email.split('@')[0];\n }\n\n // Generate the gravatar\n data.image = Message.$gravatar(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 // UIxMailPartICalViewer injects 'participants'\n if (part.participants) {\n _.forEach(part.participants, function(participant) {\n participant.image = Message.$gravatar(participant.email, 32);\n });\n }\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 _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 $reload\n * @memberof Message.prototype\n * @desc Fetch the viewable message body along with other metadata such as the list of attachments.\n * @returns a promise of the HTTP operation\n */\n Message.prototype.$reload = function(options) {\n var futureMessageData;\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(data) {\n if (data.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 data;\n }\n else {\n return Message.$q.reject(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 // 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 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 Message.$timeout(function() {\n angular.extend(_this, data);\n _this.$formatFullAddresses();\n _this.$loadUnsafeContent = false;\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 saveMessage\n * @memberof Message.prototype\n * @desc Download the current message\n * @returns a promise of the HTTP operation\n */\n Message.prototype.saveMessage = function() {\n var selectedUIDs;\n\n selectedUIDs = [ this.uid ];\n\n return Message.$$resource.download(this.$mailbox.id, 'saveMessages', {uids: selectedUIDs});\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', 'Message', 'Mailbox', 'sgMailbox_PRELOAD', function($q, $timeout, $log, Settings, Mailbox, Message, PRELOAD) {\n angular.extend(VirtualMailbox, {\n $q: $q,\n $timeout: $timeout,\n $log: $log,\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() { _this.$isLoading = false; });\n };\n\n VirtualMailbox.prototype.stopSearch = function() {\n VirtualMailbox.$log.debug(\"stopping search...\");\n this.$isLoading = false;\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 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 $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 // TODO\n return 0;\n };\n\n /**\n * @function $flagMessages\n * @memberof VirtualMailbox.prototype\n * @desc Add or remove a flag on a message set\n * @returns a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$flagMessages = function(uids, flags, operation) {\n // TODO\n // var data = {msgUIDs: uids,\n // flags: flags,\n // operation: operation};\n\n // return VirtualMailbox.$$resource.post(this.id, 'addOrRemoveLabel', data);\n };\n\n /**\n * @function $deleteMessages\n * @memberof VirtualMailbox.prototype\n * @desc Delete multiple messages from mailbox.\n * @return a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$deleteMessages = function(uids) {\n // TODO\n //return VirtualMailbox.$$resource.post(this.id, 'batchDelete', {uids: uids});\n };\n\n /**\n * @function $copyMessages\n * @memberof VirtualMailbox.prototype\n * @desc Copy multiple messages from the current mailbox to a target one\n * @return a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$copyMessages = function(uids, folder) {\n // TODO\n //return VirtualMailbox.$$resource.post(this.id, 'copyMessages', {uids: uids, folder: folder});\n };\n\n /**\n * @function $moveMessages\n * @memberof VirtualMailbox.prototype\n * @desc Move multiple messages from the current mailbox to a target one\n * @return a promise of the HTTP operation\n */\n VirtualMailbox.prototype.$moveMessages = function(uids, folder) {\n // TODO\n //return VirtualMailbox.$$resource.post(this.id, 'moveMessages', {uids: uids, folder: folder});\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', '$timeout', '$state', '$mdDialog', 'stateAccounts', 'stateAccount', 'stateMailbox', 'encodeUriFilter', 'Dialog', 'Account', 'Mailbox'];\n function MailboxController($window, $timeout, $state, $mdDialog, stateAccounts, stateAccount, stateMailbox, encodeUriFilter, Dialog, Account, Mailbox) {\n var vm = this, messageDialog = null;\n\n // Expose controller\n $window.$mailboxController = vm;\n\n Mailbox.selectedFolder = stateMailbox;\n\n vm.service = Mailbox;\n vm.accounts = stateAccounts;\n vm.account = stateAccount;\n vm.selectedFolder = stateMailbox;\n vm.selectMessage = selectMessage;\n vm.toggleMessageSelection = toggleMessageSelection;\n vm.unselectMessages = unselectMessages;\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.selectAll = selectAll;\n vm.sort = sort;\n vm.sortedBy = sortedBy;\n vm.cancelSearch = cancelSearch;\n vm.newMessage = newMessage;\n vm.mode = { search: false, multiple: 0 };\n\n function selectMessage(message) {\n if (Mailbox.$virtualMode)\n $state.go('mail.account.virtualMailbox.message', {accountId: stateAccount.id, 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 message.selected = !message.selected;\n vm.mode.multiple += message.selected? 1 : -1;\n $event.preventDefault();\n $event.stopPropagation();\n }\n\n function unselectMessages() {\n _.forEach(vm.selectedFolder.$messages, function(message) {\n message.selected = false;\n });\n vm.mode.multiple = 0;\n }\n\n function confirmDeleteSelectedMessages() {\n Dialog.confirm(l('Warning'),\n l('Are you sure you want to delete the selected messages?'),\n { ok: l('Delete') })\n .then(function() {\n var deleteSelectedMessage = false;\n var selectedMessages = _.filter(vm.selectedFolder.$messages, function(message) {\n if (message.selected &&\n message.uid == vm.selectedFolder.selectedMessage)\n deleteSelectedMessage = true;\n return message.selected;\n });\n vm.selectedFolder.$deleteMessages(selectedMessages).then(function(index) {\n unselectMessage(deleteSelectedMessage, index);\n });\n });\n }\n\n function markOrUnMarkMessagesAsJunk() {\n var moveSelectedMessage = false;\n var selectedMessages = _.filter(vm.selectedFolder.$messages, function(message) {\n if (message.selected &&\n message.uid == vm.selectedFolder.selectedMessage)\n moveSelectedMessage = true;\n return message.selected;\n });\n\n vm.selectedFolder.$markOrUnMarkMessagesAsJunk(selectedMessages).then(function() {\n var folder = '/' + vm.account.id + '/folderINBOX';\n\n if (vm.selectedFolder.type != 'junk') {\n folder = '/' + vm.account.$getMailboxByType('junk').id;\n }\n\n vm.selectedFolder.$moveMessages(selectedMessages, folder).then(function(index) {\n unselectMessage(moveSelectedMessage, index);\n });\n });\n }\n\n function unselectMessage(message, index) {\n // Unselect current message and cleverly load the next message\n var nextMessage, previousMessage, nextIndex = index;\n vm.mode.multiple = vm.selectedFolder.$selectedCount();\n if (message) {\n if (Mailbox.$virtualMode) {\n $state.go('mail.account.virtualMailbox');\n }\n else {\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 $state.go('mail.account.mailbox.message', { messageId: nextMessage.uid });\n vm.selectedFolder.$topIndex = nextIndex;\n }\n else {\n $state.go('mail.account.mailbox');\n }\n }\n }\n }\n\n function copySelectedMessages(folder) {\n var selectedMessages = _.filter(vm.selectedFolder.$messages, function(message) { return message.selected; });\n var selectedUIDs = _.map(selectedMessages, 'uid');\n vm.selectedFolder.$copyMessages(selectedUIDs, '/' + folder);\n }\n\n function moveSelectedMessages(folder) {\n var moveSelectedMessage = false;\n var selectedMessages = _.filter(vm.selectedFolder.$messages, function(message) {\n if (message.selected &&\n message.uid == vm.selectedFolder.selectedMessage)\n moveSelectedMessage = true;\n return message.selected;\n });\n vm.selectedFolder.$moveMessages(selectedMessages, '/' + folder).then(function(index) {\n unselectMessage(moveSelectedMessage, index);\n });\n }\n\n function selectAll() {\n var i = 0, length = vm.selectedFolder.$messages.length;\n for (; i < length; i++)\n vm.selectedFolder.$messages[i].selected = true;\n vm.mode.multiple = length;\n }\n\n function markSelectedMessagesAsFlagged() {\n var selectedMessages = _.filter(vm.selectedFolder.$messages, function(message) { return message.selected; });\n var selectedUIDs = _.map(selectedMessages, 'uid');\n\n vm.selectedFolder.$flagMessages(selectedUIDs, '\\\\Flagged', 'add').then(function(d) {\n // Success\n _.forEach(selectedMessages, function(message) {\n message.isflagged = true;\n });\n });\n }\n\n function markSelectedMessagesAsUnread() {\n var selectedMessages = _.filter(vm.selectedFolder.$messages, function(message) { return message.selected; });\n var selectedUIDs = _.map(selectedMessages, 'uid');\n\n vm.selectedFolder.$flagMessages(selectedUIDs, 'seen', 'remove').then(function(d) {\n // Success\n _.forEach(selectedMessages, function(message) {\n message.isread = false;\n vm.selectedFolder.unseenCount++;\n });\n });\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 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) {\n var message;\n\n if (messageDialog === null) {\n message = vm.account.$newMessage();\n 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 stateRecipients: []\n }\n })\n .finally(function() {\n messageDialog = null;\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: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */\n\n(function() {\n 'use strict';\n\n /**\n * @ngInject\n */\n MailboxesController.$inject = ['$state', '$timeout', '$mdDialog', '$mdToast', '$mdMedia', '$mdSidenav', 'sgFocus', 'encodeUriFilter', 'Dialog', 'sgSettings', 'Account', 'Mailbox', 'VirtualMailbox', 'User', 'Preferences', 'stateAccounts'];\n function MailboxesController($state, $timeout, $mdDialog, $mdToast, $mdMedia, $mdSidenav, focus, encodeUriFilter, Dialog, Settings, Account, Mailbox, VirtualMailbox, User, Preferences, stateAccounts) {\n var vm = this,\n account,\n mailbox;\n\n vm.service = Mailbox;\n vm.accounts = stateAccounts;\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\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: {'': l('Select a criteria'),\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 function showAdvancedSearch(path) {\n vm.showingAdvancedSearch = true;\n vm.search.mailbox = path;\n // Close sidenav on small devices\n if ($mdMedia('xs'))\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 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('xs'))\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('Confirmation'), l('Do you really want to move this folder into the trash ?'))\n .then(function() {\n folder.$delete()\n .then(function() {\n $state.go('mail.account.inbox');\n }, function(data, status) {\n Dialog.alert(l('An error occured while deleting the mailbox \"%{0}\".', folder.name),\n l(data.error));\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'};\n else if (folder.type == 'draft')\n return {name: l('DraftsFolderName'), icon: 'drafts'};\n else if (folder.type == 'sent')\n return {name: l('SentFolderName'), icon: 'send'};\n else if (folder.type == 'trash')\n return {name: l('TrashFolderName'), icon: 'delete'};\n else if (folder.type == 'junk')\n return {name: l('JunkFolderName'), icon: 'thumb_down'};\n else if (folder.type == 'additional')\n return {name: folder.name, icon: 'folder_shared'};\n\n return {name: folder.name, icon: 'folder_open'};\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 vm.refreshUnseenCount();\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', '$mdDialog', 'stateAccounts', 'stateAccount', 'stateMailbox', 'stateMessage', 'encodeUriFilter', 'sgSettings', 'sgFocus', 'Dialog', 'Calendar', 'Component', 'Account', 'Mailbox', 'Message'];\n function MessageController($window, $scope, $state, $mdDialog, stateAccounts, stateAccount, stateMailbox, stateMessage, encodeUriFilter, sgSettings, focus, Dialog, Calendar, Component, Account, Mailbox, Message) {\n var vm = this, messageDialog = null, popupWindow = null;\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.doDelete = doDelete;\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 // 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('viewer.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.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('viewer.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('viewer.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 /**\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 doDelete() {\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) {\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');\n }\n }\n catch (error) {}\n }\n closePopup();\n });\n }\n\n function showMailEditor($event, message) {\n if (messageDialog === null) {\n 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 stateAccounts: vm.accounts,\n stateAccount: vm.account,\n stateMessage: message\n }\n })\n .finally(function() {\n messageDialog = null;\n closePopup();\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 = ['$window', '$stateParams', '$mdConstant', '$mdDialog', '$mdToast', 'FileUploader', 'stateAccount', 'stateMessage', 'encodeUriFilter', '$timeout', 'Dialog', 'AddressBook', 'Card', 'Preferences'];\n function MessageEditorController($window, $stateParams, $mdConstant, $mdDialog, $mdToast, FileUploader, stateAccount, stateMessage, encodeUriFilter, $timeout, Dialog, AddressBook, Card, Preferences) {\n var vm = this, semicolon = 186;\n\n vm.addRecipient = addRecipient;\n vm.autocomplete = {to: {}, cc: {}, bcc: {}};\n vm.autosave = null;\n vm.autosaveDrafts = autosaveDrafts;\n vm.hideCc = (stateMessage.editable.cc.length === 0);\n vm.hideBcc = (stateMessage.editable.bcc.length === 0);\n vm.cancel = cancel;\n vm.save = save;\n vm.send = send;\n vm.removeAttachment = removeAttachment;\n vm.contactFilter = contactFilter;\n vm.identities = _.map(stateAccount.identities, 'full');\n vm.recipientSeparatorKeys = [$mdConstant.KEY_CODE.ENTER, $mdConstant.KEY_CODE.TAB, $mdConstant.KEY_CODE.COMMA, semicolon];\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 .position('top right')\n .hideDelay(3000));\n this.removeFromQueue(item);\n //console.debug(item); console.debug('error = ' + JSON.stringify(response, undefined, 2));\n }\n });\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 if ($window.opener) {\n if ($window.opener.$mailboxController) {\n if ($window.opener.$mailboxController.selectedFolder.type == 'draft') {\n ctrls.draftMailboxCtrl = $window.opener.$mailboxController;\n if ($window.opener.$messageController &&\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 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) {\n if (item.isUploading)\n vm.uploader.cancelItem(item);\n else {\n vm.message.$deleteAttachment(item.file.name);\n item.remove();\n }\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 if (vm.autosave)\n $timeout.cancel(vm.autosave);\n\n vm.message.$send().then(function(data) {\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 $mdDialog.hide();\n });\n }\n\n function contactFilter($query) {\n AddressBook.$filterAll($query);\n return AddressBook.$cards;\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()) {\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