diff --git a/dev/Admin/AdminSettingsAbout.js b/dev/Admin/AdminSettingsAbout.js index fbb267840..8a4311508 100644 --- a/dev/Admin/AdminSettingsAbout.js +++ b/dev/Admin/AdminSettingsAbout.js @@ -6,7 +6,9 @@ var ko = require('../External/ko.js'), - Data = require('../Storages/AdminDataStorage.js') + AppSettings = require('../Storages/AppSettings.js'), + Data = require('../Storages/AdminDataStorage.js'), + RL = require('../Boots/AdminApp.js') ; /** @@ -14,8 +16,8 @@ */ function AdminSettingsAbout() { - this.version = ko.observable(RL.settingsGet('Version')); - this.access = ko.observable(!!RL.settingsGet('CoreAccess')); + this.version = ko.observable(AppSettings.settingsGet('Version')); + this.access = ko.observable(!!AppSettings.settingsGet('CoreAccess')); this.errorDesc = ko.observable(''); this.coreReal = Data.coreReal; @@ -64,8 +66,6 @@ }, this); } - kn.addSettingsViewModel(AdminSettingsAbout, 'AdminSettingsAbout', 'About', 'about'); - AdminSettingsAbout.prototype.onBuild = function () { if (this.access()) diff --git a/dev/Admin/AdminSettingsBranding.js b/dev/Admin/AdminSettingsBranding.js index 7c9c76c92..21bb254e4 100644 --- a/dev/Admin/AdminSettingsBranding.js +++ b/dev/Admin/AdminSettingsBranding.js @@ -7,9 +7,11 @@ var _ = require('../External/underscore.js'), ko = require('../External/ko.js'), + Enums = require('../Common/Enums.js'), Utils = require('../Common/Utils.js'), - kn = require('../Knoin/Knoin.js'), + + AppSettings = require('..Storages/AppSettings.js'), Remote = require('../Storages/AdminAjaxRemoteStorage.js') ; @@ -18,24 +20,22 @@ */ function AdminSettingsBranding() { - this.title = ko.observable(RL.settingsGet('Title')); + this.title = ko.observable(AppSettings.settingsGet('Title')); this.title.trigger = ko.observable(Enums.SaveSettingsStep.Idle); - this.loadingDesc = ko.observable(RL.settingsGet('LoadingDescription')); + this.loadingDesc = ko.observable(AppSettings.settingsGet('LoadingDescription')); this.loadingDesc.trigger = ko.observable(Enums.SaveSettingsStep.Idle); - this.loginLogo = ko.observable(RL.settingsGet('LoginLogo')); + this.loginLogo = ko.observable(AppSettings.settingsGet('LoginLogo')); this.loginLogo.trigger = ko.observable(Enums.SaveSettingsStep.Idle); - this.loginDescription = ko.observable(RL.settingsGet('LoginDescription')); + this.loginDescription = ko.observable(AppSettings.settingsGet('LoginDescription')); this.loginDescription.trigger = ko.observable(Enums.SaveSettingsStep.Idle); - this.loginCss = ko.observable(RL.settingsGet('LoginCss')); + this.loginCss = ko.observable(AppSettings.settingsGet('LoginCss')); this.loginCss.trigger = ko.observable(Enums.SaveSettingsStep.Idle); } - kn.addSettingsViewModel(AdminSettingsBranding, 'AdminSettingsBranding', 'Branding', 'branding'); - AdminSettingsBranding.prototype.onBuild = function () { var self = this; diff --git a/dev/Admin/AdminSettingsContacts.js b/dev/Admin/AdminSettingsContacts.js index e7fe3db41..ad75f4434 100644 --- a/dev/Admin/AdminSettingsContacts.js +++ b/dev/Admin/AdminSettingsContacts.js @@ -7,8 +7,11 @@ var _ = require('../External/underscore.js'), ko = require('../External/ko.js'), + Enums = require('../Common/Enums.js'), Utils = require('../Common/Utils.js'), + + AppSettings = require('../Storages/AppSettings.js'), Remote = require('../Storages/AdminAjaxRemoteStorage.js') ; @@ -18,9 +21,9 @@ function AdminSettingsContacts() { this.defautOptionsAfterRender = Utils.defautOptionsAfterRender; - this.enableContacts = ko.observable(!!RL.settingsGet('ContactsEnable')); - this.contactsSharing = ko.observable(!!RL.settingsGet('ContactsSharing')); - this.contactsSync = ko.observable(!!RL.settingsGet('ContactsSync')); + this.enableContacts = ko.observable(!!AppSettings.settingsGet('ContactsEnable')); + this.contactsSharing = ko.observable(!!AppSettings.settingsGet('ContactsSharing')); + this.contactsSync = ko.observable(!!AppSettings.settingsGet('ContactsSync')); var aTypes = ['sqlite', 'mysql', 'pgsql'], @@ -43,15 +46,15 @@ } ; - if (!!RL.settingsGet('SQLiteIsSupported')) + if (!!AppSettings.settingsGet('SQLiteIsSupported')) { aSupportedTypes.push('sqlite'); } - if (!!RL.settingsGet('MySqlIsSupported')) + if (!!AppSettings.settingsGet('MySqlIsSupported')) { aSupportedTypes.push('mysql'); } - if (!!RL.settingsGet('PostgreSqlIsSupported')) + if (!!AppSettings.settingsGet('PostgreSqlIsSupported')) { aSupportedTypes.push('pgsql'); } @@ -99,9 +102,9 @@ this.testContactsErrorMessage(''); }, this); - this.pdoDsn = ko.observable(RL.settingsGet('ContactsPdoDsn')); - this.pdoUser = ko.observable(RL.settingsGet('ContactsPdoUser')); - this.pdoPassword = ko.observable(RL.settingsGet('ContactsPdoPassword')); + this.pdoDsn = ko.observable(AppSettings.settingsGet('ContactsPdoDsn')); + this.pdoUser = ko.observable(AppSettings.settingsGet('ContactsPdoUser')); + this.pdoPassword = ko.observable(AppSettings.settingsGet('ContactsPdoPassword')); this.pdoDsnTrigger = ko.observable(Enums.SaveSettingsStep.Idle); this.pdoUserTrigger = ko.observable(Enums.SaveSettingsStep.Idle); @@ -131,13 +134,11 @@ return '' !== this.pdoDsn() && '' !== this.pdoUser(); }); - this.contactsType(RL.settingsGet('ContactsPdoType')); + this.contactsType(AppSettings.settingsGet('ContactsPdoType')); this.onTestContactsResponse = _.bind(this.onTestContactsResponse, this); } - kn.addSettingsViewModel(AdminSettingsContacts, 'AdminSettingsContacts', 'Contacts', 'contacts'); - AdminSettingsContacts.prototype.onTestContactsResponse = function (sResult, oData) { this.testContactsSuccess(false); @@ -225,7 +226,7 @@ }); }); - self.contactsType(RL.settingsGet('ContactsPdoType')); + self.contactsType(AppSettings.settingsGet('ContactsPdoType')); }, 50); }; diff --git a/dev/Admin/AdminSettingsDomains.js b/dev/Admin/AdminSettingsDomains.js index c087b78fe..454f3f4f8 100644 --- a/dev/Admin/AdminSettingsDomains.js +++ b/dev/Admin/AdminSettingsDomains.js @@ -11,6 +11,8 @@ Enums = require('../Common/Enums.js'), + RL = require('../Boots/AdminApp.js'), + Data = require('../Storages/AdminDataStorage.js'), Remote = require('../Storages/AdminAjaxRemoteStorage.js') ; @@ -45,8 +47,6 @@ ]}); } - kn.addSettingsViewModel(AdminSettingsDomains, 'AdminSettingsDomains', 'Domains', 'domains'); - AdminSettingsDomains.prototype.startDomainForDeletionTimeout = function () { var self = this; diff --git a/dev/Admin/AdminSettingsGeneral.js b/dev/Admin/AdminSettingsGeneral.js index c8f4d08c7..a310674b0 100644 --- a/dev/Admin/AdminSettingsGeneral.js +++ b/dev/Admin/AdminSettingsGeneral.js @@ -14,6 +14,7 @@ kn = require('../Knoin/Knoin.js'), + AppSettings = require('../Storages/AppSettings.js'), Data = require('../Storages/AdminDataStorage.js'), Remote = require('../Storages/AdminAjaxRemoteStorage.js'), @@ -37,8 +38,8 @@ this.capaAdditionalAccounts = Data.capaAdditionalAccounts; this.capaAdditionalIdentities = Data.capaAdditionalIdentities; - this.mainAttachmentLimit = ko.observable(Utils.pInt(RL.settingsGet('AttachmentLimit')) / (1024 * 1024)).extend({'posInterer': 25}); - this.uploadData = RL.settingsGet('PhpUploadSizes'); + this.mainAttachmentLimit = ko.observable(Utils.pInt(AppSettings.settingsGet('AttachmentLimit')) / (1024 * 1024)).extend({'posInterer': 25}); + this.uploadData = AppSettings.settingsGet('PhpUploadSizes'); this.uploadDataDesc = this.uploadData && (this.uploadData['upload_max_filesize'] || this.uploadData['post_max_size']) ? [ this.uploadData['upload_max_filesize'] ? 'upload_max_filesize = ' + this.uploadData['upload_max_filesize'] + '; ' : '', @@ -59,15 +60,13 @@ return Utils.convertLangName(this.mainLanguage()); }, this); - this.weakPassword = !!RL.settingsGet('WeakPassword'); + this.weakPassword = !!AppSettings.settingsGet('WeakPassword'); this.attachmentLimitTrigger = ko.observable(Enums.SaveSettingsStep.Idle); this.languageTrigger = ko.observable(Enums.SaveSettingsStep.Idle); this.themeTrigger = ko.observable(Enums.SaveSettingsStep.Idle); } - kn.addSettingsViewModel(AdminSettingsGeneral, 'AdminSettingsGeneral', 'General', 'general', true); - AdminSettingsGeneral.prototype.onBuild = function () { var self = this; diff --git a/dev/Admin/AdminSettingsLicensing.js b/dev/Admin/AdminSettingsLicensing.js index 8d6e5ba6b..7fb256cc7 100644 --- a/dev/Admin/AdminSettingsLicensing.js +++ b/dev/Admin/AdminSettingsLicensing.js @@ -8,7 +8,10 @@ ko = require('../External/ko.js'), moment = require('../External/moment.js'), + AppSettings = require('../Storages/AppSettings.js'), Data = require('../Storages/AdminDataStorage.js'), + + RL = require('../Boots/AdminApp.js'), kn = require('../Knoin/Knoin.js'), PopupsActivateViewModel = require('../ViewModels/Popups/PopupsActivateViewModel.js') @@ -27,7 +30,7 @@ this.licenseTrigger = Data.licenseTrigger; this.adminDomain = ko.observable(''); - this.subscriptionEnabled = ko.observable(!!RL.settingsGet('SubscriptionEnabled')); + this.subscriptionEnabled = ko.observable(!!AppSettings.settingsGet('SubscriptionEnabled')); this.licenseTrigger.subscribe(function () { if (this.subscriptionEnabled()) @@ -37,8 +40,6 @@ }, this); } - kn.addSettingsViewModel(AdminSettingsLicensing, 'AdminSettingsLicensing', 'Licensing', 'licensing'); - AdminSettingsLicensing.prototype.onBuild = function () { if (this.subscriptionEnabled()) @@ -49,7 +50,7 @@ AdminSettingsLicensing.prototype.onShow = function () { - this.adminDomain(RL.settingsGet('AdminDomain')); + this.adminDomain(AppSettings.settingsGet('AdminDomain')); }; AdminSettingsLicensing.prototype.showActivationForm = function () diff --git a/dev/Admin/AdminSettingsLogin.js b/dev/Admin/AdminSettingsLogin.js index 9c5791f49..692844a42 100644 --- a/dev/Admin/AdminSettingsLogin.js +++ b/dev/Admin/AdminSettingsLogin.js @@ -10,6 +10,7 @@ Enums = require('../Common/Enums.js'), Utils = require('../Common/Utils.js'), + AppSettings = require('../Storages/AppSettings.js'), Data = require('../Storages/AdminDataStorage.js'), Remote = require('../Storages/AdminAjaxRemoteStorage.js') ; @@ -22,14 +23,12 @@ this.determineUserLanguage = Data.determineUserLanguage; this.determineUserDomain = Data.determineUserDomain; - this.defaultDomain = ko.observable(RL.settingsGet('LoginDefaultDomain')); + this.defaultDomain = ko.observable(AppSettings.settingsGet('LoginDefaultDomain')); this.allowLanguagesOnLogin = Data.allowLanguagesOnLogin; this.defaultDomainTrigger = ko.observable(Enums.SaveSettingsStep.Idle); } - kn.addSettingsViewModel(AdminSettingsLogin, 'AdminSettingsLogin', 'Login', 'login'); - AdminSettingsLogin.prototype.onBuild = function () { var self = this; diff --git a/dev/Admin/AdminSettingsPackages.js b/dev/Admin/AdminSettingsPackages.js index 2460d618d..f7129cb62 100644 --- a/dev/Admin/AdminSettingsPackages.js +++ b/dev/Admin/AdminSettingsPackages.js @@ -11,6 +11,8 @@ Enums = require('../Common/Enums.js'), Utils = require('../Common/Utils.js'), + RL = require('../Boots/AdminApp.js'), + Data = require('../Storages/AdminDataStorage.js'), Remote = require('../Storages/AdminAjaxRemoteStorage.js') ; @@ -44,8 +46,6 @@ }, this); } - kn.addSettingsViewModel(AdminSettingsPackages, 'AdminSettingsPackages', 'Packages', 'packages'); - AdminSettingsPackages.prototype.onShow = function () { this.packagesError(''); diff --git a/dev/Admin/AdminSettingsPlugins.js b/dev/Admin/AdminSettingsPlugins.js index a6ce8c39f..62fcca9ab 100644 --- a/dev/Admin/AdminSettingsPlugins.js +++ b/dev/Admin/AdminSettingsPlugins.js @@ -11,9 +11,12 @@ Enums = require('../Common/Enums.js'), Utils = require('../Common/Utils.js'), + AppSettings = require('../Storages/AppSettings.js'), Data = require('../Storages/AdminDataStorage.js'), Remote = require('../Storages/AdminAjaxRemoteStorage.js'), + RL = require('../Boots/AdminApp.js'), + PopupsPluginViewModel = require('../ViewModels/Popups/PopupsPluginViewModel.js') ; @@ -22,7 +25,7 @@ */ function AdminSettingsPlugins() { - this.enabledPlugins = ko.observable(!!RL.settingsGet('EnabledPlugins')); + this.enabledPlugins = ko.observable(!!AppSettings.settingsGet('EnabledPlugins')); this.pluginsError = ko.observable(''); @@ -37,8 +40,6 @@ this.onPluginDisableRequest = _.bind(this.onPluginDisableRequest, this); } - kn.addSettingsViewModel(AdminSettingsPlugins, 'AdminSettingsPlugins', 'Plugins', 'plugins'); - AdminSettingsPlugins.prototype.disablePlugin = function (oPlugin) { oPlugin.disabled(!oPlugin.disabled()); diff --git a/dev/Admin/AdminSettingsSecurity.js b/dev/Admin/AdminSettingsSecurity.js index 5ddc27106..28dcf956c 100644 --- a/dev/Admin/AdminSettingsSecurity.js +++ b/dev/Admin/AdminSettingsSecurity.js @@ -12,6 +12,7 @@ Utils = require('../Common/Utils.js'), LinkBuilder = require('../Common/LinkBuilder.js'), + AppSettings = require('../Storages/AppSettings.js'), Data = require('../Storages/AdminDataStorage.js'), Remote = require('../Storages/AdminAjaxRemoteStorage.js') ; @@ -23,10 +24,10 @@ { this.useLocalProxyForExternalImages = Data.useLocalProxyForExternalImages; - this.capaOpenPGP = ko.observable(RL.capa(Enums.Capa.OpenPGP)); - this.capaTwoFactorAuth = ko.observable(RL.capa(Enums.Capa.TwoFactor)); + this.capaOpenPGP = ko.observable(AppSettings.capa(Enums.Capa.OpenPGP)); + this.capaTwoFactorAuth = ko.observable(AppSettings.capa(Enums.Capa.TwoFactor)); - this.adminLogin = ko.observable(RL.settingsGet('AdminLogin')); + this.adminLogin = ko.observable(AppSettings.settingsGet('AdminLogin')); this.adminPassword = ko.observable(''); this.adminPasswordNew = ko.observable(''); this.adminPasswordNew2 = ko.observable(''); @@ -75,8 +76,6 @@ this.onNewAdminPasswordResponse = _.bind(this.onNewAdminPasswordResponse, this); } - kn.addSettingsViewModel(AdminSettingsSecurity, 'AdminSettingsSecurity', 'Security', 'security'); - AdminSettingsSecurity.prototype.onNewAdminPasswordResponse = function (sResult, oData) { if (Enums.StorageResultType.Success === sResult && oData && oData.Result) diff --git a/dev/Admin/AdminSettingsSocial.js b/dev/Admin/AdminSettingsSocial.js index 764519bbf..548b81c9d 100644 --- a/dev/Admin/AdminSettingsSocial.js +++ b/dev/Admin/AdminSettingsSocial.js @@ -46,8 +46,6 @@ this.dropboxTrigger1 = ko.observable(Enums.SaveSettingsStep.Idle); } - kn.addSettingsViewModel(AdminSettingsSocial, 'AdminSettingsSocial', 'Social', 'social'); - AdminSettingsSocial.prototype.onBuild = function () { var self = this; diff --git a/dev/AdminBoot.js b/dev/AdminBoot.js deleted file mode 100644 index 3ead2b25f..000000000 --- a/dev/AdminBoot.js +++ /dev/null @@ -1,11 +0,0 @@ -/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */ - -'use strict'; - -var - kn = require('./Knoin/Knoin.js'), - RL = require('./Boots/AdminApp.js'), - Remote = require('./Storages/AdminAjaxRemoteStorage.js') -; - -kn.bootstart(RL, Remote); \ No newline at end of file diff --git a/dev/Boots/AbstractApp.js b/dev/Boots/AbstractApp.js index 9824d1f36..4bf32ce70 100644 --- a/dev/Boots/AbstractApp.js +++ b/dev/Boots/AbstractApp.js @@ -7,46 +7,33 @@ var $ = require('../External/jquery.js'), _ = require('../External/underscore.js'), - ko = require('../External/ko.js'), window = require('../External/window.js'), $html = require('../External/$html.js'), $window = require('../External/$window.js'), $doc = require('../External/$doc.js'), - AppData = require('../External/AppData.js'), Globals = require('../Common/Globals.js'), Utils = require('../Common/Utils.js'), - Plugins = require('../Common/Plugins.js'), LinkBuilder = require('../Common/LinkBuilder.js'), + Events = require('../Common/Events.js'), - Remote = require('../Remote.js'), + AppSettings = require('../Storages/AppSettings.js'), kn = require('../Knoin/Knoin.js'), KnoinAbstractBoot = require('../Knoin/KnoinAbstractBoot.js') ; /** + * @param {*} Remote * @constructor * @extends KnoinAbstractBoot */ - function AbstractApp() + function AbstractApp(Remote) { KnoinAbstractBoot.call(this); - this.oSettings = null; - this.oPlugins = null; - this.oLocal = null; - this.oLink = null; - this.oSubs = {}; - this.isLocalAutocomplete = true; - this.popupVisibilityNames = ko.observableArray([]); - - this.popupVisibility = ko.computed(function () { - return 0 < this.popupVisibilityNames().length; - }, this); - this.iframe = $('').appendTo('body'); $window.on('error', function (oEvent) { @@ -55,7 +42,7 @@ 'Script error.', 'Uncaught Error: Error calling method on NPObject.' ])) { - Remote().jsError( + Remote.jsError( Utils.emptyFunction, oEvent.originalEvent.message, oEvent.originalEvent.filename, @@ -82,11 +69,20 @@ _.extend(AbstractApp.prototype, KnoinAbstractBoot.prototype); - AbstractApp.prototype.oSettings = null; - AbstractApp.prototype.oPlugins = null; - AbstractApp.prototype.oLocal = null; - AbstractApp.prototype.oLink = null; - AbstractApp.prototype.oSubs = {}; + AbstractApp.prototype.remote = function () + { + return null; + }; + + AbstractApp.prototype.data = function () + { + return null; + }; + + AbstractApp.prototype.setupSettings = function () + { + return true; + }; /** * @param {string} sLink @@ -131,38 +127,10 @@ return true; }; - /** - * @param {string} sName - * @return {?} - */ - AbstractApp.prototype.settingsGet = function (sName) - { - if (null === this.oSettings) - { - this.oSettings = Utils.isNormal(AppData) ? AppData : {}; - } - - return Utils.isUnd(this.oSettings[sName]) ? null : this.oSettings[sName]; - }; - - /** - * @param {string} sName - * @param {?} mValue - */ - AbstractApp.prototype.settingsSet = function (sName, mValue) - { - if (null === this.oSettings) - { - this.oSettings = Utils.isNormal(AppData) ? AppData : {}; - } - - this.oSettings[sName] = mValue; - }; - AbstractApp.prototype.setTitle = function (sTitle) { sTitle = ((Utils.isNormal(sTitle) && 0 < sTitle.length) ? sTitle + ' - ' : '') + - this.settingsGet('Title') || ''; + AppSettings.settingsGet('Title') || ''; window.document.title = '_'; window.document.title = sTitle; @@ -175,8 +143,8 @@ AbstractApp.prototype.loginAndLogoutReload = function (bLogout, bClose) { var - sCustomLogoutLink = Utils.pString(this.settingsGet('CustomLogoutLink')), - bInIframe = !!this.settingsGet('InIframe') + sCustomLogoutLink = Utils.pString(AppSettings.settingsGet('CustomLogoutLink')), + bInIframe = !!AppSettings.settingsGet('InIframe') ; bLogout = Utils.isUnd(bLogout) ? false : !!bLogout; @@ -233,61 +201,11 @@ fCallback([], sQuery); }; - /** - * @param {string} sName - * @param {Function} fFunc - * @param {Object=} oContext - * @return {AbstractApp} - */ - AbstractApp.prototype.sub = function (sName, fFunc, oContext) - { - if (Utils.isUnd(this.oSubs[sName])) - { - this.oSubs[sName] = []; - } - - this.oSubs[sName].push([fFunc, oContext]); - - return this; - }; - - /** - * @param {string} sName - * @param {Array=} aArgs - * @return {AbstractApp} - */ - AbstractApp.prototype.pub = function (sName, aArgs) - { - Plugins.runHook('rl-pub', [sName, aArgs]); - if (!Utils.isUnd(this.oSubs[sName])) - { - _.each(this.oSubs[sName], function (aItem) { - if (aItem[0]) - { - aItem[0].apply(aItem[1] || null, aArgs || []); - } - }); - } - - return this; - }; - - /** - * @param {string} sName - * @return {boolean} - */ - AbstractApp.prototype.capa = function (sName) - { - var mCapa = this.settingsGet('Capa'); - return Utils.isArray(mCapa) && Utils.isNormal(sName) && -1 < Utils.inArray(sName, mCapa); - }; - AbstractApp.prototype.bootstart = function () { - var - self = this, - ssm = require('../External/ssm.js') - ; + Events.pub('rl.bootstart'); + + var ssm = require('../External/ssm.js'); Utils.initOnStartOrLangChange(function () { Utils.initNotificationLanguage(); @@ -302,11 +220,11 @@ 'maxWidth': 767, 'onEnter': function() { $html.addClass('ssm-state-mobile'); - self.pub('ssm.mobile-enter'); + Events.pub('ssm.mobile-enter'); }, 'onLeave': function() { $html.removeClass('ssm-state-mobile'); - self.pub('ssm.mobile-leave'); + Events.pub('ssm.mobile-leave'); } }); @@ -345,15 +263,15 @@ } }); - this.sub('ssm.mobile-enter', function () { - RL.data().leftPanelDisabled(true); // TODO cjs + Events.sub('ssm.mobile-enter', function () { + Globals.leftPanelDisabled(true); }); - this.sub('ssm.mobile-leave', function () { - RL.data().leftPanelDisabled(false); // TODO cjs + Events.sub('ssm.mobile-leave', function () { + Globals.leftPanelDisabled(false); }); - RL.data().leftPanelDisabled.subscribe(function (bValue) { // TODO cjs + Globals.leftPanelDisabled.subscribe(function (bValue) { $html.toggleClass('rl-left-panel-disabled', bValue); }); diff --git a/dev/Boots/AdminApp.js b/dev/Boots/AdminApp.js index 862066d74..f047d6a75 100644 --- a/dev/Boots/AdminApp.js +++ b/dev/Boots/AdminApp.js @@ -15,8 +15,12 @@ kn = require('../Knoin/Knoin.js'), + AppSettings = require('../Storages/AppSettings.js'), Data = require('../Storages/AdminDataStorage.js'), Remote = require('../Storages/AdminAjaxRemoteStorage.js'), + + AdminSettingsScreen = require('../Screens/AdminSettingsScreen.js'), + AdminLoginScreen = require('../Screens/AdminLoginScreen.js'), AbstractApp = require('./AbstractApp.js') ; @@ -27,49 +31,80 @@ */ function AdminApp() { - AbstractApp.call(this); - - this.oData = null; - this.oRemote = null; - this.oCache = null; + AbstractApp.call(this, Remote); } _.extend(AdminApp.prototype, AbstractApp.prototype); - AdminApp.prototype.oData = null; - AdminApp.prototype.oRemote = null; - AdminApp.prototype.oCache = null; - - /** - * @return {AdminDataStorage} - */ - AdminApp.prototype.data = function () - { - if (null === this.oData) - { - this.oData = new AdminDataStorage(); // TODO cjs - } - - return this.oData; - }; - - /** - * @return {AdminAjaxRemoteStorage} - */ AdminApp.prototype.remote = function () { - if (null === this.oRemote) + return Remote; + }; + + AdminApp.prototype.data = function () + { + return Data; + }; + + AdminApp.prototype.setupSettings = function () + { + var + AdminSettingsGeneral = require('../Admin/AdminSettingsGeneral.js'), + AdminSettingsLogin = require('../Admin/AdminSettingsLogin.js'), + AdminSettingsBranding = require('../Admin/AdminSettingsBranding.js'), + AdminSettingsContacts = require('../Admin/AdminSettingsContacts.js'), + AdminSettingsDomains = require('../Admin/AdminSettingsDomains.js'), + AdminSettingsSecurity = require('../Admin/AdminSettingsSecurity.js'), + AdminSettingsSocial = require('../Admin/AdminSettingsSocial.js'), + AdminSettingsPlugins = require('../Admin/AdminSettingsPlugins.js'), + AdminSettingsPackages = require('../Admin/AdminSettingsPackages.js'), + AdminSettingsLicensing = require('../Admin/AdminSettingsLicensing.js'), + AdminSettingsAbout = require('../Admin/AdminSettingsAbout.js') + ; + + kn.addSettingsViewModel(AdminSettingsGeneral, + 'AdminSettingsGeneral', 'General', 'general', true); + + kn.addSettingsViewModel(AdminSettingsLogin, + 'AdminSettingsLogin', 'Login', 'login'); + + if (AppSettings.capa(Enums.Capa.Prem)) { - this.oRemote = new AdminAjaxRemoteStorage(); // TODO cjs + kn.addSettingsViewModel(AdminSettingsBranding, + 'AdminSettingsBranding', 'Branding', 'branding'); } - return this.oRemote; + kn.addSettingsViewModel(AdminSettingsContacts, + 'AdminSettingsContacts', 'Contacts', 'contacts'); + + kn.addSettingsViewModel(AdminSettingsDomains, + 'AdminSettingsDomains', 'Domains', 'domains'); + + kn.addSettingsViewModel(AdminSettingsSecurity, + 'AdminSettingsSecurity', 'Security', 'security'); + + kn.addSettingsViewModel(AdminSettingsSocial, + 'AdminSettingsSocial', 'Social', 'social'); + + kn.addSettingsViewModel(AdminSettingsPlugins, + 'AdminSettingsPlugins', 'Plugins', 'plugins'); + + kn.addSettingsViewModel(AdminSettingsPackages, + 'AdminSettingsPackages', 'Packages', 'packages'); + + kn.addSettingsViewModel(AdminSettingsLicensing, + 'AdminSettingsLicensing', 'Licensing', 'licensing'); + + kn.addSettingsViewModel(AdminSettingsAbout, + 'AdminSettingsAbout', 'About', 'about'); + + return true; }; AdminApp.prototype.reloadDomainList = function () { - // TODO cjs Data.domainsLoading(true); + Remote.domainList(function (sResult, oData) { Data.domainsLoading(false); if (Enums.StorageResultType.Success === sResult && oData && oData.Result) @@ -89,10 +124,11 @@ AdminApp.prototype.reloadPluginList = function () { - // TODO cjs Data.pluginsLoading(true); Remote.pluginList(function (sResult, oData) { + Data.pluginsLoading(false); + if (Enums.StorageResultType.Success === sResult && oData && oData.Result) { var aList = _.map(oData.Result, function (oItem) { @@ -110,7 +146,6 @@ AdminApp.prototype.reloadPackagesList = function () { - // TODO cjs Data.packagesLoading(true); Data.packagesReal(true); @@ -215,7 +250,6 @@ { bForce = Utils.isUnd(bForce) ? false : !!bForce; - // TODO cjs Data.licensingProcess(true); Data.licenseError(''); @@ -263,7 +297,7 @@ kn.hideLoading(); - if (!RL.settingsGet('AllowAdminPanel')) + if (!AppSettings.settingsGet('AllowAdminPanel')) { kn.routeOff(); kn.setHash(LinkBuilder.root(), true); @@ -275,21 +309,8 @@ } else { - // kn.removeSettingsViewModel(AdminAbout); - - if (!RL.capa(Enums.Capa.Prem)) + if (!!AppSettings.settingsGet('Auth')) { - kn.removeSettingsViewModel(AdminBranding); - } - - if (!!RL.settingsGet('Auth')) - { - // TODO - // if (!RL.settingsGet('AllowPackages') && AdminPackages) - // { - // kn.disableSettingsViewModel(AdminPackages); - // } - kn.startScreens([AdminSettingsScreen]); } else diff --git a/dev/Boots/Boot.js b/dev/Boots/Boot.js new file mode 100644 index 000000000..0c763f81c --- /dev/null +++ b/dev/Boots/Boot.js @@ -0,0 +1,77 @@ +/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */ + +(function (module) { + + 'use strict'; + + var + window = require('../External/window.js'), + $ = require('../External/jquery.js'), + $window = require('../External/$window.js'), + $html = require('../External/$html.js'), + + Globals = require('../Common/Globals.js'), + Plugins = require('../Common/Plugins.js'), + Utils = require('../Common/Utils.js') + ; + + module.exports = function (RL) { + + Globals.__RL = RL; + + RL.setupSettings(); + + Plugins.__boot = RL; + Plugins.__remote = RL.remote(); + Plugins.__data = RL.data(); + + $html.addClass(Globals.bMobileDevice ? 'mobile' : 'no-mobile'); + + $window.keydown(Utils.killCtrlAandS).keyup(Utils.killCtrlAandS); + $window.unload(function () { + Globals.bUnload = true; + }); + + $html.on('click.dropdown.data-api', function () { + Utils.detectDropdownVisibility(); + }); + + // export + window['rl'] = window['rl'] || {}; + window['rl']['addHook'] = Plugins.addHook; + window['rl']['settingsGet'] = Plugins.mainSettingsGet; + window['rl']['remoteRequest'] = Plugins.remoteRequest; + window['rl']['pluginSettingsGet'] = Plugins.settingsGet; + window['rl']['createCommand'] = Utils.createCommand; + + window['rl']['EmailModel'] = require('../Models/EmailModel.js'); + window['rl']['Enums'] = require('../Common/Enums.js'); + + window['__RLBOOT'] = function (fCall) { + + // boot + $(function () { + + if (window['rainloopTEMPLATES'] && window['rainloopTEMPLATES'][0]) + { + $('#rl-templates').html(window['rainloopTEMPLATES'][0]); + + _.delay(function () { + + RL.bootstart(); + $html.removeClass('no-js rl-booted-trigger').addClass('rl-booted'); + + }, 50); + } + else + { + fCall(false); + } + + window['__RLBOOT'] = null; + }); + }; + + }; + +}(module)); \ No newline at end of file diff --git a/dev/Boots/RainLoopApp.js b/dev/Boots/RainLoopApp.js index fbf2323c2..a3dfc5296 100644 --- a/dev/Boots/RainLoopApp.js +++ b/dev/Boots/RainLoopApp.js @@ -16,16 +16,29 @@ Plugins = require('../Common/Plugins.js'), Utils = require('../Common/Utils.js'), LinkBuilder = require('../Common/LinkBuilder.js'), + Events = require('../Common/Events.js'), kn = require('../Knoin/Knoin.js'), + LocalStorage = require('../Storages/LocalStorage.js'), + AppSettings = require('../Storages/AppSettings.js'), Data = require('../Storages/WebMailDataStorage.js'), Cache = require('../Storages/WebMailCacheStorage.js'), Remote = require('../Storages/WebMailAjaxRemoteStorage.js'), + + FolderModel = require('../Models/FolderModel.js'), + MessageModel = require('../Models/MessageModel.js'), + AccountModel = require('../Models/AccountModel.js'), + IdentityModel = require('../Models/IdentityModel.js'), PopupsFolderSystemViewModel = require('../ViewModels/Popups/PopupsAskViewModel.js'), PopupsAskViewModel = require('../ViewModels/Popups/PopupsAskViewModel.js'), - + PopupsComposeViewModel = require('../ViewModels/Popups/PopupsComposeViewModel.js'), + + MailBoxScreen = require('../Screens/MailBoxScreen.js'), + SettingsScreen = require('../Screens/SettingsScreen.js'), + LoginScreen = require('../Screens/LoginScreen.js'), + AbstractApp = require('./AbstractApp.js') ; @@ -35,11 +48,8 @@ */ function RainLoopApp() { - AbstractApp.call(this); + AbstractApp.call(this, Remote); - this.oData = null; - this.oRemote = null; - this.oCache = null; this.oMoveCache = {}; this.quotaDebounce = _.debounce(this.quota, 1000 * 30); @@ -47,33 +57,35 @@ this.messagesMoveTrigger = _.debounce(this.messagesMoveTrigger, 500); + var self = this; + window.setInterval(function () { - RL.pub('interval.30s'); + Events.pub('interval.30s'); }, 30000); window.setInterval(function () { - RL.pub('interval.1m'); + Events.pub('interval.1m'); }, 60000); window.setInterval(function () { - RL.pub('interval.2m'); + Events.pub('interval.2m'); }, 60000 * 2); window.setInterval(function () { - RL.pub('interval.3m'); + Events.pub('interval.3m'); }, 60000 * 3); window.setInterval(function () { - RL.pub('interval.5m'); + Events.pub('interval.5m'); }, 60000 * 5); window.setInterval(function () { - RL.pub('interval.10m'); + Events.pub('interval.10m'); }, 60000 * 10); window.setTimeout(function () { window.setInterval(function () { - RL.pub('interval.10m-after5m'); + Events.pub('interval.10m-after5m'); }, 60000 * 10); }, 60000 * 5); @@ -81,7 +93,7 @@ Remote.jsVersion(function (sResult, oData) { if (Enums.StorageResultType.Success === sResult && oData && !oData.Result) { - if (window.parent && !!RL.settingsGet('InIframe')) + if (window.parent && !!self.settingsGet('InIframe')) { window.parent.location.reload(); } @@ -90,40 +102,110 @@ window.location.reload(); } } - }, RL.settingsGet('Version')); + }, self.settingsGet('Version')); }, {}, 60 * 60 * 1000); + + + this.socialUsers = _.bind(this.socialUsers, this); } _.extend(RainLoopApp.prototype, AbstractApp.prototype); - RainLoopApp.prototype.oData = null; - RainLoopApp.prototype.oRemote = null; - RainLoopApp.prototype.oCache = null; - - /** - * @return {WebMailDataStorage} - */ - RainLoopApp.prototype.data = function () - { - if (null === this.oData) - { - this.oData = new WebMailDataStorage(); - } - - return this.oData; - }; - - /** - * @return {WebMailAjaxRemoteStorage} - */ RainLoopApp.prototype.remote = function () { - if (null === this.oRemote) + return Remote; + }; + + RainLoopApp.prototype.data = function () + { + return Data; + }; + + RainLoopApp.prototype.setupSettings = function () + { + var + SettingsGeneral = require('../Settings/SettingsGeneral.js'), + SettingsContacts = require('../Settings/SettingsContacts.js'), + SettingsAccounts = require('../Settings/SettingsAccounts.js'), + SettingsIdentity = require('../Settings/SettingsIdentity.js'), + SettingsIdentities = require('../Settings/SettingsIdentities.js'), + SettingsFilters = require('../Settings/SettingsFilters.js'), + SettingsSecurity = require('../Settings/SettingsSecurity.js'), + SettingsSocial = require('../Settings/SettingsSocial.js'), + SettingsChangePassword = require('../Settings/SettingsChangePassword.js'), + SettingsFolders = require('../Settings/SettingsFolders.js'), + SettingsThemes = require('../Settings/SettingsThemes.js'), + SettingsOpenPGP = require('../Settings/SettingsOpenPGP.js') + ; + + kn.addSettingsViewModel(SettingsGeneral, + 'SettingsGeneral', 'SETTINGS_LABELS/LABEL_GENERAL_NAME', 'general', true); + + if (AppSettings.settingsGet('ContactsIsAllowed')) { - this.oRemote = new WebMailAjaxRemoteStorage(); + kn.addSettingsViewModel(SettingsContacts, + 'SettingsContacts', 'SETTINGS_LABELS/LABEL_CONTACTS_NAME', 'contacts'); } - return this.oRemote; + if (AppSettings.capa(Enums.Capa.AdditionalAccounts)) + { + kn.addSettingsViewModel(SettingsAccounts, + 'SettingsAccounts', 'SETTINGS_LABELS/LABEL_ACCOUNTS_NAME', 'accounts'); + } + + if (AppSettings.capa(Enums.Capa.AdditionalIdentities)) + { + kn.addSettingsViewModel(SettingsIdentities, + 'SettingsIdentities', 'SETTINGS_LABELS/LABEL_IDENTITIES_NAME', 'identities'); + } + else + { + kn.addSettingsViewModel(SettingsIdentity, + 'SettingsIdentity', 'SETTINGS_LABELS/LABEL_IDENTITY_NAME', 'identity'); + } + + if (AppSettings.capa(Enums.Capa.Filters)) + { + kn.addSettingsViewModel(SettingsFilters, + 'SettingsFilters', 'SETTINGS_LABELS/LABEL_FILTERS_NAME', 'filters'); + } + + if (AppSettings.capa(Enums.Capa.TwoFactor)) + { + kn.addSettingsViewModel(SettingsSecurity, + 'SettingsSecurity', 'SETTINGS_LABELS/LABEL_SECURITY_NAME', 'security'); + } + + if (!AppSettings.settingsGet('AllowGoogleSocial') && + !AppSettings.settingsGet('AllowFacebookSocial') && + !AppSettings.settingsGet('AllowTwitterSocial')) + { + kn.addSettingsViewModel(SettingsSocial, + 'SettingsSocial', 'SETTINGS_LABELS/LABEL_SOCIAL_NAME', 'social'); + } + + if (AppSettings.settingsGet('ChangePasswordIsAllowed')) + { + kn.addSettingsViewModel(SettingsChangePassword, + 'SettingsChangePassword', 'SETTINGS_LABELS/LABEL_CHANGE_PASSWORD_NAME', 'change-password'); + } + + kn.addSettingsViewModel(SettingsFolders, + 'SettingsFolders', 'SETTINGS_LABELS/LABEL_FOLDERS_NAME', 'folders'); + + if (AppSettings.capa(Enums.Capa.Themes)) + { + kn.addSettingsViewModel(SettingsThemes, + 'SettingsThemes', 'SETTINGS_LABELS/LABEL_THEMES_NAME', 'themes'); + } + + if (AppSettings.capa(Enums.Capa.OpenPGP)) + { + kn.addSettingsViewModel(SettingsOpenPGP, + 'SettingsOpenPGP', 'SETTINGS_LABELS/LABEL_OPEN_PGP_NAME', 'openpgp'); + } + + return true; }; RainLoopApp.prototype.reloadFlagsCurrentMessageListAndMessageFromCache = function () @@ -142,6 +224,7 @@ RainLoopApp.prototype.reloadMessageList = function (bDropPagePosition, bDropCurrenFolderCache) { var + self = this, iOffset = (Data.messageListPage() - 1) * Data.messagesPerPage() ; @@ -163,7 +246,7 @@ { Data.messageListError(''); Data.messageListLoading(false); - Data.setMessageList(oData, bCached); + self.setMessageList(oData, bCached); } else if (Enums.StorageResultType.Unload === sResult) { @@ -189,7 +272,7 @@ RainLoopApp.prototype.reloadMessageListHelper = function (bEmptyList) { - RL.reloadMessageList(bEmptyList); + self.reloadMessageList(bEmptyList); }; /** @@ -294,8 +377,8 @@ } } - RL.reloadMessageListHelper(0 === Data.messageList().length); - RL.quotaDebounce(); + this.reloadMessageListHelper(0 === Data.messageList().length); + this.quotaDebounce(); } }; @@ -413,13 +496,13 @@ */ RainLoopApp.prototype.folders = function (fCallback) { - this.data().foldersLoading(true); - this.remote().folders(_.bind(function (sResult, oData) { + Data.foldersLoading(true); + Remote.folders(_.bind(function (sResult, oData) { Data.foldersLoading(false); if (Enums.StorageResultType.Success === sResult) { - this.data().setFolders(oData); + this.setFolders(oData); if (fCallback) { fCallback(true); @@ -491,7 +574,7 @@ if (Enums.StorageResultType.Success === sResult && oData.Result) { var - sParentEmail = RL.settingsGet('ParentEmail'), + sParentEmail = AppSettings.settingsGet('ParentEmail'), sAccountEmail = Data.accountEmail() ; @@ -527,7 +610,7 @@ RainLoopApp.prototype.quota = function () { - this.remote().quota(function (sResult, oData) { + Remote.quota(function (sResult, oData) { if (Enums.StorageResultType.Success === sResult && oData && oData.Result && Utils.isArray(oData.Result) && 1 < oData.Result.length && Utils.isPosNumeric(oData.Result[0], true) && Utils.isPosNumeric(oData.Result[1], true)) @@ -546,7 +629,8 @@ { if ('' !== Utils.trim(sFolder)) { - this.remote().folderInformation(function (sResult, oData) { + var self = this; + Remote.folderInformation(function (sResult, oData) { if (Enums.StorageResultType.Success === sResult) { if (oData && oData.Result && oData.Result.Hash && oData.Result.Folder) @@ -607,7 +691,7 @@ if (bCheck) { - RL.reloadFlagsCurrentMessageListAndMessageFromCache(); + self.reloadFlagsCurrentMessageListAndMessageFromCache(); } } @@ -617,11 +701,11 @@ { if (oFolder.fullNameRaw === Data.currentFolderFullNameRaw()) { - RL.reloadMessageList(); + self.reloadMessageList(); } else if ('INBOX' === oFolder.fullNameRaw) { - RL.recacheInboxMessageList(); + self.recacheInboxMessageList(); } } else if (bUnreadCountChange) @@ -631,7 +715,7 @@ aList = Data.messageList(); if (Utils.isNonEmptyArray(aList)) { - RL.folderInformation(oFolder.fullNameRaw, aList); + self.folderInformation(oFolder.fullNameRaw, aList); } } } @@ -650,13 +734,14 @@ bBoot = Utils.isUnd(bBoot) ? false : !!bBoot; var + self = this, iUtc = moment().unix(), aFolders = Data.getNextFolderNames(bBoot) ; if (Utils.isNonEmptyArray(aFolders)) { - this.remote().folderInformationMultiply(function (sResult, oData) { + Remote.folderInformationMultiply(function (sResult, oData) { if (Enums.StorageResultType.Success === sResult) { if (oData && oData.Result && oData.Result.List && Utils.isNonEmptyArray(oData.Result.List)) @@ -703,7 +788,7 @@ { if (oFolder.fullNameRaw === Data.currentFolderFullNameRaw()) { - RL.reloadMessageList(); + self.reloadMessageList(); } } else if (bUnreadCountChange) @@ -713,7 +798,7 @@ aList = Data.messageList(); if (Utils.isNonEmptyArray(aList)) { - RL.folderInformation(oFolder.fullNameRaw, aList); + self.folderInformation(oFolder.fullNameRaw, aList); } } } @@ -722,7 +807,7 @@ if (bBoot) { - RL.folderInformationMultiply(true); + self.folderInformationMultiply(true); } } } @@ -744,7 +829,7 @@ } Cache.storeMessageFlagsToCache(oMessage); - RL.reloadFlagsCurrentMessageListAndMessageFromCache(); + this.reloadFlagsCurrentMessageListAndMessageFromCache(); } Remote.messageSetSeen(Utils.emptyFunction, oMessage.folderFullNameRaw, [oMessage.uid], true); @@ -805,154 +890,19 @@ RainLoopApp.prototype.googleDisconnect = function () { Data.googleActions(true); - Remote.googleDisconnect(function () { - RL.socialUsers(); - }); + Remote.googleDisconnect(this.socialUsers); }; RainLoopApp.prototype.facebookDisconnect = function () { Data.facebookActions(true); - Remote.facebookDisconnect(function () { - RL.socialUsers(); - }); + Remote.facebookDisconnect(this.socialUsers); }; RainLoopApp.prototype.twitterDisconnect = function () { Data.twitterActions(true); - Remote.twitterDisconnect(function () { - RL.socialUsers(); - }); - }; - - /** - * @param {Array} aSystem - * @param {Array} aList - * @param {Array=} aDisabled - * @param {Array=} aHeaderLines - * @param {?number=} iUnDeep - * @param {Function=} fDisableCallback - * @param {Function=} fVisibleCallback - * @param {Function=} fRenameCallback - * @param {boolean=} bSystem - * @param {boolean=} bBuildUnvisible - * @return {Array} - */ - RainLoopApp.prototype.folderListOptionsBuilder = function (aSystem, aList, aDisabled, aHeaderLines, iUnDeep, fDisableCallback, fVisibleCallback, fRenameCallback, bSystem, bBuildUnvisible) - { - var - iIndex = 0, - iLen = 0, - /** - * @type {?FolderModel} - */ - oItem = null, - bSep = false, - sDeepPrefix = '\u00A0\u00A0\u00A0', - aResult = [] - ; - - bSystem = !Utils.isNormal(bSystem) ? 0 < aSystem.length : bSystem; - bBuildUnvisible = Utils.isUnd(bBuildUnvisible) ? false : !!bBuildUnvisible; - iUnDeep = !Utils.isNormal(iUnDeep) ? 0 : iUnDeep; - fDisableCallback = Utils.isNormal(fDisableCallback) ? fDisableCallback : null; - fVisibleCallback = Utils.isNormal(fVisibleCallback) ? fVisibleCallback : null; - fRenameCallback = Utils.isNormal(fRenameCallback) ? fRenameCallback : null; - - if (!Utils.isArray(aDisabled)) - { - aDisabled = []; - } - - if (!Utils.isArray(aHeaderLines)) - { - aHeaderLines = []; - } - - for (iIndex = 0, iLen = aHeaderLines.length; iIndex < iLen; iIndex++) - { - aResult.push({ - 'id': aHeaderLines[iIndex][0], - 'name': aHeaderLines[iIndex][1], - 'system': false, - 'seporator': false, - 'disabled': false - }); - } - - bSep = true; - for (iIndex = 0, iLen = aSystem.length; iIndex < iLen; iIndex++) - { - oItem = aSystem[iIndex]; - if (fVisibleCallback ? fVisibleCallback.call(null, oItem) : true) - { - if (bSep && 0 < aResult.length) - { - aResult.push({ - 'id': '---', - 'name': '---', - 'system': false, - 'seporator': true, - 'disabled': true - }); - } - - bSep = false; - aResult.push({ - 'id': oItem.fullNameRaw, - 'name': fRenameCallback ? fRenameCallback.call(null, oItem) : oItem.name(), - 'system': true, - 'seporator': false, - 'disabled': !oItem.selectable || -1 < Utils.inArray(oItem.fullNameRaw, aDisabled) || - (fDisableCallback ? fDisableCallback.call(null, oItem) : false) - }); - } - } - - bSep = true; - for (iIndex = 0, iLen = aList.length; iIndex < iLen; iIndex++) - { - oItem = aList[iIndex]; - if (oItem.subScribed() || !oItem.existen) - { - if (fVisibleCallback ? fVisibleCallback.call(null, oItem) : true) - { - if (Enums.FolderType.User === oItem.type() || !bSystem || 0 < oItem.subFolders().length) - { - if (bSep && 0 < aResult.length) - { - aResult.push({ - 'id': '---', - 'name': '---', - 'system': false, - 'seporator': true, - 'disabled': true - }); - } - - bSep = false; - aResult.push({ - 'id': oItem.fullNameRaw, - 'name': (new window.Array(oItem.deep + 1 - iUnDeep)).join(sDeepPrefix) + - (fRenameCallback ? fRenameCallback.call(null, oItem) : oItem.name()), - 'system': false, - 'seporator': false, - 'disabled': !oItem.selectable || -1 < Utils.inArray(oItem.fullNameRaw, aDisabled) || - (fDisableCallback ? fDisableCallback.call(null, oItem) : false) - }); - } - } - } - - if (oItem.subScribed() && 0 < oItem.subFolders().length) - { - aResult = aResult.concat(RL.folderListOptionsBuilder([], oItem.subFolders(), aDisabled, [], - iUnDeep, fDisableCallback, fVisibleCallback, fRenameCallback, bSystem, bBuildUnvisible)); - } - } - - return aResult; + Remote.twitterDisconnect(this.socialUsers); }; /** @@ -993,6 +943,382 @@ })); }; + RainLoopApp.prototype.setMessageList = function (oData, bCached) + { + if (oData && oData.Result && 'Collection/MessageCollection' === oData.Result['@Object'] && + oData.Result['@Collection'] && Utils.isArray(oData.Result['@Collection'])) + { + var + mLastCollapsedThreadUids = null, + iIndex = 0, + iLen = 0, + iCount = 0, + iOffset = 0, + aList = [], + iUtc = moment().unix(), + aStaticList = Data.staticMessageList, + oJsonMessage = null, + oMessage = null, + oFolder = null, + iNewCount = 0, + bUnreadCountChange = false + ; + + iCount = Utils.pInt(oData.Result.MessageResultCount); + iOffset = Utils.pInt(oData.Result.Offset); + + if (Utils.isNonEmptyArray(oData.Result.LastCollapsedThreadUids)) + { + mLastCollapsedThreadUids = oData.Result.LastCollapsedThreadUids; + } + + oFolder = Cache.getFolderFromCacheList( + Utils.isNormal(oData.Result.Folder) ? oData.Result.Folder : ''); + + if (oFolder && !bCached) + { + oFolder.interval = iUtc; + + Cache.setFolderHash(oData.Result.Folder, oData.Result.FolderHash); + + if (Utils.isNormal(oData.Result.MessageCount)) + { + oFolder.messageCountAll(oData.Result.MessageCount); + } + + if (Utils.isNormal(oData.Result.MessageUnseenCount)) + { + if (Utils.pInt(oFolder.messageCountUnread()) !== Utils.pInt(oData.Result.MessageUnseenCount)) + { + bUnreadCountChange = true; + } + + oFolder.messageCountUnread(oData.Result.MessageUnseenCount); + } + + Data.initUidNextAndNewMessages(oFolder.fullNameRaw, oData.Result.UidNext, oData.Result.NewMessages); + } + + if (bUnreadCountChange && oFolder) + { + Cache.clearMessageFlagsFromCacheByFolder(oFolder.fullNameRaw); + } + + for (iIndex = 0, iLen = oData.Result['@Collection'].length; iIndex < iLen; iIndex++) + { + oJsonMessage = oData.Result['@Collection'][iIndex]; + if (oJsonMessage && 'Object/Message' === oJsonMessage['@Object']) + { + oMessage = aStaticList[iIndex]; + if (!oMessage || !oMessage.initByJson(oJsonMessage)) + { + oMessage = MessageModel.newInstanceFromJson(oJsonMessage); + } + + if (oMessage) + { + if (Cache.hasNewMessageAndRemoveFromCache(oMessage.folderFullNameRaw, oMessage.uid) && 5 >= iNewCount) + { + iNewCount++; + oMessage.newForAnimation(true); + } + + oMessage.deleted(false); + + if (bCached) + { + Cache.initMessageFlagsFromCache(oMessage); + } + else + { + Cache.storeMessageFlagsToCache(oMessage); + } + + oMessage.lastInCollapsedThread(mLastCollapsedThreadUids && -1 < Utils.inArray(Utils.pInt(oMessage.uid), mLastCollapsedThreadUids) ? true : false); + + aList.push(oMessage); + } + } + } + + Data.messageListCount(iCount); + Data.messageListSearch(Utils.isNormal(oData.Result.Search) ? oData.Result.Search : ''); + Data.messageListPage(window.Math.ceil((iOffset / Data.messagesPerPage()) + 1)); + Data.messageListEndFolder(Utils.isNormal(oData.Result.Folder) ? oData.Result.Folder : ''); + Data.messageListEndSearch(Utils.isNormal(oData.Result.Search) ? oData.Result.Search : ''); + Data.messageListEndPage(Data.messageListPage()); + + Data.messageList(aList); + Data.messageListIsNotCompleted(false); + + if (aStaticList.length < aList.length) + { + Data.staticMessageList = aList; + } + + Cache.clearNewMessageCache(); + + if (oFolder && (bCached || bUnreadCountChange || Data.useThreads())) + { + this.folderInformation(oFolder.fullNameRaw, aList); + } + } + else + { + Data.messageListCount(0); + Data.messageList([]); + Data.messageListError(Utils.getNotification( + oData && oData.ErrorCode ? oData.ErrorCode : Enums.Notification.CantGetMessageList + )); + } + }; + + /** + * @param {string} sNamespace + * @param {Array} aFolders + * @return {Array} + */ + RainLoopApp.prototype.folderResponseParseRec = function (sNamespace, aFolders) + { + var + iIndex = 0, + iLen = 0, + oFolder = null, + oCacheFolder = null, + sFolderFullNameRaw = '', + aSubFolders = [], + aList = [] + ; + + for (iIndex = 0, iLen = aFolders.length; iIndex < iLen; iIndex++) + { + oFolder = aFolders[iIndex]; + if (oFolder) + { + sFolderFullNameRaw = oFolder.FullNameRaw; + + oCacheFolder = Cache.getFolderFromCacheList(sFolderFullNameRaw); + if (!oCacheFolder) + { + oCacheFolder = FolderModel.newInstanceFromJson(oFolder); + if (oCacheFolder) + { + Cache.setFolderToCacheList(sFolderFullNameRaw, oCacheFolder); + Cache.setFolderFullNameRaw(oCacheFolder.fullNameHash, sFolderFullNameRaw); + } + } + + if (oCacheFolder) + { + if (Globals.__RL) + { + oCacheFolder.collapsed(!Globals.__RL.isFolderExpanded(oCacheFolder.fullNameHash)); + } + + if (oFolder.Extended) + { + if (oFolder.Extended.Hash) + { + Cache.setFolderHash(oCacheFolder.fullNameRaw, oFolder.Extended.Hash); + } + + if (Utils.isNormal(oFolder.Extended.MessageCount)) + { + oCacheFolder.messageCountAll(oFolder.Extended.MessageCount); + } + + if (Utils.isNormal(oFolder.Extended.MessageUnseenCount)) + { + oCacheFolder.messageCountUnread(oFolder.Extended.MessageUnseenCount); + } + } + + aSubFolders = oFolder['SubFolders']; + if (aSubFolders && 'Collection/FolderCollection' === aSubFolders['@Object'] && + aSubFolders['@Collection'] && Utils.isArray(aSubFolders['@Collection'])) + { + oCacheFolder.subFolders( + this.folderResponseParseRec(sNamespace, aSubFolders['@Collection'])); + } + + aList.push(oCacheFolder); + } + } + } + + return aList; + }; + + /** + * @param {*} oData + */ + RainLoopApp.prototype.setFolders = function (oData) + { + var + aList = [], + bUpdate = false, + fNormalizeFolder = function (sFolderFullNameRaw) { + return ('' === sFolderFullNameRaw || Consts.Values.UnuseOptionValue === sFolderFullNameRaw || + null !== Cache.getFolderFromCacheList(sFolderFullNameRaw)) ? sFolderFullNameRaw : ''; + } + ; + + if (oData && oData.Result && 'Collection/FolderCollection' === oData.Result['@Object'] && + oData.Result['@Collection'] && Utils.isArray(oData.Result['@Collection'])) + { + if (!Utils.isUnd(oData.Result.Namespace)) + { + Data.namespace = oData.Result.Namespace; + } + + Data.threading(!!AppSettings.settingsGet('UseImapThread') && oData.Result.IsThreadsSupported && true); + + aList = this.folderResponseParseRec(Data.namespace, oData.Result['@Collection']); + Data.folderList(aList); + + if (oData.Result['SystemFolders'] && + '' === '' + AppSettings.settingsGet('SentFolder') + AppSettings.settingsGet('DraftFolder') + + AppSettings.settingsGet('SpamFolder') + AppSettings.settingsGet('TrashFolder') + AppSettings.settingsGet('ArchiveFolder') + + AppSettings.settingsGet('NullFolder')) + { + // TODO Magic Numbers + AppSettings.settingsSet('SentFolder', oData.Result['SystemFolders'][2] || null); + AppSettings.settingsSet('DraftFolder', oData.Result['SystemFolders'][3] || null); + AppSettings.settingsSet('SpamFolder', oData.Result['SystemFolders'][4] || null); + AppSettings.settingsSet('TrashFolder', oData.Result['SystemFolders'][5] || null); + AppSettings.settingsSet('ArchiveFolder', oData.Result['SystemFolders'][12] || null); + + bUpdate = true; + } + + Data.sentFolder(fNormalizeFolder(AppSettings.settingsGet('SentFolder'))); + Data.draftFolder(fNormalizeFolder(AppSettings.settingsGet('DraftFolder'))); + Data.spamFolder(fNormalizeFolder(AppSettings.settingsGet('SpamFolder'))); + Data.trashFolder(fNormalizeFolder(AppSettings.settingsGet('TrashFolder'))); + Data.archiveFolder(fNormalizeFolder(AppSettings.settingsGet('ArchiveFolder'))); + + if (bUpdate) + { + Remote.saveSystemFolders(Utils.emptyFunction, { + 'SentFolder': Data.sentFolder(), + 'DraftFolder': Data.draftFolder(), + 'SpamFolder': Data.spamFolder(), + 'TrashFolder': Data.trashFolder(), + 'ArchiveFolder': Data.archiveFolder(), + 'NullFolder': 'NullFolder' + }); + } + + LocalStorage.set(Enums.ClientSideKeyName.FoldersLashHash, oData.Result.FoldersHash); + } + }; + + /** + * @param {string} sFullNameHash + * @return {boolean} + */ + RainLoopApp.prototype.isFolderExpanded = function (sFullNameHash) + { + var aExpandedList = /** @type {Array|null} */ LocalStorage.get(Enums.ClientSideKeyName.ExpandedFolders); + return _.isArray(aExpandedList) && -1 !== _.indexOf(aExpandedList, sFullNameHash); + }; + + /** + * @param {string} sFullNameHash + * @param {boolean} bExpanded + */ + RainLoopApp.prototype.setExpandedFolder = function (sFullNameHash, bExpanded) + { + var aExpandedList = /** @type {Array|null} */ LocalStorage.get(Enums.ClientSideKeyName.ExpandedFolders); + if (!_.isArray(aExpandedList)) + { + aExpandedList = []; + } + + if (bExpanded) + { + aExpandedList.push(sFullNameHash); + aExpandedList = _.uniq(aExpandedList); + } + else + { + aExpandedList = _.without(aExpandedList, sFullNameHash); + } + + LocalStorage.set(Enums.ClientSideKeyName.ExpandedFolders, aExpandedList); + }; + + RainLoopApp.prototype.initLayoutResizer = function (sLeft, sRight, sClientSideKeyName) + { + var + iDisabledWidth = 60, + iMinWidth = 155, + oLeft = $(sLeft), + oRight = $(sRight), + + mLeftWidth = LocalStorage.get(sClientSideKeyName) || null, + + fSetWidth = function (iWidth) { + if (iWidth) + { + oLeft.css({ + 'width': '' + iWidth + 'px' + }); + + oRight.css({ + 'left': '' + iWidth + 'px' + }); + } + }, + + fDisable = function (bDisable) { + if (bDisable) + { + oLeft.resizable('disable'); + fSetWidth(iDisabledWidth); + } + else + { + oLeft.resizable('enable'); + var iWidth = Utils.pInt(LocalStorage.get(sClientSideKeyName)) || iMinWidth; + fSetWidth(iWidth > iMinWidth ? iWidth : iMinWidth); + } + }, + + fResizeFunction = function (oEvent, oObject) { + if (oObject && oObject.size && oObject.size.width) + { + LocalStorage.set(sClientSideKeyName, oObject.size.width); + + oRight.css({ + 'left': '' + oObject.size.width + 'px' + }); + } + } + ; + + if (null !== mLeftWidth) + { + fSetWidth(mLeftWidth > iMinWidth ? mLeftWidth : iMinWidth); + } + + oLeft.resizable({ + 'helper': 'ui-resizable-helper', + 'minWidth': iMinWidth, + 'maxWidth': 350, + 'handles': 'e', + 'stop': fResizeFunction + }); + + Events.sub('left-panel.off', function () { + fDisable(true); + }); + + Events.sub('left-panel.on', function () { + fDisable(false); + }); + }; + /** * @param {string} sMailToUrl * @returns {boolean} @@ -1030,69 +1356,20 @@ RainLoopApp.prototype.bootstart = function () { - RL.pub('rl.bootstart'); AbstractApp.prototype.bootstart.call(this); Data.populateDataOnStart(); var + self = this, sCustomLoginLink = '', - sJsHash = RL.settingsGet('JsHash'), - iContactsSyncInterval = Utils.pInt(RL.settingsGet('ContactsSyncInterval')), - bGoogle = RL.settingsGet('AllowGoogleSocial'), - bFacebook = RL.settingsGet('AllowFacebookSocial'), - bTwitter = RL.settingsGet('AllowTwitterSocial') + sJsHash = AppSettings.settingsGet('JsHash'), + iContactsSyncInterval = Utils.pInt(AppSettings.settingsGet('ContactsSyncInterval')), + bGoogle = AppSettings.settingsGet('AllowGoogleSocial'), + bFacebook = AppSettings.settingsGet('AllowFacebookSocial'), + bTwitter = AppSettings.settingsGet('AllowTwitterSocial') ; - if (!RL.settingsGet('ChangePasswordIsAllowed')) - { - kn.removeSettingsViewModel(SettingsChangePasswordScreen); - } - - if (!RL.settingsGet('ContactsIsAllowed')) - { - kn.removeSettingsViewModel(SettingsContacts); - } - - if (!RL.capa(Enums.Capa.AdditionalAccounts)) - { - kn.removeSettingsViewModel(SettingsAccounts); - } - - if (RL.capa(Enums.Capa.AdditionalIdentities)) - { - kn.removeSettingsViewModel(SettingsIdentity); - } - else - { - kn.removeSettingsViewModel(SettingsIdentities); - } - - if (!RL.capa(Enums.Capa.OpenPGP)) - { - kn.removeSettingsViewModel(SettingsOpenPGP); - } - - if (!RL.capa(Enums.Capa.TwoFactor)) - { - kn.removeSettingsViewModel(SettingsSecurity); - } - - if (!RL.capa(Enums.Capa.Themes)) - { - kn.removeSettingsViewModel(SettingsThemes); - } - - if (!RL.capa(Enums.Capa.Filters)) - { - kn.removeSettingsViewModel(SettingsFilters); - } - - if (!bGoogle && !bFacebook && !bTwitter) - { - kn.removeSettingsViewModel(SettingsSocialScreen); - } - Utils.initOnStartOrLangChange(function () { $.extend(true, $.magnificPopup.defaults, { @@ -1119,7 +1396,11 @@ window.SimplePace.sleep(); } - if (!!RL.settingsGet('Auth')) + Globals.leftPanelDisabled.subscribe(function (bValue) { + Events.pub('left-panel.' + (bValue ? 'off' : 'on')); + }); + + if (!!AppSettings.settingsGet('Auth')) { this.setTitle(Utils.i18n('TITLES/LOADING')); @@ -1129,7 +1410,7 @@ if (bValue) { - if (window.$LAB && window.crypto && window.crypto.getRandomValues && RL.capa(Enums.Capa.OpenPGP)) + if (window.$LAB && window.crypto && window.crypto.getRandomValues && AppSettings.capa(Enums.Capa.OpenPGP)) { window.$LAB.script(window.openpgp ? '' : LinkBuilder.openPgpJs()).wait(function () { if (window.openpgp) @@ -1137,9 +1418,9 @@ Data.openpgpKeyring = new window.openpgp.Keyring(); Data.capaOpenPGP(true); - RL.pub('openpgp.init'); + Events.pub('openpgp.init'); - RL.reloadOpenPgpKeys(); + self.reloadOpenPgpKeys(); } }); } @@ -1152,63 +1433,63 @@ if (bGoogle || bFacebook || bTwitter) { - RL.socialUsers(true); + self.socialUsers(true); } - RL.sub('interval.2m', function () { - RL.folderInformation('INBOX'); + Events.sub('interval.2m', function () { + self.folderInformation('INBOX'); }); - RL.sub('interval.2m', function () { + Events.sub('interval.2m', function () { var sF = Data.currentFolderFullNameRaw(); if ('INBOX' !== sF) { - RL.folderInformation(sF); + self.folderInformation(sF); } }); - RL.sub('interval.3m', function () { - RL.folderInformationMultiply(); + Events.sub('interval.3m', function () { + self.folderInformationMultiply(); }); - RL.sub('interval.5m', function () { - RL.quota(); + Events.sub('interval.5m', function () { + self.quota(); }); - RL.sub('interval.10m', function () { - RL.folders(); + Events.sub('interval.10m', function () { + self.folders(); }); iContactsSyncInterval = 5 <= iContactsSyncInterval ? iContactsSyncInterval : 20; iContactsSyncInterval = 320 >= iContactsSyncInterval ? iContactsSyncInterval : 320; window.setInterval(function () { - RL.contactsSync(); + self.contactsSync(); }, iContactsSyncInterval * 60000 + 5000); _.delay(function () { - RL.contactsSync(); + self.contactsSync(); }, 5000); _.delay(function () { - RL.folderInformationMultiply(true); + self.folderInformationMultiply(true); }, 500); Plugins.runHook('rl-start-user-screens'); - RL.pub('rl.bootstart-user-screens'); + Events.pub('rl.bootstart-user-screens'); - if (!!RL.settingsGet('AccountSignMe') && window.navigator.registerProtocolHandler) + if (!!AppSettings.settingsGet('AccountSignMe') && window.navigator.registerProtocolHandler) { _.delay(function () { try { window.navigator.registerProtocolHandler('mailto', window.location.protocol + '//' + window.location.host + window.location.pathname + '?mailto&to=%s', - '' + (RL.settingsGet('Title') || 'RainLoop')); + '' + (AppSettings.settingsGet('Title') || 'RainLoop')); } catch(e) {} - if (RL.settingsGet('MailToEmail')) + if (AppSettings.settingsGet('MailToEmail')) { - RL.mailToHelper(RL.settingsGet('MailToEmail')); + self.mailToHelper(AppSettings.settingsGet('MailToEmail')); } }, 500); } @@ -1218,7 +1499,7 @@ kn.startScreens([LoginScreen]); Plugins.runHook('rl-start-login-screens'); - RL.pub('rl.bootstart-login-screens'); + Events.pub('rl.bootstart-login-screens'); } if (window.SimplePace) @@ -1229,7 +1510,7 @@ if (!Globals.bMobileDevice) { _.defer(function () { - Utils.initLayoutResizer('#rl-left', '#rl-right', Enums.ClientSideKeyName.FolderListSize); + self.initLayoutResizer('#rl-left', '#rl-right', Enums.ClientSideKeyName.FolderListSize); }); } @@ -1237,14 +1518,14 @@ } else { - sCustomLoginLink = Utils.pString(RL.settingsGet('CustomLoginLink')); + sCustomLoginLink = Utils.pString(AppSettings.settingsGet('CustomLoginLink')); if (!sCustomLoginLink) { kn.hideLoading(); kn.startScreens([LoginScreen]); Plugins.runHook('rl-start-login-screens'); - RL.pub('rl.bootstart-login-screens'); + Events.pub('rl.bootstart-login-screens'); if (window.SimplePace) { @@ -1267,7 +1548,7 @@ { window['rl_' + sJsHash + '_google_service'] = function () { Data.googleActions(true); - RL.socialUsers(); + self.socialUsers(); }; } @@ -1275,7 +1556,7 @@ { window['rl_' + sJsHash + '_facebook_service'] = function () { Data.facebookActions(true); - RL.socialUsers(); + self.socialUsers(); }; } @@ -1283,16 +1564,16 @@ { window['rl_' + sJsHash + '_twitter_service'] = function () { Data.twitterActions(true); - RL.socialUsers(); + self.socialUsers(); }; } - RL.sub('interval.1m', function () { + Events.sub('interval.1m', function () { Globals.momentTrigger(!Globals.momentTrigger()); }); Plugins.runHook('rl-start-screens'); - RL.pub('rl.bootstart-end'); + Events.pub('rl.bootstart-end'); }; module.exports = new RainLoopApp(); diff --git a/dev/Common/Events.js b/dev/Common/Events.js new file mode 100644 index 000000000..224b1a832 --- /dev/null +++ b/dev/Common/Events.js @@ -0,0 +1,66 @@ +/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */ + +(function (module) { + + 'use strict'; + + var + _ = require('../External/underscore.js'), + + Utils = require('./Utils.js'), + Plugins = require('./Plugins.js') + ; + + /** + * @constructor + */ + function Events() + { + this.oSubs = {}; + } + + Events.prototype.oSubs = {}; + + /** + * @param {string} sName + * @param {Function} fFunc + * @param {Object=} oContext + * @return {Events} + */ + Events.prototype.sub = function (sName, fFunc, oContext) + { + if (Utils.isUnd(this.oSubs[sName])) + { + this.oSubs[sName] = []; + } + + this.oSubs[sName].push([fFunc, oContext]); + + return this; + }; + + /** + * @param {string} sName + * @param {Array=} aArgs + * @return {Events} + */ + Events.prototype.pub = function (sName, aArgs) + { + Plugins.runHook('rl-pub', [sName, aArgs]); + + if (!Utils.isUnd(this.oSubs[sName])) + { + _.each(this.oSubs[sName], function (aItem) { + if (aItem[0]) + { + aItem[0].apply(aItem[1] || null, aArgs || []); + } + }); + } + + return this; + }; + + module.exports = new Events(); + +}(module)); \ No newline at end of file diff --git a/dev/Common/Globals.js b/dev/Common/Globals.js index 41e6c46ec..45b1645d7 100644 --- a/dev/Common/Globals.js +++ b/dev/Common/Globals.js @@ -8,7 +8,10 @@ Globals = {}, window = require('../External/window.js'), ko = require('../External/ko.js'), - $html = require('../External/$html.js') + key = require('../External/key.js'), + $html = require('../External/$html.js'), + + Enums = require('../Common/Enums.js') ; /** @@ -36,6 +39,11 @@ */ Globals.langChangeTrigger = ko.observable(true); + /** + * @type {boolean} + */ + Globals.useKeyboardShortcuts = ko.observable(true); + /** * @type {number} */ @@ -100,6 +108,11 @@ * @type {string} */ Globals.sAnimationType = ''; + + /** + * @type {*} + */ + Globals.__RL = null; /** * @type {Object} @@ -167,17 +180,96 @@ }); } - Globals.oI18N = {}, + Globals.oI18N = window['rainloopI18N'] || {}; - Globals.oNotificationI18N = {}, + Globals.oNotificationI18N = {}; - Globals.aBootstrapDropdowns = [], + Globals.aBootstrapDropdowns = []; Globals.aViewModels = { 'settings': [], 'settings-removed': [], 'settings-disabled': [] }; + + Globals.leftPanelDisabled = ko.observable(false); + + // popups + Globals.popupVisibilityNames = ko.observableArray([]); + + Globals.popupVisibility = ko.computed(function () { + return 0 < Globals.popupVisibilityNames().length; + }, this); + + // keys + Globals.keyScopeReal = ko.observable(Enums.KeyState.All); + Globals.keyScopeFake = ko.observable(Enums.KeyState.All); + + Globals.keyScope = ko.computed({ + 'owner': this, + 'read': function () { + return Globals.keyScopeFake(); + }, + 'write': function (sValue) { + + if (Enums.KeyState.Menu !== sValue) + { + if (Enums.KeyState.Compose === sValue) + { + // disableKeyFilter + key.filter = function () { + return Globals.useKeyboardShortcuts(); + }; + } + else + { + // restoreKeyFilter + key.filter = function (event) { + + if (Globals.useKeyboardShortcuts()) + { + var + oElement = event.target || event.srcElement, + sTagName = oElement ? oElement.tagName : '' + ; + + sTagName = sTagName.toUpperCase(); + return !(sTagName === 'INPUT' || sTagName === 'SELECT' || sTagName === 'TEXTAREA' || + (oElement && sTagName === 'DIV' && 'editorHtmlArea' === oElement.className && oElement.contentEditable) + ); + } + + return false; + }; + } + + Globals.keyScopeFake(sValue); + if (Globals.dropdownVisibility()) + { + sValue = Enums.KeyState.Menu; + } + } + + Globals.keyScopeReal(sValue); + } + }); + + Globals.keyScopeReal.subscribe(function (sValue) { +// window.console.log(sValue); + key.setScope(sValue); + }); + + Globals.dropdownVisibility.subscribe(function (bValue) { + if (bValue) + { + Globals.tooltipTrigger(!Globals.tooltipTrigger()); + Globals.keyScope(Enums.KeyState.Menu); + } + else if (Enums.KeyState.Menu === key.getScope()) + { + Globals.keyScope(Globals.keyScopeFake()); + } + }); module.exports = Globals; diff --git a/dev/Common/LinkBuilder.js b/dev/Common/LinkBuilder.js index 3456df4de..d2b15ab46 100644 --- a/dev/Common/LinkBuilder.js +++ b/dev/Common/LinkBuilder.js @@ -6,7 +6,8 @@ var window = require('../External/window.js'), - Utils = require('./Utils.js') + Utils = require('./Utils.js'), + AppSettings = require('../Storages/AppSettings.js') ; /** @@ -16,9 +17,9 @@ { this.sBase = '#/'; this.sServer = './?'; - this.sVersion = RL.settingsGet('Version'); - this.sSpecSuffix = RL.settingsGet('AuthAccountHash') || '0'; - this.sStaticPrefix = RL.settingsGet('StaticPrefix') || 'rainloop/v/' + this.sVersion + '/static/'; + this.sVersion = AppSettings.settingsGet('Version'); + this.sSpecSuffix = AppSettings.settingsGet('AuthAccountHash') || '0'; + this.sStaticPrefix = AppSettings.settingsGet('StaticPrefix') || 'rainloop/v/' + this.sVersion + '/static/'; } /** diff --git a/dev/Common/NewHtmlEditorWrapper.js b/dev/Common/NewHtmlEditorWrapper.js index 5944cfe0a..ffa89bb5b 100644 --- a/dev/Common/NewHtmlEditorWrapper.js +++ b/dev/Common/NewHtmlEditorWrapper.js @@ -6,7 +6,8 @@ var window = require('../External/window.js'), - Globals = require('./Globals.js') + Globals = require('./Globals.js'), + AppSettings = require('../Storages/AppSettings.js') ; /** @@ -164,8 +165,8 @@ var oConfig = Globals.oHtmlEditorDefaultConfig, - sLanguage = RL.settingsGet('Language'), // TODO cjs - bSource = !!RL.settingsGet('AllowHtmlEditorSourceButton') + sLanguage = AppSettings.settingsGet('Language'), + bSource = !!AppSettings.settingsGet('AllowHtmlEditorSourceButton') ; if (bSource && oConfig.toolbarGroups && !oConfig.toolbarGroups.__SourceInited) diff --git a/dev/Common/Plugins.js b/dev/Common/Plugins.js index 052f91cf6..b69e45424 100644 --- a/dev/Common/Plugins.js +++ b/dev/Common/Plugins.js @@ -5,10 +5,13 @@ 'use strict'; var - Plugins = {}, - Utils = require('./Utils.js'), - Remote = require('../Remote.js'), - RL = require('../RL.js') + Plugins = { + __boot: null, + __remote: null, + __data: null + }, + _ = require('../External/underscore.js'), + Utils = require('./Utils.js') ; /** @@ -72,7 +75,12 @@ */ Plugins.mainSettingsGet = function (sName) { - return RL ? RL().settingsGet(sName) : null; + if (Plugins.__boot) + { + return Plugins.__boot.settingsGet(sName); + } + + return null; }; /** @@ -85,9 +93,9 @@ */ Plugins.remoteRequest = function (fCallback, sAction, oParameters, iTimeout, sGetAdd, aAbortActions) { - if (Remote) + if (Plugins.__remote) { - Remote().defaultRequest(fCallback, sAction, oParameters, iTimeout, sGetAdd, aAbortActions); + Plugins.__remote.defaultRequest(fCallback, sAction, oParameters, iTimeout, sGetAdd, aAbortActions); } }; diff --git a/dev/Common/Utils.js b/dev/Common/Utils.js index b7aa9b778..49889fa91 100644 --- a/dev/Common/Utils.js +++ b/dev/Common/Utils.js @@ -10,17 +10,14 @@ $ = require('../External/jquery.js'), _ = require('../External/underscore.js'), ko = require('../External/ko.js'), - key = require('../External/key.js'), window = require('../External/window.js'), $window = require('../External/$window.js'), + $html = require('../External/$html.js'), $doc = require('../External/$doc.js'), NotificationClass = require('../External/NotificationClass.js'), - LocalStorage = require('../Storages/LocalStorage.js'), - - kn = require('../Knoin/Knoin.js'), - Enums = require('./Enums.js'), + Consts = require('./Consts.js'), Globals = require('./Globals.js') ; @@ -154,24 +151,24 @@ Utils.exportPath = function (sPath, oObject, oObjectToExportTo) { var - part = null, - parts = sPath.split('.'), - cur = oObjectToExportTo || window + sPart = null, + aParts = sPath.split('.'), + oCur = oObjectToExportTo || window ; - for (; parts.length && (part = parts.shift());) + for (; aParts.length && (sPart = aParts.shift());) { - if (!parts.length && !Utils.isUnd(oObject)) + if (!aParts.length && !Utils.isUnd(oObject)) { - cur[part] = oObject; + oCur[sPart] = oObject; } - else if (cur[part]) + else if (oCur[sPart]) { - cur = cur[part]; + oCur = oCur[sPart]; } else { - cur = cur[part] = {}; + oCur = oCur[sPart] = {}; } } }; @@ -694,7 +691,7 @@ */ Utils.roundNumber = function (iNum, iDec) { - return Math.round(iNum * Math.pow(10, iDec)) / Math.pow(10, iDec); + return window.Math.round(iNum * window.Math.pow(10, iDec)) / window.Math.pow(10, iDec); }; /** @@ -1241,112 +1238,6 @@ }, oObject); }; - /** - * @param {string} sFullNameHash - * @return {boolean} - */ - Utils.isFolderExpanded = function (sFullNameHash) - { - var aExpandedList = /** @type {Array|null} */ LocalStorage.get(Enums.ClientSideKeyName.ExpandedFolders); - return _.isArray(aExpandedList) && -1 !== _.indexOf(aExpandedList, sFullNameHash); - }; - - /** - * @param {string} sFullNameHash - * @param {boolean} bExpanded - */ - Utils.setExpandedFolder = function (sFullNameHash, bExpanded) - { - var aExpandedList = /** @type {Array|null} */ LocalStorage.get(Enums.ClientSideKeyName.ExpandedFolders); - if (!_.isArray(aExpandedList)) - { - aExpandedList = []; - } - - if (bExpanded) - { - aExpandedList.push(sFullNameHash); - aExpandedList = _.uniq(aExpandedList); - } - else - { - aExpandedList = _.without(aExpandedList, sFullNameHash); - } - - LocalStorage.set(Enums.ClientSideKeyName.ExpandedFolders, aExpandedList); - }; - - Utils.initLayoutResizer = function (sLeft, sRight, sClientSideKeyName) - { - var - iDisabledWidth = 60, - iMinWidth = 155, - oLeft = $(sLeft), - oRight = $(sRight), - - mLeftWidth = LocalStorage.get(sClientSideKeyName) || null, - - fSetWidth = function (iWidth) { - if (iWidth) - { - oLeft.css({ - 'width': '' + iWidth + 'px' - }); - - oRight.css({ - 'left': '' + iWidth + 'px' - }); - } - }, - - fDisable = function (bDisable) { - if (bDisable) - { - oLeft.resizable('disable'); - fSetWidth(iDisabledWidth); - } - else - { - oLeft.resizable('enable'); - var iWidth = Utils.pInt(LocalStorage.get(sClientSideKeyName)) || iMinWidth; - fSetWidth(iWidth > iMinWidth ? iWidth : iMinWidth); - } - }, - - fResizeFunction = function (oEvent, oObject) { - if (oObject && oObject.size && oObject.size.width) - { - LocalStorage.set(sClientSideKeyName, oObject.size.width); - - oRight.css({ - 'left': '' + oObject.size.width + 'px' - }); - } - } - ; - - if (null !== mLeftWidth) - { - fSetWidth(mLeftWidth > iMinWidth ? mLeftWidth : iMinWidth); - } - - oLeft.resizable({ - 'helper': 'ui-resizable-helper', - 'minWidth': iMinWidth, - 'maxWidth': 350, - 'handles': 'e', - 'stop': fResizeFunction - }); - - RL.sub('left-panel.off', function () { - fDisable(true); - }); - - RL.sub('left-panel.on', function () { - fDisable(false); - }); - }; - /** * @param {Object} oMessageTextBody */ @@ -1526,7 +1417,10 @@ Utils.i18nToNode(oBody); - kn.applyExternal(oViewModel, $('#rl-content', oBody)[0]); + if (oViewModel && $('#rl-content', oBody)[0]) + { + ko.applyBindings(oViewModel, $('#rl-content', oBody)[0]); + } window[sFunc] = null; @@ -1863,6 +1757,135 @@ oTempImg.src = sUrl; }; + /** + * @param {Array} aSystem + * @param {Array} aList + * @param {Array=} aDisabled + * @param {Array=} aHeaderLines + * @param {?number=} iUnDeep + * @param {Function=} fDisableCallback + * @param {Function=} fVisibleCallback + * @param {Function=} fRenameCallback + * @param {boolean=} bSystem + * @param {boolean=} bBuildUnvisible + * @return {Array} + */ + Utils.folderListOptionsBuilder = function (aSystem, aList, aDisabled, aHeaderLines, iUnDeep, fDisableCallback, fVisibleCallback, fRenameCallback, bSystem, bBuildUnvisible) + { + var + /** + * @type {?FolderModel} + */ + oItem = null, + bSep = false, + iIndex = 0, + iLen = 0, + sDeepPrefix = '\u00A0\u00A0\u00A0', + aResult = [] + ; + + bSystem = !Utils.isNormal(bSystem) ? 0 < aSystem.length : bSystem; + bBuildUnvisible = Utils.isUnd(bBuildUnvisible) ? false : !!bBuildUnvisible; + iUnDeep = !Utils.isNormal(iUnDeep) ? 0 : iUnDeep; + fDisableCallback = Utils.isNormal(fDisableCallback) ? fDisableCallback : null; + fVisibleCallback = Utils.isNormal(fVisibleCallback) ? fVisibleCallback : null; + fRenameCallback = Utils.isNormal(fRenameCallback) ? fRenameCallback : null; + + if (!Utils.isArray(aDisabled)) + { + aDisabled = []; + } + + if (!Utils.isArray(aHeaderLines)) + { + aHeaderLines = []; + } + + for (iIndex = 0, iLen = aHeaderLines.length; iIndex < iLen; iIndex++) + { + aResult.push({ + 'id': aHeaderLines[iIndex][0], + 'name': aHeaderLines[iIndex][1], + 'system': false, + 'seporator': false, + 'disabled': false + }); + } + + bSep = true; + for (iIndex = 0, iLen = aSystem.length; iIndex < iLen; iIndex++) + { + oItem = aSystem[iIndex]; + if (fVisibleCallback ? fVisibleCallback.call(null, oItem) : true) + { + if (bSep && 0 < aResult.length) + { + aResult.push({ + 'id': '---', + 'name': '---', + 'system': false, + 'seporator': true, + 'disabled': true + }); + } + + bSep = false; + aResult.push({ + 'id': oItem.fullNameRaw, + 'name': fRenameCallback ? fRenameCallback.call(null, oItem) : oItem.name(), + 'system': true, + 'seporator': false, + 'disabled': !oItem.selectable || -1 < Utils.inArray(oItem.fullNameRaw, aDisabled) || + (fDisableCallback ? fDisableCallback.call(null, oItem) : false) + }); + } + } + + bSep = true; + for (iIndex = 0, iLen = aList.length; iIndex < iLen; iIndex++) + { + oItem = aList[iIndex]; + if (oItem.subScribed() || !oItem.existen) + { + if (fVisibleCallback ? fVisibleCallback.call(null, oItem) : true) + { + if (Enums.FolderType.User === oItem.type() || !bSystem || 0 < oItem.subFolders().length) + { + if (bSep && 0 < aResult.length) + { + aResult.push({ + 'id': '---', + 'name': '---', + 'system': false, + 'seporator': true, + 'disabled': true + }); + } + + bSep = false; + aResult.push({ + 'id': oItem.fullNameRaw, + 'name': (new window.Array(oItem.deep + 1 - iUnDeep)).join(sDeepPrefix) + + (fRenameCallback ? fRenameCallback.call(null, oItem) : oItem.name()), + 'system': false, + 'seporator': false, + 'disabled': !oItem.selectable || -1 < Utils.inArray(oItem.fullNameRaw, aDisabled) || + (fDisableCallback ? fDisableCallback.call(null, oItem) : false) + }); + } + } + } + + if (oItem.subScribed() && 0 < oItem.subFolders().length) + { + aResult = aResult.concat(Utils.folderListOptionsBuilder([], oItem.subFolders(), aDisabled, [], + iUnDeep, fDisableCallback, fVisibleCallback, fRenameCallback, bSystem, bBuildUnvisible)); + } + } + + return aResult; + }; + Utils.computedPagenatorHelper = function (koCurrentPage, koPageCount) { return function() { @@ -1949,7 +1972,7 @@ } else if (3 < iPrev) { - fAdd(Math.round((iPrev - 1) / 2), false, '...'); + fAdd(window.Math.round((iPrev - 1) / 2), false, '...'); } if (iPageCount - 2 === iNext) @@ -1958,7 +1981,7 @@ } else if (iPageCount - 2 > iNext) { - fAdd(Math.round((iPageCount + iNext) / 2), true, '...'); + fAdd(window.Math.round((iPageCount + iNext) / 2), true, '...'); } // first and last @@ -1984,53 +2007,19 @@ { var sel = window.getSelection(); sel.removeAllRanges(); - var range = document.createRange(); + var range = window.document.createRange(); range.selectNodeContents(element); sel.addRange(range); } - else if (document.selection) + else if (window.document.selection) { - var textRange = document.body.createTextRange(); + var textRange = window.document.body.createTextRange(); textRange.moveToElementText(element); textRange.select(); } /* jshint onevar: true */ }; - Utils.disableKeyFilter = function () - { - if (window.key) - { - key.filter = function () { - return RL.data().useKeyboardShortcuts(); - }; - } - }; - - Utils.restoreKeyFilter = function () - { - if (window.key) - { - key.filter = function (event) { - - if (RL.data().useKeyboardShortcuts()) - { - var - element = event.target || event.srcElement, - tagName = element ? element.tagName : '' - ; - - tagName = tagName.toUpperCase(); - return !(tagName === 'INPUT' || tagName === 'SELECT' || tagName === 'TEXTAREA' || - (element && tagName === 'DIV' && 'editorHtmlArea' === element.className && element.contentEditable) - ); - } - - return false; - }; - } - }; - Utils.detectDropdownVisibility = _.debounce(function () { Globals.dropdownVisibility(!!_.find(Globals.aBootstrapDropdowns, function (oItem) { return oItem.hasClass('open'); diff --git a/dev/External/NotificationClass.js b/dev/External/NotificationClass.js index 7913dc71f..fa9c34f3b 100644 --- a/dev/External/NotificationClass.js +++ b/dev/External/NotificationClass.js @@ -2,8 +2,5 @@ 'use strict'; -var - window = require('./window.js') -; - +var window = require('./window.js'); module.exports = window.Notification && window.Notification.requestPermission ? window.Notification : null; \ No newline at end of file diff --git a/dev/External/ko.js b/dev/External/ko.js index 91f42f0f7..821f2911c 100644 --- a/dev/External/ko.js +++ b/dev/External/ko.js @@ -5,20 +5,21 @@ 'use strict'; var - $ = require('./jquery.js'), - _ = require('./underscore.js'), window = require('./window.js'), + _ = require('./underscore.js'), + $ = require('./jquery.js'), $window = require('./$window.js'), - $doc = require('./$doc.js'), - - Globals = require('../Common/Globals.js'), - Utils = require('../Common/Utils.js'), - - RL = require('../RL.js') + $doc = require('./$doc.js') ; ko.bindingHandlers.tooltip = { 'init': function (oElement, fValueAccessor) { + + var + Globals = require('../Common/Globals.js'), + Utils = require('../Common/Utils.js') + ; + if (!Globals.bMobileDevice) { var @@ -56,7 +57,8 @@ var $oEl = $(oElement), sClass = $oEl.data('tooltip-class') || '', - sPlacement = $oEl.data('tooltip-placement') || 'top' + sPlacement = $oEl.data('tooltip-placement') || 'top', + Globals = require('../Common/Globals.js') ; $oEl.tooltip({ @@ -84,7 +86,10 @@ ko.bindingHandlers.tooltip3 = { 'init': function (oElement) { - var $oEl = $(oElement); + var + $oEl = $(oElement), + Globals = require('../Common/Globals.js') + ; $oEl.tooltip({ 'container': 'body', @@ -117,6 +122,11 @@ ko.bindingHandlers.registrateBootstrapDropdown = { 'init': function (oElement) { + + var + Globals = require('../Common/Globals.js') + ; + Globals.aBootstrapDropdowns.push($(oElement)); } }; @@ -125,7 +135,11 @@ 'update': function (oElement, fValueAccessor) { if (ko.utils.unwrapObservable(fValueAccessor())) { - var $el = $(oElement); + var + $el = $(oElement), + Utils = require('../Common/Utils.js') + ; + if (!$el.hasClass('open')) { $el.find('.dropdown-toggle').dropdown('toggle'); @@ -153,6 +167,11 @@ ko.bindingHandlers.csstext = { 'init': function (oElement, fValueAccessor) { + + var + Utils = require('../Common/Utils.js') + ; + if (oElement && oElement.styleSheet && !Utils.isUnd(oElement.styleSheet.cssText)) { oElement.styleSheet.cssText = ko.utils.unwrapObservable(fValueAccessor()); @@ -163,6 +182,11 @@ } }, 'update': function (oElement, fValueAccessor) { + + var + Utils = require('../Common/Utils.js') + ; + if (oElement && oElement.styleSheet && !Utils.isUnd(oElement.styleSheet.cssText)) { oElement.styleSheet.cssText = ko.utils.unwrapObservable(fValueAccessor()); @@ -229,6 +253,11 @@ ko.bindingHandlers.modal = { 'init': function (oElement, fValueAccessor) { + var + Globals = require('../Common/Globals.js'), + Utils = require('../Common/Utils.js') + ; + $(oElement).toggleClass('fade', !Globals.bMobileDevice).modal({ 'keyboard': false, 'show': ko.utils.unwrapObservable(fValueAccessor()) @@ -247,12 +276,18 @@ ko.bindingHandlers.i18nInit = { 'init': function (oElement) { + var + Utils = require('../Common/Utils.js') + ; Utils.i18nToNode(oElement); } }; ko.bindingHandlers.i18nUpdate = { 'update': function (oElement, fValueAccessor) { + var + Utils = require('../Common/Utils.js') + ; ko.utils.unwrapObservable(fValueAccessor()); Utils.i18nToNode(oElement); } @@ -292,6 +327,7 @@ }, 'update': function (oElement, fValueAccessor) { var + Utils = require('../Common/Utils.js'), aValues = ko.utils.unwrapObservable(fValueAccessor()), iValue = Utils.pInt(aValues[1]), iSize = 0, @@ -325,6 +361,11 @@ ko.bindingHandlers.draggable = { 'init': function (oElement, fValueAccessor, fAllBindingsAccessor) { + var + Globals = require('../Common/Globals.js'), + Utils = require('../Common/Utils.js') + ; + if (!Globals.bMobileDevice) { var @@ -406,6 +447,10 @@ ko.bindingHandlers.droppable = { 'init': function (oElement, fValueAccessor, fAllBindingsAccessor) { + var + Globals = require('../Common/Globals.js') + ; + if (!Globals.bMobileDevice) { var @@ -447,6 +492,11 @@ ko.bindingHandlers.nano = { 'init': function (oElement) { + + var + Globals = require('../Common/Globals.js') + ; + if (!Globals.bDisableNanoScroll) { $(oElement) @@ -540,10 +590,14 @@ }; ko.bindingHandlers.emailsTags = { - 'init': function(oElement, fValueAccessor) { + 'init': function(oElement, fValueAccessor, fAllBindingsAccessor) { + var + Utils = require('../Common/Utils.js'), $oEl = $(oElement), fValue = fValueAccessor(), + fAllBindings = fAllBindingsAccessor(), + fAutoCompleteSource = fAllBindings['autoCompleteSource'] || null, fFocusCallback = function (bValue) { if (fValue && fValue.focusTrigger) { @@ -557,13 +611,7 @@ 'allowDragAndDrop': true, 'focusCallback': fFocusCallback, 'inputDelimiters': [',', ';'], - 'autoCompleteSource': function (oData, fResponse) { - RL().getAutocomplete(oData.term, function (aData) { - fResponse(_.map(aData, function (oEmailItem) { - return oEmailItem.toLine(false); - })); - }); - }, + 'autoCompleteSource': fAutoCompleteSource, 'parseHook': function (aInput) { return _.map(aInput, function (sInputValue) { @@ -615,9 +663,13 @@ ko.bindingHandlers.contactTags = { 'init': function(oElement, fValueAccessor) { + var + Utils = require('../Common/Utils.js'), $oEl = $(oElement), fValue = fValueAccessor(), + fAllBindings = fAllBindingsAccessor(), + fAutoCompleteSource = fAllBindings['autoCompleteSource'] || null, fFocusCallback = function (bValue) { if (fValue && fValue.focusTrigger) { @@ -632,13 +684,7 @@ 'focusCallback': fFocusCallback, 'inputDelimiters': [',', ';'], 'outputDelimiter': ',', - 'autoCompleteSource': function (oData, fResponse) { - RL().getContactTagsAutocomplete(oData.term, function (aData) { - fResponse(_.map(aData, function (oTagItem) { - return oTagItem.toLine(false); - })); - }); - }, + 'autoCompleteSource': fAutoCompleteSource, 'parseHook': function (aInput) { return _.map(aInput, function (sInputValue) { @@ -731,13 +777,16 @@ ko.extenders.trimmer = function (oTarget) { - var oResult = ko.computed({ - 'read': oTarget, - 'write': function (sNewValue) { - oTarget(Utils.trim(sNewValue.toString())); - }, - 'owner': this - }); + var + Utils = require('../Common/Utils.js'), + oResult = ko.computed({ + 'read': oTarget, + 'write': function (sNewValue) { + oTarget(Utils.trim(sNewValue.toString())); + }, + 'owner': this + }) + ; oResult(oTarget()); return oResult; @@ -745,23 +794,26 @@ ko.extenders.posInterer = function (oTarget, iDefault) { - var oResult = ko.computed({ - 'read': oTarget, - 'write': function (sNewValue) { - var iNew = Utils.pInt(sNewValue.toString(), iDefault); - if (0 >= iNew) - { - iNew = iDefault; - } + var + Utils = require('../Common/Utils.js'), + oResult = ko.computed({ + 'read': oTarget, + 'write': function (sNewValue) { + var iNew = Utils.pInt(sNewValue.toString(), iDefault); + if (0 >= iNew) + { + iNew = iDefault; + } - if (iNew === oTarget() && '' + iNew !== '' + sNewValue) - { - oTarget(iNew + 1); - } + if (iNew === oTarget() && '' + iNew !== '' + sNewValue) + { + oTarget(iNew + 1); + } - oTarget(iNew); - } - }); + oTarget(iNew); + } + }) + ; oResult(oTarget()); return oResult; @@ -799,6 +851,8 @@ ko.extenders.falseTimeout = function (oTarget, iOption) { + var Utils = require('../Common/Utils.js'); + oTarget.iTimeout = 0; oTarget.subscribe(function (bValue) { if (bValue) @@ -822,6 +876,7 @@ ko.observable.fn.validateEmail = function () { + var Utils = require('../Common/Utils.js'); this.hasError = ko.observable(false); this.subscribe(function (sValue) { @@ -835,6 +890,8 @@ ko.observable.fn.validateSimpleEmail = function () { + var Utils = require('../Common/Utils.js'); + this.hasError = ko.observable(false); this.subscribe(function (sValue) { @@ -848,6 +905,7 @@ ko.observable.fn.validateFunc = function (fFunc) { + var Utils = require('../Common/Utils.js'); this.hasFuncError = ko.observable(false); if (Utils.isFunc(fFunc)) @@ -864,4 +922,4 @@ module.exports = ko; -}(module)); \ No newline at end of file +}(module)); diff --git a/dev/External/underscore.js b/dev/External/underscore.js index d2175d760..45e71558c 100644 --- a/dev/External/underscore.js +++ b/dev/External/underscore.js @@ -2,4 +2,4 @@ 'use strict'; -module.exports = window; \ No newline at end of file +module.exports = _; \ No newline at end of file diff --git a/dev/Knoin/Knoin.js b/dev/Knoin/Knoin.js index 77d16b4e5..617367ee3 100644 --- a/dev/Knoin/Knoin.js +++ b/dev/Knoin/Knoin.js @@ -11,10 +11,11 @@ hasher = require('../External/hasher.js'), crossroads = require('../External/crossroads.js'), $html = require('../External/$html.js'), + Globals = require('../Common/Globals.js'), - Enums = require('../Common/Enums.js'), Plugins = require('../Common/Plugins.js'), Utils = require('../Common/Utils.js'), + KnoinAbstractViewModel = require('../Knoin/KnoinAbstractViewModel.js') ; @@ -25,24 +26,11 @@ { this.sDefaultScreenName = ''; this.oScreens = {}; - this.oBoot = null; this.oCurrentScreen = null; } - /** - * @param {Object} thisObject - */ - Knoin.constructorEnd = function (thisObject) - { - if (Utils.isFunc(thisObject['__constructor_end'])) - { - thisObject['__constructor_end'].call(thisObject); - } - }; - Knoin.prototype.sDefaultScreenName = ''; Knoin.prototype.oScreens = {}; - Knoin.prototype.oBoot = null; Knoin.prototype.oCurrentScreen = null; Knoin.prototype.hideLoading = function () @@ -50,16 +38,6 @@ $('#rl-loading').hide(); }; - Knoin.prototype.rl = function () - { - return this.oBoot; - }; - - Knoin.prototype.remote = function () - { - return this.oRemote; - }; - /** * @param {Object} thisObject */ @@ -154,6 +132,7 @@ if (ViewModelClass && !ViewModelClass.__builded) { var + kn = this, oViewModel = new ViewModelClass(oScreen), sPosition = oViewModel.viewModelPosition(), oViewModelPlace = $('#rl-content #rl-' + sPosition.toLowerCase()), @@ -162,7 +141,6 @@ ViewModelClass.__builded = true; ViewModelClass.__vm = oViewModel; - oViewModel.data = RL.data(); // TODO cjs oViewModel.viewModelName = ViewModelClass.__name; @@ -177,7 +155,7 @@ if ('Popups' === sPosition) { oViewModel.cancelCommand = oViewModel.closeCommand = Utils.createCommand(oViewModel, function () { - kn.hideScreenPopup(ViewModelClass); // TODO cjs + kn.hideScreenPopup(ViewModelClass); }); oViewModel.modalVisibility.subscribe(function (bValue) { @@ -188,8 +166,8 @@ this.viewModelDom.show(); this.storeAndSetKeyScope(); - RL.popupVisibilityNames.push(this.viewModelName); // TODO cjs - oViewModel.viewModelDom.css('z-index', 3000 + RL.popupVisibilityNames().length + 10); // TODO cjs + Globals.popupVisibilityNames.push(this.viewModelName); + oViewModel.viewModelDom.css('z-index', 3000 + Globals.popupVisibilityNames().length + 10); Utils.delegateRun(this, 'onFocus', [], 500); } @@ -198,7 +176,7 @@ Utils.delegateRun(this, 'onHide'); this.restoreKeyScope(); - RL.popupVisibilityNames.remove(this.viewModelName); // TODO cjs + Globals.popupVisibilityNames.remove(this.viewModelName); oViewModel.viewModelDom.css('z-index', 2000); Globals.tooltipTrigger(!Globals.tooltipTrigger()); @@ -211,7 +189,7 @@ }, oViewModel); } - Plugins.runHook('view-model-pre-build', [ViewModelClass.__name, oViewModel, oViewModelDom]); // TODO cjs + Plugins.runHook('view-model-pre-build', [ViewModelClass.__name, oViewModel, oViewModelDom]); ko.applyBindingAccessorsToNode(oViewModelDom[0], { 'i18nInit': true, @@ -224,7 +202,7 @@ oViewModel.registerPopupKeyDown(); } - Plugins.runHook('view-model-post-build', [ViewModelClass.__name, oViewModel, oViewModelDom]); // TODO cjs + Plugins.runHook('view-model-post-build', [ViewModelClass.__name, oViewModel, oViewModelDom]); } else { @@ -235,18 +213,6 @@ return ViewModelClass ? ViewModelClass.__vm : null; }; - /** - * @param {Object} oViewModel - * @param {Object} oViewModelDom - */ - Knoin.prototype.applyExternal = function (oViewModel, oViewModelDom) - { - if (oViewModel && oViewModelDom) - { - ko.applyBindings(oViewModel, oViewModelDom); - } - }; - /** * @param {Function} ViewModelClassToHide */ @@ -255,7 +221,7 @@ if (ViewModelClassToHide && ViewModelClassToHide.__vm && ViewModelClassToHide.__dom) { ViewModelClassToHide.__vm.modalVisibility(false); - Plugins.runHook('view-model-on-hide', [ViewModelClassToHide.__name, ViewModelClassToHide.__vm]); // TODO cjs + Plugins.runHook('view-model-on-hide', [ViewModelClassToHide.__name, ViewModelClassToHide.__vm]); } }; @@ -273,7 +239,7 @@ { ViewModelClassToShow.__vm.modalVisibility(true); Utils.delegateRun(ViewModelClassToShow.__vm, 'onShow', aParameters || []); - Plugins.runHook('view-model-on-show', [ViewModelClassToShow.__name, ViewModelClassToShow.__vm, aParameters || []]); // TODO cjs + Plugins.runHook('view-model-on-show', [ViewModelClassToShow.__name, ViewModelClassToShow.__vm, aParameters || []]); } } }; @@ -364,7 +330,7 @@ { Utils.delegateRun(self.oCurrentScreen, 'onShow'); - Plugins.runHook('screen-on-show', [self.oCurrentScreen.screenName(), self.oCurrentScreen]); // TODO cjs + Plugins.runHook('screen-on-show', [self.oCurrentScreen.screenName(), self.oCurrentScreen]); if (Utils.isNonEmptyArray(self.oCurrentScreen.viewModels())) { @@ -378,7 +344,7 @@ Utils.delegateRun(ViewModelClass.__vm, 'onShow'); Utils.delegateRun(ViewModelClass.__vm, 'onFocus', [], 200); - Plugins.runHook('view-model-on-show', [ViewModelClass.__name, ViewModelClass.__vm]); // TODO cjs + Plugins.runHook('view-model-on-show', [ViewModelClass.__name, ViewModelClass.__vm]); } }, self); @@ -431,9 +397,9 @@ oScreen.__started = true; oScreen.__start(); - Plugins.runHook('screen-pre-start', [oScreen.screenName(), oScreen]); // TODO cjs + Plugins.runHook('screen-pre-start', [oScreen.screenName(), oScreen]); Utils.delegateRun(oScreen, 'onStart'); - Plugins.runHook('screen-post-start', [oScreen.screenName(), oScreen]); // TODO cjs + Plugins.runHook('screen-post-start', [oScreen.screenName(), oScreen]); } }, this); @@ -479,71 +445,6 @@ } }; - /** - * @return {Knoin} - */ - Knoin.prototype.bootstart = function (RL, Remote) - { - this.oBoot = RL; - this.oRemote = Remote; - - var - window = require('../External/window.js'), - $window = require('../External/$window.js'), - $html = require('../External/$html.js'), - Plugins = require('../Common/Plugins.js'), - EmailModel = require('../Models/EmailModel.js') - ; - - $html.addClass(Globals.bMobileDevice ? 'mobile' : 'no-mobile'); - - $window.keydown(Utils.killCtrlAandS).keyup(Utils.killCtrlAandS); - $window.unload(function () { - Globals.bUnload = true; - }); - - $html.on('click.dropdown.data-api', function () { - Utils.detectDropdownVisibility(); - }); - - // export - window['rl'] = window['rl'] || {}; - window['rl']['addHook'] = Plugins.addHook; - window['rl']['settingsGet'] = Plugins.mainSettingsGet; - window['rl']['remoteRequest'] = Plugins.remoteRequest; - window['rl']['pluginSettingsGet'] = Plugins.settingsGet; - window['rl']['addSettingsViewModel'] = _.bind(this.addSettingsViewModel, this); - window['rl']['createCommand'] = Utils.createCommand; - - window['rl']['EmailModel'] = EmailModel; - window['rl']['Enums'] = Enums; - - window['__RLBOOT'] = function (fCall) { - - // boot - $(function () { - - if (window['rainloopTEMPLATES'] && window['rainloopTEMPLATES'][0]) - { - $('#rl-templates').html(window['rainloopTEMPLATES'][0]); - - _.delay(function () { - - RL.bootstart(); - - $html.removeClass('no-js rl-booted-trigger').addClass('rl-booted'); - }, 50); - } - else - { - fCall(false); - } - - window['__RLBOOT'] = null; - }); - }; - }; - module.exports = new Knoin(); }(module)); \ No newline at end of file diff --git a/dev/Knoin/KnoinAbstractViewModel.js b/dev/Knoin/KnoinAbstractViewModel.js index 7814d789e..5c35cbc0a 100644 --- a/dev/Knoin/KnoinAbstractViewModel.js +++ b/dev/Knoin/KnoinAbstractViewModel.js @@ -7,8 +7,10 @@ var ko = require('../External/ko.js'), $window = require('../External/$window.js'), + Utils = require('../Common/Utils.js'), - Enums = require('../Common/Enums.js') + Enums = require('../Common/Enums.js'), + Globals = require('../Common/Globals.js') ; /** @@ -68,19 +70,18 @@ return this.sPosition; }; - KnoinAbstractViewModel.prototype.cancelCommand = KnoinAbstractViewModel.prototype.closeCommand = function () - { - }; + KnoinAbstractViewModel.prototype.cancelCommand = function () {}; + KnoinAbstractViewModel.prototype.closeCommand = function () {}; KnoinAbstractViewModel.prototype.storeAndSetKeyScope = function () { - this.sCurrentKeyScope = RL.data().keyScope(); // TODO cjs - RL.data().keyScope(this.sDefaultKeyScope); // TODO cjs + this.sCurrentKeyScope = Globals.keyScope(); + Globals.keyScope(this.sDefaultKeyScope); }; KnoinAbstractViewModel.prototype.restoreKeyScope = function () { - RL.data().keyScope(this.sCurrentKeyScope); // TODO cjs + Globals.keyScope(this.sCurrentKeyScope); }; KnoinAbstractViewModel.prototype.registerPopupKeyDown = function () diff --git a/dev/Models/AttachmentModel.js b/dev/Models/AttachmentModel.js index 3790d6670..2da3fc21c 100644 --- a/dev/Models/AttachmentModel.js +++ b/dev/Models/AttachmentModel.js @@ -118,7 +118,7 @@ */ AttachmentModel.prototype.linkDownload = function () { - return LinkBuilder.attachmentDownload(this.download); // TODO cjs + return LinkBuilder.attachmentDownload(this.download); }; /** @@ -126,7 +126,7 @@ */ AttachmentModel.prototype.linkPreview = function () { - return LinkBuilder.attachmentPreview(this.download); // TODO cjs + return LinkBuilder.attachmentPreview(this.download); }; /** diff --git a/dev/Models/FolderModel.js b/dev/Models/FolderModel.js index 04efd68ad..e721f4296 100644 --- a/dev/Models/FolderModel.js +++ b/dev/Models/FolderModel.js @@ -6,11 +6,13 @@ var _ = require('../External/underscore.js'), - ko = require('./External/ko.js'), + ko = require('../External/ko.js'), $window = require('../External/$window.js'), + Enums = require('../Common/Enums.js'), Globals = require('../Common/Globals.js'), - Utils = require('../Common/Utils.js') + Utils = require('../Common/Utils.js'), + Events = require('../Common/Events.js') ; /** @@ -42,18 +44,7 @@ this.actionBlink = ko.observable(false).extend({'falseTimeout': 1000}); this.nameForEdit = ko.observable(''); - - this.name.subscribe(function (sValue) { - this.nameForEdit(sValue); - }, this); - - this.edited.subscribe(function (bValue) { - if (bValue) - { - this.nameForEdit(this.name()); - } - }, this); - + this.privateMessageCountAll = ko.observable(0); this.privateMessageCountUnread = ko.observable(0); @@ -150,11 +141,6 @@ iType = this.type() ; - if (Enums.FolderType.Inbox === iType) - { - RL.data().foldersInboxUnreadCount(iUnread); // TODO cjs - } - if (0 < iCount) { if (Enums.FolderType.Draft === iType) @@ -290,6 +276,25 @@ }); }, this); + // subscribe + this.name.subscribe(function (sValue) { + this.nameForEdit(sValue); + }, this); + + this.edited.subscribe(function (bValue) { + if (bValue) + { + this.nameForEdit(this.name()); + } + }, this); + + this.messageCountUnread.subscribe(function (iUnread) { + if (Enums.FolderType.Inbox === this.type()) + { + Events.pub('mailbox.inbox-unread-count', [iUnread]); + } + }, this); + return this; }; diff --git a/dev/Models/MessageModel.js b/dev/Models/MessageModel.js index 2a5ad1866..1e1e49a49 100644 --- a/dev/Models/MessageModel.js +++ b/dev/Models/MessageModel.js @@ -346,16 +346,17 @@ MessageModel.prototype.computeSenderEmail = function () { - var - sSent = RL.data().sentFolder(), - sDraft = RL.data().draftFolder() - ; + var + Data = require('../Storages/WebMailDataStorage.js'), + sSent = Data.sentFolder(), + sDraft = Data.draftFolder() + ; - this.senderEmailsString(this.folderFullNameRaw === sSent || this.folderFullNameRaw === sDraft ? - this.toEmailsString() : this.fromEmailString()); + this.senderEmailsString(this.folderFullNameRaw === sSent || this.folderFullNameRaw === sDraft ? + this.toEmailsString() : this.fromEmailString()); - this.senderClearEmailsString(this.folderFullNameRaw === sSent || this.folderFullNameRaw === sDraft ? - this.toClearEmailsString() : this.fromClearEmailString()); + this.senderClearEmailsString(this.folderFullNameRaw === sSent || this.folderFullNameRaw === sDraft ? + this.toClearEmailsString() : this.fromClearEmailString()); }; /** @@ -424,6 +425,7 @@ MessageModel.prototype.initUpdateByMessageJson = function (oJsonMessage) { var + Data = require('../Storages/WebMailDataStorage.js'), bResult = false, iPriority = Enums.MessagePriority.Normal ; @@ -442,7 +444,7 @@ this.proxy = !!oJsonMessage.ExternalProxy; - if (RL.data().capaOpenPGP()) // TODO cjs + if (Data.capaOpenPGP()) { this.isPgpSigned(!!oJsonMessage.PgpSigned); this.isPgpEncrypted(!!oJsonMessage.PgpEncrypted); @@ -731,7 +733,7 @@ */ MessageModel.prototype.viewLink = function () { - return LinkBuilder.messageViewLink(this.requestHash);// TODO cjs + return LinkBuilder.messageViewLink(this.requestHash); }; /** @@ -739,7 +741,7 @@ */ MessageModel.prototype.downloadLink = function () { - return LinkBuilder.messageDownloadLink(this.requestHash);// TODO cjs + return LinkBuilder.messageDownloadLink(this.requestHash); }; /** @@ -1079,7 +1081,7 @@ this.body.data('rl-plain-raw', this.plainRaw); - if (RL.data().capaOpenPGP()) // TODO cjs + if (Data.capaOpenPGP()) { this.body.data('rl-plain-pgp-signed', !!this.isPgpSigned()); this.body.data('rl-plain-pgp-encrypted', !!this.isPgpEncrypted()); @@ -1091,7 +1093,7 @@ MessageModel.prototype.storePgpVerifyDataToDom = function () { - if (this.body && RL.data().capaOpenPGP()) // TODO cjs + if (this.body && Data.capaOpenPGP()) { this.body.data('rl-pgp-verify-status', this.pgpSignedVerifyStatus()); this.body.data('rl-pgp-verify-user', this.pgpSignedVerifyUser()); @@ -1107,7 +1109,7 @@ this.plainRaw = Utils.pString(this.body.data('rl-plain-raw')); - if (RL.data().capaOpenPGP()) // TODO cjs + if (Data.capaOpenPGP()) { this.isPgpSigned(!!this.body.data('rl-plain-pgp-signed')); this.isPgpEncrypted(!!this.body.data('rl-plain-pgp-encrypted')); @@ -1132,7 +1134,7 @@ aRes = [], mPgpMessage = null, sFrom = this.from && this.from[0] && this.from[0].email ? this.from[0].email : '', - aPublicKeys = RL.data().findPublicKeysByEmail(sFrom), // TODO cjs + aPublicKeys = Data.findPublicKeysByEmail(sFrom), oValidKey = null, oValidSysKey = null, sPlain = '' @@ -1158,7 +1160,7 @@ if (oValidKey) { - oValidSysKey = RL.data().findPublicKeyByHex(oValidKey.keyid.toHex()); // TODO cjs + oValidSysKey = Data.findPublicKeyByHex(oValidKey.keyid.toHex()); if (oValidSysKey) { sPlain = mPgpMessage.getText(); @@ -1195,8 +1197,8 @@ mPgpMessage = null, mPgpMessageDecrypted = null, sFrom = this.from && this.from[0] && this.from[0].email ? this.from[0].email : '', - aPublicKey = RL.data().findPublicKeysByEmail(sFrom), // TODO cjs - oPrivateKey = RL.data().findSelfPrivateKey(sPassword), // TODO cjs + aPublicKey = Data.findPublicKeysByEmail(sFrom), + oPrivateKey = Data.findSelfPrivateKey(sPassword), oValidKey = null, oValidSysKey = null, sPlain = '' @@ -1229,7 +1231,7 @@ if (oValidKey) { - oValidSysKey = RL.data().findPublicKeyByHex(oValidKey.keyid.toHex()); // TODO cjs + oValidSysKey = Data.findPublicKeyByHex(oValidKey.keyid.toHex()); if (oValidSysKey) { this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.Success); diff --git a/dev/RainLoopBoot.js b/dev/RainLoopBoot.js deleted file mode 100644 index db30e9aaf..000000000 --- a/dev/RainLoopBoot.js +++ /dev/null @@ -1,11 +0,0 @@ -/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */ - -'use strict'; - -var - kn = require('./Knoin/Knoin.js'), - RL = require('./Boots/RainLoopApp.js'), - Remote = require('./Storages/WebMailAjaxRemoteStorage.js') -; - -kn.bootstart(RL, Remote); \ No newline at end of file diff --git a/dev/Screens/AbstractSettings.js b/dev/Screens/AbstractSettings.js index 92e34c117..727594e4f 100644 --- a/dev/Screens/AbstractSettings.js +++ b/dev/Screens/AbstractSettings.js @@ -83,7 +83,6 @@ oViewModelDom = $('
').addClass('rl-settings-view-model').hide(); oViewModelDom.appendTo(oViewModelPlace); - oSettingsScreen.data = RL.data(); // TODO cjs oSettingsScreen.viewModelDom = oViewModelDom; oSettingsScreen.__rlSettingsData = RoutedSettingsViewModel.__rlSettingsData; @@ -139,7 +138,7 @@ } else { - kn.setHash(LinkBuilder.settings(), false, true); // TODO cjs + kn.setHash(LinkBuilder.settings(), false, true); } }; diff --git a/dev/Screens/AdminLogin.js b/dev/Screens/AdminLoginScreen.js similarity index 79% rename from dev/Screens/AdminLogin.js rename to dev/Screens/AdminLoginScreen.js index d604a9e8d..3e963565b 100644 --- a/dev/Screens/AdminLogin.js +++ b/dev/Screens/AdminLoginScreen.js @@ -6,8 +6,7 @@ var _ = require('../External/underscore.js'), - KnoinAbstractScreen = require('../Knoin/KnoinAbstractScreen.js'), - AdminLoginViewModel = require('../ViewModels/AdminLoginViewModel.js') + KnoinAbstractScreen = require('../Knoin/KnoinAbstractScreen.js') ; /** @@ -16,6 +15,7 @@ */ function AdminLoginScreen() { + var AdminLoginViewModel = require('../ViewModels/AdminLoginViewModel.js'); KnoinAbstractScreen.call(this, 'login', [AdminLoginViewModel]); } @@ -23,7 +23,8 @@ AdminLoginScreen.prototype.onShow = function () { - RL.setTitle(''); // TODO cjs + var RL = require('../Boots/AdminApp.js'); + RL.setTitle(''); }; module.exports = AdminLoginScreen; diff --git a/dev/Screens/AdminSettings.js b/dev/Screens/AdminSettingsScreen.js similarity index 65% rename from dev/Screens/AdminSettings.js rename to dev/Screens/AdminSettingsScreen.js index ac4ecf66e..bde152f97 100644 --- a/dev/Screens/AdminSettings.js +++ b/dev/Screens/AdminSettingsScreen.js @@ -6,9 +6,7 @@ var _ = require('../External/underscore.js'), - AbstractSettings = require('./AbstractSettings.js'), - AdminMenuViewModel = require('../ViewModels/AdminMenuViewModel.js'), - AdminPaneViewModel = require('../ViewModels/AdminPaneViewModel.js') + AbstractSettings = require('./AbstractSettings.js') ; /** @@ -17,6 +15,11 @@ */ function AdminSettingsScreen() { + var + AdminMenuViewModel = require('../ViewModels/AdminMenuViewModel.js'), + AdminPaneViewModel = require('../ViewModels/AdminPaneViewModel.js') + ; + AbstractSettings.call(this, [ AdminMenuViewModel, AdminPaneViewModel @@ -27,7 +30,8 @@ AdminSettingsScreen.prototype.onShow = function () { - RL.setTitle(''); // TODO cjs + var RL = require('../Boots/AdminApp.js'); + RL.setTitle(''); }; module.exports = AdminSettingsScreen; diff --git a/dev/Screens/Login.js b/dev/Screens/LoginScreen.js similarity index 79% rename from dev/Screens/Login.js rename to dev/Screens/LoginScreen.js index 1ca6c92bb..17b30a3d8 100644 --- a/dev/Screens/Login.js +++ b/dev/Screens/LoginScreen.js @@ -6,8 +6,7 @@ var _ = require('../External/underscore.js'), - KnoinAbstractScreen = require('../Knoin/KnoinAbstractScreen.js'), - LoginViewModel = require('../ViewModels/LoginViewModel.js') + KnoinAbstractScreen = require('../Knoin/KnoinAbstractScreen.js') ; /** @@ -16,6 +15,7 @@ */ function LoginScreen() { + var LoginViewModel = require('../ViewModels/LoginViewModel.js'); KnoinAbstractScreen.call(this, 'login', [LoginViewModel]); } @@ -23,7 +23,8 @@ LoginScreen.prototype.onShow = function () { - RL.setTitle(''); // TODO cjs + var RL = require('../Boots/RainLoopApp.js'); + RL.setTitle(''); }; module.exports = LoginScreen; diff --git a/dev/Screens/MailBox.js b/dev/Screens/MailBoxScreen.js similarity index 64% rename from dev/Screens/MailBox.js rename to dev/Screens/MailBoxScreen.js index 7c195d2a7..db09d22db 100644 --- a/dev/Screens/MailBox.js +++ b/dev/Screens/MailBoxScreen.js @@ -9,17 +9,16 @@ $html = require('../External/$html.js'), Enums = require('../Common/Enums.js'), + Globals = require('../Common/Globals.js'), Utils = require('../Common/Utils.js'), + Events = require('../Common/Events.js'), KnoinAbstractScreen = require('../Knoin/KnoinAbstractScreen.js'), + AppSettings = require('../Storages/AppSettings.js'), + Data = require('../Storages/WebMailDataStorage.js'), Cache = require('../Storages/WebMailCacheStorage.js'), - Remote = require('../Storages/WebMailAjaxRemoteStorage.js'), - - MailBoxSystemDropDownViewModel = require('../ViewModels/MailBoxSystemDropDownViewModel.js'), - MailBoxFolderListViewModel = require('../ViewModels/MailBoxFolderListViewModel.js'), - MailBoxMessageListViewModel = require('../ViewModels/MailBoxMessageListViewModel.js'), - MailBoxMessageViewViewModel = require('../ViewModels/MailBoxMessageViewViewModel.js') + Remote = require('../Storages/WebMailAjaxRemoteStorage.js') ; /** @@ -28,6 +27,13 @@ */ function MailBoxScreen() { + var + MailBoxSystemDropDownViewModel = require('../ViewModels/MailBoxSystemDropDownViewModel.js'), + MailBoxFolderListViewModel = require('../ViewModels/MailBoxFolderListViewModel.js'), + MailBoxMessageListViewModel = require('../ViewModels/MailBoxMessageListViewModel.js'), + MailBoxMessageViewViewModel = require('../ViewModels/MailBoxMessageViewViewModel.js') + ; + KnoinAbstractScreen.call(this, 'mailbox', [ MailBoxSystemDropDownViewModel, MailBoxFolderListViewModel, @@ -48,18 +54,19 @@ MailBoxScreen.prototype.setNewTitle = function () { var - sEmail = RL.data().accountEmail(), // TODO cjs - ifoldersInboxUnreadCount = RL.data().foldersInboxUnreadCount() // TODO cjs + RL = require('../Boots/RainLoopApp.js'), + sEmail = Data.accountEmail(), + nFoldersInboxUnreadCount = Data.foldersInboxUnreadCount() ; - // TODO cjs + RL.setTitle(('' === sEmail ? '' : - (0 < ifoldersInboxUnreadCount ? '(' + ifoldersInboxUnreadCount + ') ' : ' ') + sEmail + ' - ') + Utils.i18n('TITLES/MAILBOX')); + (0 < nFoldersInboxUnreadCount ? '(' + nFoldersInboxUnreadCount + ') ' : ' ') + sEmail + ' - ') + Utils.i18n('TITLES/MAILBOX')); }; MailBoxScreen.prototype.onShow = function () { this.setNewTitle(); - RL.data().keyScope(Enums.KeyState.MessageList);// TODO cjs + Globals.keyScope(Enums.KeyState.MessageList); }; /** @@ -70,35 +77,35 @@ */ MailBoxScreen.prototype.onRoute = function (sFolderHash, iPage, sSearch, bPreview) { + var RL = require('../Boots/RainLoopApp.js'); if (Utils.isUnd(bPreview) ? false : !!bPreview) { - if (Enums.Layout.NoPreview === RL.data().layout() && !RL.data().message())// TODO cjs + if (Enums.Layout.NoPreview === Data.layout() && !Data.message()) { - RL.historyBack();// TODO cjs + RL.historyBack(); } } else { var - oData = RL.data(),// TODO cjs sFolderFullNameRaw = Cache.getFolderFullNameRaw(sFolderHash), oFolder = Cache.getFolderFromCacheList(sFolderFullNameRaw) ; if (oFolder) { - oData + Data .currentFolder(oFolder) .messageListPage(iPage) .messageListSearch(sSearch) ; - if (Enums.Layout.NoPreview === oData.layout() && oData.message()) + if (Enums.Layout.NoPreview === Data.layout() && Data.message()) { - oData.message(null); + Data.message(null); } - RL.reloadMessageList();// TODO cjs + RL.reloadMessageList(); } } }; @@ -106,43 +113,47 @@ MailBoxScreen.prototype.onStart = function () { var - oData = RL.data(),// TODO cjs + RL = require('../Boots/RainLoopApp.js'), fResizeFunction = function () { Utils.windowResize(); } ; - if (RL.capa(Enums.Capa.AdditionalAccounts) || RL.capa(Enums.Capa.AdditionalIdentities))// TODO cjs + if (AppSettings.capa(Enums.Capa.AdditionalAccounts) || AppSettings.capa(Enums.Capa.AdditionalIdentities)) { - RL.accountsAndIdentities();// TODO cjs + RL.accountsAndIdentities(); } _.delay(function () { - if ('INBOX' !== oData.currentFolderFullNameRaw()) + if ('INBOX' !== Data.currentFolderFullNameRaw()) { - RL.folderInformation('INBOX');// TODO cjs + RL.folderInformation('INBOX'); } }, 1000); _.delay(function () { - RL.quota();// TODO cjs + RL.quota(); }, 5000); _.delay(function () { Remote.appDelayStart(Utils.emptyFunction); }, 35000); - $html.toggleClass('rl-no-preview-pane', Enums.Layout.NoPreview === oData.layout()); + $html.toggleClass('rl-no-preview-pane', Enums.Layout.NoPreview === Data.layout()); - oData.folderList.subscribe(fResizeFunction); - oData.messageList.subscribe(fResizeFunction); - oData.message.subscribe(fResizeFunction); + Data.folderList.subscribe(fResizeFunction); + Data.messageList.subscribe(fResizeFunction); + Data.message.subscribe(fResizeFunction); - oData.layout.subscribe(function (nValue) { + Data.layout.subscribe(function (nValue) { $html.toggleClass('rl-no-preview-pane', Enums.Layout.NoPreview === nValue); }); - oData.foldersInboxUnreadCount.subscribe(function () { + Events.sub('mailbox.inbox-unread-count', function (nCount) { + Data.foldersInboxUnreadCount(nCount) + }); + + Data.foldersInboxUnreadCount.subscribe(function () { this.setNewTitle(); }, this); }; diff --git a/dev/Screens/Settings.js b/dev/Screens/SettingsScreen.js similarity index 56% rename from dev/Screens/Settings.js rename to dev/Screens/SettingsScreen.js index 66ef21821..dccdcd99e 100644 --- a/dev/Screens/Settings.js +++ b/dev/Screens/SettingsScreen.js @@ -6,12 +6,12 @@ var _ = require('../External/underscore.js'), + Enums = require('../Common/Enums.js'), Utils = require('../Common/Utils.js'), - AbstractSettings = require('../AbstractSettings.js'), - SettingsSystemDropDownViewModel = require('../ViewModels/SettingsSystemDropDownViewModel.js'), - SettingsMenuViewModel = require('../ViewModels/SettingsMenuViewModel.js'), - SettingsPaneViewModel = require('../ViewModels/SettingsPaneViewModel.js') + Globals = require('../Common/Globals.js'), + + AbstractSettings = require('./AbstractSettings.js') ; /** @@ -20,6 +20,14 @@ */ function SettingsScreen() { + var + RL = require('../Boots/RainLoopApp.js'), + + SettingsSystemDropDownViewModel = require('../ViewModels/SettingsSystemDropDownViewModel.js'), + SettingsMenuViewModel = require('../ViewModels/SettingsMenuViewModel.js'), + SettingsPaneViewModel = require('../ViewModels/SettingsPaneViewModel.js') + ; + AbstractSettings.call(this, [ SettingsSystemDropDownViewModel, SettingsMenuViewModel, @@ -29,7 +37,7 @@ Utils.initOnStartOrLangChange(function () { this.sSettingsTitle = Utils.i18n('TITLES/SETTINGS'); }, this, function () { - RL.setTitle(this.sSettingsTitle); // TODO cjs + RL.setTitle(this.sSettingsTitle); }); } @@ -37,8 +45,10 @@ SettingsScreen.prototype.onShow = function () { - RL.setTitle(this.sSettingsTitle); // TODO cjs - RL.data().keyScope(Enums.KeyState.Settings); // TODO cjs + var RL = require('../Boots/RainLoopApp.js'); + + RL.setTitle(this.sSettingsTitle); + Globals.keyScope(Enums.KeyState.Settings); }; module.exports = SettingsScreen; diff --git a/dev/Settings/SettingsAccounts.js b/dev/Settings/SettingsAccounts.js index 759d2dd57..636574ba0 100644 --- a/dev/Settings/SettingsAccounts.js +++ b/dev/Settings/SettingsAccounts.js @@ -13,6 +13,7 @@ Utils = require('../Common/Utils.js'), LinkBuilder = require('../Common/LinkBuilder.js'), + Data = require('../Storages/WebMailDataStorage.js'), Remote = require('../Storages/WebMailAjaxRemoteStorage.js'), kn = require('../Knoin/Knoin.js'), @@ -24,12 +25,10 @@ */ function SettingsAccounts() { - var oData = RL.data(); - - this.accounts = oData.accounts; + this.accounts = Data.accounts; this.processText = ko.computed(function () { - return oData.accountsLoading() ? Utils.i18n('SETTINGS_ACCOUNTS/LOADING_PROCESS') : ''; + return Data.accountsLoading() ? Utils.i18n('SETTINGS_ACCOUNTS/LOADING_PROCESS') : ''; }, this); this.visibility = ko.computed(function () { @@ -51,8 +50,6 @@ ]}); } - kn.addSettingsViewModel(SettingsAccounts, 'SettingsAccounts', 'SETTINGS_LABELS/LABEL_ACCOUNTS_NAME', 'accounts'); - SettingsAccounts.prototype.addNewAccount = function () { kn.showScreenPopup(PopupsAddAccountViewModel); @@ -68,6 +65,7 @@ this.accountForDeletion(null); var + RL = require('../Boots/RainLoopApp.js'), fRemoveAccount = function (oAccount) { return oAccountToRemove === oAccount; } diff --git a/dev/Settings/SettingsChangePassword.js b/dev/Settings/SettingsChangePassword.js index 2d06ce073..06c41ffaf 100644 --- a/dev/Settings/SettingsChangePassword.js +++ b/dev/Settings/SettingsChangePassword.js @@ -77,8 +77,6 @@ this.onChangePasswordResponse = _.bind(this.onChangePasswordResponse, this); } - kn.addSettingsViewModel(SettingsChangePassword, 'SettingsChangePassword', 'SETTINGS_LABELS/LABEL_CHANGE_PASSWORD_NAME', 'change-password'); - SettingsChangePassword.prototype.onHide = function () { this.changeProcess(false); diff --git a/dev/Settings/SettingsContacts.js b/dev/Settings/SettingsContacts.js index 1d402cabe..8f0a327ae 100644 --- a/dev/Settings/SettingsContacts.js +++ b/dev/Settings/SettingsContacts.js @@ -8,8 +8,10 @@ ko = require('../External/ko.js'), Utils = require('../Common/Utils.js'), + + Remote = require('../Storages/WebMailAjaxRemoteStorage.js'), - Remote = require('../Storages/WebMailAjaxRemoteStorage.js') + Data = require('../Storages/WebMailDataStorage.js') ; /** @@ -17,15 +19,13 @@ */ function SettingsContacts() { - var oData = RL.data(); + this.contactsAutosave = Data.contactsAutosave; - this.contactsAutosave = oData.contactsAutosave; - - this.allowContactsSync = oData.allowContactsSync; - this.enableContactsSync = oData.enableContactsSync; - this.contactsSyncUrl = oData.contactsSyncUrl; - this.contactsSyncUser = oData.contactsSyncUser; - this.contactsSyncPass = oData.contactsSyncPass; + this.allowContactsSync = Data.allowContactsSync; + this.enableContactsSync = Data.enableContactsSync; + this.contactsSyncUrl = Data.contactsSyncUrl; + this.contactsSyncUser = Data.contactsSyncUser; + this.contactsSyncPass = Data.contactsSyncPass; this.saveTrigger = ko.computed(function () { return [ @@ -46,11 +46,9 @@ }, this); } - kn.addSettingsViewModel(SettingsContacts, 'SettingsContacts', 'SETTINGS_LABELS/LABEL_CONTACTS_NAME', 'contacts'); - SettingsContacts.prototype.onBuild = function () { - RL.data().contactsAutosave.subscribe(function (bValue) { + Data.contactsAutosave.subscribe(function (bValue) { Remote.saveSettings(Utils.emptyFunction, { 'ContactsAutosave': bValue ? '1' : '0' }); diff --git a/dev/Settings/SettingsFilters.js b/dev/Settings/SettingsFilters.js index dafac3ff5..92cf2f966 100644 --- a/dev/Settings/SettingsFilters.js +++ b/dev/Settings/SettingsFilters.js @@ -7,6 +7,7 @@ var ko = require('../External/ko.js'), Utils = require('../Common/Utils.js'), + kn = require('../Knoin/Knoin.js'), PopupsFilterViewModel = require('../ViewModels/Popups/PopupsFilterViewModel.js') ; @@ -23,8 +24,6 @@ }); } - kn.addSettingsViewModel(SettingsFilters, 'SettingsFilters', 'SETTINGS_LABELS/LABEL_FILTERS_NAME', 'filters'); - SettingsFilters.prototype.deleteFilter = function (oFilter) { this.filters.remove(oFilter); diff --git a/dev/Settings/SettingsFolders.js b/dev/Settings/SettingsFolders.js index 7e77f6838..4261d7449 100644 --- a/dev/Settings/SettingsFolders.js +++ b/dev/Settings/SettingsFolders.js @@ -9,10 +9,16 @@ Enums = require('../Common/Enums.js'), Utils = require('../Common/Utils.js'), + kn = require('../Knoin/Knoin.js'), + + AppSettings = require('../Storages/AppSettings.js'), LocalStorage = require('../Storages/LocalStorage.js'), + Data = require('../Storages/WebMailDataStorage.js'), Cache = require('../Storages/WebMailCacheStorage.js'), Remote = require('../Storages/WebMailAjaxRemoteStorage.js'), - + + RL = require('../Boots/RainLoopApp.js'), + PopupsFolderCreateViewModel = require('../ViewModels/Popups/PopupsFolderCreateViewModel.js'), PopupsFolderSystemViewModel = require('../ViewModels/Popups/PopupsFolderSystemViewModel.js') ; @@ -22,19 +28,16 @@ */ function SettingsFolders() { - var oData = RL.data(); - - this.foldersListError = oData.foldersListError; - this.folderList = oData.folderList; + this.foldersListError = Data.foldersListError; + this.folderList = Data.folderList; this.processText = ko.computed(function () { var - oData = RL.data(), - bLoading = oData.foldersLoading(), - bCreating = oData.foldersCreating(), - bDeleting = oData.foldersDeleting(), - bRenaming = oData.foldersRenaming() + bLoading = Data.foldersLoading(), + bCreating = Data.foldersCreating(), + bDeleting = Data.foldersDeleting(), + bRenaming = Data.foldersRenaming() ; if (bCreating) @@ -90,11 +93,9 @@ } ]}); - this.useImapSubscribe = !!RL.settingsGet('UseImapSubscribe'); + this.useImapSubscribe = !!AppSettings.settingsGet('UseImapSubscribe'); } - kn.addSettingsViewModel(SettingsFolders, 'SettingsFolders', 'SETTINGS_LABELS/LABEL_FOLDERS_NAME', 'folders'); - SettingsFolders.prototype.folderEditOnEnter = function (oFolder) { var sEditName = oFolder ? Utils.trim(oFolder.nameForEdit()) : ''; @@ -102,13 +103,13 @@ { LocalStorage.set(Enums.ClientSideKeyName.FoldersLashHash, ''); - RL.data().foldersRenaming(true); + Data.foldersRenaming(true); Remote.folderRename(function (sResult, oData) { - RL.data().foldersRenaming(false); + Data.foldersRenaming(false); if (Enums.StorageResultType.Success !== sResult || !oData || !oData.Result) { - RL.data().foldersListError( + Data.foldersListError( oData && oData.ErrorCode ? Utils.getNotification(oData.ErrorCode) : Utils.i18n('NOTIFICATIONS/CANT_RENAME_FOLDER')); } @@ -134,7 +135,7 @@ SettingsFolders.prototype.onShow = function () { - RL.data().foldersListError(''); + Data.foldersListError(''); }; SettingsFolders.prototype.createFolder = function () @@ -171,15 +172,15 @@ { LocalStorage.set(Enums.ClientSideKeyName.FoldersLashHash, ''); - RL.data().folderList.remove(fRemoveFolder); + Data.folderList.remove(fRemoveFolder); - RL.data().foldersDeleting(true); + Data.foldersDeleting(true); Remote.folderDelete(function (sResult, oData) { - RL.data().foldersDeleting(false); + Data.foldersDeleting(false); if (Enums.StorageResultType.Success !== sResult || !oData || !oData.Result) { - RL.data().foldersListError( + Data.foldersListError( oData && oData.ErrorCode ? Utils.getNotification(oData.ErrorCode) : Utils.i18n('NOTIFICATIONS/CANT_DELETE_FOLDER')); } @@ -192,7 +193,7 @@ } else if (0 < oFolderToRemove.privateMessageCountAll()) { - RL.data().foldersListError(Utils.getNotification(Enums.Notification.CantDeleteNonEmptyFolder)); + Data.foldersListError(Utils.getNotification(Enums.Notification.CantDeleteNonEmptyFolder)); } }; diff --git a/dev/Settings/SettingsGeneral.js b/dev/Settings/SettingsGeneral.js index 7d95da09e..7581efda8 100644 --- a/dev/Settings/SettingsGeneral.js +++ b/dev/Settings/SettingsGeneral.js @@ -5,6 +5,7 @@ 'use strict'; var + $ = require('../External/jquery.js'), ko = require('../External/ko.js'), Enums = require('../Common/Enums.js'), @@ -13,6 +14,7 @@ Utils = require('../Common/Utils.js'), LinkBuilder = require('../Common/LinkBuilder.js'), + Data = require('../Storages/WebMailDataStorage.js'), Remote = require('../Storages/WebMailAjaxRemoteStorage.js'), kn = require('../Knoin/Knoin.js'), @@ -24,30 +26,28 @@ */ function SettingsGeneral() { - var oData = RL.data(); - - this.mainLanguage = oData.mainLanguage; - this.mainMessagesPerPage = oData.mainMessagesPerPage; + this.mainLanguage = Data.mainLanguage; + this.mainMessagesPerPage = Data.mainMessagesPerPage; this.mainMessagesPerPageArray = Consts.Defaults.MessagesPerPageArray; - this.editorDefaultType = oData.editorDefaultType; - this.showImages = oData.showImages; - this.interfaceAnimation = oData.interfaceAnimation; - this.useDesktopNotifications = oData.useDesktopNotifications; - this.threading = oData.threading; - this.useThreads = oData.useThreads; - this.replySameFolder = oData.replySameFolder; - this.layout = oData.layout; - this.usePreviewPane = oData.usePreviewPane; - this.useCheckboxesInList = oData.useCheckboxesInList; - this.allowLanguagesOnSettings = oData.allowLanguagesOnSettings; + this.editorDefaultType = Data.editorDefaultType; + this.showImages = Data.showImages; + this.interfaceAnimation = Data.interfaceAnimation; + this.useDesktopNotifications = Data.useDesktopNotifications; + this.threading = Data.threading; + this.useThreads = Data.useThreads; + this.replySameFolder = Data.replySameFolder; + this.layout = Data.layout; + this.usePreviewPane = Data.usePreviewPane; + this.useCheckboxesInList = Data.useCheckboxesInList; + this.allowLanguagesOnSettings = Data.allowLanguagesOnSettings; this.isDesktopNotificationsSupported = ko.computed(function () { - return Enums.DesktopNotifications.NotSupported !== oData.desktopNotificationsPermisions(); + return Enums.DesktopNotifications.NotSupported !== Data.desktopNotificationsPermisions(); }); this.isDesktopNotificationsDenied = ko.computed(function () { - return Enums.DesktopNotifications.NotSupported === oData.desktopNotificationsPermisions() || - Enums.DesktopNotifications.Denied === oData.desktopNotificationsPermisions(); + return Enums.DesktopNotifications.NotSupported === Data.desktopNotificationsPermisions() || + Enums.DesktopNotifications.Denied === Data.desktopNotificationsPermisions(); }); this.mainLanguageFullName = ko.computed(function () { @@ -60,8 +60,6 @@ this.isAnimationSupported = Globals.bAnimationSupported; } - kn.addSettingsViewModel(SettingsGeneral, 'SettingsGeneral', 'SETTINGS_LABELS/LABEL_GENERAL_NAME', 'general', true); - SettingsGeneral.prototype.toggleLayout = function () { this.layout(Enums.Layout.NoPreview === this.layout() ? Enums.Layout.SidePreview : Enums.Layout.NoPreview); @@ -74,11 +72,10 @@ _.delay(function () { var - oData = RL.data(), f1 = Utils.settingsSaveHelperSimpleFunction(self.mppTrigger, self) ; - oData.language.subscribe(function (sValue) { + Data.language.subscribe(function (sValue) { self.languageTrigger(Enums.SaveSettingsStep.Animate); @@ -102,31 +99,31 @@ }); }); - oData.editorDefaultType.subscribe(function (sValue) { + Data.editorDefaultType.subscribe(function (sValue) { Remote.saveSettings(Utils.emptyFunction, { 'EditorDefaultType': sValue }); }); - oData.messagesPerPage.subscribe(function (iValue) { + Data.messagesPerPage.subscribe(function (iValue) { Remote.saveSettings(f1, { 'MPP': iValue }); }); - oData.showImages.subscribe(function (bValue) { + Data.showImages.subscribe(function (bValue) { Remote.saveSettings(Utils.emptyFunction, { 'ShowImages': bValue ? '1' : '0' }); }); - oData.interfaceAnimation.subscribe(function (sValue) { + Data.interfaceAnimation.subscribe(function (sValue) { Remote.saveSettings(Utils.emptyFunction, { 'InterfaceAnimation': sValue }); }); - oData.useDesktopNotifications.subscribe(function (bValue) { + Data.useDesktopNotifications.subscribe(function (bValue) { Utils.timeOutAction('SaveDesktopNotifications', function () { Remote.saveSettings(Utils.emptyFunction, { 'DesktopNotifications': bValue ? '1' : '0' @@ -134,7 +131,7 @@ }, 3000); }); - oData.replySameFolder.subscribe(function (bValue) { + Data.replySameFolder.subscribe(function (bValue) { Utils.timeOutAction('SaveReplySameFolder', function () { Remote.saveSettings(Utils.emptyFunction, { 'ReplySameFolder': bValue ? '1' : '0' @@ -142,25 +139,25 @@ }, 3000); }); - oData.useThreads.subscribe(function (bValue) { + Data.useThreads.subscribe(function (bValue) { - oData.messageList([]); + Data.messageList([]); Remote.saveSettings(Utils.emptyFunction, { 'UseThreads': bValue ? '1' : '0' }); }); - oData.layout.subscribe(function (nValue) { + Data.layout.subscribe(function (nValue) { - oData.messageList([]); + Data.messageList([]); Remote.saveSettings(Utils.emptyFunction, { 'Layout': nValue }); }); - oData.useCheckboxesInList.subscribe(function (bValue) { + Data.useCheckboxesInList.subscribe(function (bValue) { Remote.saveSettings(Utils.emptyFunction, { 'UseCheckboxesInList': bValue ? '1' : '0' }); @@ -171,7 +168,7 @@ SettingsGeneral.prototype.onShow = function () { - RL.data().desktopNotifications.valueHasMutated(); + Data.desktopNotifications.valueHasMutated(); }; SettingsGeneral.prototype.selectLanguage = function () diff --git a/dev/Settings/SettingsIdentities.js b/dev/Settings/SettingsIdentities.js index f9db59549..0f0950b59 100644 --- a/dev/Settings/SettingsIdentities.js +++ b/dev/Settings/SettingsIdentities.js @@ -9,9 +9,13 @@ Enums = require('../Common/Enums.js'), Utils = require('../Common/Utils.js'), + NewHtmlEditorWrapper = require('../Common/NewHtmlEditorWrapper.js'), + Data = require('../Storages/WebMailDataStorage.js'), Remote = require('../Storages/WebMailAjaxRemoteStorage.js'), + RL = require('../Boots/RainLoopApp.js'), + kn = require('../Knoin/Knoin.js'), PopupsIdentityViewModel = require('../ViewModels/Popups/PopupsIdentityViewModel.js') ; @@ -21,16 +25,14 @@ */ function SettingsIdentities() { - var oData = RL.data(); - this.editor = null; this.defautOptionsAfterRender = Utils.defautOptionsAfterRender; - this.accountEmail = oData.accountEmail; - this.displayName = oData.displayName; - this.signature = oData.signature; - this.signatureToAll = oData.signatureToAll; - this.replyTo = oData.replyTo; + this.accountEmail = Data.accountEmail; + this.displayName = Data.displayName; + this.signature = Data.signature; + this.signatureToAll = Data.signatureToAll; + this.replyTo = Data.replyTo; this.signatureDom = ko.observable(null); @@ -39,8 +41,8 @@ this.replyTrigger = ko.observable(Enums.SaveSettingsStep.Idle); this.signatureTrigger = ko.observable(Enums.SaveSettingsStep.Idle); - this.identities = oData.identities; - this.defaultIdentityID = oData.defaultIdentityID; + this.identities = Data.identities; + this.defaultIdentityID = Data.defaultIdentityID; this.identitiesOptions = ko.computed(function () { @@ -77,7 +79,7 @@ }, this); this.processText = ko.computed(function () { - return oData.identitiesLoading() ? Utils.i18n('SETTINGS_IDENTITIES/LOADING_PROCESS') : ''; + return Data.identitiesLoading() ? Utils.i18n('SETTINGS_IDENTITIES/LOADING_PROCESS') : ''; }, this); this.visibility = ko.computed(function () { @@ -99,8 +101,6 @@ ]}); } - kn.addSettingsViewModel(SettingsIdentities, 'SettingsIdentities', 'SETTINGS_LABELS/LABEL_IDENTITIES_NAME', 'identities'); - /** * * @return {string} @@ -157,11 +157,11 @@ { var self = this, - sSignature = RL.data().signature() + sSignature = Data.signature() ; this.editor = new NewHtmlEditorWrapper(self.signatureDom(), function () { - RL.data().signature( + Data.signature( (self.editor.isHtml() ? ':HTML:' : '') + self.editor.getData() ); }, function () { @@ -194,38 +194,37 @@ _.delay(function () { var - oData = RL.data(), f1 = Utils.settingsSaveHelperSimpleFunction(self.displayNameTrigger, self), f2 = Utils.settingsSaveHelperSimpleFunction(self.replyTrigger, self), f3 = Utils.settingsSaveHelperSimpleFunction(self.signatureTrigger, self), f4 = Utils.settingsSaveHelperSimpleFunction(self.defaultIdentityIDTrigger, self) ; - oData.defaultIdentityID.subscribe(function (sValue) { + Data.defaultIdentityID.subscribe(function (sValue) { Remote.saveSettings(f4, { 'DefaultIdentityID': sValue }); }); - oData.displayName.subscribe(function (sValue) { + Data.displayName.subscribe(function (sValue) { Remote.saveSettings(f1, { 'DisplayName': sValue }); }); - oData.replyTo.subscribe(function (sValue) { + Data.replyTo.subscribe(function (sValue) { Remote.saveSettings(f2, { 'ReplyTo': sValue }); }); - oData.signature.subscribe(function (sValue) { + Data.signature.subscribe(function (sValue) { Remote.saveSettings(f3, { 'Signature': sValue }); }); - oData.signatureToAll.subscribe(function (bValue) { + Data.signatureToAll.subscribe(function (bValue) { Remote.saveSettings(null, { 'SignatureToAll': bValue ? '1' : '0' }); diff --git a/dev/Settings/SettingsIdentity.js b/dev/Settings/SettingsIdentity.js index b97bc233d..89945017e 100644 --- a/dev/Settings/SettingsIdentity.js +++ b/dev/Settings/SettingsIdentity.js @@ -9,7 +9,9 @@ Enums = require('../Common/Enums.js'), Utils = require('../Common/Utils.js'), + NewHtmlEditorWrapper = require('../Common/NewHtmlEditorWrapper.js'), + Data = require('../Storages/WebMailDataStorage.js'), Remote = require('../Storages/WebMailAjaxRemoteStorage.js') ; @@ -18,14 +20,12 @@ */ function SettingsIdentity() { - var oData = RL.data(); - this.editor = null; - this.displayName = oData.displayName; - this.signature = oData.signature; - this.signatureToAll = oData.signatureToAll; - this.replyTo = oData.replyTo; + this.displayName = Data.displayName; + this.signature = Data.signature; + this.signatureToAll = Data.signatureToAll; + this.replyTo = Data.replyTo; this.signatureDom = ko.observable(null); @@ -34,19 +34,17 @@ this.signatureTrigger = ko.observable(Enums.SaveSettingsStep.Idle); } - kn.addSettingsViewModel(SettingsIdentity, 'SettingsIdentity', 'SETTINGS_LABELS/LABEL_IDENTITY_NAME', 'identity'); - SettingsIdentity.prototype.onFocus = function () { if (!this.editor && this.signatureDom()) { var self = this, - sSignature = RL.data().signature() + sSignature = Data.signature() ; this.editor = new NewHtmlEditorWrapper(self.signatureDom(), function () { - RL.data().signature( + Data.signature( (self.editor.isHtml() ? ':HTML:' : '') + self.editor.getData() ); }, function () { @@ -68,31 +66,30 @@ _.delay(function () { var - oData = RL.data(), f1 = Utils.settingsSaveHelperSimpleFunction(self.displayNameTrigger, self), f2 = Utils.settingsSaveHelperSimpleFunction(self.replyTrigger, self), f3 = Utils.settingsSaveHelperSimpleFunction(self.signatureTrigger, self) ; - oData.displayName.subscribe(function (sValue) { + Data.displayName.subscribe(function (sValue) { Remote.saveSettings(f1, { 'DisplayName': sValue }); }); - oData.replyTo.subscribe(function (sValue) { + Data.replyTo.subscribe(function (sValue) { Remote.saveSettings(f2, { 'ReplyTo': sValue }); }); - oData.signature.subscribe(function (sValue) { + Data.signature.subscribe(function (sValue) { Remote.saveSettings(f3, { 'Signature': sValue }); }); - oData.signatureToAll.subscribe(function (bValue) { + Data.signatureToAll.subscribe(function (bValue) { Remote.saveSettings(null, { 'SignatureToAll': bValue ? '1' : '0' }); diff --git a/dev/Settings/SettingsOpenPGP.js b/dev/Settings/SettingsOpenPGP.js index 6e05440e3..858c686c2 100644 --- a/dev/Settings/SettingsOpenPGP.js +++ b/dev/Settings/SettingsOpenPGP.js @@ -6,7 +6,12 @@ var ko = require('../External/ko.js'), - Utils = require('../Common/Utils.js'), + + kn = require('../Knoin/Knoin.js'), + + Data = require('../Storages/WebMailDataStorage.js'), + + RL = require('../Boots/RainLoopApp.js'), PopupsAddOpenPgpKeyViewModel = require('../ViewModels/Popups/PopupsAddOpenPgpKeyViewModel.js'), PopupsGenerateNewOpenPgpKeyViewModel = require('../ViewModels/Popups/PopupsGenerateNewOpenPgpKeyViewModel.js'), @@ -18,9 +23,9 @@ */ function SettingsOpenPGP() { - this.openpgpkeys = RL.data().openpgpkeys; - this.openpgpkeysPublic = RL.data().openpgpkeysPublic; - this.openpgpkeysPrivate = RL.data().openpgpkeysPrivate; + this.openpgpkeys = Data.openpgpkeys; + this.openpgpkeysPublic = Data.openpgpkeysPublic; + this.openpgpkeysPrivate = Data.openpgpkeysPrivate; this.openPgpKeyForDeletion = ko.observable(null).extend({'falseTimeout': 3000}).extend({'toggleSubscribe': [this, function (oPrev) { @@ -37,8 +42,6 @@ ]}); } - kn.addSettingsViewModel(SettingsOpenPGP, 'SettingsOpenPGP', 'SETTINGS_LABELS/LABEL_OPEN_PGP_NAME', 'openpgp'); - SettingsOpenPGP.prototype.addOpenPgpKey = function () { kn.showScreenPopup(PopupsAddOpenPgpKeyViewModel); @@ -66,16 +69,16 @@ { this.openPgpKeyForDeletion(null); - if (oOpenPgpKeyToRemove && RL.data().openpgpKeyring) + if (oOpenPgpKeyToRemove && Data.openpgpKeyring) { this.openpgpkeys.remove(function (oOpenPgpKey) { return oOpenPgpKeyToRemove === oOpenPgpKey; }); - RL.data().openpgpKeyring[oOpenPgpKeyToRemove.isPrivate ? 'privateKeys' : 'publicKeys'] + Data.openpgpKeyring[oOpenPgpKeyToRemove.isPrivate ? 'privateKeys' : 'publicKeys'] .removeForId(oOpenPgpKeyToRemove.guid); - RL.data().openpgpKeyring.store(); + Data.openpgpKeyring.store(); RL.reloadOpenPgpKeys(); } diff --git a/dev/Settings/SettingsSecurity.js b/dev/Settings/SettingsSecurity.js index 5098ebe87..a9167ee2e 100644 --- a/dev/Settings/SettingsSecurity.js +++ b/dev/Settings/SettingsSecurity.js @@ -7,7 +7,7 @@ var ko = require('../External/ko.js'), - Enums = require('../Common/Utils.js'), + Enums = require('../Common/Enums.js'), Globals = require('../Common/Globals.js'), Utils = require('../Common/Utils.js'), @@ -50,8 +50,6 @@ this.onSecretResult = _.bind(this.onSecretResult, this); } - kn.addSettingsViewModel(SettingsSecurity, 'SettingsSecurity', 'SETTINGS_LABELS/LABEL_SECURITY_NAME', 'security'); - SettingsSecurity.prototype.showSecret = function () { this.secreting(true); diff --git a/dev/Settings/SettingsSocial.js b/dev/Settings/SettingsSocial.js index f25655fbb..b76f40de6 100644 --- a/dev/Settings/SettingsSocial.js +++ b/dev/Settings/SettingsSocial.js @@ -5,7 +5,11 @@ 'use strict'; var - Utils = require('../Common/Utils.js') + Utils = require('../Common/Utils.js'), + + Data = require('../Storages/WebMailDataStorage.js'), + + RL = require('../Boots/RainLoopApp.js') ; /** @@ -13,25 +17,23 @@ */ function SettingsSocial() { - var oData = RL.data(); + this.googleEnable = Data.googleEnable; - this.googleEnable = oData.googleEnable; + this.googleActions = Data.googleActions; + this.googleLoggined = Data.googleLoggined; + this.googleUserName = Data.googleUserName; - this.googleActions = oData.googleActions; - this.googleLoggined = oData.googleLoggined; - this.googleUserName = oData.googleUserName; + this.facebookEnable = Data.facebookEnable; - this.facebookEnable = oData.facebookEnable; + this.facebookActions = Data.facebookActions; + this.facebookLoggined = Data.facebookLoggined; + this.facebookUserName = Data.facebookUserName; - this.facebookActions = oData.facebookActions; - this.facebookLoggined = oData.facebookLoggined; - this.facebookUserName = oData.facebookUserName; + this.twitterEnable = Data.twitterEnable; - this.twitterEnable = oData.twitterEnable; - - this.twitterActions = oData.twitterActions; - this.twitterLoggined = oData.twitterLoggined; - this.twitterUserName = oData.twitterUserName; + this.twitterActions = Data.twitterActions; + this.twitterLoggined = Data.twitterLoggined; + this.twitterUserName = Data.twitterUserName; this.connectGoogle = Utils.createCommand(this, function () { if (!this.googleLoggined()) @@ -73,8 +75,6 @@ }); } - kn.addSettingsViewModel(SettingsSocial, 'SettingsSocial', 'SETTINGS_LABELS/LABEL_SOCIAL_NAME', 'social'); - module.exports = SettingsSocial; }(module)); \ No newline at end of file diff --git a/dev/Settings/SettingsThemes.js b/dev/Settings/SettingsThemes.js index bd8effd0c..40f3842b4 100644 --- a/dev/Settings/SettingsThemes.js +++ b/dev/Settings/SettingsThemes.js @@ -12,7 +12,8 @@ Enums = require('../Common/Enums.js'), Utils = require('../Common/Utils.js'), LinkBuilder = require('../Common/LinkBuilder.js'), - + + Data = require('../Storages/WebMailDataStorage.js'), Remote = require('../Storages/WebMailAjaxRemoteStorage.js') ; @@ -21,12 +22,9 @@ */ function SettingsThemes() { - var - self = this, - oData = RL.data() - ; + var self = this; - this.mainTheme = oData.mainTheme; + this.mainTheme = Data.mainTheme; this.themesObjects = ko.observableArray([]); this.themeTrigger = ko.observable(Enums.SaveSettingsStep.Idle).extend({'throttle': 100}); @@ -34,7 +32,7 @@ this.oLastAjax = null; this.iTimer = 0; - RL.data().theme.subscribe(function (sValue) { + Data.theme.subscribe(function (sValue) { _.each(this.themesObjects(), function (oTheme) { oTheme.selected(sValue === oTheme.name); @@ -116,12 +114,10 @@ }, this); } - kn.addSettingsViewModel(SettingsThemes, 'SettingsThemes', 'SETTINGS_LABELS/LABEL_THEMES_NAME', 'themes'); - SettingsThemes.prototype.onBuild = function () { - var sCurrentTheme = RL.data().theme(); - this.themesObjects(_.map(RL.data().themes(), function (sTheme) { + var sCurrentTheme = Data.theme(); + this.themesObjects(_.map(Data.themes(), function (sTheme) { return { 'name': sTheme, 'nameDisplay': Utils.convertThemeName(sTheme), diff --git a/dev/Storages/AbstractAjaxRemoteStorage.js b/dev/Storages/AbstractAjaxRemoteStorage.js index e325b8edb..cf077a932 100644 --- a/dev/Storages/AbstractAjaxRemoteStorage.js +++ b/dev/Storages/AbstractAjaxRemoteStorage.js @@ -15,7 +15,7 @@ Plugins = require('../Common/Plugins.js'), LinkBuilder = require('../Common/LinkBuilder.js'), - RL = require('../RL.js') + AppSettings = require('./AppSettings.js') ; /** @@ -63,7 +63,10 @@ if (Consts.Values.TokenErrorLimit < Globals.iTokenErrorCount) { - RL().loginAndLogoutReload(true); + if (Globals.__RL) + { + Globals.__RL.loginAndLogoutReload(true); + } } if (oData.Logout || Consts.Values.AjaxErrorLimit < Globals.iAjaxErrorCount) @@ -73,7 +76,10 @@ window.__rlah_clear(); } - RL().loginAndLogoutReload(true); + if (Globals.__RL) + { + Globals.__RL.loginAndLogoutReload(true); + } } } else if (Enums.StorageResultType.Success === sType && oData && oData.Result) @@ -163,7 +169,7 @@ if (bPost) { - oParameters['XToken'] = RL.settingsGet('Token'); // TODO cjs + oParameters['XToken'] = AppSettings.settingsGet('Token'); } oDefAjax = $.ajax({ diff --git a/dev/Storages/AbstractData.js b/dev/Storages/AbstractData.js index 2c696980d..f80538657 100644 --- a/dev/Storages/AbstractData.js +++ b/dev/Storages/AbstractData.js @@ -5,11 +5,10 @@ 'use strict'; var - ko = require('../External/ko.js'), - key = require('../External/key.js'), Enums = require('../Common/Enums.js'), - Globals = require('../Common/Globals.js'), - Utils = require('../Common/Utils.js') + Utils = require('../Common/Utils.js'), + + AppSettings = require('./AppSettings.js') ; /** @@ -17,71 +16,15 @@ */ function AbstractData() { - this.leftPanelDisabled = ko.observable(false); - this.useKeyboardShortcuts = ko.observable(true); - - this.keyScopeReal = ko.observable(Enums.KeyState.All); - this.keyScopeFake = ko.observable(Enums.KeyState.All); - - this.keyScope = ko.computed({ - 'owner': this, - 'read': function () { - return this.keyScopeFake(); - }, - 'write': function (sValue) { - - if (Enums.KeyState.Menu !== sValue) - { - if (Enums.KeyState.Compose === sValue) - { - Utils.disableKeyFilter(); - } - else - { - Utils.restoreKeyFilter(); - } - - this.keyScopeFake(sValue); - if (Globals.dropdownVisibility()) - { - sValue = Enums.KeyState.Menu; - } - } - - this.keyScopeReal(sValue); - } - }); - - this.keyScopeReal.subscribe(function (sValue) { - // window.console.log(sValue); - key.setScope(sValue); - }); - - this.leftPanelDisabled.subscribe(function (bValue) { - RL.pub('left-panel.' + (bValue ? 'off' : 'on')); // TODO cjs - }); - - Globals.dropdownVisibility.subscribe(function (bValue) { - if (bValue) - { - Globals.tooltipTrigger(!Globals.tooltipTrigger()); - this.keyScope(Enums.KeyState.Menu); - } - else if (Enums.KeyState.Menu === key.getScope()) - { - this.keyScope(this.keyScopeFake()); - } - }, this); - Utils.initDataConstructorBySettings(this); } AbstractData.prototype.populateDataOnStart = function() { var - mLayout = Utils.pInt(RL.settingsGet('Layout')), // TODO cjs - aLanguages = RL.settingsGet('Languages'), - aThemes = RL.settingsGet('Themes') + mLayout = Utils.pInt(AppSettings.settingsGet('Layout')), + aLanguages = AppSettings.settingsGet('Languages'), + aThemes = AppSettings.settingsGet('Themes') ; if (Utils.isArray(aLanguages)) @@ -94,55 +37,55 @@ this.themes(aThemes); } - this.mainLanguage(RL.settingsGet('Language')); - this.mainTheme(RL.settingsGet('Theme')); + this.mainLanguage(AppSettings.settingsGet('Language')); + this.mainTheme(AppSettings.settingsGet('Theme')); - this.capaAdditionalAccounts(RL.capa(Enums.Capa.AdditionalAccounts)); - this.capaAdditionalIdentities(RL.capa(Enums.Capa.AdditionalIdentities)); - this.capaGravatar(RL.capa(Enums.Capa.Gravatar)); - this.determineUserLanguage(!!RL.settingsGet('DetermineUserLanguage')); - this.determineUserDomain(!!RL.settingsGet('DetermineUserDomain')); + this.capaAdditionalAccounts(AppSettings.capa(Enums.Capa.AdditionalAccounts)); + this.capaAdditionalIdentities(AppSettings.capa(Enums.Capa.AdditionalIdentities)); + this.capaGravatar(AppSettings.capa(Enums.Capa.Gravatar)); + this.determineUserLanguage(!!AppSettings.settingsGet('DetermineUserLanguage')); + this.determineUserDomain(!!AppSettings.settingsGet('DetermineUserDomain')); - this.capaThemes(RL.capa(Enums.Capa.Themes)); - this.allowLanguagesOnLogin(!!RL.settingsGet('AllowLanguagesOnLogin')); - this.allowLanguagesOnSettings(!!RL.settingsGet('AllowLanguagesOnSettings')); - this.useLocalProxyForExternalImages(!!RL.settingsGet('UseLocalProxyForExternalImages')); + this.capaThemes(AppSettings.capa(Enums.Capa.Themes)); + this.allowLanguagesOnLogin(!!AppSettings.settingsGet('AllowLanguagesOnLogin')); + this.allowLanguagesOnSettings(!!AppSettings.settingsGet('AllowLanguagesOnSettings')); + this.useLocalProxyForExternalImages(!!AppSettings.settingsGet('UseLocalProxyForExternalImages')); - this.editorDefaultType(RL.settingsGet('EditorDefaultType')); - this.showImages(!!RL.settingsGet('ShowImages')); - this.contactsAutosave(!!RL.settingsGet('ContactsAutosave')); - this.interfaceAnimation(RL.settingsGet('InterfaceAnimation')); + this.editorDefaultType(AppSettings.settingsGet('EditorDefaultType')); + this.showImages(!!AppSettings.settingsGet('ShowImages')); + this.contactsAutosave(!!AppSettings.settingsGet('ContactsAutosave')); + this.interfaceAnimation(AppSettings.settingsGet('InterfaceAnimation')); - this.mainMessagesPerPage(RL.settingsGet('MPP')); + this.mainMessagesPerPage(AppSettings.settingsGet('MPP')); - this.desktopNotifications(!!RL.settingsGet('DesktopNotifications')); - this.useThreads(!!RL.settingsGet('UseThreads')); - this.replySameFolder(!!RL.settingsGet('ReplySameFolder')); - this.useCheckboxesInList(!!RL.settingsGet('UseCheckboxesInList')); + this.desktopNotifications(!!AppSettings.settingsGet('DesktopNotifications')); + this.useThreads(!!AppSettings.settingsGet('UseThreads')); + this.replySameFolder(!!AppSettings.settingsGet('ReplySameFolder')); + this.useCheckboxesInList(!!AppSettings.settingsGet('UseCheckboxesInList')); this.layout(Enums.Layout.SidePreview); if (-1 < Utils.inArray(mLayout, [Enums.Layout.NoPreview, Enums.Layout.SidePreview, Enums.Layout.BottomPreview])) { this.layout(mLayout); } - this.facebookSupported(!!RL.settingsGet('SupportedFacebookSocial')); - this.facebookEnable(!!RL.settingsGet('AllowFacebookSocial')); - this.facebookAppID(RL.settingsGet('FacebookAppID')); - this.facebookAppSecret(RL.settingsGet('FacebookAppSecret')); + this.facebookSupported(!!AppSettings.settingsGet('SupportedFacebookSocial')); + this.facebookEnable(!!AppSettings.settingsGet('AllowFacebookSocial')); + this.facebookAppID(AppSettings.settingsGet('FacebookAppID')); + this.facebookAppSecret(AppSettings.settingsGet('FacebookAppSecret')); - this.twitterEnable(!!RL.settingsGet('AllowTwitterSocial')); - this.twitterConsumerKey(RL.settingsGet('TwitterConsumerKey')); - this.twitterConsumerSecret(RL.settingsGet('TwitterConsumerSecret')); + this.twitterEnable(!!AppSettings.settingsGet('AllowTwitterSocial')); + this.twitterConsumerKey(AppSettings.settingsGet('TwitterConsumerKey')); + this.twitterConsumerSecret(AppSettings.settingsGet('TwitterConsumerSecret')); - this.googleEnable(!!RL.settingsGet('AllowGoogleSocial')); - this.googleClientID(RL.settingsGet('GoogleClientID')); - this.googleClientSecret(RL.settingsGet('GoogleClientSecret')); - this.googleApiKey(RL.settingsGet('GoogleApiKey')); + this.googleEnable(!!AppSettings.settingsGet('AllowGoogleSocial')); + this.googleClientID(AppSettings.settingsGet('GoogleClientID')); + this.googleClientSecret(AppSettings.settingsGet('GoogleClientSecret')); + this.googleApiKey(AppSettings.settingsGet('GoogleApiKey')); - this.dropboxEnable(!!RL.settingsGet('AllowDropboxSocial')); - this.dropboxApiKey(RL.settingsGet('DropboxApiKey')); + this.dropboxEnable(!!AppSettings.settingsGet('AllowDropboxSocial')); + this.dropboxApiKey(AppSettings.settingsGet('DropboxApiKey')); - this.contactsIsAllowed(!!RL.settingsGet('ContactsIsAllowed')); + this.contactsIsAllowed(!!AppSettings.settingsGet('ContactsIsAllowed')); }; module.exports = AbstractData; diff --git a/dev/Storages/AdminAjaxRemoteStorage.js b/dev/Storages/AdminAjaxRemoteStorage.js index 28ff78859..d5d147d52 100644 --- a/dev/Storages/AdminAjaxRemoteStorage.js +++ b/dev/Storages/AdminAjaxRemoteStorage.js @@ -6,6 +6,7 @@ var _ = require('../External/underscore.js'), + AbstractAjaxRemoteStorage = require('./AbstractAjaxRemoteStorage.js') ; diff --git a/dev/Storages/AppSettings.js b/dev/Storages/AppSettings.js new file mode 100644 index 000000000..2c6e64ddf --- /dev/null +++ b/dev/Storages/AppSettings.js @@ -0,0 +1,64 @@ +/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */ + +(function (module) { + + 'use strict'; + + var + AppData = require('../External/AppData.js'), + + Utils = require('../Common/Utils.js') + ; + + /** + * @constructor + */ + function AppSettings() + { + this.oSettings = null; + } + + AppSettings.prototype.oSettings = null; + + /** + * @param {string} sName + * @return {?} + */ + AppSettings.prototype.settingsGet = function (sName) + { + if (null === this.oSettings) + { + this.oSettings = Utils.isNormal(AppData) ? AppData : {}; + } + + return Utils.isUnd(this.oSettings[sName]) ? null : this.oSettings[sName]; + }; + + /** + * @param {string} sName + * @param {?} mValue + */ + AppSettings.prototype.settingsSet = function (sName, mValue) + { + if (null === this.oSettings) + { + this.oSettings = Utils.isNormal(AppData) ? AppData : {}; + } + + this.oSettings[sName] = mValue; + }; + + /** + * @param {string} sName + * @return {boolean} + */ + AppSettings.prototype.capa = function (sName) + { + var mCapa = this.settingsGet('Capa'); + return Utils.isArray(mCapa) && Utils.isNormal(sName) && -1 < Utils.inArray(sName, mCapa); + }; + + + module.exports = new AppSettings(); + +}(module)); \ No newline at end of file diff --git a/dev/Storages/LocalStorage.js b/dev/Storages/LocalStorage.js index 76e3e18c4..b2c082270 100644 --- a/dev/Storages/LocalStorage.js +++ b/dev/Storages/LocalStorage.js @@ -6,6 +6,7 @@ var _ = require('../External/underscore.js'), + CookieDriver = require('./LocalStorages/CookieDriver.js'), LocalStorageDriver = require('./LocalStorages/LocalStorageDriver.js') ; diff --git a/dev/Storages/WebMailAjaxRemoteStorage.js b/dev/Storages/WebMailAjaxRemoteStorage.js index 796a4842e..c8437969d 100644 --- a/dev/Storages/WebMailAjaxRemoteStorage.js +++ b/dev/Storages/WebMailAjaxRemoteStorage.js @@ -8,8 +8,13 @@ _ = require('../External/underscore.js'), Utils = require('../Common/Utils.js'), + Consts = require('../Common/Consts.js'), + Globals = require('../Common/Globals.js'), + Base64 = require('../Common/Base64.js'), - Cache = require('../Storages/WebMailCacheStorage.js'), + AppSettings = require('./AppSettings.js'), + Cache = require('./WebMailCacheStorage.js'), + Data = require('./WebMailDataStorage.js'), AbstractAjaxRemoteStorage = require('./AbstractAjaxRemoteStorage.js') ; @@ -33,11 +38,11 @@ WebMailAjaxRemoteStorage.prototype.folders = function (fCallback) { this.defaultRequest(fCallback, 'Folders', { - 'SentFolder': RL.settingsGet('SentFolder'), - 'DraftFolder': RL.settingsGet('DraftFolder'), - 'SpamFolder': RL.settingsGet('SpamFolder'), - 'TrashFolder': RL.settingsGet('TrashFolder'), - 'ArchiveFolder': RL.settingsGet('ArchiveFolder') + 'SentFolder': AppSettings.settingsGet('SentFolder'), + 'DraftFolder': AppSettings.settingsGet('DraftFolder'), + 'SpamFolder': AppSettings.settingsGet('SpamFolder'), + 'TrashFolder': AppSettings.settingsGet('TrashFolder'), + 'ArchiveFolder': AppSettings.settingsGet('ArchiveFolder') }, null, '', ['Folders']); }; @@ -228,7 +233,6 @@ sFolderFullNameRaw = Utils.pString(sFolderFullNameRaw); var - oData = RL.data(), sFolderHash = Cache.getFolderHash(sFolderFullNameRaw) ; @@ -246,11 +250,11 @@ iOffset, iLimit, sSearch, - oData.projectHash(), + Data.projectHash(), sFolderHash, 'INBOX' === sFolderFullNameRaw ? Cache.getFolderUidNext(sFolderFullNameRaw) : '', - oData.threading() && oData.useThreads() ? '1' : '0', - oData.threading() && sFolderFullNameRaw === oData.messageListThreadFolder() ? oData.messageListThreadUids().join(',') : '' + Data.threading() && Data.useThreads() ? '1' : '0', + Data.threading() && sFolderFullNameRaw === Data.messageListThreadFolder() ? Data.messageListThreadUids().join(',') : '' ].join(String.fromCharCode(0))), bSilent ? [] : ['MessageList']); } else @@ -261,8 +265,8 @@ 'Limit': iLimit, 'Search': sSearch, 'UidNext': 'INBOX' === sFolderFullNameRaw ? Cache.getFolderUidNext(sFolderFullNameRaw) : '', - 'UseThreads': RL.data().threading() && RL.data().useThreads() ? '1' : '0', - 'ExpandedThreadUid': oData.threading() && sFolderFullNameRaw === oData.messageListThreadFolder() ? oData.messageListThreadUids().join(',') : '' + 'UseThreads': Data.threading() && Data.useThreads() ? '1' : '0', + 'ExpandedThreadUid': Data.threading() && sFolderFullNameRaw === Data.messageListThreadFolder() ? Data.messageListThreadUids().join(',') : '' }, '' === sSearch ? Consts.Defaults.DefaultAjaxTimeout : Consts.Defaults.SearchAjaxTimeout, '', bSilent ? [] : ['MessageList']); } }; @@ -295,8 +299,8 @@ 'Message/' + Base64.urlsafe_encode([ sFolderFullNameRaw, iUid, - RL.data().projectHash(), - RL.data().threading() && RL.data().useThreads() ? '1' : '0' + Data.projectHash(), + Data.threading() && Data.useThreads() ? '1' : '0' ].join(String.fromCharCode(0))), ['Message']); return true; @@ -375,9 +379,12 @@ 'UidNext': 'INBOX' === sFolder ? Cache.getFolderUidNext(sFolder) : '' }); } - else if (RL.data().useThreads()) + else if (Data.useThreads()) { - RL.reloadFlagsCurrentMessageListAndMessageFromCache(); + if (Globals.__RL) + { + Globals.__RL.reloadFlagsCurrentMessageListAndMessageFromCache(); + } } }; diff --git a/dev/Storages/WebMailCacheStorage.js b/dev/Storages/WebMailCacheStorage.js index 5c541d2d9..af88cf025 100644 --- a/dev/Storages/WebMailCacheStorage.js +++ b/dev/Storages/WebMailCacheStorage.js @@ -11,7 +11,7 @@ Utils = require('../Common/Utils.js'), LinkBuilder = require('../Common/LinkBuilder.js'), - RL = require('../RL.js') + AppSettings = require('./AppSettings.js') ; /** @@ -28,7 +28,7 @@ this.oNewMessage = {}; this.oRequestedMessage = {}; - this.bCapaGravatar = RL().capa(Enums.Capa.Gravatar); + this.bCapaGravatar = AppSettings.capa(Enums.Capa.Gravatar); } /** diff --git a/dev/Storages/WebMailDataStorage.js b/dev/Storages/WebMailDataStorage.js index 6e0971c5c..ecbdaa68c 100644 --- a/dev/Storages/WebMailDataStorage.js +++ b/dev/Storages/WebMailDataStorage.js @@ -19,11 +19,11 @@ Utils = require('../Common/Utils.js'), LinkBuilder = require('../Common/LinkBuilder.js'), - Cache = require('../Storages/WebMailCacheStorage.js'), - Remote = require('../Storages/WebMailAjaxRemoteStorage.js'), + AppSettings = require('./AppSettings.js'), + Cache = require('./WebMailCacheStorage.js'), kn = require('../Knoin/Knoin.js'), - + MessageModel = require('../Models/MessageModel.js'), LocalStorage = require('./LocalStorage.js'), @@ -41,7 +41,7 @@ var fRemoveSystemFolderType = function (observable) { return function () { - var oFolder = Cache.getFolderFromCacheList(observable()); // TODO cjs + var oFolder = Cache.getFolderFromCacheList(observable()); if (oFolder) { oFolder.type(Enums.FolderType.User); @@ -50,7 +50,7 @@ }, fSetSystemFolderType = function (iType) { return function (sValue) { - var oFolder = Cache.getFolderFromCacheList(sValue); // TODO cjs + var oFolder = Cache.getFolderFromCacheList(sValue); if (oFolder) { oFolder.type(iType); @@ -127,11 +127,11 @@ this.contactsSyncUser = ko.observable(''); this.contactsSyncPass = ko.observable(''); - this.allowContactsSync = ko.observable(!!RL.settingsGet('ContactsSyncIsAllowed')); // TODO cjs - this.enableContactsSync = ko.observable(!!RL.settingsGet('EnableContactsSync')); - this.contactsSyncUrl = ko.observable(RL.settingsGet('ContactsSyncUrl')); - this.contactsSyncUser = ko.observable(RL.settingsGet('ContactsSyncUser')); - this.contactsSyncPass = ko.observable(RL.settingsGet('ContactsSyncPassword')); + this.allowContactsSync = ko.observable(!!AppSettings.settingsGet('ContactsSyncIsAllowed')); + this.enableContactsSync = ko.observable(!!AppSettings.settingsGet('EnableContactsSync')); + this.contactsSyncUrl = ko.observable(AppSettings.settingsGet('ContactsSyncUrl')); + this.contactsSyncUser = ko.observable(AppSettings.settingsGet('ContactsSyncUser')); + this.contactsSyncPass = ko.observable(AppSettings.settingsGet('ContactsSyncPassword')); // folders this.namespace = ''; @@ -229,12 +229,12 @@ this.folderListSystem = ko.computed(function () { return _.compact(_.map(this.folderListSystemNames(), function (sName) { - return Cache.getFolderFromCacheList(sName); // TODO cjs + return Cache.getFolderFromCacheList(sName); })); }, this); this.folderMenuForMove = ko.computed(function () { - return RL.folderListOptionsBuilder(this.folderListSystem(), this.folderList(), [// TODO cjs + return Utils.folderListOptionsBuilder(this.folderListSystem(), this.folderList(), [ this.currentFolderFullNameRaw() ], null, null, null, null, function (oItem) { return oItem ? oItem.localName() : ''; @@ -273,7 +273,7 @@ this.mainMessageListSearch = ko.computed({ 'read': this.messageListSearch, 'write': function (sValue) { - kn.setHash(LinkBuilder.mailBox( // TODO cjs + kn.setHash(LinkBuilder.mailBox( this.currentFolderFullNameHash(), 1, Utils.trim(sValue.toString()) )); }, @@ -308,7 +308,7 @@ }, 500)); // message preview - this.staticMessageList = new MessageModel();// TODO cjs + this.staticMessageList = new MessageModel(); this.message = ko.observable(null); this.messageLoading = ko.observable(false); this.messageLoadingThrottle = ko.observable(false).extend({'throttle': 50}); @@ -322,10 +322,10 @@ this.messageFullScreenMode(false); this.hideMessageBodies(); - if (Enums.Layout.NoPreview === RL.data().layout() &&// TODO cjs + if (Enums.Layout.NoPreview === this.layout() && -1 < window.location.hash.indexOf('message-preview')) { - RL.historyBack();// TODO cjs + RL.historyBack(); // TODO cjs } } else if (Enums.Layout.NoPreview === this.layout()) @@ -338,17 +338,17 @@ if (bValue) { this.folderList.focused(false); - this.keyScope(Enums.KeyState.MessageView); + Globals.keyScope(Enums.KeyState.MessageView); } - else if (Enums.KeyState.MessageView === RL.data().keyScope())// TODO cjs + else if (Enums.KeyState.MessageView === Globals.keyScope()) { - if (Enums.Layout.NoPreview === RL.data().layout() && this.message())// TODO cjs + if (Enums.Layout.NoPreview === this.layout() && this.message()) { - this.keyScope(Enums.KeyState.MessageView); + Globals.keyScope(Enums.KeyState.MessageView); } else { - this.keyScope(Enums.KeyState.MessageList); + Globals.keyScope(Enums.KeyState.MessageList); } } }, this); @@ -356,11 +356,11 @@ this.folderList.focused.subscribe(function (bValue) { if (bValue) { - RL.data().keyScope(Enums.KeyState.FolderList);// TODO cjs + Globals.keyScope(Enums.KeyState.FolderList); } - else if (Enums.KeyState.FolderList === RL.data().keyScope())// TODO cjs + else if (Enums.KeyState.FolderList === Globals.keyScope()) { - RL.data().keyScope(Enums.KeyState.MessageList);// TODO cjs + Globals.keyScope(Enums.KeyState.MessageList); } }); @@ -510,25 +510,25 @@ { AbstractData.prototype.populateDataOnStart.call(this); - this.accountEmail(RL.settingsGet('Email'));// TODO cjs - this.accountIncLogin(RL.settingsGet('IncLogin')); - this.accountOutLogin(RL.settingsGet('OutLogin')); - this.projectHash(RL.settingsGet('ProjectHash')); + this.accountEmail(AppSettings.settingsGet('Email')); + this.accountIncLogin(AppSettings.settingsGet('IncLogin')); + this.accountOutLogin(AppSettings.settingsGet('OutLogin')); + this.projectHash(AppSettings.settingsGet('ProjectHash')); - this.defaultIdentityID(RL.settingsGet('DefaultIdentityID')); + this.defaultIdentityID(AppSettings.settingsGet('DefaultIdentityID')); - this.displayName(RL.settingsGet('DisplayName')); - this.replyTo(RL.settingsGet('ReplyTo')); - this.signature(RL.settingsGet('Signature')); - this.signatureToAll(!!RL.settingsGet('SignatureToAll')); - this.enableTwoFactor(!!RL.settingsGet('EnableTwoFactor')); + this.displayName(AppSettings.settingsGet('DisplayName')); + this.replyTo(AppSettings.settingsGet('ReplyTo')); + this.signature(AppSettings.settingsGet('Signature')); + this.signatureToAll(!!AppSettings.settingsGet('SignatureToAll')); + this.enableTwoFactor(!!AppSettings.settingsGet('EnableTwoFactor')); this.lastFoldersHash = LocalStorage.get(Enums.ClientSideKeyName.FoldersLashHash) || ''; - this.remoteSuggestions = !!RL.settingsGet('RemoteSuggestions'); + this.remoteSuggestions = !!AppSettings.settingsGet('RemoteSuggestions'); - this.devEmail = RL.settingsGet('DevEmail'); - this.devPassword = RL.settingsGet('DevPassword'); + this.devEmail = AppSettings.settingsGet('DevEmail'); + this.devPassword = AppSettings.settingsGet('DevPassword'); }; WebMailDataStorage.prototype.initUidNextAndNewMessages = function (sFolder, sUidNext, aNewMessages) @@ -538,12 +538,13 @@ if (Utils.isArray(aNewMessages) && 0 < aNewMessages.length) { var + self = this, iIndex = 0, iLen = aNewMessages.length, fNotificationHelper = function (sImageSrc, sTitle, sText) { var oNotification = null; - if (NotificationClass && RL.data().useDesktopNotifications()) + if (NotificationClass && self.useDesktopNotifications()) { oNotification = new NotificationClass(sTitle, { 'body': sText, @@ -582,7 +583,7 @@ { fNotificationHelper( LinkBuilder.notificationMailIcon(), - RL.data().accountEmail(), + this.accountEmail(), Utils.i18n('MESSAGE_LIST/NEW_MESSAGE_NOTIFICATION', { 'COUNT': iLen }) @@ -605,146 +606,6 @@ } }; - /** - * @param {string} sNamespace - * @param {Array} aFolders - * @return {Array} - */ - WebMailDataStorage.prototype.folderResponseParseRec = function (sNamespace, aFolders) - { - var - iIndex = 0, - iLen = 0, - oFolder = null, - oCacheFolder = null, - sFolderFullNameRaw = '', - aSubFolders = [], - aList = [] - ; - - for (iIndex = 0, iLen = aFolders.length; iIndex < iLen; iIndex++) - { - oFolder = aFolders[iIndex]; - if (oFolder) - { - sFolderFullNameRaw = oFolder.FullNameRaw; - - oCacheFolder = Cache.getFolderFromCacheList(sFolderFullNameRaw);// TODO cjs - if (!oCacheFolder) - { - oCacheFolder = FolderModel.newInstanceFromJson(oFolder);// TODO cjs - if (oCacheFolder) - { - Cache.setFolderToCacheList(sFolderFullNameRaw, oCacheFolder);// TODO cjs - Cache.setFolderFullNameRaw(oCacheFolder.fullNameHash, sFolderFullNameRaw);// TODO cjs - } - } - - if (oCacheFolder) - { - oCacheFolder.collapsed(!Utils.isFolderExpanded(oCacheFolder.fullNameHash)); - - if (oFolder.Extended) - { - if (oFolder.Extended.Hash) - { - Cache.setFolderHash(oCacheFolder.fullNameRaw, oFolder.Extended.Hash);// TODO cjs - } - - if (Utils.isNormal(oFolder.Extended.MessageCount)) - { - oCacheFolder.messageCountAll(oFolder.Extended.MessageCount); - } - - if (Utils.isNormal(oFolder.Extended.MessageUnseenCount)) - { - oCacheFolder.messageCountUnread(oFolder.Extended.MessageUnseenCount); - } - } - - aSubFolders = oFolder['SubFolders']; - if (aSubFolders && 'Collection/FolderCollection' === aSubFolders['@Object'] && - aSubFolders['@Collection'] && Utils.isArray(aSubFolders['@Collection'])) - { - oCacheFolder.subFolders( - this.folderResponseParseRec(sNamespace, aSubFolders['@Collection'])); - } - - aList.push(oCacheFolder); - } - } - } - - return aList; - }; - - /** - * @param {*} oData - */ - WebMailDataStorage.prototype.setFolders = function (oData) - { - var - aList = [], - bUpdate = false, - oRLData = RL.data(),// TODO cjs - fNormalizeFolder = function (sFolderFullNameRaw) { - return ('' === sFolderFullNameRaw || Consts.Values.UnuseOptionValue === sFolderFullNameRaw || - null !== Cache.getFolderFromCacheList(sFolderFullNameRaw)) ? sFolderFullNameRaw : '';// TODO cjs - } - ; - - if (oData && oData.Result && 'Collection/FolderCollection' === oData.Result['@Object'] && - oData.Result['@Collection'] && Utils.isArray(oData.Result['@Collection'])) - { - if (!Utils.isUnd(oData.Result.Namespace)) - { - oRLData.namespace = oData.Result.Namespace; - } - - this.threading(!!RL.settingsGet('UseImapThread') && oData.Result.IsThreadsSupported && true);// TODO cjs - - aList = this.folderResponseParseRec(oRLData.namespace, oData.Result['@Collection']); - oRLData.folderList(aList); - - // TODO cjs - if (oData.Result['SystemFolders'] && - '' === '' + RL.settingsGet('SentFolder') + RL.settingsGet('DraftFolder') + - RL.settingsGet('SpamFolder') + RL.settingsGet('TrashFolder') + RL.settingsGet('ArchiveFolder') + - RL.settingsGet('NullFolder')) - { - // TODO Magic Numbers - RL.settingsSet('SentFolder', oData.Result['SystemFolders'][2] || null); - RL.settingsSet('DraftFolder', oData.Result['SystemFolders'][3] || null); - RL.settingsSet('SpamFolder', oData.Result['SystemFolders'][4] || null); - RL.settingsSet('TrashFolder', oData.Result['SystemFolders'][5] || null); - RL.settingsSet('ArchiveFolder', oData.Result['SystemFolders'][12] || null); - - bUpdate = true; - } - - // TODO cjs - oRLData.sentFolder(fNormalizeFolder(RL.settingsGet('SentFolder'))); - oRLData.draftFolder(fNormalizeFolder(RL.settingsGet('DraftFolder'))); - oRLData.spamFolder(fNormalizeFolder(RL.settingsGet('SpamFolder'))); - oRLData.trashFolder(fNormalizeFolder(RL.settingsGet('TrashFolder'))); - oRLData.archiveFolder(fNormalizeFolder(RL.settingsGet('ArchiveFolder'))); - - if (bUpdate) - { - Remote.saveSystemFolders(Utils.emptyFunction, { - 'SentFolder': oRLData.sentFolder(), - 'DraftFolder': oRLData.draftFolder(), - 'SpamFolder': oRLData.spamFolder(), - 'TrashFolder': oRLData.trashFolder(), - 'ArchiveFolder': oRLData.archiveFolder(), - 'NullFolder': 'NullFolder' - }); - } - - LocalStorage.set(Enums.ClientSideKeyName.FoldersLashHash, oData.Result.FoldersHash); - } - }; - WebMailDataStorage.prototype.hideMessageBodies = function () { var oMessagesBodiesDom = this.messagesBodiesDom(); @@ -802,7 +663,7 @@ }); _.find(aTimeouts, function (aItem) { - var oFolder = Cache.getFolderFromCacheList(aItem[1]);// TODO cjs + var oFolder = Cache.getFolderFromCacheList(aItem[1]); if (oFolder) { oFolder.interval = iUtc; @@ -832,13 +693,13 @@ }); var + self = this, iUnseenCount = 0, - oData = RL.data(),// TODO cjs - aMessageList = oData.messageList(), + aMessageList = this.messageList(), oFromFolder = Cache.getFolderFromCacheList(sFromFolderFullNameRaw), oToFolder = '' === sToFolderFullNameRaw ? null : Cache.getFolderFromCacheList(sToFolderFullNameRaw || ''), - sCurrentFolderFullNameRaw = oData.currentFolderFullNameRaw(), - oCurrentMessage = oData.message(), + sCurrentFolderFullNameRaw = this.currentFolderFullNameRaw(), + oCurrentMessage = this.message(), aMessages = sCurrentFolderFullNameRaw === sFromFolderFullNameRaw ? _.filter(aMessageList, function (oMessage) { return oMessage && -1 < Utils.inArray(Utils.pInt(oMessage.uid), aUidForRemove); }) : [] @@ -884,13 +745,13 @@ } else { - oData.messageListIsNotCompleted(true); + this.messageListIsNotCompleted(true); _.each(aMessages, function (oMessage) { if (oCurrentMessage && oCurrentMessage.hash === oMessage.hash) { oCurrentMessage = null; - oData.message(null); + self.message(null); } oMessage.deleted(true); @@ -898,7 +759,7 @@ _.delay(function () { _.each(aMessages, function (oMessage) { - oData.messageList.remove(oMessage); + self.messageList.remove(oMessage); }); }, 400); } @@ -937,7 +798,7 @@ this.messageError(''); oMessage.initUpdateByMessageJson(oData.Result); - Cache.addRequestedMessage(oMessage.folderFullNameRaw, oMessage.uid);// TODO cjs + Cache.addRequestedMessage(oMessage.folderFullNameRaw, oMessage.uid); if (!bCached) { @@ -967,7 +828,7 @@ bIsHtml = false; sResultHtml = Utils.plainToHtml(oData.Result.Plain.toString(), false); - if ((oMessage.isPgpSigned() || oMessage.isPgpEncrypted()) && RL.data().capaOpenPGP()) + if ((oMessage.isPgpSigned() || oMessage.isPgpEncrypted()) && this.capaOpenPGP()) { oMessage.plainRaw = Utils.pString(oData.Result.Plain); @@ -1079,137 +940,6 @@ }).join('|'); }; - WebMailDataStorage.prototype.setMessageList = function (oData, bCached) - { - if (oData && oData.Result && 'Collection/MessageCollection' === oData.Result['@Object'] && - oData.Result['@Collection'] && Utils.isArray(oData.Result['@Collection'])) - { - var - oRainLoopData = RL.data(), - mLastCollapsedThreadUids = null, - iIndex = 0, - iLen = 0, - iCount = 0, - iOffset = 0, - aList = [], - iUtc = moment().unix(), - aStaticList = oRainLoopData.staticMessageList, - oJsonMessage = null, - oMessage = null, - oFolder = null, - iNewCount = 0, - bUnreadCountChange = false - ; - - iCount = Utils.pInt(oData.Result.MessageResultCount); - iOffset = Utils.pInt(oData.Result.Offset); - - if (Utils.isNonEmptyArray(oData.Result.LastCollapsedThreadUids)) - { - mLastCollapsedThreadUids = oData.Result.LastCollapsedThreadUids; - } - - oFolder = Cache.getFolderFromCacheList( - Utils.isNormal(oData.Result.Folder) ? oData.Result.Folder : ''); - - if (oFolder && !bCached) - { - oFolder.interval = iUtc; - - Cache.setFolderHash(oData.Result.Folder, oData.Result.FolderHash); - - if (Utils.isNormal(oData.Result.MessageCount)) - { - oFolder.messageCountAll(oData.Result.MessageCount); - } - - if (Utils.isNormal(oData.Result.MessageUnseenCount)) - { - if (Utils.pInt(oFolder.messageCountUnread()) !== Utils.pInt(oData.Result.MessageUnseenCount)) - { - bUnreadCountChange = true; - } - - oFolder.messageCountUnread(oData.Result.MessageUnseenCount); - } - - this.initUidNextAndNewMessages(oFolder.fullNameRaw, oData.Result.UidNext, oData.Result.NewMessages); - } - - if (bUnreadCountChange && oFolder) - { - Cache.clearMessageFlagsFromCacheByFolder(oFolder.fullNameRaw); - } - - for (iIndex = 0, iLen = oData.Result['@Collection'].length; iIndex < iLen; iIndex++) - { - oJsonMessage = oData.Result['@Collection'][iIndex]; - if (oJsonMessage && 'Object/Message' === oJsonMessage['@Object']) - { - oMessage = aStaticList[iIndex]; - if (!oMessage || !oMessage.initByJson(oJsonMessage)) - { - oMessage = MessageModel.newInstanceFromJson(oJsonMessage); - } - - if (oMessage) - { - if (Cache.hasNewMessageAndRemoveFromCache(oMessage.folderFullNameRaw, oMessage.uid) && 5 >= iNewCount) - { - iNewCount++; - oMessage.newForAnimation(true); - } - - oMessage.deleted(false); - - if (bCached) - { - Cache.initMessageFlagsFromCache(oMessage); - } - else - { - Cache.storeMessageFlagsToCache(oMessage); - } - - oMessage.lastInCollapsedThread(mLastCollapsedThreadUids && -1 < Utils.inArray(Utils.pInt(oMessage.uid), mLastCollapsedThreadUids) ? true : false); - - aList.push(oMessage); - } - } - } - - oRainLoopData.messageListCount(iCount); - oRainLoopData.messageListSearch(Utils.isNormal(oData.Result.Search) ? oData.Result.Search : ''); - oRainLoopData.messageListPage(Math.ceil((iOffset / oRainLoopData.messagesPerPage()) + 1)); - oRainLoopData.messageListEndFolder(Utils.isNormal(oData.Result.Folder) ? oData.Result.Folder : ''); - oRainLoopData.messageListEndSearch(Utils.isNormal(oData.Result.Search) ? oData.Result.Search : ''); - oRainLoopData.messageListEndPage(oRainLoopData.messageListPage()); - - oRainLoopData.messageList(aList); - oRainLoopData.messageListIsNotCompleted(false); - - if (aStaticList.length < aList.length) - { - oRainLoopData.staticMessageList = aList; - } - - Cache.clearNewMessageCache(); - - if (oFolder && (bCached || bUnreadCountChange || RL.data().useThreads())) - { - RL.folderInformation(oFolder.fullNameRaw, aList); - } - } - else - { - RL.data().messageListCount(0); - RL.data().messageList([]); - RL.data().messageListError(Utils.getNotification( - oData && oData.ErrorCode ? oData.ErrorCode : Enums.Notification.CantGetMessageList - )); - } - }; - WebMailDataStorage.prototype.findPublicKeyByHex = function (sHash) { return _.find(this.openpgpkeysPublic(), function (oItem) { diff --git a/dev/ViewModels/AbstractSystemDropDownViewModel.js b/dev/ViewModels/AbstractSystemDropDownViewModel.js index 2487374c5..adf1e2283 100644 --- a/dev/ViewModels/AbstractSystemDropDownViewModel.js +++ b/dev/ViewModels/AbstractSystemDropDownViewModel.js @@ -14,8 +14,15 @@ Utils = require('../Common/Utils.js'), LinkBuilder = require('../Common/LinkBuilder.js'), + AppSettings = require('../Storages/AppSettings.js'), + Data = require('../Storages/WebMailDataStorage.js'), Remote = require('../Storages/WebMailAjaxRemoteStorage.js'), + RL = require('../Boots/RainLoopApp.js'), + + PopupsKeyboardShortcutsHelpViewModel = require('../ViewModels/Popups/PopupsKeyboardShortcutsHelpViewModel.js'), + PopupsAddAccountViewModel = require('../ViewModels/Popups/PopupsKeyboardShortcutsHelpViewModel.js'), + kn = require('../Knoin/Knoin.js'), KnoinAbstractViewModel = require('../Knoin/KnoinAbstractViewModel.js') ; @@ -28,15 +35,13 @@ { KnoinAbstractViewModel.call(this, 'Right', 'SystemDropDown'); - var oData = RL.data(); - - this.accounts = oData.accounts; - this.accountEmail = oData.accountEmail; - this.accountsLoading = oData.accountsLoading; + this.accounts = Data.accounts; + this.accountEmail = Data.accountEmail; + this.accountsLoading = Data.accountsLoading; this.accountMenuDropdownTrigger = ko.observable(false); - this.capaAdditionalAccounts = RL.capa(Enums.Capa.AdditionalAccounts); + this.capaAdditionalAccounts = AppSettings.capa(Enums.Capa.AdditionalAccounts); this.loading = ko.computed(function () { return this.accountsLoading(); @@ -63,7 +68,7 @@ AbstractSystemDropDownViewModel.prototype.emailTitle = function () { - return RL.data().accountEmail(); + return Data.accountEmail(); }; AbstractSystemDropDownViewModel.prototype.settingsClick = function () @@ -92,7 +97,7 @@ window.__rlah_clear(); } - RL.loginAndLogoutReload(true, RL.settingsGet('ParentEmail') && 0 < RL.settingsGet('ParentEmail').length); + RL.loginAndLogoutReload(true, AppSettings.settingsGet('ParentEmail') && 0 < AppSettings.settingsGet('ParentEmail').length); }); }; @@ -116,6 +121,6 @@ }); }; - module.exports = new AbstractSystemDropDownViewModel(); + module.exports = AbstractSystemDropDownViewModel; }(module)); \ No newline at end of file diff --git a/dev/ViewModels/AdminLoginViewModel.js b/dev/ViewModels/AdminLoginViewModel.js index 5e4109be1..b5d759c5d 100644 --- a/dev/ViewModels/AdminLoginViewModel.js +++ b/dev/ViewModels/AdminLoginViewModel.js @@ -12,6 +12,8 @@ Utils = require('../Common/Utils.js'), Remote = require('../Storages/AdminAjaxRemoteStorage.js'), + + RL = require('../Boots/AdminApp.js'), kn = require('../Knoin/Knoin.js'), KnoinAbstractViewModel = require('../Knoin/KnoinAbstractViewModel.js') @@ -116,6 +118,6 @@ this.submitCommand(); }; - module.exports = new AdminLoginViewModel(); + module.exports = AdminLoginViewModel; }(module)); \ No newline at end of file diff --git a/dev/ViewModels/AdminMenuViewModel.js b/dev/ViewModels/AdminMenuViewModel.js index de73acd39..888ddfb85 100644 --- a/dev/ViewModels/AdminMenuViewModel.js +++ b/dev/ViewModels/AdminMenuViewModel.js @@ -5,7 +5,8 @@ 'use strict'; var - kn = require('../External/kn.js'), + kn = require('../Knoin/Knoin.js'), + Globals = require('../Common/Globals.js'), KnoinAbstractViewModel = require('../Knoin/KnoinAbstractViewModel.js') ; @@ -19,7 +20,7 @@ { KnoinAbstractViewModel.call(this, 'Left', 'AdminMenu'); - this.leftPanelDisabled = RL.data().leftPanelDisabled; + this.leftPanelDisabled = Globals.leftPanelDisabled; this.menu = oScreen.menu; @@ -33,6 +34,6 @@ return '#/' + sRoute; }; - module.exports = new AdminMenuViewModel(); + module.exports = AdminMenuViewModel; }(module)); diff --git a/dev/ViewModels/AdminPaneViewModel.js b/dev/ViewModels/AdminPaneViewModel.js index 374165697..7066c5685 100644 --- a/dev/ViewModels/AdminPaneViewModel.js +++ b/dev/ViewModels/AdminPaneViewModel.js @@ -7,7 +7,11 @@ var ko = require('../External/ko.js'), + AppSettings = require('../Storages/AppSettings.js'), + Data = require('../Storages/AdminDataStorage.js'), Remote = require('../Storages/AdminAjaxRemoteStorage.js'), + + RL = require('../Boots/AdminApp.js'), kn = require('../Knoin/Knoin.js'), KnoinAbstractViewModel = require('../Knoin/KnoinAbstractViewModel.js') @@ -21,10 +25,10 @@ { KnoinAbstractViewModel.call(this, 'Right', 'AdminPane'); - this.adminDomain = ko.observable(RL.settingsGet('AdminDomain')); - this.version = ko.observable(RL.settingsGet('Version')); + this.adminDomain = ko.observable(AppSettings.settingsGet('AdminDomain')); + this.version = ko.observable(AppSettings.settingsGet('Version')); - this.adminManLoadingVisibility = RL.data().adminManLoadingVisibility; + this.adminManLoadingVisibility = Data.adminManLoadingVisibility; kn.constructorEnd(this); } @@ -38,6 +42,6 @@ }); }; - module.exports = new AdminPaneViewModel(); + module.exports = AdminPaneViewModel; }(module)); \ No newline at end of file diff --git a/dev/ViewModels/LoginViewModel.js b/dev/ViewModels/LoginViewModel.js index 22c30b669..8f0971a35 100644 --- a/dev/ViewModels/LoginViewModel.js +++ b/dev/ViewModels/LoginViewModel.js @@ -14,10 +14,16 @@ Enums = require('../Common/Enums.js'), LinkBuilder = require('../Common/LinkBuilder.js'), + AppSettings = require('../Storages/AppSettings.js'), + Data = require('../Storages/WebMailDataStorage.js'), Remote = require('../Storages/WebMailAjaxRemoteStorage.js'), + RL = require('../Boots/RainLoopApp.js'), + kn = require('../Knoin/Knoin.js'), - KnoinAbstractViewModel = require('../Knoin/KnoinAbstractViewModel.js') + KnoinAbstractViewModel = require('../Knoin/KnoinAbstractViewModel.js'), + + PopupsLanguagesViewModel = require('../ViewModels/Popups/PopupsLanguagesViewModel.js') ; /** @@ -28,8 +34,6 @@ { KnoinAbstractViewModel.call(this, 'Center', 'Login'); - var oData = RL.data(); - this.email = ko.observable(''); this.password = ko.observable(''); this.signMe = ko.observable(false); @@ -40,9 +44,9 @@ this.additionalCode.visibility = ko.observable(false); this.additionalCodeSignMe = ko.observable(false); - this.logoImg = Utils.trim(RL.settingsGet('LoginLogo')); - this.loginDescription = Utils.trim(RL.settingsGet('LoginDescription')); - this.logoCss = Utils.trim(RL.settingsGet('LoginCss')); + this.logoImg = Utils.trim(AppSettings.settingsGet('LoginLogo')); + this.loginDescription = Utils.trim(AppSettings.settingsGet('LoginDescription')); + this.logoCss = Utils.trim(AppSettings.settingsGet('LoginCss')); this.emailError = ko.observable(false); this.passwordError = ko.observable(false); @@ -71,10 +75,10 @@ this.submitRequest = ko.observable(false); this.submitError = ko.observable(''); - this.allowLanguagesOnLogin = oData.allowLanguagesOnLogin; + this.allowLanguagesOnLogin = Data.allowLanguagesOnLogin; this.langRequest = ko.observable(false); - this.mainLanguage = oData.mainLanguage; + this.mainLanguage = Data.mainLanguage; this.bSendLanguage = false; this.mainLanguageFullName = ko.computed(function () { @@ -164,7 +168,7 @@ }, this) ; - if (!!RL.settingsGet('UseRsaEncryption') && Utils.rsaEncode.supported) + if (!!AppSettings.settingsGet('UseRsaEncryption') && Utils.rsaEncode.supported) { Remote.getPublicKey(_.bind(function (sResult, oData) { @@ -203,7 +207,8 @@ this.facebookCommand = Utils.createCommand(this, function () { - window.open(LinkBuilder.socialFacebook(), 'Facebook', 'left=200,top=100,width=650,height=335,menubar=no,status=no,resizable=yes,scrollbars=yes'); + window.open(LinkBuilder.socialFacebook(), 'Facebook', + 'left=200,top=100,width=650,height=335,menubar=no,status=no,resizable=yes,scrollbars=yes'); return true; }, function () { @@ -214,7 +219,8 @@ this.googleCommand = Utils.createCommand(this, function () { - window.open(LinkBuilder.socialGoogle(), 'Google', 'left=200,top=100,width=650,height=335,menubar=no,status=no,resizable=yes,scrollbars=yes'); + window.open(LinkBuilder.socialGoogle(), 'Google', + 'left=200,top=100,width=650,height=335,menubar=no,status=no,resizable=yes,scrollbars=yes'); return true; }, function () { @@ -225,7 +231,8 @@ this.twitterCommand = Utils.createCommand(this, function () { - window.open(LinkBuilder.socialTwitter(), 'Twitter', 'left=200,top=100,width=650,height=335,menubar=no,status=no,resizable=yes,scrollbars=yes'); + window.open(LinkBuilder.socialTwitter(), 'Twitter', + 'left=200,top=100,width=650,height=335,menubar=no,status=no,resizable=yes,scrollbars=yes'); return true; }, function () { @@ -262,9 +269,9 @@ this.emailFocus(true); } - if (RL.settingsGet('UserLanguage')) + if (AppSettings.settingsGet('UserLanguage')) { - $.cookie('rllang', RL.data().language(), {'expires': 30}); + $.cookie('rllang', Data.language(), {'expires': 30}); } }, this), 100); @@ -280,7 +287,7 @@ { var self = this, - sJsHash = RL.settingsGet('JsHash'), + sJsHash = AppSettings.settingsGet('JsHash'), fSocial = function (iErrorCode) { iErrorCode = Utils.pInt(iErrorCode); if (0 === iErrorCode) @@ -295,11 +302,11 @@ } ; - this.facebookLoginEnabled(!!RL.settingsGet('AllowFacebookSocial')); - this.twitterLoginEnabled(!!RL.settingsGet('AllowTwitterSocial')); - this.googleLoginEnabled(!!RL.settingsGet('AllowGoogleSocial')); + this.facebookLoginEnabled(!!AppSettings.settingsGet('AllowFacebookSocial')); + this.twitterLoginEnabled(!!AppSettings.settingsGet('AllowTwitterSocial')); + this.googleLoginEnabled(!!AppSettings.settingsGet('AllowGoogleSocial')); - switch ((RL.settingsGet('SignMe') || 'unused').toLowerCase()) + switch ((AppSettings.settingsGet('SignMe') || 'unused').toLowerCase()) { case Enums.LoginSignMeTypeAsString.DefaultOff: this.signMeType(Enums.LoginSignMeType.DefaultOff); @@ -313,8 +320,8 @@ break; } - this.email(RL.data().devEmail); - this.password(RL.data().devPassword); + this.email(Data.devEmail); + this.password(Data.devPassword); if (this.googleLoginEnabled()) { @@ -332,7 +339,7 @@ } _.delay(function () { - RL.data().language.subscribe(function (sValue) { + Data.language.subscribe(function (sValue) { self.langRequest(true); $.ajax({ 'url': LinkBuilder.langLink(sValue), @@ -341,7 +348,7 @@ }).done(function() { self.bSendLanguage = true; Utils.i18nReload(); - $.cookie('rllang', RL.data().language(), {'expires': 30}); + $.cookie('rllang', Data.language(), {'expires': 30}); }).always(function() { self.langRequest(false); }); @@ -361,6 +368,6 @@ kn.showScreenPopup(PopupsLanguagesViewModel); }; - module.exports = new LoginViewModel(); + module.exports = LoginViewModel; }(module)); \ No newline at end of file diff --git a/dev/ViewModels/MailBoxFolderListViewModel.js b/dev/ViewModels/MailBoxFolderListViewModel.js index ee60f655a..31aaaa73a 100644 --- a/dev/ViewModels/MailBoxFolderListViewModel.js +++ b/dev/ViewModels/MailBoxFolderListViewModel.js @@ -13,9 +13,18 @@ Utils = require('../Common/Utils.js'), Enums = require('../Common/Enums.js'), + Globals = require('../Common/Globals.js'), LinkBuilder = require('../Common/LinkBuilder.js'), + AppSettings = require('../Storages/AppSettings.js'), Cache = require('../Storages/WebMailCacheStorage.js'), + Data = require('../Storages/WebMailDataStorage.js'), + + RL = require('../Boots/RainLoopApp.js'), + + PopupsComposeViewModel = require('./Popups/PopupsComposeViewModel.js'), + PopupsFolderCreateViewModel = require('./Popups/PopupsFolderCreateViewModel.js'), + PopupsContactsViewModel = require('./Popups/PopupsContactsViewModel.js'), kn = require('../Knoin/Knoin.js'), KnoinAbstractViewModel = require('../Knoin/KnoinAbstractViewModel.js') @@ -29,21 +38,19 @@ { KnoinAbstractViewModel.call(this, 'Left', 'MailFolderList'); - var oData = RL.data(); - this.oContentVisible = null; this.oContentScrollable = null; - this.messageList = oData.messageList; - this.folderList = oData.folderList; - this.folderListSystem = oData.folderListSystem; - this.foldersChanging = oData.foldersChanging; + this.messageList = Data.messageList; + this.folderList = Data.folderList; + this.folderListSystem = Data.folderListSystem; + this.foldersChanging = Data.foldersChanging; - this.leftPanelDisabled = oData.leftPanelDisabled; + this.leftPanelDisabled = Globals.leftPanelDisabled; this.iDropOverTimer = 0; - this.allowContacts = !!RL.settingsGet('ContactsIsAllowed'); + this.allowContacts = !!AppSettings.settingsGet('ContactsIsAllowed'); kn.constructorEnd(this); } @@ -68,7 +75,7 @@ if (oFolder && oEvent) { bCollapsed = oFolder.collapsed(); - Utils.setExpandedFolder(oFolder.fullNameHash, bCollapsed); + RL.setExpandedFolder(oFolder.fullNameHash, bCollapsed); oFolder.collapsed(!bCollapsed); oEvent.preventDefault(); @@ -80,18 +87,17 @@ oEvent.preventDefault(); var - oData = RL.data(), oFolder = ko.dataFor(this) ; if (oFolder) { - if (Enums.Layout.NoPreview === oData.layout()) + if (Enums.Layout.NoPreview === Data.layout()) { - oData.message(null); + Data.message(null); } - if (oFolder.fullNameRaw === oData.currentFolderFullNameRaw()) + if (oFolder.fullNameRaw === Data.currentFolderFullNameRaw()) { Cache.setFolderHash(oFolder.fullNameRaw, ''); } @@ -152,7 +158,7 @@ if (oFolder) { bCollapsed = oFolder.collapsed(); - Utils.setExpandedFolder(oFolder.fullNameHash, bCollapsed); + RL.setExpandedFolder(oFolder.fullNameHash, bCollapsed); oFolder.collapsed(!bCollapsed); } } @@ -181,7 +187,7 @@ { this.iDropOverTimer = window.setTimeout(function () { oFolder.collapsed(false); - Utils.setExpandedFolder(oFolder.fullNameHash, true); + RL.setExpandedFolder(oFolder.fullNameHash, true); Utils.windowResize(); }, 500); } @@ -269,6 +275,6 @@ } }; - module.exports = new MailBoxFolderListViewModel(); + module.exports = MailBoxFolderListViewModel; }(module)); diff --git a/dev/ViewModels/MailBoxMessageListViewModel.js b/dev/ViewModels/MailBoxMessageListViewModel.js index 1d74f8fa7..1659737d1 100644 --- a/dev/ViewModels/MailBoxMessageListViewModel.js +++ b/dev/ViewModels/MailBoxMessageListViewModel.js @@ -17,10 +17,16 @@ Consts = require('../Common/Consts.js'), Globals = require('../Common/Globals.js'), LinkBuilder = require('../Common/LinkBuilder.js'), + Events = require('../Common/Events.js'), + Selector = require('../Common/Selector.js'), + AppSettings = require('../Storages/AppSettings.js'), Cache = require('../Storages/WebMailCacheStorage.js'), + Data = require('../Storages/WebMailDataStorage.js'), Remote = require('../Storages/WebMailAjaxRemoteStorage.js'), + RL = require('../Boots/RainLoopApp.js'), + kn = require('../Knoin/Knoin.js'), KnoinAbstractViewModel = require('../Knoin/KnoinAbstractViewModel.js'), @@ -39,38 +45,36 @@ this.bPrefetch = false; this.emptySubjectValue = ''; - this.hideDangerousActions = !!RL.settingsGet('HideDangerousActions'); + this.hideDangerousActions = !!AppSettings.settingsGet('HideDangerousActions'); - var oData = RL.data(); + this.popupVisibility = Globals.popupVisibility; - this.popupVisibility = RL.popupVisibility; + this.message = Data.message; + this.messageList = Data.messageList; + this.folderList = Data.folderList; + this.currentMessage = Data.currentMessage; + this.isMessageSelected = Data.isMessageSelected; + this.messageListSearch = Data.messageListSearch; + this.messageListError = Data.messageListError; + this.folderMenuForMove = Data.folderMenuForMove; - this.message = oData.message; - this.messageList = oData.messageList; - this.folderList = oData.folderList; - this.currentMessage = oData.currentMessage; - this.isMessageSelected = oData.isMessageSelected; - this.messageListSearch = oData.messageListSearch; - this.messageListError = oData.messageListError; - this.folderMenuForMove = oData.folderMenuForMove; + this.useCheckboxesInList = Data.useCheckboxesInList; - this.useCheckboxesInList = oData.useCheckboxesInList; + this.mainMessageListSearch = Data.mainMessageListSearch; + this.messageListEndFolder = Data.messageListEndFolder; - this.mainMessageListSearch = oData.mainMessageListSearch; - this.messageListEndFolder = oData.messageListEndFolder; - - this.messageListChecked = oData.messageListChecked; - this.messageListCheckedOrSelected = oData.messageListCheckedOrSelected; - this.messageListCheckedOrSelectedUidsWithSubMails = oData.messageListCheckedOrSelectedUidsWithSubMails; - this.messageListCompleteLoadingThrottle = oData.messageListCompleteLoadingThrottle; + this.messageListChecked = Data.messageListChecked; + this.messageListCheckedOrSelected = Data.messageListCheckedOrSelected; + this.messageListCheckedOrSelectedUidsWithSubMails = Data.messageListCheckedOrSelectedUidsWithSubMails; + this.messageListCompleteLoadingThrottle = Data.messageListCompleteLoadingThrottle; Utils.initOnStartOrLangChange(function () { this.emptySubjectValue = Utils.i18n('MESSAGE_LIST/EMPTY_SUBJECT_TEXT'); }, this); - this.userQuota = oData.userQuota; - this.userUsageSize = oData.userUsageSize; - this.userUsageProc = oData.userUsageProc; + this.userQuota = Data.userQuota; + this.userUsageSize = Data.userUsageSize; + this.userUsageProc = Data.userUsageProc; this.moveDropdownTrigger = ko.observable(false); this.moreDropdownTrigger = ko.observable(false); @@ -82,25 +86,25 @@ this.dragOverBodyArea = ko.observable(null); this.messageListItemTemplate = ko.computed(function () { - return Enums.Layout.NoPreview !== oData.layout() ? + return Enums.Layout.NoPreview !== Data.layout() ? 'MailMessageListItem' : 'MailMessageListItemNoPreviewPane'; }); this.messageListSearchDesc = ko.computed(function () { - var sValue = oData.messageListEndSearch(); + var sValue = Data.messageListEndSearch(); return '' === sValue ? '' : Utils.i18n('MESSAGE_LIST/SEARCH_RESULT_FOR', {'SEARCH': sValue}); }); - this.messageListPagenator = ko.computed(Utils.computedPagenatorHelper(oData.messageListPage, oData.messageListPageCount)); + this.messageListPagenator = ko.computed(Utils.computedPagenatorHelper(Data.messageListPage, Data.messageListPageCount)); this.checkAll = ko.computed({ 'read': function () { - return 0 < RL.data().messageListChecked().length; + return 0 < Data.messageListChecked().length; }, 'write': function (bValue) { bValue = !!bValue; - _.each(RL.data().messageList(), function (oMessage) { + _.each(Data.messageList(), function (oMessage) { oMessage.checked(bValue); }); } @@ -119,8 +123,8 @@ this.isIncompleteChecked = ko.computed(function () { var - iM = RL.data().messageList().length, - iC = RL.data().messageListChecked().length + iM = Data.messageList().length, + iC = Data.messageListChecked().length ; return 0 < iM && 0 < iC && iM > iC; }, this); @@ -134,82 +138,82 @@ }, this); this.isSpamFolder = ko.computed(function () { - return oData.spamFolder() === this.messageListEndFolder() && - '' !== oData.spamFolder(); + return Data.spamFolder() === this.messageListEndFolder() && + '' !== Data.spamFolder(); }, this); this.isSpamDisabled = ko.computed(function () { - return Consts.Values.UnuseOptionValue === oData.spamFolder(); + return Consts.Values.UnuseOptionValue === Data.spamFolder(); }, this); this.isTrashFolder = ko.computed(function () { - return oData.trashFolder() === this.messageListEndFolder() && - '' !== oData.trashFolder(); + return Data.trashFolder() === this.messageListEndFolder() && + '' !== Data.trashFolder(); }, this); this.isDraftFolder = ko.computed(function () { - return oData.draftFolder() === this.messageListEndFolder() && - '' !== oData.draftFolder(); + return Data.draftFolder() === this.messageListEndFolder() && + '' !== Data.draftFolder(); }, this); this.isSentFolder = ko.computed(function () { - return oData.sentFolder() === this.messageListEndFolder() && - '' !== oData.sentFolder(); + return Data.sentFolder() === this.messageListEndFolder() && + '' !== Data.sentFolder(); }, this); this.isArchiveFolder = ko.computed(function () { - return oData.archiveFolder() === this.messageListEndFolder() && - '' !== oData.archiveFolder(); + return Data.archiveFolder() === this.messageListEndFolder() && + '' !== Data.archiveFolder(); }, this); this.isArchiveDisabled = ko.computed(function () { - return Consts.Values.UnuseOptionValue === RL.data().archiveFolder(); + return Consts.Values.UnuseOptionValue === Data.archiveFolder(); }, this); this.canBeMoved = this.hasCheckedOrSelectedLines; this.clearCommand = Utils.createCommand(this, function () { - kn.showScreenPopup(PopupsFolderClearViewModel, [RL.data().currentFolder()]); + kn.showScreenPopup(PopupsFolderClearViewModel, [Data.currentFolder()]); }); this.multyForwardCommand = Utils.createCommand(this, function () { - kn.showScreenPopup(PopupsComposeViewModel, [Enums.ComposeType.ForwardAsAttachment, RL.data().messageListCheckedOrSelected()]); + kn.showScreenPopup(PopupsComposeViewModel, [Enums.ComposeType.ForwardAsAttachment, Data.messageListCheckedOrSelected()]); }, this.canBeMoved); this.deleteWithoutMoveCommand = Utils.createCommand(this, function () { RL.deleteMessagesFromFolder(Enums.FolderType.Trash, - RL.data().currentFolderFullNameRaw(), - RL.data().messageListCheckedOrSelectedUidsWithSubMails(), false); + Data.currentFolderFullNameRaw(), + Data.messageListCheckedOrSelectedUidsWithSubMails(), false); }, this.canBeMoved); this.deleteCommand = Utils.createCommand(this, function () { RL.deleteMessagesFromFolder(Enums.FolderType.Trash, - RL.data().currentFolderFullNameRaw(), - RL.data().messageListCheckedOrSelectedUidsWithSubMails(), true); + Data.currentFolderFullNameRaw(), + Data.messageListCheckedOrSelectedUidsWithSubMails(), true); }, this.canBeMoved); this.archiveCommand = Utils.createCommand(this, function () { RL.deleteMessagesFromFolder(Enums.FolderType.Archive, - RL.data().currentFolderFullNameRaw(), - RL.data().messageListCheckedOrSelectedUidsWithSubMails(), true); + Data.currentFolderFullNameRaw(), + Data.messageListCheckedOrSelectedUidsWithSubMails(), true); }, this.canBeMoved); this.spamCommand = Utils.createCommand(this, function () { RL.deleteMessagesFromFolder(Enums.FolderType.Spam, - RL.data().currentFolderFullNameRaw(), - RL.data().messageListCheckedOrSelectedUidsWithSubMails(), true); + Data.currentFolderFullNameRaw(), + Data.messageListCheckedOrSelectedUidsWithSubMails(), true); }, this.canBeMoved); this.notSpamCommand = Utils.createCommand(this, function () { RL.deleteMessagesFromFolder(Enums.FolderType.NotSpam, - RL.data().currentFolderFullNameRaw(), - RL.data().messageListCheckedOrSelectedUidsWithSubMails(), true); + Data.currentFolderFullNameRaw(), + Data.messageListCheckedOrSelectedUidsWithSubMails(), true); }, this.canBeMoved); this.moveCommand = Utils.createCommand(this, Utils.emptyFunction, this.canBeMoved); this.reloadCommand = Utils.createCommand(this, function () { - if (!RL.data().messageListCompleteLoadingThrottle()) + if (!Data.messageListCompleteLoadingThrottle()) { RL.reloadMessageList(false, true); } @@ -224,18 +228,18 @@ this.selector.on('onItemSelect', _.bind(function (oMessage) { if (oMessage) { - oData.message(oData.staticMessageList.populateByMessageListItem(oMessage)); - this.populateMessageBody(oData.message()); + Data.message(Data.staticMessageList.populateByMessageListItem(oMessage)); + this.populateMessageBody(Data.message()); - if (Enums.Layout.NoPreview === oData.layout()) + if (Enums.Layout.NoPreview === Data.layout()) { kn.setHash(LinkBuilder.messagePreview(), true); - oData.message.focused(true); + Data.message.focused(true); } } else { - oData.message(null); + Data.message(null); } }, this)); @@ -243,17 +247,17 @@ return oMessage ? oMessage.generateUid() : ''; }); - oData.messageListEndHash.subscribe(function () { + Data.messageListEndHash.subscribe(function () { this.selector.scrollToTop(); }, this); - oData.layout.subscribe(function (mValue) { + Data.layout.subscribe(function (mValue) { this.selector.autoSelect(Enums.Layout.NoPreview !== mValue); }, this); - oData.layout.valueHasMutated(); + Data.layout.valueHasMutated(); - RL + Events .sub('mailbox.message-list.selector.go-down', function () { this.selector.goDown(true); }, this) @@ -302,8 +306,8 @@ if (this.canBeMoved()) { RL.moveMessagesToFolder( - RL.data().currentFolderFullNameRaw(), - RL.data().messageListCheckedOrSelectedUidsWithSubMails(), sToFolderFullNameRaw, bCopy); + Data.currentFolderFullNameRaw(), + Data.messageListCheckedOrSelectedUidsWithSubMails(), sToFolderFullNameRaw, bCopy); } return false; @@ -318,15 +322,15 @@ var oEl = Utils.draggeblePlace(), - aUids = RL.data().messageListCheckedOrSelectedUidsWithSubMails() + aUids = Data.messageListCheckedOrSelectedUidsWithSubMails() ; - oEl.data('rl-folder', RL.data().currentFolderFullNameRaw()); + oEl.data('rl-folder', Data.currentFolderFullNameRaw()); oEl.data('rl-uids', aUids); oEl.find('.text').text('' + aUids.length); _.defer(function () { - var aUids = RL.data().messageListCheckedOrSelectedUidsWithSubMails(); + var aUids = Data.messageListCheckedOrSelectedUidsWithSubMails(); oEl.data('rl-uids', aUids); oEl.find('.text').text('' + aUids.length); @@ -342,24 +346,22 @@ */ MailBoxMessageListViewModel.prototype.onMessageResponse = function (sResult, oData, bCached) { - var oRainLoopData = RL.data(); - - oRainLoopData.hideMessageBodies(); - oRainLoopData.messageLoading(false); + Data.hideMessageBodies(); + Data.messageLoading(false); if (Enums.StorageResultType.Success === sResult && oData && oData.Result) { - oRainLoopData.setMessage(oData, bCached); + Data.setMessage(oData, bCached); } else if (Enums.StorageResultType.Unload === sResult) { - oRainLoopData.message(null); - oRainLoopData.messageError(''); + Data.message(null); + Data.messageError(''); } else if (Enums.StorageResultType.Abort !== sResult) { - oRainLoopData.message(null); - oRainLoopData.messageError((oData && oData.ErrorCode ? + Data.message(null); + Data.messageError((oData && oData.ErrorCode ? Utils.getNotification(oData.ErrorCode) : Utils.getNotification(Enums.Notification.UnknownError))); } @@ -371,7 +373,7 @@ { if (Remote.message(this.onMessageResponse, oMessage.folderFullNameRaw, oMessage.uid)) { - RL.data().messageLoading(true); + Data.messageLoading(true); } else { @@ -395,7 +397,7 @@ if (Utils.isUnd(aMessages)) { - aMessages = RL.data().messageListChecked(); + aMessages = Data.messageListChecked(); } aUids = _.map(aMessages, function (oMessage) { @@ -470,7 +472,7 @@ { var oFolder = null, - aMessages = RL.data().messageList() + aMessages = Data.messageList() ; if ('' !== sFolderFullNameRaw) @@ -516,27 +518,27 @@ MailBoxMessageListViewModel.prototype.listSetSeen = function () { - this.setAction(RL.data().currentFolderFullNameRaw(), Enums.MessageSetAction.SetSeen, RL.data().messageListCheckedOrSelected()); + this.setAction(Data.currentFolderFullNameRaw(), Enums.MessageSetAction.SetSeen, Data.messageListCheckedOrSelected()); }; MailBoxMessageListViewModel.prototype.listSetAllSeen = function () { - this.setActionForAll(RL.data().currentFolderFullNameRaw(), Enums.MessageSetAction.SetSeen); + this.setActionForAll(Data.currentFolderFullNameRaw(), Enums.MessageSetAction.SetSeen); }; MailBoxMessageListViewModel.prototype.listUnsetSeen = function () { - this.setAction(RL.data().currentFolderFullNameRaw(), Enums.MessageSetAction.UnsetSeen, RL.data().messageListCheckedOrSelected()); + this.setAction(Data.currentFolderFullNameRaw(), Enums.MessageSetAction.UnsetSeen, Data.messageListCheckedOrSelected()); }; MailBoxMessageListViewModel.prototype.listSetFlags = function () { - this.setAction(RL.data().currentFolderFullNameRaw(), Enums.MessageSetAction.SetFlag, RL.data().messageListCheckedOrSelected()); + this.setAction(Data.currentFolderFullNameRaw(), Enums.MessageSetAction.SetFlag, Data.messageListCheckedOrSelected()); }; MailBoxMessageListViewModel.prototype.listUnsetFlags = function () { - this.setAction(RL.data().currentFolderFullNameRaw(), Enums.MessageSetAction.UnsetFlag, RL.data().messageListCheckedOrSelected()); + this.setAction(Data.currentFolderFullNameRaw(), Enums.MessageSetAction.UnsetFlag, Data.messageListCheckedOrSelected()); }; MailBoxMessageListViewModel.prototype.flagMessages = function (oCurrentMessage) @@ -623,8 +625,7 @@ MailBoxMessageListViewModel.prototype.onBuild = function (oDom) { var - self = this, - oData = RL.data() + self = this ; this.oContentVisible = $('.b-content', oDom); @@ -638,9 +639,9 @@ if (oMessage && !oMessage.lastInCollapsedThreadLoading()) { - RL.data().messageListThreadFolder(oMessage.folderFullNameRaw); + Data.messageListThreadFolder(oMessage.folderFullNameRaw); - aList = RL.data().messageListThreadUids(); + aList = Data.messageListThreadUids(); if (oMessage.lastInCollapsedThread()) { @@ -651,7 +652,7 @@ aList = _.without(aList, 0 < oMessage.parentUid() ? oMessage.parentUid() : oMessage.uid); } - RL.data().messageListThreadUids(_.uniq(aList)); + Data.messageListThreadUids(_.uniq(aList)); oMessage.lastInCollapsedThreadLoading(true); oMessage.lastInCollapsedThread(!oMessage.lastInCollapsedThread()); @@ -675,9 +676,9 @@ if (oPage) { kn.setHash(LinkBuilder.mailBox( - oData.currentFolderFullNameHash(), + Data.currentFolderFullNameHash(), oPage.value, - oData.messageListSearch() + Data.messageListSearch() )); } }) @@ -692,7 +693,7 @@ this.initUploaderForAppend(); this.initShortcuts(); - if (!Globals.bMobileDevice && RL.capa(Enums.Capa.Prefetch) && ifvisible) + if (!Globals.bMobileDevice && AppSettings.capa(Enums.Capa.Prefetch) && ifvisible) { ifvisible.setIdleDuration(10); @@ -721,7 +722,7 @@ key('delete, shift+delete, shift+3', Enums.KeyState.MessageList, function (event, handler) { if (event) { - if (0 < RL.data().messageListCheckedOrSelected().length) + if (0 < Data.messageListCheckedOrSelected().length) { if (handler && 'shift+delete' === handler.shortcut) { @@ -880,7 +881,7 @@ MailBoxMessageListViewModel.prototype.initUploaderForAppend = function () { - if (!RL.settingsGet('AllowAppendMessage') || !this.dragOverArea()) + if (!AppSettings.settingsGet('AllowAppendMessage') || !this.dragOverArea()) { return false; } @@ -893,7 +894,7 @@ 'disableFolderDragAndDrop': true, 'hidden': { 'Folder': function () { - return RL.data().currentFolderFullNameRaw(); + return Data.currentFolderFullNameRaw(); } }, 'dragAndDropElement': this.dragOverArea(), @@ -916,7 +917,7 @@ .on('onSelect', _.bind(function (sUid, oData) { if (sUid && oData && 'message/rfc822' === oData['Type']) { - RL.data().messageListLoading(true); + Data.messageListLoading(true); return true; } @@ -930,6 +931,6 @@ return !!oJua; }; - module.exports = new MailBoxMessageListViewModel(); + module.exports = MailBoxMessageListViewModel; }(module)); diff --git a/dev/ViewModels/MailBoxMessageViewViewModel.js b/dev/ViewModels/MailBoxMessageViewViewModel.js index 42da72d63..f4a979461 100644 --- a/dev/ViewModels/MailBoxMessageViewViewModel.js +++ b/dev/ViewModels/MailBoxMessageViewViewModel.js @@ -5,16 +5,22 @@ 'use strict'; var + $ = require('../External/jquery.js'), ko = require('../External/ko.js'), key = require('../External/key.js'), $html = require('../External/$html.js'), Consts = require('../Common/Consts.js'), Enums = require('../Common/Enums.js'), + Globals = require('../Common/Globals.js'), Utils = require('../Common/Utils.js'), + Events = require('../Common/Events.js'), Cache = require('../Storages/WebMailCacheStorage.js'), + Data = require('../Storages/WebMailDataStorage.js'), Remote = require('../Storages/WebMailAjaxRemoteStorage.js'), + + RL = require('../Boots/RainLoopApp.js'), kn = require('../Knoin/Knoin.js'), KnoinAbstractViewModel = require('../Knoin/KnoinAbstractViewModel.js') @@ -31,7 +37,6 @@ var self = this, sLastEmail = '', - oData = RL.data(), createCommandHelper = function (sType) { return Utils.createCommand(self, function () { this.replyOrforward(sType); @@ -41,24 +46,23 @@ this.oMessageScrollerDom = null; - this.keyScope = oData.keyScope; - this.message = oData.message; - this.currentMessage = oData.currentMessage; - this.messageListChecked = oData.messageListChecked; - this.hasCheckedMessages = oData.hasCheckedMessages; - this.messageListCheckedOrSelectedUidsWithSubMails = oData.messageListCheckedOrSelectedUidsWithSubMails; - this.messageLoading = oData.messageLoading; - this.messageLoadingThrottle = oData.messageLoadingThrottle; - this.messagesBodiesDom = oData.messagesBodiesDom; - this.useThreads = oData.useThreads; - this.replySameFolder = oData.replySameFolder; - this.layout = oData.layout; - this.usePreviewPane = oData.usePreviewPane; - this.isMessageSelected = oData.isMessageSelected; - this.messageActiveDom = oData.messageActiveDom; - this.messageError = oData.messageError; + this.message = Data.message; + this.currentMessage = Data.currentMessage; + this.messageListChecked = Data.messageListChecked; + this.hasCheckedMessages = Data.hasCheckedMessages; + this.messageListCheckedOrSelectedUidsWithSubMails = Data.messageListCheckedOrSelectedUidsWithSubMails; + this.messageLoading = Data.messageLoading; + this.messageLoadingThrottle = Data.messageLoadingThrottle; + this.messagesBodiesDom = Data.messagesBodiesDom; + this.useThreads = Data.useThreads; + this.replySameFolder = Data.replySameFolder; + this.layout = Data.layout; + this.usePreviewPane = Data.usePreviewPane; + this.isMessageSelected = Data.isMessageSelected; + this.messageActiveDom = Data.messageActiveDom; + this.messageError = Data.messageError; - this.fullScreenMode = oData.messageFullScreenMode; + this.fullScreenMode = Data.messageFullScreenMode; this.showFullInfo = ko.observable(false); this.moreDropdownTrigger = ko.observable(false); @@ -79,7 +83,7 @@ // commands this.closeMessage = Utils.createCommand(this, function () { - oData.message(null); + Data.message(null); }); this.replyCommand = createCommandHelper(Enums.ComposeType.Reply); @@ -107,7 +111,7 @@ if (this.message()) { RL.deleteMessagesFromFolder(Enums.FolderType.Trash, - RL.data().currentFolderFullNameRaw(), + Data.currentFolderFullNameRaw(), [this.message().uid], false); } }, this.messageVisibility); @@ -235,11 +239,11 @@ }); this.goUpCommand = Utils.createCommand(this, function () { - RL.pub('mailbox.message-list.selector.go-up'); + Events.pub('mailbox.message-list.selector.go-up'); }); this.goDownCommand = Utils.createCommand(this, function () { - RL.pub('mailbox.message-list.selector.go-down'); + Events.pub('mailbox.message-list.selector.go-down'); }); kn.constructorEnd(this); @@ -331,14 +335,13 @@ */ MailBoxMessageViewViewModel.prototype.replyOrforward = function (sType) { - kn.showScreenPopup(PopupsComposeViewModel, [sType, RL.data().message()]); + kn.showScreenPopup(PopupsComposeViewModel, [sType, Data.message()]); }; MailBoxMessageViewViewModel.prototype.onBuild = function (oDom) { var - self = this, - oData = RL.data() + self = this ; this.fullScreenMode.subscribe(function (bValue) { @@ -358,10 +361,10 @@ }, 'callbacks': { 'open': function() { - oData.useKeyboardShortcuts(false); + Globals.useKeyboardShortcuts(false); }, 'close': function() { - oData.useKeyboardShortcuts(true); + Globals.useKeyboardShortcuts(true); } }, 'mainClass': 'mfp-fade', @@ -370,7 +373,7 @@ oDom .on('click', '.messageView .messageItem .messageItemHeader', function () { - if (oData.useKeyboardShortcuts() && self.message()) + if (Globals.useKeyboardShortcuts() && self.message()) { self.message.focused(true); } @@ -407,13 +410,13 @@ }, this); this.messageDomFocused.subscribe(function (bValue) { - if (!bValue && Enums.KeyState.MessageView === this.keyScope()) + if (!bValue && Enums.KeyState.MessageView === Globals.keyScope()) { this.message.focused(false); } }, this); - this.keyScope.subscribe(function (sValue) { + Globals.keyScope.subscribe(function (sValue) { if (Enums.KeyState.MessageView === sValue && this.message.focused()) { this.messageDomFocused(true); @@ -437,7 +440,7 @@ { this.fullScreenMode(false); } - else if (Enums.Layout.NoPreview === RL.data().layout()) + else if (Enums.Layout.NoPreview === Data.layout()) { this.message(null); } @@ -453,8 +456,7 @@ MailBoxMessageViewViewModel.prototype.initShortcuts = function () { var - self = this, - oData = RL.data() + self = this ; // exit fullscreen, back @@ -467,7 +469,7 @@ }); key('enter', Enums.KeyState.MessageList, function () { - if (Enums.Layout.NoPreview !== oData.layout() && self.message()) + if (Enums.Layout.NoPreview !== Data.layout() && self.message()) { self.toggleFullScreen(); return false; @@ -482,7 +484,7 @@ // reply key('r', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () { - if (oData.message()) + if (Data.message()) { self.replyCommand(); return false; @@ -491,7 +493,7 @@ // replaAll key('a', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () { - if (oData.message()) + if (Data.message()) { self.replyAllCommand(); return false; @@ -500,7 +502,7 @@ // forward key('f', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () { - if (oData.message()) + if (Data.message()) { self.forwardCommand(); return false; @@ -518,9 +520,9 @@ // toggle message blockquotes key('b', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () { - if (oData.message() && oData.message().body) + if (Data.message() && Data.message().body) { - Utils.toggleMessageBlockquote(oData.message().body); + Utils.toggleMessageBlockquote(Data.message().body); return false; } }); @@ -564,7 +566,7 @@ // change focused state key('tab, shift+tab, left', Enums.KeyState.MessageView, function () { - if (!self.fullScreenMode() && self.message() && Enums.Layout.NoPreview !== oData.layout()) + if (!self.fullScreenMode() && self.message() && Enums.Layout.NoPreview !== Data.layout()) { self.message.focused(false); } @@ -578,7 +580,7 @@ */ MailBoxMessageViewViewModel.prototype.isDraftFolder = function () { - return RL.data().message() && RL.data().draftFolder() === RL.data().message().folderFullNameRaw; + return Data.message() && Data.draftFolder() === Data.message().folderFullNameRaw; }; /** @@ -586,7 +588,7 @@ */ MailBoxMessageViewViewModel.prototype.isSentFolder = function () { - return RL.data().message() && RL.data().sentFolder() === RL.data().message().folderFullNameRaw; + return Data.message() && Data.sentFolder() === Data.message().folderFullNameRaw; }; /** @@ -594,7 +596,7 @@ */ MailBoxMessageViewViewModel.prototype.isSpamFolder = function () { - return RL.data().message() && RL.data().spamFolder() === RL.data().message().folderFullNameRaw; + return Data.message() && Data.spamFolder() === Data.message().folderFullNameRaw; }; /** @@ -602,7 +604,7 @@ */ MailBoxMessageViewViewModel.prototype.isSpamDisabled = function () { - return RL.data().message() && RL.data().spamFolder() === Consts.Values.UnuseOptionValue; + return Data.message() && Data.spamFolder() === Consts.Values.UnuseOptionValue; }; /** @@ -610,7 +612,7 @@ */ MailBoxMessageViewViewModel.prototype.isArchiveFolder = function () { - return RL.data().message() && RL.data().archiveFolder() === RL.data().message().folderFullNameRaw; + return Data.message() && Data.archiveFolder() === Data.message().folderFullNameRaw; }; /** @@ -618,7 +620,7 @@ */ MailBoxMessageViewViewModel.prototype.isArchiveDisabled = function () { - return RL.data().message() && RL.data().archiveFolder() === Consts.Values.UnuseOptionValue; + return Data.message() && Data.archiveFolder() === Consts.Values.UnuseOptionValue; }; /** @@ -636,9 +638,9 @@ MailBoxMessageViewViewModel.prototype.editMessage = function () { - if (RL.data().message()) + if (Data.message()) { - kn.showScreenPopup(PopupsComposeViewModel, [Enums.ComposeType.Draft, RL.data().message()]); + kn.showScreenPopup(PopupsComposeViewModel, [Enums.ComposeType.Draft, Data.message()]); } }; @@ -703,7 +705,7 @@ Remote.sendReadReceiptMessage(Utils.emptyFunction, oMessage.folderFullNameRaw, oMessage.uid, oMessage.readReceipt(), Utils.i18n('READ_RECEIPT/SUBJECT', {'SUBJECT': oMessage.subject()}), - Utils.i18n('READ_RECEIPT/BODY', {'READ-RECEIPT': RL.data().accountEmail()})); + Utils.i18n('READ_RECEIPT/BODY', {'READ-RECEIPT': Data.accountEmail()})); oMessage.isReadReceipt(true); diff --git a/dev/ViewModels/Popups/PopupsActivateViewModel.js b/dev/ViewModels/Popups/PopupsActivateViewModel.js index c24a4355a..3af9e3cca 100644 --- a/dev/ViewModels/Popups/PopupsActivateViewModel.js +++ b/dev/ViewModels/Popups/PopupsActivateViewModel.js @@ -9,6 +9,7 @@ Enums = require('../../Common/Enums.js'), Utils = require('../../Common/Utils.js'), + AppSettings = require('../../Storages/AppSettings.js'), Data = require('../../Storages/AdminDataStorage.js'), Remote = require('../../Storages/AdminAjaxRemoteStorage.js'), @@ -106,7 +107,7 @@ PopupsActivateViewModel.prototype.onShow = function () { - this.domain(RL.settingsGet('AdminDomain')); + this.domain(AppSettings.settingsGet('AdminDomain')); if (!this.activateProcess()) { this.key(''); @@ -133,6 +134,6 @@ return '' === sValue || !!/^RL[\d]+-[A-Z0-9\-]+Z$/.test(Utils.trim(sValue)); }; - module.exports = new PopupsActivateViewModel(); + module.exports = PopupsActivateViewModel; }(module)); \ No newline at end of file diff --git a/dev/ViewModels/Popups/PopupsAddAccountViewModel.js b/dev/ViewModels/Popups/PopupsAddAccountViewModel.js index 4882f62ee..6409e1994 100644 --- a/dev/ViewModels/Popups/PopupsAddAccountViewModel.js +++ b/dev/ViewModels/Popups/PopupsAddAccountViewModel.js @@ -11,6 +11,8 @@ Utils = require('../../Common/Utils.js'), Remote = require('../../Storages/WebMailAjaxRemoteStorage.js'), + + RL = require('../../Boots/RainLoopApp.js'), kn = require('../../Knoin/Knoin.js'), KnoinAbstractViewModel = require('../../Knoin/KnoinAbstractViewModel.js') @@ -110,6 +112,6 @@ this.emailFocus(true); }; - module.exports = new PopupsAddAccountViewModel(); + module.exports = PopupsAddAccountViewModel; }(module)); \ No newline at end of file diff --git a/dev/ViewModels/Popups/PopupsAddOpenPgpKeyViewModel.js b/dev/ViewModels/Popups/PopupsAddOpenPgpKeyViewModel.js index fccb0a134..dd73efddc 100644 --- a/dev/ViewModels/Popups/PopupsAddOpenPgpKeyViewModel.js +++ b/dev/ViewModels/Popups/PopupsAddOpenPgpKeyViewModel.js @@ -11,6 +11,8 @@ Data = require('../../Storages/WebMailDataStorage.js'), + RL = require('../../Boots/RainLoopApp.js'), + kn = require('../../Knoin/Knoin.js'), KnoinAbstractViewModel = require('../../Knoin/KnoinAbstractViewModel.js') ; @@ -104,6 +106,6 @@ this.key.focus(true); }; - module.exports = new PopupsAddOpenPgpKeyViewModel(); + module.exports = PopupsAddOpenPgpKeyViewModel; }(module)); \ No newline at end of file diff --git a/dev/ViewModels/Popups/PopupsAdvancedSearchViewModel.js b/dev/ViewModels/Popups/PopupsAdvancedSearchViewModel.js index f83ebc53d..7f86adae4 100644 --- a/dev/ViewModels/Popups/PopupsAdvancedSearchViewModel.js +++ b/dev/ViewModels/Popups/PopupsAdvancedSearchViewModel.js @@ -152,6 +152,6 @@ this.fromFocus(true); }; - module.exports = new PopupsAdvancedSearchViewModel(); + module.exports = PopupsAdvancedSearchViewModel; }(module)); \ No newline at end of file diff --git a/dev/ViewModels/Popups/PopupsAskViewModel.js b/dev/ViewModels/Popups/PopupsAskViewModel.js index 2bad36503..02a5f4452 100644 --- a/dev/ViewModels/Popups/PopupsAskViewModel.js +++ b/dev/ViewModels/Popups/PopupsAskViewModel.js @@ -123,6 +123,6 @@ }, this)); }; - module.exports = new PopupsAskViewModel(); + module.exports = PopupsAskViewModel; }(module)); \ No newline at end of file diff --git a/dev/ViewModels/Popups/PopupsComposeOpenPgpViewModel.js b/dev/ViewModels/Popups/PopupsComposeOpenPgpViewModel.js index a3740f407..92efc90a0 100644 --- a/dev/ViewModels/Popups/PopupsComposeOpenPgpViewModel.js +++ b/dev/ViewModels/Popups/PopupsComposeOpenPgpViewModel.js @@ -257,6 +257,6 @@ this.text(sText); }; - module.exports = new PopupsComposeOpenPgpViewModel(); + module.exports = PopupsComposeOpenPgpViewModel; }(module)); \ No newline at end of file diff --git a/dev/ViewModels/Popups/PopupsComposeViewModel.js b/dev/ViewModels/Popups/PopupsComposeViewModel.js index ec782c908..b5d1393ee 100644 --- a/dev/ViewModels/Popups/PopupsComposeViewModel.js +++ b/dev/ViewModels/Popups/PopupsComposeViewModel.js @@ -5,6 +5,7 @@ 'use strict'; var + window = require('../../External/window.js'), $ = require('../../External/jquery.js'), _ = require('../../External/underscore.js'), ko = require('../../External/ko.js'), @@ -13,12 +14,20 @@ Enums = require('../../Common/Enums.js'), Consts = require('../../Common/Consts.js'), Utils = require('../../Common/Utils.js'), - LinkBuilder = require('../Common/LinkBuilder.js'), + Globals = require('../../Common/Globals.js'), + LinkBuilder = require('../../Common/LinkBuilder.js'), + Events = require('../../Common/Events.js'), + NewHtmlEditorWrapper = require('../../Common/NewHtmlEditorWrapper.js'), + AppSettings = require('../../Storages/AppSettings.js'), Data = require('../../Storages/WebMailDataStorage.js'), Cache = require('../../Storages/WebMailCacheStorage.js'), Remote = require('../../Storages/WebMailAjaxRemoteStorage.js'), + RL = require('../../Boots/RainLoopApp.js'), + + PopupsComposeOpenPgpViewModel = require('./PopupsComposeOpenPgpViewModel.js'), + kn = require('../../Knoin/Knoin.js'), KnoinAbstractViewModel = require('../../Knoin/KnoinAbstractViewModel.js') ; @@ -38,7 +47,7 @@ this.bSkipNext = false; this.sReferences = ''; - this.bCapaAdditionalIdentities = RL.capa(Enums.Capa.AdditionalIdentities); + this.bCapaAdditionalIdentities = AppSettings.capa(Enums.Capa.AdditionalIdentities); var self = this, @@ -330,7 +339,7 @@ }, this.canBeSendedOrSaved); - RL.sub('interval.1m', function () { + Events.sub('interval.1m', function () { if (this.modalVisibility() && !Data.draftFolderNotEnabled() && !this.isEmptyForm(false) && !this.bSkipNext && !this.saving() && !this.sending() && !this.savedError()) { @@ -343,7 +352,7 @@ this.triggerForResize(); }, this); - this.dropboxEnabled = ko.observable(!!RL.settingsGet('DropboxApiKey')); + this.dropboxEnabled = ko.observable(!!AppSettings.settingsGet('DropboxApiKey')); this.dropboxCommand = Utils.createCommand(this, function () { @@ -370,7 +379,7 @@ }); this.driveEnabled = ko.observable(Globals.bXMLHttpRequestSupported && - !!RL.settingsGet('GoogleClientID') && !!RL.settingsGet('GoogleApiKey')); + !!AppSettings.settingsGet('GoogleClientID') && !!AppSettings.settingsGet('GoogleApiKey')); this.driveVisible = ko.observable(false); @@ -390,11 +399,22 @@ this.tryToClosePopup = _.debounce(_.bind(this.tryToClosePopup, this), 200); + this.emailsSource = _.bind(this.emailsSource, this); + kn.constructorEnd(this); } kn.extendAsViewModel('PopupsComposeViewModel', PopupsComposeViewModel); + PopupsComposeViewModel.prototype.emailsSource = function (oData, fResponse) + { + RL.getAutocomplete(oData.term, function (aData) { + fResponse(_.map(aData, function (oEmailItem) { + return oEmailItem.toLine(false); + })); + }); + }; + PopupsComposeViewModel.prototype.openOpenPgpPopup = function () { if (this.capaOpenPGP() && this.oEditor && !this.oEditor.isHtml()) @@ -1037,7 +1057,7 @@ oScript = document.createElement('script'); oScript.type = 'text/javascript'; oScript.src = 'https://www.dropbox.com/static/api/1/dropins.js'; - $(oScript).attr('id', 'dropboxjs').attr('data-app-key', RL.settingsGet('DropboxApiKey')); + $(oScript).attr('id', 'dropboxjs').attr('data-app-key', AppSettings.settingsGet('DropboxApiKey')); document.body.appendChild(oScript); } @@ -1136,7 +1156,7 @@ new window.google.picker.DocsView() .setIncludeFolders(true) ) - .setAppId(RL.settingsGet('GoogleClientID')) + .setAppId(AppSettings.settingsGet('GoogleClientID')) .setOAuthToken(oOauthToken.access_token) .setCallback(_.bind(self.driveCallback, self, oOauthToken.access_token)) .enableFeature(window.google.picker.Feature.NAV_HIDDEN) @@ -1161,7 +1181,7 @@ if (!oAuthToken) { window.gapi.auth.authorize({ - 'client_id': RL.settingsGet('GoogleClientID'), + 'client_id': AppSettings.settingsGet('GoogleClientID'), 'scope': 'https://www.googleapis.com/auth/drive.readonly', 'immediate': true }, function (oAuthResult) { @@ -1176,7 +1196,7 @@ else { window.gapi.auth.authorize({ - 'client_id': RL.settingsGet('GoogleClientID'), + 'client_id': AppSettings.settingsGet('GoogleClientID'), 'scope': 'https://www.googleapis.com/auth/drive.readonly', 'immediate': false }, function (oAuthResult) { @@ -1229,7 +1249,7 @@ { var oUploadCache = {}, - iAttachmentSizeLimit = Utils.pInt(RL.settingsGet('AttachmentLimit')), + iAttachmentSizeLimit = Utils.pInt(AppSettings.settingsGet('AttachmentLimit')), oJua = new Jua({ 'action': LinkBuilder.upload(), 'name': 'uploader', @@ -1478,7 +1498,7 @@ }); }; }, - iAttachmentSizeLimit = Utils.pInt(RL.settingsGet('AttachmentLimit')), + iAttachmentSizeLimit = Utils.pInt(AppSettings.settingsGet('AttachmentLimit')), mSize = oDropboxFile['bytes'] ; @@ -1539,7 +1559,7 @@ }); }; }, - iAttachmentSizeLimit = Utils.pInt(RL.settingsGet('AttachmentLimit')), + iAttachmentSizeLimit = Utils.pInt(AppSettings.settingsGet('AttachmentLimit')), oAttachment = null, mSize = oDriveFile['fileSize'] ? Utils.pInt(oDriveFile['fileSize']) : 0 ; @@ -1751,6 +1771,6 @@ this.editorResizeThrottle(); }; - module.exports = new PopupsComposeViewModel(); + module.exports = PopupsComposeViewModel; }(module)); \ No newline at end of file diff --git a/dev/ViewModels/Popups/PopupsContactsViewModel.js b/dev/ViewModels/Popups/PopupsContactsViewModel.js index 39388837c..a825a6e91 100644 --- a/dev/ViewModels/Popups/PopupsContactsViewModel.js +++ b/dev/ViewModels/Popups/PopupsContactsViewModel.js @@ -15,11 +15,14 @@ Consts = require('../../Common/Consts.js'), Globals = require('../../Common/Globals.js'), Utils = require('../../Common/Utils.js'), - LinkBuilder = require('../Common/LinkBuilder.js'), + LinkBuilder = require('../../Common/LinkBuilder.js'), + Selector = require('../../Common/Selector.js'), Data = require('../../Storages/WebMailDataStorage.js'), Remote = require('../../Storages/WebMailAjaxRemoteStorage.js'), + RL = require('../../Boots/RainLoopApp.js'), + kn = require('../../Knoin/Knoin.js'), KnoinAbstractViewModel = require('../../Knoin/KnoinAbstractViewModel.js') ; @@ -380,11 +383,22 @@ this.sDefaultKeyScope = Enums.KeyState.ContactList; + this.contactTagsSource = _.bind(this.contactTagsSource, this); + kn.constructorEnd(this); } kn.extendAsViewModel('PopupsContactsViewModel', PopupsContactsViewModel); + PopupsContactsViewModel.prototype.contactTagsSource = function (oData, fResponse) + { + RL.getContactTagsAutocomplete(oData.term, function (aData) { + fResponse(_.map(aData, function (oTagItem) { + return oTagItem.toLine(false); + })); + }); + }; + PopupsContactsViewModel.prototype.getPropertyPlceholder = function (sType) { var sResult = ''; @@ -763,6 +777,6 @@ this.contacts([]); }; - module.exports = new PopupsContactsViewModel(); + module.exports = PopupsContactsViewModel; }(module)); \ No newline at end of file diff --git a/dev/ViewModels/Popups/PopupsDomainViewModel.js b/dev/ViewModels/Popups/PopupsDomainViewModel.js index 6c6b3b38e..2274c781c 100644 --- a/dev/ViewModels/Popups/PopupsDomainViewModel.js +++ b/dev/ViewModels/Popups/PopupsDomainViewModel.js @@ -13,6 +13,8 @@ Utils = require('../../Common/Utils.js'), Remote = require('../../Storages/AdminAjaxRemoteStorage.js'), + + RL = require('../../Boots/AdminApp.js'), kn = require('../../Knoin/Knoin.js'), KnoinAbstractViewModel = require('../../Knoin/KnoinAbstractViewModel.js') @@ -313,6 +315,6 @@ this.whiteList(''); }; - module.exports = new PopupsDomainViewModel(); + module.exports = PopupsDomainViewModel; }(module)); \ No newline at end of file diff --git a/dev/ViewModels/Popups/PopupsFiterViewModel.js b/dev/ViewModels/Popups/PopupsFilterViewModel.js similarity index 90% rename from dev/ViewModels/Popups/PopupsFiterViewModel.js rename to dev/ViewModels/Popups/PopupsFilterViewModel.js index b56737b65..66d39647a 100644 --- a/dev/ViewModels/Popups/PopupsFiterViewModel.js +++ b/dev/ViewModels/Popups/PopupsFilterViewModel.js @@ -47,11 +47,6 @@ this.filter(oFilter); }; -// PopupsFilterViewModel.prototype.onFocus = function () -// { -// -// }; - - module.exports = new PopupsFilterViewModel(); + module.exports = PopupsFilterViewModel; }(module)); \ No newline at end of file diff --git a/dev/ViewModels/Popups/PopupsFolderClearViewModel.js b/dev/ViewModels/Popups/PopupsFolderClearViewModel.js index f0b1a2839..a3e4d38b6 100644 --- a/dev/ViewModels/Popups/PopupsFolderClearViewModel.js +++ b/dev/ViewModels/Popups/PopupsFolderClearViewModel.js @@ -15,6 +15,8 @@ Cache = require('../../Storages/WebMailCacheStorage.js'), Remote = require('../../Storages/WebMailAjaxRemoteStorage.js'), + RL = require('../../Boots/RainLoopApp.js'), + kn = require('../../Knoin/Knoin.js'), KnoinAbstractViewModel = require('../../Knoin/KnoinAbstractViewModel.js') ; @@ -115,6 +117,6 @@ } }; - module.exports = new PopupsFolderClearViewModel(); + module.exports = PopupsFolderClearViewModel; }(module)); diff --git a/dev/ViewModels/Popups/PopupsFolderCreateViewModel.js b/dev/ViewModels/Popups/PopupsFolderCreateViewModel.js index f659c4fe3..e0192ec35 100644 --- a/dev/ViewModels/Popups/PopupsFolderCreateViewModel.js +++ b/dev/ViewModels/Popups/PopupsFolderCreateViewModel.js @@ -14,6 +14,8 @@ Data = require('../../Storages/WebMailDataStorage.js'), Remote = require('../../Storages/WebMailAjaxRemoteStorage.js'), + RL = require('../../Boots/RainLoopApp.js'), + kn = require('../../Knoin/Knoin.js'), KnoinAbstractViewModel = require('../../Knoin/KnoinAbstractViewModel.js') ; @@ -57,7 +59,7 @@ }; } - return RL.folderListOptionsBuilder([], aList, [], aTop, null, fDisableCallback, fVisibleCallback, fRenameCallback); + return Utils.folderListOptionsBuilder([], aList, [], aTop, null, fDisableCallback, fVisibleCallback, fRenameCallback); }, this); @@ -123,6 +125,6 @@ this.folderName.focused(true); }; - module.exports = new PopupsFolderCreateViewModel(); + module.exports = PopupsFolderCreateViewModel; }(module)); \ No newline at end of file diff --git a/dev/ViewModels/Popups/PopupsFolderSystemViewModel.js b/dev/ViewModels/Popups/PopupsFolderSystemViewModel.js index ead50695e..81997cdac 100644 --- a/dev/ViewModels/Popups/PopupsFolderSystemViewModel.js +++ b/dev/ViewModels/Popups/PopupsFolderSystemViewModel.js @@ -11,9 +11,12 @@ Consts = require('../../Common/Consts.js'), Utils = require('../../Common/Utils.js'), + AppSettings = require('../../Storages/AppSettings.js'), Data = require('../../Storages/WebMailDataStorage.js'), Remote = require('../../Storages/WebMailAjaxRemoteStorage.js'), + RL = require('../../Boots/RainLoopApp.js'), + kn = require('../../Knoin/Knoin.js'), KnoinAbstractViewModel = require('../../Knoin/KnoinAbstractViewModel.js') ; @@ -34,7 +37,7 @@ this.notification = ko.observable(''); this.folderSelectList = ko.computed(function () { - return RL.folderListOptionsBuilder([], Data.folderList(), Data.folderListSystemNames(), [ + return Utils.folderListOptionsBuilder([], Data.folderList(), Data.folderListSystemNames(), [ ['', this.sChooseOnText], [Consts.Values.UnuseOptionValue, this.sUnuseText] ]); @@ -54,11 +57,11 @@ fSaveSystemFolders = _.debounce(function () { - RL.settingsSet('SentFolder', self.sentFolder()); - RL.settingsSet('DraftFolder', self.draftFolder()); - RL.settingsSet('SpamFolder', self.spamFolder()); - RL.settingsSet('TrashFolder', self.trashFolder()); - RL.settingsSet('ArchiveFolder', self.archiveFolder()); + AppSettings.settingsSet('SentFolder', self.sentFolder()); + AppSettings.settingsSet('DraftFolder', self.draftFolder()); + AppSettings.settingsSet('SpamFolder', self.spamFolder()); + AppSettings.settingsSet('TrashFolder', self.trashFolder()); + AppSettings.settingsSet('ArchiveFolder', self.archiveFolder()); Remote.saveSystemFolders(Utils.emptyFunction, { 'SentFolder': self.sentFolder(), @@ -73,11 +76,11 @@ fCallback = function () { - RL.settingsSet('SentFolder', self.sentFolder()); - RL.settingsSet('DraftFolder', self.draftFolder()); - RL.settingsSet('SpamFolder', self.spamFolder()); - RL.settingsSet('TrashFolder', self.trashFolder()); - RL.settingsSet('ArchiveFolder', self.archiveFolder()); + AppSettings.settingsSet('SentFolder', self.sentFolder()); + AppSettings.settingsSet('DraftFolder', self.draftFolder()); + AppSettings.settingsSet('SpamFolder', self.spamFolder()); + AppSettings.settingsSet('TrashFolder', self.trashFolder()); + AppSettings.settingsSet('ArchiveFolder', self.archiveFolder()); fSaveSystemFolders(); }; @@ -129,6 +132,6 @@ this.notification(sNotification); }; - module.exports = new PopupsFolderSystemViewModel(); + module.exports = PopupsFolderSystemViewModel; }(module)); \ No newline at end of file diff --git a/dev/ViewModels/Popups/PopupsGenerateNewOpenPgpKeyViewModel.js b/dev/ViewModels/Popups/PopupsGenerateNewOpenPgpKeyViewModel.js index b4f3f8e06..b6b5f1b12 100644 --- a/dev/ViewModels/Popups/PopupsGenerateNewOpenPgpKeyViewModel.js +++ b/dev/ViewModels/Popups/PopupsGenerateNewOpenPgpKeyViewModel.js @@ -12,6 +12,8 @@ Data = require('../../Storages/WebMailDataStorage.js'), + RL = require('../../Boots/RainLoopApp.js'), + kn = require('../../Knoin/Knoin.js'), KnoinAbstractViewModel = require('../../Knoin/KnoinAbstractViewModel.js') ; @@ -110,6 +112,6 @@ this.email.focus(true); }; - module.exports = new PopupsGenerateNewOpenPgpKeyViewModel(); + module.exports = PopupsGenerateNewOpenPgpKeyViewModel; }(module)); \ No newline at end of file diff --git a/dev/ViewModels/Popups/PopupsIdentityViewModel.js b/dev/ViewModels/Popups/PopupsIdentityViewModel.js index d9b9cf283..3eeb1f51e 100644 --- a/dev/ViewModels/Popups/PopupsIdentityViewModel.js +++ b/dev/ViewModels/Popups/PopupsIdentityViewModel.js @@ -14,6 +14,8 @@ Remote = require('../../Storages/WebMailAjaxRemoteStorage.js'), Data = require('../../Storages/WebMailDataStorage.js'), + RL = require('../../Boots/RainLoopApp.js'), + KnoinAbstractViewModel = require('../../Knoin/KnoinAbstractViewModel.js') ; @@ -165,6 +167,6 @@ } }; - module.exports = new PopupsIdentityViewModel(); + module.exports = PopupsIdentityViewModel; }(module)); \ No newline at end of file diff --git a/dev/ViewModels/Popups/PopupsKeyboardShortcutsHelpViewModel.js b/dev/ViewModels/Popups/PopupsKeyboardShortcutsHelpViewModel.js index 5cbb2a9f2..f6e52ae92 100644 --- a/dev/ViewModels/Popups/PopupsKeyboardShortcutsHelpViewModel.js +++ b/dev/ViewModels/Popups/PopupsKeyboardShortcutsHelpViewModel.js @@ -58,6 +58,6 @@ }, this)); }; - module.exports = new AdminPaneViewModel(); + module.exports = PopupsKeyboardShortcutsHelpViewModel; }(module)); \ No newline at end of file diff --git a/dev/ViewModels/Popups/PopupsLanguagesViewModel.js b/dev/ViewModels/Popups/PopupsLanguagesViewModel.js index b64d0c9d9..973d7fcb9 100644 --- a/dev/ViewModels/Popups/PopupsLanguagesViewModel.js +++ b/dev/ViewModels/Popups/PopupsLanguagesViewModel.js @@ -76,6 +76,6 @@ this.cancelCommand(); }; - module.exports = new PopupsLanguagesViewModel(); + module.exports = PopupsLanguagesViewModel; }(module)); \ No newline at end of file diff --git a/dev/ViewModels/Popups/PopupsPluginViewModel.js b/dev/ViewModels/Popups/PopupsPluginViewModel.js index 3921a156b..8c3f49a6f 100644 --- a/dev/ViewModels/Popups/PopupsPluginViewModel.js +++ b/dev/ViewModels/Popups/PopupsPluginViewModel.js @@ -160,6 +160,6 @@ }, this)); }; - module.exports = new PopupsPluginViewModel(); + module.exports = PopupsPluginViewModel; }(module)); \ No newline at end of file diff --git a/dev/ViewModels/Popups/PopupsTwoFactorTestViewModel.js b/dev/ViewModels/Popups/PopupsTwoFactorTestViewModel.js index 603e9d5e0..5317d02be 100644 --- a/dev/ViewModels/Popups/PopupsTwoFactorTestViewModel.js +++ b/dev/ViewModels/Popups/PopupsTwoFactorTestViewModel.js @@ -70,6 +70,6 @@ this.code.focused(true); }; - module.exports = new PopupsTwoFactorTestViewModel(); + module.exports = PopupsTwoFactorTestViewModel; }(module)); \ No newline at end of file diff --git a/dev/ViewModels/Popups/PopupsViewOpenPgpKeyViewModel.js b/dev/ViewModels/Popups/PopupsViewOpenPgpKeyViewModel.js index c3732ba5f..03928e4bd 100644 --- a/dev/ViewModels/Popups/PopupsViewOpenPgpKeyViewModel.js +++ b/dev/ViewModels/Popups/PopupsViewOpenPgpKeyViewModel.js @@ -51,6 +51,6 @@ } }; - module.exports = new PopupsViewOpenPgpKeyViewModel(); + module.exports = PopupsViewOpenPgpKeyViewModel; }(module)); \ No newline at end of file diff --git a/dev/ViewModels/SettingsMenuViewModel.js b/dev/ViewModels/SettingsMenuViewModel.js index 7529c9a2a..4a2acd660 100644 --- a/dev/ViewModels/SettingsMenuViewModel.js +++ b/dev/ViewModels/SettingsMenuViewModel.js @@ -6,9 +6,8 @@ var LinkBuilder = require('../Common/LinkBuilder.js'), + Globals = require('../Common/Globals.js'), - Data = require('../Storages/WebMailDataStorage.js'), - kn = require('../Knoin/Knoin.js'), KnoinAbstractViewModel = require('../Knoin/KnoinAbstractViewModel.js') ; @@ -23,7 +22,7 @@ { KnoinAbstractViewModel.call(this, 'Left', 'SettingsMenu'); - this.leftPanelDisabled = Data.leftPanelDisabled; + this.leftPanelDisabled = Globals.leftPanelDisabled; this.menu = oScreen.menu; diff --git a/dev/ViewModels/SettingsSystemDropDownViewModel.js b/dev/ViewModels/SettingsSystemDropDownViewModel.js index 43039cb46..cac6272bc 100644 --- a/dev/ViewModels/SettingsSystemDropDownViewModel.js +++ b/dev/ViewModels/SettingsSystemDropDownViewModel.js @@ -5,7 +5,7 @@ 'use strict'; var - kn = require('./Knoin/Knoin.js'), + kn = require('../Knoin/Knoin.js'), AbstractSystemDropDownViewModel = require('./AbstractSystemDropDownViewModel.js') ; diff --git a/dev/RL.js b/dev/_AdminBoot.js similarity index 52% rename from dev/RL.js rename to dev/_AdminBoot.js index 85a86f65d..1ad4116c7 100644 --- a/dev/RL.js +++ b/dev/_AdminBoot.js @@ -1,7 +1,6 @@ -/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */ - -'use strict'; - -module.exports = function () { - return require('./Knoin/Knoin.js').rl(); -}; \ No newline at end of file +/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */ + +'use strict'; + +var boot = require('./Boots/Boot.js'); +boot(require('./Boots/AdminApp.js')); \ No newline at end of file diff --git a/dev/Remote.js b/dev/_RainLoopBoot.js similarity index 51% rename from dev/Remote.js rename to dev/_RainLoopBoot.js index e3270e6ab..1aa2712be 100644 --- a/dev/Remote.js +++ b/dev/_RainLoopBoot.js @@ -1,7 +1,6 @@ -/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */ - -'use strict'; - -module.exports = function () { - return require('./Knoin/Knoin.js').remote(); -}; \ No newline at end of file +/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */ + +'use strict'; + +var boot = require('./Boots/Boot.js'); +boot(require('./Boots/RainLoopApp.js')); \ No newline at end of file diff --git a/gulpfile.js b/gulpfile.js index 4e6a18a5a..95563275b 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -610,6 +610,7 @@ gulp.task('b+', ['rainloop+']); gulp.task('own', ['owncloud']); var browserify = require('browserify'); +var streamify = require('gulp-streamify'); var source = require('vinyl-source-stream'); gulp.task('bro', function() { @@ -618,8 +619,14 @@ gulp.task('bro', function() { 'detectGlobals': false, 'debug': false }) - .add('./RainLoopBoot.js') + .add('./_RainLoopBoot.js') .bundle() - .pipe(source('bro.js')) + .pipe(source('app.js')) +// .pipe(rename('app.min.js')) +// .pipe(streamify(uglify(cfg.uglify))) .pipe(gulp.dest(cfg.paths.staticJS)); }); + +gulp.task('ww', ['bro'], function() { + gulp.watch('dev/**/*.js', {interval: 1000}, ['bro']); +}); \ No newline at end of file diff --git a/package.json b/package.json index 63308eb88..3adba3162 100644 --- a/package.json +++ b/package.json @@ -59,6 +59,7 @@ "gulp-rename": "*", "gulp-header": "*", "gulp-footer": "*", + "gulp-streamify": "*", "gulp-minify-css": "*", "gulp-concat-util": "*" diff --git a/rainloop/v/0.0.0/app/templates/Views/App/PopupsCompose.html b/rainloop/v/0.0.0/app/templates/Views/App/PopupsCompose.html index 7ad66ca01..49497f0bb 100644 --- a/rainloop/v/0.0.0/app/templates/Views/App/PopupsCompose.html +++ b/rainloop/v/0.0.0/app/templates/Views/App/PopupsCompose.html @@ -57,7 +57,7 @@]*>([\s\S\r\n]*)<\/pre>/gmi, convertPre)
+ .replace(/[\s]+/gm, ' ')
+ .replace(/((?:href|data)\s?=\s?)("[^"]+?"|'[^']+?')/gmi, fixAttibuteValue)
+ .replace(/
]*>/gmi, '\n')
+ .replace(/<\/h[\d]>/gi, '\n')
+ .replace(/<\/p>/gi, '\n\n')
+ .replace(/<\/li>/gi, '\n')
+ .replace(/<\/td>/gi, '\n')
+ .replace(/<\/tr>/gi, '\n')
+ .replace(/
]*>/gmi, '\n_______________________________\n\n')
+ .replace(/]*>([\s\S\r\n]*)<\/div>/gmi, convertDivs)
+ .replace(/]*>/gmi, '\n__bq__start__\n')
+ .replace(/<\/blockquote>/gmi, '\n__bq__end__\n')
+ .replace(/]*>([\s\S\r\n]*?)<\/a>/gmi, convertLinks)
+ .replace(/<\/div>/gi, '\n')
+ .replace(/ /gi, ' ')
+ .replace(/"/gi, '"')
+ .replace(/<[^>]*>/gm, '')
+ ;
+
+ sText = Utils.$div.html(sText).text();
+
+ sText = sText
+ .replace(/\n[ \t]+/gm, '\n')
+ .replace(/[\n]{3,}/gm, '\n\n')
+ .replace(/>/gi, '>')
+ .replace(/</gi, '<')
+ .replace(/&/gi, '&')
+ ;
+
+ iPos = 0;
+ iLimit = 100;
+
+ while (0 < iLimit)
+ {
+ iLimit--;
+ iP1 = sText.indexOf('__bq__start__', iPos);
+ if (-1 < iP1)
+ {
+ iP2 = sText.indexOf('__bq__start__', iP1 + 5);
+ iP3 = sText.indexOf('__bq__end__', iP1 + 5);
+
+ if ((-1 === iP2 || iP3 < iP2) && iP1 < iP3)
+ {
+ sText = sText.substring(0, iP1) +
+ convertBlockquote(sText.substring(iP1 + 13, iP3)) +
+ sText.substring(iP3 + 11);
+
+ iPos = 0;
+ }
+ else if (-1 < iP2 && iP2 < iP3)
+ {
+ iPos = iP2 - 1;
+ }
+ else
+ {
+ iPos = 0;
+ }
+ }
+ else
+ {
+ break;
+ }
+ }
+
+ sText = sText
+ .replace(/__bq__start__/gm, '')
+ .replace(/__bq__end__/gm, '')
+ ;
+
+ return sText;
+};
+
+/**
+ * @param {string} sPlain
+ * @param {boolean} bLinkify = false
+ * @return {string}
+ */
+Utils.plainToHtml = function (sPlain, bLinkify)
+{
+ sPlain = sPlain.toString().replace(/\r/g, '');
+
+ var
+ bIn = false,
+ bDo = true,
+ bStart = true,
+ aNextText = [],
+ sLine = '',
+ iIndex = 0,
+ aText = sPlain.split("\n")
+ ;
+
+ do
+ {
+ bDo = false;
+ aNextText = [];
+ for (iIndex = 0; iIndex < aText.length; iIndex++)
+ {
+ sLine = aText[iIndex];
+ bStart = '>' === sLine.substr(0, 1);
+ if (bStart && !bIn)
+ {
+ bDo = true;
+ bIn = true;
+ aNextText.push('~~~blockquote~~~');
+ aNextText.push(sLine.substr(1));
+ }
+ else if (!bStart && bIn)
+ {
+ bIn = false;
+ aNextText.push('~~~/blockquote~~~');
+ aNextText.push(sLine);
+ }
+ else if (bStart && bIn)
+ {
+ aNextText.push(sLine.substr(1));
+ }
+ else
+ {
+ aNextText.push(sLine);
+ }
+ }
+
+ if (bIn)
+ {
+ bIn = false;
+ aNextText.push('~~~/blockquote~~~');
+ }
+
+ aText = aNextText;
+ }
+ while (bDo);
+
+ sPlain = aText.join("\n");
+
+ sPlain = sPlain
+ .replace(/&/g, '&')
+ .replace(/>/g, '>').replace(/')
+ .replace(/[\s]*~~~\/blockquote~~~/g, '
')
+ .replace(/[\-_~]{10,}/g, '
')
+ .replace(/\n/g, '
');
+
+ return bLinkify ? Utils.linkify(sPlain) : sPlain;
+};
+
+window.rainloop_Utils_htmlToPlain = Utils.htmlToPlain;
+window.rainloop_Utils_plainToHtml = Utils.plainToHtml;
+
+/**
+ * @param {string} sHtml
+ * @return {string}
+ */
+Utils.linkify = function (sHtml)
+{
+ if ($.fn && $.fn.linkify)
+ {
+ sHtml = Utils.$div.html(sHtml.replace(/&/ig, 'amp_amp_12345_amp_amp'))
+ .linkify()
+ .find('.linkified').removeClass('linkified').end()
+ .html()
+ .replace(/amp_amp_12345_amp_amp/g, '&')
+ ;
+ }
+
+ return sHtml;
+};
+
+Utils.resizeAndCrop = function (sUrl, iValue, fCallback)
+{
+ var oTempImg = new window.Image();
+ oTempImg.onload = function() {
+
+ var
+ aDiff = [0, 0],
+ oCanvas = document.createElement('canvas'),
+ oCtx = oCanvas.getContext('2d')
+ ;
+
+ oCanvas.width = iValue;
+ oCanvas.height = iValue;
+
+ if (this.width > this.height)
+ {
+ aDiff = [this.width - this.height, 0];
+ }
+ else
+ {
+ aDiff = [0, this.height - this.width];
+ }
+
+ oCtx.fillStyle = '#fff';
+ oCtx.fillRect(0, 0, iValue, iValue);
+ oCtx.drawImage(this, aDiff[0] / 2, aDiff[1] / 2, this.width - aDiff[0], this.height - aDiff[1], 0, 0, iValue, iValue);
+
+ fCallback(oCanvas.toDataURL('image/jpeg'));
+ };
+
+ oTempImg.src = sUrl;
+};
+
+Utils.computedPagenatorHelper = function (koCurrentPage, koPageCount)
+{
+ return function() {
+ var
+ iPrev = 0,
+ iNext = 0,
+ iLimit = 2,
+ aResult = [],
+ iCurrentPage = koCurrentPage(),
+ iPageCount = koPageCount(),
+
+ /**
+ * @param {number} iIndex
+ * @param {boolean=} bPush
+ * @param {string=} sCustomName
+ */
+ fAdd = function (iIndex, bPush, sCustomName) {
+
+ var oData = {
+ 'current': iIndex === iCurrentPage,
+ 'name': Utils.isUnd(sCustomName) ? iIndex.toString() : sCustomName.toString(),
+ 'custom': Utils.isUnd(sCustomName) ? false : true,
+ 'title': Utils.isUnd(sCustomName) ? '' : iIndex.toString(),
+ 'value': iIndex.toString()
+ };
+
+ if (Utils.isUnd(bPush) ? true : !!bPush)
+ {
+ aResult.push(oData);
+ }
+ else
+ {
+ aResult.unshift(oData);
+ }
+ }
+ ;
+
+ if (1 < iPageCount || (0 < iPageCount && iPageCount < iCurrentPage))
+// if (0 < iPageCount && 0 < iCurrentPage)
+ {
+ if (iPageCount < iCurrentPage)
+ {
+ fAdd(iPageCount);
+ iPrev = iPageCount;
+ iNext = iPageCount;
+ }
+ else
+ {
+ if (3 >= iCurrentPage || iPageCount - 2 <= iCurrentPage)
+ {
+ iLimit += 2;
+ }
+
+ fAdd(iCurrentPage);
+ iPrev = iCurrentPage;
+ iNext = iCurrentPage;
+ }
+
+ while (0 < iLimit) {
+
+ iPrev -= 1;
+ iNext += 1;
+
+ if (0 < iPrev)
+ {
+ fAdd(iPrev, false);
+ iLimit--;
+ }
+
+ if (iPageCount >= iNext)
+ {
+ fAdd(iNext, true);
+ iLimit--;
+ }
+ else if (0 >= iPrev)
+ {
+ break;
+ }
+ }
+
+ if (3 === iPrev)
+ {
+ fAdd(2, false);
+ }
+ else if (3 < iPrev)
+ {
+ fAdd(Math.round((iPrev - 1) / 2), false, '...');
+ }
+
+ if (iPageCount - 2 === iNext)
+ {
+ fAdd(iPageCount - 1, true);
+ }
+ else if (iPageCount - 2 > iNext)
+ {
+ fAdd(Math.round((iPageCount + iNext) / 2), true, '...');
+ }
+
+ // first and last
+ if (1 < iPrev)
+ {
+ fAdd(1, false);
+ }
+
+ if (iPageCount > iNext)
+ {
+ fAdd(iPageCount, true);
+ }
+ }
+
+ return aResult;
+ };
+};
+
+Utils.selectElement = function (element)
+{
+ /* jshint onevar: false */
+ if (window.getSelection)
+ {
+ var sel = window.getSelection();
+ sel.removeAllRanges();
+ var range = document.createRange();
+ range.selectNodeContents(element);
+ sel.addRange(range);
+ }
+ else if (document.selection)
+ {
+ var textRange = document.body.createTextRange();
+ textRange.moveToElementText(element);
+ textRange.select();
+ }
+ /* jshint onevar: true */
+};
+
+Utils.disableKeyFilter = function ()
+{
+ if (window.key)
+ {
+ key.filter = function () {
+ return RL.data().useKeyboardShortcuts();
+ };
+ }
+};
+
+Utils.restoreKeyFilter = function ()
+{
+ if (window.key)
+ {
+ key.filter = function (event) {
+
+ if (RL.data().useKeyboardShortcuts())
+ {
+ var
+ element = event.target || event.srcElement,
+ tagName = element ? element.tagName : ''
+ ;
+
+ tagName = tagName.toUpperCase();
+ return !(tagName === 'INPUT' || tagName === 'SELECT' || tagName === 'TEXTAREA' ||
+ (element && tagName === 'DIV' && 'editorHtmlArea' === element.className && element.contentEditable)
+ );
+ }
+
+ return false;
+ };
+ }
+};
+
+Utils.detectDropdownVisibility = _.debounce(function () {
+ Globals.dropdownVisibility(!!_.find(BootstrapDropdowns, function (oItem) {
+ return oItem.hasClass('open');
+ }));
+}, 50);
+
+Utils.triggerAutocompleteInputChange = function (bDelay) {
+
+ var fFunc = function () {
+ $('.checkAutocomplete').trigger('change');
+ };
+
+ if (bDelay)
+ {
+ _.delay(fFunc, 100);
+ }
+ else
+ {
+ fFunc();
+ }
+};
+
+
+
+/*jslint bitwise: true*/
+// Base64 encode / decode
+// http://www.webtoolkit.info/
+
+Base64 = {
+
+ // private property
+ _keyStr : 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
+
+ // public method for urlsafe encoding
+ urlsafe_encode : function (input) {
+ return Base64.encode(input).replace(/[+]/g, '-').replace(/[\/]/g, '_').replace(/[=]/g, '.');
+ },
+
+ // public method for encoding
+ encode : function (input) {
+ var
+ output = '',
+ chr1, chr2, chr3, enc1, enc2, enc3, enc4,
+ i = 0
+ ;
+
+ input = Base64._utf8_encode(input);
+
+ while (i < input.length)
+ {
+ chr1 = input.charCodeAt(i++);
+ chr2 = input.charCodeAt(i++);
+ chr3 = input.charCodeAt(i++);
+
+ enc1 = chr1 >> 2;
+ enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
+ enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
+ enc4 = chr3 & 63;
+
+ if (isNaN(chr2))
+ {
+ enc3 = enc4 = 64;
+ }
+ else if (isNaN(chr3))
+ {
+ enc4 = 64;
+ }
+
+ output = output +
+ this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
+ this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
+ }
+
+ return output;
+ },
+
+ // public method for decoding
+ decode : function (input) {
+ var
+ output = '',
+ chr1, chr2, chr3, enc1, enc2, enc3, enc4,
+ i = 0
+ ;
+
+ input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
+
+ while (i < input.length)
+ {
+ enc1 = this._keyStr.indexOf(input.charAt(i++));
+ enc2 = this._keyStr.indexOf(input.charAt(i++));
+ enc3 = this._keyStr.indexOf(input.charAt(i++));
+ enc4 = this._keyStr.indexOf(input.charAt(i++));
+
+ chr1 = (enc1 << 2) | (enc2 >> 4);
+ chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
+ chr3 = ((enc3 & 3) << 6) | enc4;
+
+ output = output + String.fromCharCode(chr1);
+
+ if (enc3 !== 64)
+ {
+ output = output + String.fromCharCode(chr2);
+ }
+
+ if (enc4 !== 64)
+ {
+ output = output + String.fromCharCode(chr3);
+ }
+ }
+
+ return Base64._utf8_decode(output);
+ },
+
+ // private method for UTF-8 encoding
+ _utf8_encode : function (string) {
+
+ string = string.replace(/\r\n/g, "\n");
+
+ var
+ utftext = '',
+ n = 0,
+ l = string.length,
+ c = 0
+ ;
+
+ for (; n < l; n++) {
+
+ c = string.charCodeAt(n);
+
+ if (c < 128)
+ {
+ utftext += String.fromCharCode(c);
+ }
+ else if ((c > 127) && (c < 2048))
+ {
+ utftext += String.fromCharCode((c >> 6) | 192);
+ utftext += String.fromCharCode((c & 63) | 128);
+ }
+ else
+ {
+ utftext += String.fromCharCode((c >> 12) | 224);
+ utftext += String.fromCharCode(((c >> 6) & 63) | 128);
+ utftext += String.fromCharCode((c & 63) | 128);
+ }
+ }
+
+ return utftext;
+ },
+
+ // private method for UTF-8 decoding
+ _utf8_decode : function (utftext) {
+ var
+ string = '',
+ i = 0,
+ c = 0,
+ c2 = 0,
+ c3 = 0
+ ;
+
+ while ( i < utftext.length )
+ {
+ c = utftext.charCodeAt(i);
+
+ if (c < 128)
+ {
+ string += String.fromCharCode(c);
+ i++;
+ }
+ else if((c > 191) && (c < 224))
+ {
+ c2 = utftext.charCodeAt(i+1);
+ string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
+ i += 2;
+ }
+ else
+ {
+ c2 = utftext.charCodeAt(i+1);
+ c3 = utftext.charCodeAt(i+2);
+ string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
+ i += 3;
+ }
+ }
+
+ return string;
+ }
+};
+
+/*jslint bitwise: false*/
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+ko.bindingHandlers.tooltip = {
+ 'init': function (oElement, fValueAccessor) {
+ if (!Globals.bMobileDevice)
+ {
+ var
+ $oEl = $(oElement),
+ sClass = $oEl.data('tooltip-class') || '',
+ sPlacement = $oEl.data('tooltip-placement') || 'top'
+ ;
+
+ $oEl.tooltip({
+ 'delay': {
+ 'show': 500,
+ 'hide': 100
+ },
+ 'html': true,
+ 'container': 'body',
+ 'placement': sPlacement,
+ 'trigger': 'hover',
+ 'title': function () {
+ return $oEl.is('.disabled') || Globals.dropdownVisibility() ? '' : '' +
+ Utils.i18n(ko.utils.unwrapObservable(fValueAccessor())) + '';
+ }
+ }).click(function () {
+ $oEl.tooltip('hide');
+ });
+
+ Globals.tooltipTrigger.subscribe(function () {
+ $oEl.tooltip('hide');
+ });
+ }
+ }
+};
+
+ko.bindingHandlers.tooltip2 = {
+ 'init': function (oElement, fValueAccessor) {
+ var
+ $oEl = $(oElement),
+ sClass = $oEl.data('tooltip-class') || '',
+ sPlacement = $oEl.data('tooltip-placement') || 'top'
+ ;
+
+ $oEl.tooltip({
+ 'delay': {
+ 'show': 500,
+ 'hide': 100
+ },
+ 'html': true,
+ 'container': 'body',
+ 'placement': sPlacement,
+ 'title': function () {
+ return $oEl.is('.disabled') || Globals.dropdownVisibility() ? '' :
+ '' + fValueAccessor()() + '';
+ }
+ }).click(function () {
+ $oEl.tooltip('hide');
+ });
+
+ Globals.tooltipTrigger.subscribe(function () {
+ $oEl.tooltip('hide');
+ });
+ }
+};
+
+ko.bindingHandlers.tooltip3 = {
+ 'init': function (oElement) {
+
+ var $oEl = $(oElement);
+
+ $oEl.tooltip({
+ 'container': 'body',
+ 'trigger': 'hover manual',
+ 'title': function () {
+ return $oEl.data('tooltip3-data') || '';
+ }
+ });
+
+ $document.click(function () {
+ $oEl.tooltip('hide');
+ });
+
+ Globals.tooltipTrigger.subscribe(function () {
+ $oEl.tooltip('hide');
+ });
+ },
+ 'update': function (oElement, fValueAccessor) {
+ var sValue = ko.utils.unwrapObservable(fValueAccessor());
+ if ('' === sValue)
+ {
+ $(oElement).data('tooltip3-data', '').tooltip('hide');
+ }
+ else
+ {
+ $(oElement).data('tooltip3-data', sValue).tooltip('show');
+ }
+ }
+};
+
+ko.bindingHandlers.registrateBootstrapDropdown = {
+ 'init': function (oElement) {
+ BootstrapDropdowns.push($(oElement));
+ }
+};
+
+ko.bindingHandlers.openDropdownTrigger = {
+ 'update': function (oElement, fValueAccessor) {
+ if (ko.utils.unwrapObservable(fValueAccessor()))
+ {
+ var $el = $(oElement);
+ if (!$el.hasClass('open'))
+ {
+ $el.find('.dropdown-toggle').dropdown('toggle');
+ Utils.detectDropdownVisibility();
+ }
+
+ fValueAccessor()(false);
+ }
+ }
+};
+
+ko.bindingHandlers.dropdownCloser = {
+ 'init': function (oElement) {
+ $(oElement).closest('.dropdown').on('click', '.e-item', function () {
+ $(oElement).dropdown('toggle');
+ });
+ }
+};
+
+ko.bindingHandlers.popover = {
+ 'init': function (oElement, fValueAccessor) {
+ $(oElement).popover(ko.utils.unwrapObservable(fValueAccessor()));
+ }
+};
+
+ko.bindingHandlers.csstext = {
+ 'init': function (oElement, fValueAccessor) {
+ if (oElement && oElement.styleSheet && !Utils.isUnd(oElement.styleSheet.cssText))
+ {
+ oElement.styleSheet.cssText = ko.utils.unwrapObservable(fValueAccessor());
+ }
+ else
+ {
+ $(oElement).text(ko.utils.unwrapObservable(fValueAccessor()));
+ }
+ },
+ 'update': function (oElement, fValueAccessor) {
+ if (oElement && oElement.styleSheet && !Utils.isUnd(oElement.styleSheet.cssText))
+ {
+ oElement.styleSheet.cssText = ko.utils.unwrapObservable(fValueAccessor());
+ }
+ else
+ {
+ $(oElement).text(ko.utils.unwrapObservable(fValueAccessor()));
+ }
+ }
+};
+
+ko.bindingHandlers.resizecrop = {
+ 'init': function (oElement) {
+ $(oElement).addClass('resizecrop').resizecrop({
+ 'width': '100',
+ 'height': '100',
+ 'wrapperCSS': {
+ 'border-radius': '10px'
+ }
+ });
+ },
+ 'update': function (oElement, fValueAccessor) {
+ fValueAccessor()();
+ $(oElement).resizecrop({
+ 'width': '100',
+ 'height': '100'
+ });
+ }
+};
+
+ko.bindingHandlers.onEnter = {
+ 'init': function (oElement, fValueAccessor, fAllBindingsAccessor, oViewModel) {
+ $(oElement).on('keypress', function (oEvent) {
+ if (oEvent && 13 === window.parseInt(oEvent.keyCode, 10))
+ {
+ $(oElement).trigger('change');
+ fValueAccessor().call(oViewModel);
+ }
+ });
+ }
+};
+
+ko.bindingHandlers.onEsc = {
+ 'init': function (oElement, fValueAccessor, fAllBindingsAccessor, oViewModel) {
+ $(oElement).on('keypress', function (oEvent) {
+ if (oEvent && 27 === window.parseInt(oEvent.keyCode, 10))
+ {
+ $(oElement).trigger('change');
+ fValueAccessor().call(oViewModel);
+ }
+ });
+ }
+};
+
+ko.bindingHandlers.clickOnTrue = {
+ 'update': function (oElement, fValueAccessor) {
+ if (ko.utils.unwrapObservable(fValueAccessor()))
+ {
+ $(oElement).click();
+ }
+ }
+};
+
+ko.bindingHandlers.modal = {
+ 'init': function (oElement, fValueAccessor) {
+
+ $(oElement).toggleClass('fade', !Globals.bMobileDevice).modal({
+ 'keyboard': false,
+ 'show': ko.utils.unwrapObservable(fValueAccessor())
+ })
+ .on('shown', function () {
+ Utils.windowResize();
+ })
+ .find('.close').click(function () {
+ fValueAccessor()(false);
+ });
+ },
+ 'update': function (oElement, fValueAccessor) {
+ $(oElement).modal(ko.utils.unwrapObservable(fValueAccessor()) ? 'show' : 'hide');
+ }
+};
+
+ko.bindingHandlers.i18nInit = {
+ 'init': function (oElement) {
+ Utils.i18nToNode(oElement);
+ }
+};
+
+ko.bindingHandlers.i18nUpdate = {
+ 'update': function (oElement, fValueAccessor) {
+ ko.utils.unwrapObservable(fValueAccessor());
+ Utils.i18nToNode(oElement);
+ }
+};
+
+ko.bindingHandlers.link = {
+ 'update': function (oElement, fValueAccessor) {
+ $(oElement).attr('href', ko.utils.unwrapObservable(fValueAccessor()));
+ }
+};
+
+ko.bindingHandlers.title = {
+ 'update': function (oElement, fValueAccessor) {
+ $(oElement).attr('title', ko.utils.unwrapObservable(fValueAccessor()));
+ }
+};
+
+ko.bindingHandlers.textF = {
+ 'init': function (oElement, fValueAccessor) {
+ $(oElement).text(ko.utils.unwrapObservable(fValueAccessor()));
+ }
+};
+
+ko.bindingHandlers.initDom = {
+ 'init': function (oElement, fValueAccessor) {
+ fValueAccessor()(oElement);
+ }
+};
+
+ko.bindingHandlers.initResizeTrigger = {
+ 'init': function (oElement, fValueAccessor) {
+ var aValues = ko.utils.unwrapObservable(fValueAccessor());
+ $(oElement).css({
+ 'height': aValues[1],
+ 'min-height': aValues[1]
+ });
+ },
+ 'update': function (oElement, fValueAccessor) {
+ var
+ aValues = ko.utils.unwrapObservable(fValueAccessor()),
+ iValue = Utils.pInt(aValues[1]),
+ iSize = 0,
+ iOffset = $(oElement).offset().top
+ ;
+
+ if (0 < iOffset)
+ {
+ iOffset += Utils.pInt(aValues[2]);
+ iSize = $window.height() - iOffset;
+
+ if (iValue < iSize)
+ {
+ iValue = iSize;
+ }
+
+ $(oElement).css({
+ 'height': iValue,
+ 'min-height': iValue
+ });
+ }
+ }
+};
+
+ko.bindingHandlers.appendDom = {
+ 'update': function (oElement, fValueAccessor) {
+ $(oElement).hide().empty().append(ko.utils.unwrapObservable(fValueAccessor())).show();
+ }
+};
+
+ko.bindingHandlers.draggable = {
+ 'init': function (oElement, fValueAccessor, fAllBindingsAccessor) {
+
+ if (!Globals.bMobileDevice)
+ {
+ var
+ iTriggerZone = 100,
+ iScrollSpeed = 3,
+ fAllValueFunc = fAllBindingsAccessor(),
+ sDroppableSelector = fAllValueFunc && fAllValueFunc['droppableSelector'] ? fAllValueFunc['droppableSelector'] : '',
+ oConf = {
+ 'distance': 20,
+ 'handle': '.dragHandle',
+ 'cursorAt': {'top': 22, 'left': 3},
+ 'refreshPositions': true,
+ 'scroll': true
+ }
+ ;
+
+ if (sDroppableSelector)
+ {
+ oConf['drag'] = function (oEvent) {
+
+ $(sDroppableSelector).each(function () {
+ var
+ moveUp = null,
+ moveDown = null,
+ $this = $(this),
+ oOffset = $this.offset(),
+ bottomPos = oOffset.top + $this.height()
+ ;
+
+ window.clearInterval($this.data('timerScroll'));
+ $this.data('timerScroll', false);
+
+ if (oEvent.pageX >= oOffset.left && oEvent.pageX <= oOffset.left + $this.width())
+ {
+ if (oEvent.pageY >= bottomPos - iTriggerZone && oEvent.pageY <= bottomPos)
+ {
+ moveUp = function() {
+ $this.scrollTop($this.scrollTop() + iScrollSpeed);
+ Utils.windowResize();
+ };
+
+ $this.data('timerScroll', window.setInterval(moveUp, 10));
+ moveUp();
+ }
+
+ if (oEvent.pageY >= oOffset.top && oEvent.pageY <= oOffset.top + iTriggerZone)
+ {
+ moveDown = function() {
+ $this.scrollTop($this.scrollTop() - iScrollSpeed);
+ Utils.windowResize();
+ };
+
+ $this.data('timerScroll', window.setInterval(moveDown, 10));
+ moveDown();
+ }
+ }
+ });
+ };
+
+ oConf['stop'] = function() {
+ $(sDroppableSelector).each(function () {
+ window.clearInterval($(this).data('timerScroll'));
+ $(this).data('timerScroll', false);
+ });
+ };
+ }
+
+ oConf['helper'] = function (oEvent) {
+ return fValueAccessor()(oEvent && oEvent.target ? ko.dataFor(oEvent.target) : null);
+ };
+
+ $(oElement).draggable(oConf).on('mousedown', function () {
+ Utils.removeInFocus();
+ });
+ }
+ }
+};
+
+ko.bindingHandlers.droppable = {
+ 'init': function (oElement, fValueAccessor, fAllBindingsAccessor) {
+
+ if (!Globals.bMobileDevice)
+ {
+ var
+ fValueFunc = fValueAccessor(),
+ fAllValueFunc = fAllBindingsAccessor(),
+ fOverCallback = fAllValueFunc && fAllValueFunc['droppableOver'] ? fAllValueFunc['droppableOver'] : null,
+ fOutCallback = fAllValueFunc && fAllValueFunc['droppableOut'] ? fAllValueFunc['droppableOut'] : null,
+ oConf = {
+ 'tolerance': 'pointer',
+ 'hoverClass': 'droppableHover'
+ }
+ ;
+
+ if (fValueFunc)
+ {
+ oConf['drop'] = function (oEvent, oUi) {
+ fValueFunc(oEvent, oUi);
+ };
+
+ if (fOverCallback)
+ {
+ oConf['over'] = function (oEvent, oUi) {
+ fOverCallback(oEvent, oUi);
+ };
+ }
+
+ if (fOutCallback)
+ {
+ oConf['out'] = function (oEvent, oUi) {
+ fOutCallback(oEvent, oUi);
+ };
+ }
+
+ $(oElement).droppable(oConf);
+ }
+ }
+ }
+};
+
+ko.bindingHandlers.nano = {
+ 'init': function (oElement) {
+ if (!Globals.bDisableNanoScroll)
+ {
+ $(oElement)
+ .addClass('nano')
+ .nanoScroller({
+ 'iOSNativeScrolling': false,
+ 'preventPageScrolling': true
+ })
+ ;
+ }
+ }
+};
+
+ko.bindingHandlers.saveTrigger = {
+ 'init': function (oElement) {
+
+ var $oEl = $(oElement);
+
+ $oEl.data('save-trigger-type', $oEl.is('input[type=text],input[type=email],input[type=password],select,textarea') ? 'input' : 'custom');
+
+ if ('custom' === $oEl.data('save-trigger-type'))
+ {
+ $oEl.append(
+ ' '
+ ).addClass('settings-saved-trigger');
+ }
+ else
+ {
+ $oEl.addClass('settings-saved-trigger-input');
+ }
+ },
+ 'update': function (oElement, fValueAccessor) {
+ var
+ mValue = ko.utils.unwrapObservable(fValueAccessor()),
+ $oEl = $(oElement)
+ ;
+
+ if ('custom' === $oEl.data('save-trigger-type'))
+ {
+ switch (mValue.toString())
+ {
+ case '1':
+ $oEl
+ .find('.animated,.error').hide().removeClass('visible')
+ .end()
+ .find('.success').show().addClass('visible')
+ ;
+ break;
+ case '0':
+ $oEl
+ .find('.animated,.success').hide().removeClass('visible')
+ .end()
+ .find('.error').show().addClass('visible')
+ ;
+ break;
+ case '-2':
+ $oEl
+ .find('.error,.success').hide().removeClass('visible')
+ .end()
+ .find('.animated').show().addClass('visible')
+ ;
+ break;
+ default:
+ $oEl
+ .find('.animated').hide()
+ .end()
+ .find('.error,.success').removeClass('visible')
+ ;
+ break;
+ }
+ }
+ else
+ {
+ switch (mValue.toString())
+ {
+ case '1':
+ $oEl.addClass('success').removeClass('error');
+ break;
+ case '0':
+ $oEl.addClass('error').removeClass('success');
+ break;
+ case '-2':
+// $oEl;
+ break;
+ default:
+ $oEl.removeClass('error success');
+ break;
+ }
+ }
+ }
+};
+
+ko.bindingHandlers.emailsTags = {
+ 'init': function(oElement, fValueAccessor) {
+ var
+ $oEl = $(oElement),
+ fValue = fValueAccessor(),
+ fFocusCallback = function (bValue) {
+ if (fValue && fValue.focusTrigger)
+ {
+ fValue.focusTrigger(bValue);
+ }
+ }
+ ;
+
+ $oEl.inputosaurus({
+ 'parseOnBlur': true,
+ 'allowDragAndDrop': true,
+ 'focusCallback': fFocusCallback,
+ 'inputDelimiters': [',', ';'],
+ 'autoCompleteSource': function (oData, fResponse) {
+ RL.getAutocomplete(oData.term, function (aData) {
+ fResponse(_.map(aData, function (oEmailItem) {
+ return oEmailItem.toLine(false);
+ }));
+ });
+ },
+ 'parseHook': function (aInput) {
+ return _.map(aInput, function (sInputValue) {
+
+ var
+ sValue = Utils.trim(sInputValue),
+ oEmail = null
+ ;
+
+ if ('' !== sValue)
+ {
+ oEmail = new EmailModel();
+ oEmail.mailsoParse(sValue);
+ oEmail.clearDuplicateName();
+ return [oEmail.toLine(false), oEmail];
+ }
+
+ return [sValue, null];
+
+ });
+ },
+ 'change': _.bind(function (oEvent) {
+ $oEl.data('EmailsTagsValue', oEvent.target.value);
+ fValue(oEvent.target.value);
+ }, this)
+ });
+ },
+ 'update': function (oElement, fValueAccessor, fAllBindingsAccessor) {
+
+ var
+ $oEl = $(oElement),
+ fAllValueFunc = fAllBindingsAccessor(),
+ fEmailsTagsFilter = fAllValueFunc['emailsTagsFilter'] || null,
+ sValue = ko.utils.unwrapObservable(fValueAccessor())
+ ;
+
+ if ($oEl.data('EmailsTagsValue') !== sValue)
+ {
+ $oEl.val(sValue);
+ $oEl.data('EmailsTagsValue', sValue);
+ $oEl.inputosaurus('refresh');
+ }
+
+ if (fEmailsTagsFilter && ko.utils.unwrapObservable(fEmailsTagsFilter))
+ {
+ $oEl.inputosaurus('focus');
+ }
+ }
+};
+
+ko.bindingHandlers.contactTags = {
+ 'init': function(oElement, fValueAccessor) {
+ var
+ $oEl = $(oElement),
+ fValue = fValueAccessor(),
+ fFocusCallback = function (bValue) {
+ if (fValue && fValue.focusTrigger)
+ {
+ fValue.focusTrigger(bValue);
+ }
+ }
+ ;
+
+ $oEl.inputosaurus({
+ 'parseOnBlur': true,
+ 'allowDragAndDrop': false,
+ 'focusCallback': fFocusCallback,
+ 'inputDelimiters': [',', ';'],
+ 'outputDelimiter': ',',
+ 'autoCompleteSource': function (oData, fResponse) {
+ RL.getContactTagsAutocomplete(oData.term, function (aData) {
+ fResponse(_.map(aData, function (oTagItem) {
+ return oTagItem.toLine(false);
+ }));
+ });
+ },
+ 'parseHook': function (aInput) {
+ return _.map(aInput, function (sInputValue) {
+
+ var
+ sValue = Utils.trim(sInputValue),
+ oTag = null
+ ;
+
+ if ('' !== sValue)
+ {
+ oTag = new ContactTagModel();
+ oTag.name(sValue);
+ return [oTag.toLine(false), oTag];
+ }
+
+ return [sValue, null];
+
+ });
+ },
+ 'change': _.bind(function (oEvent) {
+ $oEl.data('ContactTagsValue', oEvent.target.value);
+ fValue(oEvent.target.value);
+ }, this)
+ });
+ },
+ 'update': function (oElement, fValueAccessor, fAllBindingsAccessor) {
+
+ var
+ $oEl = $(oElement),
+ fAllValueFunc = fAllBindingsAccessor(),
+ fContactTagsFilter = fAllValueFunc['contactTagsFilter'] || null,
+ sValue = ko.utils.unwrapObservable(fValueAccessor())
+ ;
+
+ if ($oEl.data('ContactTagsValue') !== sValue)
+ {
+ $oEl.val(sValue);
+ $oEl.data('ContactTagsValue', sValue);
+ $oEl.inputosaurus('refresh');
+ }
+
+ if (fContactTagsFilter && ko.utils.unwrapObservable(fContactTagsFilter))
+ {
+ $oEl.inputosaurus('focus');
+ }
+ }
+};
+
+ko.bindingHandlers.command = {
+ 'init': function (oElement, fValueAccessor, fAllBindingsAccessor, oViewModel) {
+ var
+ jqElement = $(oElement),
+ oCommand = fValueAccessor()
+ ;
+
+ if (!oCommand || !oCommand.enabled || !oCommand.canExecute)
+ {
+ throw new Error('You are not using command function');
+ }
+
+ jqElement.addClass('command');
+ ko.bindingHandlers[jqElement.is('form') ? 'submit' : 'click'].init.apply(oViewModel, arguments);
+ },
+
+ 'update': function (oElement, fValueAccessor) {
+
+ var
+ bResult = true,
+ jqElement = $(oElement),
+ oCommand = fValueAccessor()
+ ;
+
+ bResult = oCommand.enabled();
+ jqElement.toggleClass('command-not-enabled', !bResult);
+
+ if (bResult)
+ {
+ bResult = oCommand.canExecute();
+ jqElement.toggleClass('command-can-not-be-execute', !bResult);
+ }
+
+ jqElement.toggleClass('command-disabled disable disabled', !bResult).toggleClass('no-disabled', !!bResult);
+
+ if (jqElement.is('input') || jqElement.is('button'))
+ {
+ jqElement.prop('disabled', !bResult);
+ }
+ }
+};
+
+ko.extenders.trimmer = function (oTarget)
+{
+ var oResult = ko.computed({
+ 'read': oTarget,
+ 'write': function (sNewValue) {
+ oTarget(Utils.trim(sNewValue.toString()));
+ },
+ 'owner': this
+ });
+
+ oResult(oTarget());
+ return oResult;
+};
+
+ko.extenders.posInterer = function (oTarget, iDefault)
+{
+ var oResult = ko.computed({
+ 'read': oTarget,
+ 'write': function (sNewValue) {
+ var iNew = Utils.pInt(sNewValue.toString(), iDefault);
+ if (0 >= iNew)
+ {
+ iNew = iDefault;
+ }
+
+ if (iNew === oTarget() && '' + iNew !== '' + sNewValue)
+ {
+ oTarget(iNew + 1);
+ }
+
+ oTarget(iNew);
+ }
+ });
+
+ oResult(oTarget());
+ return oResult;
+};
+
+ko.extenders.reversible = function (oTarget)
+{
+ var mValue = oTarget();
+
+ oTarget.commit = function ()
+ {
+ mValue = oTarget();
+ };
+
+ oTarget.reverse = function ()
+ {
+ oTarget(mValue);
+ };
+
+ oTarget.commitedValue = function ()
+ {
+ return mValue;
+ };
+
+ return oTarget;
+};
+
+ko.extenders.toggleSubscribe = function (oTarget, oOptions)
+{
+ oTarget.subscribe(oOptions[1], oOptions[0], 'beforeChange');
+ oTarget.subscribe(oOptions[2], oOptions[0]);
+
+ return oTarget;
+};
+
+ko.extenders.falseTimeout = function (oTarget, iOption)
+{
+ oTarget.iTimeout = 0;
+ oTarget.subscribe(function (bValue) {
+ if (bValue)
+ {
+ window.clearTimeout(oTarget.iTimeout);
+ oTarget.iTimeout = window.setTimeout(function () {
+ oTarget(false);
+ oTarget.iTimeout = 0;
+ }, Utils.pInt(iOption));
+ }
+ });
+
+ return oTarget;
+};
+
+ko.observable.fn.validateNone = function ()
+{
+ this.hasError = ko.observable(false);
+ return this;
+};
+
+ko.observable.fn.validateEmail = function ()
+{
+ this.hasError = ko.observable(false);
+
+ this.subscribe(function (sValue) {
+ sValue = Utils.trim(sValue);
+ this.hasError('' !== sValue && !(/^[^@\s]+@[^@\s]+$/.test(sValue)));
+ }, this);
+
+ this.valueHasMutated();
+ return this;
+};
+
+ko.observable.fn.validateSimpleEmail = function ()
+{
+ this.hasError = ko.observable(false);
+
+ this.subscribe(function (sValue) {
+ sValue = Utils.trim(sValue);
+ this.hasError('' !== sValue && !(/^.+@.+$/.test(sValue)));
+ }, this);
+
+ this.valueHasMutated();
+ return this;
+};
+
+ko.observable.fn.validateFunc = function (fFunc)
+{
+ this.hasFuncError = ko.observable(false);
+
+ if (Utils.isFunc(fFunc))
+ {
+ this.subscribe(function (sValue) {
+ this.hasFuncError(!fFunc(sValue));
+ }, this);
+
+ this.valueHasMutated();
+ }
+
+ return this;
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ */
+function LinkBuilder()
+{
+ this.sBase = '#/';
+ this.sServer = './?';
+ this.sVersion = RL.settingsGet('Version');
+ this.sSpecSuffix = RL.settingsGet('AuthAccountHash') || '0';
+ this.sStaticPrefix = RL.settingsGet('StaticPrefix') || 'rainloop/v/' + this.sVersion + '/static/';
+}
+
+/**
+ * @return {string}
+ */
+LinkBuilder.prototype.root = function ()
+{
+ return this.sBase;
+};
+
+/**
+ * @param {string} sDownload
+ * @return {string}
+ */
+LinkBuilder.prototype.attachmentDownload = function (sDownload)
+{
+ return this.sServer + '/Raw/' + this.sSpecSuffix + '/Download/' + sDownload;
+};
+
+/**
+ * @param {string} sDownload
+ * @return {string}
+ */
+LinkBuilder.prototype.attachmentPreview = function (sDownload)
+{
+ return this.sServer + '/Raw/' + this.sSpecSuffix + '/View/' + sDownload;
+};
+
+/**
+ * @param {string} sDownload
+ * @return {string}
+ */
+LinkBuilder.prototype.attachmentPreviewAsPlain = function (sDownload)
+{
+ return this.sServer + '/Raw/' + this.sSpecSuffix + '/ViewAsPlain/' + sDownload;
+};
+
+/**
+ * @return {string}
+ */
+LinkBuilder.prototype.upload = function ()
+{
+ return this.sServer + '/Upload/' + this.sSpecSuffix + '/';
+};
+
+/**
+ * @return {string}
+ */
+LinkBuilder.prototype.uploadContacts = function ()
+{
+ return this.sServer + '/UploadContacts/' + this.sSpecSuffix + '/';
+};
+
+/**
+ * @return {string}
+ */
+LinkBuilder.prototype.uploadBackground = function ()
+{
+ return this.sServer + '/UploadBackground/' + this.sSpecSuffix + '/';
+};
+
+/**
+ * @return {string}
+ */
+LinkBuilder.prototype.append = function ()
+{
+ return this.sServer + '/Append/' + this.sSpecSuffix + '/';
+};
+
+/**
+ * @param {string} sEmail
+ * @return {string}
+ */
+LinkBuilder.prototype.change = function (sEmail)
+{
+ return this.sServer + '/Change/' + this.sSpecSuffix + '/' + window.encodeURIComponent(sEmail) + '/';
+};
+
+/**
+ * @param {string=} sAdd
+ * @return {string}
+ */
+LinkBuilder.prototype.ajax = function (sAdd)
+{
+ return this.sServer + '/Ajax/' + this.sSpecSuffix + '/' + sAdd;
+};
+
+/**
+ * @param {string} sRequestHash
+ * @return {string}
+ */
+LinkBuilder.prototype.messageViewLink = function (sRequestHash)
+{
+ return this.sServer + '/Raw/' + this.sSpecSuffix + '/ViewAsPlain/' + sRequestHash;
+};
+
+/**
+ * @param {string} sRequestHash
+ * @return {string}
+ */
+LinkBuilder.prototype.messageDownloadLink = function (sRequestHash)
+{
+ return this.sServer + '/Raw/' + this.sSpecSuffix + '/Download/' + sRequestHash;
+};
+
+/**
+ * @param {string} sEmail
+ * @return {string}
+ */
+LinkBuilder.prototype.avatarLink = function (sEmail)
+{
+ return this.sServer + '/Raw/0/Avatar/' + window.encodeURIComponent(sEmail) + '/';
+// return '//secure.gravatar.com/avatar/' + Utils.md5(sEmail.toLowerCase()) + '.jpg?s=80&d=mm';
+};
+
+/**
+ * @return {string}
+ */
+LinkBuilder.prototype.inbox = function ()
+{
+ return this.sBase + 'mailbox/Inbox';
+};
+
+/**
+ * @return {string}
+ */
+LinkBuilder.prototype.messagePreview = function ()
+{
+ return this.sBase + 'mailbox/message-preview';
+};
+
+/**
+ * @param {string=} sScreenName
+ * @return {string}
+ */
+LinkBuilder.prototype.settings = function (sScreenName)
+{
+ var sResult = this.sBase + 'settings';
+ if (!Utils.isUnd(sScreenName) && '' !== sScreenName)
+ {
+ sResult += '/' + sScreenName;
+ }
+
+ return sResult;
+};
+
+/**
+ * @param {string} sScreenName
+ * @return {string}
+ */
+LinkBuilder.prototype.admin = function (sScreenName)
+{
+ var sResult = this.sBase;
+ switch (sScreenName) {
+ case 'AdminDomains':
+ sResult += 'domains';
+ break;
+ case 'AdminSecurity':
+ sResult += 'security';
+ break;
+ case 'AdminLicensing':
+ sResult += 'licensing';
+ break;
+ }
+
+ return sResult;
+};
+
+/**
+ * @param {string} sFolder
+ * @param {number=} iPage = 1
+ * @param {string=} sSearch = ''
+ * @return {string}
+ */
+LinkBuilder.prototype.mailBox = function (sFolder, iPage, sSearch)
+{
+ iPage = Utils.isNormal(iPage) ? Utils.pInt(iPage) : 1;
+ sSearch = Utils.pString(sSearch);
+
+ var sResult = this.sBase + 'mailbox/';
+ if ('' !== sFolder)
+ {
+ sResult += encodeURI(sFolder);
+ }
+ if (1 < iPage)
+ {
+ sResult = sResult.replace(/[\/]+$/, '');
+ sResult += '/p' + iPage;
+ }
+ if ('' !== sSearch)
+ {
+ sResult = sResult.replace(/[\/]+$/, '');
+ sResult += '/' + encodeURI(sSearch);
+ }
+
+ return sResult;
+};
+
+/**
+ * @return {string}
+ */
+LinkBuilder.prototype.phpInfo = function ()
+{
+ return this.sServer + 'Info';
+};
+
+/**
+ * @param {string} sLang
+ * @return {string}
+ */
+LinkBuilder.prototype.langLink = function (sLang)
+{
+ return this.sServer + '/Lang/0/' + encodeURI(sLang) + '/' + this.sVersion + '/';
+};
+
+/**
+ * @return {string}
+ */
+LinkBuilder.prototype.exportContactsVcf = function ()
+{
+ return this.sServer + '/Raw/' + this.sSpecSuffix + '/ContactsVcf/';
+};
+
+/**
+ * @return {string}
+ */
+LinkBuilder.prototype.exportContactsCsv = function ()
+{
+ return this.sServer + '/Raw/' + this.sSpecSuffix + '/ContactsCsv/';
+};
+
+/**
+ * @return {string}
+ */
+LinkBuilder.prototype.emptyContactPic = function ()
+{
+ return this.sStaticPrefix + 'css/images/empty-contact.png';
+};
+
+/**
+ * @param {string} sFileName
+ * @return {string}
+ */
+LinkBuilder.prototype.sound = function (sFileName)
+{
+ return this.sStaticPrefix + 'sounds/' + sFileName;
+};
+
+/**
+ * @param {string} sTheme
+ * @return {string}
+ */
+LinkBuilder.prototype.themePreviewLink = function (sTheme)
+{
+ var sPrefix = 'rainloop/v/' + this.sVersion + '/';
+ if ('@custom' === sTheme.substr(-7))
+ {
+ sTheme = Utils.trim(sTheme.substring(0, sTheme.length - 7));
+ sPrefix = '';
+ }
+
+ return sPrefix + 'themes/' + encodeURI(sTheme) + '/images/preview.png';
+};
+
+/**
+ * @return {string}
+ */
+LinkBuilder.prototype.notificationMailIcon = function ()
+{
+ return this.sStaticPrefix + 'css/images/icom-message-notification.png';
+};
+
+/**
+ * @return {string}
+ */
+LinkBuilder.prototype.openPgpJs = function ()
+{
+ return this.sStaticPrefix + 'js/openpgp.min.js';
+};
+
+/**
+ * @return {string}
+ */
+LinkBuilder.prototype.socialGoogle = function ()
+{
+ return this.sServer + 'SocialGoogle' + ('' !== this.sSpecSuffix ? '/' + this.sSpecSuffix + '/' : '');
+};
+
+/**
+ * @return {string}
+ */
+LinkBuilder.prototype.socialTwitter = function ()
+{
+ return this.sServer + 'SocialTwitter' + ('' !== this.sSpecSuffix ? '/' + this.sSpecSuffix + '/' : '');
+};
+
+/**
+ * @return {string}
+ */
+LinkBuilder.prototype.socialFacebook = function ()
+{
+ return this.sServer + 'SocialFacebook' + ('' !== this.sSpecSuffix ? '/' + this.sSpecSuffix + '/' : '');
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @type {Object}
+ */
+Plugins.oViewModelsHooks = {};
+
+/**
+ * @type {Object}
+ */
+Plugins.oSimpleHooks = {};
+
+/**
+ * @param {string} sName
+ * @param {Function} ViewModel
+ */
+Plugins.regViewModelHook = function (sName, ViewModel)
+{
+ if (ViewModel)
+ {
+ ViewModel.__hookName = sName;
+ }
+};
+
+/**
+ * @param {string} sName
+ * @param {Function} fCallback
+ */
+Plugins.addHook = function (sName, fCallback)
+{
+ if (Utils.isFunc(fCallback))
+ {
+ if (!Utils.isArray(Plugins.oSimpleHooks[sName]))
+ {
+ Plugins.oSimpleHooks[sName] = [];
+ }
+
+ Plugins.oSimpleHooks[sName].push(fCallback);
+ }
+};
+
+/**
+ * @param {string} sName
+ * @param {Array=} aArguments
+ */
+Plugins.runHook = function (sName, aArguments)
+{
+ if (Utils.isArray(Plugins.oSimpleHooks[sName]))
+ {
+ aArguments = aArguments || [];
+
+ _.each(Plugins.oSimpleHooks[sName], function (fCallback) {
+ fCallback.apply(null, aArguments);
+ });
+ }
+};
+
+/**
+ * @param {string} sName
+ * @return {?}
+ */
+Plugins.mainSettingsGet = function (sName)
+{
+ return RL ? RL.settingsGet(sName) : null;
+};
+
+/**
+ * @param {Function} fCallback
+ * @param {string} sAction
+ * @param {Object=} oParameters
+ * @param {?number=} iTimeout
+ * @param {string=} sGetAdd = ''
+ * @param {Array=} aAbortActions = []
+ */
+Plugins.remoteRequest = function (fCallback, sAction, oParameters, iTimeout, sGetAdd, aAbortActions)
+{
+ if (RL)
+ {
+ RL.remote().defaultRequest(fCallback, sAction, oParameters, iTimeout, sGetAdd, aAbortActions);
+ }
+};
+
+/**
+ * @param {string} sPluginSection
+ * @param {string} sName
+ * @return {?}
+ */
+Plugins.settingsGet = function (sPluginSection, sName)
+{
+ var oPlugin = Plugins.mainSettingsGet('Plugins');
+ oPlugin = oPlugin && Utils.isUnd(oPlugin[sPluginSection]) ? null : oPlugin[sPluginSection];
+ return oPlugin ? (Utils.isUnd(oPlugin[sName]) ? null : oPlugin[sName]) : null;
+};
+
+
+
+
+/**
+ * @constructor
+ * @param {Object} oElement
+ * @param {Function=} fOnBlur
+ * @param {Function=} fOnReady
+ * @param {Function=} fOnModeChange
+ */
+function NewHtmlEditorWrapper(oElement, fOnBlur, fOnReady, fOnModeChange)
+{
+ var self = this;
+ self.editor = null;
+ self.iBlurTimer = 0;
+ self.fOnBlur = fOnBlur || null;
+ self.fOnReady = fOnReady || null;
+ self.fOnModeChange = fOnModeChange || null;
+
+ self.$element = $(oElement);
+
+ self.resize = _.throttle(_.bind(self.resize, self), 100);
+
+ self.init();
+}
+
+NewHtmlEditorWrapper.prototype.blurTrigger = function ()
+{
+ if (this.fOnBlur)
+ {
+ var self = this;
+ window.clearTimeout(self.iBlurTimer);
+ self.iBlurTimer = window.setTimeout(function () {
+ self.fOnBlur();
+ }, 200);
+ }
+};
+
+NewHtmlEditorWrapper.prototype.focusTrigger = function ()
+{
+ if (this.fOnBlur)
+ {
+ window.clearTimeout(this.iBlurTimer);
+ }
+};
+
+/**
+ * @return {boolean}
+ */
+NewHtmlEditorWrapper.prototype.isHtml = function ()
+{
+ return this.editor ? 'wysiwyg' === this.editor.mode : false;
+};
+
+/**
+ * @return {boolean}
+ */
+NewHtmlEditorWrapper.prototype.checkDirty = function ()
+{
+ return this.editor ? this.editor.checkDirty() : false;
+};
+
+NewHtmlEditorWrapper.prototype.resetDirty = function ()
+{
+ if (this.editor)
+ {
+ this.editor.resetDirty();
+ }
+};
+
+/**
+ * @return {string}
+ */
+NewHtmlEditorWrapper.prototype.getData = function (bWrapIsHtml)
+{
+ if (this.editor)
+ {
+ if ('plain' === this.editor.mode && this.editor.plugins.plain && this.editor.__plain)
+ {
+ return this.editor.__plain.getRawData();
+ }
+
+ return bWrapIsHtml ?
+ '' +
+ this.editor.getData() + '' : this.editor.getData();
+ }
+
+ return '';
+};
+
+NewHtmlEditorWrapper.prototype.modeToggle = function (bPlain)
+{
+ if (this.editor)
+ {
+ if (bPlain)
+ {
+ if ('plain' === this.editor.mode)
+ {
+ this.editor.setMode('wysiwyg');
+ }
+ }
+ else
+ {
+ if ('wysiwyg' === this.editor.mode)
+ {
+ this.editor.setMode('plain');
+ }
+ }
+
+ this.resize();
+ }
+};
+
+NewHtmlEditorWrapper.prototype.setHtml = function (sHtml, bFocus)
+{
+ if (this.editor)
+ {
+ this.modeToggle(true);
+ this.editor.setData(sHtml);
+
+ if (bFocus)
+ {
+ this.focus();
+ }
+ }
+};
+
+NewHtmlEditorWrapper.prototype.setPlain = function (sPlain, bFocus)
+{
+ if (this.editor)
+ {
+ this.modeToggle(false);
+ if ('plain' === this.editor.mode && this.editor.plugins.plain && this.editor.__plain)
+ {
+ return this.editor.__plain.setRawData(sPlain);
+ }
+ else
+ {
+ this.editor.setData(sPlain);
+ }
+
+ if (bFocus)
+ {
+ this.focus();
+ }
+ }
+};
+
+NewHtmlEditorWrapper.prototype.init = function ()
+{
+ if (this.$element && this.$element[0])
+ {
+ var
+ self = this,
+ fInit = function () {
+
+ var
+ oConfig = Globals.oHtmlEditorDefaultConfig,
+ sLanguage = RL.settingsGet('Language'),
+ bSource = !!RL.settingsGet('AllowHtmlEditorSourceButton')
+ ;
+
+ if (bSource && oConfig.toolbarGroups && !oConfig.toolbarGroups.__SourceInited)
+ {
+ oConfig.toolbarGroups.__SourceInited = true;
+ oConfig.toolbarGroups.push({name: 'document', groups: ['mode', 'document', 'doctools']});
+ }
+
+ oConfig.enterMode = window.CKEDITOR.ENTER_BR;
+ oConfig.shiftEnterMode = window.CKEDITOR.ENTER_BR;
+
+ oConfig.language = Globals.oHtmlEditorLangsMap[sLanguage] || 'en';
+ if (window.CKEDITOR.env)
+ {
+ window.CKEDITOR.env.isCompatible = true;
+ }
+
+ self.editor = window.CKEDITOR.appendTo(self.$element[0], oConfig);
+
+ self.editor.on('key', function(oEvent) {
+ if (oEvent && oEvent.data && 9 /* Tab */ === oEvent.data.keyCode)
+ {
+ return false;
+ }
+ });
+
+ self.editor.on('blur', function() {
+ self.blurTrigger();
+ });
+
+ self.editor.on('mode', function() {
+
+ self.blurTrigger();
+
+ if (self.fOnModeChange)
+ {
+ self.fOnModeChange('plain' !== self.editor.mode);
+ }
+ });
+
+ self.editor.on('focus', function() {
+ self.focusTrigger();
+ });
+
+ if (self.fOnReady)
+ {
+ self.editor.on('instanceReady', function () {
+
+ self.editor.setKeystroke(window.CKEDITOR.CTRL + 65 /* A */, 'selectAll');
+
+ self.fOnReady();
+ self.__resizable = true;
+ self.resize();
+ });
+ }
+ }
+ ;
+
+ if (window.CKEDITOR)
+ {
+ fInit();
+ }
+ else
+ {
+ window.__initEditor = fInit;
+ }
+ }
+};
+
+NewHtmlEditorWrapper.prototype.focus = function ()
+{
+ if (this.editor)
+ {
+ this.editor.focus();
+ }
+};
+
+NewHtmlEditorWrapper.prototype.blur = function ()
+{
+ if (this.editor)
+ {
+ this.editor.focusManager.blur(true);
+ }
+};
+
+NewHtmlEditorWrapper.prototype.resize = function ()
+{
+ if (this.editor && this.__resizable)
+ {
+ try
+ {
+ this.editor.resize(this.$element.width(), this.$element.innerHeight());
+ }
+ catch (e) {}
+ }
+};
+
+NewHtmlEditorWrapper.prototype.clear = function (bFocus)
+{
+ this.setHtml('', bFocus);
+};
+
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @param {koProperty} oKoList
+ * @param {koProperty} oKoSelectedItem
+ * @param {string} sItemSelector
+ * @param {string} sItemSelectedSelector
+ * @param {string} sItemCheckedSelector
+ * @param {string} sItemFocusedSelector
+ */
+function Selector(oKoList, oKoSelectedItem,
+ sItemSelector, sItemSelectedSelector, sItemCheckedSelector, sItemFocusedSelector)
+{
+ this.list = oKoList;
+
+ this.listChecked = ko.computed(function () {
+ return _.filter(this.list(), function (oItem) {
+ return oItem.checked();
+ });
+ }, this).extend({'rateLimit': 0});
+
+ this.isListChecked = ko.computed(function () {
+ return 0 < this.listChecked().length;
+ }, this);
+
+ this.focusedItem = ko.observable(null);
+ this.selectedItem = oKoSelectedItem;
+ this.selectedItemUseCallback = true;
+
+ this.itemSelectedThrottle = _.debounce(_.bind(this.itemSelected, this), 300);
+
+ this.listChecked.subscribe(function (aItems) {
+ if (0 < aItems.length)
+ {
+ if (null === this.selectedItem())
+ {
+ this.selectedItem.valueHasMutated();
+ }
+ else
+ {
+ this.selectedItem(null);
+ }
+ }
+ else if (this.bAutoSelect && this.focusedItem())
+ {
+ this.selectedItem(this.focusedItem());
+ }
+ }, this);
+
+ this.selectedItem.subscribe(function (oItem) {
+
+ if (oItem)
+ {
+ if (this.isListChecked())
+ {
+ _.each(this.listChecked(), function (oSubItem) {
+ oSubItem.checked(false);
+ });
+ }
+
+ if (this.selectedItemUseCallback)
+ {
+ this.itemSelectedThrottle(oItem);
+ }
+ }
+ else if (this.selectedItemUseCallback)
+ {
+ this.itemSelected(null);
+ }
+
+ }, this);
+
+ this.selectedItem.extend({'toggleSubscribe': [null,
+ function (oPrev) {
+ if (oPrev)
+ {
+ oPrev.selected(false);
+ }
+ }, function (oNext) {
+ if (oNext)
+ {
+ oNext.selected(true);
+ }
+ }
+ ]});
+
+ this.focusedItem.extend({'toggleSubscribe': [null,
+ function (oPrev) {
+ if (oPrev)
+ {
+ oPrev.focused(false);
+ }
+ }, function (oNext) {
+ if (oNext)
+ {
+ oNext.focused(true);
+ }
+ }
+ ]});
+
+ this.oContentVisible = null;
+ this.oContentScrollable = null;
+
+ this.sItemSelector = sItemSelector;
+ this.sItemSelectedSelector = sItemSelectedSelector;
+ this.sItemCheckedSelector = sItemCheckedSelector;
+ this.sItemFocusedSelector = sItemFocusedSelector;
+
+ this.sLastUid = '';
+ this.bAutoSelect = true;
+ this.oCallbacks = {};
+
+ this.emptyFunction = function () {};
+
+ this.focusedItem.subscribe(function (oItem) {
+ if (oItem)
+ {
+ this.sLastUid = this.getItemUid(oItem);
+ }
+ }, this);
+
+ var
+ aCache = [],
+ aCheckedCache = [],
+ mFocused = null,
+ mSelected = null
+ ;
+
+ this.list.subscribe(function (aItems) {
+
+ var self = this;
+ if (Utils.isArray(aItems))
+ {
+ _.each(aItems, function (oItem) {
+ if (oItem)
+ {
+ var sUid = self.getItemUid(oItem);
+
+ aCache.push(sUid);
+ if (oItem.checked())
+ {
+ aCheckedCache.push(sUid);
+ }
+ if (null === mFocused && oItem.focused())
+ {
+ mFocused = sUid;
+ }
+ if (null === mSelected && oItem.selected())
+ {
+ mSelected = sUid;
+ }
+ }
+ });
+ }
+ }, this, 'beforeChange');
+
+ this.list.subscribe(function (aItems) {
+
+ var
+ self = this,
+ oTemp = null,
+ bGetNext = false,
+ aUids = [],
+ mNextFocused = mFocused,
+ bChecked = false,
+ bSelected = false,
+ iLen = 0
+ ;
+
+ this.selectedItemUseCallback = false;
+
+ this.focusedItem(null);
+ this.selectedItem(null);
+
+ if (Utils.isArray(aItems))
+ {
+ iLen = aCheckedCache.length;
+
+ _.each(aItems, function (oItem) {
+
+ var sUid = self.getItemUid(oItem);
+ aUids.push(sUid);
+
+ if (null !== mFocused && mFocused === sUid)
+ {
+ self.focusedItem(oItem);
+ mFocused = null;
+ }
+
+ if (0 < iLen && -1 < Utils.inArray(sUid, aCheckedCache))
+ {
+ bChecked = true;
+ oItem.checked(true);
+ iLen--;
+ }
+
+ if (!bChecked && null !== mSelected && mSelected === sUid)
+ {
+ bSelected = true;
+ self.selectedItem(oItem);
+ mSelected = null;
+ }
+ });
+
+ this.selectedItemUseCallback = true;
+
+ if (!bChecked && !bSelected && this.bAutoSelect)
+ {
+ if (self.focusedItem())
+ {
+ self.selectedItem(self.focusedItem());
+ }
+ else if (0 < aItems.length)
+ {
+ if (null !== mNextFocused)
+ {
+ bGetNext = false;
+ mNextFocused = _.find(aCache, function (sUid) {
+ if (bGetNext && -1 < Utils.inArray(sUid, aUids))
+ {
+ return sUid;
+ }
+ else if (mNextFocused === sUid)
+ {
+ bGetNext = true;
+ }
+ return false;
+ });
+
+ if (mNextFocused)
+ {
+ oTemp = _.find(aItems, function (oItem) {
+ return mNextFocused === self.getItemUid(oItem);
+ });
+ }
+ }
+
+ self.selectedItem(oTemp || null);
+ self.focusedItem(self.selectedItem());
+ }
+ }
+ }
+
+ aCache = [];
+ aCheckedCache = [];
+ mFocused = null;
+ mSelected = null;
+
+ }, this);
+}
+
+Selector.prototype.itemSelected = function (oItem)
+{
+ if (this.isListChecked())
+ {
+ if (!oItem)
+ {
+ (this.oCallbacks['onItemSelect'] || this.emptyFunction)(oItem || null);
+ }
+ }
+ else
+ {
+ if (oItem)
+ {
+ (this.oCallbacks['onItemSelect'] || this.emptyFunction)(oItem);
+ }
+ }
+};
+
+Selector.prototype.goDown = function (bForceSelect)
+{
+ this.newSelectPosition(Enums.EventKeyCode.Down, false, bForceSelect);
+};
+
+Selector.prototype.goUp = function (bForceSelect)
+{
+ this.newSelectPosition(Enums.EventKeyCode.Up, false, bForceSelect);
+};
+
+Selector.prototype.init = function (oContentVisible, oContentScrollable, sKeyScope)
+{
+ this.oContentVisible = oContentVisible;
+ this.oContentScrollable = oContentScrollable;
+
+ sKeyScope = sKeyScope || 'all';
+
+ if (this.oContentVisible && this.oContentScrollable)
+ {
+ var
+ self = this
+ ;
+
+ $(this.oContentVisible)
+ .on('selectstart', function (oEvent) {
+ if (oEvent && oEvent.preventDefault)
+ {
+ oEvent.preventDefault();
+ }
+ })
+ .on('click', this.sItemSelector, function (oEvent) {
+ self.actionClick(ko.dataFor(this), oEvent);
+ })
+ .on('click', this.sItemCheckedSelector, function (oEvent) {
+ var oItem = ko.dataFor(this);
+ if (oItem)
+ {
+ if (oEvent && oEvent.shiftKey)
+ {
+ self.actionClick(oItem, oEvent);
+ }
+ else
+ {
+ self.focusedItem(oItem);
+ oItem.checked(!oItem.checked());
+ }
+ }
+ })
+ ;
+
+ key('enter', sKeyScope, function () {
+ if (self.focusedItem() && !self.focusedItem().selected())
+ {
+ self.actionClick(self.focusedItem());
+ return false;
+ }
+
+ return true;
+ });
+
+ key('ctrl+up, command+up, ctrl+down, command+down', sKeyScope, function () {
+ return false;
+ });
+
+ key('up, shift+up, down, shift+down, home, end, pageup, pagedown, insert, space', sKeyScope, function (event, handler) {
+ if (event && handler && handler.shortcut)
+ {
+ // TODO
+ var iKey = 0;
+ switch (handler.shortcut)
+ {
+ case 'up':
+ case 'shift+up':
+ iKey = Enums.EventKeyCode.Up;
+ break;
+ case 'down':
+ case 'shift+down':
+ iKey = Enums.EventKeyCode.Down;
+ break;
+ case 'insert':
+ iKey = Enums.EventKeyCode.Insert;
+ break;
+ case 'space':
+ iKey = Enums.EventKeyCode.Space;
+ break;
+ case 'home':
+ iKey = Enums.EventKeyCode.Home;
+ break;
+ case 'end':
+ iKey = Enums.EventKeyCode.End;
+ break;
+ case 'pageup':
+ iKey = Enums.EventKeyCode.PageUp;
+ break;
+ case 'pagedown':
+ iKey = Enums.EventKeyCode.PageDown;
+ break;
+ }
+
+ if (0 < iKey)
+ {
+ self.newSelectPosition(iKey, key.shift);
+ return false;
+ }
+ }
+ });
+ }
+};
+
+Selector.prototype.autoSelect = function (bValue)
+{
+ this.bAutoSelect = !!bValue;
+};
+
+/**
+ * @param {Object} oItem
+ * @returns {string}
+ */
+Selector.prototype.getItemUid = function (oItem)
+{
+ var
+ sUid = '',
+ fGetItemUidCallback = this.oCallbacks['onItemGetUid'] || null
+ ;
+
+ if (fGetItemUidCallback && oItem)
+ {
+ sUid = fGetItemUidCallback(oItem);
+ }
+
+ return sUid.toString();
+};
+
+/**
+ * @param {number} iEventKeyCode
+ * @param {boolean} bShiftKey
+ * @param {boolean=} bForceSelect = false
+ */
+Selector.prototype.newSelectPosition = function (iEventKeyCode, bShiftKey, bForceSelect)
+{
+ var
+ iIndex = 0,
+ iPageStep = 10,
+ bNext = false,
+ bStop = false,
+ oResult = null,
+ aList = this.list(),
+ iListLen = aList ? aList.length : 0,
+ oFocused = this.focusedItem()
+ ;
+
+ if (0 < iListLen)
+ {
+ if (!oFocused)
+ {
+ if (Enums.EventKeyCode.Down === iEventKeyCode || Enums.EventKeyCode.Insert === iEventKeyCode || Enums.EventKeyCode.Space === iEventKeyCode || Enums.EventKeyCode.Home === iEventKeyCode || Enums.EventKeyCode.PageUp === iEventKeyCode)
+ {
+ oResult = aList[0];
+ }
+ else if (Enums.EventKeyCode.Up === iEventKeyCode || Enums.EventKeyCode.End === iEventKeyCode || Enums.EventKeyCode.PageDown === iEventKeyCode)
+ {
+ oResult = aList[aList.length - 1];
+ }
+ }
+ else if (oFocused)
+ {
+ if (Enums.EventKeyCode.Down === iEventKeyCode || Enums.EventKeyCode.Up === iEventKeyCode || Enums.EventKeyCode.Insert === iEventKeyCode || Enums.EventKeyCode.Space === iEventKeyCode)
+ {
+ _.each(aList, function (oItem) {
+ if (!bStop)
+ {
+ switch (iEventKeyCode) {
+ case Enums.EventKeyCode.Up:
+ if (oFocused === oItem)
+ {
+ bStop = true;
+ }
+ else
+ {
+ oResult = oItem;
+ }
+ break;
+ case Enums.EventKeyCode.Down:
+ case Enums.EventKeyCode.Insert:
+ if (bNext)
+ {
+ oResult = oItem;
+ bStop = true;
+ }
+ else if (oFocused === oItem)
+ {
+ bNext = true;
+ }
+ break;
+ }
+ }
+ });
+ }
+ else if (Enums.EventKeyCode.Home === iEventKeyCode || Enums.EventKeyCode.End === iEventKeyCode)
+ {
+ if (Enums.EventKeyCode.Home === iEventKeyCode)
+ {
+ oResult = aList[0];
+ }
+ else if (Enums.EventKeyCode.End === iEventKeyCode)
+ {
+ oResult = aList[aList.length - 1];
+ }
+ }
+ else if (Enums.EventKeyCode.PageDown === iEventKeyCode)
+ {
+ for (; iIndex < iListLen; iIndex++)
+ {
+ if (oFocused === aList[iIndex])
+ {
+ iIndex += iPageStep;
+ iIndex = iListLen - 1 < iIndex ? iListLen - 1 : iIndex;
+ oResult = aList[iIndex];
+ break;
+ }
+ }
+ }
+ else if (Enums.EventKeyCode.PageUp === iEventKeyCode)
+ {
+ for (iIndex = iListLen; iIndex >= 0; iIndex--)
+ {
+ if (oFocused === aList[iIndex])
+ {
+ iIndex -= iPageStep;
+ iIndex = 0 > iIndex ? 0 : iIndex;
+ oResult = aList[iIndex];
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ if (oResult)
+ {
+ this.focusedItem(oResult);
+
+ if (oFocused)
+ {
+ if (bShiftKey)
+ {
+ if (Enums.EventKeyCode.Up === iEventKeyCode || Enums.EventKeyCode.Down === iEventKeyCode)
+ {
+ oFocused.checked(!oFocused.checked());
+ }
+ }
+ else if (Enums.EventKeyCode.Insert === iEventKeyCode || Enums.EventKeyCode.Space === iEventKeyCode)
+ {
+ oFocused.checked(!oFocused.checked());
+ }
+ }
+
+ if ((this.bAutoSelect || !!bForceSelect) &&
+ !this.isListChecked() && Enums.EventKeyCode.Space !== iEventKeyCode)
+ {
+ this.selectedItem(oResult);
+ }
+
+ this.scrollToFocused();
+ }
+ else if (oFocused)
+ {
+ if (bShiftKey && (Enums.EventKeyCode.Up === iEventKeyCode || Enums.EventKeyCode.Down === iEventKeyCode))
+ {
+ oFocused.checked(!oFocused.checked());
+ }
+ else if (Enums.EventKeyCode.Insert === iEventKeyCode || Enums.EventKeyCode.Space === iEventKeyCode)
+ {
+ oFocused.checked(!oFocused.checked());
+ }
+
+ this.focusedItem(oFocused);
+ }
+};
+
+/**
+ * @return {boolean}
+ */
+Selector.prototype.scrollToFocused = function ()
+{
+ if (!this.oContentVisible || !this.oContentScrollable)
+ {
+ return false;
+ }
+
+ var
+ iOffset = 20,
+ oFocused = $(this.sItemFocusedSelector, this.oContentScrollable),
+ oPos = oFocused.position(),
+ iVisibleHeight = this.oContentVisible.height(),
+ iFocusedHeight = oFocused.outerHeight()
+ ;
+
+ if (oPos && (oPos.top < 0 || oPos.top + iFocusedHeight > iVisibleHeight))
+ {
+ if (oPos.top < 0)
+ {
+ this.oContentScrollable.scrollTop(this.oContentScrollable.scrollTop() + oPos.top - iOffset);
+ }
+ else
+ {
+ this.oContentScrollable.scrollTop(this.oContentScrollable.scrollTop() + oPos.top - iVisibleHeight + iFocusedHeight + iOffset);
+ }
+
+ return true;
+ }
+
+ return false;
+};
+
+/**
+ * @param {boolean=} bFast = false
+ * @return {boolean}
+ */
+Selector.prototype.scrollToTop = function (bFast)
+{
+ if (!this.oContentVisible || !this.oContentScrollable)
+ {
+ return false;
+ }
+
+ if (bFast)
+ {
+ this.oContentScrollable.scrollTop(0);
+ }
+ else
+ {
+ this.oContentScrollable.stop().animate({'scrollTop': 0}, 200);
+ }
+
+ return true;
+};
+
+Selector.prototype.eventClickFunction = function (oItem, oEvent)
+{
+ var
+ sUid = this.getItemUid(oItem),
+ iIndex = 0,
+ iLength = 0,
+ oListItem = null,
+ sLineUid = '',
+ bChangeRange = false,
+ bIsInRange = false,
+ aList = [],
+ bChecked = false
+ ;
+
+ if (oEvent && oEvent.shiftKey)
+ {
+ if ('' !== sUid && '' !== this.sLastUid && sUid !== this.sLastUid)
+ {
+ aList = this.list();
+ bChecked = oItem.checked();
+
+ for (iIndex = 0, iLength = aList.length; iIndex < iLength; iIndex++)
+ {
+ oListItem = aList[iIndex];
+ sLineUid = this.getItemUid(oListItem);
+
+ bChangeRange = false;
+ if (sLineUid === this.sLastUid || sLineUid === sUid)
+ {
+ bChangeRange = true;
+ }
+
+ if (bChangeRange)
+ {
+ bIsInRange = !bIsInRange;
+ }
+
+ if (bIsInRange || bChangeRange)
+ {
+ oListItem.checked(bChecked);
+ }
+ }
+ }
+ }
+
+ this.sLastUid = '' === sUid ? '' : sUid;
+};
+
+/**
+ * @param {Object} oItem
+ * @param {Object=} oEvent
+ */
+Selector.prototype.actionClick = function (oItem, oEvent)
+{
+ if (oItem)
+ {
+ var
+ bClick = true,
+ sUid = this.getItemUid(oItem)
+ ;
+
+ if (oEvent)
+ {
+ if (oEvent.shiftKey && !oEvent.ctrlKey && !oEvent.altKey)
+ {
+ bClick = false;
+ if ('' === this.sLastUid)
+ {
+ this.sLastUid = sUid;
+ }
+
+ oItem.checked(!oItem.checked());
+ this.eventClickFunction(oItem, oEvent);
+
+ this.focusedItem(oItem);
+ }
+ else if (oEvent.ctrlKey && !oEvent.shiftKey && !oEvent.altKey)
+ {
+ bClick = false;
+ this.focusedItem(oItem);
+
+ if (this.selectedItem() && oItem !== this.selectedItem())
+ {
+ this.selectedItem().checked(true);
+ }
+
+ oItem.checked(!oItem.checked());
+ }
+ }
+
+ if (bClick)
+ {
+ this.focusedItem(oItem);
+ this.selectedItem(oItem);
+
+ this.scrollToFocused();
+ }
+ }
+};
+
+Selector.prototype.on = function (sEventName, fCallback)
+{
+ this.oCallbacks[sEventName] = fCallback;
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ */
+function CookieDriver()
+{
+
+}
+
+CookieDriver.supported = function ()
+{
+ return true;
+};
+
+/**
+ * @param {string} sKey
+ * @param {*} mData
+ * @returns {boolean}
+ */
+CookieDriver.prototype.set = function (sKey, mData)
+{
+ var
+ mCokieValue = $.cookie(Consts.Values.ClientSideCookieIndexName),
+ bResult = false,
+ mResult = null
+ ;
+
+ try
+ {
+ mResult = null === mCokieValue ? null : JSON.parse(mCokieValue);
+ if (!mResult)
+ {
+ mResult = {};
+ }
+
+ mResult[sKey] = mData;
+ $.cookie(Consts.Values.ClientSideCookieIndexName, JSON.stringify(mResult), {
+ 'expires': 30
+ });
+
+ bResult = true;
+ }
+ catch (oException) {}
+
+ return bResult;
+};
+
+/**
+ * @param {string} sKey
+ * @returns {*}
+ */
+CookieDriver.prototype.get = function (sKey)
+{
+ var
+ mCokieValue = $.cookie(Consts.Values.ClientSideCookieIndexName),
+ mResult = null
+ ;
+
+ try
+ {
+ mResult = null === mCokieValue ? null : JSON.parse(mCokieValue);
+ if (mResult && !Utils.isUnd(mResult[sKey]))
+ {
+ mResult = mResult[sKey];
+ }
+ else
+ {
+ mResult = null;
+ }
+ }
+ catch (oException) {}
+
+ return mResult;
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ */
+function LocalStorageDriver()
+{
+}
+
+LocalStorageDriver.supported = function ()
+{
+ return !!window.localStorage;
+};
+
+/**
+ * @param {string} sKey
+ * @param {*} mData
+ * @returns {boolean}
+ */
+LocalStorageDriver.prototype.set = function (sKey, mData)
+{
+ var
+ mCookieValue = window.localStorage[Consts.Values.ClientSideCookieIndexName] || null,
+ bResult = false,
+ mResult = null
+ ;
+
+ try
+ {
+ mResult = null === mCookieValue ? null : JSON.parse(mCookieValue);
+ if (!mResult)
+ {
+ mResult = {};
+ }
+
+ mResult[sKey] = mData;
+ window.localStorage[Consts.Values.ClientSideCookieIndexName] = JSON.stringify(mResult);
+
+ bResult = true;
+ }
+ catch (oException) {}
+
+ return bResult;
+};
+
+/**
+ * @param {string} sKey
+ * @returns {*}
+ */
+LocalStorageDriver.prototype.get = function (sKey)
+{
+ var
+ mCokieValue = window.localStorage[Consts.Values.ClientSideCookieIndexName] || null,
+ mResult = null
+ ;
+
+ try
+ {
+ mResult = null === mCokieValue ? null : JSON.parse(mCokieValue);
+ if (mResult && !Utils.isUnd(mResult[sKey]))
+ {
+ mResult = mResult[sKey];
+ }
+ else
+ {
+ mResult = null;
+ }
+ }
+ catch (oException) {}
+
+ return mResult;
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ */
+function LocalStorage()
+{
+ var
+ sStorages = [
+ LocalStorageDriver,
+ CookieDriver
+ ],
+ NextStorageDriver = _.find(sStorages, function (NextStorageDriver) {
+ return NextStorageDriver.supported();
+ })
+ ;
+
+ if (NextStorageDriver)
+ {
+ NextStorageDriver = /** @type {?Function} */ NextStorageDriver;
+ this.oDriver = new NextStorageDriver();
+ }
+}
+
+LocalStorage.prototype.oDriver = null;
+
+/**
+ * @param {number} iKey
+ * @param {*} mData
+ * @return {boolean}
+ */
+LocalStorage.prototype.set = function (iKey, mData)
+{
+ return this.oDriver ? this.oDriver.set('p' + iKey, mData) : false;
+};
+
+/**
+ * @param {number} iKey
+ * @return {*}
+ */
+LocalStorage.prototype.get = function (iKey)
+{
+ return this.oDriver ? this.oDriver.get('p' + iKey) : null;
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ */
+function KnoinAbstractBoot()
+{
+
+}
+
+KnoinAbstractBoot.prototype.bootstart = function ()
+{
+
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @param {string=} sPosition = ''
+ * @param {string=} sTemplate = ''
+ * @constructor
+ */
+function KnoinAbstractViewModel(sPosition, sTemplate)
+{
+ this.bDisabeCloseOnEsc = false;
+ this.sPosition = Utils.pString(sPosition);
+ this.sTemplate = Utils.pString(sTemplate);
+
+ this.sDefaultKeyScope = Enums.KeyState.None;
+ this.sCurrentKeyScope = this.sDefaultKeyScope;
+
+ this.viewModelName = '';
+ this.viewModelVisibility = ko.observable(false);
+ this.modalVisibility = ko.observable(false).extend({'rateLimit': 0});
+
+ this.viewModelDom = null;
+}
+
+/**
+ * @type {string}
+ */
+KnoinAbstractViewModel.prototype.sPosition = '';
+
+/**
+ * @type {string}
+ */
+KnoinAbstractViewModel.prototype.sTemplate = '';
+
+/**
+ * @type {string}
+ */
+KnoinAbstractViewModel.prototype.viewModelName = '';
+
+/**
+ * @type {?}
+ */
+KnoinAbstractViewModel.prototype.viewModelDom = null;
+
+/**
+ * @return {string}
+ */
+KnoinAbstractViewModel.prototype.viewModelTemplate = function ()
+{
+ return this.sTemplate;
+};
+
+/**
+ * @return {string}
+ */
+KnoinAbstractViewModel.prototype.viewModelPosition = function ()
+{
+ return this.sPosition;
+};
+
+KnoinAbstractViewModel.prototype.cancelCommand = KnoinAbstractViewModel.prototype.closeCommand = function ()
+{
+};
+
+KnoinAbstractViewModel.prototype.storeAndSetKeyScope = function ()
+{
+ this.sCurrentKeyScope = RL.data().keyScope();
+ RL.data().keyScope(this.sDefaultKeyScope);
+};
+
+KnoinAbstractViewModel.prototype.restoreKeyScope = function ()
+{
+ RL.data().keyScope(this.sCurrentKeyScope);
+};
+
+KnoinAbstractViewModel.prototype.registerPopupKeyDown = function ()
+{
+ var self = this;
+ $window.on('keydown', function (oEvent) {
+ if (oEvent && self.modalVisibility && self.modalVisibility())
+ {
+ if (!this.bDisabeCloseOnEsc && Enums.EventKeyCode.Esc === oEvent.keyCode)
+ {
+ Utils.delegateRun(self, 'cancelCommand');
+ return false;
+ }
+ else if (Enums.EventKeyCode.Backspace === oEvent.keyCode && !Utils.inFocus())
+ {
+ return false;
+ }
+ }
+
+ return true;
+ });
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @param {string} sScreenName
+ * @param {?=} aViewModels = []
+ * @constructor
+ */
+function KnoinAbstractScreen(sScreenName, aViewModels)
+{
+ this.sScreenName = sScreenName;
+ this.aViewModels = Utils.isArray(aViewModels) ? aViewModels : [];
+}
+
+/**
+ * @type {Array}
+ */
+KnoinAbstractScreen.prototype.oCross = null;
+
+/**
+ * @type {string}
+ */
+KnoinAbstractScreen.prototype.sScreenName = '';
+
+/**
+ * @type {Array}
+ */
+KnoinAbstractScreen.prototype.aViewModels = [];
+
+/**
+ * @return {Array}
+ */
+KnoinAbstractScreen.prototype.viewModels = function ()
+{
+ return this.aViewModels;
+};
+
+/**
+ * @return {string}
+ */
+KnoinAbstractScreen.prototype.screenName = function ()
+{
+ return this.sScreenName;
+};
+
+KnoinAbstractScreen.prototype.routes = function ()
+{
+ return null;
+};
+
+/**
+ * @return {?Object}
+ */
+KnoinAbstractScreen.prototype.__cross = function ()
+{
+ return this.oCross;
+};
+
+KnoinAbstractScreen.prototype.__start = function ()
+{
+ var
+ aRoutes = this.routes(),
+ oRoute = null,
+ fMatcher = null
+ ;
+
+ if (Utils.isNonEmptyArray(aRoutes))
+ {
+ fMatcher = _.bind(this.onRoute || Utils.emptyFunction, this);
+ oRoute = crossroads.create();
+
+ _.each(aRoutes, function (aItem) {
+ oRoute.addRoute(aItem[0], fMatcher).rules = aItem[1];
+ });
+
+ this.oCross = oRoute;
+ }
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ */
+function Knoin()
+{
+ this.sDefaultScreenName = '';
+ this.oScreens = {};
+ this.oBoot = null;
+ this.oCurrentScreen = null;
+}
+
+/**
+ * @param {Object} thisObject
+ */
+Knoin.constructorEnd = function (thisObject)
+{
+ if (Utils.isFunc(thisObject['__constructor_end']))
+ {
+ thisObject['__constructor_end'].call(thisObject);
+ }
+};
+
+Knoin.prototype.sDefaultScreenName = '';
+Knoin.prototype.oScreens = {};
+Knoin.prototype.oBoot = null;
+Knoin.prototype.oCurrentScreen = null;
+
+Knoin.prototype.hideLoading = function ()
+{
+ $('#rl-loading').hide();
+};
+
+Knoin.prototype.routeOff = function ()
+{
+ hasher.changed.active = false;
+};
+
+Knoin.prototype.routeOn = function ()
+{
+ hasher.changed.active = true;
+};
+
+/**
+ * @param {Object} oBoot
+ * @return {Knoin}
+ */
+Knoin.prototype.setBoot = function (oBoot)
+{
+ if (Utils.isNormal(oBoot))
+ {
+ this.oBoot = oBoot;
+ }
+
+ return this;
+};
+
+/**
+ * @param {string} sScreenName
+ * @return {?Object}
+ */
+Knoin.prototype.screen = function (sScreenName)
+{
+ return ('' !== sScreenName && !Utils.isUnd(this.oScreens[sScreenName])) ? this.oScreens[sScreenName] : null;
+};
+
+/**
+ * @param {Function} ViewModelClass
+ * @param {Object=} oScreen
+ */
+Knoin.prototype.buildViewModel = function (ViewModelClass, oScreen)
+{
+ if (ViewModelClass && !ViewModelClass.__builded)
+ {
+ var
+ oViewModel = new ViewModelClass(oScreen),
+ sPosition = oViewModel.viewModelPosition(),
+ oViewModelPlace = $('#rl-content #rl-' + sPosition.toLowerCase()),
+ oViewModelDom = null
+ ;
+
+ ViewModelClass.__builded = true;
+ ViewModelClass.__vm = oViewModel;
+ oViewModel.data = RL.data();
+
+ oViewModel.viewModelName = ViewModelClass.__name;
+
+ if (oViewModelPlace && 1 === oViewModelPlace.length)
+ {
+ oViewModelDom = $('').addClass('rl-view-model').addClass('RL-' + oViewModel.viewModelTemplate()).hide();
+ oViewModelDom.appendTo(oViewModelPlace);
+
+ oViewModel.viewModelDom = oViewModelDom;
+ ViewModelClass.__dom = oViewModelDom;
+
+ if ('Popups' === sPosition)
+ {
+ oViewModel.cancelCommand = oViewModel.closeCommand = Utils.createCommand(oViewModel, function () {
+ kn.hideScreenPopup(ViewModelClass);
+ });
+
+ oViewModel.modalVisibility.subscribe(function (bValue) {
+
+ var self = this;
+ if (bValue)
+ {
+ this.viewModelDom.show();
+ this.storeAndSetKeyScope();
+
+ RL.popupVisibilityNames.push(this.viewModelName);
+ oViewModel.viewModelDom.css('z-index', 3000 + RL.popupVisibilityNames().length + 10);
+
+ Utils.delegateRun(this, 'onFocus', [], 500);
+ }
+ else
+ {
+ Utils.delegateRun(this, 'onHide');
+ this.restoreKeyScope();
+
+ RL.popupVisibilityNames.remove(this.viewModelName);
+ oViewModel.viewModelDom.css('z-index', 2000);
+
+ Globals.tooltipTrigger(!Globals.tooltipTrigger());
+
+ _.delay(function () {
+ self.viewModelDom.hide();
+ }, 300);
+ }
+
+ }, oViewModel);
+ }
+
+ Plugins.runHook('view-model-pre-build', [ViewModelClass.__name, oViewModel, oViewModelDom]);
+
+ ko.applyBindingAccessorsToNode(oViewModelDom[0], {
+ 'i18nInit': true,
+ 'template': function () { return {'name': oViewModel.viewModelTemplate()};}
+ }, oViewModel);
+
+ Utils.delegateRun(oViewModel, 'onBuild', [oViewModelDom]);
+ if (oViewModel && 'Popups' === sPosition)
+ {
+ oViewModel.registerPopupKeyDown();
+ }
+
+ Plugins.runHook('view-model-post-build', [ViewModelClass.__name, oViewModel, oViewModelDom]);
+ }
+ else
+ {
+ Utils.log('Cannot find view model position: ' + sPosition);
+ }
+ }
+
+ return ViewModelClass ? ViewModelClass.__vm : null;
+};
+
+/**
+ * @param {Object} oViewModel
+ * @param {Object} oViewModelDom
+ */
+Knoin.prototype.applyExternal = function (oViewModel, oViewModelDom)
+{
+ if (oViewModel && oViewModelDom)
+ {
+ ko.applyBindings(oViewModel, oViewModelDom);
+ }
+};
+
+/**
+ * @param {Function} ViewModelClassToHide
+ */
+Knoin.prototype.hideScreenPopup = function (ViewModelClassToHide)
+{
+ if (ViewModelClassToHide && ViewModelClassToHide.__vm && ViewModelClassToHide.__dom)
+ {
+ ViewModelClassToHide.__vm.modalVisibility(false);
+ Plugins.runHook('view-model-on-hide', [ViewModelClassToHide.__name, ViewModelClassToHide.__vm]);
+ }
+};
+
+/**
+ * @param {Function} ViewModelClassToShow
+ * @param {Array=} aParameters
+ */
+Knoin.prototype.showScreenPopup = function (ViewModelClassToShow, aParameters)
+{
+ if (ViewModelClassToShow)
+ {
+ this.buildViewModel(ViewModelClassToShow);
+
+ if (ViewModelClassToShow.__vm && ViewModelClassToShow.__dom)
+ {
+ ViewModelClassToShow.__vm.modalVisibility(true);
+ Utils.delegateRun(ViewModelClassToShow.__vm, 'onShow', aParameters || []);
+ Plugins.runHook('view-model-on-show', [ViewModelClassToShow.__name, ViewModelClassToShow.__vm, aParameters || []]);
+ }
+ }
+};
+
+/**
+ * @param {Function} ViewModelClassToShow
+ * @return {boolean}
+ */
+Knoin.prototype.isPopupVisible = function (ViewModelClassToShow)
+{
+ return ViewModelClassToShow && ViewModelClassToShow.__vm ? ViewModelClassToShow.__vm.modalVisibility() : false;
+};
+
+/**
+ * @param {string} sScreenName
+ * @param {string} sSubPart
+ */
+Knoin.prototype.screenOnRoute = function (sScreenName, sSubPart)
+{
+ var
+ self = this,
+ oScreen = null,
+ oCross = null
+ ;
+
+ if ('' === Utils.pString(sScreenName))
+ {
+ sScreenName = this.sDefaultScreenName;
+ }
+
+ if ('' !== sScreenName)
+ {
+ oScreen = this.screen(sScreenName);
+ if (!oScreen)
+ {
+ oScreen = this.screen(this.sDefaultScreenName);
+ if (oScreen)
+ {
+ sSubPart = sScreenName + '/' + sSubPart;
+ sScreenName = this.sDefaultScreenName;
+ }
+ }
+
+ if (oScreen && oScreen.__started)
+ {
+ if (!oScreen.__builded)
+ {
+ oScreen.__builded = true;
+
+ if (Utils.isNonEmptyArray(oScreen.viewModels()))
+ {
+ _.each(oScreen.viewModels(), function (ViewModelClass) {
+ this.buildViewModel(ViewModelClass, oScreen);
+ }, this);
+ }
+
+ Utils.delegateRun(oScreen, 'onBuild');
+ }
+
+ _.defer(function () {
+
+ // hide screen
+ if (self.oCurrentScreen)
+ {
+ Utils.delegateRun(self.oCurrentScreen, 'onHide');
+
+ if (Utils.isNonEmptyArray(self.oCurrentScreen.viewModels()))
+ {
+ _.each(self.oCurrentScreen.viewModels(), function (ViewModelClass) {
+
+ if (ViewModelClass.__vm && ViewModelClass.__dom &&
+ 'Popups' !== ViewModelClass.__vm.viewModelPosition())
+ {
+ ViewModelClass.__dom.hide();
+ ViewModelClass.__vm.viewModelVisibility(false);
+ Utils.delegateRun(ViewModelClass.__vm, 'onHide');
+ }
+
+ });
+ }
+ }
+ // --
+
+ self.oCurrentScreen = oScreen;
+
+ // show screen
+ if (self.oCurrentScreen)
+ {
+ Utils.delegateRun(self.oCurrentScreen, 'onShow');
+
+ Plugins.runHook('screen-on-show', [self.oCurrentScreen.screenName(), self.oCurrentScreen]);
+
+ if (Utils.isNonEmptyArray(self.oCurrentScreen.viewModels()))
+ {
+ _.each(self.oCurrentScreen.viewModels(), function (ViewModelClass) {
+
+ if (ViewModelClass.__vm && ViewModelClass.__dom &&
+ 'Popups' !== ViewModelClass.__vm.viewModelPosition())
+ {
+ ViewModelClass.__dom.show();
+ ViewModelClass.__vm.viewModelVisibility(true);
+ Utils.delegateRun(ViewModelClass.__vm, 'onShow');
+ Utils.delegateRun(ViewModelClass.__vm, 'onFocus', [], 200);
+
+ Plugins.runHook('view-model-on-show', [ViewModelClass.__name, ViewModelClass.__vm]);
+ }
+
+ }, self);
+ }
+ }
+ // --
+
+ oCross = oScreen.__cross();
+ if (oCross)
+ {
+ oCross.parse(sSubPart);
+ }
+ });
+ }
+ }
+};
+
+/**
+ * @param {Array} aScreensClasses
+ */
+Knoin.prototype.startScreens = function (aScreensClasses)
+{
+ $('#rl-content').css({
+ 'visibility': 'hidden'
+ });
+
+ _.each(aScreensClasses, function (CScreen) {
+
+ var
+ oScreen = new CScreen(),
+ sScreenName = oScreen ? oScreen.screenName() : ''
+ ;
+
+ if (oScreen && '' !== sScreenName)
+ {
+ if ('' === this.sDefaultScreenName)
+ {
+ this.sDefaultScreenName = sScreenName;
+ }
+
+ this.oScreens[sScreenName] = oScreen;
+ }
+
+ }, this);
+
+
+ _.each(this.oScreens, function (oScreen) {
+ if (oScreen && !oScreen.__started && oScreen.__start)
+ {
+ oScreen.__started = true;
+ oScreen.__start();
+
+ Plugins.runHook('screen-pre-start', [oScreen.screenName(), oScreen]);
+ Utils.delegateRun(oScreen, 'onStart');
+ Plugins.runHook('screen-post-start', [oScreen.screenName(), oScreen]);
+ }
+ }, this);
+
+ var oCross = crossroads.create();
+ oCross.addRoute(/^([a-zA-Z0-9\-]*)\/?(.*)$/, _.bind(this.screenOnRoute, this));
+
+ hasher.initialized.add(oCross.parse, oCross);
+ hasher.changed.add(oCross.parse, oCross);
+ hasher.init();
+
+ $('#rl-content').css({
+ 'visibility': 'visible'
+ });
+
+ _.delay(function () {
+ $html.removeClass('rl-started-trigger').addClass('rl-started');
+ }, 50);
+};
+
+/**
+ * @param {string} sHash
+ * @param {boolean=} bSilence = false
+ * @param {boolean=} bReplace = false
+ */
+Knoin.prototype.setHash = function (sHash, bSilence, bReplace)
+{
+ sHash = '#' === sHash.substr(0, 1) ? sHash.substr(1) : sHash;
+ sHash = '/' === sHash.substr(0, 1) ? sHash.substr(1) : sHash;
+
+ bReplace = Utils.isUnd(bReplace) ? false : !!bReplace;
+
+ if (Utils.isUnd(bSilence) ? false : !!bSilence)
+ {
+ hasher.changed.active = false;
+ hasher[bReplace ? 'replaceHash' : 'setHash'](sHash);
+ hasher.changed.active = true;
+ }
+ else
+ {
+ hasher.changed.active = true;
+ hasher[bReplace ? 'replaceHash' : 'setHash'](sHash);
+ hasher.setHash(sHash);
+ }
+};
+
+/**
+ * @return {Knoin}
+ */
+Knoin.prototype.bootstart = function ()
+{
+ if (this.oBoot && this.oBoot.bootstart)
+ {
+ this.oBoot.bootstart();
+ }
+
+ return this;
+};
+
+kn = new Knoin();
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @param {string=} sEmail
+ * @param {string=} sName
+ *
+ * @constructor
+ */
+function EmailModel(sEmail, sName)
+{
+ this.email = sEmail || '';
+ this.name = sName || '';
+ this.privateType = null;
+
+ this.clearDuplicateName();
+}
+
+/**
+ * @static
+ * @param {AjaxJsonEmail} oJsonEmail
+ * @return {?EmailModel}
+ */
+EmailModel.newInstanceFromJson = function (oJsonEmail)
+{
+ var oEmailModel = new EmailModel();
+ return oEmailModel.initByJson(oJsonEmail) ? oEmailModel : null;
+};
+
+/**
+ * @type {string}
+ */
+EmailModel.prototype.name = '';
+
+/**
+ * @type {string}
+ */
+EmailModel.prototype.email = '';
+
+/**
+ * @type {(number|null)}
+ */
+EmailModel.prototype.privateType = null;
+
+EmailModel.prototype.clear = function ()
+{
+ this.email = '';
+ this.name = '';
+ this.privateType = null;
+};
+
+/**
+ * @returns {boolean}
+ */
+EmailModel.prototype.validate = function ()
+{
+ return '' !== this.name || '' !== this.email;
+};
+
+/**
+ * @param {boolean} bWithoutName = false
+ * @return {string}
+ */
+EmailModel.prototype.hash = function (bWithoutName)
+{
+ return '#' + (bWithoutName ? '' : this.name) + '#' + this.email + '#';
+};
+
+EmailModel.prototype.clearDuplicateName = function ()
+{
+ if (this.name === this.email)
+ {
+ this.name = '';
+ }
+};
+
+/**
+ * @return {number}
+ */
+EmailModel.prototype.type = function ()
+{
+ if (null === this.privateType)
+ {
+ if (this.email && '@facebook.com' === this.email.substr(-13))
+ {
+ this.privateType = Enums.EmailType.Facebook;
+ }
+
+ if (null === this.privateType)
+ {
+ this.privateType = Enums.EmailType.Default;
+ }
+ }
+
+ return this.privateType;
+};
+
+/**
+ * @param {string} sQuery
+ * @return {boolean}
+ */
+EmailModel.prototype.search = function (sQuery)
+{
+ return -1 < (this.name + ' ' + this.email).toLowerCase().indexOf(sQuery.toLowerCase());
+};
+
+/**
+ * @param {string} sString
+ */
+EmailModel.prototype.parse = function (sString)
+{
+ this.clear();
+
+ sString = Utils.trim(sString);
+
+ var
+ mRegex = /(?:"([^"]+)")? ?(.*?@[^>,]+)>?,? ?/g,
+ mMatch = mRegex.exec(sString)
+ ;
+
+ if (mMatch)
+ {
+ this.name = mMatch[1] || '';
+ this.email = mMatch[2] || '';
+
+ this.clearDuplicateName();
+ }
+ else if ((/^[^@]+@[^@]+$/).test(sString))
+ {
+ this.name = '';
+ this.email = sString;
+ }
+};
+
+/**
+ * @param {AjaxJsonEmail} oJsonEmail
+ * @return {boolean}
+ */
+EmailModel.prototype.initByJson = function (oJsonEmail)
+{
+ var bResult = false;
+ if (oJsonEmail && 'Object/Email' === oJsonEmail['@Object'])
+ {
+ this.name = Utils.trim(oJsonEmail.Name);
+ this.email = Utils.trim(oJsonEmail.Email);
+
+ bResult = '' !== this.email;
+ this.clearDuplicateName();
+ }
+
+ return bResult;
+};
+
+/**
+ * @param {boolean} bFriendlyView
+ * @param {boolean=} bWrapWithLink = false
+ * @param {boolean=} bEncodeHtml = false
+ * @return {string}
+ */
+EmailModel.prototype.toLine = function (bFriendlyView, bWrapWithLink, bEncodeHtml)
+{
+ var sResult = '';
+ if ('' !== this.email)
+ {
+ bWrapWithLink = Utils.isUnd(bWrapWithLink) ? false : !!bWrapWithLink;
+ bEncodeHtml = Utils.isUnd(bEncodeHtml) ? false : !!bEncodeHtml;
+
+ if (bFriendlyView && '' !== this.name)
+ {
+ sResult = bWrapWithLink ? '') +
+ '" target="_blank" tabindex="-1">' + Utils.encodeHtml(this.name) + '' :
+ (bEncodeHtml ? Utils.encodeHtml(this.name) : this.name);
+ }
+ else
+ {
+ sResult = this.email;
+ if ('' !== this.name)
+ {
+ if (bWrapWithLink)
+ {
+ sResult = Utils.encodeHtml('"' + this.name + '" <') +
+ '') + '" target="_blank" tabindex="-1">' + Utils.encodeHtml(sResult) + '' + Utils.encodeHtml('>');
+ }
+ else
+ {
+ sResult = '"' + this.name + '" <' + sResult + '>';
+ if (bEncodeHtml)
+ {
+ sResult = Utils.encodeHtml(sResult);
+ }
+ }
+ }
+ else if (bWrapWithLink)
+ {
+ sResult = '' + Utils.encodeHtml(this.email) + '';
+ }
+ }
+ }
+
+ return sResult;
+};
+
+/**
+ * @param {string} $sEmailAddress
+ * @return {boolean}
+ */
+EmailModel.prototype.mailsoParse = function ($sEmailAddress)
+{
+ $sEmailAddress = Utils.trim($sEmailAddress);
+ if ('' === $sEmailAddress)
+ {
+ return false;
+ }
+
+ var
+ substr = function (str, start, len) {
+ str += '';
+ var end = str.length;
+
+ if (start < 0) {
+ start += end;
+ }
+
+ end = typeof len === 'undefined' ? end : (len < 0 ? len + end : len + start);
+
+ return start >= str.length || start < 0 || start > end ? false : str.slice(start, end);
+ },
+
+ substr_replace = function (str, replace, start, length) {
+ if (start < 0) {
+ start = start + str.length;
+ }
+ length = length !== undefined ? length : str.length;
+ if (length < 0) {
+ length = length + str.length - start;
+ }
+ return str.slice(0, start) + replace.substr(0, length) + replace.slice(length) + str.slice(start + length);
+ },
+
+ $sName = '',
+ $sEmail = '',
+ $sComment = '',
+
+ $bInName = false,
+ $bInAddress = false,
+ $bInComment = false,
+
+ $aRegs = null,
+
+ $iStartIndex = 0,
+ $iEndIndex = 0,
+ $iCurrentIndex = 0
+ ;
+
+ while ($iCurrentIndex < $sEmailAddress.length)
+ {
+ switch ($sEmailAddress.substr($iCurrentIndex, 1))
+ {
+ case '"':
+ if ((!$bInName) && (!$bInAddress) && (!$bInComment))
+ {
+ $bInName = true;
+ $iStartIndex = $iCurrentIndex;
+ }
+ else if ((!$bInAddress) && (!$bInComment))
+ {
+ $iEndIndex = $iCurrentIndex;
+ $sName = substr($sEmailAddress, $iStartIndex + 1, $iEndIndex - $iStartIndex - 1);
+ $sEmailAddress = substr_replace($sEmailAddress, '', $iStartIndex, $iEndIndex - $iStartIndex + 1);
+ $iEndIndex = 0;
+ $iCurrentIndex = 0;
+ $iStartIndex = 0;
+ $bInName = false;
+ }
+ break;
+ case '<':
+ if ((!$bInName) && (!$bInAddress) && (!$bInComment))
+ {
+ if ($iCurrentIndex > 0 && $sName.length === 0)
+ {
+ $sName = substr($sEmailAddress, 0, $iCurrentIndex);
+ }
+
+ $bInAddress = true;
+ $iStartIndex = $iCurrentIndex;
+ }
+ break;
+ case '>':
+ if ($bInAddress)
+ {
+ $iEndIndex = $iCurrentIndex;
+ $sEmail = substr($sEmailAddress, $iStartIndex + 1, $iEndIndex - $iStartIndex - 1);
+ $sEmailAddress = substr_replace($sEmailAddress, '', $iStartIndex, $iEndIndex - $iStartIndex + 1);
+ $iEndIndex = 0;
+ $iCurrentIndex = 0;
+ $iStartIndex = 0;
+ $bInAddress = false;
+ }
+ break;
+ case '(':
+ if ((!$bInName) && (!$bInAddress) && (!$bInComment))
+ {
+ $bInComment = true;
+ $iStartIndex = $iCurrentIndex;
+ }
+ break;
+ case ')':
+ if ($bInComment)
+ {
+ $iEndIndex = $iCurrentIndex;
+ $sComment = substr($sEmailAddress, $iStartIndex + 1, $iEndIndex - $iStartIndex - 1);
+ $sEmailAddress = substr_replace($sEmailAddress, '', $iStartIndex, $iEndIndex - $iStartIndex + 1);
+ $iEndIndex = 0;
+ $iCurrentIndex = 0;
+ $iStartIndex = 0;
+ $bInComment = false;
+ }
+ break;
+ case '\\':
+ $iCurrentIndex++;
+ break;
+ }
+
+ $iCurrentIndex++;
+ }
+
+ if ($sEmail.length === 0)
+ {
+ $aRegs = $sEmailAddress.match(/[^@\s]+@\S+/i);
+ if ($aRegs && $aRegs[0])
+ {
+ $sEmail = $aRegs[0];
+ }
+ else
+ {
+ $sName = $sEmailAddress;
+ }
+ }
+
+ if ($sEmail.length > 0 && $sName.length === 0 && $sComment.length === 0)
+ {
+ $sName = $sEmailAddress.replace($sEmail, '');
+ }
+
+ $sEmail = Utils.trim($sEmail).replace(/^[<]+/, '').replace(/[>]+$/, '');
+ $sName = Utils.trim($sName).replace(/^["']+/, '').replace(/["']+$/, '');
+ $sComment = Utils.trim($sComment).replace(/^[(]+/, '').replace(/[)]+$/, '');
+
+ // Remove backslash
+ $sName = $sName.replace(/\\\\(.)/, '$1');
+ $sComment = $sComment.replace(/\\\\(.)/, '$1');
+
+ this.name = $sName;
+ this.email = $sEmail;
+
+ this.clearDuplicateName();
+ return true;
+};
+
+/**
+ * @return {string}
+ */
+EmailModel.prototype.inputoTagLine = function ()
+{
+ return 0 < this.name.length ? this.name + ' (' + this.email + ')' : this.email;
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ */
+function ContactModel()
+{
+ this.idContact = 0;
+ this.display = '';
+ this.properties = [];
+ this.tags = '';
+ this.readOnly = false;
+
+ this.focused = ko.observable(false);
+ this.selected = ko.observable(false);
+ this.checked = ko.observable(false);
+ this.deleted = ko.observable(false);
+}
+
+/**
+ * @return {Array|null}
+ */
+ContactModel.prototype.getNameAndEmailHelper = function ()
+{
+ var
+ sName = '',
+ sEmail = ''
+ ;
+
+ if (Utils.isNonEmptyArray(this.properties))
+ {
+ _.each(this.properties, function (aProperty) {
+ if (aProperty)
+ {
+ if (Enums.ContactPropertyType.FirstName === aProperty[0])
+ {
+ sName = Utils.trim(aProperty[1] + ' ' + sName);
+ }
+ else if (Enums.ContactPropertyType.LastName === aProperty[0])
+ {
+ sName = Utils.trim(sName + ' ' + aProperty[1]);
+ }
+ else if ('' === sEmail && Enums.ContactPropertyType.Email === aProperty[0])
+ {
+ sEmail = aProperty[1];
+ }
+ }
+ }, this);
+ }
+
+ return '' === sEmail ? null : [sEmail, sName];
+};
+
+ContactModel.prototype.parse = function (oItem)
+{
+ var bResult = false;
+ if (oItem && 'Object/Contact' === oItem['@Object'])
+ {
+ this.idContact = Utils.pInt(oItem['IdContact']);
+ this.display = Utils.pString(oItem['Display']);
+ this.readOnly = !!oItem['ReadOnly'];
+ this.tags = '';
+
+ if (Utils.isNonEmptyArray(oItem['Properties']))
+ {
+ _.each(oItem['Properties'], function (oProperty) {
+ if (oProperty && oProperty['Type'] && Utils.isNormal(oProperty['Value']) && Utils.isNormal(oProperty['TypeStr']))
+ {
+ this.properties.push([Utils.pInt(oProperty['Type']), Utils.pString(oProperty['Value']), Utils.pString(oProperty['TypeStr'])]);
+ }
+ }, this);
+ }
+
+ if (Utils.isNonEmptyArray(oItem['Tags']))
+ {
+ this.tags = oItem['Tags'].join(',');
+ }
+
+ bResult = true;
+ }
+
+ return bResult;
+};
+
+/**
+ * @return {string}
+ */
+ContactModel.prototype.srcAttr = function ()
+{
+ return RL.link().emptyContactPic();
+};
+
+/**
+ * @return {string}
+ */
+ContactModel.prototype.generateUid = function ()
+{
+ return '' + this.idContact;
+};
+
+/**
+ * @return string
+ */
+ContactModel.prototype.lineAsCcc = function ()
+{
+ var aResult = [];
+ if (this.deleted())
+ {
+ aResult.push('deleted');
+ }
+ if (this.selected())
+ {
+ aResult.push('selected');
+ }
+ if (this.checked())
+ {
+ aResult.push('checked');
+ }
+ if (this.focused())
+ {
+ aResult.push('focused');
+ }
+
+ return aResult.join(' ');
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @param {number=} iType = Enums.ContactPropertyType.Unknown
+ * @param {string=} sTypeStr = ''
+ * @param {string=} sValue = ''
+ * @param {boolean=} bFocused = false
+ * @param {string=} sPlaceholder = ''
+ *
+ * @constructor
+ */
+function ContactPropertyModel(iType, sTypeStr, sValue, bFocused, sPlaceholder)
+{
+ this.type = ko.observable(Utils.isUnd(iType) ? Enums.ContactPropertyType.Unknown : iType);
+ this.typeStr = ko.observable(Utils.isUnd(sTypeStr) ? '' : sTypeStr);
+ this.focused = ko.observable(Utils.isUnd(bFocused) ? false : !!bFocused);
+ this.value = ko.observable(Utils.pString(sValue));
+
+ this.placeholder = ko.observable(sPlaceholder || '');
+
+ this.placeholderValue = ko.computed(function () {
+ var sPlaceholder = this.placeholder();
+ return sPlaceholder ? Utils.i18n(sPlaceholder) : '';
+ }, this);
+
+ this.largeValue = ko.computed(function () {
+ return Enums.ContactPropertyType.Note === this.type();
+ }, this);
+
+}
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ */
+function ContactTagModel()
+{
+ this.idContactTag = 0;
+ this.name = ko.observable('');
+ this.readOnly = false;
+}
+
+ContactTagModel.prototype.parse = function (oItem)
+{
+ var bResult = false;
+ if (oItem && 'Object/Tag' === oItem['@Object'])
+ {
+ this.idContact = Utils.pInt(oItem['IdContactTag']);
+ this.name(Utils.pString(oItem['Name']));
+ this.readOnly = !!oItem['ReadOnly'];
+
+ bResult = true;
+ }
+
+ return bResult;
+};
+
+/**
+ * @param {string} sSearch
+ * @return {boolean}
+ */
+ContactTagModel.prototype.filterHelper = function (sSearch)
+{
+ return this.name().toLowerCase().indexOf(sSearch.toLowerCase()) !== -1;
+};
+
+/**
+ * @param {boolean=} bEncodeHtml = false
+ * @return {string}
+ */
+ContactTagModel.prototype.toLine = function (bEncodeHtml)
+{
+ return (Utils.isUnd(bEncodeHtml) ? false : !!bEncodeHtml) ?
+ Utils.encodeHtml(this.name()) : this.name();
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ */
+function AttachmentModel()
+{
+ this.mimeType = '';
+ this.fileName = '';
+ this.estimatedSize = 0;
+ this.friendlySize = '';
+ this.isInline = false;
+ this.isLinked = false;
+ this.cid = '';
+ this.cidWithOutTags = '';
+ this.contentLocation = '';
+ this.download = '';
+ this.folder = '';
+ this.uid = '';
+ this.mimeIndex = '';
+}
+
+/**
+ * @static
+ * @param {AjaxJsonAttachment} oJsonAttachment
+ * @return {?AttachmentModel}
+ */
+AttachmentModel.newInstanceFromJson = function (oJsonAttachment)
+{
+ var oAttachmentModel = new AttachmentModel();
+ return oAttachmentModel.initByJson(oJsonAttachment) ? oAttachmentModel : null;
+};
+
+AttachmentModel.prototype.mimeType = '';
+AttachmentModel.prototype.fileName = '';
+AttachmentModel.prototype.estimatedSize = 0;
+AttachmentModel.prototype.friendlySize = '';
+AttachmentModel.prototype.isInline = false;
+AttachmentModel.prototype.isLinked = false;
+AttachmentModel.prototype.cid = '';
+AttachmentModel.prototype.cidWithOutTags = '';
+AttachmentModel.prototype.contentLocation = '';
+AttachmentModel.prototype.download = '';
+AttachmentModel.prototype.folder = '';
+AttachmentModel.prototype.uid = '';
+AttachmentModel.prototype.mimeIndex = '';
+
+/**
+ * @param {AjaxJsonAttachment} oJsonAttachment
+ */
+AttachmentModel.prototype.initByJson = function (oJsonAttachment)
+{
+ var bResult = false;
+ if (oJsonAttachment && 'Object/Attachment' === oJsonAttachment['@Object'])
+ {
+ this.mimeType = (oJsonAttachment.MimeType || '').toLowerCase();
+ this.fileName = oJsonAttachment.FileName;
+ this.estimatedSize = Utils.pInt(oJsonAttachment.EstimatedSize);
+ this.isInline = !!oJsonAttachment.IsInline;
+ this.isLinked = !!oJsonAttachment.IsLinked;
+ this.cid = oJsonAttachment.CID;
+ this.contentLocation = oJsonAttachment.ContentLocation;
+ this.download = oJsonAttachment.Download;
+
+ this.folder = oJsonAttachment.Folder;
+ this.uid = oJsonAttachment.Uid;
+ this.mimeIndex = oJsonAttachment.MimeIndex;
+
+ this.friendlySize = Utils.friendlySize(this.estimatedSize);
+ this.cidWithOutTags = this.cid.replace(/^<+/, '').replace(/>+$/, '');
+
+ bResult = true;
+ }
+
+ return bResult;
+};
+
+/**
+ * @return {boolean}
+ */
+AttachmentModel.prototype.isImage = function ()
+{
+ return -1 < Utils.inArray(this.mimeType.toLowerCase(),
+ ['image/png', 'image/jpg', 'image/jpeg', 'image/gif']
+ );
+};
+
+/**
+ * @return {boolean}
+ */
+AttachmentModel.prototype.isText = function ()
+{
+ return 'text/' === this.mimeType.substr(0, 5) &&
+ -1 === Utils.inArray(this.mimeType, ['text/html']);
+};
+
+/**
+ * @return {boolean}
+ */
+AttachmentModel.prototype.isPdf = function ()
+{
+ return Globals.bAllowPdfPreview && 'application/pdf' === this.mimeType;
+};
+
+/**
+ * @return {string}
+ */
+AttachmentModel.prototype.linkDownload = function ()
+{
+ return RL.link().attachmentDownload(this.download);
+};
+
+/**
+ * @return {string}
+ */
+AttachmentModel.prototype.linkPreview = function ()
+{
+ return RL.link().attachmentPreview(this.download);
+};
+
+/**
+ * @return {string}
+ */
+AttachmentModel.prototype.linkPreviewAsPlain = function ()
+{
+ return RL.link().attachmentPreviewAsPlain(this.download);
+};
+
+/**
+ * @return {string}
+ */
+AttachmentModel.prototype.generateTransferDownloadUrl = function ()
+{
+ var sLink = this.linkDownload();
+ if ('http' !== sLink.substr(0, 4))
+ {
+ sLink = window.location.protocol + '//' + window.location.host + window.location.pathname + sLink;
+ }
+
+ return this.mimeType + ':' + this.fileName + ':' + sLink;
+};
+
+/**
+ * @param {AttachmentModel} oAttachment
+ * @param {*} oEvent
+ * @return {boolean}
+ */
+AttachmentModel.prototype.eventDragStart = function (oAttachment, oEvent)
+{
+ var oLocalEvent = oEvent.originalEvent || oEvent;
+ if (oAttachment && oLocalEvent && oLocalEvent.dataTransfer && oLocalEvent.dataTransfer.setData)
+ {
+ oLocalEvent.dataTransfer.setData('DownloadURL', this.generateTransferDownloadUrl());
+ }
+
+ return true;
+};
+
+AttachmentModel.prototype.iconClass = function ()
+{
+ var
+ aParts = this.mimeType.toLocaleString().split('/'),
+ sClass = 'icon-file'
+ ;
+
+ if (aParts && aParts[1])
+ {
+ if ('image' === aParts[0])
+ {
+ sClass = 'icon-file-image';
+ }
+ else if ('text' === aParts[0])
+ {
+ sClass = 'icon-file-text';
+ }
+ else if ('audio' === aParts[0])
+ {
+ sClass = 'icon-file-music';
+ }
+ else if ('video' === aParts[0])
+ {
+ sClass = 'icon-file-movie';
+ }
+ else if (-1 < Utils.inArray(aParts[1],
+ ['zip', '7z', 'tar', 'rar', 'gzip', 'bzip', 'bzip2', 'x-zip', 'x-7z', 'x-rar', 'x-tar', 'x-gzip', 'x-bzip', 'x-bzip2', 'x-zip-compressed', 'x-7z-compressed', 'x-rar-compressed']))
+ {
+ sClass = 'icon-file-zip';
+ }
+// else if (-1 < Utils.inArray(aParts[1],
+// ['pdf', 'x-pdf']))
+// {
+// sClass = 'icon-file-pdf';
+// }
+// else if (-1 < Utils.inArray(aParts[1], [
+// 'exe', 'x-exe', 'x-winexe', 'bat'
+// ]))
+// {
+// sClass = 'icon-console';
+// }
+ else if (-1 < Utils.inArray(aParts[1], [
+ 'rtf', 'msword', 'vnd.msword', 'vnd.openxmlformats-officedocument.wordprocessingml.document',
+ 'vnd.openxmlformats-officedocument.wordprocessingml.template',
+ 'vnd.ms-word.document.macroEnabled.12',
+ 'vnd.ms-word.template.macroEnabled.12'
+ ]))
+ {
+ sClass = 'icon-file-text';
+ }
+ else if (-1 < Utils.inArray(aParts[1], [
+ 'excel', 'ms-excel', 'vnd.ms-excel',
+ 'vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+ 'vnd.openxmlformats-officedocument.spreadsheetml.template',
+ 'vnd.ms-excel.sheet.macroEnabled.12',
+ 'vnd.ms-excel.template.macroEnabled.12',
+ 'vnd.ms-excel.addin.macroEnabled.12',
+ 'vnd.ms-excel.sheet.binary.macroEnabled.12'
+ ]))
+ {
+ sClass = 'icon-file-excel';
+ }
+ else if (-1 < Utils.inArray(aParts[1], [
+ 'powerpoint', 'ms-powerpoint', 'vnd.ms-powerpoint',
+ 'vnd.openxmlformats-officedocument.presentationml.presentation',
+ 'vnd.openxmlformats-officedocument.presentationml.template',
+ 'vnd.openxmlformats-officedocument.presentationml.slideshow',
+ 'vnd.ms-powerpoint.addin.macroEnabled.12',
+ 'vnd.ms-powerpoint.presentation.macroEnabled.12',
+ 'vnd.ms-powerpoint.template.macroEnabled.12',
+ 'vnd.ms-powerpoint.slideshow.macroEnabled.12'
+ ]))
+ {
+ sClass = 'icon-file-chart-graph';
+ }
+ }
+
+ return sClass;
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @param {string} sId
+ * @param {string} sFileName
+ * @param {?number=} nSize
+ * @param {boolean=} bInline
+ * @param {boolean=} bLinked
+ * @param {string=} sCID
+ * @param {string=} sContentLocation
+ */
+function ComposeAttachmentModel(sId, sFileName, nSize, bInline, bLinked, sCID, sContentLocation)
+{
+ this.id = sId;
+ this.isInline = Utils.isUnd(bInline) ? false : !!bInline;
+ this.isLinked = Utils.isUnd(bLinked) ? false : !!bLinked;
+ this.CID = Utils.isUnd(sCID) ? '' : sCID;
+ this.contentLocation = Utils.isUnd(sContentLocation) ? '' : sContentLocation;
+ this.fromMessage = false;
+
+ this.fileName = ko.observable(sFileName);
+ this.size = ko.observable(Utils.isUnd(nSize) ? null : nSize);
+ this.tempName = ko.observable('');
+
+ this.progress = ko.observable('');
+ this.error = ko.observable('');
+ this.waiting = ko.observable(true);
+ this.uploading = ko.observable(false);
+ this.enabled = ko.observable(true);
+
+ this.friendlySize = ko.computed(function () {
+ var mSize = this.size();
+ return null === mSize ? '' : Utils.friendlySize(this.size());
+ }, this);
+}
+
+ComposeAttachmentModel.prototype.id = '';
+ComposeAttachmentModel.prototype.isInline = false;
+ComposeAttachmentModel.prototype.isLinked = false;
+ComposeAttachmentModel.prototype.CID = '';
+ComposeAttachmentModel.prototype.contentLocation = '';
+ComposeAttachmentModel.prototype.fromMessage = false;
+ComposeAttachmentModel.prototype.cancel = Utils.emptyFunction;
+
+/**
+ * @param {AjaxJsonComposeAttachment} oJsonAttachment
+ */
+ComposeAttachmentModel.prototype.initByUploadJson = function (oJsonAttachment)
+{
+ var bResult = false;
+ if (oJsonAttachment)
+ {
+ this.fileName(oJsonAttachment.Name);
+ this.size(Utils.isUnd(oJsonAttachment.Size) ? 0 : Utils.pInt(oJsonAttachment.Size));
+ this.tempName(Utils.isUnd(oJsonAttachment.TempName) ? '' : oJsonAttachment.TempName);
+ this.isInline = false;
+
+ bResult = true;
+ }
+
+ return bResult;
+};
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ */
+function MessageModel()
+{
+ this.folderFullNameRaw = '';
+ this.uid = '';
+ this.hash = '';
+ this.requestHash = '';
+ this.subject = ko.observable('');
+ this.subjectPrefix = ko.observable('');
+ this.subjectSuffix = ko.observable('');
+ this.size = ko.observable(0);
+ this.dateTimeStampInUTC = ko.observable(0);
+ this.priority = ko.observable(Enums.MessagePriority.Normal);
+
+ this.proxy = false;
+
+ this.fromEmailString = ko.observable('');
+ this.fromClearEmailString = ko.observable('');
+ this.toEmailsString = ko.observable('');
+ this.toClearEmailsString = ko.observable('');
+
+ this.senderEmailsString = ko.observable('');
+ this.senderClearEmailsString = ko.observable('');
+
+ this.emails = [];
+
+ this.from = [];
+ this.to = [];
+ this.cc = [];
+ this.bcc = [];
+ this.replyTo = [];
+ this.deliveredTo = [];
+
+ this.newForAnimation = ko.observable(false);
+
+ this.deleted = ko.observable(false);
+ this.unseen = ko.observable(false);
+ this.flagged = ko.observable(false);
+ this.answered = ko.observable(false);
+ this.forwarded = ko.observable(false);
+ this.isReadReceipt = ko.observable(false);
+
+ this.focused = ko.observable(false);
+ this.selected = ko.observable(false);
+ this.checked = ko.observable(false);
+ this.hasAttachments = ko.observable(false);
+ this.attachmentsMainType = ko.observable('');
+
+ this.moment = ko.observable(moment(moment.unix(0)));
+
+ this.attachmentIconClass = ko.computed(function () {
+ var sClass = '';
+ if (this.hasAttachments())
+ {
+ sClass = 'icon-attachment';
+ switch (this.attachmentsMainType())
+ {
+ case 'image':
+ sClass = 'icon-image';
+ break;
+ case 'archive':
+ sClass = 'icon-file-zip';
+ break;
+ case 'doc':
+ sClass = 'icon-file-text';
+ break;
+// case 'pdf':
+// sClass = 'icon-file-pdf';
+// break;
+ }
+ }
+ return sClass;
+ }, this);
+
+ this.fullFormatDateValue = ko.computed(function () {
+ return MessageModel.calculateFullFromatDateValue(this.dateTimeStampInUTC());
+ }, this);
+
+ this.momentDate = Utils.createMomentDate(this);
+ this.momentShortDate = Utils.createMomentShortDate(this);
+
+ this.dateTimeStampInUTC.subscribe(function (iValue) {
+ var iNow = moment().unix();
+ this.moment(moment.unix(iNow < iValue ? iNow : iValue));
+ }, this);
+
+ this.body = null;
+ this.plainRaw = '';
+ this.isHtml = ko.observable(false);
+ this.hasImages = ko.observable(false);
+ this.attachments = ko.observableArray([]);
+
+ this.isPgpSigned = ko.observable(false);
+ this.isPgpEncrypted = ko.observable(false);
+ this.pgpSignedVerifyStatus = ko.observable(Enums.SignedVerifyStatus.None);
+ this.pgpSignedVerifyUser = ko.observable('');
+
+ this.priority = ko.observable(Enums.MessagePriority.Normal);
+ this.readReceipt = ko.observable('');
+
+ this.aDraftInfo = [];
+ this.sMessageId = '';
+ this.sInReplyTo = '';
+ this.sReferences = '';
+
+ this.parentUid = ko.observable(0);
+ this.threads = ko.observableArray([]);
+ this.threadsLen = ko.observable(0);
+ this.hasUnseenSubMessage = ko.observable(false);
+ this.hasFlaggedSubMessage = ko.observable(false);
+
+ this.lastInCollapsedThread = ko.observable(false);
+ this.lastInCollapsedThreadLoading = ko.observable(false);
+
+ this.threadsLenResult = ko.computed(function () {
+ var iCount = this.threadsLen();
+ return 0 === this.parentUid() && 0 < iCount ? iCount + 1 : '';
+ }, this);
+}
+
+/**
+ * @static
+ * @param {AjaxJsonMessage} oJsonMessage
+ * @return {?MessageModel}
+ */
+MessageModel.newInstanceFromJson = function (oJsonMessage)
+{
+ var oMessageModel = new MessageModel();
+ return oMessageModel.initByJson(oJsonMessage) ? oMessageModel : null;
+};
+
+/**
+ * @static
+ * @param {number} iTimeStampInUTC
+ * @return {string}
+ */
+MessageModel.calculateFullFromatDateValue = function (iTimeStampInUTC)
+{
+ return 0 < iTimeStampInUTC ? moment.unix(iTimeStampInUTC).format('LLL') : '';
+};
+
+/**
+ * @static
+ * @param {Array} aEmail
+ * @param {boolean=} bFriendlyView
+ * @param {boolean=} bWrapWithLink = false
+ * @return {string}
+ */
+MessageModel.emailsToLine = function (aEmail, bFriendlyView, bWrapWithLink)
+{
+ var
+ aResult = [],
+ iIndex = 0,
+ iLen = 0
+ ;
+
+ if (Utils.isNonEmptyArray(aEmail))
+ {
+ for (iIndex = 0, iLen = aEmail.length; iIndex < iLen; iIndex++)
+ {
+ aResult.push(aEmail[iIndex].toLine(bFriendlyView, bWrapWithLink));
+ }
+ }
+
+ return aResult.join(', ');
+};
+
+/**
+ * @static
+ * @param {Array} aEmail
+ * @return {string}
+ */
+MessageModel.emailsToLineClear = function (aEmail)
+{
+ var
+ aResult = [],
+ iIndex = 0,
+ iLen = 0
+ ;
+
+ if (Utils.isNonEmptyArray(aEmail))
+ {
+ for (iIndex = 0, iLen = aEmail.length; iIndex < iLen; iIndex++)
+ {
+ if (aEmail[iIndex] && aEmail[iIndex].email && '' !== aEmail[iIndex].name)
+ {
+ aResult.push(aEmail[iIndex].email);
+ }
+ }
+ }
+
+ return aResult.join(', ');
+};
+
+/**
+ * @static
+ * @param {?Array} aJsonEmails
+ * @return {Array.}
+ */
+MessageModel.initEmailsFromJson = function (aJsonEmails)
+{
+ var
+ iIndex = 0,
+ iLen = 0,
+ oEmailModel = null,
+ aResult = []
+ ;
+
+ if (Utils.isNonEmptyArray(aJsonEmails))
+ {
+ for (iIndex = 0, iLen = aJsonEmails.length; iIndex < iLen; iIndex++)
+ {
+ oEmailModel = EmailModel.newInstanceFromJson(aJsonEmails[iIndex]);
+ if (oEmailModel)
+ {
+ aResult.push(oEmailModel);
+ }
+ }
+ }
+
+ return aResult;
+};
+
+/**
+ * @static
+ * @param {Array.} aMessageEmails
+ * @param {Object} oLocalUnic
+ * @param {Array} aLocalEmails
+ */
+MessageModel.replyHelper = function (aMessageEmails, oLocalUnic, aLocalEmails)
+{
+ if (aMessageEmails && 0 < aMessageEmails.length)
+ {
+ var
+ iIndex = 0,
+ iLen = aMessageEmails.length
+ ;
+
+ for (; iIndex < iLen; iIndex++)
+ {
+ if (Utils.isUnd(oLocalUnic[aMessageEmails[iIndex].email]))
+ {
+ oLocalUnic[aMessageEmails[iIndex].email] = true;
+ aLocalEmails.push(aMessageEmails[iIndex]);
+ }
+ }
+ }
+};
+
+MessageModel.prototype.clear = function ()
+{
+ this.folderFullNameRaw = '';
+ this.uid = '';
+ this.hash = '';
+ this.requestHash = '';
+ this.subject('');
+ this.subjectPrefix('');
+ this.subjectSuffix('');
+ this.size(0);
+ this.dateTimeStampInUTC(0);
+ this.priority(Enums.MessagePriority.Normal);
+
+ this.proxy = false;
+
+ this.fromEmailString('');
+ this.fromClearEmailString('');
+ this.toEmailsString('');
+ this.toClearEmailsString('');
+ this.senderEmailsString('');
+ this.senderClearEmailsString('');
+
+ this.emails = [];
+
+ this.from = [];
+ this.to = [];
+ this.cc = [];
+ this.bcc = [];
+ this.replyTo = [];
+ this.deliveredTo = [];
+
+ this.newForAnimation(false);
+
+ this.deleted(false);
+ this.unseen(false);
+ this.flagged(false);
+ this.answered(false);
+ this.forwarded(false);
+ this.isReadReceipt(false);
+
+ this.selected(false);
+ this.checked(false);
+ this.hasAttachments(false);
+ this.attachmentsMainType('');
+
+ this.body = null;
+ this.isHtml(false);
+ this.hasImages(false);
+ this.attachments([]);
+
+ this.isPgpSigned(false);
+ this.isPgpEncrypted(false);
+ this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.None);
+ this.pgpSignedVerifyUser('');
+
+ this.priority(Enums.MessagePriority.Normal);
+ this.readReceipt('');
+ this.aDraftInfo = [];
+ this.sMessageId = '';
+ this.sInReplyTo = '';
+ this.sReferences = '';
+
+ this.parentUid(0);
+ this.threads([]);
+ this.threadsLen(0);
+ this.hasUnseenSubMessage(false);
+ this.hasFlaggedSubMessage(false);
+
+ this.lastInCollapsedThread(false);
+ this.lastInCollapsedThreadLoading(false);
+};
+
+MessageModel.prototype.computeSenderEmail = function ()
+{
+ var
+ sSent = RL.data().sentFolder(),
+ sDraft = RL.data().draftFolder()
+ ;
+
+ this.senderEmailsString(this.folderFullNameRaw === sSent || this.folderFullNameRaw === sDraft ?
+ this.toEmailsString() : this.fromEmailString());
+
+ this.senderClearEmailsString(this.folderFullNameRaw === sSent || this.folderFullNameRaw === sDraft ?
+ this.toClearEmailsString() : this.fromClearEmailString());
+};
+
+/**
+ * @param {AjaxJsonMessage} oJsonMessage
+ * @return {boolean}
+ */
+MessageModel.prototype.initByJson = function (oJsonMessage)
+{
+ var bResult = false;
+ if (oJsonMessage && 'Object/Message' === oJsonMessage['@Object'])
+ {
+ this.folderFullNameRaw = oJsonMessage.Folder;
+ this.uid = oJsonMessage.Uid;
+ this.hash = oJsonMessage.Hash;
+ this.requestHash = oJsonMessage.RequestHash;
+
+ this.proxy = !!oJsonMessage.ExternalProxy;
+
+ this.size(Utils.pInt(oJsonMessage.Size));
+
+ this.from = MessageModel.initEmailsFromJson(oJsonMessage.From);
+ this.to = MessageModel.initEmailsFromJson(oJsonMessage.To);
+ this.cc = MessageModel.initEmailsFromJson(oJsonMessage.Cc);
+ this.bcc = MessageModel.initEmailsFromJson(oJsonMessage.Bcc);
+ this.replyTo = MessageModel.initEmailsFromJson(oJsonMessage.ReplyTo);
+ this.deliveredTo = MessageModel.initEmailsFromJson(oJsonMessage.DeliveredTo);
+
+ this.subject(oJsonMessage.Subject);
+ if (Utils.isArray(oJsonMessage.SubjectParts))
+ {
+ this.subjectPrefix(oJsonMessage.SubjectParts[0]);
+ this.subjectSuffix(oJsonMessage.SubjectParts[1]);
+ }
+ else
+ {
+ this.subjectPrefix('');
+ this.subjectSuffix(this.subject());
+ }
+
+ this.dateTimeStampInUTC(Utils.pInt(oJsonMessage.DateTimeStampInUTC));
+ this.hasAttachments(!!oJsonMessage.HasAttachments);
+ this.attachmentsMainType(oJsonMessage.AttachmentsMainType);
+
+ this.fromEmailString(MessageModel.emailsToLine(this.from, true));
+ this.fromClearEmailString(MessageModel.emailsToLineClear(this.from));
+ this.toEmailsString(MessageModel.emailsToLine(this.to, true));
+ this.toClearEmailsString(MessageModel.emailsToLineClear(this.to));
+
+ this.parentUid(Utils.pInt(oJsonMessage.ParentThread));
+ this.threads(Utils.isArray(oJsonMessage.Threads) ? oJsonMessage.Threads : []);
+ this.threadsLen(Utils.pInt(oJsonMessage.ThreadsLen));
+
+ this.initFlagsByJson(oJsonMessage);
+ this.computeSenderEmail();
+
+ bResult = true;
+ }
+
+ return bResult;
+};
+
+/**
+ * @param {AjaxJsonMessage} oJsonMessage
+ * @return {boolean}
+ */
+MessageModel.prototype.initUpdateByMessageJson = function (oJsonMessage)
+{
+ var
+ bResult = false,
+ iPriority = Enums.MessagePriority.Normal
+ ;
+
+ if (oJsonMessage && 'Object/Message' === oJsonMessage['@Object'])
+ {
+ iPriority = Utils.pInt(oJsonMessage.Priority);
+ this.priority(-1 < Utils.inArray(iPriority, [Enums.MessagePriority.High, Enums.MessagePriority.Low]) ?
+ iPriority : Enums.MessagePriority.Normal);
+
+ this.aDraftInfo = oJsonMessage.DraftInfo;
+
+ this.sMessageId = oJsonMessage.MessageId;
+ this.sInReplyTo = oJsonMessage.InReplyTo;
+ this.sReferences = oJsonMessage.References;
+
+ this.proxy = !!oJsonMessage.ExternalProxy;
+
+ if (RL.data().capaOpenPGP())
+ {
+ this.isPgpSigned(!!oJsonMessage.PgpSigned);
+ this.isPgpEncrypted(!!oJsonMessage.PgpEncrypted);
+ }
+
+ this.hasAttachments(!!oJsonMessage.HasAttachments);
+ this.attachmentsMainType(oJsonMessage.AttachmentsMainType);
+
+ this.foundedCIDs = Utils.isArray(oJsonMessage.FoundedCIDs) ? oJsonMessage.FoundedCIDs : [];
+ this.attachments(this.initAttachmentsFromJson(oJsonMessage.Attachments));
+
+ this.readReceipt(oJsonMessage.ReadReceipt || '');
+
+ this.computeSenderEmail();
+
+ bResult = true;
+ }
+
+ return bResult;
+};
+
+/**
+ * @param {(AjaxJsonAttachment|null)} oJsonAttachments
+ * @return {Array}
+ */
+MessageModel.prototype.initAttachmentsFromJson = function (oJsonAttachments)
+{
+ var
+ iIndex = 0,
+ iLen = 0,
+ oAttachmentModel = null,
+ aResult = []
+ ;
+
+ if (oJsonAttachments && 'Collection/AttachmentCollection' === oJsonAttachments['@Object'] &&
+ Utils.isNonEmptyArray(oJsonAttachments['@Collection']))
+ {
+ for (iIndex = 0, iLen = oJsonAttachments['@Collection'].length; iIndex < iLen; iIndex++)
+ {
+ oAttachmentModel = AttachmentModel.newInstanceFromJson(oJsonAttachments['@Collection'][iIndex]);
+ if (oAttachmentModel)
+ {
+ if ('' !== oAttachmentModel.cidWithOutTags && 0 < this.foundedCIDs.length &&
+ 0 <= Utils.inArray(oAttachmentModel.cidWithOutTags, this.foundedCIDs))
+ {
+ oAttachmentModel.isLinked = true;
+ }
+
+ aResult.push(oAttachmentModel);
+ }
+ }
+ }
+
+ return aResult;
+};
+
+/**
+ * @param {AjaxJsonMessage} oJsonMessage
+ * @return {boolean}
+ */
+MessageModel.prototype.initFlagsByJson = function (oJsonMessage)
+{
+ var bResult = false;
+
+ if (oJsonMessage && 'Object/Message' === oJsonMessage['@Object'])
+ {
+ this.unseen(!oJsonMessage.IsSeen);
+ this.flagged(!!oJsonMessage.IsFlagged);
+ this.answered(!!oJsonMessage.IsAnswered);
+ this.forwarded(!!oJsonMessage.IsForwarded);
+ this.isReadReceipt(!!oJsonMessage.IsReadReceipt);
+
+ bResult = true;
+ }
+
+ return bResult;
+};
+
+/**
+ * @param {boolean} bFriendlyView
+ * @param {boolean=} bWrapWithLink = false
+ * @return {string}
+ */
+MessageModel.prototype.fromToLine = function (bFriendlyView, bWrapWithLink)
+{
+ return MessageModel.emailsToLine(this.from, bFriendlyView, bWrapWithLink);
+};
+
+/**
+ * @param {boolean} bFriendlyView
+ * @param {boolean=} bWrapWithLink = false
+ * @return {string}
+ */
+MessageModel.prototype.toToLine = function (bFriendlyView, bWrapWithLink)
+{
+ return MessageModel.emailsToLine(this.to, bFriendlyView, bWrapWithLink);
+};
+
+/**
+ * @param {boolean} bFriendlyView
+ * @param {boolean=} bWrapWithLink = false
+ * @return {string}
+ */
+MessageModel.prototype.ccToLine = function (bFriendlyView, bWrapWithLink)
+{
+ return MessageModel.emailsToLine(this.cc, bFriendlyView, bWrapWithLink);
+};
+
+/**
+ * @param {boolean} bFriendlyView
+ * @param {boolean=} bWrapWithLink = false
+ * @return {string}
+ */
+MessageModel.prototype.bccToLine = function (bFriendlyView, bWrapWithLink)
+{
+ return MessageModel.emailsToLine(this.bcc, bFriendlyView, bWrapWithLink);
+};
+
+/**
+ * @return string
+ */
+MessageModel.prototype.lineAsCcc = function ()
+{
+ var aResult = [];
+ if (this.deleted())
+ {
+ aResult.push('deleted');
+ }
+ if (this.selected())
+ {
+ aResult.push('selected');
+ }
+ if (this.checked())
+ {
+ aResult.push('checked');
+ }
+ if (this.flagged())
+ {
+ aResult.push('flagged');
+ }
+ if (this.unseen())
+ {
+ aResult.push('unseen');
+ }
+ if (this.answered())
+ {
+ aResult.push('answered');
+ }
+ if (this.forwarded())
+ {
+ aResult.push('forwarded');
+ }
+ if (this.focused())
+ {
+ aResult.push('focused');
+ }
+ if (this.hasAttachments())
+ {
+ aResult.push('withAttachments');
+ switch (this.attachmentsMainType())
+ {
+ case 'image':
+ aResult.push('imageOnlyAttachments');
+ break;
+ case 'archive':
+ aResult.push('archiveOnlyAttachments');
+ break;
+ }
+ }
+ if (this.newForAnimation())
+ {
+ aResult.push('new');
+ }
+ if ('' === this.subject())
+ {
+ aResult.push('emptySubject');
+ }
+ if (0 < this.parentUid())
+ {
+ aResult.push('hasParentMessage');
+ }
+ if (0 < this.threadsLen() && 0 === this.parentUid())
+ {
+ aResult.push('hasChildrenMessage');
+ }
+ if (this.hasUnseenSubMessage())
+ {
+ aResult.push('hasUnseenSubMessage');
+ }
+ if (this.hasFlaggedSubMessage())
+ {
+ aResult.push('hasFlaggedSubMessage');
+ }
+
+ return aResult.join(' ');
+};
+
+/**
+ * @return {boolean}
+ */
+MessageModel.prototype.hasVisibleAttachments = function ()
+{
+ return !!_.find(this.attachments(), function (oAttachment) {
+ return !oAttachment.isLinked;
+ });
+// return 0 < this.attachments().length;
+};
+
+/**
+ * @param {string} sCid
+ * @return {*}
+ */
+MessageModel.prototype.findAttachmentByCid = function (sCid)
+{
+ var
+ oResult = null,
+ aAttachments = this.attachments()
+ ;
+
+ if (Utils.isNonEmptyArray(aAttachments))
+ {
+ sCid = sCid.replace(/^<+/, '').replace(/>+$/, '');
+ oResult = _.find(aAttachments, function (oAttachment) {
+ return sCid === oAttachment.cidWithOutTags;
+ });
+ }
+
+ return oResult || null;
+};
+
+/**
+ * @param {string} sContentLocation
+ * @return {*}
+ */
+MessageModel.prototype.findAttachmentByContentLocation = function (sContentLocation)
+{
+ var
+ oResult = null,
+ aAttachments = this.attachments()
+ ;
+
+ if (Utils.isNonEmptyArray(aAttachments))
+ {
+ oResult = _.find(aAttachments, function (oAttachment) {
+ return sContentLocation === oAttachment.contentLocation;
+ });
+ }
+
+ return oResult || null;
+};
+
+
+/**
+ * @return {string}
+ */
+MessageModel.prototype.messageId = function ()
+{
+ return this.sMessageId;
+};
+
+/**
+ * @return {string}
+ */
+MessageModel.prototype.inReplyTo = function ()
+{
+ return this.sInReplyTo;
+};
+
+/**
+ * @return {string}
+ */
+MessageModel.prototype.references = function ()
+{
+ return this.sReferences;
+};
+
+/**
+ * @return {string}
+ */
+MessageModel.prototype.fromAsSingleEmail = function ()
+{
+ return Utils.isArray(this.from) && this.from[0] ? this.from[0].email : '';
+};
+
+/**
+ * @return {string}
+ */
+MessageModel.prototype.viewLink = function ()
+{
+ return RL.link().messageViewLink(this.requestHash);
+};
+
+/**
+ * @return {string}
+ */
+MessageModel.prototype.downloadLink = function ()
+{
+ return RL.link().messageDownloadLink(this.requestHash);
+};
+
+/**
+ * @param {Object} oExcludeEmails
+ * @return {Array}
+ */
+MessageModel.prototype.replyEmails = function (oExcludeEmails)
+{
+ var
+ aResult = [],
+ oUnic = Utils.isUnd(oExcludeEmails) ? {} : oExcludeEmails
+ ;
+
+ MessageModel.replyHelper(this.replyTo, oUnic, aResult);
+ if (0 === aResult.length)
+ {
+ MessageModel.replyHelper(this.from, oUnic, aResult);
+ }
+
+ return aResult;
+};
+
+/**
+ * @param {Object} oExcludeEmails
+ * @return {Array.}
+ */
+MessageModel.prototype.replyAllEmails = function (oExcludeEmails)
+{
+ var
+ aToResult = [],
+ aCcResult = [],
+ oUnic = Utils.isUnd(oExcludeEmails) ? {} : oExcludeEmails
+ ;
+
+ MessageModel.replyHelper(this.replyTo, oUnic, aToResult);
+ if (0 === aToResult.length)
+ {
+ MessageModel.replyHelper(this.from, oUnic, aToResult);
+ }
+
+ MessageModel.replyHelper(this.to, oUnic, aToResult);
+ MessageModel.replyHelper(this.cc, oUnic, aCcResult);
+
+ return [aToResult, aCcResult];
+};
+
+/**
+ * @return {string}
+ */
+MessageModel.prototype.textBodyToString = function ()
+{
+ return this.body ? this.body.html() : '';
+};
+
+/**
+ * @return {string}
+ */
+MessageModel.prototype.attachmentsToStringLine = function ()
+{
+ var aAttachLines = _.map(this.attachments(), function (oItem) {
+ return oItem.fileName + ' (' + oItem.friendlySize + ')';
+ });
+
+ return aAttachLines && 0 < aAttachLines.length ? aAttachLines.join(', ') : '';
+};
+
+/**
+ * @return {Object}
+ */
+MessageModel.prototype.getDataForWindowPopup = function ()
+{
+ return {
+ 'popupFrom': this.fromToLine(false),
+ 'popupTo': this.toToLine(false),
+ 'popupCc': this.ccToLine(false),
+ 'popupBcc': this.bccToLine(false),
+ 'popupSubject': this.subject(),
+ 'popupDate': this.fullFormatDateValue(),
+ 'popupAttachments': this.attachmentsToStringLine(),
+ 'popupBody': this.textBodyToString()
+ };
+};
+
+/**
+ * @param {boolean=} bPrint = false
+ */
+MessageModel.prototype.viewPopupMessage = function (bPrint)
+{
+ Utils.windowPopupKnockout(this.getDataForWindowPopup(), 'PopupsWindowSimpleMessage', this.subject(), function (oPopupWin) {
+ if (oPopupWin && oPopupWin.document && oPopupWin.document.body)
+ {
+ $('img.lazy', oPopupWin.document.body).each(function (iIndex, oImg) {
+
+ var
+ $oImg = $(oImg),
+ sOrig = $oImg.data('original'),
+ sSrc = $oImg.attr('src')
+ ;
+
+ if (0 <= iIndex && sOrig && !sSrc)
+ {
+ $oImg.attr('src', sOrig);
+ }
+ });
+
+ if (bPrint)
+ {
+ window.setTimeout(function () {
+ oPopupWin.print();
+ }, 100);
+ }
+ }
+ });
+};
+
+MessageModel.prototype.printMessage = function ()
+{
+ this.viewPopupMessage(true);
+};
+
+/**
+ * @returns {string}
+ */
+MessageModel.prototype.generateUid = function ()
+{
+ return this.folderFullNameRaw + '/' + this.uid;
+};
+
+/**
+ * @param {MessageModel} oMessage
+ * @return {MessageModel}
+ */
+MessageModel.prototype.populateByMessageListItem = function (oMessage)
+{
+ this.folderFullNameRaw = oMessage.folderFullNameRaw;
+ this.uid = oMessage.uid;
+ this.hash = oMessage.hash;
+ this.requestHash = oMessage.requestHash;
+ this.subject(oMessage.subject());
+ this.subjectPrefix(this.subjectPrefix());
+ this.subjectSuffix(this.subjectSuffix());
+
+ this.size(oMessage.size());
+ this.dateTimeStampInUTC(oMessage.dateTimeStampInUTC());
+ this.priority(oMessage.priority());
+
+ this.proxy = oMessage.proxy;
+
+ this.fromEmailString(oMessage.fromEmailString());
+ this.fromClearEmailString(oMessage.fromClearEmailString());
+ this.toEmailsString(oMessage.toEmailsString());
+ this.toClearEmailsString(oMessage.toClearEmailsString());
+
+ this.emails = oMessage.emails;
+
+ this.from = oMessage.from;
+ this.to = oMessage.to;
+ this.cc = oMessage.cc;
+ this.bcc = oMessage.bcc;
+ this.replyTo = oMessage.replyTo;
+ this.deliveredTo = oMessage.deliveredTo;
+
+ this.unseen(oMessage.unseen());
+ this.flagged(oMessage.flagged());
+ this.answered(oMessage.answered());
+ this.forwarded(oMessage.forwarded());
+ this.isReadReceipt(oMessage.isReadReceipt());
+
+ this.selected(oMessage.selected());
+ this.checked(oMessage.checked());
+ this.hasAttachments(oMessage.hasAttachments());
+ this.attachmentsMainType(oMessage.attachmentsMainType());
+
+ this.moment(oMessage.moment());
+
+ this.body = null;
+// this.isHtml(false);
+// this.hasImages(false);
+// this.attachments([]);
+
+// this.isPgpSigned(false);
+// this.isPgpEncrypted(false);
+
+ this.priority(Enums.MessagePriority.Normal);
+ this.aDraftInfo = [];
+ this.sMessageId = '';
+ this.sInReplyTo = '';
+ this.sReferences = '';
+
+ this.parentUid(oMessage.parentUid());
+ this.threads(oMessage.threads());
+ this.threadsLen(oMessage.threadsLen());
+
+ this.computeSenderEmail();
+
+ return this;
+};
+
+MessageModel.prototype.showExternalImages = function (bLazy)
+{
+ if (this.body && this.body.data('rl-has-images'))
+ {
+ var sAttr = '';
+ bLazy = Utils.isUnd(bLazy) ? false : bLazy;
+
+ this.hasImages(false);
+ this.body.data('rl-has-images', false);
+
+ sAttr = this.proxy ? 'data-x-additional-src' : 'data-x-src';
+ $('[' + sAttr + ']', this.body).each(function () {
+ if (bLazy && $(this).is('img'))
+ {
+ $(this)
+ .addClass('lazy')
+ .attr('data-original', $(this).attr(sAttr))
+ .removeAttr(sAttr)
+ ;
+ }
+ else
+ {
+ $(this).attr('src', $(this).attr(sAttr)).removeAttr(sAttr);
+ }
+ });
+
+ sAttr = this.proxy ? 'data-x-additional-style-url' : 'data-x-style-url';
+ $('[' + sAttr + ']', this.body).each(function () {
+ var sStyle = Utils.trim($(this).attr('style'));
+ sStyle = '' === sStyle ? '' : (';' === sStyle.substr(-1) ? sStyle + ' ' : sStyle + '; ');
+ $(this).attr('style', sStyle + $(this).attr(sAttr)).removeAttr(sAttr);
+ });
+
+ if (bLazy)
+ {
+ $('img.lazy', this.body).addClass('lazy-inited').lazyload({
+ 'threshold' : 400,
+ 'effect' : 'fadeIn',
+ 'skip_invisible' : false,
+ 'container': $('.RL-MailMessageView .messageView .messageItem .content')[0]
+ });
+
+ $window.resize();
+ }
+
+ Utils.windowResize(500);
+ }
+};
+
+MessageModel.prototype.showInternalImages = function (bLazy)
+{
+ if (this.body && !this.body.data('rl-init-internal-images'))
+ {
+ this.body.data('rl-init-internal-images', true);
+
+ bLazy = Utils.isUnd(bLazy) ? false : bLazy;
+
+ var self = this;
+
+ $('[data-x-src-cid]', this.body).each(function () {
+
+ var oAttachment = self.findAttachmentByCid($(this).attr('data-x-src-cid'));
+ if (oAttachment && oAttachment.download)
+ {
+ if (bLazy && $(this).is('img'))
+ {
+ $(this)
+ .addClass('lazy')
+ .attr('data-original', oAttachment.linkPreview());
+ }
+ else
+ {
+ $(this).attr('src', oAttachment.linkPreview());
+ }
+ }
+ });
+
+ $('[data-x-src-location]', this.body).each(function () {
+
+ var oAttachment = self.findAttachmentByContentLocation($(this).attr('data-x-src-location'));
+ if (!oAttachment)
+ {
+ oAttachment = self.findAttachmentByCid($(this).attr('data-x-src-location'));
+ }
+
+ if (oAttachment && oAttachment.download)
+ {
+ if (bLazy && $(this).is('img'))
+ {
+ $(this)
+ .addClass('lazy')
+ .attr('data-original', oAttachment.linkPreview());
+ }
+ else
+ {
+ $(this).attr('src', oAttachment.linkPreview());
+ }
+ }
+ });
+
+ $('[data-x-style-cid]', this.body).each(function () {
+
+ var
+ sStyle = '',
+ sName = '',
+ oAttachment = self.findAttachmentByCid($(this).attr('data-x-style-cid'))
+ ;
+
+ if (oAttachment && oAttachment.linkPreview)
+ {
+ sName = $(this).attr('data-x-style-cid-name');
+ if ('' !== sName)
+ {
+ sStyle = Utils.trim($(this).attr('style'));
+ sStyle = '' === sStyle ? '' : (';' === sStyle.substr(-1) ? sStyle + ' ' : sStyle + '; ');
+ $(this).attr('style', sStyle + sName + ': url(\'' + oAttachment.linkPreview() + '\')');
+ }
+ }
+ });
+
+ if (bLazy)
+ {
+ (function ($oImg, oContainer) {
+ _.delay(function () {
+ $oImg.addClass('lazy-inited').lazyload({
+ 'threshold' : 400,
+ 'effect' : 'fadeIn',
+ 'skip_invisible' : false,
+ 'container': oContainer
+ });
+ }, 300);
+ }($('img.lazy', self.body), $('.RL-MailMessageView .messageView .messageItem .content')[0]));
+ }
+
+ Utils.windowResize(500);
+ }
+};
+
+MessageModel.prototype.storeDataToDom = function ()
+{
+ if (this.body)
+ {
+ this.body.data('rl-is-html', !!this.isHtml());
+ this.body.data('rl-has-images', !!this.hasImages());
+
+ this.body.data('rl-plain-raw', this.plainRaw);
+
+ if (RL.data().capaOpenPGP())
+ {
+ this.body.data('rl-plain-pgp-signed', !!this.isPgpSigned());
+ this.body.data('rl-plain-pgp-encrypted', !!this.isPgpEncrypted());
+ this.body.data('rl-pgp-verify-status', this.pgpSignedVerifyStatus());
+ this.body.data('rl-pgp-verify-user', this.pgpSignedVerifyUser());
+ }
+ }
+};
+
+MessageModel.prototype.storePgpVerifyDataToDom = function ()
+{
+ if (this.body && RL.data().capaOpenPGP())
+ {
+ this.body.data('rl-pgp-verify-status', this.pgpSignedVerifyStatus());
+ this.body.data('rl-pgp-verify-user', this.pgpSignedVerifyUser());
+ }
+};
+
+MessageModel.prototype.fetchDataToDom = function ()
+{
+ if (this.body)
+ {
+ this.isHtml(!!this.body.data('rl-is-html'));
+ this.hasImages(!!this.body.data('rl-has-images'));
+
+ this.plainRaw = Utils.pString(this.body.data('rl-plain-raw'));
+
+ if (RL.data().capaOpenPGP())
+ {
+ this.isPgpSigned(!!this.body.data('rl-plain-pgp-signed'));
+ this.isPgpEncrypted(!!this.body.data('rl-plain-pgp-encrypted'));
+ this.pgpSignedVerifyStatus(this.body.data('rl-pgp-verify-status'));
+ this.pgpSignedVerifyUser(this.body.data('rl-pgp-verify-user'));
+ }
+ else
+ {
+ this.isPgpSigned(false);
+ this.isPgpEncrypted(false);
+ this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.None);
+ this.pgpSignedVerifyUser('');
+ }
+ }
+};
+
+MessageModel.prototype.verifyPgpSignedClearMessage = function ()
+{
+ if (this.isPgpSigned())
+ {
+ var
+ aRes = [],
+ mPgpMessage = null,
+ sFrom = this.from && this.from[0] && this.from[0].email ? this.from[0].email : '',
+ aPublicKeys = RL.data().findPublicKeysByEmail(sFrom),
+ oValidKey = null,
+ oValidSysKey = null,
+ sPlain = ''
+ ;
+
+ this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.Error);
+ this.pgpSignedVerifyUser('');
+
+ try
+ {
+ mPgpMessage = window.openpgp.cleartext.readArmored(this.plainRaw);
+ if (mPgpMessage && mPgpMessage.getText)
+ {
+ this.pgpSignedVerifyStatus(
+ aPublicKeys.length ? Enums.SignedVerifyStatus.Unverified : Enums.SignedVerifyStatus.UnknownPublicKeys);
+
+ aRes = mPgpMessage.verify(aPublicKeys);
+ if (aRes && 0 < aRes.length)
+ {
+ oValidKey = _.find(aRes, function (oItem) {
+ return oItem && oItem.keyid && oItem.valid;
+ });
+
+ if (oValidKey)
+ {
+ oValidSysKey = RL.data().findPublicKeyByHex(oValidKey.keyid.toHex());
+ if (oValidSysKey)
+ {
+ sPlain = mPgpMessage.getText();
+
+ this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.Success);
+ this.pgpSignedVerifyUser(oValidSysKey.user);
+
+ sPlain =
+ $proxyDiv.empty().append(
+ $('').text(sPlain)
+ ).html()
+ ;
+
+ $proxyDiv.empty();
+
+ this.replacePlaneTextBody(sPlain);
+ }
+ }
+ }
+ }
+ }
+ catch (oExc) {}
+
+ this.storePgpVerifyDataToDom();
+ }
+};
+
+MessageModel.prototype.decryptPgpEncryptedMessage = function (sPassword)
+{
+ if (this.isPgpEncrypted())
+ {
+ var
+ aRes = [],
+ mPgpMessage = null,
+ mPgpMessageDecrypted = null,
+ sFrom = this.from && this.from[0] && this.from[0].email ? this.from[0].email : '',
+ aPublicKey = RL.data().findPublicKeysByEmail(sFrom),
+ oPrivateKey = RL.data().findSelfPrivateKey(sPassword),
+ oValidKey = null,
+ oValidSysKey = null,
+ sPlain = ''
+ ;
+
+ this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.Error);
+ this.pgpSignedVerifyUser('');
+
+ if (!oPrivateKey)
+ {
+ this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.UnknownPrivateKey);
+ }
+
+ try
+ {
+ mPgpMessage = window.openpgp.message.readArmored(this.plainRaw);
+ if (mPgpMessage && oPrivateKey && mPgpMessage.decrypt)
+ {
+ this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.Unverified);
+
+ mPgpMessageDecrypted = mPgpMessage.decrypt(oPrivateKey);
+ if (mPgpMessageDecrypted)
+ {
+ aRes = mPgpMessageDecrypted.verify(aPublicKey);
+ if (aRes && 0 < aRes.length)
+ {
+ oValidKey = _.find(aRes, function (oItem) {
+ return oItem && oItem.keyid && oItem.valid;
+ });
+
+ if (oValidKey)
+ {
+ oValidSysKey = RL.data().findPublicKeyByHex(oValidKey.keyid.toHex());
+ if (oValidSysKey)
+ {
+ this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.Success);
+ this.pgpSignedVerifyUser(oValidSysKey.user);
+ }
+ }
+ }
+
+ sPlain = mPgpMessageDecrypted.getText();
+
+ sPlain =
+ $proxyDiv.empty().append(
+ $('').text(sPlain)
+ ).html()
+ ;
+
+ $proxyDiv.empty();
+
+ this.replacePlaneTextBody(sPlain);
+ }
+ }
+ }
+ catch (oExc) {}
+
+ this.storePgpVerifyDataToDom();
+ }
+};
+
+MessageModel.prototype.replacePlaneTextBody = function (sPlain)
+{
+ if (this.body)
+ {
+ this.body.html(sPlain).addClass('b-text-part plain');
+ }
+};
+
+/**
+ * @return {string}
+ */
+MessageModel.prototype.flagHash = function ()
+{
+ return [this.deleted(), this.unseen(), this.flagged(), this.answered(), this.forwarded(),
+ this.isReadReceipt()].join('');
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ */
+function FolderModel()
+{
+ this.name = ko.observable('');
+ this.fullName = '';
+ this.fullNameRaw = '';
+ this.fullNameHash = '';
+ this.delimiter = '';
+ this.namespace = '';
+ this.deep = 0;
+ this.interval = 0;
+
+ this.selectable = false;
+ this.existen = true;
+
+ this.type = ko.observable(Enums.FolderType.User);
+
+ this.focused = ko.observable(false);
+ this.selected = ko.observable(false);
+ this.edited = ko.observable(false);
+ this.collapsed = ko.observable(true);
+ this.subScribed = ko.observable(true);
+ this.subFolders = ko.observableArray([]);
+ this.deleteAccess = ko.observable(false);
+ this.actionBlink = ko.observable(false).extend({'falseTimeout': 1000});
+
+ this.nameForEdit = ko.observable('');
+
+ this.name.subscribe(function (sValue) {
+ this.nameForEdit(sValue);
+ }, this);
+
+ this.edited.subscribe(function (bValue) {
+ if (bValue)
+ {
+ this.nameForEdit(this.name());
+ }
+ }, this);
+
+ this.privateMessageCountAll = ko.observable(0);
+ this.privateMessageCountUnread = ko.observable(0);
+
+ this.collapsedPrivate = ko.observable(true);
+}
+
+/**
+ * @static
+ * @param {AjaxJsonFolder} oJsonFolder
+ * @return {?FolderModel}
+ */
+FolderModel.newInstanceFromJson = function (oJsonFolder)
+{
+ var oFolderModel = new FolderModel();
+ return oFolderModel.initByJson(oJsonFolder) ? oFolderModel.initComputed() : null;
+};
+
+/**
+ * @return {FolderModel}
+ */
+FolderModel.prototype.initComputed = function ()
+{
+ this.hasSubScribedSubfolders = ko.computed(function () {
+ return !!_.find(this.subFolders(), function (oFolder) {
+ return oFolder.subScribed() && !oFolder.isSystemFolder();
+ });
+ }, this);
+
+ this.canBeEdited = ko.computed(function () {
+ return Enums.FolderType.User === this.type() && this.existen && this.selectable;
+ }, this);
+
+ this.visible = ko.computed(function () {
+ var
+ bSubScribed = this.subScribed(),
+ bSubFolders = this.hasSubScribedSubfolders()
+ ;
+
+ return (bSubScribed || (bSubFolders && (!this.existen || !this.selectable)));
+ }, this);
+
+ this.isSystemFolder = ko.computed(function () {
+ return Enums.FolderType.User !== this.type();
+ }, this);
+
+ this.hidden = ko.computed(function () {
+ var
+ bSystem = this.isSystemFolder(),
+ bSubFolders = this.hasSubScribedSubfolders()
+ ;
+
+ return (bSystem && !bSubFolders) || (!this.selectable && !bSubFolders);
+
+ }, this);
+
+ this.selectableForFolderList = ko.computed(function () {
+ return !this.isSystemFolder() && this.selectable;
+ }, this);
+
+ this.messageCountAll = ko.computed({
+ 'read': this.privateMessageCountAll,
+ 'write': function (iValue) {
+ if (Utils.isPosNumeric(iValue, true))
+ {
+ this.privateMessageCountAll(iValue);
+ }
+ else
+ {
+ this.privateMessageCountAll.valueHasMutated();
+ }
+ },
+ 'owner': this
+ });
+
+ this.messageCountUnread = ko.computed({
+ 'read': this.privateMessageCountUnread,
+ 'write': function (iValue) {
+ if (Utils.isPosNumeric(iValue, true))
+ {
+ this.privateMessageCountUnread(iValue);
+ }
+ else
+ {
+ this.privateMessageCountUnread.valueHasMutated();
+ }
+ },
+ 'owner': this
+ });
+
+ this.printableUnreadCount = ko.computed(function () {
+ var
+ iCount = this.messageCountAll(),
+ iUnread = this.messageCountUnread(),
+ iType = this.type()
+ ;
+
+ if (Enums.FolderType.Inbox === iType)
+ {
+ RL.data().foldersInboxUnreadCount(iUnread);
+ }
+
+ if (0 < iCount)
+ {
+ if (Enums.FolderType.Draft === iType)
+ {
+ return '' + iCount;
+ }
+ else if (0 < iUnread && Enums.FolderType.Trash !== iType && Enums.FolderType.Archive !== iType && Enums.FolderType.SentItems !== iType)
+ {
+ return '' + iUnread;
+ }
+ }
+
+ return '';
+
+ }, this);
+
+ this.canBeDeleted = ko.computed(function () {
+ var
+ bSystem = this.isSystemFolder()
+ ;
+ return !bSystem && 0 === this.subFolders().length && 'INBOX' !== this.fullNameRaw;
+ }, this);
+
+ this.canBeSubScribed = ko.computed(function () {
+ return !this.isSystemFolder() && this.selectable && 'INBOX' !== this.fullNameRaw;
+ }, this);
+
+ this.visible.subscribe(function () {
+ Utils.timeOutAction('folder-list-folder-visibility-change', function () {
+ $window.trigger('folder-list-folder-visibility-change');
+ }, 100);
+ });
+
+ this.localName = ko.computed(function () {
+
+ Globals.langChangeTrigger();
+
+ var
+ iType = this.type(),
+ sName = this.name()
+ ;
+
+ if (this.isSystemFolder())
+ {
+ switch (iType)
+ {
+ case Enums.FolderType.Inbox:
+ sName = Utils.i18n('FOLDER_LIST/INBOX_NAME');
+ break;
+ case Enums.FolderType.SentItems:
+ sName = Utils.i18n('FOLDER_LIST/SENT_NAME');
+ break;
+ case Enums.FolderType.Draft:
+ sName = Utils.i18n('FOLDER_LIST/DRAFTS_NAME');
+ break;
+ case Enums.FolderType.Spam:
+ sName = Utils.i18n('FOLDER_LIST/SPAM_NAME');
+ break;
+ case Enums.FolderType.Trash:
+ sName = Utils.i18n('FOLDER_LIST/TRASH_NAME');
+ break;
+ case Enums.FolderType.Archive:
+ sName = Utils.i18n('FOLDER_LIST/ARCHIVE_NAME');
+ break;
+ }
+ }
+
+ return sName;
+
+ }, this);
+
+ this.manageFolderSystemName = ko.computed(function () {
+
+ Globals.langChangeTrigger();
+
+ var
+ sSuffix = '',
+ iType = this.type(),
+ sName = this.name()
+ ;
+
+ if (this.isSystemFolder())
+ {
+ switch (iType)
+ {
+ case Enums.FolderType.Inbox:
+ sSuffix = '(' + Utils.i18n('FOLDER_LIST/INBOX_NAME') + ')';
+ break;
+ case Enums.FolderType.SentItems:
+ sSuffix = '(' + Utils.i18n('FOLDER_LIST/SENT_NAME') + ')';
+ break;
+ case Enums.FolderType.Draft:
+ sSuffix = '(' + Utils.i18n('FOLDER_LIST/DRAFTS_NAME') + ')';
+ break;
+ case Enums.FolderType.Spam:
+ sSuffix = '(' + Utils.i18n('FOLDER_LIST/SPAM_NAME') + ')';
+ break;
+ case Enums.FolderType.Trash:
+ sSuffix = '(' + Utils.i18n('FOLDER_LIST/TRASH_NAME') + ')';
+ break;
+ case Enums.FolderType.Archive:
+ sSuffix = '(' + Utils.i18n('FOLDER_LIST/ARCHIVE_NAME') + ')';
+ break;
+ }
+ }
+
+ if ('' !== sSuffix && '(' + sName + ')' === sSuffix || '(inbox)' === sSuffix.toLowerCase())
+ {
+ sSuffix = '';
+ }
+
+ return sSuffix;
+
+ }, this);
+
+ this.collapsed = ko.computed({
+ 'read': function () {
+ return !this.hidden() && this.collapsedPrivate();
+ },
+ 'write': function (mValue) {
+ this.collapsedPrivate(mValue);
+ },
+ 'owner': this
+ });
+
+ this.hasUnreadMessages = ko.computed(function () {
+ return 0 < this.messageCountUnread();
+ }, this);
+
+ this.hasSubScribedUnreadMessagesSubfolders = ko.computed(function () {
+ return !!_.find(this.subFolders(), function (oFolder) {
+ return oFolder.hasUnreadMessages() || oFolder.hasSubScribedUnreadMessagesSubfolders();
+ });
+ }, this);
+
+ return this;
+};
+
+FolderModel.prototype.fullName = '';
+FolderModel.prototype.fullNameRaw = '';
+FolderModel.prototype.fullNameHash = '';
+FolderModel.prototype.delimiter = '';
+FolderModel.prototype.namespace = '';
+FolderModel.prototype.deep = 0;
+FolderModel.prototype.interval = 0;
+
+/**
+ * @return {string}
+ */
+FolderModel.prototype.collapsedCss = function ()
+{
+ return this.hasSubScribedSubfolders() ?
+ (this.collapsed() ? 'icon-right-mini e-collapsed-sign' : 'icon-down-mini e-collapsed-sign') : 'icon-none e-collapsed-sign';
+};
+
+/**
+ * @param {AjaxJsonFolder} oJsonFolder
+ * @return {boolean}
+ */
+FolderModel.prototype.initByJson = function (oJsonFolder)
+{
+ var bResult = false;
+ if (oJsonFolder && 'Object/Folder' === oJsonFolder['@Object'])
+ {
+ this.name(oJsonFolder.Name);
+ this.delimiter = oJsonFolder.Delimiter;
+ this.fullName = oJsonFolder.FullName;
+ this.fullNameRaw = oJsonFolder.FullNameRaw;
+ this.fullNameHash = oJsonFolder.FullNameHash;
+ this.deep = oJsonFolder.FullNameRaw.split(this.delimiter).length - 1;
+ this.selectable = !!oJsonFolder.IsSelectable;
+ this.existen = !!oJsonFolder.IsExists;
+
+ this.subScribed(!!oJsonFolder.IsSubscribed);
+ this.type('INBOX' === this.fullNameRaw ? Enums.FolderType.Inbox : Enums.FolderType.User);
+
+ bResult = true;
+ }
+
+ return bResult;
+};
+
+/**
+ * @return {string}
+ */
+FolderModel.prototype.printableFullName = function ()
+{
+ return this.fullName.split(this.delimiter).join(' / ');
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @param {string} sEmail
+ * @param {boolean=} bCanBeDelete = true
+ * @constructor
+ */
+function AccountModel(sEmail, bCanBeDelete)
+{
+ this.email = sEmail;
+ this.deleteAccess = ko.observable(false);
+ this.canBeDalete = ko.observable(bCanBeDelete);
+}
+
+AccountModel.prototype.email = '';
+
+/**
+ * @return {string}
+ */
+AccountModel.prototype.changeAccountLink = function ()
+{
+ return RL.link().change(this.email);
+};
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @param {string} sId
+ * @param {string} sEmail
+ * @param {boolean=} bCanBeDelete = true
+ * @constructor
+ */
+function IdentityModel(sId, sEmail, bCanBeDelete)
+{
+ this.id = sId;
+ this.email = ko.observable(sEmail);
+ this.name = ko.observable('');
+ this.replyTo = ko.observable('');
+ this.bcc = ko.observable('');
+
+ this.deleteAccess = ko.observable(false);
+ this.canBeDalete = ko.observable(bCanBeDelete);
+}
+
+IdentityModel.prototype.formattedName = function ()
+{
+ var sName = this.name();
+ return '' === sName ? this.email() : sName + ' <' + this.email() + '>';
+};
+
+IdentityModel.prototype.formattedNameForCompose = function ()
+{
+ var sName = this.name();
+ return '' === sName ? this.email() : sName + ' (' + this.email() + ')';
+};
+
+IdentityModel.prototype.formattedNameForEmail = function ()
+{
+ var sName = this.name();
+ return '' === sName ? this.email() : '"' + Utils.quoteName(sName) + '" <' + this.email() + '>';
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ */
+function FilterConditionModel(oKoList)
+{
+ this.parentList = oKoList;
+
+ this.field = ko.observable(Enums.FilterConditionField.From);
+
+ this.fieldOptions = [ // TODO i18n
+ {'id': Enums.FilterConditionField.From, 'name': 'From'},
+ {'id': Enums.FilterConditionField.Recipient, 'name': 'Recipient (To or CC)'},
+ {'id': Enums.FilterConditionField.To, 'name': 'To'},
+ {'id': Enums.FilterConditionField.Subject, 'name': 'Subject'}
+ ];
+
+ this.type = ko.observable(Enums.FilterConditionType.EqualTo);
+
+ this.typeOptions = [ // TODO i18n
+ {'id': Enums.FilterConditionType.EqualTo, 'name': 'Equal To'},
+ {'id': Enums.FilterConditionType.NotEqualTo, 'name': 'Not Equal To'},
+ {'id': Enums.FilterConditionType.Contains, 'name': 'Contains'},
+ {'id': Enums.FilterConditionType.NotContains, 'name': 'Not Contains'}
+ ];
+
+ this.value = ko.observable('');
+
+ this.template = ko.computed(function () {
+
+ var sTemplate = '';
+ switch (this.type())
+ {
+ default:
+ sTemplate = 'SettingsFiltersConditionDefault';
+ break;
+ }
+
+ return sTemplate;
+
+ }, this);
+}
+
+FilterConditionModel.prototype.removeSelf = function ()
+{
+ this.parentList.remove(this);
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ */
+function FilterModel()
+{
+ this.new = ko.observable(true);
+ this.enabled = ko.observable(true);
+
+ this.name = ko.observable('');
+
+ this.conditionsType = ko.observable(Enums.FilterRulesType.And);
+
+ this.conditions = ko.observableArray([]);
+
+ this.conditions.subscribe(function () {
+ Utils.windowResize();
+ });
+
+ // Actions
+ this.actionMarkAsRead = ko.observable(false);
+ this.actionSkipOtherFilters = ko.observable(true);
+ this.actionValue = ko.observable('');
+
+ this.actionType = ko.observable(Enums.FiltersAction.Move);
+ this.actionTypeOptions = [ // TODO i18n
+ {'id': Enums.FiltersAction.None, 'name': 'Action - None'},
+ {'id': Enums.FiltersAction.Move, 'name': 'Action - Move to'},
+// {'id': Enums.FiltersAction.Forward, 'name': 'Action - Forward to'},
+ {'id': Enums.FiltersAction.Discard, 'name': 'Action - Discard'}
+ ];
+
+ this.actionMarkAsReadVisiblity = ko.computed(function () {
+ return -1 < Utils.inArray(this.actionType(), [
+ Enums.FiltersAction.None, Enums.FiltersAction.Forward, Enums.FiltersAction.Move
+ ]);
+ }, this);
+
+ this.actionTemplate = ko.computed(function () {
+
+ var sTemplate = '';
+ switch (this.actionType())
+ {
+ default:
+ case Enums.FiltersAction.Move:
+ sTemplate = 'SettingsFiltersActionValueAsFolders';
+ break;
+ case Enums.FiltersAction.Forward:
+ sTemplate = 'SettingsFiltersActionWithValue';
+ break;
+ case Enums.FiltersAction.None:
+ case Enums.FiltersAction.Discard:
+ sTemplate = 'SettingsFiltersActionNoValue';
+ break;
+ }
+
+ return sTemplate;
+
+ }, this);
+}
+
+FilterModel.prototype.addCondition = function ()
+{
+ this.conditions.push(new FilterConditionModel(this.conditions));
+};
+
+FilterModel.prototype.parse = function (oItem)
+{
+ var bResult = false;
+ if (oItem && 'Object/Filter' === oItem['@Object'])
+ {
+ this.name(Utils.pString(oItem['Name']));
+
+ bResult = true;
+ }
+
+ return bResult;
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @param {string} iIndex
+ * @param {string} sGuID
+ * @param {string} sID
+ * @param {string} sUserID
+ * @param {string} sEmail
+ * @param {boolean} bIsPrivate
+ * @param {string} sArmor
+ * @constructor
+ */
+function OpenPgpKeyModel(iIndex, sGuID, sID, sUserID, sEmail, bIsPrivate, sArmor)
+{
+ this.index = iIndex;
+ this.id = sID;
+ this.guid = sGuID;
+ this.user = sUserID;
+ this.email = sEmail;
+ this.armor = sArmor;
+ this.isPrivate = !!bIsPrivate;
+
+ this.deleteAccess = ko.observable(false);
+}
+
+OpenPgpKeyModel.prototype.index = 0;
+OpenPgpKeyModel.prototype.id = '';
+OpenPgpKeyModel.prototype.guid = '';
+OpenPgpKeyModel.prototype.user = '';
+OpenPgpKeyModel.prototype.email = '';
+OpenPgpKeyModel.prototype.armor = '';
+OpenPgpKeyModel.prototype.isPrivate = false;
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+function PopupsFolderClearViewModel()
+{
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsFolderClear');
+
+ this.selectedFolder = ko.observable(null);
+ this.clearingProcess = ko.observable(false);
+ this.clearingError = ko.observable('');
+
+ this.folderFullNameForClear = ko.computed(function () {
+ var oFolder = this.selectedFolder();
+ return oFolder ? oFolder.printableFullName() : '';
+ }, this);
+
+ this.folderNameForClear = ko.computed(function () {
+ var oFolder = this.selectedFolder();
+ return oFolder ? oFolder.localName() : '';
+ }, this);
+
+ this.dangerDescHtml = ko.computed(function () {
+ return Utils.i18n('POPUPS_CLEAR_FOLDER/DANGER_DESC_HTML_1', {
+ 'FOLDER': this.folderNameForClear()
+ });
+ }, this);
+
+ this.clearCommand = Utils.createCommand(this, function () {
+
+ var
+ self = this,
+ oFolderToClear = this.selectedFolder()
+ ;
+
+ if (oFolderToClear)
+ {
+ RL.data().message(null);
+ RL.data().messageList([]);
+
+ this.clearingProcess(true);
+
+ RL.cache().setFolderHash(oFolderToClear.fullNameRaw, '');
+ RL.remote().folderClear(function (sResult, oData) {
+
+ self.clearingProcess(false);
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ {
+ RL.reloadMessageList(true);
+ self.cancelCommand();
+ }
+ else
+ {
+ if (oData && oData.ErrorCode)
+ {
+ self.clearingError(Utils.getNotification(oData.ErrorCode));
+ }
+ else
+ {
+ self.clearingError(Utils.getNotification(Enums.Notification.MailServerError));
+ }
+ }
+ }, oFolderToClear.fullNameRaw);
+ }
+
+ }, function () {
+
+ var
+ oFolder = this.selectedFolder(),
+ bIsClearing = this.clearingProcess()
+ ;
+
+ return !bIsClearing && null !== oFolder;
+
+ });
+
+ Knoin.constructorEnd(this);
+}
+
+Utils.extendAsViewModel('PopupsFolderClearViewModel', PopupsFolderClearViewModel);
+
+PopupsFolderClearViewModel.prototype.clearPopup = function ()
+{
+ this.clearingProcess(false);
+ this.selectedFolder(null);
+};
+
+PopupsFolderClearViewModel.prototype.onShow = function (oFolder)
+{
+ this.clearPopup();
+ if (oFolder)
+ {
+ this.selectedFolder(oFolder);
+ }
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+function PopupsFolderCreateViewModel()
+{
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsFolderCreate');
+
+ Utils.initOnStartOrLangChange(function () {
+ this.sNoParentText = Utils.i18n('POPUPS_CREATE_FOLDER/SELECT_NO_PARENT');
+ }, this);
+
+ this.folderName = ko.observable('');
+ this.folderName.focused = ko.observable(false);
+
+ this.selectedParentValue = ko.observable(Consts.Values.UnuseOptionValue);
+
+ this.parentFolderSelectList = ko.computed(function () {
+
+ var
+ oData = RL.data(),
+ aTop = [],
+ fDisableCallback = null,
+ fVisibleCallback = null,
+ aList = oData.folderList(),
+ fRenameCallback = function (oItem) {
+ return oItem ? (oItem.isSystemFolder() ? oItem.name() + ' ' + oItem.manageFolderSystemName() : oItem.name()) : '';
+ }
+ ;
+
+ aTop.push(['', this.sNoParentText]);
+
+ if ('' !== oData.namespace)
+ {
+ fDisableCallback = function (oItem)
+ {
+ return oData.namespace !== oItem.fullNameRaw.substr(0, oData.namespace.length);
+ };
+ }
+
+ return RL.folderListOptionsBuilder([], aList, [], aTop, null, fDisableCallback, fVisibleCallback, fRenameCallback);
+
+ }, this);
+
+ // commands
+ this.createFolder = Utils.createCommand(this, function () {
+
+ var
+ oData = RL.data(),
+ sParentFolderName = this.selectedParentValue()
+ ;
+
+ if ('' === sParentFolderName && 1 < oData.namespace.length)
+ {
+ sParentFolderName = oData.namespace.substr(0, oData.namespace.length - 1);
+ }
+
+ oData.foldersCreating(true);
+ RL.remote().folderCreate(function (sResult, oData) {
+
+ RL.data().foldersCreating(false);
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ {
+ RL.folders();
+ }
+ else
+ {
+ RL.data().foldersListError(
+ oData && oData.ErrorCode ? Utils.getNotification(oData.ErrorCode) : Utils.i18n('NOTIFICATIONS/CANT_CREATE_FOLDER'));
+ }
+
+ }, this.folderName(), sParentFolderName);
+
+ this.cancelCommand();
+
+ }, function () {
+ return this.simpleFolderNameValidation(this.folderName());
+ });
+
+ this.defautOptionsAfterRender = Utils.defautOptionsAfterRender;
+
+ Knoin.constructorEnd(this);
+}
+
+Utils.extendAsViewModel('PopupsFolderCreateViewModel', PopupsFolderCreateViewModel);
+
+PopupsFolderCreateViewModel.prototype.sNoParentText = '';
+
+PopupsFolderCreateViewModel.prototype.simpleFolderNameValidation = function (sName)
+{
+ return (/^[^\\\/]+$/g).test(Utils.trim(sName));
+};
+
+PopupsFolderCreateViewModel.prototype.clearPopup = function ()
+{
+ this.folderName('');
+ this.selectedParentValue('');
+ this.folderName.focused(false);
+};
+
+PopupsFolderCreateViewModel.prototype.onShow = function ()
+{
+ this.clearPopup();
+};
+
+PopupsFolderCreateViewModel.prototype.onFocus = function ()
+{
+ this.folderName.focused(true);
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+function PopupsFolderSystemViewModel()
+{
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsFolderSystem');
+
+ Utils.initOnStartOrLangChange(function () {
+ this.sChooseOnText = Utils.i18n('POPUPS_SYSTEM_FOLDERS/SELECT_CHOOSE_ONE');
+ this.sUnuseText = Utils.i18n('POPUPS_SYSTEM_FOLDERS/SELECT_UNUSE_NAME');
+ }, this);
+
+ this.notification = ko.observable('');
+
+ this.folderSelectList = ko.computed(function () {
+ return RL.folderListOptionsBuilder([], RL.data().folderList(), RL.data().folderListSystemNames(), [
+ ['', this.sChooseOnText],
+ [Consts.Values.UnuseOptionValue, this.sUnuseText]
+ ]);
+ }, this);
+
+ var
+ oData = RL.data(),
+ self = this,
+ fSaveSystemFolders = null,
+ fCallback = null
+ ;
+
+ this.sentFolder = oData.sentFolder;
+ this.draftFolder = oData.draftFolder;
+ this.spamFolder = oData.spamFolder;
+ this.trashFolder = oData.trashFolder;
+ this.archiveFolder = oData.archiveFolder;
+
+ fSaveSystemFolders = _.debounce(function () {
+
+ RL.settingsSet('SentFolder', self.sentFolder());
+ RL.settingsSet('DraftFolder', self.draftFolder());
+ RL.settingsSet('SpamFolder', self.spamFolder());
+ RL.settingsSet('TrashFolder', self.trashFolder());
+ RL.settingsSet('ArchiveFolder', self.archiveFolder());
+
+ RL.remote().saveSystemFolders(Utils.emptyFunction, {
+ 'SentFolder': self.sentFolder(),
+ 'DraftFolder': self.draftFolder(),
+ 'SpamFolder': self.spamFolder(),
+ 'TrashFolder': self.trashFolder(),
+ 'ArchiveFolder': self.archiveFolder(),
+ 'NullFolder': 'NullFolder'
+ });
+
+ }, 1000);
+
+ fCallback = function () {
+
+ RL.settingsSet('SentFolder', self.sentFolder());
+ RL.settingsSet('DraftFolder', self.draftFolder());
+ RL.settingsSet('SpamFolder', self.spamFolder());
+ RL.settingsSet('TrashFolder', self.trashFolder());
+ RL.settingsSet('ArchiveFolder', self.archiveFolder());
+
+ fSaveSystemFolders();
+ };
+
+ this.sentFolder.subscribe(fCallback);
+ this.draftFolder.subscribe(fCallback);
+ this.spamFolder.subscribe(fCallback);
+ this.trashFolder.subscribe(fCallback);
+ this.archiveFolder.subscribe(fCallback);
+
+ this.defautOptionsAfterRender = Utils.defautOptionsAfterRender;
+
+ Knoin.constructorEnd(this);
+}
+
+Utils.extendAsViewModel('PopupsFolderSystemViewModel', PopupsFolderSystemViewModel);
+
+PopupsFolderSystemViewModel.prototype.sChooseOnText = '';
+PopupsFolderSystemViewModel.prototype.sUnuseText = '';
+
+/**
+ * @param {number=} iNotificationType = Enums.SetSystemFoldersNotification.None
+ */
+PopupsFolderSystemViewModel.prototype.onShow = function (iNotificationType)
+{
+ var sNotification = '';
+
+ iNotificationType = Utils.isUnd(iNotificationType) ? Enums.SetSystemFoldersNotification.None : iNotificationType;
+
+ switch (iNotificationType)
+ {
+ case Enums.SetSystemFoldersNotification.Sent:
+ sNotification = Utils.i18n('POPUPS_SYSTEM_FOLDERS/NOTIFICATION_SENT');
+ break;
+ case Enums.SetSystemFoldersNotification.Draft:
+ sNotification = Utils.i18n('POPUPS_SYSTEM_FOLDERS/NOTIFICATION_DRAFTS');
+ break;
+ case Enums.SetSystemFoldersNotification.Spam:
+ sNotification = Utils.i18n('POPUPS_SYSTEM_FOLDERS/NOTIFICATION_SPAM');
+ break;
+ case Enums.SetSystemFoldersNotification.Trash:
+ sNotification = Utils.i18n('POPUPS_SYSTEM_FOLDERS/NOTIFICATION_TRASH');
+ break;
+ case Enums.SetSystemFoldersNotification.Archive:
+ sNotification = Utils.i18n('POPUPS_SYSTEM_FOLDERS/NOTIFICATION_ARCHIVE');
+ break;
+ }
+
+ this.notification(sNotification);
+};
+
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+function PopupsComposeViewModel()
+{
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsCompose');
+
+ this.oEditor = null;
+ this.aDraftInfo = null;
+ this.sInReplyTo = '';
+ this.bFromDraft = false;
+ this.bSkipNext = false;
+ this.sReferences = '';
+
+ this.bCapaAdditionalIdentities = RL.capa(Enums.Capa.AdditionalIdentities);
+
+ var
+ self = this,
+ oRainLoopData = RL.data(),
+ fCcAndBccCheckHelper = function (aValue) {
+ if (false === self.showCcAndBcc() && 0 < aValue.length)
+ {
+ self.showCcAndBcc(true);
+ }
+ }
+ ;
+
+ this.capaOpenPGP = oRainLoopData.capaOpenPGP;
+
+ this.resizer = ko.observable(false).extend({'throttle': 50});
+
+ this.identitiesDropdownTrigger = ko.observable(false);
+
+ this.to = ko.observable('');
+ this.to.focusTrigger = ko.observable(false);
+ this.cc = ko.observable('');
+ this.bcc = ko.observable('');
+
+ this.replyTo = ko.observable('');
+ this.subject = ko.observable('');
+ this.isHtml = ko.observable(false);
+
+ this.requestReadReceipt = ko.observable(false);
+
+ this.sendError = ko.observable(false);
+ this.sendSuccessButSaveError = ko.observable(false);
+ this.savedError = ko.observable(false);
+
+ this.savedTime = ko.observable(0);
+ this.savedOrSendingText = ko.observable('');
+
+ this.emptyToError = ko.observable(false);
+ this.attachmentsInProcessError = ko.observable(false);
+ this.showCcAndBcc = ko.observable(false);
+
+ this.cc.subscribe(fCcAndBccCheckHelper, this);
+ this.bcc.subscribe(fCcAndBccCheckHelper, this);
+
+ this.draftFolder = ko.observable('');
+ this.draftUid = ko.observable('');
+ this.sending = ko.observable(false);
+ this.saving = ko.observable(false);
+ this.attachments = ko.observableArray([]);
+
+ this.attachmentsInProcess = this.attachments.filter(function (oItem) {
+ return oItem && '' === oItem.tempName();
+ });
+
+ this.attachmentsInReady = this.attachments.filter(function (oItem) {
+ return oItem && '' !== oItem.tempName();
+ });
+
+ this.attachments.subscribe(function () {
+ this.triggerForResize();
+ }, this);
+
+ this.isDraftFolderMessage = ko.computed(function () {
+ return '' !== this.draftFolder() && '' !== this.draftUid();
+ }, this);
+
+ this.composeUploaderButton = ko.observable(null);
+ this.composeUploaderDropPlace = ko.observable(null);
+ this.dragAndDropEnabled = ko.observable(false);
+ this.dragAndDropOver = ko.observable(false).extend({'throttle': 1});
+ this.dragAndDropVisible = ko.observable(false).extend({'throttle': 1});
+ this.attacheMultipleAllowed = ko.observable(false);
+ this.addAttachmentEnabled = ko.observable(false);
+
+ this.composeEditorArea = ko.observable(null);
+
+ this.identities = RL.data().identities;
+ this.defaultIdentityID = RL.data().defaultIdentityID;
+ this.currentIdentityID = ko.observable('');
+
+ this.currentIdentityString = ko.observable('');
+ this.currentIdentityResultEmail = ko.observable('');
+
+ this.identitiesOptions = ko.computed(function () {
+
+ var aList = [{
+ 'optValue': oRainLoopData.accountEmail(),
+ 'optText': this.formattedFrom(false)
+ }];
+
+ _.each(oRainLoopData.identities(), function (oItem) {
+ aList.push({
+ 'optValue': oItem.id,
+ 'optText': oItem.formattedNameForCompose()
+ });
+ });
+
+ return aList;
+
+ }, this);
+
+ ko.computed(function () {
+
+ var
+ sResult = '',
+ sResultEmail = '',
+ oItem = null,
+ aList = this.identities(),
+ sID = this.currentIdentityID()
+ ;
+
+ if (this.bCapaAdditionalIdentities && sID && sID !== RL.data().accountEmail())
+ {
+ oItem = _.find(aList, function (oItem) {
+ return oItem && sID === oItem['id'];
+ });
+
+ sResult = oItem ? oItem.formattedNameForCompose() : '';
+ sResultEmail = oItem ? oItem.formattedNameForEmail() : '';
+
+ if ('' === sResult && aList[0])
+ {
+ this.currentIdentityID(aList[0]['id']);
+ return '';
+ }
+ }
+
+ if ('' === sResult)
+ {
+ sResult = this.formattedFrom(false);
+ sResultEmail = this.formattedFrom(true);
+ }
+
+ this.currentIdentityString(sResult);
+ this.currentIdentityResultEmail(sResultEmail);
+
+ return sResult;
+
+ }, this);
+
+ this.to.subscribe(function (sValue) {
+ if (this.emptyToError() && 0 < sValue.length)
+ {
+ this.emptyToError(false);
+ }
+ }, this);
+
+ this.attachmentsInProcess.subscribe(function (aValue) {
+ if (this.attachmentsInProcessError() && Utils.isArray(aValue) && 0 === aValue.length)
+ {
+ this.attachmentsInProcessError(false);
+ }
+ }, this);
+
+ this.editorResizeThrottle = _.throttle(_.bind(this.editorResize, this), 100);
+
+ this.resizer.subscribe(function () {
+ this.editorResizeThrottle();
+ }, this);
+
+ this.canBeSendedOrSaved = ko.computed(function () {
+ return !this.sending() && !this.saving();
+ }, this);
+
+ this.deleteCommand = Utils.createCommand(this, function () {
+
+ RL.deleteMessagesFromFolderWithoutCheck(this.draftFolder(), [this.draftUid()]);
+ kn.hideScreenPopup(PopupsComposeViewModel);
+
+ }, function () {
+ return this.isDraftFolderMessage();
+ });
+
+ this.sendMessageResponse = _.bind(this.sendMessageResponse, this);
+ this.saveMessageResponse = _.bind(this.saveMessageResponse, this);
+
+ this.sendCommand = Utils.createCommand(this, function () {
+ var
+ sTo = Utils.trim(this.to()),
+ sSentFolder = RL.data().sentFolder(),
+ aFlagsCache = []
+ ;
+
+ if (0 < this.attachmentsInProcess().length)
+ {
+ this.attachmentsInProcessError(true);
+ }
+ else if (0 === sTo.length)
+ {
+ this.emptyToError(true);
+ }
+ else
+ {
+ if (RL.data().replySameFolder())
+ {
+ if (Utils.isArray(this.aDraftInfo) && 3 === this.aDraftInfo.length && Utils.isNormal(this.aDraftInfo[2]) && 0 < this.aDraftInfo[2].length)
+ {
+ sSentFolder = this.aDraftInfo[2];
+ }
+ }
+
+ if ('' === sSentFolder)
+ {
+ kn.showScreenPopup(PopupsFolderSystemViewModel, [Enums.SetSystemFoldersNotification.Sent]);
+ }
+ else
+ {
+ this.sendError(false);
+ this.sending(true);
+
+ if (Utils.isArray(this.aDraftInfo) && 3 === this.aDraftInfo.length)
+ {
+ aFlagsCache = RL.cache().getMessageFlagsFromCache(this.aDraftInfo[2], this.aDraftInfo[1]);
+ if (aFlagsCache)
+ {
+ if ('forward' === this.aDraftInfo[0])
+ {
+ aFlagsCache[3] = true;
+ }
+ else
+ {
+ aFlagsCache[2] = true;
+ }
+
+ RL.cache().setMessageFlagsToCache(this.aDraftInfo[2], this.aDraftInfo[1], aFlagsCache);
+ RL.reloadFlagsCurrentMessageListAndMessageFromCache();
+ RL.cache().setFolderHash(this.aDraftInfo[2], '');
+ }
+ }
+
+ sSentFolder = Consts.Values.UnuseOptionValue === sSentFolder ? '' : sSentFolder;
+
+ RL.cache().setFolderHash(this.draftFolder(), '');
+ RL.cache().setFolderHash(sSentFolder, '');
+
+ RL.remote().sendMessage(
+ this.sendMessageResponse,
+ this.draftFolder(),
+ this.draftUid(),
+ sSentFolder,
+ this.currentIdentityResultEmail(),
+ sTo,
+ this.cc(),
+ this.bcc(),
+ this.subject(),
+ this.oEditor ? this.oEditor.isHtml() : false,
+ this.oEditor ? this.oEditor.getData(true) : '',
+ this.prepearAttachmentsForSendOrSave(),
+ this.aDraftInfo,
+ this.sInReplyTo,
+ this.sReferences,
+ this.requestReadReceipt()
+ );
+ }
+ }
+ }, this.canBeSendedOrSaved);
+
+ this.saveCommand = Utils.createCommand(this, function () {
+
+ if (RL.data().draftFolderNotEnabled())
+ {
+ kn.showScreenPopup(PopupsFolderSystemViewModel, [Enums.SetSystemFoldersNotification.Draft]);
+ }
+ else
+ {
+ this.savedError(false);
+ this.saving(true);
+
+ this.bSkipNext = true;
+
+ RL.cache().setFolderHash(RL.data().draftFolder(), '');
+
+ RL.remote().saveMessage(
+ this.saveMessageResponse,
+ this.draftFolder(),
+ this.draftUid(),
+ RL.data().draftFolder(),
+ this.currentIdentityResultEmail(),
+ this.to(),
+ this.cc(),
+ this.bcc(),
+ this.subject(),
+ this.oEditor ? this.oEditor.isHtml() : false,
+ this.oEditor ? this.oEditor.getData(true) : '',
+ this.prepearAttachmentsForSendOrSave(),
+ this.aDraftInfo,
+ this.sInReplyTo,
+ this.sReferences
+ );
+ }
+
+ }, this.canBeSendedOrSaved);
+
+ RL.sub('interval.1m', function () {
+ if (this.modalVisibility() && !RL.data().draftFolderNotEnabled() && !this.isEmptyForm(false) &&
+ !this.bSkipNext && !this.saving() && !this.sending() && !this.savedError())
+ {
+ this.bSkipNext = false;
+ this.saveCommand();
+ }
+ }, this);
+
+ this.showCcAndBcc.subscribe(function () {
+ this.triggerForResize();
+ }, this);
+
+ this.dropboxEnabled = ko.observable(!!RL.settingsGet('DropboxApiKey'));
+
+ this.dropboxCommand = Utils.createCommand(this, function () {
+
+ if (window.Dropbox)
+ {
+ window.Dropbox.choose({
+ //'iframe': true,
+ 'success': function(aFiles) {
+
+ if (aFiles && aFiles[0] && aFiles[0]['link'])
+ {
+ self.addDropboxAttachment(aFiles[0]);
+ }
+ },
+ 'linkType': "direct",
+ 'multiselect': false
+ });
+ }
+
+ return true;
+
+ }, function () {
+ return this.dropboxEnabled();
+ });
+
+ this.driveEnabled = ko.observable(Globals.bXMLHttpRequestSupported &&
+ !!RL.settingsGet('GoogleClientID') && !!RL.settingsGet('GoogleApiKey'));
+
+ this.driveVisible = ko.observable(false);
+
+ this.driveCommand = Utils.createCommand(this, function () {
+
+ this.driveOpenPopup();
+ return true;
+
+ }, function () {
+ return this.driveEnabled();
+ });
+
+ this.driveCallback = _.bind(this.driveCallback, this);
+
+ this.bDisabeCloseOnEsc = true;
+ this.sDefaultKeyScope = Enums.KeyState.Compose;
+
+ this.tryToClosePopup = _.debounce(_.bind(this.tryToClosePopup, this), 200);
+
+ Knoin.constructorEnd(this);
+}
+
+Utils.extendAsViewModel('PopupsComposeViewModel', PopupsComposeViewModel);
+
+PopupsComposeViewModel.prototype.openOpenPgpPopup = function ()
+{
+ if (this.capaOpenPGP() && this.oEditor && !this.oEditor.isHtml())
+ {
+ var self = this;
+ kn.showScreenPopup(PopupsComposeOpenPgpViewModel, [
+ function (sResult) {
+ self.editor(function (oEditor) {
+ oEditor.setPlain(sResult);
+ });
+ },
+ this.oEditor.getData(),
+ this.currentIdentityResultEmail(),
+ this.to(),
+ this.cc(),
+ this.bcc()
+ ]);
+ }
+};
+
+PopupsComposeViewModel.prototype.reloadDraftFolder = function ()
+{
+ var sDraftFolder = RL.data().draftFolder();
+ if ('' !== sDraftFolder)
+ {
+ RL.cache().setFolderHash(sDraftFolder, '');
+ if (RL.data().currentFolderFullNameRaw() === sDraftFolder)
+ {
+ RL.reloadMessageList(true);
+ }
+ else
+ {
+ RL.folderInformation(sDraftFolder);
+ }
+ }
+};
+
+PopupsComposeViewModel.prototype.findIdentityIdByMessage = function (sComposeType, oMessage)
+{
+ var
+ oIDs = {},
+ sResult = '',
+ fFindHelper = function (oItem) {
+ if (oItem && oItem.email && oIDs[oItem.email])
+ {
+ sResult = oIDs[oItem.email];
+ return true;
+ }
+
+ return false;
+ }
+ ;
+
+ if (this.bCapaAdditionalIdentities)
+ {
+ _.each(this.identities(), function (oItem) {
+ oIDs[oItem.email()] = oItem['id'];
+ });
+ }
+
+ oIDs[RL.data().accountEmail()] = RL.data().accountEmail();
+
+ if (oMessage)
+ {
+ switch (sComposeType)
+ {
+ case Enums.ComposeType.Empty:
+ break;
+ case Enums.ComposeType.Reply:
+ case Enums.ComposeType.ReplyAll:
+ case Enums.ComposeType.Forward:
+ case Enums.ComposeType.ForwardAsAttachment:
+ _.find(_.union(oMessage.to, oMessage.cc, oMessage.bcc, oMessage.deliveredTo), fFindHelper);
+ break;
+ case Enums.ComposeType.Draft:
+ _.find(_.union(oMessage.from, oMessage.replyTo), fFindHelper);
+ break;
+ }
+ }
+
+ if ('' === sResult)
+ {
+ sResult = this.defaultIdentityID();
+ }
+
+ if ('' === sResult)
+ {
+ sResult = RL.data().accountEmail();
+ }
+
+ return sResult;
+};
+
+PopupsComposeViewModel.prototype.selectIdentity = function (oIdentity)
+{
+ if (oIdentity)
+ {
+ this.currentIdentityID(oIdentity.optValue);
+ }
+};
+
+/**
+ *
+ * @param {boolean=} bHeaderResult = false
+ * @returns {string}
+ */
+PopupsComposeViewModel.prototype.formattedFrom = function (bHeaderResult)
+{
+ var
+ sDisplayName = RL.data().displayName(),
+ sEmail = RL.data().accountEmail()
+ ;
+
+ return '' === sDisplayName ? sEmail :
+ ((Utils.isUnd(bHeaderResult) ? false : !!bHeaderResult) ?
+ '"' + Utils.quoteName(sDisplayName) + '" <' + sEmail + '>' :
+ sDisplayName + ' (' + sEmail + ')')
+ ;
+};
+
+PopupsComposeViewModel.prototype.sendMessageResponse = function (sResult, oData)
+{
+ var
+ bResult = false,
+ sMessage = ''
+ ;
+
+ this.sending(false);
+
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ {
+ bResult = true;
+ if (this.modalVisibility())
+ {
+ Utils.delegateRun(this, 'closeCommand');
+ }
+ }
+
+ if (this.modalVisibility() && !bResult)
+ {
+ if (oData && Enums.Notification.CantSaveMessage === oData.ErrorCode)
+ {
+ this.sendSuccessButSaveError(true);
+ window.alert(Utils.trim(Utils.i18n('COMPOSE/SAVED_ERROR_ON_SEND')));
+ }
+ else
+ {
+ sMessage = Utils.getNotification(oData && oData.ErrorCode ? oData.ErrorCode : Enums.Notification.CantSendMessage,
+ oData && oData.ErrorMessage ? oData.ErrorMessage : '');
+
+ this.sendError(true);
+ window.alert(sMessage || Utils.getNotification(Enums.Notification.CantSendMessage));
+ }
+ }
+
+ this.reloadDraftFolder();
+};
+
+PopupsComposeViewModel.prototype.saveMessageResponse = function (sResult, oData)
+{
+ var
+ bResult = false,
+ oMessage = null
+ ;
+
+ this.saving(false);
+
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ {
+ if (oData.Result.NewFolder && oData.Result.NewUid)
+ {
+ if (this.bFromDraft)
+ {
+ oMessage = RL.data().message();
+ if (oMessage && this.draftFolder() === oMessage.folderFullNameRaw && this.draftUid() === oMessage.uid)
+ {
+ RL.data().message(null);
+ }
+ }
+
+ this.draftFolder(oData.Result.NewFolder);
+ this.draftUid(oData.Result.NewUid);
+
+ if (this.modalVisibility())
+ {
+ this.savedTime(Math.round((new window.Date()).getTime() / 1000));
+
+ this.savedOrSendingText(
+ 0 < this.savedTime() ? Utils.i18n('COMPOSE/SAVED_TIME', {
+ 'TIME': moment.unix(this.savedTime() - 1).format('LT')
+ }) : ''
+ );
+
+ bResult = true;
+
+ if (this.bFromDraft)
+ {
+ RL.cache().setFolderHash(this.draftFolder(), '');
+ }
+ }
+ }
+ }
+
+ if (!this.modalVisibility() && !bResult)
+ {
+ this.savedError(true);
+ this.savedOrSendingText(Utils.getNotification(Enums.Notification.CantSaveMessage));
+ }
+
+ this.reloadDraftFolder();
+};
+
+PopupsComposeViewModel.prototype.onHide = function ()
+{
+ this.reset();
+ kn.routeOn();
+};
+
+/**
+ * @param {string} sSignature
+ * @param {string=} sFrom
+ * @param {string=} sData
+ * @param {string=} sComposeType
+ * @return {string}
+ */
+PopupsComposeViewModel.prototype.convertSignature = function (sSignature, sFrom, sData, sComposeType)
+{
+ var bHtml = false, bData = false;
+ if ('' !== sSignature)
+ {
+ if (':HTML:' === sSignature.substr(0, 6))
+ {
+ bHtml = true;
+ sSignature = sSignature.substr(6);
+ }
+
+ sSignature = sSignature.replace(/[\r]/, '');
+
+ sFrom = Utils.pString(sFrom);
+ if ('' !== sFrom)
+ {
+ sSignature = sSignature.replace(/{{FROM}}/, sFrom);
+ }
+
+ sSignature = sSignature.replace(/[\s]{1,2}{{FROM}}/, '{{FROM}}');
+
+ sSignature = sSignature.replace(/{{FROM}}/, '');
+ sSignature = sSignature.replace(/{{DATE}}/, moment().format('llll'));
+
+ if (sData && Enums.ComposeType.Empty === sComposeType &&
+ -1 < sSignature.indexOf('{{DATA}}'))
+ {
+ bData = true;
+ sSignature = sSignature.replace('{{DATA}}', sData);
+ }
+
+ sSignature = sSignature.replace(/{{DATA}}/, '');
+
+ if (!bHtml)
+ {
+ sSignature = Utils.convertPlainTextToHtml(sSignature);
+ }
+ }
+
+ if (sData && !bData)
+ {
+ switch (sComposeType)
+ {
+ case Enums.ComposeType.Empty:
+ sSignature = sData + '
' + sSignature;
+ break;
+ default:
+ sSignature = sSignature + '
' + sData;
+ break;
+ }
+ }
+
+ return sSignature;
+};
+
+PopupsComposeViewModel.prototype.editor = function (fOnInit)
+{
+ if (fOnInit)
+ {
+ var self = this;
+ if (!this.oEditor && this.composeEditorArea())
+ {
+ _.delay(function () {
+ self.oEditor = new NewHtmlEditorWrapper(self.composeEditorArea(), null, function () {
+ fOnInit(self.oEditor);
+ }, function (bHtml) {
+ self.isHtml(!!bHtml);
+ });
+ }, 300);
+ }
+ else if (this.oEditor)
+ {
+ fOnInit(this.oEditor);
+ }
+ }
+};
+
+/**
+ * @param {string=} sType = Enums.ComposeType.Empty
+ * @param {?MessageModel|Array=} oMessageOrArray = null
+ * @param {Array=} aToEmails = null
+ * @param {string=} sCustomSubject = null
+ * @param {string=} sCustomPlainText = null
+ */
+PopupsComposeViewModel.prototype.onShow = function (sType, oMessageOrArray, aToEmails, sCustomSubject, sCustomPlainText)
+{
+ kn.routeOff();
+
+ var
+ self = this,
+ sFrom = '',
+ sTo = '',
+ sCc = '',
+ sDate = '',
+ sSubject = '',
+ oText = null,
+ oSubText = null,
+ sText = '',
+ sReplyTitle = '',
+ aResplyAllParts = [],
+ oExcludeEmail = {},
+ mEmail = RL.data().accountEmail(),
+ sSignature = RL.data().signature(),
+ bSignatureToAll = RL.data().signatureToAll(),
+ aDownloads = [],
+ aDraftInfo = null,
+ oMessage = null,
+ sComposeType = sType || Enums.ComposeType.Empty,
+ fEmailArrayToStringLineHelper = function (aList, bFriendly) {
+
+ var
+ iIndex = 0,
+ iLen = aList.length,
+ aResult = []
+ ;
+
+ for (; iIndex < iLen; iIndex++)
+ {
+ aResult.push(aList[iIndex].toLine(!!bFriendly));
+ }
+
+ return aResult.join(', ');
+ }
+ ;
+
+ oMessageOrArray = oMessageOrArray || null;
+ if (oMessageOrArray && Utils.isNormal(oMessageOrArray))
+ {
+ oMessage = Utils.isArray(oMessageOrArray) && 1 === oMessageOrArray.length ? oMessageOrArray[0] :
+ (!Utils.isArray(oMessageOrArray) ? oMessageOrArray : null);
+ }
+
+ if (null !== mEmail)
+ {
+ oExcludeEmail[mEmail] = true;
+ }
+
+ this.currentIdentityID(this.findIdentityIdByMessage(sComposeType, oMessage));
+ this.reset();
+
+ if (Utils.isNonEmptyArray(aToEmails))
+ {
+ this.to(fEmailArrayToStringLineHelper(aToEmails));
+ }
+
+ if ('' !== sComposeType && oMessage)
+ {
+ sDate = oMessage.fullFormatDateValue();
+ sSubject = oMessage.subject();
+ aDraftInfo = oMessage.aDraftInfo;
+
+ oText = $(oMessage.body).clone();
+ Utils.removeBlockquoteSwitcher(oText);
+
+ oSubText = oText.find('[data-html-editor-font-wrapper=true]');
+ sText = oSubText && oSubText[0] ? oSubText.html() : oText.html();
+
+ switch (sComposeType)
+ {
+ case Enums.ComposeType.Empty:
+ break;
+
+ case Enums.ComposeType.Reply:
+ this.to(fEmailArrayToStringLineHelper(oMessage.replyEmails(oExcludeEmail)));
+ this.subject(Utils.replySubjectAdd('Re', sSubject));
+ this.prepearMessageAttachments(oMessage, sComposeType);
+ this.aDraftInfo = ['reply', oMessage.uid, oMessage.folderFullNameRaw];
+ this.sInReplyTo = oMessage.sMessageId;
+ this.sReferences = Utils.trim(this.sInReplyTo + ' ' + oMessage.sReferences);
+ break;
+
+ case Enums.ComposeType.ReplyAll:
+ aResplyAllParts = oMessage.replyAllEmails(oExcludeEmail);
+ this.to(fEmailArrayToStringLineHelper(aResplyAllParts[0]));
+ this.cc(fEmailArrayToStringLineHelper(aResplyAllParts[1]));
+ this.subject(Utils.replySubjectAdd('Re', sSubject));
+ this.prepearMessageAttachments(oMessage, sComposeType);
+ this.aDraftInfo = ['reply', oMessage.uid, oMessage.folderFullNameRaw];
+ this.sInReplyTo = oMessage.sMessageId;
+ this.sReferences = Utils.trim(this.sInReplyTo + ' ' + oMessage.references());
+ break;
+
+ case Enums.ComposeType.Forward:
+ this.subject(Utils.replySubjectAdd('Fwd', sSubject));
+ this.prepearMessageAttachments(oMessage, sComposeType);
+ this.aDraftInfo = ['forward', oMessage.uid, oMessage.folderFullNameRaw];
+ this.sInReplyTo = oMessage.sMessageId;
+ this.sReferences = Utils.trim(this.sInReplyTo + ' ' + oMessage.sReferences);
+ break;
+
+ case Enums.ComposeType.ForwardAsAttachment:
+ this.subject(Utils.replySubjectAdd('Fwd', sSubject));
+ this.prepearMessageAttachments(oMessage, sComposeType);
+ this.aDraftInfo = ['forward', oMessage.uid, oMessage.folderFullNameRaw];
+ this.sInReplyTo = oMessage.sMessageId;
+ this.sReferences = Utils.trim(this.sInReplyTo + ' ' + oMessage.sReferences);
+ break;
+
+ case Enums.ComposeType.Draft:
+ this.to(fEmailArrayToStringLineHelper(oMessage.to));
+ this.cc(fEmailArrayToStringLineHelper(oMessage.cc));
+ this.bcc(fEmailArrayToStringLineHelper(oMessage.bcc));
+
+ this.bFromDraft = true;
+
+ this.draftFolder(oMessage.folderFullNameRaw);
+ this.draftUid(oMessage.uid);
+
+ this.subject(sSubject);
+ this.prepearMessageAttachments(oMessage, sComposeType);
+
+ this.aDraftInfo = Utils.isNonEmptyArray(aDraftInfo) && 3 === aDraftInfo.length ? aDraftInfo : null;
+ this.sInReplyTo = oMessage.sInReplyTo;
+ this.sReferences = oMessage.sReferences;
+ break;
+
+ case Enums.ComposeType.EditAsNew:
+ this.to(fEmailArrayToStringLineHelper(oMessage.to));
+ this.cc(fEmailArrayToStringLineHelper(oMessage.cc));
+ this.bcc(fEmailArrayToStringLineHelper(oMessage.bcc));
+
+ this.subject(sSubject);
+ this.prepearMessageAttachments(oMessage, sComposeType);
+
+ this.aDraftInfo = Utils.isNonEmptyArray(aDraftInfo) && 3 === aDraftInfo.length ? aDraftInfo : null;
+ this.sInReplyTo = oMessage.sInReplyTo;
+ this.sReferences = oMessage.sReferences;
+ break;
+ }
+
+ switch (sComposeType)
+ {
+ case Enums.ComposeType.Reply:
+ case Enums.ComposeType.ReplyAll:
+ sFrom = oMessage.fromToLine(false, true);
+ sReplyTitle = Utils.i18n('COMPOSE/REPLY_MESSAGE_TITLE', {
+ 'DATETIME': sDate,
+ 'EMAIL': sFrom
+ });
+
+ sText = '
' + sReplyTitle + ':' +
+ '' + sText + '
';
+
+ break;
+
+ case Enums.ComposeType.Forward:
+ sFrom = oMessage.fromToLine(false, true);
+ sTo = oMessage.toToLine(false, true);
+ sCc = oMessage.ccToLine(false, true);
+ sText = '
' + Utils.i18n('COMPOSE/FORWARD_MESSAGE_TOP_TITLE') +
+ '
' + Utils.i18n('COMPOSE/FORWARD_MESSAGE_TOP_FROM') + ': ' + sFrom +
+ '
' + Utils.i18n('COMPOSE/FORWARD_MESSAGE_TOP_TO') + ': ' + sTo +
+ (0 < sCc.length ? '
' + Utils.i18n('COMPOSE/FORWARD_MESSAGE_TOP_CC') + ': ' + sCc : '') +
+ '
' + Utils.i18n('COMPOSE/FORWARD_MESSAGE_TOP_SENT') + ': ' + Utils.encodeHtml(sDate) +
+ '
' + Utils.i18n('COMPOSE/FORWARD_MESSAGE_TOP_SUBJECT') + ': ' + Utils.encodeHtml(sSubject) +
+ '
' + sText;
+ break;
+ case Enums.ComposeType.ForwardAsAttachment:
+ sText = '';
+ break;
+ }
+
+ if (bSignatureToAll && '' !== sSignature &&
+ Enums.ComposeType.EditAsNew !== sComposeType && Enums.ComposeType.Draft !== sComposeType)
+ {
+ sText = this.convertSignature(sSignature, fEmailArrayToStringLineHelper(oMessage.from, true), sText, sComposeType);
+ }
+
+ this.editor(function (oEditor) {
+ oEditor.setHtml(sText, false);
+ if (!oMessage.isHtml())
+ {
+ oEditor.modeToggle(false);
+ }
+ });
+ }
+ else if (Enums.ComposeType.Empty === sComposeType)
+ {
+ this.subject(Utils.isNormal(sCustomSubject) ? '' + sCustomSubject : '');
+
+ sText = Utils.isNormal(sCustomPlainText) ? '' + sCustomPlainText : '';
+ if (bSignatureToAll && '' !== sSignature)
+ {
+ sText = this.convertSignature(sSignature, '',
+ Utils.convertPlainTextToHtml(sText), sComposeType);
+ }
+
+ this.editor(function (oEditor) {
+ oEditor.setHtml(sText, false);
+ if (Enums.EditorDefaultType.Html !== RL.data().editorDefaultType())
+ {
+ oEditor.modeToggle(false);
+ }
+ });
+ }
+ else if (Utils.isNonEmptyArray(oMessageOrArray))
+ {
+ _.each(oMessageOrArray, function (oMessage) {
+ self.addMessageAsAttachment(oMessage);
+ });
+ }
+
+ aDownloads = this.getAttachmentsDownloadsForUpload();
+ if (Utils.isNonEmptyArray(aDownloads))
+ {
+ RL.remote().messageUploadAttachments(function (sResult, oData) {
+
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ {
+ var
+ oAttachment = null,
+ sTempName = ''
+ ;
+
+ if (!self.viewModelVisibility())
+ {
+ for (sTempName in oData.Result)
+ {
+ if (oData.Result.hasOwnProperty(sTempName))
+ {
+ oAttachment = self.getAttachmentById(oData.Result[sTempName]);
+ if (oAttachment)
+ {
+ oAttachment.tempName(sTempName);
+ }
+ }
+ }
+ }
+ }
+ else
+ {
+ self.setMessageAttachmentFailedDowbloadText();
+ }
+
+ }, aDownloads);
+ }
+
+ this.triggerForResize();
+};
+
+PopupsComposeViewModel.prototype.onFocus = function ()
+{
+ if ('' === this.to())
+ {
+ this.to.focusTrigger(!this.to.focusTrigger());
+ }
+ else if (this.oEditor)
+ {
+ this.oEditor.focus();
+ }
+
+ this.triggerForResize();
+};
+
+PopupsComposeViewModel.prototype.editorResize = function ()
+{
+ if (this.oEditor)
+ {
+ this.oEditor.resize();
+ }
+};
+
+PopupsComposeViewModel.prototype.tryToClosePopup = function ()
+{
+ var self = this;
+ if (!kn.isPopupVisible(PopupsAskViewModel))
+ {
+ kn.showScreenPopup(PopupsAskViewModel, [Utils.i18n('POPUPS_ASK/DESC_WANT_CLOSE_THIS_WINDOW'), function () {
+ if (self.modalVisibility())
+ {
+ Utils.delegateRun(self, 'closeCommand');
+ }
+ }]);
+ }
+};
+
+PopupsComposeViewModel.prototype.onBuild = function ()
+{
+ this.initUploader();
+
+ var
+ self = this,
+ oScript = null
+ ;
+
+ key('ctrl+q, command+q', Enums.KeyState.Compose, function () {
+ self.identitiesDropdownTrigger(true);
+ return false;
+ });
+
+ key('ctrl+s, command+s', Enums.KeyState.Compose, function () {
+ self.saveCommand();
+ return false;
+ });
+
+ key('ctrl+enter, command+enter', Enums.KeyState.Compose, function () {
+ self.sendCommand();
+ return false;
+ });
+
+ key('esc', Enums.KeyState.Compose, function () {
+ if (self.modalVisibility())
+ {
+ self.tryToClosePopup();
+ }
+ return false;
+ });
+
+ $window.on('resize', function () {
+ self.triggerForResize();
+ });
+
+ if (this.dropboxEnabled())
+ {
+ oScript = document.createElement('script');
+ oScript.type = 'text/javascript';
+ oScript.src = 'https://www.dropbox.com/static/api/1/dropins.js';
+ $(oScript).attr('id', 'dropboxjs').attr('data-app-key', RL.settingsGet('DropboxApiKey'));
+
+ document.body.appendChild(oScript);
+ }
+
+ if (this.driveEnabled())
+ {
+ $.getScript('https://apis.google.com/js/api.js', function () {
+ if (window.gapi)
+ {
+ self.driveVisible(true);
+ }
+ });
+ }
+};
+
+PopupsComposeViewModel.prototype.driveCallback = function (sAccessToken, oData)
+{
+ if (oData && window.XMLHttpRequest && window.google &&
+ oData[window.google.picker.Response.ACTION] === window.google.picker.Action.PICKED &&
+ oData[window.google.picker.Response.DOCUMENTS] && oData[window.google.picker.Response.DOCUMENTS][0] &&
+ oData[window.google.picker.Response.DOCUMENTS][0]['id'])
+ {
+ var
+ self = this,
+ oRequest = new window.XMLHttpRequest()
+ ;
+
+ oRequest.open('GET', 'https://www.googleapis.com/drive/v2/files/' + oData[window.google.picker.Response.DOCUMENTS][0]['id']);
+ oRequest.setRequestHeader('Authorization', 'Bearer ' + sAccessToken);
+ oRequest.addEventListener('load', function() {
+ if (oRequest && oRequest.responseText)
+ {
+ var oItem = JSON.parse(oRequest.responseText), fExport = function (oItem, sMimeType, sExt) {
+ if (oItem && oItem['exportLinks'])
+ {
+ if (oItem['exportLinks'][sMimeType])
+ {
+ oItem['downloadUrl'] = oItem['exportLinks'][sMimeType];
+ oItem['title'] = oItem['title'] + '.' + sExt;
+ oItem['mimeType'] = sMimeType;
+ }
+ else if (oItem['exportLinks']['application/pdf'])
+ {
+ oItem['downloadUrl'] = oItem['exportLinks']['application/pdf'];
+ oItem['title'] = oItem['title'] + '.pdf';
+ oItem['mimeType'] = 'application/pdf';
+ }
+ }
+ };
+
+ if (oItem && !oItem['downloadUrl'] && oItem['mimeType'] && oItem['exportLinks'])
+ {
+ switch (oItem['mimeType'].toString().toLowerCase())
+ {
+ case 'application/vnd.google-apps.document':
+ fExport(oItem, 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'docx');
+ break;
+ case 'application/vnd.google-apps.spreadsheet':
+ fExport(oItem, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'xlsx');
+ break;
+ case 'application/vnd.google-apps.drawing':
+ fExport(oItem, 'image/png', 'png');
+ break;
+ case 'application/vnd.google-apps.presentation':
+ fExport(oItem, 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'pptx');
+ break;
+ default:
+ fExport(oItem, 'application/pdf', 'pdf');
+ break;
+ }
+ }
+
+ if (oItem && oItem['downloadUrl'])
+ {
+ self.addDriveAttachment(oItem, sAccessToken);
+ }
+ }
+ });
+
+ oRequest.send();
+ }
+};
+
+PopupsComposeViewModel.prototype.driveCreatePiker = function (oOauthToken)
+{
+ if (window.gapi && oOauthToken && oOauthToken.access_token)
+ {
+ var self = this;
+
+ window.gapi.load('picker', {'callback': function () {
+
+ if (window.google && window.google.picker)
+ {
+ var drivePicker = new window.google.picker.PickerBuilder()
+ .addView(
+ new window.google.picker.DocsView()
+ .setIncludeFolders(true)
+ )
+ .setAppId(RL.settingsGet('GoogleClientID'))
+ .setOAuthToken(oOauthToken.access_token)
+ .setCallback(_.bind(self.driveCallback, self, oOauthToken.access_token))
+ .enableFeature(window.google.picker.Feature.NAV_HIDDEN)
+ .build()
+ ;
+
+ drivePicker.setVisible(true);
+ }
+ }});
+ }
+};
+
+PopupsComposeViewModel.prototype.driveOpenPopup = function ()
+{
+ if (window.gapi)
+ {
+ var self = this;
+
+ window.gapi.load('auth', {'callback': function () {
+
+ var oAuthToken = window.gapi.auth.getToken();
+ if (!oAuthToken)
+ {
+ window.gapi.auth.authorize({
+ 'client_id': RL.settingsGet('GoogleClientID'),
+ 'scope': 'https://www.googleapis.com/auth/drive.readonly',
+ 'immediate': true
+ }, function (oAuthResult) {
+ if (oAuthResult && !oAuthResult.error)
+ {
+ var oAuthToken = window.gapi.auth.getToken();
+ if (oAuthToken)
+ {
+ self.driveCreatePiker(oAuthToken);
+ }
+ }
+ else
+ {
+ window.gapi.auth.authorize({
+ 'client_id': RL.settingsGet('GoogleClientID'),
+ 'scope': 'https://www.googleapis.com/auth/drive.readonly',
+ 'immediate': false
+ }, function (oAuthResult) {
+ if (oAuthResult && !oAuthResult.error)
+ {
+ var oAuthToken = window.gapi.auth.getToken();
+ if (oAuthToken)
+ {
+ self.driveCreatePiker(oAuthToken);
+ }
+ }
+ });
+ }
+ });
+ }
+ else
+ {
+ self.driveCreatePiker(oAuthToken);
+ }
+ }});
+ }
+};
+
+/**
+ * @param {string} sId
+ * @return {?Object}
+ */
+PopupsComposeViewModel.prototype.getAttachmentById = function (sId)
+{
+ var
+ aAttachments = this.attachments(),
+ iIndex = 0,
+ iLen = aAttachments.length
+ ;
+
+ for (; iIndex < iLen; iIndex++)
+ {
+ if (aAttachments[iIndex] && sId === aAttachments[iIndex].id)
+ {
+ return aAttachments[iIndex];
+ }
+ }
+
+ return null;
+};
+
+PopupsComposeViewModel.prototype.initUploader = function ()
+{
+ if (this.composeUploaderButton())
+ {
+ var
+ oUploadCache = {},
+ iAttachmentSizeLimit = Utils.pInt(RL.settingsGet('AttachmentLimit')),
+ oJua = new Jua({
+ 'action': RL.link().upload(),
+ 'name': 'uploader',
+ 'queueSize': 2,
+ 'multipleSizeLimit': 50,
+ 'disableFolderDragAndDrop': false,
+ 'clickElement': this.composeUploaderButton(),
+ 'dragAndDropElement': this.composeUploaderDropPlace()
+ })
+ ;
+
+ if (oJua)
+ {
+ oJua
+// .on('onLimitReached', function (iLimit) {
+// alert(iLimit);
+// })
+ .on('onDragEnter', _.bind(function () {
+ this.dragAndDropOver(true);
+ }, this))
+ .on('onDragLeave', _.bind(function () {
+ this.dragAndDropOver(false);
+ }, this))
+ .on('onBodyDragEnter', _.bind(function () {
+ this.dragAndDropVisible(true);
+ }, this))
+ .on('onBodyDragLeave', _.bind(function () {
+ this.dragAndDropVisible(false);
+ }, this))
+ .on('onProgress', _.bind(function (sId, iLoaded, iTotal) {
+ var oItem = null;
+ if (Utils.isUnd(oUploadCache[sId]))
+ {
+ oItem = this.getAttachmentById(sId);
+ if (oItem)
+ {
+ oUploadCache[sId] = oItem;
+ }
+ }
+ else
+ {
+ oItem = oUploadCache[sId];
+ }
+
+ if (oItem)
+ {
+ oItem.progress(' - ' + Math.floor(iLoaded / iTotal * 100) + '%');
+ }
+
+ }, this))
+ .on('onSelect', _.bind(function (sId, oData) {
+
+ this.dragAndDropOver(false);
+
+ var
+ that = this,
+ sFileName = Utils.isUnd(oData.FileName) ? '' : oData.FileName.toString(),
+ mSize = Utils.isNormal(oData.Size) ? Utils.pInt(oData.Size) : null,
+ oAttachment = new ComposeAttachmentModel(sId, sFileName, mSize)
+ ;
+
+ oAttachment.cancel = (function (sId) {
+
+ return function () {
+ that.attachments.remove(function (oItem) {
+ return oItem && oItem.id === sId;
+ });
+
+ if (oJua)
+ {
+ oJua.cancel(sId);
+ }
+ };
+
+ }(sId));
+
+ this.attachments.push(oAttachment);
+
+ if (0 < mSize && 0 < iAttachmentSizeLimit && iAttachmentSizeLimit < mSize)
+ {
+ oAttachment.error(Utils.i18n('UPLOAD/ERROR_FILE_IS_TOO_BIG'));
+ return false;
+ }
+
+ return true;
+
+ }, this))
+ .on('onStart', _.bind(function (sId) {
+
+ var
+ oItem = null
+ ;
+
+ if (Utils.isUnd(oUploadCache[sId]))
+ {
+ oItem = this.getAttachmentById(sId);
+ if (oItem)
+ {
+ oUploadCache[sId] = oItem;
+ }
+ }
+ else
+ {
+ oItem = oUploadCache[sId];
+ }
+
+ if (oItem)
+ {
+ oItem.waiting(false);
+ oItem.uploading(true);
+ }
+
+ }, this))
+ .on('onComplete', _.bind(function (sId, bResult, oData) {
+
+ var
+ sError = '',
+ mErrorCode = null,
+ oAttachmentJson = null,
+ oAttachment = this.getAttachmentById(sId)
+ ;
+
+ oAttachmentJson = bResult && oData && oData.Result && oData.Result.Attachment ? oData.Result.Attachment : null;
+ mErrorCode = oData && oData.Result && oData.Result.ErrorCode ? oData.Result.ErrorCode : null;
+
+ if (null !== mErrorCode)
+ {
+ sError = Utils.getUploadErrorDescByCode(mErrorCode);
+ }
+ else if (!oAttachmentJson)
+ {
+ sError = Utils.i18n('UPLOAD/ERROR_UNKNOWN');
+ }
+
+ if (oAttachment)
+ {
+ if ('' !== sError && 0 < sError.length)
+ {
+ oAttachment
+ .waiting(false)
+ .uploading(false)
+ .error(sError)
+ ;
+ }
+ else if (oAttachmentJson)
+ {
+ oAttachment
+ .waiting(false)
+ .uploading(false)
+ ;
+
+ oAttachment.initByUploadJson(oAttachmentJson);
+ }
+
+ if (Utils.isUnd(oUploadCache[sId]))
+ {
+ delete (oUploadCache[sId]);
+ }
+ }
+
+ }, this))
+ ;
+
+ this
+ .addAttachmentEnabled(true)
+ .dragAndDropEnabled(oJua.isDragAndDropSupported())
+ ;
+ }
+ else
+ {
+ this
+ .addAttachmentEnabled(false)
+ .dragAndDropEnabled(false)
+ ;
+ }
+ }
+};
+
+/**
+ * @return {Object}
+ */
+PopupsComposeViewModel.prototype.prepearAttachmentsForSendOrSave = function ()
+{
+ var oResult = {};
+ _.each(this.attachmentsInReady(), function (oItem) {
+ if (oItem && '' !== oItem.tempName() && oItem.enabled())
+ {
+ oResult[oItem.tempName()] = [
+ oItem.fileName(),
+ oItem.isInline ? '1' : '0',
+ oItem.CID,
+ oItem.contentLocation
+ ];
+ }
+ });
+
+ return oResult;
+};
+
+/**
+ * @param {MessageModel} oMessage
+ */
+PopupsComposeViewModel.prototype.addMessageAsAttachment = function (oMessage)
+{
+ if (oMessage)
+ {
+ var
+ self = this,
+ oAttachment = null,
+ sTemp = oMessage.subject(),
+ fCancelFunc = function (sId) {
+ return function () {
+ self.attachments.remove(function (oItem) {
+ return oItem && oItem.id === sId;
+ });
+ };
+ }
+ ;
+
+ sTemp = '.eml' === sTemp.substr(-4).toLowerCase() ? sTemp : sTemp + '.eml';
+ oAttachment = new ComposeAttachmentModel(
+ oMessage.requestHash, sTemp, oMessage.size()
+ );
+
+ oAttachment.fromMessage = true;
+ oAttachment.cancel = fCancelFunc(oMessage.requestHash);
+ oAttachment.waiting(false).uploading(true);
+
+ this.attachments.push(oAttachment);
+ }
+};
+
+/**
+ * @param {Object} oDropboxFile
+ * @return {boolean}
+ */
+PopupsComposeViewModel.prototype.addDropboxAttachment = function (oDropboxFile)
+{
+ var
+ self = this,
+ oAttachment = null,
+ fCancelFunc = function (sId) {
+ return function () {
+ self.attachments.remove(function (oItem) {
+ return oItem && oItem.id === sId;
+ });
+ };
+ },
+ iAttachmentSizeLimit = Utils.pInt(RL.settingsGet('AttachmentLimit')),
+ mSize = oDropboxFile['bytes']
+ ;
+
+ oAttachment = new ComposeAttachmentModel(
+ oDropboxFile['link'], oDropboxFile['name'], mSize
+ );
+
+ oAttachment.fromMessage = false;
+ oAttachment.cancel = fCancelFunc(oDropboxFile['link']);
+ oAttachment.waiting(false).uploading(true);
+
+ this.attachments.push(oAttachment);
+
+ if (0 < mSize && 0 < iAttachmentSizeLimit && iAttachmentSizeLimit < mSize)
+ {
+ oAttachment.uploading(false);
+ oAttachment.error(Utils.i18n('UPLOAD/ERROR_FILE_IS_TOO_BIG'));
+ return false;
+ }
+
+ RL.remote().composeUploadExternals(function (sResult, oData) {
+
+ var bResult = false;
+ oAttachment.uploading(false);
+
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ {
+ if (oData.Result[oAttachment.id])
+ {
+ bResult = true;
+ oAttachment.tempName(oData.Result[oAttachment.id]);
+ }
+ }
+
+ if (!bResult)
+ {
+ oAttachment.error(Utils.getUploadErrorDescByCode(Enums.UploadErrorCode.FileNoUploaded));
+ }
+
+ }, [oDropboxFile['link']]);
+
+ return true;
+};
+
+/**
+ * @param {Object} oDriveFile
+ * @param {string} sAccessToken
+ * @return {boolean}
+ */
+PopupsComposeViewModel.prototype.addDriveAttachment = function (oDriveFile, sAccessToken)
+{
+ var
+ self = this,
+ fCancelFunc = function (sId) {
+ return function () {
+ self.attachments.remove(function (oItem) {
+ return oItem && oItem.id === sId;
+ });
+ };
+ },
+ iAttachmentSizeLimit = Utils.pInt(RL.settingsGet('AttachmentLimit')),
+ oAttachment = null,
+ mSize = oDriveFile['fileSize'] ? Utils.pInt(oDriveFile['fileSize']) : 0
+ ;
+
+ oAttachment = new ComposeAttachmentModel(
+ oDriveFile['downloadUrl'], oDriveFile['title'], mSize
+ );
+
+ oAttachment.fromMessage = false;
+ oAttachment.cancel = fCancelFunc(oDriveFile['downloadUrl']);
+ oAttachment.waiting(false).uploading(true);
+
+ this.attachments.push(oAttachment);
+
+ if (0 < mSize && 0 < iAttachmentSizeLimit && iAttachmentSizeLimit < mSize)
+ {
+ oAttachment.uploading(false);
+ oAttachment.error(Utils.i18n('UPLOAD/ERROR_FILE_IS_TOO_BIG'));
+ return false;
+ }
+
+ RL.remote().composeUploadDrive(function (sResult, oData) {
+
+ var bResult = false;
+ oAttachment.uploading(false);
+
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ {
+ if (oData.Result[oAttachment.id])
+ {
+ bResult = true;
+ oAttachment.tempName(oData.Result[oAttachment.id][0]);
+ oAttachment.size(Utils.pInt(oData.Result[oAttachment.id][1]));
+ }
+ }
+
+ if (!bResult)
+ {
+ oAttachment.error(Utils.getUploadErrorDescByCode(Enums.UploadErrorCode.FileNoUploaded));
+ }
+
+ }, oDriveFile['downloadUrl'], sAccessToken);
+
+ return true;
+};
+
+/**
+ * @param {MessageModel} oMessage
+ * @param {string} sType
+ */
+PopupsComposeViewModel.prototype.prepearMessageAttachments = function (oMessage, sType)
+{
+ if (oMessage)
+ {
+ var
+ self = this,
+ aAttachments = Utils.isNonEmptyArray(oMessage.attachments()) ? oMessage.attachments() : [],
+ iIndex = 0,
+ iLen = aAttachments.length,
+ oAttachment = null,
+ oItem = null,
+ bAdd = false,
+ fCancelFunc = function (sId) {
+ return function () {
+ self.attachments.remove(function (oItem) {
+ return oItem && oItem.id === sId;
+ });
+ };
+ }
+ ;
+
+ if (Enums.ComposeType.ForwardAsAttachment === sType)
+ {
+ this.addMessageAsAttachment(oMessage);
+ }
+ else
+ {
+ for (; iIndex < iLen; iIndex++)
+ {
+ oItem = aAttachments[iIndex];
+
+ bAdd = false;
+ switch (sType) {
+ case Enums.ComposeType.Reply:
+ case Enums.ComposeType.ReplyAll:
+ bAdd = oItem.isLinked;
+ break;
+
+ case Enums.ComposeType.Forward:
+ case Enums.ComposeType.Draft:
+ case Enums.ComposeType.EditAsNew:
+ bAdd = true;
+ break;
+ }
+
+ if (bAdd)
+ {
+ oAttachment = new ComposeAttachmentModel(
+ oItem.download, oItem.fileName, oItem.estimatedSize,
+ oItem.isInline, oItem.isLinked, oItem.cid, oItem.contentLocation
+ );
+
+ oAttachment.fromMessage = true;
+ oAttachment.cancel = fCancelFunc(oItem.download);
+ oAttachment.waiting(false).uploading(true);
+
+ this.attachments.push(oAttachment);
+ }
+ }
+ }
+ }
+};
+
+PopupsComposeViewModel.prototype.removeLinkedAttachments = function ()
+{
+ this.attachments.remove(function (oItem) {
+ return oItem && oItem.isLinked;
+ });
+};
+
+PopupsComposeViewModel.prototype.setMessageAttachmentFailedDowbloadText = function ()
+{
+ _.each(this.attachments(), function(oAttachment) {
+ if (oAttachment && oAttachment.fromMessage)
+ {
+ oAttachment
+ .waiting(false)
+ .uploading(false)
+ .error(Utils.getUploadErrorDescByCode(Enums.UploadErrorCode.FileNoUploaded))
+ ;
+ }
+ }, this);
+};
+
+/**
+ * @param {boolean=} bIncludeAttachmentInProgress = true
+ * @return {boolean}
+ */
+PopupsComposeViewModel.prototype.isEmptyForm = function (bIncludeAttachmentInProgress)
+{
+ bIncludeAttachmentInProgress = Utils.isUnd(bIncludeAttachmentInProgress) ? true : !!bIncludeAttachmentInProgress;
+ var bAttach = bIncludeAttachmentInProgress ?
+ 0 === this.attachments().length : 0 === this.attachmentsInReady().length;
+
+ return 0 === this.to().length &&
+ 0 === this.cc().length &&
+ 0 === this.bcc().length &&
+ 0 === this.subject().length &&
+ bAttach &&
+ (!this.oEditor || '' === this.oEditor.getData())
+ ;
+};
+
+PopupsComposeViewModel.prototype.reset = function ()
+{
+ this.to('');
+ this.cc('');
+ this.bcc('');
+ this.replyTo('');
+ this.subject('');
+
+ this.requestReadReceipt(false);
+
+ this.aDraftInfo = null;
+ this.sInReplyTo = '';
+ this.bFromDraft = false;
+ this.sReferences = '';
+
+ this.sendError(false);
+ this.sendSuccessButSaveError(false);
+ this.savedError(false);
+ this.savedTime(0);
+ this.savedOrSendingText('');
+ this.emptyToError(false);
+ this.attachmentsInProcessError(false);
+ this.showCcAndBcc(false);
+
+ this.attachments([]);
+ this.dragAndDropOver(false);
+ this.dragAndDropVisible(false);
+
+ this.draftFolder('');
+ this.draftUid('');
+
+ this.sending(false);
+ this.saving(false);
+
+ if (this.oEditor)
+ {
+ this.oEditor.clear(false);
+ }
+};
+
+/**
+ * @return {Array}
+ */
+PopupsComposeViewModel.prototype.getAttachmentsDownloadsForUpload = function ()
+{
+ return _.map(_.filter(this.attachments(), function (oItem) {
+ return oItem && '' === oItem.tempName();
+ }), function (oItem) {
+ return oItem.id;
+ });
+};
+
+PopupsComposeViewModel.prototype.triggerForResize = function ()
+{
+ this.resizer(!this.resizer());
+ this.editorResizeThrottle();
+};
+
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+function PopupsContactsViewModel()
+{
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsContacts');
+
+ var
+ self = this,
+ fFastClearEmptyListHelper = function (aList) {
+ if (aList && 0 < aList.length) {
+ self.viewProperties.removeAll(aList);
+ }
+ }
+ ;
+
+ this.allowContactsSync = RL.data().allowContactsSync;
+ this.enableContactsSync = RL.data().enableContactsSync;
+ this.allowExport = !Globals.bMobileDevice;
+
+ this.search = ko.observable('');
+ this.contactsCount = ko.observable(0);
+ this.contacts = RL.data().contacts;
+ this.contactTags = RL.data().contactTags;
+
+ this.currentContact = ko.observable(null);
+
+ this.importUploaderButton = ko.observable(null);
+
+ this.contactsPage = ko.observable(1);
+ this.contactsPageCount = ko.computed(function () {
+ var iPage = Math.ceil(this.contactsCount() / Consts.Defaults.ContactsPerPage);
+ return 0 >= iPage ? 1 : iPage;
+ }, this);
+
+ this.contactsPagenator = ko.computed(Utils.computedPagenatorHelper(this.contactsPage, this.contactsPageCount));
+
+ this.emptySelection = ko.observable(true);
+ this.viewClearSearch = ko.observable(false);
+
+ this.viewID = ko.observable('');
+ this.viewReadOnly = ko.observable(false);
+ this.viewProperties = ko.observableArray([]);
+
+ this.viewTags = ko.observable('');
+ this.viewTags.visibility = ko.observable(false);
+ this.viewTags.focusTrigger = ko.observable(false);
+
+ this.viewTags.focusTrigger.subscribe(function (bValue) {
+ if (!bValue && '' === this.viewTags())
+ {
+ this.viewTags.visibility(false);
+ }
+ else if (bValue)
+ {
+ this.viewTags.visibility(true);
+ }
+ }, this);
+
+ this.viewSaveTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
+
+ this.viewPropertiesNames = this.viewProperties.filter(function(oProperty) {
+ return -1 < Utils.inArray(oProperty.type(), [
+ Enums.ContactPropertyType.FirstName, Enums.ContactPropertyType.LastName
+ ]);
+ });
+
+ this.viewPropertiesOther = this.viewProperties.filter(function(oProperty) {
+ return -1 < Utils.inArray(oProperty.type(), [
+ Enums.ContactPropertyType.Note
+ ]);
+ });
+
+ this.viewPropertiesOther = ko.computed(function () {
+
+ var aList = _.filter(this.viewProperties(), function (oProperty) {
+ return -1 < Utils.inArray(oProperty.type(), [
+ Enums.ContactPropertyType.Nick
+ ]);
+ });
+
+ return _.sortBy(aList, function (oProperty) {
+ return oProperty.type();
+ });
+
+ }, this);
+
+ this.viewPropertiesEmails = this.viewProperties.filter(function(oProperty) {
+ return Enums.ContactPropertyType.Email === oProperty.type();
+ });
+
+ this.viewPropertiesWeb = this.viewProperties.filter(function(oProperty) {
+ return Enums.ContactPropertyType.Web === oProperty.type();
+ });
+
+ this.viewHasNonEmptyRequaredProperties = ko.computed(function() {
+
+ var
+ aNames = this.viewPropertiesNames(),
+ aEmail = this.viewPropertiesEmails(),
+ fHelper = function (oProperty) {
+ return '' !== Utils.trim(oProperty.value());
+ }
+ ;
+
+ return !!(_.find(aNames, fHelper) || _.find(aEmail, fHelper));
+ }, this);
+
+ this.viewPropertiesPhones = this.viewProperties.filter(function(oProperty) {
+ return Enums.ContactPropertyType.Phone === oProperty.type();
+ });
+
+ this.viewPropertiesEmailsNonEmpty = this.viewPropertiesNames.filter(function(oProperty) {
+ return '' !== Utils.trim(oProperty.value());
+ });
+
+ this.viewPropertiesEmailsEmptyAndOnFocused = this.viewPropertiesEmails.filter(function(oProperty) {
+ var bF = oProperty.focused();
+ return '' === Utils.trim(oProperty.value()) && !bF;
+ });
+
+ this.viewPropertiesPhonesEmptyAndOnFocused = this.viewPropertiesPhones.filter(function(oProperty) {
+ var bF = oProperty.focused();
+ return '' === Utils.trim(oProperty.value()) && !bF;
+ });
+
+ this.viewPropertiesWebEmptyAndOnFocused = this.viewPropertiesWeb.filter(function(oProperty) {
+ var bF = oProperty.focused();
+ return '' === Utils.trim(oProperty.value()) && !bF;
+ });
+
+ this.viewPropertiesOtherEmptyAndOnFocused = ko.computed(function () {
+ return _.filter(this.viewPropertiesOther(), function (oProperty) {
+ var bF = oProperty.focused();
+ return '' === Utils.trim(oProperty.value()) && !bF;
+ });
+ }, this);
+
+ this.viewPropertiesEmailsEmptyAndOnFocused.subscribe(function(aList) {
+ fFastClearEmptyListHelper(aList);
+ });
+
+ this.viewPropertiesPhonesEmptyAndOnFocused.subscribe(function(aList) {
+ fFastClearEmptyListHelper(aList);
+ });
+
+ this.viewPropertiesWebEmptyAndOnFocused.subscribe(function(aList) {
+ fFastClearEmptyListHelper(aList);
+ });
+
+ this.viewPropertiesOtherEmptyAndOnFocused.subscribe(function(aList) {
+ fFastClearEmptyListHelper(aList);
+ });
+
+ this.viewSaving = ko.observable(false);
+
+ this.useCheckboxesInList = RL.data().useCheckboxesInList;
+
+ this.search.subscribe(function () {
+ this.reloadContactList();
+ }, this);
+
+ this.contacts.subscribe(function () {
+ Utils.windowResize();
+ }, this);
+
+ this.viewProperties.subscribe(function () {
+ Utils.windowResize();
+ }, this);
+
+ this.contactsChecked = ko.computed(function () {
+ return _.filter(this.contacts(), function (oItem) {
+ return oItem.checked();
+ });
+ }, this);
+
+ this.contactsCheckedOrSelected = ko.computed(function () {
+
+ var
+ aChecked = this.contactsChecked(),
+ oSelected = this.currentContact()
+ ;
+
+ return _.union(aChecked, oSelected ? [oSelected] : []);
+
+ }, this);
+
+ this.contactsCheckedOrSelectedUids = ko.computed(function () {
+ return _.map(this.contactsCheckedOrSelected(), function (oContact) {
+ return oContact.idContact;
+ });
+ }, this);
+
+ this.selector = new Selector(this.contacts, this.currentContact,
+ '.e-contact-item .actionHandle', '.e-contact-item.selected', '.e-contact-item .checkboxItem',
+ '.e-contact-item.focused');
+
+ this.selector.on('onItemSelect', _.bind(function (oContact) {
+ this.populateViewContact(oContact ? oContact : null);
+ if (!oContact)
+ {
+ this.emptySelection(true);
+ }
+ }, this));
+
+ this.selector.on('onItemGetUid', function (oContact) {
+ return oContact ? oContact.generateUid() : '';
+ });
+
+ this.newCommand = Utils.createCommand(this, function () {
+ this.populateViewContact(null);
+ this.currentContact(null);
+ });
+
+ this.deleteCommand = Utils.createCommand(this, function () {
+ this.deleteSelectedContacts();
+ this.emptySelection(true);
+ }, function () {
+ return 0 < this.contactsCheckedOrSelected().length;
+ });
+
+ this.newMessageCommand = Utils.createCommand(this, function () {
+ var aC = this.contactsCheckedOrSelected(), aE = [];
+ if (Utils.isNonEmptyArray(aC))
+ {
+ aE = _.map(aC, function (oItem) {
+ if (oItem)
+ {
+ var
+ aData = oItem.getNameAndEmailHelper(),
+ oEmail = aData ? new EmailModel(aData[0], aData[1]) : null
+ ;
+
+ if (oEmail && oEmail.validate())
+ {
+ return oEmail;
+ }
+ }
+
+ return null;
+ });
+
+ aE = _.compact(aE);
+ }
+
+ if (Utils.isNonEmptyArray(aE))
+ {
+ kn.hideScreenPopup(PopupsContactsViewModel);
+ kn.showScreenPopup(PopupsComposeViewModel, [Enums.ComposeType.Empty, null, aE]);
+ }
+
+ }, function () {
+ return 0 < this.contactsCheckedOrSelected().length;
+ });
+
+ this.clearCommand = Utils.createCommand(this, function () {
+ this.search('');
+ });
+
+ this.saveCommand = Utils.createCommand(this, function () {
+
+ this.viewSaving(true);
+ this.viewSaveTrigger(Enums.SaveSettingsStep.Animate);
+
+ var
+ sRequestUid = Utils.fakeMd5(),
+ aProperties = []
+ ;
+
+ _.each(this.viewProperties(), function (oItem) {
+ if (oItem.type() && '' !== Utils.trim(oItem.value()))
+ {
+ aProperties.push([oItem.type(), oItem.value(), oItem.typeStr()]);
+ }
+ });
+
+ RL.remote().contactSave(function (sResult, oData) {
+
+ var bRes = false;
+ self.viewSaving(false);
+
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result &&
+ oData.Result.RequestUid === sRequestUid && 0 < Utils.pInt(oData.Result.ResultID))
+ {
+ if ('' === self.viewID())
+ {
+ self.viewID(Utils.pInt(oData.Result.ResultID));
+ }
+
+ self.reloadContactList();
+ bRes = true;
+ }
+
+ _.delay(function () {
+ self.viewSaveTrigger(bRes ? Enums.SaveSettingsStep.TrueResult : Enums.SaveSettingsStep.FalseResult);
+ }, 300);
+
+ if (bRes)
+ {
+ self.watchDirty(false);
+
+ _.delay(function () {
+ self.viewSaveTrigger(Enums.SaveSettingsStep.Idle);
+ }, 1000);
+ }
+
+ }, sRequestUid, this.viewID(), this.viewTags(), aProperties);
+
+ }, function () {
+ var
+ bV = this.viewHasNonEmptyRequaredProperties(),
+ bReadOnly = this.viewReadOnly()
+ ;
+ return !this.viewSaving() && bV && !bReadOnly;
+ });
+
+ this.syncCommand = Utils.createCommand(this, function () {
+
+ var self = this;
+ RL.contactsSync(function (sResult, oData) {
+ if (Enums.StorageResultType.Success !== sResult || !oData || !oData.Result)
+ {
+ window.alert(Utils.getNotification(
+ oData && oData.ErrorCode ? oData.ErrorCode : Enums.Notification.ContactsSyncError));
+ }
+
+ self.reloadContactList(true);
+ });
+
+ }, function () {
+ return !this.contacts.syncing() && !this.contacts.importing();
+ });
+
+ this.bDropPageAfterDelete = false;
+
+ this.watchDirty = ko.observable(false);
+ this.watchHash = ko.observable(false);
+
+ this.viewHash = ko.computed(function () {
+ return '' + self.viewTags() + '|' + _.map(self.viewProperties(), function (oItem) {
+ return oItem.value();
+ }).join('');
+ });
+
+// this.saveCommandDebounce = _.debounce(_.bind(this.saveCommand, this), 1000);
+
+ this.viewHash.subscribe(function () {
+ if (this.watchHash() && !this.viewReadOnly() && !this.watchDirty())
+ {
+ this.watchDirty(true);
+ }
+ }, this);
+
+ this.sDefaultKeyScope = Enums.KeyState.ContactList;
+
+ Knoin.constructorEnd(this);
+}
+
+Utils.extendAsViewModel('PopupsContactsViewModel', PopupsContactsViewModel);
+
+PopupsContactsViewModel.prototype.getPropertyPlceholder = function (sType)
+{
+ var sResult = '';
+ switch (sType)
+ {
+ case Enums.ContactPropertyType.LastName:
+ sResult = 'CONTACTS/PLACEHOLDER_ENTER_LAST_NAME';
+ break;
+ case Enums.ContactPropertyType.FirstName:
+ sResult = 'CONTACTS/PLACEHOLDER_ENTER_FIRST_NAME';
+ break;
+ case Enums.ContactPropertyType.Nick:
+ sResult = 'CONTACTS/PLACEHOLDER_ENTER_NICK_NAME';
+ break;
+ }
+
+ return sResult;
+};
+
+PopupsContactsViewModel.prototype.addNewProperty = function (sType, sTypeStr)
+{
+ this.viewProperties.push(new ContactPropertyModel(sType, sTypeStr || '', '', true, this.getPropertyPlceholder(sType)));
+};
+
+PopupsContactsViewModel.prototype.addNewOrFocusProperty = function (sType, sTypeStr)
+{
+ var oItem = _.find(this.viewProperties(), function (oItem) {
+ return sType === oItem.type();
+ });
+
+ if (oItem)
+ {
+ oItem.focused(true);
+ }
+ else
+ {
+ this.addNewProperty(sType, sTypeStr);
+ }
+};
+
+PopupsContactsViewModel.prototype.addNewTag = function ()
+{
+ this.viewTags.visibility(true);
+ this.viewTags.focusTrigger(true);
+};
+
+PopupsContactsViewModel.prototype.addNewEmail = function ()
+{
+ this.addNewProperty(Enums.ContactPropertyType.Email, 'Home');
+};
+
+PopupsContactsViewModel.prototype.addNewPhone = function ()
+{
+ this.addNewProperty(Enums.ContactPropertyType.Phone, 'Mobile');
+};
+
+PopupsContactsViewModel.prototype.addNewWeb = function ()
+{
+ this.addNewProperty(Enums.ContactPropertyType.Web);
+};
+
+PopupsContactsViewModel.prototype.addNewNickname = function ()
+{
+ this.addNewOrFocusProperty(Enums.ContactPropertyType.Nick);
+};
+
+PopupsContactsViewModel.prototype.addNewNotes = function ()
+{
+ this.addNewOrFocusProperty(Enums.ContactPropertyType.Note);
+};
+
+PopupsContactsViewModel.prototype.addNewBirthday = function ()
+{
+ this.addNewOrFocusProperty(Enums.ContactPropertyType.Birthday);
+};
+
+//PopupsContactsViewModel.prototype.addNewAddress = function ()
+//{
+//};
+
+PopupsContactsViewModel.prototype.exportVcf = function ()
+{
+ RL.download(RL.link().exportContactsVcf());
+};
+
+PopupsContactsViewModel.prototype.exportCsv = function ()
+{
+ RL.download(RL.link().exportContactsCsv());
+};
+
+PopupsContactsViewModel.prototype.initUploader = function ()
+{
+ if (this.importUploaderButton())
+ {
+ var
+ oJua = new Jua({
+ 'action': RL.link().uploadContacts(),
+ 'name': 'uploader',
+ 'queueSize': 1,
+ 'multipleSizeLimit': 1,
+ 'disableFolderDragAndDrop': true,
+ 'disableDragAndDrop': true,
+ 'disableMultiple': true,
+ 'disableDocumentDropPrevent': true,
+ 'clickElement': this.importUploaderButton()
+ })
+ ;
+
+ if (oJua)
+ {
+ oJua
+ .on('onStart', _.bind(function () {
+ this.contacts.importing(true);
+ }, this))
+ .on('onComplete', _.bind(function (sId, bResult, oData) {
+
+ this.contacts.importing(false);
+ this.reloadContactList();
+
+ if (!sId || !bResult || !oData || !oData.Result)
+ {
+ window.alert(Utils.i18n('CONTACTS/ERROR_IMPORT_FILE'));
+ }
+
+ }, this))
+ ;
+ }
+ }
+};
+
+PopupsContactsViewModel.prototype.removeCheckedOrSelectedContactsFromList = function ()
+{
+ var
+ self = this,
+ oKoContacts = this.contacts,
+ oCurrentContact = this.currentContact(),
+ iCount = this.contacts().length,
+ aContacts = this.contactsCheckedOrSelected()
+ ;
+
+ if (0 < aContacts.length)
+ {
+ _.each(aContacts, function (oContact) {
+
+ if (oCurrentContact && oCurrentContact.idContact === oContact.idContact)
+ {
+ oCurrentContact = null;
+ self.currentContact(null);
+ }
+
+ oContact.deleted(true);
+ iCount--;
+ });
+
+ if (iCount <= 0)
+ {
+ this.bDropPageAfterDelete = true;
+ }
+
+ _.delay(function () {
+
+ _.each(aContacts, function (oContact) {
+ oKoContacts.remove(oContact);
+ });
+
+ }, 500);
+ }
+};
+
+PopupsContactsViewModel.prototype.deleteSelectedContacts = function ()
+{
+ if (0 < this.contactsCheckedOrSelected().length)
+ {
+ RL.remote().contactsDelete(
+ _.bind(this.deleteResponse, this),
+ this.contactsCheckedOrSelectedUids()
+ );
+
+ this.removeCheckedOrSelectedContactsFromList();
+ }
+};
+
+/**
+ * @param {string} sResult
+ * @param {AjaxJsonDefaultResponse} oData
+ */
+PopupsContactsViewModel.prototype.deleteResponse = function (sResult, oData)
+{
+ if (500 < (Enums.StorageResultType.Success === sResult && oData && oData.Time ? Utils.pInt(oData.Time) : 0))
+ {
+ this.reloadContactList(this.bDropPageAfterDelete);
+ }
+ else
+ {
+ _.delay((function (self) {
+ return function () {
+ self.reloadContactList(self.bDropPageAfterDelete);
+ };
+ }(this)), 500);
+ }
+};
+
+PopupsContactsViewModel.prototype.removeProperty = function (oProp)
+{
+ this.viewProperties.remove(oProp);
+};
+
+/**
+ * @param {?ContactModel} oContact
+ */
+PopupsContactsViewModel.prototype.populateViewContact = function (oContact)
+{
+ var
+ sId = '',
+ sLastName = '',
+ sFirstName = '',
+ aList = []
+ ;
+
+ this.watchHash(false);
+
+ this.emptySelection(false);
+ this.viewReadOnly(false);
+ this.viewTags('');
+
+ if (oContact)
+ {
+ sId = oContact.idContact;
+ if (Utils.isNonEmptyArray(oContact.properties))
+ {
+ _.each(oContact.properties, function (aProperty) {
+ if (aProperty && aProperty[0])
+ {
+ if (Enums.ContactPropertyType.LastName === aProperty[0])
+ {
+ sLastName = aProperty[1];
+ }
+ else if (Enums.ContactPropertyType.FirstName === aProperty[0])
+ {
+ sFirstName = aProperty[1];
+ }
+ else
+ {
+ aList.push(new ContactPropertyModel(aProperty[0], aProperty[2] || '', aProperty[1]));
+ }
+ }
+ });
+ }
+
+ this.viewTags(oContact.tags);
+
+ this.viewReadOnly(!!oContact.readOnly);
+ }
+
+ this.viewTags.focusTrigger.valueHasMutated();
+ this.viewTags.visibility('' !== this.viewTags());
+
+ aList.unshift(new ContactPropertyModel(Enums.ContactPropertyType.LastName, '', sLastName, false,
+ this.getPropertyPlceholder(Enums.ContactPropertyType.LastName)));
+
+ aList.unshift(new ContactPropertyModel(Enums.ContactPropertyType.FirstName, '', sFirstName, !oContact,
+ this.getPropertyPlceholder(Enums.ContactPropertyType.FirstName)));
+
+ this.viewID(sId);
+ this.viewProperties([]);
+ this.viewProperties(aList);
+
+ this.watchDirty(false);
+ this.watchHash(true);
+};
+
+/**
+ * @param {boolean=} bDropPagePosition = false
+ */
+PopupsContactsViewModel.prototype.reloadContactList = function (bDropPagePosition)
+{
+ var
+ self = this,
+ iOffset = (this.contactsPage() - 1) * Consts.Defaults.ContactsPerPage
+ ;
+
+ this.bDropPageAfterDelete = false;
+
+ if (Utils.isUnd(bDropPagePosition) ? false : !!bDropPagePosition)
+ {
+ this.contactsPage(1);
+ iOffset = 0;
+ }
+
+ this.contacts.loading(true);
+ RL.remote().contacts(function (sResult, oData) {
+ var
+ iCount = 0,
+ aList = [],
+ aTagsList = []
+ ;
+
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result && oData.Result.List)
+ {
+ if (Utils.isNonEmptyArray(oData.Result.List))
+ {
+ aList = _.map(oData.Result.List, function (oItem) {
+ var oContact = new ContactModel();
+ return oContact.parse(oItem) ? oContact : null;
+ });
+
+ aList = _.compact(aList);
+
+ iCount = Utils.pInt(oData.Result.Count);
+ iCount = 0 < iCount ? iCount : 0;
+ }
+
+ if (Utils.isNonEmptyArray(oData.Result.Tags))
+ {
+ aTagsList = _.map(oData.Result.Tags, function (oItem) {
+ var oContactTag = new ContactTagModel();
+ return oContactTag.parse(oItem) ? oContactTag : null;
+ });
+
+ aTagsList = _.compact(aTagsList);
+ }
+ }
+
+ self.contactsCount(iCount);
+
+ self.contacts(aList);
+ self.contacts.loading(false);
+ self.contactTags(aTagsList);
+
+ self.viewClearSearch('' !== self.search());
+
+ }, iOffset, Consts.Defaults.ContactsPerPage, this.search());
+};
+
+PopupsContactsViewModel.prototype.onBuild = function (oDom)
+{
+ this.oContentVisible = $('.b-list-content', oDom);
+ this.oContentScrollable = $('.content', this.oContentVisible);
+
+ this.selector.init(this.oContentVisible, this.oContentScrollable, Enums.KeyState.ContactList);
+
+ var self = this;
+
+ key('delete', Enums.KeyState.ContactList, function () {
+ self.deleteCommand();
+ return false;
+ });
+
+ oDom
+ .on('click', '.e-pagenator .e-page', function () {
+ var oPage = ko.dataFor(this);
+ if (oPage)
+ {
+ self.contactsPage(Utils.pInt(oPage.value));
+ self.reloadContactList();
+ }
+ })
+ ;
+
+ this.initUploader();
+};
+
+PopupsContactsViewModel.prototype.onShow = function ()
+{
+ kn.routeOff();
+ this.reloadContactList(true);
+};
+
+PopupsContactsViewModel.prototype.onHide = function ()
+{
+ kn.routeOn();
+ this.currentContact(null);
+ this.emptySelection(true);
+ this.search('');
+ this.contactsCount(0);
+ this.contacts([]);
+// _.each(this.contacts(), function (oItem) {
+// oItem.checked(false);
+// });
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+function PopupsAdvancedSearchViewModel()
+{
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsAdvancedSearch');
+
+ this.fromFocus = ko.observable(false);
+
+ this.from = ko.observable('');
+ this.to = ko.observable('');
+ this.subject = ko.observable('');
+ this.text = ko.observable('');
+ this.selectedDateValue = ko.observable(-1);
+
+ this.hasAttachment = ko.observable(false);
+ this.starred = ko.observable(false);
+ this.unseen = ko.observable(false);
+
+ this.searchCommand = Utils.createCommand(this, function () {
+
+ var sSearch = this.buildSearchString();
+ if ('' !== sSearch)
+ {
+ RL.data().mainMessageListSearch(sSearch);
+ }
+
+ this.cancelCommand();
+ });
+
+ Knoin.constructorEnd(this);
+}
+
+Utils.extendAsViewModel('PopupsAdvancedSearchViewModel', PopupsAdvancedSearchViewModel);
+
+PopupsAdvancedSearchViewModel.prototype.buildSearchStringValue = function (sValue)
+{
+ if (-1 < sValue.indexOf(' '))
+ {
+ sValue = '"' + sValue + '"';
+ }
+
+ return sValue;
+};
+
+PopupsAdvancedSearchViewModel.prototype.buildSearchString = function ()
+{
+ var
+ aResult = [],
+ sFrom = Utils.trim(this.from()),
+ sTo = Utils.trim(this.to()),
+ sSubject = Utils.trim(this.subject()),
+ sText = Utils.trim(this.text()),
+ aIs = [],
+ aHas = []
+ ;
+
+ if (sFrom && '' !== sFrom)
+ {
+ aResult.push('from:' + this.buildSearchStringValue(sFrom));
+ }
+
+ if (sTo && '' !== sTo)
+ {
+ aResult.push('to:' + this.buildSearchStringValue(sTo));
+ }
+
+ if (sSubject && '' !== sSubject)
+ {
+ aResult.push('subject:' + this.buildSearchStringValue(sSubject));
+ }
+
+ if (this.hasAttachment())
+ {
+ aHas.push('attachment');
+ }
+
+ if (this.unseen())
+ {
+ aIs.push('unseen');
+ }
+
+ if (this.starred())
+ {
+ aIs.push('flagged');
+ }
+
+ if (0 < aHas.length)
+ {
+ aResult.push('has:' + aHas.join(','));
+ }
+
+ if (0 < aIs.length)
+ {
+ aResult.push('is:' + aIs.join(','));
+ }
+
+ if (-1 < this.selectedDateValue())
+ {
+ aResult.push('date:' + moment().subtract('days', this.selectedDateValue()).format('YYYY.MM.DD') + '/');
+ }
+
+ if (sText && '' !== sText)
+ {
+ aResult.push('text:' + this.buildSearchStringValue(sText));
+ }
+
+ return Utils.trim(aResult.join(' '));
+};
+
+PopupsAdvancedSearchViewModel.prototype.clearPopup = function ()
+{
+ this.from('');
+ this.to('');
+ this.subject('');
+ this.text('');
+
+ this.selectedDateValue(-1);
+ this.hasAttachment(false);
+ this.starred(false);
+ this.unseen(false);
+
+ this.fromFocus(true);
+};
+
+PopupsAdvancedSearchViewModel.prototype.onShow = function ()
+{
+ this.clearPopup();
+};
+
+PopupsAdvancedSearchViewModel.prototype.onFocus = function ()
+{
+ this.fromFocus(true);
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+function PopupsAddAccountViewModel()
+{
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsAddAccount');
+
+ this.email = ko.observable('');
+ this.password = ko.observable('');
+
+ this.emailError = ko.observable(false);
+ this.passwordError = ko.observable(false);
+
+ this.email.subscribe(function () {
+ this.emailError(false);
+ }, this);
+
+ this.password.subscribe(function () {
+ this.passwordError(false);
+ }, this);
+
+ this.submitRequest = ko.observable(false);
+ this.submitError = ko.observable('');
+
+ this.emailFocus = ko.observable(false);
+
+ this.addAccountCommand = Utils.createCommand(this, function () {
+
+ this.emailError('' === Utils.trim(this.email()));
+ this.passwordError('' === Utils.trim(this.password()));
+
+ if (this.emailError() || this.passwordError())
+ {
+ return false;
+ }
+
+ this.submitRequest(true);
+
+ RL.remote().accountAdd(_.bind(function (sResult, oData) {
+
+ this.submitRequest(false);
+ if (Enums.StorageResultType.Success === sResult && oData && 'AccountAdd' === oData.Action)
+ {
+ if (oData.Result)
+ {
+ RL.accountsAndIdentities();
+ this.cancelCommand();
+ }
+ else if (oData.ErrorCode)
+ {
+ this.submitError(Utils.getNotification(oData.ErrorCode));
+ }
+ }
+ else
+ {
+ this.submitError(Utils.getNotification(Enums.Notification.UnknownError));
+ }
+
+ }, this), this.email(), '', this.password());
+
+ return true;
+
+ }, function () {
+ return !this.submitRequest();
+ });
+
+ Knoin.constructorEnd(this);
+}
+
+Utils.extendAsViewModel('PopupsAddAccountViewModel', PopupsAddAccountViewModel);
+
+PopupsAddAccountViewModel.prototype.clearPopup = function ()
+{
+ this.email('');
+ this.password('');
+
+ this.emailError(false);
+ this.passwordError(false);
+
+ this.submitRequest(false);
+ this.submitError('');
+};
+
+PopupsAddAccountViewModel.prototype.onShow = function ()
+{
+ this.clearPopup();
+};
+
+PopupsAddAccountViewModel.prototype.onFocus = function ()
+{
+ this.emailFocus(true);
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+function PopupsAddOpenPgpKeyViewModel()
+{
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsAddOpenPgpKey');
+
+ this.key = ko.observable('');
+ this.key.error = ko.observable(false);
+ this.key.focus = ko.observable(false);
+
+ this.key.subscribe(function () {
+ this.key.error(false);
+ }, this);
+
+ this.addOpenPgpKeyCommand = Utils.createCommand(this, function () {
+
+ var
+ iCount = 30,
+ aMatch = null,
+ sKey = Utils.trim(this.key()),
+ oReg = /[\-]{3,6}BEGIN[\s]PGP[\s](PRIVATE|PUBLIC)[\s]KEY[\s]BLOCK[\-]{3,6}[\s\S]+?[\-]{3,6}END[\s]PGP[\s](PRIVATE|PUBLIC)[\s]KEY[\s]BLOCK[\-]{3,6}/gi,
+ oOpenpgpKeyring = RL.data().openpgpKeyring
+ ;
+
+ sKey = sKey.replace(/[\r\n]([a-zA-Z0-9]{2,}:[^\r\n]+)[\r\n]+([a-zA-Z0-9\/\\+=]{10,})/g, '\n$1!-!N!-!$2')
+ .replace(/[\n\r]+/g, '\n').replace(/!-!N!-!/g, '\n\n');
+
+ this.key.error('' === sKey);
+
+ if (!oOpenpgpKeyring || this.key.error())
+ {
+ return false;
+ }
+
+ do
+ {
+ aMatch = oReg.exec(sKey);
+ if (!aMatch || 0 > iCount)
+ {
+ break;
+ }
+
+ if (aMatch[0] && aMatch[1] && aMatch[2] && aMatch[1] === aMatch[2])
+ {
+ if ('PRIVATE' === aMatch[1])
+ {
+ oOpenpgpKeyring.privateKeys.importKey(aMatch[0]);
+ }
+ else if ('PUBLIC' === aMatch[1])
+ {
+ oOpenpgpKeyring.publicKeys.importKey(aMatch[0]);
+ }
+ }
+
+ iCount--;
+ }
+ while (true);
+
+ oOpenpgpKeyring.store();
+
+ RL.reloadOpenPgpKeys();
+ Utils.delegateRun(this, 'cancelCommand');
+
+ return true;
+ });
+
+ Knoin.constructorEnd(this);
+}
+
+Utils.extendAsViewModel('PopupsAddOpenPgpKeyViewModel', PopupsAddOpenPgpKeyViewModel);
+
+PopupsAddOpenPgpKeyViewModel.prototype.clearPopup = function ()
+{
+ this.key('');
+ this.key.error(false);
+};
+
+PopupsAddOpenPgpKeyViewModel.prototype.onShow = function ()
+{
+ this.clearPopup();
+};
+
+PopupsAddOpenPgpKeyViewModel.prototype.onFocus = function ()
+{
+ this.key.focus(true);
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+function PopupsViewOpenPgpKeyViewModel()
+{
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsViewOpenPgpKey');
+
+ this.key = ko.observable('');
+ this.keyDom = ko.observable(null);
+
+ Knoin.constructorEnd(this);
+}
+
+Utils.extendAsViewModel('PopupsViewOpenPgpKeyViewModel', PopupsViewOpenPgpKeyViewModel);
+
+PopupsViewOpenPgpKeyViewModel.prototype.clearPopup = function ()
+{
+ this.key('');
+};
+
+PopupsViewOpenPgpKeyViewModel.prototype.selectKey = function ()
+{
+ var oEl = this.keyDom();
+ if (oEl)
+ {
+ Utils.selectElement(oEl);
+ }
+};
+
+PopupsViewOpenPgpKeyViewModel.prototype.onShow = function (oOpenPgpKey)
+{
+ this.clearPopup();
+
+ if (oOpenPgpKey)
+ {
+ this.key(oOpenPgpKey.armor);
+ }
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+function PopupsGenerateNewOpenPgpKeyViewModel()
+{
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsGenerateNewOpenPgpKey');
+
+ this.email = ko.observable('');
+ this.email.focus = ko.observable('');
+ this.email.error = ko.observable(false);
+
+ this.name = ko.observable('');
+ this.password = ko.observable('');
+ this.keyBitLength = ko.observable(2048);
+
+ this.submitRequest = ko.observable(false);
+
+ this.email.subscribe(function () {
+ this.email.error(false);
+ }, this);
+
+ this.generateOpenPgpKeyCommand = Utils.createCommand(this, function () {
+
+ var
+ self = this,
+ sUserID = '',
+ mKeyPair = null,
+ oOpenpgpKeyring = RL.data().openpgpKeyring
+ ;
+
+ this.email.error('' === Utils.trim(this.email()));
+ if (!oOpenpgpKeyring || this.email.error())
+ {
+ return false;
+ }
+
+ sUserID = this.email();
+ if ('' !== this.name())
+ {
+ sUserID = this.name() + ' <' + sUserID + '>';
+ }
+
+ this.submitRequest(true);
+
+ _.delay(function () {
+// mKeyPair = window.openpgp.generateKeyPair(1, Utils.pInt(self.keyBitLength()), sUserID, Utils.trim(self.password()));
+ mKeyPair = window.openpgp.generateKeyPair({
+ 'userId': sUserID,
+ 'numBits': Utils.pInt(self.keyBitLength()),
+ 'passphrase': Utils.trim(self.password())
+ });
+
+ if (mKeyPair && mKeyPair.privateKeyArmored)
+ {
+ oOpenpgpKeyring.privateKeys.importKey(mKeyPair.privateKeyArmored);
+ oOpenpgpKeyring.publicKeys.importKey(mKeyPair.publicKeyArmored);
+ oOpenpgpKeyring.store();
+
+ RL.reloadOpenPgpKeys();
+ Utils.delegateRun(self, 'cancelCommand');
+ }
+
+ self.submitRequest(false);
+ }, 100);
+
+ return true;
+ });
+
+ Knoin.constructorEnd(this);
+}
+
+Utils.extendAsViewModel('PopupsGenerateNewOpenPgpKeyViewModel', PopupsGenerateNewOpenPgpKeyViewModel);
+
+PopupsGenerateNewOpenPgpKeyViewModel.prototype.clearPopup = function ()
+{
+ this.name('');
+ this.password('');
+
+ this.email('');
+ this.email.error(false);
+ this.keyBitLength(2048);
+};
+
+PopupsGenerateNewOpenPgpKeyViewModel.prototype.onShow = function ()
+{
+ this.clearPopup();
+};
+
+PopupsGenerateNewOpenPgpKeyViewModel.prototype.onFocus = function ()
+{
+ this.email.focus(true);
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+function PopupsComposeOpenPgpViewModel()
+{
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsComposeOpenPgp');
+
+ this.notification = ko.observable('');
+
+ this.sign = ko.observable(true);
+ this.encrypt = ko.observable(true);
+
+ this.password = ko.observable('');
+ this.password.focus = ko.observable(false);
+ this.buttonFocus = ko.observable(false);
+
+ this.from = ko.observable('');
+ this.to = ko.observableArray([]);
+ this.text = ko.observable('');
+
+ this.resultCallback = null;
+
+ this.submitRequest = ko.observable(false);
+
+ // commands
+ this.doCommand = Utils.createCommand(this, function () {
+
+ var
+ self = this,
+ bResult = true,
+ oData = RL.data(),
+ oPrivateKey = null,
+ aPublicKeys = []
+ ;
+
+ this.submitRequest(true);
+
+ if (bResult && this.sign() && '' === this.from())
+ {
+ this.notification(Utils.i18n('PGP_NOTIFICATIONS/SPECIFY_FROM_EMAIL'));
+ bResult = false;
+ }
+
+ if (bResult && this.sign())
+ {
+ oPrivateKey = oData.findPrivateKeyByEmail(this.from(), this.password());
+ if (!oPrivateKey)
+ {
+ this.notification(Utils.i18n('PGP_NOTIFICATIONS/NO_PRIVATE_KEY_FOUND_FOR', {
+ 'EMAIL': this.from()
+ }));
+
+ bResult = false;
+ }
+ }
+
+ if (bResult && this.encrypt() && 0 === this.to().length)
+ {
+ this.notification(Utils.i18n('PGP_NOTIFICATIONS/SPECIFY_AT_LEAST_ONE_RECIPIENT'));
+ bResult = false;
+ }
+
+ if (bResult && this.encrypt())
+ {
+ aPublicKeys = [];
+ _.each(this.to(), function (sEmail) {
+ var aKeys = oData.findPublicKeysByEmail(sEmail);
+ if (0 === aKeys.length && bResult)
+ {
+ self.notification(Utils.i18n('PGP_NOTIFICATIONS/NO_PUBLIC_KEYS_FOUND_FOR', {
+ 'EMAIL': sEmail
+ }));
+
+ bResult = false;
+ }
+
+ aPublicKeys = aPublicKeys.concat(aKeys);
+ });
+
+ if (bResult && (0 === aPublicKeys.length || this.to().length !== aPublicKeys.length))
+ {
+ bResult = false;
+ }
+ }
+
+ _.delay(function () {
+
+ if (self.resultCallback && bResult)
+ {
+ try {
+
+ if (oPrivateKey && 0 === aPublicKeys.length)
+ {
+ self.resultCallback(
+ window.openpgp.signClearMessage([oPrivateKey], self.text())
+ );
+ }
+ else if (oPrivateKey && 0 < aPublicKeys.length)
+ {
+ self.resultCallback(
+ window.openpgp.signAndEncryptMessage(aPublicKeys, oPrivateKey, self.text())
+ );
+ }
+ else if (!oPrivateKey && 0 < aPublicKeys.length)
+ {
+ self.resultCallback(
+ window.openpgp.encryptMessage(aPublicKeys, self.text())
+ );
+ }
+ }
+ catch (e)
+ {
+ self.notification(Utils.i18n('PGP_NOTIFICATIONS/PGP_ERROR', {
+ 'ERROR': '' + e
+ }));
+
+ bResult = false;
+ }
+ }
+
+ if (bResult)
+ {
+ self.cancelCommand();
+ }
+
+ self.submitRequest(false);
+
+ }, 10);
+
+ }, function () {
+ return !this.submitRequest() && (this.sign() || this.encrypt());
+ });
+
+ this.sDefaultKeyScope = Enums.KeyState.PopupComposeOpenPGP;
+
+ Knoin.constructorEnd(this);
+}
+
+Utils.extendAsViewModel('PopupsComposeOpenPgpViewModel', PopupsComposeOpenPgpViewModel);
+
+PopupsComposeOpenPgpViewModel.prototype.clearPopup = function ()
+{
+ this.notification('');
+
+ this.password('');
+ this.password.focus(false);
+ this.buttonFocus(false);
+
+ this.from('');
+ this.to([]);
+ this.text('');
+
+ this.submitRequest(false);
+
+ this.resultCallback = null;
+};
+
+PopupsComposeOpenPgpViewModel.prototype.onBuild = function ()
+{
+ key('tab,shift+tab', Enums.KeyState.PopupComposeOpenPGP, _.bind(function () {
+
+ switch (true)
+ {
+ case this.password.focus():
+ this.buttonFocus(true);
+ break;
+ case this.buttonFocus():
+ this.password.focus(true);
+ break;
+ }
+
+ return false;
+
+ }, this));
+};
+
+PopupsComposeOpenPgpViewModel.prototype.onHide = function ()
+{
+ this.clearPopup();
+};
+
+PopupsComposeOpenPgpViewModel.prototype.onFocus = function ()
+{
+ if (this.sign())
+ {
+ this.password.focus(true);
+ }
+ else
+ {
+ this.buttonFocus(true);
+ }
+};
+
+PopupsComposeOpenPgpViewModel.prototype.onShow = function (fCallback, sText, sFromEmail, sTo, sCc, sBcc)
+{
+ this.clearPopup();
+
+ var
+ oEmail = new EmailModel(),
+ sResultFromEmail = '',
+ aRec = []
+ ;
+
+ this.resultCallback = fCallback;
+
+ oEmail.clear();
+ oEmail.mailsoParse(sFromEmail);
+ if ('' !== oEmail.email)
+ {
+ sResultFromEmail = oEmail.email;
+ }
+
+ if ('' !== sTo)
+ {
+ aRec.push(sTo);
+ }
+
+ if ('' !== sCc)
+ {
+ aRec.push(sCc);
+ }
+
+ if ('' !== sBcc)
+ {
+ aRec.push(sBcc);
+ }
+
+ aRec = aRec.join(', ').split(',');
+ aRec = _.compact(_.map(aRec, function (sValue) {
+ oEmail.clear();
+ oEmail.mailsoParse(Utils.trim(sValue));
+ return '' === oEmail.email ? false : oEmail.email;
+ }));
+
+ this.from(sResultFromEmail);
+ this.to(aRec);
+ this.text(sText);
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+function PopupsIdentityViewModel()
+{
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsIdentity');
+
+ this.id = '';
+ this.edit = ko.observable(false);
+ this.owner = ko.observable(false);
+
+ this.email = ko.observable('').validateEmail();
+ this.email.focused = ko.observable(false);
+ this.name = ko.observable('');
+ this.name.focused = ko.observable(false);
+ this.replyTo = ko.observable('').validateSimpleEmail();
+ this.replyTo.focused = ko.observable(false);
+ this.bcc = ko.observable('').validateSimpleEmail();
+ this.bcc.focused = ko.observable(false);
+
+// this.email.subscribe(function () {
+// this.email.hasError(false);
+// }, this);
+
+ this.submitRequest = ko.observable(false);
+ this.submitError = ko.observable('');
+
+ this.addOrEditIdentityCommand = Utils.createCommand(this, function () {
+
+ if (!this.email.hasError())
+ {
+ this.email.hasError('' === Utils.trim(this.email()));
+ }
+
+ if (this.email.hasError())
+ {
+ if (!this.owner())
+ {
+ this.email.focused(true);
+ }
+
+ return false;
+ }
+
+ if (this.replyTo.hasError())
+ {
+ this.replyTo.focused(true);
+ return false;
+ }
+
+ if (this.bcc.hasError())
+ {
+ this.bcc.focused(true);
+ return false;
+ }
+
+ this.submitRequest(true);
+
+ RL.remote().identityUpdate(_.bind(function (sResult, oData) {
+
+ this.submitRequest(false);
+ if (Enums.StorageResultType.Success === sResult && oData)
+ {
+ if (oData.Result)
+ {
+ RL.accountsAndIdentities();
+ this.cancelCommand();
+ }
+ else if (oData.ErrorCode)
+ {
+ this.submitError(Utils.getNotification(oData.ErrorCode));
+ }
+ }
+ else
+ {
+ this.submitError(Utils.getNotification(Enums.Notification.UnknownError));
+ }
+
+ }, this), this.id, this.email(), this.name(), this.replyTo(), this.bcc());
+
+ return true;
+
+ }, function () {
+ return !this.submitRequest();
+ });
+
+ this.label = ko.computed(function () {
+ return Utils.i18n('POPUPS_IDENTITIES/' + (this.edit() ? 'TITLE_UPDATE_IDENTITY': 'TITLE_ADD_IDENTITY'));
+ }, this);
+
+ this.button = ko.computed(function () {
+ return Utils.i18n('POPUPS_IDENTITIES/' + (this.edit() ? 'BUTTON_UPDATE_IDENTITY': 'BUTTON_ADD_IDENTITY'));
+ }, this);
+
+ Knoin.constructorEnd(this);
+}
+
+Utils.extendAsViewModel('PopupsIdentityViewModel', PopupsIdentityViewModel);
+
+PopupsIdentityViewModel.prototype.clearPopup = function ()
+{
+ this.id = '';
+ this.edit(false);
+ this.owner(false);
+
+ this.name('');
+ this.email('');
+ this.replyTo('');
+ this.bcc('');
+
+ this.email.hasError(false);
+ this.replyTo.hasError(false);
+ this.bcc.hasError(false);
+
+ this.submitRequest(false);
+ this.submitError('');
+};
+
+/**
+ * @param {?IdentityModel} oIdentity
+ */
+PopupsIdentityViewModel.prototype.onShow = function (oIdentity)
+{
+ this.clearPopup();
+
+ if (oIdentity)
+ {
+ this.edit(true);
+
+ this.id = oIdentity.id;
+ this.name(oIdentity.name());
+ this.email(oIdentity.email());
+ this.replyTo(oIdentity.replyTo());
+ this.bcc(oIdentity.bcc());
+
+ this.owner(this.id === RL.data().accountEmail());
+ }
+};
+
+PopupsIdentityViewModel.prototype.onFocus = function ()
+{
+ if (!this.owner())
+ {
+ this.email.focused(true);
+ }
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+function PopupsLanguagesViewModel()
+{
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsLanguages');
+
+ this.exp = ko.observable(false);
+
+ this.languages = ko.computed(function () {
+ return _.map(RL.data().languages(), function (sLanguage) {
+ return {
+ 'key': sLanguage,
+ 'selected': ko.observable(false),
+ 'fullName': Utils.convertLangName(sLanguage)
+ };
+ });
+ });
+
+ RL.data().mainLanguage.subscribe(function () {
+ this.resetMainLanguage();
+ }, this);
+
+ Knoin.constructorEnd(this);
+}
+
+Utils.extendAsViewModel('PopupsLanguagesViewModel', PopupsLanguagesViewModel);
+
+PopupsLanguagesViewModel.prototype.languageEnName = function (sLanguage)
+{
+ return Utils.convertLangName(sLanguage, true);
+};
+
+PopupsLanguagesViewModel.prototype.resetMainLanguage = function ()
+{
+ var sCurrent = RL.data().mainLanguage();
+ _.each(this.languages(), function (oItem) {
+ oItem['selected'](oItem['key'] === sCurrent);
+ });
+};
+
+PopupsLanguagesViewModel.prototype.onShow = function ()
+{
+ this.exp(true);
+
+ this.resetMainLanguage();
+};
+
+PopupsLanguagesViewModel.prototype.onHide = function ()
+{
+ this.exp(false);
+};
+
+PopupsLanguagesViewModel.prototype.changeLanguage = function (sLang)
+{
+ RL.data().mainLanguage(sLang);
+ this.cancelCommand();
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+function PopupsTwoFactorTestViewModel()
+{
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsTwoFactorTest');
+
+ var self = this;
+
+ this.code = ko.observable('');
+ this.code.focused = ko.observable(false);
+ this.code.status = ko.observable(null);
+
+ this.testing = ko.observable(false);
+
+ // commands
+ this.testCode = Utils.createCommand(this, function () {
+
+ this.testing(true);
+ RL.remote().testTwoFactor(function (sResult, oData) {
+
+ self.testing(false);
+ self.code.status(Enums.StorageResultType.Success === sResult && oData && oData.Result ? true : false);
+
+ }, this.code());
+
+ }, function () {
+ return '' !== this.code() && !this.testing();
+ });
+
+ Knoin.constructorEnd(this);
+}
+
+Utils.extendAsViewModel('PopupsTwoFactorTestViewModel', PopupsTwoFactorTestViewModel);
+
+PopupsTwoFactorTestViewModel.prototype.clearPopup = function ()
+{
+ this.code('');
+ this.code.focused(false);
+ this.code.status(null);
+ this.testing(false);
+};
+
+PopupsTwoFactorTestViewModel.prototype.onShow = function ()
+{
+ this.clearPopup();
+};
+
+PopupsTwoFactorTestViewModel.prototype.onFocus = function ()
+{
+ this.code.focused(true);
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+function PopupsAskViewModel()
+{
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsAsk');
+
+ this.askDesc = ko.observable('');
+ this.yesButton = ko.observable('');
+ this.noButton = ko.observable('');
+
+ this.yesFocus = ko.observable(false);
+ this.noFocus = ko.observable(false);
+
+ this.fYesAction = null;
+ this.fNoAction = null;
+
+ this.bDisabeCloseOnEsc = true;
+ this.sDefaultKeyScope = Enums.KeyState.PopupAsk;
+
+ Knoin.constructorEnd(this);
+}
+
+Utils.extendAsViewModel('PopupsAskViewModel', PopupsAskViewModel);
+
+PopupsAskViewModel.prototype.clearPopup = function ()
+{
+ this.askDesc('');
+ this.yesButton(Utils.i18n('POPUPS_ASK/BUTTON_YES'));
+ this.noButton(Utils.i18n('POPUPS_ASK/BUTTON_NO'));
+
+ this.yesFocus(false);
+ this.noFocus(false);
+
+ this.fYesAction = null;
+ this.fNoAction = null;
+};
+
+PopupsAskViewModel.prototype.yesClick = function ()
+{
+ this.cancelCommand();
+
+ if (Utils.isFunc(this.fYesAction))
+ {
+ this.fYesAction.call(null);
+ }
+};
+
+PopupsAskViewModel.prototype.noClick = function ()
+{
+ this.cancelCommand();
+
+ if (Utils.isFunc(this.fNoAction))
+ {
+ this.fNoAction.call(null);
+ }
+};
+
+/**
+ * @param {string} sAskDesc
+ * @param {Function=} fYesFunc
+ * @param {Function=} fNoFunc
+ * @param {string=} sYesButton
+ * @param {string=} sNoButton
+ */
+PopupsAskViewModel.prototype.onShow = function (sAskDesc, fYesFunc, fNoFunc, sYesButton, sNoButton)
+{
+ this.clearPopup();
+
+ this.fYesAction = fYesFunc || null;
+ this.fNoAction = fNoFunc || null;
+
+ this.askDesc(sAskDesc || '');
+ if (sYesButton)
+ {
+ this.yesButton(sYesButton);
+ }
+
+ if (sYesButton)
+ {
+ this.yesButton(sNoButton);
+ }
+};
+
+PopupsAskViewModel.prototype.onFocus = function ()
+{
+ this.yesFocus(true);
+};
+
+PopupsAskViewModel.prototype.onBuild = function ()
+{
+ key('tab, shift+tab, right, left', Enums.KeyState.PopupAsk, _.bind(function () {
+ if (this.yesFocus())
+ {
+ this.noFocus(true);
+ }
+ else
+ {
+ this.yesFocus(true);
+ }
+ return false;
+ }, this));
+
+ key('esc', Enums.KeyState.PopupAsk, _.bind(function () {
+ this.noClick();
+ return false;
+ }, this));
+};
+
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+function PopupsKeyboardShortcutsHelpViewModel()
+{
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsKeyboardShortcutsHelp');
+
+ this.sDefaultKeyScope = Enums.KeyState.PopupKeyboardShortcutsHelp;
+
+ Knoin.constructorEnd(this);
+}
+
+Utils.extendAsViewModel('PopupsKeyboardShortcutsHelpViewModel', PopupsKeyboardShortcutsHelpViewModel);
+
+PopupsKeyboardShortcutsHelpViewModel.prototype.onBuild = function (oDom)
+{
+ key('tab, shift+tab, left, right', Enums.KeyState.PopupKeyboardShortcutsHelp, _.bind(function (event, handler) {
+ if (event && handler)
+ {
+ var
+ $tabs = oDom.find('.nav.nav-tabs > li'),
+ bNext = handler && ('tab' === handler.shortcut || 'right' === handler.shortcut),
+ iIndex = $tabs.index($tabs.filter('.active'))
+ ;
+
+ if (!bNext && iIndex > 0)
+ {
+ iIndex--;
+ }
+ else if (bNext && iIndex < $tabs.length - 1)
+ {
+ iIndex++;
+ }
+ else
+ {
+ iIndex = bNext ? 0 : $tabs.length - 1;
+ }
+
+ $tabs.eq(iIndex).find('a[data-toggle="tab"]').tab('show');
+ return false;
+ }
+ }, this));
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+function PopupsFilterViewModel()
+{
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsFilter');
+
+ this.filter = ko.observable(null);
+
+ this.selectedFolderValue = ko.observable(Consts.Values.UnuseOptionValue);
+ this.folderSelectList = RL.data().folderMenuForMove;
+ this.defautOptionsAfterRender = Utils.defautOptionsAfterRender;
+
+ Knoin.constructorEnd(this);
+}
+
+Utils.extendAsViewModel('PopupsFilterViewModel', PopupsFilterViewModel);
+
+PopupsFilterViewModel.prototype.clearPopup = function ()
+{
+
+};
+
+PopupsFilterViewModel.prototype.onShow = function (oFilter)
+{
+ this.clearPopup();
+
+ this.filter(oFilter);
+};
+
+PopupsFilterViewModel.prototype.onFocus = function ()
+{
+
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+function LoginViewModel()
+{
+ KnoinAbstractViewModel.call(this, 'Center', 'Login');
+
+ var oData = RL.data();
+
+ this.email = ko.observable('');
+ this.password = ko.observable('');
+ this.signMe = ko.observable(false);
+
+ this.additionalCode = ko.observable('');
+ this.additionalCode.error = ko.observable(false);
+ this.additionalCode.focused = ko.observable(false);
+ this.additionalCode.visibility = ko.observable(false);
+ this.additionalCodeSignMe = ko.observable(false);
+
+ this.logoImg = Utils.trim(RL.settingsGet('LoginLogo'));
+ this.loginDescription = Utils.trim(RL.settingsGet('LoginDescription'));
+ this.logoCss = Utils.trim(RL.settingsGet('LoginCss'));
+
+ this.emailError = ko.observable(false);
+ this.passwordError = ko.observable(false);
+
+ this.emailFocus = ko.observable(false);
+ this.submitFocus = ko.observable(false);
+
+ this.email.subscribe(function () {
+ this.emailError(false);
+ this.additionalCode('');
+ this.additionalCode.visibility(false);
+ }, this);
+
+ this.password.subscribe(function () {
+ this.passwordError(false);
+ }, this);
+
+ this.additionalCode.subscribe(function () {
+ this.additionalCode.error(false);
+ }, this);
+
+ this.additionalCode.visibility.subscribe(function () {
+ this.additionalCode.error(false);
+ }, this);
+
+ this.submitRequest = ko.observable(false);
+ this.submitError = ko.observable('');
+
+ this.allowLanguagesOnLogin = oData.allowLanguagesOnLogin;
+
+ this.langRequest = ko.observable(false);
+ this.mainLanguage = oData.mainLanguage;
+ this.bSendLanguage = false;
+
+ this.mainLanguageFullName = ko.computed(function () {
+ return Utils.convertLangName(this.mainLanguage());
+ }, this);
+
+ this.signMeType = ko.observable(Enums.LoginSignMeType.Unused);
+
+ this.signMeType.subscribe(function (iValue) {
+ this.signMe(Enums.LoginSignMeType.DefaultOn === iValue);
+ }, this);
+
+ this.signMeVisibility = ko.computed(function () {
+ return Enums.LoginSignMeType.Unused !== this.signMeType();
+ }, this);
+
+ this.submitCommand = Utils.createCommand(this, function () {
+
+ Utils.triggerAutocompleteInputChange();
+
+ this.emailError('' === Utils.trim(this.email()));
+ this.passwordError('' === Utils.trim(this.password()));
+
+ if (this.additionalCode.visibility())
+ {
+ this.additionalCode.error('' === Utils.trim(this.additionalCode()));
+ }
+
+ if (this.emailError() || this.passwordError() || this.additionalCode.error())
+ {
+ return false;
+ }
+
+ this.submitRequest(true);
+
+ var
+ sPassword = this.password(),
+
+ fLoginRequest = _.bind(function (sPassword) {
+
+ RL.remote().login(_.bind(function (sResult, oData) {
+
+ if (Enums.StorageResultType.Success === sResult && oData && 'Login' === oData.Action)
+ {
+ if (oData.Result)
+ {
+ if (oData.TwoFactorAuth)
+ {
+ this.additionalCode('');
+ this.additionalCode.visibility(true);
+ this.additionalCode.focused(true);
+
+ this.submitRequest(false);
+ }
+ else
+ {
+ RL.loginAndLogoutReload();
+ }
+ }
+ else if (oData.ErrorCode)
+ {
+ this.submitRequest(false);
+ this.submitError(Utils.getNotification(oData.ErrorCode));
+
+ if ('' === this.submitError())
+ {
+ this.submitError(Utils.getNotification(Enums.Notification.UnknownError));
+ }
+ }
+ else
+ {
+ this.submitRequest(false);
+ }
+ }
+ else
+ {
+ this.submitRequest(false);
+ this.submitError(Utils.getNotification(Enums.Notification.UnknownError));
+ }
+
+ }, this), this.email(), '', sPassword, !!this.signMe(),
+ this.bSendLanguage ? this.mainLanguage() : '',
+ this.additionalCode.visibility() ? this.additionalCode() : '',
+ this.additionalCode.visibility() ? !!this.additionalCodeSignMe() : false
+ );
+
+ }, this)
+ ;
+
+ if (!!RL.settingsGet('UseRsaEncryption') && Utils.rsaEncode.supported)
+ {
+ RL.remote().getPublicKey(_.bind(function (sResult, oData) {
+
+ var bRequest = false;
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result &&
+ Utils.isArray(oData.Result) && oData.Result[0] && oData.Result[1] && oData.Result[2])
+ {
+ var sEncryptedPassword = Utils.rsaEncode(sPassword, oData.Result[0], oData.Result[1], oData.Result[2]);
+ if (sEncryptedPassword)
+ {
+ fLoginRequest(sEncryptedPassword);
+ bRequest = true;
+ }
+ }
+
+ if (!bRequest)
+ {
+ this.submitRequest(false);
+ this.submitError(Utils.getNotification(Enums.Notification.UnknownError));
+ }
+
+ }, this));
+ }
+ else
+ {
+ fLoginRequest(sPassword);
+ }
+
+ return true;
+
+ }, function () {
+ return !this.submitRequest();
+ });
+
+ this.facebookLoginEnabled = ko.observable(false);
+
+ this.facebookCommand = Utils.createCommand(this, function () {
+
+ window.open(RL.link().socialFacebook(), 'Facebook', 'left=200,top=100,width=650,height=335,menubar=no,status=no,resizable=yes,scrollbars=yes');
+ return true;
+
+ }, function () {
+ return !this.submitRequest() && this.facebookLoginEnabled();
+ });
+
+ this.googleLoginEnabled = ko.observable(false);
+
+ this.googleCommand = Utils.createCommand(this, function () {
+
+ window.open(RL.link().socialGoogle(), 'Google', 'left=200,top=100,width=650,height=335,menubar=no,status=no,resizable=yes,scrollbars=yes');
+ return true;
+
+ }, function () {
+ return !this.submitRequest() && this.googleLoginEnabled();
+ });
+
+ this.twitterLoginEnabled = ko.observable(false);
+
+ this.twitterCommand = Utils.createCommand(this, function () {
+
+ window.open(RL.link().socialTwitter(), 'Twitter', 'left=200,top=100,width=650,height=335,menubar=no,status=no,resizable=yes,scrollbars=yes');
+ return true;
+
+ }, function () {
+ return !this.submitRequest() && this.twitterLoginEnabled();
+ });
+
+ this.socialLoginEnabled = ko.computed(function () {
+
+ var
+ bF = this.facebookLoginEnabled(),
+ bG = this.googleLoginEnabled(),
+ bT = this.twitterLoginEnabled()
+ ;
+
+ return bF || bG || bT;
+ }, this);
+
+ Knoin.constructorEnd(this);
+}
+
+Utils.extendAsViewModel('LoginViewModel', LoginViewModel);
+
+LoginViewModel.prototype.onShow = function ()
+{
+ kn.routeOff();
+
+ _.delay(_.bind(function () {
+ if ('' !== this.email() && '' !== this.password())
+ {
+ this.submitFocus(true);
+ }
+ else
+ {
+ this.emailFocus(true);
+ }
+
+ if (RL.settingsGet('UserLanguage'))
+ {
+ $.cookie('rllang', RL.data().language(), {'expires': 30});
+ }
+
+ }, this), 100);
+};
+
+LoginViewModel.prototype.onHide = function ()
+{
+ this.submitFocus(false);
+ this.emailFocus(false);
+};
+
+LoginViewModel.prototype.onBuild = function ()
+{
+ var
+ self = this,
+ sJsHash = RL.settingsGet('JsHash'),
+ fSocial = function (iErrorCode) {
+ iErrorCode = Utils.pInt(iErrorCode);
+ if (0 === iErrorCode)
+ {
+ self.submitRequest(true);
+ RL.loginAndLogoutReload();
+ }
+ else
+ {
+ self.submitError(Utils.getNotification(iErrorCode));
+ }
+ }
+ ;
+
+ this.facebookLoginEnabled(!!RL.settingsGet('AllowFacebookSocial'));
+ this.twitterLoginEnabled(!!RL.settingsGet('AllowTwitterSocial'));
+ this.googleLoginEnabled(!!RL.settingsGet('AllowGoogleSocial'));
+
+ switch ((RL.settingsGet('SignMe') || 'unused').toLowerCase())
+ {
+ case Enums.LoginSignMeTypeAsString.DefaultOff:
+ this.signMeType(Enums.LoginSignMeType.DefaultOff);
+ break;
+ case Enums.LoginSignMeTypeAsString.DefaultOn:
+ this.signMeType(Enums.LoginSignMeType.DefaultOn);
+ break;
+ default:
+ case Enums.LoginSignMeTypeAsString.Unused:
+ this.signMeType(Enums.LoginSignMeType.Unused);
+ break;
+ }
+
+ this.email(RL.data().devEmail);
+ this.password(RL.data().devPassword);
+
+ if (this.googleLoginEnabled())
+ {
+ window['rl_' + sJsHash + '_google_login_service'] = fSocial;
+ }
+
+ if (this.facebookLoginEnabled())
+ {
+ window['rl_' + sJsHash + '_facebook_login_service'] = fSocial;
+ }
+
+ if (this.twitterLoginEnabled())
+ {
+ window['rl_' + sJsHash + '_twitter_login_service'] = fSocial;
+ }
+
+ _.delay(function () {
+ RL.data().language.subscribe(function (sValue) {
+ self.langRequest(true);
+ $.ajax({
+ 'url': RL.link().langLink(sValue),
+ 'dataType': 'script',
+ 'cache': true
+ }).done(function() {
+ self.bSendLanguage = true;
+ Utils.i18nToDoc();
+ $.cookie('rllang', RL.data().language(), {'expires': 30});
+ }).always(function() {
+ self.langRequest(false);
+ });
+ });
+ }, 50);
+
+ Utils.triggerAutocompleteInputChange(true);
+
+};
+
+LoginViewModel.prototype.submitForm = function ()
+{
+ this.submitCommand();
+};
+
+LoginViewModel.prototype.selectLanguage = function ()
+{
+ kn.showScreenPopup(PopupsLanguagesViewModel);
+};
+
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+function AbstractSystemDropDownViewModel()
+{
+ KnoinAbstractViewModel.call(this, 'Right', 'SystemDropDown');
+
+ var oData = RL.data();
+
+ this.accounts = oData.accounts;
+ this.accountEmail = oData.accountEmail;
+ this.accountsLoading = oData.accountsLoading;
+
+ this.accountMenuDropdownTrigger = ko.observable(false);
+
+ this.capaAdditionalAccounts = RL.capa(Enums.Capa.AdditionalAccounts);
+
+ this.loading = ko.computed(function () {
+ return this.accountsLoading();
+ }, this);
+
+ this.accountClick = _.bind(this.accountClick, this);
+}
+
+_.extend(AbstractSystemDropDownViewModel.prototype, KnoinAbstractViewModel.prototype);
+
+AbstractSystemDropDownViewModel.prototype.accountClick = function (oAccount, oEvent)
+{
+ if (oAccount && oEvent && !Utils.isUnd(oEvent.which) && 1 === oEvent.which)
+ {
+ var self = this;
+ this.accountsLoading(true);
+ _.delay(function () {
+ self.accountsLoading(false);
+ }, 1000);
+ }
+
+ return true;
+};
+
+AbstractSystemDropDownViewModel.prototype.emailTitle = function ()
+{
+ return RL.data().accountEmail();
+};
+
+AbstractSystemDropDownViewModel.prototype.settingsClick = function ()
+{
+ kn.setHash(RL.link().settings());
+};
+
+AbstractSystemDropDownViewModel.prototype.settingsHelp = function ()
+{
+ kn.showScreenPopup(PopupsKeyboardShortcutsHelpViewModel);
+};
+
+AbstractSystemDropDownViewModel.prototype.addAccountClick = function ()
+{
+ if (this.capaAdditionalAccounts)
+ {
+ kn.showScreenPopup(PopupsAddAccountViewModel);
+ }
+};
+
+AbstractSystemDropDownViewModel.prototype.logoutClick = function ()
+{
+ RL.remote().logout(function () {
+ if (window.__rlah_clear)
+ {
+ window.__rlah_clear();
+ }
+
+ RL.loginAndLogoutReload(true, RL.settingsGet('ParentEmail') && 0 < RL.settingsGet('ParentEmail').length);
+ });
+};
+
+AbstractSystemDropDownViewModel.prototype.onBuild = function ()
+{
+ var self = this;
+ key('`', [Enums.KeyState.MessageList, Enums.KeyState.MessageView, Enums.KeyState.Settings], function () {
+ if (self.viewModelVisibility())
+ {
+ self.accountMenuDropdownTrigger(true);
+ }
+ });
+
+ // shortcuts help
+ key('shift+/', [Enums.KeyState.MessageList, Enums.KeyState.MessageView, Enums.KeyState.Settings], function () {
+ if (self.viewModelVisibility())
+ {
+ kn.showScreenPopup(PopupsKeyboardShortcutsHelpViewModel);
+ return false;
+ }
+ });
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends AbstractSystemDropDownViewModel
+ */
+function MailBoxSystemDropDownViewModel()
+{
+ AbstractSystemDropDownViewModel.call(this);
+ Knoin.constructorEnd(this);
+}
+
+Utils.extendAsViewModel('MailBoxSystemDropDownViewModel', MailBoxSystemDropDownViewModel, AbstractSystemDropDownViewModel);
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends AbstractSystemDropDownViewModel
+ */
+function SettingsSystemDropDownViewModel()
+{
+ AbstractSystemDropDownViewModel.call(this);
+ Knoin.constructorEnd(this);
+}
+
+Utils.extendAsViewModel('SettingsSystemDropDownViewModel', SettingsSystemDropDownViewModel, AbstractSystemDropDownViewModel);
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+function MailBoxFolderListViewModel()
+{
+ KnoinAbstractViewModel.call(this, 'Left', 'MailFolderList');
+
+ var oData = RL.data();
+
+ this.oContentVisible = null;
+ this.oContentScrollable = null;
+
+ this.messageList = oData.messageList;
+ this.folderList = oData.folderList;
+ this.folderListSystem = oData.folderListSystem;
+ this.foldersChanging = oData.foldersChanging;
+
+ this.leftPanelDisabled = oData.leftPanelDisabled;
+
+ this.iDropOverTimer = 0;
+
+ this.allowContacts = !!RL.settingsGet('ContactsIsAllowed');
+
+ Knoin.constructorEnd(this);
+}
+
+Utils.extendAsViewModel('MailBoxFolderListViewModel', MailBoxFolderListViewModel);
+
+MailBoxFolderListViewModel.prototype.onBuild = function (oDom)
+{
+ this.oContentVisible = $('.b-content', oDom);
+ this.oContentScrollable = $('.content', this.oContentVisible);
+
+ var self = this;
+
+ oDom
+ .on('click', '.b-folders .e-item .e-link .e-collapsed-sign', function (oEvent) {
+
+ var
+ oFolder = ko.dataFor(this),
+ bCollapsed = false
+ ;
+
+ if (oFolder && oEvent)
+ {
+ bCollapsed = oFolder.collapsed();
+ Utils.setExpandedFolder(oFolder.fullNameHash, bCollapsed);
+
+ oFolder.collapsed(!bCollapsed);
+ oEvent.preventDefault();
+ oEvent.stopPropagation();
+ }
+ })
+ .on('click', '.b-folders .e-item .e-link.selectable', function (oEvent) {
+
+ oEvent.preventDefault();
+
+ var
+ oData = RL.data(),
+ oFolder = ko.dataFor(this)
+ ;
+
+ if (oFolder)
+ {
+ if (Enums.Layout.NoPreview === oData.layout())
+ {
+ oData.message(null);
+ }
+
+ if (oFolder.fullNameRaw === oData.currentFolderFullNameRaw())
+ {
+ RL.cache().setFolderHash(oFolder.fullNameRaw, '');
+ }
+
+ kn.setHash(RL.link().mailBox(oFolder.fullNameHash));
+ }
+ })
+ ;
+
+ key('up, down', Enums.KeyState.FolderList, function (event, handler) {
+
+ var
+ iIndex = -1,
+ iKeyCode = handler && 'up' === handler.shortcut ? 38 : 40,
+ $items = $('.b-folders .e-item .e-link:not(.hidden):visible', oDom)
+ ;
+
+ if (event && $items.length)
+ {
+ iIndex = $items.index($items.filter('.focused'));
+ if (-1 < iIndex)
+ {
+ $items.eq(iIndex).removeClass('focused');
+ }
+
+ if (iKeyCode === 38 && iIndex > 0)
+ {
+ iIndex--;
+ }
+ else if (iKeyCode === 40 && iIndex < $items.length - 1)
+ {
+ iIndex++;
+ }
+
+ $items.eq(iIndex).addClass('focused');
+ self.scrollToFocused();
+ }
+
+ return false;
+ });
+
+ key('enter', Enums.KeyState.FolderList, function () {
+ var $items = $('.b-folders .e-item .e-link:not(.hidden).focused', oDom);
+ if ($items.length && $items[0])
+ {
+ self.folderList.focused(false);
+ $items.click();
+ }
+
+ return false;
+ });
+
+ key('space', Enums.KeyState.FolderList, function () {
+ var bCollapsed = true, oFolder = null, $items = $('.b-folders .e-item .e-link:not(.hidden).focused', oDom);
+ if ($items.length && $items[0])
+ {
+ oFolder = ko.dataFor($items[0]);
+ if (oFolder)
+ {
+ bCollapsed = oFolder.collapsed();
+ Utils.setExpandedFolder(oFolder.fullNameHash, bCollapsed);
+ oFolder.collapsed(!bCollapsed);
+ }
+ }
+
+ return false;
+ });
+
+ key('esc, tab, shift+tab, right', Enums.KeyState.FolderList, function () {
+ self.folderList.focused(false);
+ return false;
+ });
+
+ self.folderList.focused.subscribe(function (bValue) {
+ $('.b-folders .e-item .e-link.focused', oDom).removeClass('focused');
+ if (bValue)
+ {
+ $('.b-folders .e-item .e-link.selected', oDom).addClass('focused');
+ }
+ });
+};
+
+MailBoxFolderListViewModel.prototype.messagesDropOver = function (oFolder)
+{
+ window.clearTimeout(this.iDropOverTimer);
+ if (oFolder && oFolder.collapsed())
+ {
+ this.iDropOverTimer = window.setTimeout(function () {
+ oFolder.collapsed(false);
+ Utils.setExpandedFolder(oFolder.fullNameHash, true);
+ Utils.windowResize();
+ }, 500);
+ }
+};
+
+MailBoxFolderListViewModel.prototype.messagesDropOut = function ()
+{
+ window.clearTimeout(this.iDropOverTimer);
+};
+
+MailBoxFolderListViewModel.prototype.scrollToFocused = function ()
+{
+ if (!this.oContentVisible || !this.oContentScrollable)
+ {
+ return false;
+ }
+
+ var
+ iOffset = 20,
+ oFocused = $('.e-item .e-link.focused', this.oContentScrollable),
+ oPos = oFocused.position(),
+ iVisibleHeight = this.oContentVisible.height(),
+ iFocusedHeight = oFocused.outerHeight()
+ ;
+
+ if (oPos && (oPos.top < 0 || oPos.top + iFocusedHeight > iVisibleHeight))
+ {
+ if (oPos.top < 0)
+ {
+ this.oContentScrollable.scrollTop(this.oContentScrollable.scrollTop() + oPos.top - iOffset);
+ }
+ else
+ {
+ this.oContentScrollable.scrollTop(this.oContentScrollable.scrollTop() + oPos.top - iVisibleHeight + iFocusedHeight + iOffset);
+ }
+
+ return true;
+ }
+
+ return false;
+};
+
+/**
+ *
+ * @param {FolderModel} oToFolder
+ * @param {{helper:jQuery}} oUi
+ */
+MailBoxFolderListViewModel.prototype.messagesDrop = function (oToFolder, oUi)
+{
+ if (oToFolder && oUi && oUi.helper)
+ {
+ var
+ sFromFolderFullNameRaw = oUi.helper.data('rl-folder'),
+ bCopy = $html.hasClass('rl-ctrl-key-pressed'),
+ aUids = oUi.helper.data('rl-uids')
+ ;
+
+ if (Utils.isNormal(sFromFolderFullNameRaw) && '' !== sFromFolderFullNameRaw && Utils.isArray(aUids))
+ {
+ RL.moveMessagesToFolder(sFromFolderFullNameRaw, aUids, oToFolder.fullNameRaw, bCopy);
+ }
+ }
+};
+
+MailBoxFolderListViewModel.prototype.composeClick = function ()
+{
+ kn.showScreenPopup(PopupsComposeViewModel);
+};
+
+MailBoxFolderListViewModel.prototype.createFolder = function ()
+{
+ kn.showScreenPopup(PopupsFolderCreateViewModel);
+};
+
+MailBoxFolderListViewModel.prototype.configureFolders = function ()
+{
+ kn.setHash(RL.link().settings('folders'));
+};
+
+MailBoxFolderListViewModel.prototype.contactsClick = function ()
+{
+ if (this.allowContacts)
+ {
+ kn.showScreenPopup(PopupsContactsViewModel);
+ }
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+function MailBoxMessageListViewModel()
+{
+ KnoinAbstractViewModel.call(this, 'Right', 'MailMessageList');
+
+ this.sLastUid = null;
+ this.bPrefetch = false;
+ this.emptySubjectValue = '';
+
+ this.hideDangerousActions = !!RL.settingsGet('HideDangerousActions');
+
+ var oData = RL.data();
+
+ this.popupVisibility = RL.popupVisibility;
+
+ this.message = oData.message;
+ this.messageList = oData.messageList;
+ this.folderList = oData.folderList;
+ this.currentMessage = oData.currentMessage;
+ this.isMessageSelected = oData.isMessageSelected;
+ this.messageListSearch = oData.messageListSearch;
+ this.messageListError = oData.messageListError;
+ this.folderMenuForMove = oData.folderMenuForMove;
+
+ this.useCheckboxesInList = oData.useCheckboxesInList;
+
+ this.mainMessageListSearch = oData.mainMessageListSearch;
+ this.messageListEndFolder = oData.messageListEndFolder;
+
+ this.messageListChecked = oData.messageListChecked;
+ this.messageListCheckedOrSelected = oData.messageListCheckedOrSelected;
+ this.messageListCheckedOrSelectedUidsWithSubMails = oData.messageListCheckedOrSelectedUidsWithSubMails;
+ this.messageListCompleteLoadingThrottle = oData.messageListCompleteLoadingThrottle;
+
+ Utils.initOnStartOrLangChange(function () {
+ this.emptySubjectValue = Utils.i18n('MESSAGE_LIST/EMPTY_SUBJECT_TEXT');
+ }, this);
+
+ this.userQuota = oData.userQuota;
+ this.userUsageSize = oData.userUsageSize;
+ this.userUsageProc = oData.userUsageProc;
+
+ this.moveDropdownTrigger = ko.observable(false);
+ this.moreDropdownTrigger = ko.observable(false);
+
+ // append drag and drop
+ this.dragOver = ko.observable(false).extend({'throttle': 1});
+ this.dragOverEnter = ko.observable(false).extend({'throttle': 1});
+ this.dragOverArea = ko.observable(null);
+ this.dragOverBodyArea = ko.observable(null);
+
+ this.messageListItemTemplate = ko.computed(function () {
+ return Enums.Layout.NoPreview !== oData.layout() ?
+ 'MailMessageListItem' : 'MailMessageListItemNoPreviewPane';
+ });
+
+ this.messageListSearchDesc = ko.computed(function () {
+ var sValue = oData.messageListEndSearch();
+ return '' === sValue ? '' : Utils.i18n('MESSAGE_LIST/SEARCH_RESULT_FOR', {'SEARCH': sValue});
+ });
+
+ this.messageListPagenator = ko.computed(Utils.computedPagenatorHelper(oData.messageListPage, oData.messageListPageCount));
+
+ this.checkAll = ko.computed({
+ 'read': function () {
+ return 0 < RL.data().messageListChecked().length;
+ },
+
+ 'write': function (bValue) {
+ bValue = !!bValue;
+ _.each(RL.data().messageList(), function (oMessage) {
+ oMessage.checked(bValue);
+ });
+ }
+ });
+
+ this.inputMessageListSearchFocus = ko.observable(false);
+
+ this.sLastSearchValue = '';
+ this.inputProxyMessageListSearch = ko.computed({
+ 'read': this.mainMessageListSearch,
+ 'write': function (sValue) {
+ this.sLastSearchValue = sValue;
+ },
+ 'owner': this
+ });
+
+ this.isIncompleteChecked = ko.computed(function () {
+ var
+ iM = RL.data().messageList().length,
+ iC = RL.data().messageListChecked().length
+ ;
+ return 0 < iM && 0 < iC && iM > iC;
+ }, this);
+
+ this.hasMessages = ko.computed(function () {
+ return 0 < this.messageList().length;
+ }, this);
+
+ this.hasCheckedOrSelectedLines = ko.computed(function () {
+ return 0 < this.messageListCheckedOrSelected().length;
+ }, this);
+
+ this.isSpamFolder = ko.computed(function () {
+ return oData.spamFolder() === this.messageListEndFolder() &&
+ '' !== oData.spamFolder();
+ }, this);
+
+ this.isSpamDisabled = ko.computed(function () {
+ return Consts.Values.UnuseOptionValue === oData.spamFolder();
+ }, this);
+
+ this.isTrashFolder = ko.computed(function () {
+ return oData.trashFolder() === this.messageListEndFolder() &&
+ '' !== oData.trashFolder();
+ }, this);
+
+ this.isDraftFolder = ko.computed(function () {
+ return oData.draftFolder() === this.messageListEndFolder() &&
+ '' !== oData.draftFolder();
+ }, this);
+
+ this.isSentFolder = ko.computed(function () {
+ return oData.sentFolder() === this.messageListEndFolder() &&
+ '' !== oData.sentFolder();
+ }, this);
+
+ this.isArchiveFolder = ko.computed(function () {
+ return oData.archiveFolder() === this.messageListEndFolder() &&
+ '' !== oData.archiveFolder();
+ }, this);
+
+ this.isArchiveDisabled = ko.computed(function () {
+ return Consts.Values.UnuseOptionValue === RL.data().archiveFolder();
+ }, this);
+
+ this.canBeMoved = this.hasCheckedOrSelectedLines;
+
+ this.clearCommand = Utils.createCommand(this, function () {
+ kn.showScreenPopup(PopupsFolderClearViewModel, [RL.data().currentFolder()]);
+ });
+
+ this.multyForwardCommand = Utils.createCommand(this, function () {
+ kn.showScreenPopup(PopupsComposeViewModel, [Enums.ComposeType.ForwardAsAttachment, RL.data().messageListCheckedOrSelected()]);
+ }, this.canBeMoved);
+
+ this.deleteWithoutMoveCommand = Utils.createCommand(this, function () {
+ RL.deleteMessagesFromFolder(Enums.FolderType.Trash,
+ RL.data().currentFolderFullNameRaw(),
+ RL.data().messageListCheckedOrSelectedUidsWithSubMails(), false);
+ }, this.canBeMoved);
+
+ this.deleteCommand = Utils.createCommand(this, function () {
+ RL.deleteMessagesFromFolder(Enums.FolderType.Trash,
+ RL.data().currentFolderFullNameRaw(),
+ RL.data().messageListCheckedOrSelectedUidsWithSubMails(), true);
+ }, this.canBeMoved);
+
+ this.archiveCommand = Utils.createCommand(this, function () {
+ RL.deleteMessagesFromFolder(Enums.FolderType.Archive,
+ RL.data().currentFolderFullNameRaw(),
+ RL.data().messageListCheckedOrSelectedUidsWithSubMails(), true);
+ }, this.canBeMoved);
+
+ this.spamCommand = Utils.createCommand(this, function () {
+ RL.deleteMessagesFromFolder(Enums.FolderType.Spam,
+ RL.data().currentFolderFullNameRaw(),
+ RL.data().messageListCheckedOrSelectedUidsWithSubMails(), true);
+ }, this.canBeMoved);
+
+ this.notSpamCommand = Utils.createCommand(this, function () {
+ RL.deleteMessagesFromFolder(Enums.FolderType.NotSpam,
+ RL.data().currentFolderFullNameRaw(),
+ RL.data().messageListCheckedOrSelectedUidsWithSubMails(), true);
+ }, this.canBeMoved);
+
+ this.moveCommand = Utils.createCommand(this, Utils.emptyFunction, this.canBeMoved);
+
+ this.reloadCommand = Utils.createCommand(this, function () {
+ if (!RL.data().messageListCompleteLoadingThrottle())
+ {
+ RL.reloadMessageList(false, true);
+ }
+ });
+
+ this.quotaTooltip = _.bind(this.quotaTooltip, this);
+
+ this.selector = new Selector(this.messageList, this.currentMessage,
+ '.messageListItem .actionHandle', '.messageListItem.selected', '.messageListItem .checkboxMessage',
+ '.messageListItem.focused');
+
+ this.selector.on('onItemSelect', _.bind(function (oMessage) {
+ if (oMessage)
+ {
+ oData.message(oData.staticMessageList.populateByMessageListItem(oMessage));
+ this.populateMessageBody(oData.message());
+
+ if (Enums.Layout.NoPreview === oData.layout())
+ {
+ kn.setHash(RL.link().messagePreview(), true);
+ oData.message.focused(true);
+ }
+ }
+ else
+ {
+ oData.message(null);
+ }
+ }, this));
+
+ this.selector.on('onItemGetUid', function (oMessage) {
+ return oMessage ? oMessage.generateUid() : '';
+ });
+
+ oData.messageListEndHash.subscribe(function () {
+ this.selector.scrollToTop();
+ }, this);
+
+ oData.layout.subscribe(function (mValue) {
+ this.selector.autoSelect(Enums.Layout.NoPreview !== mValue);
+ }, this);
+
+ oData.layout.valueHasMutated();
+
+ RL
+ .sub('mailbox.message-list.selector.go-down', function () {
+ this.selector.goDown(true);
+ }, this)
+ .sub('mailbox.message-list.selector.go-up', function () {
+ this.selector.goUp(true);
+ }, this)
+ ;
+
+ Knoin.constructorEnd(this);
+}
+
+Utils.extendAsViewModel('MailBoxMessageListViewModel', MailBoxMessageListViewModel);
+
+/**
+ * @type {string}
+ */
+MailBoxMessageListViewModel.prototype.emptySubjectValue = '';
+
+MailBoxMessageListViewModel.prototype.searchEnterAction = function ()
+{
+ this.mainMessageListSearch(this.sLastSearchValue);
+ this.inputMessageListSearchFocus(false);
+};
+
+/**
+ * @returns {string}
+ */
+MailBoxMessageListViewModel.prototype.printableMessageCountForDeletion = function ()
+{
+ var iCnt = this.messageListCheckedOrSelectedUidsWithSubMails().length;
+ return 1 < iCnt ? ' (' + (100 > iCnt ? iCnt : '99+') + ')' : '';
+};
+
+MailBoxMessageListViewModel.prototype.cancelSearch = function ()
+{
+ this.mainMessageListSearch('');
+ this.inputMessageListSearchFocus(false);
+};
+
+/**
+ * @param {string} sToFolderFullNameRaw
+ * @return {boolean}
+ */
+MailBoxMessageListViewModel.prototype.moveSelectedMessagesToFolder = function (sToFolderFullNameRaw, bCopy)
+{
+ if (this.canBeMoved())
+ {
+ RL.moveMessagesToFolder(
+ RL.data().currentFolderFullNameRaw(),
+ RL.data().messageListCheckedOrSelectedUidsWithSubMails(), sToFolderFullNameRaw, bCopy);
+ }
+
+ return false;
+};
+
+MailBoxMessageListViewModel.prototype.dragAndDronHelper = function (oMessageListItem)
+{
+ if (oMessageListItem)
+ {
+ oMessageListItem.checked(true);
+ }
+
+ var
+ oEl = Utils.draggeblePlace(),
+ aUids = RL.data().messageListCheckedOrSelectedUidsWithSubMails()
+ ;
+
+ oEl.data('rl-folder', RL.data().currentFolderFullNameRaw());
+ oEl.data('rl-uids', aUids);
+ oEl.find('.text').text('' + aUids.length);
+
+ _.defer(function () {
+ var aUids = RL.data().messageListCheckedOrSelectedUidsWithSubMails();
+
+ oEl.data('rl-uids', aUids);
+ oEl.find('.text').text('' + aUids.length);
+ });
+
+ return oEl;
+};
+
+/**
+ * @param {string} sResult
+ * @param {AjaxJsonDefaultResponse} oData
+ * @param {boolean} bCached
+ */
+MailBoxMessageListViewModel.prototype.onMessageResponse = function (sResult, oData, bCached)
+{
+ var oRainLoopData = RL.data();
+
+ oRainLoopData.hideMessageBodies();
+ oRainLoopData.messageLoading(false);
+
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ {
+ oRainLoopData.setMessage(oData, bCached);
+ }
+ else if (Enums.StorageResultType.Unload === sResult)
+ {
+ oRainLoopData.message(null);
+ oRainLoopData.messageError('');
+ }
+ else if (Enums.StorageResultType.Abort !== sResult)
+ {
+ oRainLoopData.message(null);
+ oRainLoopData.messageError((oData && oData.ErrorCode ?
+ Utils.getNotification(oData.ErrorCode) :
+ Utils.getNotification(Enums.Notification.UnknownError)));
+ }
+};
+
+MailBoxMessageListViewModel.prototype.populateMessageBody = function (oMessage)
+{
+ if (oMessage)
+ {
+ if (RL.remote().message(this.onMessageResponse, oMessage.folderFullNameRaw, oMessage.uid))
+ {
+ RL.data().messageLoading(true);
+ }
+ else
+ {
+ Utils.log('Error: Unknown message request: ' + oMessage.folderFullNameRaw + ' ~ ' + oMessage.uid + ' [e-101]');
+ }
+ }
+};
+
+/**
+ * @param {string} sFolderFullNameRaw
+ * @param {number} iSetAction
+ * @param {Array=} aMessages = null
+ */
+MailBoxMessageListViewModel.prototype.setAction = function (sFolderFullNameRaw, iSetAction, aMessages)
+{
+ var
+ aUids = [],
+ oFolder = null,
+ oCache = RL.cache(),
+ iAlreadyUnread = 0
+ ;
+
+ if (Utils.isUnd(aMessages))
+ {
+ aMessages = RL.data().messageListChecked();
+ }
+
+ aUids = _.map(aMessages, function (oMessage) {
+ return oMessage.uid;
+ });
+
+ if ('' !== sFolderFullNameRaw && 0 < aUids.length)
+ {
+ switch (iSetAction) {
+ case Enums.MessageSetAction.SetSeen:
+ _.each(aMessages, function (oMessage) {
+ if (oMessage.unseen())
+ {
+ iAlreadyUnread++;
+ }
+
+ oMessage.unseen(false);
+ oCache.storeMessageFlagsToCache(oMessage);
+ });
+
+ oFolder = oCache.getFolderFromCacheList(sFolderFullNameRaw);
+ if (oFolder)
+ {
+ oFolder.messageCountUnread(oFolder.messageCountUnread() - iAlreadyUnread);
+ }
+
+ RL.remote().messageSetSeen(Utils.emptyFunction, sFolderFullNameRaw, aUids, true);
+ break;
+ case Enums.MessageSetAction.UnsetSeen:
+ _.each(aMessages, function (oMessage) {
+ if (oMessage.unseen())
+ {
+ iAlreadyUnread++;
+ }
+
+ oMessage.unseen(true);
+ oCache.storeMessageFlagsToCache(oMessage);
+ });
+
+ oFolder = oCache.getFolderFromCacheList(sFolderFullNameRaw);
+ if (oFolder)
+ {
+ oFolder.messageCountUnread(oFolder.messageCountUnread() - iAlreadyUnread + aUids.length);
+ }
+ RL.remote().messageSetSeen(Utils.emptyFunction, sFolderFullNameRaw, aUids, false);
+ break;
+ case Enums.MessageSetAction.SetFlag:
+ _.each(aMessages, function (oMessage) {
+ oMessage.flagged(true);
+ oCache.storeMessageFlagsToCache(oMessage);
+ });
+ RL.remote().messageSetFlagged(Utils.emptyFunction, sFolderFullNameRaw, aUids, true);
+ break;
+ case Enums.MessageSetAction.UnsetFlag:
+ _.each(aMessages, function (oMessage) {
+ oMessage.flagged(false);
+ oCache.storeMessageFlagsToCache(oMessage);
+ });
+ RL.remote().messageSetFlagged(Utils.emptyFunction, sFolderFullNameRaw, aUids, false);
+ break;
+ }
+
+ RL.reloadFlagsCurrentMessageListAndMessageFromCache();
+ }
+};
+
+/**
+ * @param {string} sFolderFullNameRaw
+ * @param {number} iSetAction
+ */
+MailBoxMessageListViewModel.prototype.setActionForAll = function (sFolderFullNameRaw, iSetAction)
+{
+ var
+ oFolder = null,
+ aMessages = RL.data().messageList(),
+ oCache = RL.cache()
+ ;
+
+ if ('' !== sFolderFullNameRaw)
+ {
+ oFolder = oCache.getFolderFromCacheList(sFolderFullNameRaw);
+
+ if (oFolder)
+ {
+ switch (iSetAction) {
+ case Enums.MessageSetAction.SetSeen:
+ oFolder = oCache.getFolderFromCacheList(sFolderFullNameRaw);
+ if (oFolder)
+ {
+ _.each(aMessages, function (oMessage) {
+ oMessage.unseen(false);
+ });
+
+ oFolder.messageCountUnread(0);
+ oCache.clearMessageFlagsFromCacheByFolder(sFolderFullNameRaw);
+ }
+
+ RL.remote().messageSetSeenToAll(Utils.emptyFunction, sFolderFullNameRaw, true);
+ break;
+ case Enums.MessageSetAction.UnsetSeen:
+ oFolder = oCache.getFolderFromCacheList(sFolderFullNameRaw);
+ if (oFolder)
+ {
+ _.each(aMessages, function (oMessage) {
+ oMessage.unseen(true);
+ });
+
+ oFolder.messageCountUnread(oFolder.messageCountAll());
+ oCache.clearMessageFlagsFromCacheByFolder(sFolderFullNameRaw);
+ }
+ RL.remote().messageSetSeenToAll(Utils.emptyFunction, sFolderFullNameRaw, false);
+ break;
+ }
+
+ RL.reloadFlagsCurrentMessageListAndMessageFromCache();
+ }
+ }
+};
+
+MailBoxMessageListViewModel.prototype.listSetSeen = function ()
+{
+ this.setAction(RL.data().currentFolderFullNameRaw(), Enums.MessageSetAction.SetSeen, RL.data().messageListCheckedOrSelected());
+};
+
+MailBoxMessageListViewModel.prototype.listSetAllSeen = function ()
+{
+ this.setActionForAll(RL.data().currentFolderFullNameRaw(), Enums.MessageSetAction.SetSeen);
+};
+
+MailBoxMessageListViewModel.prototype.listUnsetSeen = function ()
+{
+ this.setAction(RL.data().currentFolderFullNameRaw(), Enums.MessageSetAction.UnsetSeen, RL.data().messageListCheckedOrSelected());
+};
+
+MailBoxMessageListViewModel.prototype.listSetFlags = function ()
+{
+ this.setAction(RL.data().currentFolderFullNameRaw(), Enums.MessageSetAction.SetFlag, RL.data().messageListCheckedOrSelected());
+};
+
+MailBoxMessageListViewModel.prototype.listUnsetFlags = function ()
+{
+ this.setAction(RL.data().currentFolderFullNameRaw(), Enums.MessageSetAction.UnsetFlag, RL.data().messageListCheckedOrSelected());
+};
+
+MailBoxMessageListViewModel.prototype.flagMessages = function (oCurrentMessage)
+{
+ var
+ aChecked = this.messageListCheckedOrSelected(),
+ aCheckedUids = []
+ ;
+
+ if (oCurrentMessage)
+ {
+ if (0 < aChecked.length)
+ {
+ aCheckedUids = _.map(aChecked, function (oMessage) {
+ return oMessage.uid;
+ });
+ }
+
+ if (0 < aCheckedUids.length && -1 < Utils.inArray(oCurrentMessage.uid, aCheckedUids))
+ {
+ this.setAction(oCurrentMessage.folderFullNameRaw, oCurrentMessage.flagged() ?
+ Enums.MessageSetAction.UnsetFlag : Enums.MessageSetAction.SetFlag, aChecked);
+ }
+ else
+ {
+ this.setAction(oCurrentMessage.folderFullNameRaw, oCurrentMessage.flagged() ?
+ Enums.MessageSetAction.UnsetFlag : Enums.MessageSetAction.SetFlag, [oCurrentMessage]);
+ }
+ }
+};
+
+MailBoxMessageListViewModel.prototype.flagMessagesFast = function (bFlag)
+{
+ var
+ aChecked = this.messageListCheckedOrSelected(),
+ aFlagged = []
+ ;
+
+ if (0 < aChecked.length)
+ {
+ aFlagged = _.filter(aChecked, function (oMessage) {
+ return oMessage.flagged();
+ });
+
+ if (Utils.isUnd(bFlag))
+ {
+ this.setAction(aChecked[0].folderFullNameRaw,
+ aChecked.length === aFlagged.length ? Enums.MessageSetAction.UnsetFlag : Enums.MessageSetAction.SetFlag, aChecked);
+ }
+ else
+ {
+ this.setAction(aChecked[0].folderFullNameRaw,
+ !bFlag ? Enums.MessageSetAction.UnsetFlag : Enums.MessageSetAction.SetFlag, aChecked);
+ }
+ }
+};
+
+MailBoxMessageListViewModel.prototype.seenMessagesFast = function (bSeen)
+{
+ var
+ aChecked = this.messageListCheckedOrSelected(),
+ aUnseen = []
+ ;
+
+ if (0 < aChecked.length)
+ {
+ aUnseen = _.filter(aChecked, function (oMessage) {
+ return oMessage.unseen();
+ });
+
+ if (Utils.isUnd(bSeen))
+ {
+ this.setAction(aChecked[0].folderFullNameRaw,
+ 0 < aUnseen.length ? Enums.MessageSetAction.SetSeen : Enums.MessageSetAction.UnsetSeen, aChecked);
+ }
+ else
+ {
+ this.setAction(aChecked[0].folderFullNameRaw,
+ bSeen ? Enums.MessageSetAction.SetSeen : Enums.MessageSetAction.UnsetSeen, aChecked);
+ }
+ }
+};
+
+MailBoxMessageListViewModel.prototype.onBuild = function (oDom)
+{
+ var
+ self = this,
+ oData = RL.data()
+ ;
+
+ this.oContentVisible = $('.b-content', oDom);
+ this.oContentScrollable = $('.content', this.oContentVisible);
+
+ this.oContentVisible.on('click', '.fullThreadHandle', function () {
+ var
+ aList = [],
+ oMessage = ko.dataFor(this)
+ ;
+
+ if (oMessage && !oMessage.lastInCollapsedThreadLoading())
+ {
+ RL.data().messageListThreadFolder(oMessage.folderFullNameRaw);
+
+ aList = RL.data().messageListThreadUids();
+
+ if (oMessage.lastInCollapsedThread())
+ {
+ aList.push(0 < oMessage.parentUid() ? oMessage.parentUid() : oMessage.uid);
+ }
+ else
+ {
+ aList = _.without(aList, 0 < oMessage.parentUid() ? oMessage.parentUid() : oMessage.uid);
+ }
+
+ RL.data().messageListThreadUids(_.uniq(aList));
+
+ oMessage.lastInCollapsedThreadLoading(true);
+ oMessage.lastInCollapsedThread(!oMessage.lastInCollapsedThread());
+ RL.reloadMessageList();
+ }
+
+ return false;
+ });
+
+ this.selector.init(this.oContentVisible, this.oContentScrollable, Enums.KeyState.MessageList);
+
+ oDom
+ .on('click', '.messageList .b-message-list-wrapper', function () {
+ if (self.message.focused())
+ {
+ self.message.focused(false);
+ }
+ })
+ .on('click', '.e-pagenator .e-page', function () {
+ var oPage = ko.dataFor(this);
+ if (oPage)
+ {
+ kn.setHash(RL.link().mailBox(
+ oData.currentFolderFullNameHash(),
+ oPage.value,
+ oData.messageListSearch()
+ ));
+ }
+ })
+ .on('click', '.messageList .checkboxCkeckAll', function () {
+ self.checkAll(!self.checkAll());
+ })
+ .on('click', '.messageList .messageListItem .flagParent', function () {
+ self.flagMessages(ko.dataFor(this));
+ })
+ ;
+
+ this.initUploaderForAppend();
+ this.initShortcuts();
+
+ if (!Globals.bMobileDevice && RL.capa(Enums.Capa.Prefetch) && ifvisible)
+ {
+ ifvisible.setIdleDuration(10);
+
+ ifvisible.idle(function () {
+ self.prefetchNextTick();
+ });
+ }
+};
+
+MailBoxMessageListViewModel.prototype.initShortcuts = function ()
+{
+ var self = this;
+
+ // disable print
+ key('ctrl+p, command+p', Enums.KeyState.MessageList, function () {
+ return false;
+ });
+
+ // archive (zip)
+ key('z', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
+ self.archiveCommand();
+ return false;
+ });
+
+ // delete
+ key('delete, shift+delete, shift+3', Enums.KeyState.MessageList, function (event, handler) {
+ if (event)
+ {
+ if (0 < RL.data().messageListCheckedOrSelected().length)
+ {
+ if (handler && 'shift+delete' === handler.shortcut)
+ {
+ self.deleteWithoutMoveCommand();
+ }
+ else
+ {
+ self.deleteCommand();
+ }
+ }
+
+ return false;
+ }
+ });
+
+ // check mail
+ key('ctrl+r, command+r', [Enums.KeyState.FolderList, Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
+ self.reloadCommand();
+ return false;
+ });
+
+ // check all
+ key('ctrl+a, command+a', Enums.KeyState.MessageList, function () {
+ self.checkAll(!(self.checkAll() && !self.isIncompleteChecked()));
+ return false;
+ });
+
+ // write/compose (open compose popup)
+ key('w,c', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
+ kn.showScreenPopup(PopupsComposeViewModel);
+ return false;
+ });
+
+ // important - star/flag messages
+ key('i', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
+ self.flagMessagesFast();
+ return false;
+ });
+
+ // move
+ key('m', Enums.KeyState.MessageList, function () {
+ self.moveDropdownTrigger(true);
+ return false;
+ });
+
+ // read
+ key('q', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
+ self.seenMessagesFast(true);
+ return false;
+ });
+
+ // unread
+ key('u', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
+ self.seenMessagesFast(false);
+ return false;
+ });
+
+ key('shift+f', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
+ self.multyForwardCommand();
+ return false;
+ });
+
+ // search input focus
+ key('/', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
+ self.inputMessageListSearchFocus(true);
+ return false;
+ });
+
+ // cancel search
+ key('esc', Enums.KeyState.MessageList, function () {
+ if ('' !== self.messageListSearchDesc())
+ {
+ self.cancelSearch();
+ return false;
+ }
+ });
+
+ // change focused state
+ key('tab, shift+tab, left, right', Enums.KeyState.MessageList, function (event, handler) {
+ if (event && handler && 'shift+tab' === handler.shortcut || 'left' === handler.shortcut)
+ {
+ self.folderList.focused(true);
+ }
+ else if (self.message())
+ {
+ self.message.focused(true);
+ }
+
+ return false;
+ });
+
+ // TODO
+ key('ctrl+left, command+left', Enums.KeyState.MessageView, function () {
+ return false;
+ });
+
+ // TODO
+ key('ctrl+right, command+right', Enums.KeyState.MessageView, function () {
+ return false;
+ });
+};
+
+MailBoxMessageListViewModel.prototype.prefetchNextTick = function ()
+{
+ if (!this.bPrefetch && !ifvisible.now() && this.viewModelVisibility())
+ {
+ var
+ self = this,
+ oCache = RL.cache(),
+ oMessage = _.find(this.messageList(), function (oMessage) {
+ return oMessage &&
+ !oCache.hasRequestedMessage(oMessage.folderFullNameRaw, oMessage.uid);
+ })
+ ;
+
+ if (oMessage)
+ {
+ this.bPrefetch = true;
+
+ RL.cache().addRequestedMessage(oMessage.folderFullNameRaw, oMessage.uid);
+
+ RL.remote().message(function (sResult, oData) {
+
+ var bNext = !!(Enums.StorageResultType.Success === sResult && oData && oData.Result);
+
+ _.delay(function () {
+ self.bPrefetch = false;
+ if (bNext)
+ {
+ self.prefetchNextTick();
+ }
+ }, 1000);
+
+ }, oMessage.folderFullNameRaw, oMessage.uid);
+ }
+ }
+};
+
+MailBoxMessageListViewModel.prototype.composeClick = function ()
+{
+ kn.showScreenPopup(PopupsComposeViewModel);
+};
+
+MailBoxMessageListViewModel.prototype.advancedSearchClick = function ()
+{
+ kn.showScreenPopup(PopupsAdvancedSearchViewModel);
+};
+
+MailBoxMessageListViewModel.prototype.quotaTooltip = function ()
+{
+ return Utils.i18n('MESSAGE_LIST/QUOTA_SIZE', {
+ 'SIZE': Utils.friendlySize(this.userUsageSize()),
+ 'PROC': this.userUsageProc(),
+ 'LIMIT': Utils.friendlySize(this.userQuota())
+ });
+};
+
+MailBoxMessageListViewModel.prototype.initUploaderForAppend = function ()
+{
+ if (!RL.settingsGet('AllowAppendMessage') || !this.dragOverArea())
+ {
+ return false;
+ }
+
+ var oJua = new Jua({
+ 'action': RL.link().append(),
+ 'name': 'AppendFile',
+ 'queueSize': 1,
+ 'multipleSizeLimit': 1,
+ 'disableFolderDragAndDrop': true,
+ 'hidden': {
+ 'Folder': function () {
+ return RL.data().currentFolderFullNameRaw();
+ }
+ },
+ 'dragAndDropElement': this.dragOverArea(),
+ 'dragAndDropBodyElement': this.dragOverBodyArea()
+ });
+
+ oJua
+ .on('onDragEnter', _.bind(function () {
+ this.dragOverEnter(true);
+ }, this))
+ .on('onDragLeave', _.bind(function () {
+ this.dragOverEnter(false);
+ }, this))
+ .on('onBodyDragEnter', _.bind(function () {
+ this.dragOver(true);
+ }, this))
+ .on('onBodyDragLeave', _.bind(function () {
+ this.dragOver(false);
+ }, this))
+ .on('onSelect', _.bind(function (sUid, oData) {
+ if (sUid && oData && 'message/rfc822' === oData['Type'])
+ {
+ RL.data().messageListLoading(true);
+ return true;
+ }
+
+ return false;
+ }, this))
+ .on('onComplete', _.bind(function () {
+ RL.reloadMessageList(true, true);
+ }, this))
+ ;
+
+ return !!oJua;
+};
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+function MailBoxMessageViewViewModel()
+{
+ KnoinAbstractViewModel.call(this, 'Right', 'MailMessageView');
+
+ var
+ self = this,
+ sLastEmail = '',
+ oData = RL.data(),
+ createCommandHelper = function (sType) {
+ return Utils.createCommand(self, function () {
+ this.replyOrforward(sType);
+ }, self.canBeRepliedOrForwarded);
+ }
+ ;
+
+ this.oMessageScrollerDom = null;
+
+ this.keyScope = oData.keyScope;
+ this.message = oData.message;
+ this.currentMessage = oData.currentMessage;
+ this.messageListChecked = oData.messageListChecked;
+ this.hasCheckedMessages = oData.hasCheckedMessages;
+ this.messageListCheckedOrSelectedUidsWithSubMails = oData.messageListCheckedOrSelectedUidsWithSubMails;
+ this.messageLoading = oData.messageLoading;
+ this.messageLoadingThrottle = oData.messageLoadingThrottle;
+ this.messagesBodiesDom = oData.messagesBodiesDom;
+ this.useThreads = oData.useThreads;
+ this.replySameFolder = oData.replySameFolder;
+ this.layout = oData.layout;
+ this.usePreviewPane = oData.usePreviewPane;
+ this.isMessageSelected = oData.isMessageSelected;
+ this.messageActiveDom = oData.messageActiveDom;
+ this.messageError = oData.messageError;
+
+ this.fullScreenMode = oData.messageFullScreenMode;
+
+ this.showFullInfo = ko.observable(false);
+ this.moreDropdownTrigger = ko.observable(false);
+ this.messageDomFocused = ko.observable(false).extend({'rateLimit': 0});
+
+ this.messageVisibility = ko.computed(function () {
+ return !this.messageLoadingThrottle() && !!this.message();
+ }, this);
+
+ this.message.subscribe(function (oMessage) {
+ if (!oMessage)
+ {
+ this.currentMessage(null);
+ }
+ }, this);
+
+ this.canBeRepliedOrForwarded = this.messageVisibility;
+
+ // commands
+ this.closeMessage = Utils.createCommand(this, function () {
+ oData.message(null);
+ });
+
+ this.replyCommand = createCommandHelper(Enums.ComposeType.Reply);
+ this.replyAllCommand = createCommandHelper(Enums.ComposeType.ReplyAll);
+ this.forwardCommand = createCommandHelper(Enums.ComposeType.Forward);
+ this.forwardAsAttachmentCommand = createCommandHelper(Enums.ComposeType.ForwardAsAttachment);
+ this.editAsNewCommand = createCommandHelper(Enums.ComposeType.EditAsNew);
+
+ this.messageVisibilityCommand = Utils.createCommand(this, Utils.emptyFunction, this.messageVisibility);
+
+ this.messageEditCommand = Utils.createCommand(this, function () {
+ this.editMessage();
+ }, this.messageVisibility);
+
+ this.deleteCommand = Utils.createCommand(this, function () {
+ if (this.message())
+ {
+ RL.deleteMessagesFromFolder(Enums.FolderType.Trash,
+ this.message().folderFullNameRaw,
+ [this.message().uid], true);
+ }
+ }, this.messageVisibility);
+
+ this.deleteWithoutMoveCommand = Utils.createCommand(this, function () {
+ if (this.message())
+ {
+ RL.deleteMessagesFromFolder(Enums.FolderType.Trash,
+ RL.data().currentFolderFullNameRaw(),
+ [this.message().uid], false);
+ }
+ }, this.messageVisibility);
+
+ this.archiveCommand = Utils.createCommand(this, function () {
+ if (this.message())
+ {
+ RL.deleteMessagesFromFolder(Enums.FolderType.Archive,
+ this.message().folderFullNameRaw,
+ [this.message().uid], true);
+ }
+ }, this.messageVisibility);
+
+ this.spamCommand = Utils.createCommand(this, function () {
+ if (this.message())
+ {
+ RL.deleteMessagesFromFolder(Enums.FolderType.Spam,
+ this.message().folderFullNameRaw,
+ [this.message().uid], true);
+ }
+ }, this.messageVisibility);
+
+ this.notSpamCommand = Utils.createCommand(this, function () {
+ if (this.message())
+ {
+ RL.deleteMessagesFromFolder(Enums.FolderType.NotSpam,
+ this.message().folderFullNameRaw,
+ [this.message().uid], true);
+ }
+ }, this.messageVisibility);
+
+ // viewer
+ this.viewHash = '';
+ this.viewSubject = ko.observable('');
+ this.viewFromShort = ko.observable('');
+ this.viewToShort = ko.observable('');
+ this.viewFrom = ko.observable('');
+ this.viewTo = ko.observable('');
+ this.viewCc = ko.observable('');
+ this.viewBcc = ko.observable('');
+ this.viewDate = ko.observable('');
+ this.viewMoment = ko.observable('');
+ this.viewLineAsCcc = ko.observable('');
+ this.viewViewLink = ko.observable('');
+ this.viewDownloadLink = ko.observable('');
+ this.viewUserPic = ko.observable(Consts.DataImages.UserDotPic);
+ this.viewUserPicVisible = ko.observable(false);
+
+ this.viewPgpPassword = ko.observable('');
+ this.viewPgpSignedVerifyStatus = ko.computed(function () {
+ return this.message() ? this.message().pgpSignedVerifyStatus() : Enums.SignedVerifyStatus.None;
+ }, this);
+
+ this.viewPgpSignedVerifyUser = ko.computed(function () {
+ return this.message() ? this.message().pgpSignedVerifyUser() : '';
+ }, this);
+
+ this.message.subscribe(function (oMessage) {
+
+ this.messageActiveDom(null);
+
+ this.viewPgpPassword('');
+
+ if (oMessage)
+ {
+ if (this.viewHash !== oMessage.hash)
+ {
+ this.scrollMessageToTop();
+ }
+
+ this.viewHash = oMessage.hash;
+ this.viewSubject(oMessage.subject());
+ this.viewFromShort(oMessage.fromToLine(true, true));
+ this.viewToShort(oMessage.toToLine(true, true));
+ this.viewFrom(oMessage.fromToLine(false));
+ this.viewTo(oMessage.toToLine(false));
+ this.viewCc(oMessage.ccToLine(false));
+ this.viewBcc(oMessage.bccToLine(false));
+ this.viewDate(oMessage.fullFormatDateValue());
+ this.viewMoment(oMessage.momentDate());
+ this.viewLineAsCcc(oMessage.lineAsCcc());
+ this.viewViewLink(oMessage.viewLink());
+ this.viewDownloadLink(oMessage.downloadLink());
+
+ sLastEmail = oMessage.fromAsSingleEmail();
+ RL.cache().getUserPic(sLastEmail, function (sPic, $sEmail) {
+ if (sPic !== self.viewUserPic() && sLastEmail === $sEmail)
+ {
+ self.viewUserPicVisible(false);
+ self.viewUserPic(Consts.DataImages.UserDotPic);
+ if ('' !== sPic)
+ {
+ self.viewUserPicVisible(true);
+ self.viewUserPic(sPic);
+ }
+ }
+ });
+ }
+ else
+ {
+ this.viewHash = '';
+ this.scrollMessageToTop();
+ }
+
+ }, this);
+
+ this.fullScreenMode.subscribe(function (bValue) {
+ if (bValue)
+ {
+ $html.addClass('rl-message-fullscreen');
+ }
+ else
+ {
+ $html.removeClass('rl-message-fullscreen');
+ }
+
+ Utils.windowResize();
+ });
+
+ this.messageLoadingThrottle.subscribe(function (bV) {
+ if (bV)
+ {
+ Utils.windowResize();
+ }
+ });
+
+ this.goUpCommand = Utils.createCommand(this, function () {
+ RL.pub('mailbox.message-list.selector.go-up');
+ });
+
+ this.goDownCommand = Utils.createCommand(this, function () {
+ RL.pub('mailbox.message-list.selector.go-down');
+ });
+
+ Knoin.constructorEnd(this);
+}
+
+Utils.extendAsViewModel('MailBoxMessageViewViewModel', MailBoxMessageViewViewModel);
+
+MailBoxMessageViewViewModel.prototype.isPgpActionVisible = function ()
+{
+ return Enums.SignedVerifyStatus.Success !== this.viewPgpSignedVerifyStatus();
+};
+
+MailBoxMessageViewViewModel.prototype.isPgpStatusVerifyVisible = function ()
+{
+ return Enums.SignedVerifyStatus.None !== this.viewPgpSignedVerifyStatus();
+};
+
+MailBoxMessageViewViewModel.prototype.isPgpStatusVerifySuccess = function ()
+{
+ return Enums.SignedVerifyStatus.Success === this.viewPgpSignedVerifyStatus();
+};
+
+MailBoxMessageViewViewModel.prototype.pgpStatusVerifyMessage = function ()
+{
+ var sResult = '';
+ switch (this.viewPgpSignedVerifyStatus())
+ {
+ case Enums.SignedVerifyStatus.UnknownPublicKeys:
+ sResult = Utils.i18n('PGP_NOTIFICATIONS/NO_PUBLIC_KEYS_FOUND');
+ break;
+ case Enums.SignedVerifyStatus.UnknownPrivateKey:
+ sResult = Utils.i18n('PGP_NOTIFICATIONS/NO_PRIVATE_KEY_FOUND');
+ break;
+ case Enums.SignedVerifyStatus.Unverified:
+ sResult = Utils.i18n('PGP_NOTIFICATIONS/UNVERIFIRED_SIGNATURE');
+ break;
+ case Enums.SignedVerifyStatus.Error:
+ sResult = Utils.i18n('PGP_NOTIFICATIONS/DECRYPTION_ERROR');
+ break;
+ case Enums.SignedVerifyStatus.Success:
+ sResult = Utils.i18n('PGP_NOTIFICATIONS/GOOD_SIGNATURE', {
+ 'USER': this.viewPgpSignedVerifyUser()
+ });
+ break;
+ }
+
+ return sResult;
+};
+
+MailBoxMessageViewViewModel.prototype.scrollToTop = function ()
+{
+ var oCont = $('.messageItem.nano .content', this.viewModelDom);
+ if (oCont && oCont[0])
+ {
+// oCont.animate({'scrollTop': 0}, 300);
+ oCont.scrollTop(0);
+ }
+ else
+ {
+// $('.messageItem', this.viewModelDom).animate({'scrollTop': 0}, 300);
+ $('.messageItem', this.viewModelDom).scrollTop(0);
+ }
+
+ Utils.windowResize();
+};
+
+MailBoxMessageViewViewModel.prototype.fullScreen = function ()
+{
+ this.fullScreenMode(true);
+ Utils.windowResize();
+};
+
+MailBoxMessageViewViewModel.prototype.unFullScreen = function ()
+{
+ this.fullScreenMode(false);
+ Utils.windowResize();
+};
+
+MailBoxMessageViewViewModel.prototype.toggleFullScreen = function ()
+{
+ Utils.removeSelection();
+
+ this.fullScreenMode(!this.fullScreenMode());
+ Utils.windowResize();
+};
+
+/**
+ * @param {string} sType
+ */
+MailBoxMessageViewViewModel.prototype.replyOrforward = function (sType)
+{
+ kn.showScreenPopup(PopupsComposeViewModel, [sType, RL.data().message()]);
+};
+
+MailBoxMessageViewViewModel.prototype.onBuild = function (oDom)
+{
+ var
+ self = this,
+ oData = RL.data()
+ ;
+
+ this.fullScreenMode.subscribe(function (bValue) {
+ if (bValue)
+ {
+ self.message.focused(true);
+ }
+ }, this);
+
+ $('.attachmentsPlace', oDom).magnificPopup({
+ 'delegate': '.magnificPopupImage:visible',
+ 'type': 'image',
+ 'gallery': {
+ 'enabled': true,
+ 'preload': [1, 1],
+ 'navigateByImgClick': true
+ },
+ 'callbacks': {
+ 'open': function() {
+ oData.useKeyboardShortcuts(false);
+ },
+ 'close': function() {
+ oData.useKeyboardShortcuts(true);
+ }
+ },
+ 'mainClass': 'mfp-fade',
+ 'removalDelay': 400
+ });
+
+ oDom
+ .on('click', '.messageView .messageItem .messageItemHeader', function () {
+ if (oData.useKeyboardShortcuts() && self.message())
+ {
+ self.message.focused(true);
+ }
+ })
+ .on('click', 'a', function (oEvent) {
+ // setup maito protocol
+ return !(!!oEvent && 3 !== oEvent['which'] && RL.mailToHelper($(this).attr('href')));
+ })
+ .on('click', '.attachmentsPlace .attachmentPreview', function (oEvent) {
+ if (oEvent && oEvent.stopPropagation)
+ {
+ oEvent.stopPropagation();
+ }
+ })
+ .on('click', '.attachmentsPlace .attachmentItem', function () {
+
+ var
+ oAttachment = ko.dataFor(this)
+ ;
+
+ if (oAttachment && oAttachment.download)
+ {
+ RL.download(oAttachment.linkDownload());
+ }
+ })
+ ;
+
+ this.message.focused.subscribe(function (bValue) {
+ if (bValue && !Utils.inFocus()) {
+ this.messageDomFocused(true);
+ } else {
+ this.messageDomFocused(false);
+ }
+ }, this);
+
+ this.messageDomFocused.subscribe(function (bValue) {
+ if (!bValue && Enums.KeyState.MessageView === this.keyScope())
+ {
+ this.message.focused(false);
+ }
+ }, this);
+
+ this.keyScope.subscribe(function (sValue) {
+ if (Enums.KeyState.MessageView === sValue && this.message.focused())
+ {
+ this.messageDomFocused(true);
+ }
+ }, this);
+
+ this.oMessageScrollerDom = oDom.find('.messageItem .content');
+ this.oMessageScrollerDom = this.oMessageScrollerDom && this.oMessageScrollerDom[0] ? this.oMessageScrollerDom : null;
+
+ this.initShortcuts();
+};
+
+/**
+ * @return {boolean}
+ */
+MailBoxMessageViewViewModel.prototype.escShortcuts = function ()
+{
+ if (this.viewModelVisibility() && this.message())
+ {
+ if (this.fullScreenMode())
+ {
+ this.fullScreenMode(false);
+ }
+ else if (Enums.Layout.NoPreview === RL.data().layout())
+ {
+ this.message(null);
+ }
+ else
+ {
+ this.message.focused(false);
+ }
+
+ return false;
+ }
+};
+
+MailBoxMessageViewViewModel.prototype.initShortcuts = function ()
+{
+ var
+ self = this,
+ oData = RL.data()
+ ;
+
+ // exit fullscreen, back
+ key('esc', Enums.KeyState.MessageView, _.bind(this.escShortcuts, this));
+
+ // fullscreen
+ key('enter', Enums.KeyState.MessageView, function () {
+ self.toggleFullScreen();
+ return false;
+ });
+
+ key('enter', Enums.KeyState.MessageList, function () {
+ if (Enums.Layout.NoPreview !== oData.layout() && self.message())
+ {
+ self.toggleFullScreen();
+ return false;
+ }
+ });
+
+ // TODO // more toggle
+// key('', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
+// self.moreDropdownTrigger(true);
+// return false;
+// });
+
+ // reply
+ key('r', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
+ if (oData.message())
+ {
+ self.replyCommand();
+ return false;
+ }
+ });
+
+ // replaAll
+ key('a', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
+ if (oData.message())
+ {
+ self.replyAllCommand();
+ return false;
+ }
+ });
+
+ // forward
+ key('f', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
+ if (oData.message())
+ {
+ self.forwardCommand();
+ return false;
+ }
+ });
+
+ // message information
+// key('i', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
+// if (oData.message())
+// {
+// self.showFullInfo(!self.showFullInfo());
+// return false;
+// }
+// });
+
+ // toggle message blockquotes
+ key('b', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
+ if (oData.message() && oData.message().body)
+ {
+ Utils.toggleMessageBlockquote(oData.message().body);
+ return false;
+ }
+ });
+
+ key('ctrl+left, command+left, ctrl+up, command+up', Enums.KeyState.MessageView, function () {
+ self.goUpCommand();
+ return false;
+ });
+
+ key('ctrl+right, command+right, ctrl+down, command+down', Enums.KeyState.MessageView, function () {
+ self.goDownCommand();
+ return false;
+ });
+
+ // print
+ key('ctrl+p, command+p', Enums.KeyState.MessageView, function () {
+ if (self.message())
+ {
+ self.message().printMessage();
+ }
+
+ return false;
+ });
+
+ // delete
+ key('delete, shift+delete', Enums.KeyState.MessageView, function (event, handler) {
+ if (event)
+ {
+ if (handler && 'shift+delete' === handler.shortcut)
+ {
+ self.deleteWithoutMoveCommand();
+ }
+ else
+ {
+ self.deleteCommand();
+ }
+
+ return false;
+ }
+ });
+
+ // change focused state
+ key('tab, shift+tab, left', Enums.KeyState.MessageView, function () {
+ if (!self.fullScreenMode() && self.message() && Enums.Layout.NoPreview !== oData.layout())
+ {
+ self.message.focused(false);
+ }
+
+ return false;
+ });
+};
+
+/**
+ * @return {boolean}
+ */
+MailBoxMessageViewViewModel.prototype.isDraftFolder = function ()
+{
+ return RL.data().message() && RL.data().draftFolder() === RL.data().message().folderFullNameRaw;
+};
+
+/**
+ * @return {boolean}
+ */
+MailBoxMessageViewViewModel.prototype.isSentFolder = function ()
+{
+ return RL.data().message() && RL.data().sentFolder() === RL.data().message().folderFullNameRaw;
+};
+
+/**
+ * @return {boolean}
+ */
+MailBoxMessageViewViewModel.prototype.isSpamFolder = function ()
+{
+ return RL.data().message() && RL.data().spamFolder() === RL.data().message().folderFullNameRaw;
+};
+
+/**
+ * @return {boolean}
+ */
+MailBoxMessageViewViewModel.prototype.isSpamDisabled = function ()
+{
+ return RL.data().message() && RL.data().spamFolder() === Consts.Values.UnuseOptionValue;
+};
+
+/**
+ * @return {boolean}
+ */
+MailBoxMessageViewViewModel.prototype.isArchiveFolder = function ()
+{
+ return RL.data().message() && RL.data().archiveFolder() === RL.data().message().folderFullNameRaw;
+};
+
+/**
+ * @return {boolean}
+ */
+MailBoxMessageViewViewModel.prototype.isArchiveDisabled = function ()
+{
+ return RL.data().message() && RL.data().archiveFolder() === Consts.Values.UnuseOptionValue;
+};
+
+/**
+ * @return {boolean}
+ */
+MailBoxMessageViewViewModel.prototype.isDraftOrSentFolder = function ()
+{
+ return this.isDraftFolder() || this.isSentFolder();
+};
+
+MailBoxMessageViewViewModel.prototype.composeClick = function ()
+{
+ kn.showScreenPopup(PopupsComposeViewModel);
+};
+
+MailBoxMessageViewViewModel.prototype.editMessage = function ()
+{
+ if (RL.data().message())
+ {
+ kn.showScreenPopup(PopupsComposeViewModel, [Enums.ComposeType.Draft, RL.data().message()]);
+ }
+};
+
+MailBoxMessageViewViewModel.prototype.scrollMessageToTop = function ()
+{
+ if (this.oMessageScrollerDom)
+ {
+ this.oMessageScrollerDom.scrollTop(0);
+ }
+};
+
+/**
+ * @param {MessageModel} oMessage
+ */
+MailBoxMessageViewViewModel.prototype.showImages = function (oMessage)
+{
+ if (oMessage && oMessage.showExternalImages)
+ {
+ oMessage.showExternalImages(true);
+ }
+};
+
+/**
+ * @returns {string}
+ */
+MailBoxMessageViewViewModel.prototype.printableCheckedMessageCount = function ()
+{
+ var iCnt = this.messageListCheckedOrSelectedUidsWithSubMails().length;
+ return 0 < iCnt ? (100 > iCnt ? iCnt : '99+') : '';
+};
+
+
+/**
+ * @param {MessageModel} oMessage
+ */
+MailBoxMessageViewViewModel.prototype.verifyPgpSignedClearMessage = function (oMessage)
+{
+ if (oMessage)
+ {
+ oMessage.verifyPgpSignedClearMessage();
+ }
+};
+
+/**
+ * @param {MessageModel} oMessage
+ */
+MailBoxMessageViewViewModel.prototype.decryptPgpEncryptedMessage = function (oMessage)
+{
+ if (oMessage)
+ {
+ oMessage.decryptPgpEncryptedMessage(this.viewPgpPassword());
+ }
+};
+
+/**
+ * @param {MessageModel} oMessage
+ */
+MailBoxMessageViewViewModel.prototype.readReceipt = function (oMessage)
+{
+ if (oMessage && '' !== oMessage.readReceipt())
+ {
+ RL.remote().sendReadReceiptMessage(Utils.emptyFunction, oMessage.folderFullNameRaw, oMessage.uid,
+ oMessage.readReceipt(),
+ Utils.i18n('READ_RECEIPT/SUBJECT', {'SUBJECT': oMessage.subject()}),
+ Utils.i18n('READ_RECEIPT/BODY', {'READ-RECEIPT': RL.data().accountEmail()}));
+
+ oMessage.isReadReceipt(true);
+
+ RL.cache().storeMessageFlagsToCache(oMessage);
+ RL.reloadFlagsCurrentMessageListAndMessageFromCache();
+ }
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @param {?} oScreen
+ *
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+function SettingsMenuViewModel(oScreen)
+{
+ KnoinAbstractViewModel.call(this, 'Left', 'SettingsMenu');
+
+ this.leftPanelDisabled = RL.data().leftPanelDisabled;
+
+ this.menu = oScreen.menu;
+
+ Knoin.constructorEnd(this);
+}
+
+Utils.extendAsViewModel('SettingsMenuViewModel', SettingsMenuViewModel);
+
+SettingsMenuViewModel.prototype.link = function (sRoute)
+{
+ return RL.link().settings(sRoute);
+};
+
+SettingsMenuViewModel.prototype.backToMailBoxClick = function ()
+{
+ kn.setHash(RL.link().inbox());
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+function SettingsPaneViewModel()
+{
+ KnoinAbstractViewModel.call(this, 'Right', 'SettingsPane');
+
+ Knoin.constructorEnd(this);
+}
+
+Utils.extendAsViewModel('SettingsPaneViewModel', SettingsPaneViewModel);
+
+SettingsPaneViewModel.prototype.onBuild = function ()
+{
+ var self = this;
+ key('esc', Enums.KeyState.Settings, function () {
+ self.backToMailBoxClick();
+ });
+};
+
+SettingsPaneViewModel.prototype.onShow = function ()
+{
+ RL.data().message(null);
+};
+
+SettingsPaneViewModel.prototype.backToMailBoxClick = function ()
+{
+ kn.setHash(RL.link().inbox());
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ */
+function SettingsGeneral()
+{
+ var oData = RL.data();
+
+ this.mainLanguage = oData.mainLanguage;
+ this.mainMessagesPerPage = oData.mainMessagesPerPage;
+ this.mainMessagesPerPageArray = Consts.Defaults.MessagesPerPageArray;
+ this.editorDefaultType = oData.editorDefaultType;
+ this.showImages = oData.showImages;
+ this.interfaceAnimation = oData.interfaceAnimation;
+ this.useDesktopNotifications = oData.useDesktopNotifications;
+ this.threading = oData.threading;
+ this.useThreads = oData.useThreads;
+ this.replySameFolder = oData.replySameFolder;
+ this.layout = oData.layout;
+ this.usePreviewPane = oData.usePreviewPane;
+ this.useCheckboxesInList = oData.useCheckboxesInList;
+ this.allowLanguagesOnSettings = oData.allowLanguagesOnSettings;
+
+ this.isDesktopNotificationsSupported = ko.computed(function () {
+ return Enums.DesktopNotifications.NotSupported !== oData.desktopNotificationsPermisions();
+ });
+
+ this.isDesktopNotificationsDenied = ko.computed(function () {
+ return Enums.DesktopNotifications.NotSupported === oData.desktopNotificationsPermisions() ||
+ Enums.DesktopNotifications.Denied === oData.desktopNotificationsPermisions();
+ });
+
+ this.mainLanguageFullName = ko.computed(function () {
+ return Utils.convertLangName(this.mainLanguage());
+ }, this);
+
+ this.languageTrigger = ko.observable(Enums.SaveSettingsStep.Idle).extend({'throttle': 100});
+ this.mppTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
+
+ this.isAnimationSupported = Globals.bAnimationSupported;
+}
+
+Utils.addSettingsViewModel(SettingsGeneral, 'SettingsGeneral', 'SETTINGS_LABELS/LABEL_GENERAL_NAME', 'general', true);
+
+SettingsGeneral.prototype.toggleLayout = function ()
+{
+ this.layout(Enums.Layout.NoPreview === this.layout() ? Enums.Layout.SidePreview : Enums.Layout.NoPreview);
+};
+
+SettingsGeneral.prototype.onBuild = function ()
+{
+ var self = this;
+
+ _.delay(function () {
+
+ var
+ oData = RL.data(),
+ f1 = Utils.settingsSaveHelperSimpleFunction(self.mppTrigger, self)
+ ;
+
+ oData.language.subscribe(function (sValue) {
+
+ self.languageTrigger(Enums.SaveSettingsStep.Animate);
+
+ $.ajax({
+ 'url': RL.link().langLink(sValue),
+ 'dataType': 'script',
+ 'cache': true
+ }).done(function() {
+ Utils.i18nToDoc();
+ self.languageTrigger(Enums.SaveSettingsStep.TrueResult);
+ }).fail(function() {
+ self.languageTrigger(Enums.SaveSettingsStep.FalseResult);
+ }).always(function() {
+ _.delay(function () {
+ self.languageTrigger(Enums.SaveSettingsStep.Idle);
+ }, 1000);
+ });
+
+ RL.remote().saveSettings(Utils.emptyFunction, {
+ 'Language': sValue
+ });
+ });
+
+ oData.editorDefaultType.subscribe(function (sValue) {
+ RL.remote().saveSettings(Utils.emptyFunction, {
+ 'EditorDefaultType': sValue
+ });
+ });
+
+ oData.messagesPerPage.subscribe(function (iValue) {
+ RL.remote().saveSettings(f1, {
+ 'MPP': iValue
+ });
+ });
+
+ oData.showImages.subscribe(function (bValue) {
+ RL.remote().saveSettings(Utils.emptyFunction, {
+ 'ShowImages': bValue ? '1' : '0'
+ });
+ });
+
+ oData.interfaceAnimation.subscribe(function (sValue) {
+ RL.remote().saveSettings(Utils.emptyFunction, {
+ 'InterfaceAnimation': sValue
+ });
+ });
+
+ oData.useDesktopNotifications.subscribe(function (bValue) {
+ Utils.timeOutAction('SaveDesktopNotifications', function () {
+ RL.remote().saveSettings(Utils.emptyFunction, {
+ 'DesktopNotifications': bValue ? '1' : '0'
+ });
+ }, 3000);
+ });
+
+ oData.replySameFolder.subscribe(function (bValue) {
+ Utils.timeOutAction('SaveReplySameFolder', function () {
+ RL.remote().saveSettings(Utils.emptyFunction, {
+ 'ReplySameFolder': bValue ? '1' : '0'
+ });
+ }, 3000);
+ });
+
+ oData.useThreads.subscribe(function (bValue) {
+
+ oData.messageList([]);
+
+ RL.remote().saveSettings(Utils.emptyFunction, {
+ 'UseThreads': bValue ? '1' : '0'
+ });
+ });
+
+ oData.layout.subscribe(function (nValue) {
+
+ oData.messageList([]);
+
+ RL.remote().saveSettings(Utils.emptyFunction, {
+ 'Layout': nValue
+ });
+ });
+
+ oData.useCheckboxesInList.subscribe(function (bValue) {
+ RL.remote().saveSettings(Utils.emptyFunction, {
+ 'UseCheckboxesInList': bValue ? '1' : '0'
+ });
+ });
+
+ }, 50);
+};
+
+SettingsGeneral.prototype.onShow = function ()
+{
+ RL.data().desktopNotifications.valueHasMutated();
+};
+
+SettingsGeneral.prototype.selectLanguage = function ()
+{
+ kn.showScreenPopup(PopupsLanguagesViewModel);
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ */
+function SettingsContacts()
+{
+ var oData = RL.data();
+
+ this.contactsAutosave = oData.contactsAutosave;
+
+ this.allowContactsSync = oData.allowContactsSync;
+ this.enableContactsSync = oData.enableContactsSync;
+ this.contactsSyncUrl = oData.contactsSyncUrl;
+ this.contactsSyncUser = oData.contactsSyncUser;
+ this.contactsSyncPass = oData.contactsSyncPass;
+
+ this.saveTrigger = ko.computed(function () {
+ return [
+ this.enableContactsSync() ? '1' : '0',
+ this.contactsSyncUrl(),
+ this.contactsSyncUser(),
+ this.contactsSyncPass()
+ ].join('|');
+ }, this).extend({'throttle': 500});
+
+ this.saveTrigger.subscribe(function () {
+ RL.remote().saveContactsSyncData(null,
+ this.enableContactsSync(),
+ this.contactsSyncUrl(),
+ this.contactsSyncUser(),
+ this.contactsSyncPass()
+ );
+ }, this);
+}
+
+Utils.addSettingsViewModel(SettingsContacts, 'SettingsContacts', 'SETTINGS_LABELS/LABEL_CONTACTS_NAME', 'contacts');
+
+SettingsContacts.prototype.onBuild = function ()
+{
+ RL.data().contactsAutosave.subscribe(function (bValue) {
+ RL.remote().saveSettings(Utils.emptyFunction, {
+ 'ContactsAutosave': bValue ? '1' : '0'
+ });
+ });
+};
+
+//SettingsContacts.prototype.onShow = function ()
+//{
+//
+//};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ */
+function SettingsAccounts()
+{
+ var oData = RL.data();
+
+ this.accounts = oData.accounts;
+
+ this.processText = ko.computed(function () {
+ return oData.accountsLoading() ? Utils.i18n('SETTINGS_ACCOUNTS/LOADING_PROCESS') : '';
+ }, this);
+
+ this.visibility = ko.computed(function () {
+ return '' === this.processText() ? 'hidden' : 'visible';
+ }, this);
+
+ this.accountForDeletion = ko.observable(null).extend({'falseTimeout': 3000}).extend({'toggleSubscribe': [this,
+ function (oPrev) {
+ if (oPrev)
+ {
+ oPrev.deleteAccess(false);
+ }
+ }, function (oNext) {
+ if (oNext)
+ {
+ oNext.deleteAccess(true);
+ }
+ }
+ ]});
+}
+
+Utils.addSettingsViewModel(SettingsAccounts, 'SettingsAccounts', 'SETTINGS_LABELS/LABEL_ACCOUNTS_NAME', 'accounts');
+
+SettingsAccounts.prototype.addNewAccount = function ()
+{
+ kn.showScreenPopup(PopupsAddAccountViewModel);
+};
+
+/**
+ * @param {AccountModel} oAccountToRemove
+ */
+SettingsAccounts.prototype.deleteAccount = function (oAccountToRemove)
+{
+ if (oAccountToRemove && oAccountToRemove.deleteAccess())
+ {
+ this.accountForDeletion(null);
+
+ var
+ fRemoveAccount = function (oAccount) {
+ return oAccountToRemove === oAccount;
+ }
+ ;
+
+ if (oAccountToRemove)
+ {
+ this.accounts.remove(fRemoveAccount);
+
+ RL.remote().accountDelete(function (sResult, oData) {
+
+ if (Enums.StorageResultType.Success === sResult && oData &&
+ oData.Result && oData.Reload)
+ {
+ kn.routeOff();
+ kn.setHash(RL.link().root(), true);
+ kn.routeOff();
+
+ _.defer(function () {
+ window.location.reload();
+ });
+ }
+ else
+ {
+ RL.accountsAndIdentities();
+ }
+
+ }, oAccountToRemove.email);
+ }
+ }
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ */
+function SettingsIdentity()
+{
+ var oData = RL.data();
+
+ this.editor = null;
+
+ this.displayName = oData.displayName;
+ this.signature = oData.signature;
+ this.signatureToAll = oData.signatureToAll;
+ this.replyTo = oData.replyTo;
+
+ this.signatureDom = ko.observable(null);
+
+ this.displayNameTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
+ this.replyTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
+ this.signatureTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
+}
+
+Utils.addSettingsViewModel(SettingsIdentity, 'SettingsIdentity', 'SETTINGS_LABELS/LABEL_IDENTITY_NAME', 'identity');
+
+SettingsIdentity.prototype.onFocus = function ()
+{
+ if (!this.editor && this.signatureDom())
+ {
+ var
+ self = this,
+ sSignature = RL.data().signature()
+ ;
+
+ this.editor = new NewHtmlEditorWrapper(self.signatureDom(), function () {
+ RL.data().signature(
+ (self.editor.isHtml() ? ':HTML:' : '') + self.editor.getData()
+ );
+ }, function () {
+ if (':HTML:' === sSignature.substr(0, 6))
+ {
+ self.editor.setHtml(sSignature.substr(6), false);
+ }
+ else
+ {
+ self.editor.setPlain(sSignature, false);
+ }
+ });
+ }
+};
+
+SettingsIdentity.prototype.onBuild = function ()
+{
+ var self = this;
+ _.delay(function () {
+
+ var
+ oData = RL.data(),
+ f1 = Utils.settingsSaveHelperSimpleFunction(self.displayNameTrigger, self),
+ f2 = Utils.settingsSaveHelperSimpleFunction(self.replyTrigger, self),
+ f3 = Utils.settingsSaveHelperSimpleFunction(self.signatureTrigger, self)
+ ;
+
+ oData.displayName.subscribe(function (sValue) {
+ RL.remote().saveSettings(f1, {
+ 'DisplayName': sValue
+ });
+ });
+
+ oData.replyTo.subscribe(function (sValue) {
+ RL.remote().saveSettings(f2, {
+ 'ReplyTo': sValue
+ });
+ });
+
+ oData.signature.subscribe(function (sValue) {
+ RL.remote().saveSettings(f3, {
+ 'Signature': sValue
+ });
+ });
+
+ oData.signatureToAll.subscribe(function (bValue) {
+ RL.remote().saveSettings(null, {
+ 'SignatureToAll': bValue ? '1' : '0'
+ });
+ });
+
+ }, 50);
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ */
+function SettingsIdentities()
+{
+ var oData = RL.data();
+
+ this.editor = null;
+ this.defautOptionsAfterRender = Utils.defautOptionsAfterRender;
+
+ this.accountEmail = oData.accountEmail;
+ this.displayName = oData.displayName;
+ this.signature = oData.signature;
+ this.signatureToAll = oData.signatureToAll;
+ this.replyTo = oData.replyTo;
+
+ this.signatureDom = ko.observable(null);
+
+ this.defaultIdentityIDTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
+ this.displayNameTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
+ this.replyTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
+ this.signatureTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
+
+ this.identities = oData.identities;
+ this.defaultIdentityID = oData.defaultIdentityID;
+
+ this.identitiesOptions = ko.computed(function () {
+
+ var
+ aList = this.identities(),
+ aResult = []
+ ;
+
+ if (0 < aList.length)
+ {
+ aResult.push({
+ 'id': this.accountEmail.peek(),
+ 'name': this.formattedAccountIdentity(),
+ 'seporator': false
+ });
+
+ aResult.push({
+ 'id': '---',
+ 'name': '---',
+ 'seporator': true,
+ 'disabled': true
+ });
+
+ _.each(aList, function (oItem) {
+ aResult.push({
+ 'id': oItem.id,
+ 'name': oItem.formattedNameForEmail(),
+ 'seporator': false
+ });
+ });
+ }
+
+ return aResult;
+ }, this);
+
+ this.processText = ko.computed(function () {
+ return oData.identitiesLoading() ? Utils.i18n('SETTINGS_IDENTITIES/LOADING_PROCESS') : '';
+ }, this);
+
+ this.visibility = ko.computed(function () {
+ return '' === this.processText() ? 'hidden' : 'visible';
+ }, this);
+
+ this.identityForDeletion = ko.observable(null).extend({'falseTimeout': 3000}).extend({'toggleSubscribe': [this,
+ function (oPrev) {
+ if (oPrev)
+ {
+ oPrev.deleteAccess(false);
+ }
+ }, function (oNext) {
+ if (oNext)
+ {
+ oNext.deleteAccess(true);
+ }
+ }
+ ]});
+}
+
+Utils.addSettingsViewModel(SettingsIdentities, 'SettingsIdentities', 'SETTINGS_LABELS/LABEL_IDENTITIES_NAME', 'identities');
+
+/**
+ *
+ * @return {string}
+ */
+SettingsIdentities.prototype.formattedAccountIdentity = function ()
+{
+ var
+ sDisplayName = this.displayName.peek(),
+ sEmail = this.accountEmail.peek()
+ ;
+
+ return '' === sDisplayName ? sEmail : '"' + Utils.quoteName(sDisplayName) + '" <' + sEmail + '>';
+};
+
+SettingsIdentities.prototype.addNewIdentity = function ()
+{
+ kn.showScreenPopup(PopupsIdentityViewModel);
+};
+
+SettingsIdentities.prototype.editIdentity = function (oIdentity)
+{
+ kn.showScreenPopup(PopupsIdentityViewModel, [oIdentity]);
+};
+
+/**
+ * @param {IdentityModel} oIdentityToRemove
+ */
+SettingsIdentities.prototype.deleteIdentity = function (oIdentityToRemove)
+{
+ if (oIdentityToRemove && oIdentityToRemove.deleteAccess())
+ {
+ this.identityForDeletion(null);
+
+ var
+ fRemoveFolder = function (oIdentity) {
+ return oIdentityToRemove === oIdentity;
+ }
+ ;
+
+ if (oIdentityToRemove)
+ {
+ this.identities.remove(fRemoveFolder);
+
+ RL.remote().identityDelete(function () {
+ RL.accountsAndIdentities();
+ }, oIdentityToRemove.id);
+ }
+ }
+};
+
+SettingsIdentities.prototype.onFocus = function ()
+{
+ if (!this.editor && this.signatureDom())
+ {
+ var
+ self = this,
+ sSignature = RL.data().signature()
+ ;
+
+ this.editor = new NewHtmlEditorWrapper(self.signatureDom(), function () {
+ RL.data().signature(
+ (self.editor.isHtml() ? ':HTML:' : '') + self.editor.getData()
+ );
+ }, function () {
+ if (':HTML:' === sSignature.substr(0, 6))
+ {
+ self.editor.setHtml(sSignature.substr(6), false);
+ }
+ else
+ {
+ self.editor.setPlain(sSignature, false);
+ }
+ });
+ }
+};
+
+SettingsIdentities.prototype.onBuild = function (oDom)
+{
+ var self = this;
+
+ oDom
+ .on('click', '.identity-item .e-action', function () {
+ var oIdentityItem = ko.dataFor(this);
+ if (oIdentityItem)
+ {
+ self.editIdentity(oIdentityItem);
+ }
+ })
+ ;
+
+ _.delay(function () {
+
+ var
+ oData = RL.data(),
+ f1 = Utils.settingsSaveHelperSimpleFunction(self.displayNameTrigger, self),
+ f2 = Utils.settingsSaveHelperSimpleFunction(self.replyTrigger, self),
+ f3 = Utils.settingsSaveHelperSimpleFunction(self.signatureTrigger, self),
+ f4 = Utils.settingsSaveHelperSimpleFunction(self.defaultIdentityIDTrigger, self)
+ ;
+
+ oData.defaultIdentityID.subscribe(function (sValue) {
+ RL.remote().saveSettings(f4, {
+ 'DefaultIdentityID': sValue
+ });
+ });
+
+ oData.displayName.subscribe(function (sValue) {
+ RL.remote().saveSettings(f1, {
+ 'DisplayName': sValue
+ });
+ });
+
+ oData.replyTo.subscribe(function (sValue) {
+ RL.remote().saveSettings(f2, {
+ 'ReplyTo': sValue
+ });
+ });
+
+ oData.signature.subscribe(function (sValue) {
+ RL.remote().saveSettings(f3, {
+ 'Signature': sValue
+ });
+ });
+
+ oData.signatureToAll.subscribe(function (bValue) {
+ RL.remote().saveSettings(null, {
+ 'SignatureToAll': bValue ? '1' : '0'
+ });
+ });
+
+ }, 50);
+};
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ */
+function SettingsFilters()
+{
+// var oData = RL.data();
+
+ this.filters = ko.observableArray([]);
+ this.filters.loading = ko.observable(false);
+
+ this.filters.subscribe(function () {
+ Utils.windowResize();
+ });
+}
+
+Utils.addSettingsViewModel(SettingsFilters, 'SettingsFilters', 'SETTINGS_LABELS/LABEL_FILTERS_NAME', 'filters');
+
+//SettingsFilters.prototype.onBuild = function ()
+//{
+//};
+
+SettingsFilters.prototype.deleteFilter = function (oFilter)
+{
+ this.filters.remove(oFilter);
+};
+
+SettingsFilters.prototype.addFilter = function ()
+{
+ kn.showScreenPopup(PopupsFilterViewModel, [new FilterModel()]);
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ */
+function SettingsSecurity()
+{
+ this.processing = ko.observable(false);
+ this.clearing = ko.observable(false);
+ this.secreting = ko.observable(false);
+
+ this.viewUser = ko.observable('');
+ this.viewEnable = ko.observable(false);
+ this.viewEnable.subs = true;
+ this.twoFactorStatus = ko.observable(false);
+
+ this.viewSecret = ko.observable('');
+ this.viewBackupCodes = ko.observable('');
+ this.viewUrl = ko.observable('');
+
+ this.bFirst = true;
+
+ this.viewTwoFactorStatus = ko.computed(function () {
+ Globals.langChangeTrigger();
+ return Utils.i18n(
+ this.twoFactorStatus() ?
+ 'SETTINGS_SECURITY/TWO_FACTOR_SECRET_CONFIGURED_DESC' :
+ 'SETTINGS_SECURITY/TWO_FACTOR_SECRET_NOT_CONFIGURED_DESC'
+ );
+ }, this);
+
+ this.onResult = _.bind(this.onResult, this);
+ this.onSecretResult = _.bind(this.onSecretResult, this);
+}
+
+Utils.addSettingsViewModel(SettingsSecurity, 'SettingsSecurity', 'SETTINGS_LABELS/LABEL_SECURITY_NAME', 'security');
+
+SettingsSecurity.prototype.showSecret = function ()
+{
+ this.secreting(true);
+ RL.remote().showTwoFactorSecret(this.onSecretResult);
+};
+
+SettingsSecurity.prototype.hideSecret = function ()
+{
+ this.viewSecret('');
+ this.viewBackupCodes('');
+ this.viewUrl('');
+};
+
+SettingsSecurity.prototype.createTwoFactor = function ()
+{
+ this.processing(true);
+ RL.remote().createTwoFactor(this.onResult);
+};
+
+SettingsSecurity.prototype.enableTwoFactor = function ()
+{
+ this.processing(true);
+ RL.remote().enableTwoFactor(this.onResult, this.viewEnable());
+};
+
+SettingsSecurity.prototype.testTwoFactor = function ()
+{
+ kn.showScreenPopup(PopupsTwoFactorTestViewModel);
+};
+
+SettingsSecurity.prototype.clearTwoFactor = function ()
+{
+ this.viewSecret('');
+ this.viewBackupCodes('');
+ this.viewUrl('');
+
+ this.clearing(true);
+ RL.remote().clearTwoFactor(this.onResult);
+};
+
+SettingsSecurity.prototype.onShow = function ()
+{
+ this.viewSecret('');
+ this.viewBackupCodes('');
+ this.viewUrl('');
+};
+
+SettingsSecurity.prototype.onResult = function (sResult, oData)
+{
+ this.processing(false);
+ this.clearing(false);
+
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ {
+ this.viewUser(Utils.pString(oData.Result.User));
+ this.viewEnable(!!oData.Result.Enable);
+ this.twoFactorStatus(!!oData.Result.IsSet);
+
+ this.viewSecret(Utils.pString(oData.Result.Secret));
+ this.viewBackupCodes(Utils.pString(oData.Result.BackupCodes).replace(/[\s]+/g, ' '));
+ this.viewUrl(Utils.pString(oData.Result.Url));
+ }
+ else
+ {
+ this.viewUser('');
+ this.viewEnable(false);
+ this.twoFactorStatus(false);
+
+ this.viewSecret('');
+ this.viewBackupCodes('');
+ this.viewUrl('');
+ }
+
+ if (this.bFirst)
+ {
+ this.bFirst = false;
+ var self = this;
+ this.viewEnable.subscribe(function (bValue) {
+ if (this.viewEnable.subs)
+ {
+ RL.remote().enableTwoFactor(function (sResult, oData) {
+ if (Enums.StorageResultType.Success !== sResult || !oData || !oData.Result)
+ {
+ self.viewEnable.subs = false;
+ self.viewEnable(false);
+ self.viewEnable.subs = true;
+ }
+ }, bValue);
+ }
+ }, this);
+ }
+};
+
+SettingsSecurity.prototype.onSecretResult = function (sResult, oData)
+{
+ this.secreting(false);
+
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ {
+ this.viewSecret(Utils.pString(oData.Result.Secret));
+ this.viewUrl(Utils.pString(oData.Result.Url));
+ }
+ else
+ {
+ this.viewSecret('');
+ this.viewUrl('');
+ }
+};
+
+SettingsSecurity.prototype.onBuild = function ()
+{
+ this.processing(true);
+ RL.remote().getTwoFactor(this.onResult);
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ */
+function SettingsSocialScreen()
+{
+ var oData = RL.data();
+
+ this.googleEnable = oData.googleEnable;
+
+ this.googleActions = oData.googleActions;
+ this.googleLoggined = oData.googleLoggined;
+ this.googleUserName = oData.googleUserName;
+
+ this.facebookEnable = oData.facebookEnable;
+
+ this.facebookActions = oData.facebookActions;
+ this.facebookLoggined = oData.facebookLoggined;
+ this.facebookUserName = oData.facebookUserName;
+
+ this.twitterEnable = oData.twitterEnable;
+
+ this.twitterActions = oData.twitterActions;
+ this.twitterLoggined = oData.twitterLoggined;
+ this.twitterUserName = oData.twitterUserName;
+
+ this.connectGoogle = Utils.createCommand(this, function () {
+ if (!this.googleLoggined())
+ {
+ RL.googleConnect();
+ }
+ }, function () {
+ return !this.googleLoggined() && !this.googleActions();
+ });
+
+ this.disconnectGoogle = Utils.createCommand(this, function () {
+ RL.googleDisconnect();
+ });
+
+ this.connectFacebook = Utils.createCommand(this, function () {
+ if (!this.facebookLoggined())
+ {
+ RL.facebookConnect();
+ }
+ }, function () {
+ return !this.facebookLoggined() && !this.facebookActions();
+ });
+
+ this.disconnectFacebook = Utils.createCommand(this, function () {
+ RL.facebookDisconnect();
+ });
+
+ this.connectTwitter = Utils.createCommand(this, function () {
+ if (!this.twitterLoggined())
+ {
+ RL.twitterConnect();
+ }
+ }, function () {
+ return !this.twitterLoggined() && !this.twitterActions();
+ });
+
+ this.disconnectTwitter = Utils.createCommand(this, function () {
+ RL.twitterDisconnect();
+ });
+}
+
+Utils.addSettingsViewModel(SettingsSocialScreen, 'SettingsSocial', 'SETTINGS_LABELS/LABEL_SOCIAL_NAME', 'social');
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ */
+function SettingsChangePasswordScreen()
+{
+ this.changeProcess = ko.observable(false);
+
+ this.errorDescription = ko.observable('');
+ this.passwordMismatch = ko.observable(false);
+ this.passwordUpdateError = ko.observable(false);
+ this.passwordUpdateSuccess = ko.observable(false);
+
+ this.currentPassword = ko.observable('');
+ this.currentPassword.error = ko.observable(false);
+ this.newPassword = ko.observable('');
+ this.newPassword2 = ko.observable('');
+
+ this.currentPassword.subscribe(function () {
+ this.passwordUpdateError(false);
+ this.passwordUpdateSuccess(false);
+ this.currentPassword.error(false);
+ }, this);
+
+ this.newPassword.subscribe(function () {
+ this.passwordUpdateError(false);
+ this.passwordUpdateSuccess(false);
+ this.passwordMismatch(false);
+ }, this);
+
+ this.newPassword2.subscribe(function () {
+ this.passwordUpdateError(false);
+ this.passwordUpdateSuccess(false);
+ this.passwordMismatch(false);
+ }, this);
+
+ this.saveNewPasswordCommand = Utils.createCommand(this, function () {
+
+ if (this.newPassword() !== this.newPassword2())
+ {
+ this.passwordMismatch(true);
+ this.errorDescription(Utils.i18n('SETTINGS_CHANGE_PASSWORD/ERROR_PASSWORD_MISMATCH'));
+ }
+ else
+ {
+ this.changeProcess(true);
+
+ this.passwordUpdateError(false);
+ this.passwordUpdateSuccess(false);
+ this.currentPassword.error(false);
+ this.passwordMismatch(false);
+ this.errorDescription('');
+
+ RL.remote().changePassword(this.onChangePasswordResponse, this.currentPassword(), this.newPassword());
+ }
+
+ }, function () {
+ return !this.changeProcess() && '' !== this.currentPassword() &&
+ '' !== this.newPassword() && '' !== this.newPassword2();
+ });
+
+ this.onChangePasswordResponse = _.bind(this.onChangePasswordResponse, this);
+}
+
+Utils.addSettingsViewModel(SettingsChangePasswordScreen, 'SettingsChangePassword', 'SETTINGS_LABELS/LABEL_CHANGE_PASSWORD_NAME', 'change-password');
+
+SettingsChangePasswordScreen.prototype.onHide = function ()
+{
+ this.changeProcess(false);
+ this.currentPassword('');
+ this.newPassword('');
+ this.newPassword2('');
+ this.errorDescription('');
+ this.passwordMismatch(false);
+ this.currentPassword.error(false);
+};
+
+SettingsChangePasswordScreen.prototype.onChangePasswordResponse = function (sResult, oData)
+{
+ this.changeProcess(false);
+ this.passwordMismatch(false);
+ this.errorDescription('');
+ this.currentPassword.error(false);
+
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ {
+ this.currentPassword('');
+ this.newPassword('');
+ this.newPassword2('');
+
+ this.passwordUpdateSuccess(true);
+ this.currentPassword.error(false);
+ }
+ else
+ {
+ if (oData && Enums.Notification.CurrentPasswordIncorrect === oData.ErrorCode)
+ {
+ this.currentPassword.error(true);
+ }
+
+ this.passwordUpdateError(true);
+ this.errorDescription(oData && oData.ErrorCode ? Utils.getNotification(oData.ErrorCode) :
+ Utils.getNotification(Enums.Notification.CouldNotSaveNewPassword));
+ }
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ */
+function SettingsFolders()
+{
+ var oData = RL.data();
+
+ this.foldersListError = oData.foldersListError;
+ this.folderList = oData.folderList;
+
+ this.processText = ko.computed(function () {
+
+ var
+ oData = RL.data(),
+ bLoading = oData.foldersLoading(),
+ bCreating = oData.foldersCreating(),
+ bDeleting = oData.foldersDeleting(),
+ bRenaming = oData.foldersRenaming()
+ ;
+
+ if (bCreating)
+ {
+ return Utils.i18n('SETTINGS_FOLDERS/CREATING_PROCESS');
+ }
+ else if (bDeleting)
+ {
+ return Utils.i18n('SETTINGS_FOLDERS/DELETING_PROCESS');
+ }
+ else if (bRenaming)
+ {
+ return Utils.i18n('SETTINGS_FOLDERS/RENAMING_PROCESS');
+ }
+ else if (bLoading)
+ {
+ return Utils.i18n('SETTINGS_FOLDERS/LOADING_PROCESS');
+ }
+
+ return '';
+
+ }, this);
+
+ this.visibility = ko.computed(function () {
+ return '' === this.processText() ? 'hidden' : 'visible';
+ }, this);
+
+ this.folderForDeletion = ko.observable(null).extend({'falseTimeout': 3000}).extend({'toggleSubscribe': [this,
+ function (oPrev) {
+ if (oPrev)
+ {
+ oPrev.deleteAccess(false);
+ }
+ }, function (oNext) {
+ if (oNext)
+ {
+ oNext.deleteAccess(true);
+ }
+ }
+ ]});
+
+ this.folderForEdit = ko.observable(null).extend({'toggleSubscribe': [this,
+ function (oPrev) {
+ if (oPrev)
+ {
+ oPrev.edited(false);
+ }
+ }, function (oNext) {
+ if (oNext && oNext.canBeEdited())
+ {
+ oNext.edited(true);
+ }
+ }
+ ]});
+
+ this.useImapSubscribe = !!RL.settingsGet('UseImapSubscribe');
+}
+
+Utils.addSettingsViewModel(SettingsFolders, 'SettingsFolders', 'SETTINGS_LABELS/LABEL_FOLDERS_NAME', 'folders');
+
+SettingsFolders.prototype.folderEditOnEnter = function (oFolder)
+{
+ var sEditName = oFolder ? Utils.trim(oFolder.nameForEdit()) : '';
+ if ('' !== sEditName && oFolder.name() !== sEditName)
+ {
+ RL.local().set(Enums.ClientSideKeyName.FoldersLashHash, '');
+
+ RL.data().foldersRenaming(true);
+ RL.remote().folderRename(function (sResult, oData) {
+
+ RL.data().foldersRenaming(false);
+ if (Enums.StorageResultType.Success !== sResult || !oData || !oData.Result)
+ {
+ RL.data().foldersListError(
+ oData && oData.ErrorCode ? Utils.getNotification(oData.ErrorCode) : Utils.i18n('NOTIFICATIONS/CANT_RENAME_FOLDER'));
+ }
+
+ RL.folders();
+
+ }, oFolder.fullNameRaw, sEditName);
+
+ RL.cache().removeFolderFromCacheList(oFolder.fullNameRaw);
+
+ oFolder.name(sEditName);
+ }
+
+ oFolder.edited(false);
+};
+
+SettingsFolders.prototype.folderEditOnEsc = function (oFolder)
+{
+ if (oFolder)
+ {
+ oFolder.edited(false);
+ }
+};
+
+SettingsFolders.prototype.onShow = function ()
+{
+ RL.data().foldersListError('');
+};
+
+SettingsFolders.prototype.createFolder = function ()
+{
+ kn.showScreenPopup(PopupsFolderCreateViewModel);
+};
+
+SettingsFolders.prototype.systemFolder = function ()
+{
+ kn.showScreenPopup(PopupsFolderSystemViewModel);
+};
+
+SettingsFolders.prototype.deleteFolder = function (oFolderToRemove)
+{
+ if (oFolderToRemove && oFolderToRemove.canBeDeleted() && oFolderToRemove.deleteAccess() &&
+ 0 === oFolderToRemove.privateMessageCountAll())
+ {
+ this.folderForDeletion(null);
+
+ var
+ fRemoveFolder = function (oFolder) {
+
+ if (oFolderToRemove === oFolder)
+ {
+ return true;
+ }
+
+ oFolder.subFolders.remove(fRemoveFolder);
+ return false;
+ }
+ ;
+
+ if (oFolderToRemove)
+ {
+ RL.local().set(Enums.ClientSideKeyName.FoldersLashHash, '');
+
+ RL.data().folderList.remove(fRemoveFolder);
+
+ RL.data().foldersDeleting(true);
+ RL.remote().folderDelete(function (sResult, oData) {
+
+ RL.data().foldersDeleting(false);
+ if (Enums.StorageResultType.Success !== sResult || !oData || !oData.Result)
+ {
+ RL.data().foldersListError(
+ oData && oData.ErrorCode ? Utils.getNotification(oData.ErrorCode) : Utils.i18n('NOTIFICATIONS/CANT_DELETE_FOLDER'));
+ }
+
+ RL.folders();
+
+ }, oFolderToRemove.fullNameRaw);
+
+ RL.cache().removeFolderFromCacheList(oFolderToRemove.fullNameRaw);
+ }
+ }
+ else if (0 < oFolderToRemove.privateMessageCountAll())
+ {
+ RL.data().foldersListError(Utils.getNotification(Enums.Notification.CantDeleteNonEmptyFolder));
+ }
+};
+
+SettingsFolders.prototype.subscribeFolder = function (oFolder)
+{
+ RL.local().set(Enums.ClientSideKeyName.FoldersLashHash, '');
+ RL.remote().folderSetSubscribe(Utils.emptyFunction, oFolder.fullNameRaw, true);
+
+ oFolder.subScribed(true);
+};
+
+SettingsFolders.prototype.unSubscribeFolder = function (oFolder)
+{
+ RL.local().set(Enums.ClientSideKeyName.FoldersLashHash, '');
+ RL.remote().folderSetSubscribe(Utils.emptyFunction, oFolder.fullNameRaw, false);
+
+ oFolder.subScribed(false);
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ */
+function SettingsThemes()
+{
+ var
+ self = this,
+ oData = RL.data()
+ ;
+
+ this.mainTheme = oData.mainTheme;
+ this.themesObjects = ko.observableArray([]);
+
+ this.themeTrigger = ko.observable(Enums.SaveSettingsStep.Idle).extend({'throttle': 100});
+
+ this.oLastAjax = null;
+ this.iTimer = 0;
+
+ RL.data().theme.subscribe(function (sValue) {
+
+ _.each(this.themesObjects(), function (oTheme) {
+ oTheme.selected(sValue === oTheme.name);
+ });
+
+ var
+ oThemeLink = $('#rlThemeLink'),
+ oThemeStyle = $('#rlThemeStyle'),
+ sUrl = oThemeLink.attr('href')
+ ;
+
+ if (!sUrl)
+ {
+ sUrl = oThemeStyle.attr('data-href');
+ }
+
+ if (sUrl)
+ {
+ sUrl = sUrl.toString().replace(/\/-\/[^\/]+\/\-\//, '/-/' + sValue + '/-/');
+ sUrl = sUrl.toString().replace(/\/Css\/[^\/]+\/User\//, '/Css/0/User/');
+
+ if ('Json/' !== sUrl.substring(sUrl.length - 5, sUrl.length))
+ {
+ sUrl += 'Json/';
+ }
+
+ window.clearTimeout(self.iTimer);
+ self.themeTrigger(Enums.SaveSettingsStep.Animate);
+
+ if (this.oLastAjax && this.oLastAjax.abort)
+ {
+ this.oLastAjax.abort();
+ }
+
+ this.oLastAjax = $.ajax({
+ 'url': sUrl,
+ 'dataType': 'json'
+ }).done(function(aData) {
+ if (aData && Utils.isArray(aData) && 2 === aData.length)
+ {
+ if (oThemeLink && oThemeLink[0] && (!oThemeStyle || !oThemeStyle[0]))
+ {
+ oThemeStyle = $('');
+ oThemeLink.after(oThemeStyle);
+ oThemeLink.remove();
+ }
+
+ if (oThemeStyle && oThemeStyle[0])
+ {
+ oThemeStyle.attr('data-href', sUrl).attr('data-theme', aData[0]);
+ if (oThemeStyle && oThemeStyle[0] && oThemeStyle[0].styleSheet && !Utils.isUnd(oThemeStyle[0].styleSheet.cssText))
+ {
+ oThemeStyle[0].styleSheet.cssText = aData[1];
+ }
+ else
+ {
+ oThemeStyle.text(aData[1]);
+ }
+ }
+
+ self.themeTrigger(Enums.SaveSettingsStep.TrueResult);
+ }
+
+ }).always(function() {
+
+ self.iTimer = window.setTimeout(function () {
+ self.themeTrigger(Enums.SaveSettingsStep.Idle);
+ }, 1000);
+
+ self.oLastAjax = null;
+ });
+ }
+
+ RL.remote().saveSettings(null, {
+ 'Theme': sValue
+ });
+
+ }, this);
+}
+
+Utils.addSettingsViewModel(SettingsThemes, 'SettingsThemes', 'SETTINGS_LABELS/LABEL_THEMES_NAME', 'themes');
+
+SettingsThemes.prototype.onBuild = function ()
+{
+ var sCurrentTheme = RL.data().theme();
+ this.themesObjects(_.map(RL.data().themes(), function (sTheme) {
+ return {
+ 'name': sTheme,
+ 'nameDisplay': Utils.convertThemeName(sTheme),
+ 'selected': ko.observable(sTheme === sCurrentTheme),
+ 'themePreviewSrc': RL.link().themePreviewLink(sTheme)
+ };
+ }));
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ */
+function SettingsOpenPGP()
+{
+ this.openpgpkeys = RL.data().openpgpkeys;
+ this.openpgpkeysPublic = RL.data().openpgpkeysPublic;
+ this.openpgpkeysPrivate = RL.data().openpgpkeysPrivate;
+
+ this.openPgpKeyForDeletion = ko.observable(null).extend({'falseTimeout': 3000}).extend({'toggleSubscribe': [this,
+ function (oPrev) {
+ if (oPrev)
+ {
+ oPrev.deleteAccess(false);
+ }
+ }, function (oNext) {
+ if (oNext)
+ {
+ oNext.deleteAccess(true);
+ }
+ }
+ ]});
+}
+
+Utils.addSettingsViewModel(SettingsOpenPGP, 'SettingsOpenPGP', 'SETTINGS_LABELS/LABEL_OPEN_PGP_NAME', 'openpgp');
+
+SettingsOpenPGP.prototype.addOpenPgpKey = function ()
+{
+ kn.showScreenPopup(PopupsAddOpenPgpKeyViewModel);
+};
+
+SettingsOpenPGP.prototype.generateOpenPgpKey = function ()
+{
+ kn.showScreenPopup(PopupsGenerateNewOpenPgpKeyViewModel);
+};
+
+SettingsOpenPGP.prototype.viewOpenPgpKey = function (oOpenPgpKey)
+{
+ if (oOpenPgpKey)
+ {
+ kn.showScreenPopup(PopupsViewOpenPgpKeyViewModel, [oOpenPgpKey]);
+ }
+};
+
+/**
+ * @param {OpenPgpKeyModel} oOpenPgpKeyToRemove
+ */
+SettingsOpenPGP.prototype.deleteOpenPgpKey = function (oOpenPgpKeyToRemove)
+{
+ if (oOpenPgpKeyToRemove && oOpenPgpKeyToRemove.deleteAccess())
+ {
+ this.openPgpKeyForDeletion(null);
+
+ if (oOpenPgpKeyToRemove && RL.data().openpgpKeyring)
+ {
+ this.openpgpkeys.remove(function (oOpenPgpKey) {
+ return oOpenPgpKeyToRemove === oOpenPgpKey;
+ });
+
+ RL.data().openpgpKeyring[oOpenPgpKeyToRemove.isPrivate ? 'privateKeys' : 'publicKeys']
+ .removeForId(oOpenPgpKeyToRemove.guid);
+
+ RL.data().openpgpKeyring.store();
+
+ RL.reloadOpenPgpKeys();
+ }
+ }
+};
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ */
+function AbstractData()
+{
+ this.leftPanelDisabled = ko.observable(false);
+ this.useKeyboardShortcuts = ko.observable(true);
+
+ this.keyScopeReal = ko.observable(Enums.KeyState.All);
+ this.keyScopeFake = ko.observable(Enums.KeyState.All);
+
+ this.keyScope = ko.computed({
+ 'owner': this,
+ 'read': function () {
+ return this.keyScopeFake();
+ },
+ 'write': function (sValue) {
+
+ if (Enums.KeyState.Menu !== sValue)
+ {
+ if (Enums.KeyState.Compose === sValue)
+ {
+ Utils.disableKeyFilter();
+ }
+ else
+ {
+ Utils.restoreKeyFilter();
+ }
+
+ this.keyScopeFake(sValue);
+ if (Globals.dropdownVisibility())
+ {
+ sValue = Enums.KeyState.Menu;
+ }
+ }
+
+ this.keyScopeReal(sValue);
+ }
+ });
+
+ this.keyScopeReal.subscribe(function (sValue) {
+// window.console.log(sValue);
+ key.setScope(sValue);
+ });
+
+ this.leftPanelDisabled.subscribe(function (bValue) {
+ RL.pub('left-panel.' + (bValue ? 'off' : 'on'));
+ });
+
+ Globals.dropdownVisibility.subscribe(function (bValue) {
+ if (bValue)
+ {
+ Globals.tooltipTrigger(!Globals.tooltipTrigger());
+ this.keyScope(Enums.KeyState.Menu);
+ }
+ else if (Enums.KeyState.Menu === key.getScope())
+ {
+ this.keyScope(this.keyScopeFake());
+ }
+ }, this);
+
+ Utils.initDataConstructorBySettings(this);
+}
+
+AbstractData.prototype.populateDataOnStart = function()
+{
+ var
+ mLayout = Utils.pInt(RL.settingsGet('Layout')),
+ aLanguages = RL.settingsGet('Languages'),
+ aThemes = RL.settingsGet('Themes')
+ ;
+
+ if (Utils.isArray(aLanguages))
+ {
+ this.languages(aLanguages);
+ }
+
+ if (Utils.isArray(aThemes))
+ {
+ this.themes(aThemes);
+ }
+
+ this.mainLanguage(RL.settingsGet('Language'));
+ this.mainTheme(RL.settingsGet('Theme'));
+
+ this.capaAdditionalAccounts(RL.capa(Enums.Capa.AdditionalAccounts));
+ this.capaAdditionalIdentities(RL.capa(Enums.Capa.AdditionalIdentities));
+ this.capaGravatar(RL.capa(Enums.Capa.Gravatar));
+ this.determineUserLanguage(!!RL.settingsGet('DetermineUserLanguage'));
+ this.determineUserDomain(!!RL.settingsGet('DetermineUserDomain'));
+
+ this.capaThemes(RL.capa(Enums.Capa.Themes));
+ this.allowLanguagesOnLogin(!!RL.settingsGet('AllowLanguagesOnLogin'));
+ this.allowLanguagesOnSettings(!!RL.settingsGet('AllowLanguagesOnSettings'));
+ this.useLocalProxyForExternalImages(!!RL.settingsGet('UseLocalProxyForExternalImages'));
+
+ this.editorDefaultType(RL.settingsGet('EditorDefaultType'));
+ this.showImages(!!RL.settingsGet('ShowImages'));
+ this.contactsAutosave(!!RL.settingsGet('ContactsAutosave'));
+ this.interfaceAnimation(RL.settingsGet('InterfaceAnimation'));
+
+ this.mainMessagesPerPage(RL.settingsGet('MPP'));
+
+ this.desktopNotifications(!!RL.settingsGet('DesktopNotifications'));
+ this.useThreads(!!RL.settingsGet('UseThreads'));
+ this.replySameFolder(!!RL.settingsGet('ReplySameFolder'));
+ this.useCheckboxesInList(!!RL.settingsGet('UseCheckboxesInList'));
+
+ this.layout(Enums.Layout.SidePreview);
+ if (-1 < Utils.inArray(mLayout, [Enums.Layout.NoPreview, Enums.Layout.SidePreview, Enums.Layout.BottomPreview]))
+ {
+ this.layout(mLayout);
+ }
+ this.facebookSupported(!!RL.settingsGet('SupportedFacebookSocial'));
+ this.facebookEnable(!!RL.settingsGet('AllowFacebookSocial'));
+ this.facebookAppID(RL.settingsGet('FacebookAppID'));
+ this.facebookAppSecret(RL.settingsGet('FacebookAppSecret'));
+
+ this.twitterEnable(!!RL.settingsGet('AllowTwitterSocial'));
+ this.twitterConsumerKey(RL.settingsGet('TwitterConsumerKey'));
+ this.twitterConsumerSecret(RL.settingsGet('TwitterConsumerSecret'));
+
+ this.googleEnable(!!RL.settingsGet('AllowGoogleSocial'));
+ this.googleClientID(RL.settingsGet('GoogleClientID'));
+ this.googleClientSecret(RL.settingsGet('GoogleClientSecret'));
+ this.googleApiKey(RL.settingsGet('GoogleApiKey'));
+
+ this.dropboxEnable(!!RL.settingsGet('AllowDropboxSocial'));
+ this.dropboxApiKey(RL.settingsGet('DropboxApiKey'));
+
+ this.contactsIsAllowed(!!RL.settingsGet('ContactsIsAllowed'));
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends AbstractData
+ */
+function WebMailDataStorage()
+{
+ AbstractData.call(this);
+
+ var
+ fRemoveSystemFolderType = function (observable) {
+ return function () {
+ var oFolder = RL.cache().getFolderFromCacheList(observable());
+ if (oFolder)
+ {
+ oFolder.type(Enums.FolderType.User);
+ }
+ };
+ },
+ fSetSystemFolderType = function (iType) {
+ return function (sValue) {
+ var oFolder = RL.cache().getFolderFromCacheList(sValue);
+ if (oFolder)
+ {
+ oFolder.type(iType);
+ }
+ };
+ }
+ ;
+
+ this.devEmail = '';
+ this.devPassword = '';
+
+ this.accountEmail = ko.observable('');
+ this.accountIncLogin = ko.observable('');
+ this.accountOutLogin = ko.observable('');
+ this.projectHash = ko.observable('');
+ this.threading = ko.observable(false);
+
+ this.lastFoldersHash = '';
+ this.remoteSuggestions = false;
+
+ // system folders
+ this.sentFolder = ko.observable('');
+ this.draftFolder = ko.observable('');
+ this.spamFolder = ko.observable('');
+ this.trashFolder = ko.observable('');
+ this.archiveFolder = ko.observable('');
+
+ this.sentFolder.subscribe(fRemoveSystemFolderType(this.sentFolder), this, 'beforeChange');
+ this.draftFolder.subscribe(fRemoveSystemFolderType(this.draftFolder), this, 'beforeChange');
+ this.spamFolder.subscribe(fRemoveSystemFolderType(this.spamFolder), this, 'beforeChange');
+ this.trashFolder.subscribe(fRemoveSystemFolderType(this.trashFolder), this, 'beforeChange');
+ this.archiveFolder.subscribe(fRemoveSystemFolderType(this.archiveFolder), this, 'beforeChange');
+
+ this.sentFolder.subscribe(fSetSystemFolderType(Enums.FolderType.SentItems), this);
+ this.draftFolder.subscribe(fSetSystemFolderType(Enums.FolderType.Draft), this);
+ this.spamFolder.subscribe(fSetSystemFolderType(Enums.FolderType.Spam), this);
+ this.trashFolder.subscribe(fSetSystemFolderType(Enums.FolderType.Trash), this);
+ this.archiveFolder.subscribe(fSetSystemFolderType(Enums.FolderType.Archive), this);
+
+ this.draftFolderNotEnabled = ko.computed(function () {
+ return '' === this.draftFolder() || Consts.Values.UnuseOptionValue === this.draftFolder();
+ }, this);
+
+ // personal
+ this.displayName = ko.observable('');
+ this.signature = ko.observable('');
+ this.signatureToAll = ko.observable(false);
+ this.replyTo = ko.observable('');
+
+ // security
+ this.enableTwoFactor = ko.observable(false);
+
+ // accounts
+ this.accounts = ko.observableArray([]);
+ this.accountsLoading = ko.observable(false).extend({'throttle': 100});
+
+ // identities
+ this.defaultIdentityID = ko.observable('');
+ this.identities = ko.observableArray([]);
+ this.identitiesLoading = ko.observable(false).extend({'throttle': 100});
+
+ // contacts
+ this.contactTags = ko.observableArray([]);
+ this.contacts = ko.observableArray([]);
+ this.contacts.loading = ko.observable(false).extend({'throttle': 200});
+ this.contacts.importing = ko.observable(false).extend({'throttle': 200});
+ this.contacts.syncing = ko.observable(false).extend({'throttle': 200});
+ this.contacts.exportingVcf = ko.observable(false).extend({'throttle': 200});
+ this.contacts.exportingCsv = ko.observable(false).extend({'throttle': 200});
+
+ this.allowContactsSync = ko.observable(false);
+ this.enableContactsSync = ko.observable(false);
+ this.contactsSyncUrl = ko.observable('');
+ this.contactsSyncUser = ko.observable('');
+ this.contactsSyncPass = ko.observable('');
+
+ this.allowContactsSync = ko.observable(!!RL.settingsGet('ContactsSyncIsAllowed'));
+ this.enableContactsSync = ko.observable(!!RL.settingsGet('EnableContactsSync'));
+ this.contactsSyncUrl = ko.observable(RL.settingsGet('ContactsSyncUrl'));
+ this.contactsSyncUser = ko.observable(RL.settingsGet('ContactsSyncUser'));
+ this.contactsSyncPass = ko.observable(RL.settingsGet('ContactsSyncPassword'));
+
+ // folders
+ this.namespace = '';
+ this.folderList = ko.observableArray([]);
+ this.folderList.focused = ko.observable(false);
+
+ this.foldersListError = ko.observable('');
+
+ this.foldersLoading = ko.observable(false);
+ this.foldersCreating = ko.observable(false);
+ this.foldersDeleting = ko.observable(false);
+ this.foldersRenaming = ko.observable(false);
+
+ this.foldersChanging = ko.computed(function () {
+ var
+ bLoading = this.foldersLoading(),
+ bCreating = this.foldersCreating(),
+ bDeleting = this.foldersDeleting(),
+ bRenaming = this.foldersRenaming()
+ ;
+ return bLoading || bCreating || bDeleting || bRenaming;
+ }, this);
+
+ this.foldersInboxUnreadCount = ko.observable(0);
+
+ this.currentFolder = ko.observable(null).extend({'toggleSubscribe': [null,
+ function (oPrev) {
+ if (oPrev)
+ {
+ oPrev.selected(false);
+ }
+ }, function (oNext) {
+ if (oNext)
+ {
+ oNext.selected(true);
+ }
+ }
+ ]});
+
+ this.currentFolderFullNameRaw = ko.computed(function () {
+ return this.currentFolder() ? this.currentFolder().fullNameRaw : '';
+ }, this);
+
+ this.currentFolderFullName = ko.computed(function () {
+ return this.currentFolder() ? this.currentFolder().fullName : '';
+ }, this);
+
+ this.currentFolderFullNameHash = ko.computed(function () {
+ return this.currentFolder() ? this.currentFolder().fullNameHash : '';
+ }, this);
+
+ this.currentFolderName = ko.computed(function () {
+ return this.currentFolder() ? this.currentFolder().name() : '';
+ }, this);
+
+ this.folderListSystemNames = ko.computed(function () {
+
+ var
+ aList = ['INBOX'],
+ aFolders = this.folderList(),
+ sSentFolder = this.sentFolder(),
+ sDraftFolder = this.draftFolder(),
+ sSpamFolder = this.spamFolder(),
+ sTrashFolder = this.trashFolder(),
+ sArchiveFolder = this.archiveFolder()
+ ;
+
+ if (Utils.isArray(aFolders) && 0 < aFolders.length)
+ {
+ if ('' !== sSentFolder && Consts.Values.UnuseOptionValue !== sSentFolder)
+ {
+ aList.push(sSentFolder);
+ }
+ if ('' !== sDraftFolder && Consts.Values.UnuseOptionValue !== sDraftFolder)
+ {
+ aList.push(sDraftFolder);
+ }
+ if ('' !== sSpamFolder && Consts.Values.UnuseOptionValue !== sSpamFolder)
+ {
+ aList.push(sSpamFolder);
+ }
+ if ('' !== sTrashFolder && Consts.Values.UnuseOptionValue !== sTrashFolder)
+ {
+ aList.push(sTrashFolder);
+ }
+ if ('' !== sArchiveFolder && Consts.Values.UnuseOptionValue !== sArchiveFolder)
+ {
+ aList.push(sArchiveFolder);
+ }
+ }
+
+ return aList;
+
+ }, this);
+
+ this.folderListSystem = ko.computed(function () {
+ return _.compact(_.map(this.folderListSystemNames(), function (sName) {
+ return RL.cache().getFolderFromCacheList(sName);
+ }));
+ }, this);
+
+ this.folderMenuForMove = ko.computed(function () {
+ return RL.folderListOptionsBuilder(this.folderListSystem(), this.folderList(), [
+ this.currentFolderFullNameRaw()
+ ], null, null, null, null, function (oItem) {
+ return oItem ? oItem.localName() : '';
+ });
+ }, this);
+
+ // message list
+ this.staticMessageList = [];
+
+ this.messageList = ko.observableArray([]).extend({'rateLimit': 0});
+
+ this.messageListCount = ko.observable(0);
+ this.messageListSearch = ko.observable('');
+ this.messageListPage = ko.observable(1);
+
+ this.messageListThreadFolder = ko.observable('');
+ this.messageListThreadUids = ko.observableArray([]);
+
+ this.messageListThreadFolder.subscribe(function () {
+ this.messageListThreadUids([]);
+ }, this);
+
+ this.messageListEndFolder = ko.observable('');
+ this.messageListEndSearch = ko.observable('');
+ this.messageListEndPage = ko.observable(1);
+
+ this.messageListEndHash = ko.computed(function () {
+ return this.messageListEndFolder() + '|' + this.messageListEndSearch() + '|' + this.messageListEndPage();
+ }, this);
+
+ this.messageListPageCount = ko.computed(function () {
+ var iPage = Math.ceil(this.messageListCount() / this.messagesPerPage());
+ return 0 >= iPage ? 1 : iPage;
+ }, this);
+
+ this.mainMessageListSearch = ko.computed({
+ 'read': this.messageListSearch,
+ 'write': function (sValue) {
+ kn.setHash(RL.link().mailBox(
+ this.currentFolderFullNameHash(), 1, Utils.trim(sValue.toString())
+ ));
+ },
+ 'owner': this
+ });
+
+ this.messageListError = ko.observable('');
+
+ this.messageListLoading = ko.observable(false);
+ this.messageListIsNotCompleted = ko.observable(false);
+ this.messageListCompleteLoadingThrottle = ko.observable(false).extend({'throttle': 200});
+
+ this.messageListCompleteLoading = ko.computed(function () {
+ var
+ bOne = this.messageListLoading(),
+ bTwo = this.messageListIsNotCompleted()
+ ;
+ return bOne || bTwo;
+ }, this);
+
+ this.messageListCompleteLoading.subscribe(function (bValue) {
+ this.messageListCompleteLoadingThrottle(bValue);
+ }, this);
+
+ this.messageList.subscribe(_.debounce(function (aList) {
+ _.each(aList, function (oItem) {
+ if (oItem.newForAnimation())
+ {
+ oItem.newForAnimation(false);
+ }
+ });
+ }, 500));
+
+ // message preview
+ this.staticMessageList = new MessageModel();
+ this.message = ko.observable(null);
+ this.messageLoading = ko.observable(false);
+ this.messageLoadingThrottle = ko.observable(false).extend({'throttle': 50});
+
+ this.message.focused = ko.observable(false);
+
+ this.message.subscribe(function (oMessage) {
+ if (!oMessage)
+ {
+ this.message.focused(false);
+ this.messageFullScreenMode(false);
+ this.hideMessageBodies();
+
+ if (Enums.Layout.NoPreview === RL.data().layout() &&
+ -1 < window.location.hash.indexOf('message-preview'))
+ {
+ RL.historyBack();
+ }
+ }
+ else if (Enums.Layout.NoPreview === this.layout())
+ {
+ this.message.focused(true);
+ }
+ }, this);
+
+ this.message.focused.subscribe(function (bValue) {
+ if (bValue)
+ {
+ this.folderList.focused(false);
+ this.keyScope(Enums.KeyState.MessageView);
+ }
+ else if (Enums.KeyState.MessageView === RL.data().keyScope())
+ {
+ if (Enums.Layout.NoPreview === RL.data().layout() && this.message())
+ {
+ this.keyScope(Enums.KeyState.MessageView);
+ }
+ else
+ {
+ this.keyScope(Enums.KeyState.MessageList);
+ }
+ }
+ }, this);
+
+ this.folderList.focused.subscribe(function (bValue) {
+ if (bValue)
+ {
+ RL.data().keyScope(Enums.KeyState.FolderList);
+ }
+ else if (Enums.KeyState.FolderList === RL.data().keyScope())
+ {
+ RL.data().keyScope(Enums.KeyState.MessageList);
+ }
+ });
+
+ this.messageLoading.subscribe(function (bValue) {
+ this.messageLoadingThrottle(bValue);
+ }, this);
+
+ this.messageFullScreenMode = ko.observable(false);
+
+ this.messageError = ko.observable('');
+
+ this.messagesBodiesDom = ko.observable(null);
+
+ this.messagesBodiesDom.subscribe(function (oDom) {
+ if (oDom && !(oDom instanceof jQuery))
+ {
+ this.messagesBodiesDom($(oDom));
+ }
+ }, this);
+
+ this.messageActiveDom = ko.observable(null);
+
+ this.isMessageSelected = ko.computed(function () {
+ return null !== this.message();
+ }, this);
+
+ this.currentMessage = ko.observable(null);
+
+ this.messageListChecked = ko.computed(function () {
+ return _.filter(this.messageList(), function (oItem) {
+ return oItem.checked();
+ });
+ }, this).extend({'rateLimit': 0});
+
+ this.hasCheckedMessages = ko.computed(function () {
+ return 0 < this.messageListChecked().length;
+ }, this).extend({'rateLimit': 0});
+
+ this.messageListCheckedOrSelected = ko.computed(function () {
+
+ var
+ aChecked = this.messageListChecked(),
+ oSelectedMessage = this.currentMessage()
+ ;
+
+ return _.union(aChecked, oSelectedMessage ? [oSelectedMessage] : []);
+
+ }, this);
+
+ this.messageListCheckedOrSelectedUidsWithSubMails = ko.computed(function () {
+ var aList = [];
+ _.each(this.messageListCheckedOrSelected(), function (oMessage) {
+ if (oMessage)
+ {
+ aList.push(oMessage.uid);
+ if (0 < oMessage.threadsLen() && 0 === oMessage.parentUid() && oMessage.lastInCollapsedThread())
+ {
+ aList = _.union(aList, oMessage.threads());
+ }
+ }
+ });
+ return aList;
+ }, this);
+
+ // quota
+ this.userQuota = ko.observable(0);
+ this.userUsageSize = ko.observable(0);
+ this.userUsageProc = ko.computed(function () {
+
+ var
+ iQuota = this.userQuota(),
+ iUsed = this.userUsageSize()
+ ;
+
+ return 0 < iQuota ? Math.ceil((iUsed / iQuota) * 100) : 0;
+
+ }, this);
+
+ // other
+ this.capaOpenPGP = ko.observable(false);
+ this.openpgpkeys = ko.observableArray([]);
+ this.openpgpKeyring = null;
+
+ this.openpgpkeysPublic = this.openpgpkeys.filter(function (oItem) {
+ return !!(oItem && !oItem.isPrivate);
+ });
+
+ this.openpgpkeysPrivate = this.openpgpkeys.filter(function (oItem) {
+ return !!(oItem && oItem.isPrivate);
+ });
+
+ // google
+ this.googleActions = ko.observable(false);
+ this.googleLoggined = ko.observable(false);
+ this.googleUserName = ko.observable('');
+
+ // facebook
+ this.facebookActions = ko.observable(false);
+ this.facebookLoggined = ko.observable(false);
+ this.facebookUserName = ko.observable('');
+
+ // twitter
+ this.twitterActions = ko.observable(false);
+ this.twitterLoggined = ko.observable(false);
+ this.twitterUserName = ko.observable('');
+
+ this.customThemeType = ko.observable(Enums.CustomThemeType.Light);
+
+ this.purgeMessageBodyCacheThrottle = _.throttle(this.purgeMessageBodyCache, 1000 * 30);
+}
+
+_.extend(WebMailDataStorage.prototype, AbstractData.prototype);
+
+WebMailDataStorage.prototype.purgeMessageBodyCache = function()
+{
+ var
+ iCount = 0,
+ oMessagesBodiesDom = null,
+ iEnd = Globals.iMessageBodyCacheCount - Consts.Values.MessageBodyCacheLimit
+ ;
+
+ if (0 < iEnd)
+ {
+ oMessagesBodiesDom = this.messagesBodiesDom();
+ if (oMessagesBodiesDom)
+ {
+ oMessagesBodiesDom.find('.rl-cache-class').each(function () {
+ var oItem = $(this);
+ if (iEnd > oItem.data('rl-cache-count'))
+ {
+ oItem.addClass('rl-cache-purge');
+ iCount++;
+ }
+ });
+
+ if (0 < iCount)
+ {
+ _.delay(function () {
+ oMessagesBodiesDom.find('.rl-cache-purge').remove();
+ }, 300);
+ }
+ }
+ }
+};
+
+WebMailDataStorage.prototype.populateDataOnStart = function()
+{
+ AbstractData.prototype.populateDataOnStart.call(this);
+
+ this.accountEmail(RL.settingsGet('Email'));
+ this.accountIncLogin(RL.settingsGet('IncLogin'));
+ this.accountOutLogin(RL.settingsGet('OutLogin'));
+ this.projectHash(RL.settingsGet('ProjectHash'));
+
+ this.defaultIdentityID(RL.settingsGet('DefaultIdentityID'));
+
+ this.displayName(RL.settingsGet('DisplayName'));
+ this.replyTo(RL.settingsGet('ReplyTo'));
+ this.signature(RL.settingsGet('Signature'));
+ this.signatureToAll(!!RL.settingsGet('SignatureToAll'));
+ this.enableTwoFactor(!!RL.settingsGet('EnableTwoFactor'));
+
+ this.lastFoldersHash = RL.local().get(Enums.ClientSideKeyName.FoldersLashHash) || '';
+
+ this.remoteSuggestions = !!RL.settingsGet('RemoteSuggestions');
+
+ this.devEmail = RL.settingsGet('DevEmail');
+ this.devPassword = RL.settingsGet('DevPassword');
+};
+
+WebMailDataStorage.prototype.initUidNextAndNewMessages = function (sFolder, sUidNext, aNewMessages)
+{
+ if ('INBOX' === sFolder && Utils.isNormal(sUidNext) && sUidNext !== '')
+ {
+ if (Utils.isArray(aNewMessages) && 0 < aNewMessages.length)
+ {
+ var
+ oCache = RL.cache(),
+ iIndex = 0,
+ iLen = aNewMessages.length,
+ fNotificationHelper = function (sImageSrc, sTitle, sText)
+ {
+ var oNotification = null;
+ if (NotificationClass && RL.data().useDesktopNotifications())
+ {
+ oNotification = new NotificationClass(sTitle, {
+ 'body': sText,
+ 'icon': sImageSrc
+ });
+
+ if (oNotification)
+ {
+ if (oNotification.show)
+ {
+ oNotification.show();
+ }
+
+ window.setTimeout((function (oLocalNotifications) {
+ return function () {
+ if (oLocalNotifications.cancel)
+ {
+ oLocalNotifications.cancel();
+ }
+ else if (oLocalNotifications.close)
+ {
+ oLocalNotifications.close();
+ }
+ };
+ }(oNotification)), 7000);
+ }
+ }
+ }
+ ;
+
+ _.each(aNewMessages, function (oItem) {
+ oCache.addNewMessageCache(sFolder, oItem.Uid);
+ });
+
+ if (3 < iLen)
+ {
+ fNotificationHelper(
+ RL.link().notificationMailIcon(),
+ RL.data().accountEmail(),
+ Utils.i18n('MESSAGE_LIST/NEW_MESSAGE_NOTIFICATION', {
+ 'COUNT': iLen
+ })
+ );
+ }
+ else
+ {
+ for (; iIndex < iLen; iIndex++)
+ {
+ fNotificationHelper(
+ RL.link().notificationMailIcon(),
+ MessageModel.emailsToLine(MessageModel.initEmailsFromJson(aNewMessages[iIndex].From), false),
+ aNewMessages[iIndex].Subject
+ );
+ }
+ }
+ }
+
+ RL.cache().setFolderUidNext(sFolder, sUidNext);
+ }
+};
+
+/**
+ * @param {string} sNamespace
+ * @param {Array} aFolders
+ * @return {Array}
+ */
+WebMailDataStorage.prototype.folderResponseParseRec = function (sNamespace, aFolders)
+{
+ var
+ iIndex = 0,
+ iLen = 0,
+ oFolder = null,
+ oCacheFolder = null,
+ sFolderFullNameRaw = '',
+ aSubFolders = [],
+ aList = []
+ ;
+
+ for (iIndex = 0, iLen = aFolders.length; iIndex < iLen; iIndex++)
+ {
+ oFolder = aFolders[iIndex];
+ if (oFolder)
+ {
+ sFolderFullNameRaw = oFolder.FullNameRaw;
+
+ oCacheFolder = RL.cache().getFolderFromCacheList(sFolderFullNameRaw);
+ if (!oCacheFolder)
+ {
+ oCacheFolder = FolderModel.newInstanceFromJson(oFolder);
+ if (oCacheFolder)
+ {
+ RL.cache().setFolderToCacheList(sFolderFullNameRaw, oCacheFolder);
+ RL.cache().setFolderFullNameRaw(oCacheFolder.fullNameHash, sFolderFullNameRaw);
+ }
+ }
+
+ if (oCacheFolder)
+ {
+ oCacheFolder.collapsed(!Utils.isFolderExpanded(oCacheFolder.fullNameHash));
+
+ if (oFolder.Extended)
+ {
+ if (oFolder.Extended.Hash)
+ {
+ RL.cache().setFolderHash(oCacheFolder.fullNameRaw, oFolder.Extended.Hash);
+ }
+
+ if (Utils.isNormal(oFolder.Extended.MessageCount))
+ {
+ oCacheFolder.messageCountAll(oFolder.Extended.MessageCount);
+ }
+
+ if (Utils.isNormal(oFolder.Extended.MessageUnseenCount))
+ {
+ oCacheFolder.messageCountUnread(oFolder.Extended.MessageUnseenCount);
+ }
+ }
+
+ aSubFolders = oFolder['SubFolders'];
+ if (aSubFolders && 'Collection/FolderCollection' === aSubFolders['@Object'] &&
+ aSubFolders['@Collection'] && Utils.isArray(aSubFolders['@Collection']))
+ {
+ oCacheFolder.subFolders(
+ this.folderResponseParseRec(sNamespace, aSubFolders['@Collection']));
+ }
+
+ aList.push(oCacheFolder);
+ }
+ }
+ }
+
+ return aList;
+};
+
+/**
+ * @param {*} oData
+ */
+WebMailDataStorage.prototype.setFolders = function (oData)
+{
+ var
+ aList = [],
+ bUpdate = false,
+ oRLData = RL.data(),
+ fNormalizeFolder = function (sFolderFullNameRaw) {
+ return ('' === sFolderFullNameRaw || Consts.Values.UnuseOptionValue === sFolderFullNameRaw ||
+ null !== RL.cache().getFolderFromCacheList(sFolderFullNameRaw)) ? sFolderFullNameRaw : '';
+ }
+ ;
+
+ if (oData && oData.Result && 'Collection/FolderCollection' === oData.Result['@Object'] &&
+ oData.Result['@Collection'] && Utils.isArray(oData.Result['@Collection']))
+ {
+ if (!Utils.isUnd(oData.Result.Namespace))
+ {
+ oRLData.namespace = oData.Result.Namespace;
+ }
+
+ this.threading(!!RL.settingsGet('UseImapThread') && oData.Result.IsThreadsSupported && true);
+
+ aList = this.folderResponseParseRec(oRLData.namespace, oData.Result['@Collection']);
+ oRLData.folderList(aList);
+
+ if (oData.Result['SystemFolders'] &&
+ '' === '' + RL.settingsGet('SentFolder') + RL.settingsGet('DraftFolder') +
+ RL.settingsGet('SpamFolder') + RL.settingsGet('TrashFolder') + RL.settingsGet('ArchiveFolder') +
+ RL.settingsGet('NullFolder'))
+ {
+ // TODO Magic Numbers
+ RL.settingsSet('SentFolder', oData.Result['SystemFolders'][2] || null);
+ RL.settingsSet('DraftFolder', oData.Result['SystemFolders'][3] || null);
+ RL.settingsSet('SpamFolder', oData.Result['SystemFolders'][4] || null);
+ RL.settingsSet('TrashFolder', oData.Result['SystemFolders'][5] || null);
+ RL.settingsSet('ArchiveFolder', oData.Result['SystemFolders'][12] || null);
+
+ bUpdate = true;
+ }
+
+ oRLData.sentFolder(fNormalizeFolder(RL.settingsGet('SentFolder')));
+ oRLData.draftFolder(fNormalizeFolder(RL.settingsGet('DraftFolder')));
+ oRLData.spamFolder(fNormalizeFolder(RL.settingsGet('SpamFolder')));
+ oRLData.trashFolder(fNormalizeFolder(RL.settingsGet('TrashFolder')));
+ oRLData.archiveFolder(fNormalizeFolder(RL.settingsGet('ArchiveFolder')));
+
+ if (bUpdate)
+ {
+ RL.remote().saveSystemFolders(Utils.emptyFunction, {
+ 'SentFolder': oRLData.sentFolder(),
+ 'DraftFolder': oRLData.draftFolder(),
+ 'SpamFolder': oRLData.spamFolder(),
+ 'TrashFolder': oRLData.trashFolder(),
+ 'ArchiveFolder': oRLData.archiveFolder(),
+ 'NullFolder': 'NullFolder'
+ });
+ }
+
+ RL.local().set(Enums.ClientSideKeyName.FoldersLashHash, oData.Result.FoldersHash);
+ }
+};
+
+WebMailDataStorage.prototype.hideMessageBodies = function ()
+{
+ var oMessagesBodiesDom = this.messagesBodiesDom();
+ if (oMessagesBodiesDom)
+ {
+ oMessagesBodiesDom.find('.b-text-part').hide();
+ }
+};
+
+/**
+ * @param {boolean=} bBoot = false
+ * @returns {Array}
+ */
+WebMailDataStorage.prototype.getNextFolderNames = function (bBoot)
+{
+ bBoot = Utils.isUnd(bBoot) ? false : !!bBoot;
+
+ var
+ aResult = [],
+ iLimit = 10,
+ iUtc = moment().unix(),
+ iTimeout = iUtc - 60 * 5,
+ aTimeouts = [],
+ fSearchFunction = function (aList) {
+ _.each(aList, function (oFolder) {
+ if (oFolder && 'INBOX' !== oFolder.fullNameRaw &&
+ oFolder.selectable && oFolder.existen &&
+ iTimeout > oFolder.interval &&
+ (!bBoot || oFolder.subScribed()))
+ {
+ aTimeouts.push([oFolder.interval, oFolder.fullNameRaw]);
+ }
+
+ if (oFolder && 0 < oFolder.subFolders().length)
+ {
+ fSearchFunction(oFolder.subFolders());
+ }
+ });
+ }
+ ;
+
+ fSearchFunction(this.folderList());
+
+ aTimeouts.sort(function(a, b) {
+ if (a[0] < b[0])
+ {
+ return -1;
+ }
+ else if (a[0] > b[0])
+ {
+ return 1;
+ }
+
+ return 0;
+ });
+
+ _.find(aTimeouts, function (aItem) {
+ var oFolder = RL.cache().getFolderFromCacheList(aItem[1]);
+ if (oFolder)
+ {
+ oFolder.interval = iUtc;
+ aResult.push(aItem[1]);
+ }
+
+ return iLimit <= aResult.length;
+ });
+
+ return _.uniq(aResult);
+};
+
+/**
+ * @param {string} sFromFolderFullNameRaw
+ * @param {Array} aUidForRemove
+ * @param {string=} sToFolderFullNameRaw = ''
+ * @param {bCopy=} bCopy = false
+ */
+WebMailDataStorage.prototype.removeMessagesFromList = function (
+ sFromFolderFullNameRaw, aUidForRemove, sToFolderFullNameRaw, bCopy)
+{
+ sToFolderFullNameRaw = Utils.isNormal(sToFolderFullNameRaw) ? sToFolderFullNameRaw : '';
+ bCopy = Utils.isUnd(bCopy) ? false : !!bCopy;
+
+ aUidForRemove = _.map(aUidForRemove, function (mValue) {
+ return Utils.pInt(mValue);
+ });
+
+ var
+ iUnseenCount = 0,
+ oData = RL.data(),
+ oCache = RL.cache(),
+ aMessageList = oData.messageList(),
+ oFromFolder = RL.cache().getFolderFromCacheList(sFromFolderFullNameRaw),
+ oToFolder = '' === sToFolderFullNameRaw ? null : oCache.getFolderFromCacheList(sToFolderFullNameRaw || ''),
+ sCurrentFolderFullNameRaw = oData.currentFolderFullNameRaw(),
+ oCurrentMessage = oData.message(),
+ aMessages = sCurrentFolderFullNameRaw === sFromFolderFullNameRaw ? _.filter(aMessageList, function (oMessage) {
+ return oMessage && -1 < Utils.inArray(Utils.pInt(oMessage.uid), aUidForRemove);
+ }) : []
+ ;
+
+ _.each(aMessages, function (oMessage) {
+ if (oMessage && oMessage.unseen())
+ {
+ iUnseenCount++;
+ }
+ });
+
+ if (oFromFolder && !bCopy)
+ {
+ oFromFolder.messageCountAll(0 <= oFromFolder.messageCountAll() - aUidForRemove.length ?
+ oFromFolder.messageCountAll() - aUidForRemove.length : 0);
+
+ if (0 < iUnseenCount)
+ {
+ oFromFolder.messageCountUnread(0 <= oFromFolder.messageCountUnread() - iUnseenCount ?
+ oFromFolder.messageCountUnread() - iUnseenCount : 0);
+ }
+ }
+
+ if (oToFolder)
+ {
+ oToFolder.messageCountAll(oToFolder.messageCountAll() + aUidForRemove.length);
+ if (0 < iUnseenCount)
+ {
+ oToFolder.messageCountUnread(oToFolder.messageCountUnread() + iUnseenCount);
+ }
+
+ oToFolder.actionBlink(true);
+ }
+
+ if (0 < aMessages.length)
+ {
+ if (bCopy)
+ {
+ _.each(aMessages, function (oMessage) {
+ oMessage.checked(false);
+ });
+ }
+ else
+ {
+ oData.messageListIsNotCompleted(true);
+
+ _.each(aMessages, function (oMessage) {
+ if (oCurrentMessage && oCurrentMessage.hash === oMessage.hash)
+ {
+ oCurrentMessage = null;
+ oData.message(null);
+ }
+
+ oMessage.deleted(true);
+ });
+
+ _.delay(function () {
+ _.each(aMessages, function (oMessage) {
+ oData.messageList.remove(oMessage);
+ });
+ }, 400);
+ }
+ }
+
+ if ('' !== sFromFolderFullNameRaw)
+ {
+ oCache.setFolderHash(sFromFolderFullNameRaw, '');
+ }
+
+ if ('' !== sToFolderFullNameRaw)
+ {
+ oCache.setFolderHash(sToFolderFullNameRaw, '');
+ }
+};
+
+WebMailDataStorage.prototype.setMessage = function (oData, bCached)
+{
+ var
+ bIsHtml = false,
+ bHasExternals = false,
+ bHasInternals = false,
+ oBody = null,
+ oTextBody = null,
+ sId = '',
+ sResultHtml = '',
+ bPgpSigned = false,
+ bPgpEncrypted = false,
+ oMessagesBodiesDom = this.messagesBodiesDom(),
+ oMessage = this.message()
+ ;
+
+ if (oData && oMessage && oData.Result && 'Object/Message' === oData.Result['@Object'] &&
+ oMessage.folderFullNameRaw === oData.Result.Folder && oMessage.uid === oData.Result.Uid)
+ {
+ this.messageError('');
+
+ oMessage.initUpdateByMessageJson(oData.Result);
+ RL.cache().addRequestedMessage(oMessage.folderFullNameRaw, oMessage.uid);
+
+ if (!bCached)
+ {
+ oMessage.initFlagsByJson(oData.Result);
+ }
+
+ oMessagesBodiesDom = oMessagesBodiesDom && oMessagesBodiesDom[0] ? oMessagesBodiesDom : null;
+ if (oMessagesBodiesDom)
+ {
+ sId = 'rl-mgs-' + oMessage.hash.replace(/[^a-zA-Z0-9]/g, '');
+ oTextBody = oMessagesBodiesDom.find('#' + sId);
+ if (!oTextBody || !oTextBody[0])
+ {
+ bHasExternals = !!oData.Result.HasExternals;
+ bHasInternals = !!oData.Result.HasInternals;
+
+ oBody = $('').hide().addClass('rl-cache-class');
+ oBody.data('rl-cache-count', ++Globals.iMessageBodyCacheCount);
+
+ if (Utils.isNormal(oData.Result.Html) && '' !== oData.Result.Html)
+ {
+ bIsHtml = true;
+ sResultHtml = oData.Result.Html.toString();
+ }
+ else if (Utils.isNormal(oData.Result.Plain) && '' !== oData.Result.Plain)
+ {
+ bIsHtml = false;
+ sResultHtml = Utils.plainToHtml(oData.Result.Plain.toString(), false);
+
+ if ((oMessage.isPgpSigned() || oMessage.isPgpEncrypted()) && RL.data().capaOpenPGP())
+ {
+ oMessage.plainRaw = Utils.pString(oData.Result.Plain);
+
+ bPgpEncrypted = /---BEGIN PGP MESSAGE---/.test(oMessage.plainRaw);
+ if (!bPgpEncrypted)
+ {
+ bPgpSigned = /-----BEGIN PGP SIGNED MESSAGE-----/.test(oMessage.plainRaw) &&
+ /-----BEGIN PGP SIGNATURE-----/.test(oMessage.plainRaw);
+ }
+
+ $proxyDiv.empty();
+ if (bPgpSigned && oMessage.isPgpSigned())
+ {
+ sResultHtml =
+ $proxyDiv.append(
+ $('').text(oMessage.plainRaw)
+ ).html()
+ ;
+ }
+ else if (bPgpEncrypted && oMessage.isPgpEncrypted())
+ {
+ sResultHtml =
+ $proxyDiv.append(
+ $('').text(oMessage.plainRaw)
+ ).html()
+ ;
+ }
+
+ $proxyDiv.empty();
+
+ oMessage.isPgpSigned(bPgpSigned);
+ oMessage.isPgpEncrypted(bPgpEncrypted);
+ }
+ }
+ else
+ {
+ bIsHtml = false;
+ }
+
+ oBody
+ .html(Utils.linkify(sResultHtml))
+ .addClass('b-text-part ' + (bIsHtml ? 'html' : 'plain'))
+ ;
+
+ oMessage.isHtml(!!bIsHtml);
+ oMessage.hasImages(!!bHasExternals);
+ oMessage.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.None);
+ oMessage.pgpSignedVerifyUser('');
+
+ oMessage.body = oBody;
+ if (oMessage.body)
+ {
+ oMessagesBodiesDom.append(oMessage.body);
+ }
+
+ oMessage.storeDataToDom();
+
+ if (bHasInternals)
+ {
+ oMessage.showInternalImages(true);
+ }
+
+ if (oMessage.hasImages() && this.showImages())
+ {
+ oMessage.showExternalImages(true);
+ }
+
+ this.purgeMessageBodyCacheThrottle();
+ }
+ else
+ {
+ oMessage.body = oTextBody;
+ if (oMessage.body)
+ {
+ oMessage.body.data('rl-cache-count', ++Globals.iMessageBodyCacheCount);
+ oMessage.fetchDataToDom();
+ }
+ }
+
+ this.messageActiveDom(oMessage.body);
+
+ this.hideMessageBodies();
+ oMessage.body.show();
+
+ if (oBody)
+ {
+ Utils.initBlockquoteSwitcher(oBody);
+ }
+ }
+
+ RL.cache().initMessageFlagsFromCache(oMessage);
+ if (oMessage.unseen())
+ {
+ RL.setMessageSeen(oMessage);
+ }
+
+ Utils.windowResize();
+ }
+};
+
+/**
+ * @param {Array} aList
+ * @returns {string}
+ */
+WebMailDataStorage.prototype.calculateMessageListHash = function (aList)
+{
+ return _.map(aList, function (oMessage) {
+ return '' + oMessage.hash + '_' + oMessage.threadsLen() + '_' + oMessage.flagHash();
+ }).join('|');
+};
+
+WebMailDataStorage.prototype.setMessageList = function (oData, bCached)
+{
+ if (oData && oData.Result && 'Collection/MessageCollection' === oData.Result['@Object'] &&
+ oData.Result['@Collection'] && Utils.isArray(oData.Result['@Collection']))
+ {
+ var
+ oRainLoopData = RL.data(),
+ oCache = RL.cache(),
+ mLastCollapsedThreadUids = null,
+ iIndex = 0,
+ iLen = 0,
+ iCount = 0,
+ iOffset = 0,
+ aList = [],
+ iUtc = moment().unix(),
+ aStaticList = oRainLoopData.staticMessageList,
+ oJsonMessage = null,
+ oMessage = null,
+ oFolder = null,
+ iNewCount = 0,
+ bUnreadCountChange = false
+ ;
+
+ iCount = Utils.pInt(oData.Result.MessageResultCount);
+ iOffset = Utils.pInt(oData.Result.Offset);
+
+ if (Utils.isNonEmptyArray(oData.Result.LastCollapsedThreadUids))
+ {
+ mLastCollapsedThreadUids = oData.Result.LastCollapsedThreadUids;
+ }
+
+ oFolder = RL.cache().getFolderFromCacheList(
+ Utils.isNormal(oData.Result.Folder) ? oData.Result.Folder : '');
+
+ if (oFolder && !bCached)
+ {
+ oFolder.interval = iUtc;
+
+ RL.cache().setFolderHash(oData.Result.Folder, oData.Result.FolderHash);
+
+ if (Utils.isNormal(oData.Result.MessageCount))
+ {
+ oFolder.messageCountAll(oData.Result.MessageCount);
+ }
+
+ if (Utils.isNormal(oData.Result.MessageUnseenCount))
+ {
+ if (Utils.pInt(oFolder.messageCountUnread()) !== Utils.pInt(oData.Result.MessageUnseenCount))
+ {
+ bUnreadCountChange = true;
+ }
+
+ oFolder.messageCountUnread(oData.Result.MessageUnseenCount);
+ }
+
+ this.initUidNextAndNewMessages(oFolder.fullNameRaw, oData.Result.UidNext, oData.Result.NewMessages);
+ }
+
+ if (bUnreadCountChange && oFolder)
+ {
+ RL.cache().clearMessageFlagsFromCacheByFolder(oFolder.fullNameRaw);
+ }
+
+ for (iIndex = 0, iLen = oData.Result['@Collection'].length; iIndex < iLen; iIndex++)
+ {
+ oJsonMessage = oData.Result['@Collection'][iIndex];
+ if (oJsonMessage && 'Object/Message' === oJsonMessage['@Object'])
+ {
+ oMessage = aStaticList[iIndex];
+ if (!oMessage || !oMessage.initByJson(oJsonMessage))
+ {
+ oMessage = MessageModel.newInstanceFromJson(oJsonMessage);
+ }
+
+ if (oMessage)
+ {
+ if (oCache.hasNewMessageAndRemoveFromCache(oMessage.folderFullNameRaw, oMessage.uid) && 5 >= iNewCount)
+ {
+ iNewCount++;
+ oMessage.newForAnimation(true);
+ }
+
+ oMessage.deleted(false);
+
+ if (bCached)
+ {
+ RL.cache().initMessageFlagsFromCache(oMessage);
+ }
+ else
+ {
+ RL.cache().storeMessageFlagsToCache(oMessage);
+ }
+
+ oMessage.lastInCollapsedThread(mLastCollapsedThreadUids && -1 < Utils.inArray(Utils.pInt(oMessage.uid), mLastCollapsedThreadUids) ? true : false);
+
+ aList.push(oMessage);
+ }
+ }
+ }
+
+ oRainLoopData.messageListCount(iCount);
+ oRainLoopData.messageListSearch(Utils.isNormal(oData.Result.Search) ? oData.Result.Search : '');
+ oRainLoopData.messageListPage(Math.ceil((iOffset / oRainLoopData.messagesPerPage()) + 1));
+ oRainLoopData.messageListEndFolder(Utils.isNormal(oData.Result.Folder) ? oData.Result.Folder : '');
+ oRainLoopData.messageListEndSearch(Utils.isNormal(oData.Result.Search) ? oData.Result.Search : '');
+ oRainLoopData.messageListEndPage(oRainLoopData.messageListPage());
+
+ oRainLoopData.messageList(aList);
+ oRainLoopData.messageListIsNotCompleted(false);
+
+ if (aStaticList.length < aList.length)
+ {
+ oRainLoopData.staticMessageList = aList;
+ }
+
+ oCache.clearNewMessageCache();
+
+ if (oFolder && (bCached || bUnreadCountChange || RL.data().useThreads()))
+ {
+ RL.folderInformation(oFolder.fullNameRaw, aList);
+ }
+ }
+ else
+ {
+ RL.data().messageListCount(0);
+ RL.data().messageList([]);
+ RL.data().messageListError(Utils.getNotification(
+ oData && oData.ErrorCode ? oData.ErrorCode : Enums.Notification.CantGetMessageList
+ ));
+ }
+};
+
+WebMailDataStorage.prototype.findPublicKeyByHex = function (sHash)
+{
+ return _.find(this.openpgpkeysPublic(), function (oItem) {
+ return oItem && sHash === oItem.id;
+ });
+};
+
+WebMailDataStorage.prototype.findPublicKeysByEmail = function (sEmail)
+{
+ return _.compact(_.map(this.openpgpkeysPublic(), function (oItem) {
+
+ var oKey = null;
+ if (oItem && sEmail === oItem.email)
+ {
+ try
+ {
+ oKey = window.openpgp.key.readArmored(oItem.armor);
+ if (oKey && !oKey.err && oKey.keys && oKey.keys[0])
+ {
+ return oKey.keys[0];
+ }
+ }
+ catch (e) {}
+ }
+
+ return null;
+
+ }));
+};
+
+/**
+ * @param {string} sEmail
+ * @param {string=} sPassword
+ * @returns {?}
+ */
+WebMailDataStorage.prototype.findPrivateKeyByEmail = function (sEmail, sPassword)
+{
+ var
+ oPrivateKey = null,
+ oKey = _.find(this.openpgpkeysPrivate(), function (oItem) {
+ return oItem && sEmail === oItem.email;
+ })
+ ;
+
+ if (oKey)
+ {
+ try
+ {
+ oPrivateKey = window.openpgp.key.readArmored(oKey.armor);
+ if (oPrivateKey && !oPrivateKey.err && oPrivateKey.keys && oPrivateKey.keys[0])
+ {
+ oPrivateKey = oPrivateKey.keys[0];
+ oPrivateKey.decrypt(Utils.pString(sPassword));
+ }
+ else
+ {
+ oPrivateKey = null;
+ }
+ }
+ catch (e)
+ {
+ oPrivateKey = null;
+ }
+ }
+
+ return oPrivateKey;
+};
+
+/**
+ * @param {string=} sPassword
+ * @returns {?}
+ */
+WebMailDataStorage.prototype.findSelfPrivateKey = function (sPassword)
+{
+ return this.findPrivateKeyByEmail(this.accountEmail(), sPassword);
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ */
+function AbstractAjaxRemoteStorage()
+{
+ this.oRequests = {};
+}
+
+AbstractAjaxRemoteStorage.prototype.oRequests = {};
+
+/**
+ * @param {?Function} fCallback
+ * @param {string} sRequestAction
+ * @param {string} sType
+ * @param {?AjaxJsonDefaultResponse} oData
+ * @param {boolean} bCached
+ * @param {*=} oRequestParameters
+ */
+AbstractAjaxRemoteStorage.prototype.defaultResponse = function (fCallback, sRequestAction, sType, oData, bCached, oRequestParameters)
+{
+ var
+ fCall = function () {
+ if (Enums.StorageResultType.Success !== sType && Globals.bUnload)
+ {
+ sType = Enums.StorageResultType.Unload;
+ }
+
+ if (Enums.StorageResultType.Success === sType && oData && !oData.Result)
+ {
+ if (oData && -1 < Utils.inArray(oData.ErrorCode, [
+ Enums.Notification.AuthError, Enums.Notification.AccessError,
+ Enums.Notification.ConnectionError, Enums.Notification.DomainNotAllowed, Enums.Notification.AccountNotAllowed,
+ Enums.Notification.MailServerError, Enums.Notification.UnknownNotification, Enums.Notification.UnknownError
+ ]))
+ {
+ Globals.iAjaxErrorCount++;
+ }
+
+ if (oData && Enums.Notification.InvalidToken === oData.ErrorCode)
+ {
+ Globals.iTokenErrorCount++;
+ }
+
+ if (Consts.Values.TokenErrorLimit < Globals.iTokenErrorCount)
+ {
+ RL.loginAndLogoutReload(true);
+ }
+
+ if (oData.Logout || Consts.Values.AjaxErrorLimit < Globals.iAjaxErrorCount)
+ {
+ if (window.__rlah_clear)
+ {
+ window.__rlah_clear();
+ }
+
+ RL.loginAndLogoutReload(true);
+ }
+ }
+ else if (Enums.StorageResultType.Success === sType && oData && oData.Result)
+ {
+ Globals.iAjaxErrorCount = 0;
+ Globals.iTokenErrorCount = 0;
+ }
+
+ if (fCallback)
+ {
+ Plugins.runHook('ajax-default-response', [sRequestAction, Enums.StorageResultType.Success === sType ? oData : null, sType, bCached, oRequestParameters]);
+
+ fCallback(
+ sType,
+ Enums.StorageResultType.Success === sType ? oData : null,
+ bCached,
+ sRequestAction,
+ oRequestParameters
+ );
+ }
+ }
+ ;
+
+ switch (sType)
+ {
+ case 'success':
+ sType = Enums.StorageResultType.Success;
+ break;
+ case 'abort':
+ sType = Enums.StorageResultType.Abort;
+ break;
+ default:
+ sType = Enums.StorageResultType.Error;
+ break;
+ }
+
+ if (Enums.StorageResultType.Error === sType)
+ {
+ _.delay(fCall, 300);
+ }
+ else
+ {
+ fCall();
+ }
+};
+
+/**
+ * @param {?Function} fResultCallback
+ * @param {Object} oParameters
+ * @param {?number=} iTimeOut = 20000
+ * @param {string=} sGetAdd = ''
+ * @param {Array=} aAbortActions = []
+ * @return {jQuery.jqXHR}
+ */
+AbstractAjaxRemoteStorage.prototype.ajaxRequest = function (fResultCallback, oParameters, iTimeOut, sGetAdd, aAbortActions)
+{
+ var
+ self = this,
+ bPost = '' === sGetAdd,
+ oHeaders = {},
+ iStart = (new window.Date()).getTime(),
+ oDefAjax = null,
+ sAction = ''
+ ;
+
+ oParameters = oParameters || {};
+ iTimeOut = Utils.isNormal(iTimeOut) ? iTimeOut : 20000;
+ sGetAdd = Utils.isUnd(sGetAdd) ? '' : Utils.pString(sGetAdd);
+ aAbortActions = Utils.isArray(aAbortActions) ? aAbortActions : [];
+
+ sAction = oParameters.Action || '';
+
+ if (sAction && 0 < aAbortActions.length)
+ {
+ _.each(aAbortActions, function (sActionToAbort) {
+ if (self.oRequests[sActionToAbort])
+ {
+ self.oRequests[sActionToAbort].__aborted = true;
+ if (self.oRequests[sActionToAbort].abort)
+ {
+ self.oRequests[sActionToAbort].abort();
+ }
+ self.oRequests[sActionToAbort] = null;
+ }
+ });
+ }
+
+ if (bPost)
+ {
+ oParameters['XToken'] = RL.settingsGet('Token');
+ }
+
+ oDefAjax = $.ajax({
+ 'type': bPost ? 'POST' : 'GET',
+ 'url': RL.link().ajax(sGetAdd),
+ 'async': true,
+ 'dataType': 'json',
+ 'data': bPost ? oParameters : {},
+ 'headers': oHeaders,
+ 'timeout': iTimeOut,
+ 'global': true
+ });
+
+ oDefAjax.always(function (oData, sType) {
+
+ var bCached = false;
+ if (oData && oData['Time'])
+ {
+ bCached = Utils.pInt(oData['Time']) > (new window.Date()).getTime() - iStart;
+ }
+
+ if (sAction && self.oRequests[sAction])
+ {
+ if (self.oRequests[sAction].__aborted)
+ {
+ sType = 'abort';
+ }
+
+ self.oRequests[sAction] = null;
+ }
+
+ self.defaultResponse(fResultCallback, sAction, sType, oData, bCached, oParameters);
+ });
+
+ if (sAction && 0 < aAbortActions.length && -1 < Utils.inArray(sAction, aAbortActions))
+ {
+ if (this.oRequests[sAction])
+ {
+ this.oRequests[sAction].__aborted = true;
+ if (this.oRequests[sAction].abort)
+ {
+ this.oRequests[sAction].abort();
+ }
+ this.oRequests[sAction] = null;
+ }
+
+ this.oRequests[sAction] = oDefAjax;
+ }
+
+ return oDefAjax;
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {string} sAction
+ * @param {Object=} oParameters
+ * @param {?number=} iTimeout
+ * @param {string=} sGetAdd = ''
+ * @param {Array=} aAbortActions = []
+ */
+AbstractAjaxRemoteStorage.prototype.defaultRequest = function (fCallback, sAction, oParameters, iTimeout, sGetAdd, aAbortActions)
+{
+ oParameters = oParameters || {};
+ oParameters.Action = sAction;
+
+ sGetAdd = Utils.pString(sGetAdd);
+
+ Plugins.runHook('ajax-default-request', [sAction, oParameters, sGetAdd]);
+
+ this.ajaxRequest(fCallback, oParameters,
+ Utils.isUnd(iTimeout) ? Consts.Defaults.DefaultAjaxTimeout : Utils.pInt(iTimeout), sGetAdd, aAbortActions);
+};
+
+/**
+ * @param {?Function} fCallback
+ */
+AbstractAjaxRemoteStorage.prototype.noop = function (fCallback)
+{
+ this.defaultRequest(fCallback, 'Noop');
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {string} sMessage
+ * @param {string} sFileName
+ * @param {number} iLineNo
+ * @param {string} sLocation
+ * @param {string} sHtmlCapa
+ * @param {number} iTime
+ */
+AbstractAjaxRemoteStorage.prototype.jsError = function (fCallback, sMessage, sFileName, iLineNo, sLocation, sHtmlCapa, iTime)
+{
+ this.defaultRequest(fCallback, 'JsError', {
+ 'Message': sMessage,
+ 'FileName': sFileName,
+ 'LineNo': iLineNo,
+ 'Location': sLocation,
+ 'HtmlCapa': sHtmlCapa,
+ 'TimeOnPage': iTime
+ });
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {string} sType
+ * @param {Array=} mData = null
+ * @param {boolean=} bIsError = false
+ */
+AbstractAjaxRemoteStorage.prototype.jsInfo = function (fCallback, sType, mData, bIsError)
+{
+ this.defaultRequest(fCallback, 'JsInfo', {
+ 'Type': sType,
+ 'Data': mData,
+ 'IsError': (Utils.isUnd(bIsError) ? false : !!bIsError) ? '1' : '0'
+ });
+};
+
+/**
+ * @param {?Function} fCallback
+ */
+AbstractAjaxRemoteStorage.prototype.getPublicKey = function (fCallback)
+{
+ this.defaultRequest(fCallback, 'GetPublicKey');
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {string} sVersion
+ */
+AbstractAjaxRemoteStorage.prototype.jsVersion = function (fCallback, sVersion)
+{
+ this.defaultRequest(fCallback, 'Version', {
+ 'Version': sVersion
+ });
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends AbstractAjaxRemoteStorage
+ */
+function WebMailAjaxRemoteStorage()
+{
+ AbstractAjaxRemoteStorage.call(this);
+
+ this.oRequests = {};
+}
+
+_.extend(WebMailAjaxRemoteStorage.prototype, AbstractAjaxRemoteStorage.prototype);
+
+/**
+ * @param {?Function} fCallback
+ */
+WebMailAjaxRemoteStorage.prototype.folders = function (fCallback)
+{
+ this.defaultRequest(fCallback, 'Folders', {
+ 'SentFolder': RL.settingsGet('SentFolder'),
+ 'DraftFolder': RL.settingsGet('DraftFolder'),
+ 'SpamFolder': RL.settingsGet('SpamFolder'),
+ 'TrashFolder': RL.settingsGet('TrashFolder'),
+ 'ArchiveFolder': RL.settingsGet('ArchiveFolder')
+ }, null, '', ['Folders']);
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {string} sEmail
+ * @param {string} sLogin
+ * @param {string} sPassword
+ * @param {boolean} bSignMe
+ * @param {string=} sLanguage
+ * @param {string=} sAdditionalCode
+ * @param {boolean=} bAdditionalCodeSignMe
+ */
+WebMailAjaxRemoteStorage.prototype.login = function (fCallback, sEmail, sLogin, sPassword, bSignMe, sLanguage, sAdditionalCode, bAdditionalCodeSignMe)
+{
+ this.defaultRequest(fCallback, 'Login', {
+ 'Email': sEmail,
+ 'Login': sLogin,
+ 'Password': sPassword,
+ 'Language': sLanguage || '',
+ 'AdditionalCode': sAdditionalCode || '',
+ 'AdditionalCodeSignMe': bAdditionalCodeSignMe ? '1' : '0',
+ 'SignMe': bSignMe ? '1' : '0'
+ });
+};
+
+/**
+ * @param {?Function} fCallback
+ */
+WebMailAjaxRemoteStorage.prototype.getTwoFactor = function (fCallback)
+{
+ this.defaultRequest(fCallback, 'GetTwoFactorInfo');
+};
+
+/**
+ * @param {?Function} fCallback
+ */
+WebMailAjaxRemoteStorage.prototype.createTwoFactor = function (fCallback)
+{
+ this.defaultRequest(fCallback, 'CreateTwoFactorSecret');
+};
+
+/**
+ * @param {?Function} fCallback
+ */
+WebMailAjaxRemoteStorage.prototype.clearTwoFactor = function (fCallback)
+{
+ this.defaultRequest(fCallback, 'ClearTwoFactorInfo');
+};
+
+/**
+ * @param {?Function} fCallback
+ */
+WebMailAjaxRemoteStorage.prototype.showTwoFactorSecret = function (fCallback)
+{
+ this.defaultRequest(fCallback, 'ShowTwoFactorSecret');
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {string} sCode
+ */
+WebMailAjaxRemoteStorage.prototype.testTwoFactor = function (fCallback, sCode)
+{
+ this.defaultRequest(fCallback, 'TestTwoFactorInfo', {
+ 'Code': sCode
+ });
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {boolean} bEnable
+ */
+WebMailAjaxRemoteStorage.prototype.enableTwoFactor = function (fCallback, bEnable)
+{
+ this.defaultRequest(fCallback, 'EnableTwoFactor', {
+ 'Enable': bEnable ? '1' : '0'
+ });
+};
+
+/**
+ * @param {?Function} fCallback
+ */
+WebMailAjaxRemoteStorage.prototype.clearTwoFactorInfo = function (fCallback)
+{
+ this.defaultRequest(fCallback, 'ClearTwoFactorInfo');
+};
+
+/**
+ * @param {?Function} fCallback
+ */
+WebMailAjaxRemoteStorage.prototype.contactsSync = function (fCallback)
+{
+ this.defaultRequest(fCallback, 'ContactsSync', null, Consts.Defaults.ContactsSyncAjaxTimeout);
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {boolean} bEnable
+ * @param {string} sUrl
+ * @param {string} sUser
+ * @param {string} sPassword
+ */
+WebMailAjaxRemoteStorage.prototype.saveContactsSyncData = function (fCallback, bEnable, sUrl, sUser, sPassword)
+{
+ this.defaultRequest(fCallback, 'SaveContactsSyncData', {
+ 'Enable': bEnable ? '1' : '0',
+ 'Url': sUrl,
+ 'User': sUser,
+ 'Password': sPassword
+ });
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {string} sEmail
+ * @param {string} sLogin
+ * @param {string} sPassword
+ */
+WebMailAjaxRemoteStorage.prototype.accountAdd = function (fCallback, sEmail, sLogin, sPassword)
+{
+ this.defaultRequest(fCallback, 'AccountAdd', {
+ 'Email': sEmail,
+ 'Login': sLogin,
+ 'Password': sPassword
+ });
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {string} sEmailToDelete
+ */
+WebMailAjaxRemoteStorage.prototype.accountDelete = function (fCallback, sEmailToDelete)
+{
+ this.defaultRequest(fCallback, 'AccountDelete', {
+ 'EmailToDelete': sEmailToDelete
+ });
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {string} sId
+ * @param {string} sEmail
+ * @param {string} sName
+ * @param {string} sReplyTo
+ * @param {string} sBcc
+ */
+WebMailAjaxRemoteStorage.prototype.identityUpdate = function (fCallback, sId, sEmail, sName, sReplyTo, sBcc)
+{
+ this.defaultRequest(fCallback, 'IdentityUpdate', {
+ 'Id': sId,
+ 'Email': sEmail,
+ 'Name': sName,
+ 'ReplyTo': sReplyTo,
+ 'Bcc': sBcc
+ });
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {string} sIdToDelete
+ */
+WebMailAjaxRemoteStorage.prototype.identityDelete = function (fCallback, sIdToDelete)
+{
+ this.defaultRequest(fCallback, 'IdentityDelete', {
+ 'IdToDelete': sIdToDelete
+ });
+};
+
+/**
+ * @param {?Function} fCallback
+ */
+WebMailAjaxRemoteStorage.prototype.accountsAndIdentities = function (fCallback)
+{
+ this.defaultRequest(fCallback, 'AccountsAndIdentities');
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {string} sFolderFullNameRaw
+ * @param {number=} iOffset = 0
+ * @param {number=} iLimit = 20
+ * @param {string=} sSearch = ''
+ * @param {boolean=} bSilent = false
+ */
+WebMailAjaxRemoteStorage.prototype.messageList = function (fCallback, sFolderFullNameRaw, iOffset, iLimit, sSearch, bSilent)
+{
+ sFolderFullNameRaw = Utils.pString(sFolderFullNameRaw);
+
+ var
+ oData = RL.data(),
+ sFolderHash = RL.cache().getFolderHash(sFolderFullNameRaw)
+ ;
+
+ bSilent = Utils.isUnd(bSilent) ? false : !!bSilent;
+ iOffset = Utils.isUnd(iOffset) ? 0 : Utils.pInt(iOffset);
+ iLimit = Utils.isUnd(iOffset) ? 20 : Utils.pInt(iLimit);
+ sSearch = Utils.pString(sSearch);
+
+ if ('' !== sFolderHash && ('' === sSearch || -1 === sSearch.indexOf('is:')))
+ {
+ this.defaultRequest(fCallback, 'MessageList', {},
+ '' === sSearch ? Consts.Defaults.DefaultAjaxTimeout : Consts.Defaults.SearchAjaxTimeout,
+ 'MessageList/' + Base64.urlsafe_encode([
+ sFolderFullNameRaw,
+ iOffset,
+ iLimit,
+ sSearch,
+ oData.projectHash(),
+ sFolderHash,
+ 'INBOX' === sFolderFullNameRaw ? RL.cache().getFolderUidNext(sFolderFullNameRaw) : '',
+ oData.threading() && oData.useThreads() ? '1' : '0',
+ oData.threading() && sFolderFullNameRaw === oData.messageListThreadFolder() ? oData.messageListThreadUids().join(',') : ''
+ ].join(String.fromCharCode(0))), bSilent ? [] : ['MessageList']);
+ }
+ else
+ {
+ this.defaultRequest(fCallback, 'MessageList', {
+ 'Folder': sFolderFullNameRaw,
+ 'Offset': iOffset,
+ 'Limit': iLimit,
+ 'Search': sSearch,
+ 'UidNext': 'INBOX' === sFolderFullNameRaw ? RL.cache().getFolderUidNext(sFolderFullNameRaw) : '',
+ 'UseThreads': RL.data().threading() && RL.data().useThreads() ? '1' : '0',
+ 'ExpandedThreadUid': oData.threading() && sFolderFullNameRaw === oData.messageListThreadFolder() ? oData.messageListThreadUids().join(',') : ''
+ }, '' === sSearch ? Consts.Defaults.DefaultAjaxTimeout : Consts.Defaults.SearchAjaxTimeout, '', bSilent ? [] : ['MessageList']);
+ }
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {Array} aDownloads
+ */
+WebMailAjaxRemoteStorage.prototype.messageUploadAttachments = function (fCallback, aDownloads)
+{
+ this.defaultRequest(fCallback, 'MessageUploadAttachments', {
+ 'Attachments': aDownloads
+ }, 999000);
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {string} sFolderFullNameRaw
+ * @param {number} iUid
+ * @return {boolean}
+ */
+WebMailAjaxRemoteStorage.prototype.message = function (fCallback, sFolderFullNameRaw, iUid)
+{
+ sFolderFullNameRaw = Utils.pString(sFolderFullNameRaw);
+ iUid = Utils.pInt(iUid);
+
+ if (RL.cache().getFolderFromCacheList(sFolderFullNameRaw) && 0 < iUid)
+ {
+ this.defaultRequest(fCallback, 'Message', {}, null,
+ 'Message/' + Base64.urlsafe_encode([
+ sFolderFullNameRaw,
+ iUid,
+ RL.data().projectHash(),
+ RL.data().threading() && RL.data().useThreads() ? '1' : '0'
+ ].join(String.fromCharCode(0))), ['Message']);
+
+ return true;
+ }
+
+ return false;
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {Array} aExternals
+ */
+WebMailAjaxRemoteStorage.prototype.composeUploadExternals = function (fCallback, aExternals)
+{
+ this.defaultRequest(fCallback, 'ComposeUploadExternals', {
+ 'Externals': aExternals
+ }, 999000);
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {string} sUrl
+ * @param {string} sAccessToken
+ */
+WebMailAjaxRemoteStorage.prototype.composeUploadDrive = function (fCallback, sUrl, sAccessToken)
+{
+ this.defaultRequest(fCallback, 'ComposeUploadDrive', {
+ 'AccessToken': sAccessToken,
+ 'Url': sUrl
+ }, 999000);
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {string} sFolder
+ * @param {Array=} aList = []
+ */
+WebMailAjaxRemoteStorage.prototype.folderInformation = function (fCallback, sFolder, aList)
+{
+ var
+ bRequest = true,
+ oCache = RL.cache(),
+ aUids = []
+ ;
+
+ if (Utils.isArray(aList) && 0 < aList.length)
+ {
+ bRequest = false;
+ _.each(aList, function (oMessageListItem) {
+ if (!oCache.getMessageFlagsFromCache(oMessageListItem.folderFullNameRaw, oMessageListItem.uid))
+ {
+ aUids.push(oMessageListItem.uid);
+ }
+
+ if (0 < oMessageListItem.threads().length)
+ {
+ _.each(oMessageListItem.threads(), function (sUid) {
+ if (!oCache.getMessageFlagsFromCache(oMessageListItem.folderFullNameRaw, sUid))
+ {
+ aUids.push(sUid);
+ }
+ });
+ }
+ });
+
+ if (0 < aUids.length)
+ {
+ bRequest = true;
+ }
+ }
+
+ if (bRequest)
+ {
+ this.defaultRequest(fCallback, 'FolderInformation', {
+ 'Folder': sFolder,
+ 'FlagsUids': Utils.isArray(aUids) ? aUids.join(',') : '',
+ 'UidNext': 'INBOX' === sFolder ? RL.cache().getFolderUidNext(sFolder) : ''
+ });
+ }
+ else if (RL.data().useThreads())
+ {
+ RL.reloadFlagsCurrentMessageListAndMessageFromCache();
+ }
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {Array} aFolders
+ */
+WebMailAjaxRemoteStorage.prototype.folderInformationMultiply = function (fCallback, aFolders)
+{
+ this.defaultRequest(fCallback, 'FolderInformationMultiply', {
+ 'Folders': aFolders
+ });
+};
+
+/**
+ * @param {?Function} fCallback
+ */
+WebMailAjaxRemoteStorage.prototype.logout = function (fCallback)
+{
+ this.defaultRequest(fCallback, 'Logout');
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {string} sFolderFullNameRaw
+ * @param {Array} aUids
+ * @param {boolean} bSetFlagged
+ */
+WebMailAjaxRemoteStorage.prototype.messageSetFlagged = function (fCallback, sFolderFullNameRaw, aUids, bSetFlagged)
+{
+ this.defaultRequest(fCallback, 'MessageSetFlagged', {
+ 'Folder': sFolderFullNameRaw,
+ 'Uids': aUids.join(','),
+ 'SetAction': bSetFlagged ? '1' : '0'
+ });
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {string} sFolderFullNameRaw
+ * @param {Array} aUids
+ * @param {boolean} bSetSeen
+ */
+WebMailAjaxRemoteStorage.prototype.messageSetSeen = function (fCallback, sFolderFullNameRaw, aUids, bSetSeen)
+{
+ this.defaultRequest(fCallback, 'MessageSetSeen', {
+ 'Folder': sFolderFullNameRaw,
+ 'Uids': aUids.join(','),
+ 'SetAction': bSetSeen ? '1' : '0'
+ });
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {string} sFolderFullNameRaw
+ * @param {boolean} bSetSeen
+ */
+WebMailAjaxRemoteStorage.prototype.messageSetSeenToAll = function (fCallback, sFolderFullNameRaw, bSetSeen)
+{
+ this.defaultRequest(fCallback, 'MessageSetSeenToAll', {
+ 'Folder': sFolderFullNameRaw,
+ 'SetAction': bSetSeen ? '1' : '0'
+ });
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {string} sMessageFolder
+ * @param {string} sMessageUid
+ * @param {string} sDraftFolder
+ * @param {string} sFrom
+ * @param {string} sTo
+ * @param {string} sCc
+ * @param {string} sBcc
+ * @param {string} sSubject
+ * @param {boolean} bTextIsHtml
+ * @param {string} sText
+ * @param {Array} aAttachments
+ * @param {(Array|null)} aDraftInfo
+ * @param {string} sInReplyTo
+ * @param {string} sReferences
+ */
+WebMailAjaxRemoteStorage.prototype.saveMessage = function (fCallback, sMessageFolder, sMessageUid, sDraftFolder,
+ sFrom, sTo, sCc, sBcc, sSubject, bTextIsHtml, sText, aAttachments, aDraftInfo, sInReplyTo, sReferences)
+{
+ this.defaultRequest(fCallback, 'SaveMessage', {
+ 'MessageFolder': sMessageFolder,
+ 'MessageUid': sMessageUid,
+ 'DraftFolder': sDraftFolder,
+ 'From': sFrom,
+ 'To': sTo,
+ 'Cc': sCc,
+ 'Bcc': sBcc,
+ 'Subject': sSubject,
+ 'TextIsHtml': bTextIsHtml ? '1' : '0',
+ 'Text': sText,
+ 'DraftInfo': aDraftInfo,
+ 'InReplyTo': sInReplyTo,
+ 'References': sReferences,
+ 'Attachments': aAttachments
+ }, Consts.Defaults.SaveMessageAjaxTimeout);
+};
+
+
+/**
+ * @param {?Function} fCallback
+ * @param {string} sMessageFolder
+ * @param {string} sMessageUid
+ * @param {string} sReadReceipt
+ * @param {string} sSubject
+ * @param {string} sText
+ */
+WebMailAjaxRemoteStorage.prototype.sendReadReceiptMessage = function (fCallback, sMessageFolder, sMessageUid, sReadReceipt, sSubject, sText)
+{
+ this.defaultRequest(fCallback, 'SendReadReceiptMessage', {
+ 'MessageFolder': sMessageFolder,
+ 'MessageUid': sMessageUid,
+ 'ReadReceipt': sReadReceipt,
+ 'Subject': sSubject,
+ 'Text': sText
+ });
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {string} sMessageFolder
+ * @param {string} sMessageUid
+ * @param {string} sSentFolder
+ * @param {string} sFrom
+ * @param {string} sTo
+ * @param {string} sCc
+ * @param {string} sBcc
+ * @param {string} sSubject
+ * @param {boolean} bTextIsHtml
+ * @param {string} sText
+ * @param {Array} aAttachments
+ * @param {(Array|null)} aDraftInfo
+ * @param {string} sInReplyTo
+ * @param {string} sReferences
+ * @param {boolean} bRequestReadReceipt
+ */
+WebMailAjaxRemoteStorage.prototype.sendMessage = function (fCallback, sMessageFolder, sMessageUid, sSentFolder,
+ sFrom, sTo, sCc, sBcc, sSubject, bTextIsHtml, sText, aAttachments, aDraftInfo, sInReplyTo, sReferences, bRequestReadReceipt)
+{
+ this.defaultRequest(fCallback, 'SendMessage', {
+ 'MessageFolder': sMessageFolder,
+ 'MessageUid': sMessageUid,
+ 'SentFolder': sSentFolder,
+ 'From': sFrom,
+ 'To': sTo,
+ 'Cc': sCc,
+ 'Bcc': sBcc,
+ 'Subject': sSubject,
+ 'TextIsHtml': bTextIsHtml ? '1' : '0',
+ 'Text': sText,
+ 'DraftInfo': aDraftInfo,
+ 'InReplyTo': sInReplyTo,
+ 'References': sReferences,
+ 'ReadReceiptRequest': bRequestReadReceipt ? '1' : '0',
+ 'Attachments': aAttachments
+ }, Consts.Defaults.SendMessageAjaxTimeout);
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {Object} oData
+ */
+WebMailAjaxRemoteStorage.prototype.saveSystemFolders = function (fCallback, oData)
+{
+ this.defaultRequest(fCallback, 'SystemFoldersUpdate', oData);
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {Object} oData
+ */
+WebMailAjaxRemoteStorage.prototype.saveSettings = function (fCallback, oData)
+{
+ this.defaultRequest(fCallback, 'SettingsUpdate', oData);
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {string} sPrevPassword
+ * @param {string} sNewPassword
+ */
+WebMailAjaxRemoteStorage.prototype.changePassword = function (fCallback, sPrevPassword, sNewPassword)
+{
+ this.defaultRequest(fCallback, 'ChangePassword', {
+ 'PrevPassword': sPrevPassword,
+ 'NewPassword': sNewPassword
+ });
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {string} sNewFolderName
+ * @param {string} sParentName
+ */
+WebMailAjaxRemoteStorage.prototype.folderCreate = function (fCallback, sNewFolderName, sParentName)
+{
+ this.defaultRequest(fCallback, 'FolderCreate', {
+ 'Folder': sNewFolderName,
+ 'Parent': sParentName
+ }, null, '', ['Folders']);
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {string} sFolderFullNameRaw
+ */
+WebMailAjaxRemoteStorage.prototype.folderDelete = function (fCallback, sFolderFullNameRaw)
+{
+ this.defaultRequest(fCallback, 'FolderDelete', {
+ 'Folder': sFolderFullNameRaw
+ }, null, '', ['Folders']);
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {string} sPrevFolderFullNameRaw
+ * @param {string} sNewFolderName
+ */
+WebMailAjaxRemoteStorage.prototype.folderRename = function (fCallback, sPrevFolderFullNameRaw, sNewFolderName)
+{
+ this.defaultRequest(fCallback, 'FolderRename', {
+ 'Folder': sPrevFolderFullNameRaw,
+ 'NewFolderName': sNewFolderName
+ }, null, '', ['Folders']);
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {string} sFolderFullNameRaw
+ */
+WebMailAjaxRemoteStorage.prototype.folderClear = function (fCallback, sFolderFullNameRaw)
+{
+ this.defaultRequest(fCallback, 'FolderClear', {
+ 'Folder': sFolderFullNameRaw
+ });
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {string} sFolderFullNameRaw
+ * @param {boolean} bSubscribe
+ */
+WebMailAjaxRemoteStorage.prototype.folderSetSubscribe = function (fCallback, sFolderFullNameRaw, bSubscribe)
+{
+ this.defaultRequest(fCallback, 'FolderSubscribe', {
+ 'Folder': sFolderFullNameRaw,
+ 'Subscribe': bSubscribe ? '1' : '0'
+ });
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {string} sFolder
+ * @param {string} sToFolder
+ * @param {Array} aUids
+ * @param {string=} sLearning
+ */
+WebMailAjaxRemoteStorage.prototype.messagesMove = function (fCallback, sFolder, sToFolder, aUids, sLearning)
+{
+ this.defaultRequest(fCallback, 'MessageMove', {
+ 'FromFolder': sFolder,
+ 'ToFolder': sToFolder,
+ 'Uids': aUids.join(','),
+ 'Learning': sLearning || ''
+ }, null, '', ['MessageList']);
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {string} sFolder
+ * @param {string} sToFolder
+ * @param {Array} aUids
+ */
+WebMailAjaxRemoteStorage.prototype.messagesCopy = function (fCallback, sFolder, sToFolder, aUids)
+{
+ this.defaultRequest(fCallback, 'MessageCopy', {
+ 'FromFolder': sFolder,
+ 'ToFolder': sToFolder,
+ 'Uids': aUids.join(',')
+ });
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {string} sFolder
+ * @param {Array} aUids
+ */
+WebMailAjaxRemoteStorage.prototype.messagesDelete = function (fCallback, sFolder, aUids)
+{
+ this.defaultRequest(fCallback, 'MessageDelete', {
+ 'Folder': sFolder,
+ 'Uids': aUids.join(',')
+ }, null, '', ['MessageList']);
+};
+
+/**
+ * @param {?Function} fCallback
+ */
+WebMailAjaxRemoteStorage.prototype.appDelayStart = function (fCallback)
+{
+ this.defaultRequest(fCallback, 'AppDelayStart');
+};
+
+/**
+ * @param {?Function} fCallback
+ */
+WebMailAjaxRemoteStorage.prototype.quota = function (fCallback)
+{
+ this.defaultRequest(fCallback, 'Quota');
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {number} iOffset
+ * @param {number} iLimit
+ * @param {string} sSearch
+ */
+WebMailAjaxRemoteStorage.prototype.contacts = function (fCallback, iOffset, iLimit, sSearch)
+{
+ this.defaultRequest(fCallback, 'Contacts', {
+ 'Offset': iOffset,
+ 'Limit': iLimit,
+ 'Search': sSearch
+ }, null, '', ['Contacts']);
+};
+
+/**
+ * @param {?Function} fCallback
+ */
+WebMailAjaxRemoteStorage.prototype.contactSave = function (fCallback, sRequestUid, sUid, sTags, aProperties)
+{
+ this.defaultRequest(fCallback, 'ContactSave', {
+ 'RequestUid': sRequestUid,
+ 'Uid': Utils.trim(sUid),
+ 'Tags': Utils.trim(sTags),
+ 'Properties': aProperties
+ });
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {Array} aUids
+ */
+WebMailAjaxRemoteStorage.prototype.contactsDelete = function (fCallback, aUids)
+{
+ this.defaultRequest(fCallback, 'ContactsDelete', {
+ 'Uids': aUids.join(',')
+ });
+};
+
+/**
+ * @param {?Function} fCallback
+ * @param {string} sQuery
+ * @param {number} iPage
+ */
+WebMailAjaxRemoteStorage.prototype.suggestions = function (fCallback, sQuery, iPage)
+{
+ this.defaultRequest(fCallback, 'Suggestions', {
+ 'Query': sQuery,
+ 'Page': iPage
+ }, null, '', ['Suggestions']);
+};
+
+/**
+ * @param {?Function} fCallback
+ */
+WebMailAjaxRemoteStorage.prototype.facebookUser = function (fCallback)
+{
+ this.defaultRequest(fCallback, 'SocialFacebookUserInformation');
+};
+
+/**
+ * @param {?Function} fCallback
+ */
+WebMailAjaxRemoteStorage.prototype.facebookDisconnect = function (fCallback)
+{
+ this.defaultRequest(fCallback, 'SocialFacebookDisconnect');
+};
+
+/**
+ * @param {?Function} fCallback
+ */
+WebMailAjaxRemoteStorage.prototype.twitterUser = function (fCallback)
+{
+ this.defaultRequest(fCallback, 'SocialTwitterUserInformation');
+};
+
+/**
+ * @param {?Function} fCallback
+ */
+WebMailAjaxRemoteStorage.prototype.twitterDisconnect = function (fCallback)
+{
+ this.defaultRequest(fCallback, 'SocialTwitterDisconnect');
+};
+
+/**
+ * @param {?Function} fCallback
+ */
+WebMailAjaxRemoteStorage.prototype.googleUser = function (fCallback)
+{
+ this.defaultRequest(fCallback, 'SocialGoogleUserInformation');
+};
+
+/**
+ * @param {?Function} fCallback
+ */
+WebMailAjaxRemoteStorage.prototype.googleDisconnect = function (fCallback)
+{
+ this.defaultRequest(fCallback, 'SocialGoogleDisconnect');
+};
+
+/**
+ * @param {?Function} fCallback
+ */
+WebMailAjaxRemoteStorage.prototype.socialUsers = function (fCallback)
+{
+ this.defaultRequest(fCallback, 'SocialUsers');
+};
+
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ */
+function AbstractCacheStorage()
+{
+ this.bCapaGravatar = RL.capa(Enums.Capa.Gravatar);
+}
+
+/**
+ * @type {Object}
+ */
+AbstractCacheStorage.prototype.oServices = {};
+
+/**
+ * @type {boolean}
+ */
+AbstractCacheStorage.prototype.bCapaGravatar = false;
+
+AbstractCacheStorage.prototype.clear = function ()
+{
+ this.bCapaGravatar = !!this.bCapaGravatar; // TODO
+};
+
+/**
+ * @param {string} sEmail
+ * @return {string}
+ */
+AbstractCacheStorage.prototype.getUserPic = function (sEmail, fCallback)
+{
+ sEmail = Utils.trim(sEmail);
+ fCallback(this.bCapaGravatar && '' !== sEmail ? RL.link().avatarLink(sEmail) : '', sEmail);
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends AbstractCacheStorage
+ */
+function WebMailCacheStorage()
+{
+ AbstractCacheStorage.call(this);
+
+ this.oFoldersCache = {};
+ this.oFoldersNamesCache = {};
+ this.oFolderHashCache = {};
+ this.oFolderUidNextCache = {};
+ this.oMessageListHashCache = {};
+ this.oMessageFlagsCache = {};
+ this.oNewMessage = {};
+ this.oRequestedMessage = {};
+}
+
+_.extend(WebMailCacheStorage.prototype, AbstractCacheStorage.prototype);
+
+/**
+ * @type {Object}
+ */
+WebMailCacheStorage.prototype.oFoldersCache = {};
+
+/**
+ * @type {Object}
+ */
+WebMailCacheStorage.prototype.oFoldersNamesCache = {};
+
+/**
+ * @type {Object}
+ */
+WebMailCacheStorage.prototype.oFolderHashCache = {};
+
+/**
+ * @type {Object}
+ */
+WebMailCacheStorage.prototype.oFolderUidNextCache = {};
+
+/**
+ * @type {Object}
+ */
+WebMailCacheStorage.prototype.oMessageListHashCache = {};
+
+/**
+ * @type {Object}
+ */
+WebMailCacheStorage.prototype.oMessageFlagsCache = {};
+
+/**
+ * @type {Object}
+ */
+WebMailCacheStorage.prototype.oBodies = {};
+
+/**
+ * @type {Object}
+ */
+WebMailCacheStorage.prototype.oNewMessage = {};
+
+/**
+ * @type {Object}
+ */
+WebMailCacheStorage.prototype.oRequestedMessage = {};
+
+WebMailCacheStorage.prototype.clear = function ()
+{
+ AbstractCacheStorage.prototype.clear.call(this);
+
+ this.oFoldersCache = {};
+ this.oFoldersNamesCache = {};
+ this.oFolderHashCache = {};
+ this.oFolderUidNextCache = {};
+ this.oMessageListHashCache = {};
+ this.oMessageFlagsCache = {};
+ this.oBodies = {};
+};
+
+/**
+ * @param {string} sFolderFullNameRaw
+ * @param {string} sUid
+ * @return {string}
+ */
+WebMailCacheStorage.prototype.getMessageKey = function (sFolderFullNameRaw, sUid)
+{
+ return sFolderFullNameRaw + '#' + sUid;
+};
+
+/**
+ * @param {string} sFolder
+ * @param {string} sUid
+ */
+WebMailCacheStorage.prototype.addRequestedMessage = function (sFolder, sUid)
+{
+ this.oRequestedMessage[this.getMessageKey(sFolder, sUid)] = true;
+};
+
+/**
+ * @param {string} sFolder
+ * @param {string} sUid
+ * @return {boolean}
+ */
+WebMailCacheStorage.prototype.hasRequestedMessage = function (sFolder, sUid)
+{
+ return true === this.oRequestedMessage[this.getMessageKey(sFolder, sUid)];
+};
+
+/**
+ * @param {string} sFolderFullNameRaw
+ * @param {string} sUid
+ */
+WebMailCacheStorage.prototype.addNewMessageCache = function (sFolderFullNameRaw, sUid)
+{
+ this.oNewMessage[this.getMessageKey(sFolderFullNameRaw, sUid)] = true;
+};
+
+/**
+ * @param {string} sFolderFullNameRaw
+ * @param {string} sUid
+ */
+WebMailCacheStorage.prototype.hasNewMessageAndRemoveFromCache = function (sFolderFullNameRaw, sUid)
+{
+ if (this.oNewMessage[this.getMessageKey(sFolderFullNameRaw, sUid)])
+ {
+ this.oNewMessage[this.getMessageKey(sFolderFullNameRaw, sUid)] = null;
+ return true;
+ }
+
+ return false;
+};
+
+WebMailCacheStorage.prototype.clearNewMessageCache = function ()
+{
+ this.oNewMessage = {};
+};
+
+/**
+ * @param {string} sFolderHash
+ * @return {string}
+ */
+WebMailCacheStorage.prototype.getFolderFullNameRaw = function (sFolderHash)
+{
+ return '' !== sFolderHash && this.oFoldersNamesCache[sFolderHash] ? this.oFoldersNamesCache[sFolderHash] : '';
+};
+
+/**
+ * @param {string} sFolderHash
+ * @param {string} sFolderFullNameRaw
+ */
+WebMailCacheStorage.prototype.setFolderFullNameRaw = function (sFolderHash, sFolderFullNameRaw)
+{
+ this.oFoldersNamesCache[sFolderHash] = sFolderFullNameRaw;
+};
+
+/**
+ * @param {string} sFolderFullNameRaw
+ * @return {string}
+ */
+WebMailCacheStorage.prototype.getFolderHash = function (sFolderFullNameRaw)
+{
+ return '' !== sFolderFullNameRaw && this.oFolderHashCache[sFolderFullNameRaw] ? this.oFolderHashCache[sFolderFullNameRaw] : '';
+};
+
+/**
+ * @param {string} sFolderFullNameRaw
+ * @param {string} sFolderHash
+ */
+WebMailCacheStorage.prototype.setFolderHash = function (sFolderFullNameRaw, sFolderHash)
+{
+ this.oFolderHashCache[sFolderFullNameRaw] = sFolderHash;
+};
+
+/**
+ * @param {string} sFolderFullNameRaw
+ * @return {string}
+ */
+WebMailCacheStorage.prototype.getFolderUidNext = function (sFolderFullNameRaw)
+{
+ return '' !== sFolderFullNameRaw && this.oFolderUidNextCache[sFolderFullNameRaw] ? this.oFolderUidNextCache[sFolderFullNameRaw] : '';
+};
+
+/**
+ * @param {string} sFolderFullNameRaw
+ * @param {string} sUidNext
+ */
+WebMailCacheStorage.prototype.setFolderUidNext = function (sFolderFullNameRaw, sUidNext)
+{
+ this.oFolderUidNextCache[sFolderFullNameRaw] = sUidNext;
+};
+
+/**
+ * @param {string} sFolderFullNameRaw
+ * @return {?FolderModel}
+ */
+WebMailCacheStorage.prototype.getFolderFromCacheList = function (sFolderFullNameRaw)
+{
+ return '' !== sFolderFullNameRaw && this.oFoldersCache[sFolderFullNameRaw] ? this.oFoldersCache[sFolderFullNameRaw] : null;
+};
+
+/**
+ * @param {string} sFolderFullNameRaw
+ * @param {?FolderModel} oFolder
+ */
+WebMailCacheStorage.prototype.setFolderToCacheList = function (sFolderFullNameRaw, oFolder)
+{
+ this.oFoldersCache[sFolderFullNameRaw] = oFolder;
+};
+
+/**
+ * @param {string} sFolderFullNameRaw
+ */
+WebMailCacheStorage.prototype.removeFolderFromCacheList = function (sFolderFullNameRaw)
+{
+ this.setFolderToCacheList(sFolderFullNameRaw, null);
+};
+
+/**
+ * @param {string} sFolderFullName
+ * @param {string} sUid
+ * @return {?Array}
+ */
+WebMailCacheStorage.prototype.getMessageFlagsFromCache = function (sFolderFullName, sUid)
+{
+ return this.oMessageFlagsCache[sFolderFullName] && this.oMessageFlagsCache[sFolderFullName][sUid] ?
+ this.oMessageFlagsCache[sFolderFullName][sUid] : null;
+};
+
+/**
+ * @param {string} sFolderFullName
+ * @param {string} sUid
+ * @param {Array} aFlagsCache
+ */
+WebMailCacheStorage.prototype.setMessageFlagsToCache = function (sFolderFullName, sUid, aFlagsCache)
+{
+ if (!this.oMessageFlagsCache[sFolderFullName])
+ {
+ this.oMessageFlagsCache[sFolderFullName] = {};
+ }
+
+ this.oMessageFlagsCache[sFolderFullName][sUid] = aFlagsCache;
+};
+
+/**
+ * @param {string} sFolderFullName
+ */
+WebMailCacheStorage.prototype.clearMessageFlagsFromCacheByFolder = function (sFolderFullName)
+{
+ this.oMessageFlagsCache[sFolderFullName] = {};
+};
+
+/**
+ * @param {(MessageModel|null)} oMessage
+ */
+WebMailCacheStorage.prototype.initMessageFlagsFromCache = function (oMessage)
+{
+ if (oMessage)
+ {
+ var
+ self = this,
+ aFlags = this.getMessageFlagsFromCache(oMessage.folderFullNameRaw, oMessage.uid),
+ mUnseenSubUid = null,
+ mFlaggedSubUid = null
+ ;
+
+ if (aFlags && 0 < aFlags.length)
+ {
+ oMessage.unseen(!!aFlags[0]);
+ oMessage.flagged(!!aFlags[1]);
+ oMessage.answered(!!aFlags[2]);
+ oMessage.forwarded(!!aFlags[3]);
+ oMessage.isReadReceipt(!!aFlags[4]);
+ }
+
+ if (0 < oMessage.threads().length)
+ {
+ mUnseenSubUid = _.find(oMessage.threads(), function (iSubUid) {
+ var aFlags = self.getMessageFlagsFromCache(oMessage.folderFullNameRaw, iSubUid);
+ return aFlags && 0 < aFlags.length && !!aFlags[0];
+ });
+
+ mFlaggedSubUid = _.find(oMessage.threads(), function (iSubUid) {
+ var aFlags = self.getMessageFlagsFromCache(oMessage.folderFullNameRaw, iSubUid);
+ return aFlags && 0 < aFlags.length && !!aFlags[1];
+ });
+
+ oMessage.hasUnseenSubMessage(mUnseenSubUid && 0 < Utils.pInt(mUnseenSubUid));
+ oMessage.hasFlaggedSubMessage(mFlaggedSubUid && 0 < Utils.pInt(mFlaggedSubUid));
+ }
+ }
+};
+
+/**
+ * @param {(MessageModel|null)} oMessage
+ */
+WebMailCacheStorage.prototype.storeMessageFlagsToCache = function (oMessage)
+{
+ if (oMessage)
+ {
+ this.setMessageFlagsToCache(
+ oMessage.folderFullNameRaw,
+ oMessage.uid,
+ [oMessage.unseen(), oMessage.flagged(), oMessage.answered(), oMessage.forwarded(), oMessage.isReadReceipt()]
+ );
+ }
+};
+/**
+ * @param {string} sFolder
+ * @param {string} sUid
+ * @param {Array} aFlags
+ */
+WebMailCacheStorage.prototype.storeMessageFlagsToCacheByFolderAndUid = function (sFolder, sUid, aFlags)
+{
+ if (Utils.isArray(aFlags) && 0 < aFlags.length)
+ {
+ this.setMessageFlagsToCache(sFolder, sUid, aFlags);
+ }
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @param {Array} aViewModels
+ * @constructor
+ * @extends KnoinAbstractScreen
+ */
+function AbstractSettings(aViewModels)
+{
+ KnoinAbstractScreen.call(this, 'settings', aViewModels);
+
+ this.menu = ko.observableArray([]);
+
+ this.oCurrentSubScreen = null;
+ this.oViewModelPlace = null;
+}
+
+_.extend(AbstractSettings.prototype, KnoinAbstractScreen.prototype);
+
+AbstractSettings.prototype.onRoute = function (sSubName)
+{
+ var
+ self = this,
+ oSettingsScreen = null,
+ RoutedSettingsViewModel = null,
+ oViewModelPlace = null,
+ oViewModelDom = null
+ ;
+
+ RoutedSettingsViewModel = _.find(ViewModels['settings'], function (SettingsViewModel) {
+ return SettingsViewModel && SettingsViewModel.__rlSettingsData &&
+ sSubName === SettingsViewModel.__rlSettingsData.Route;
+ });
+
+ if (RoutedSettingsViewModel)
+ {
+ if (_.find(ViewModels['settings-removed'], function (DisabledSettingsViewModel) {
+ return DisabledSettingsViewModel && DisabledSettingsViewModel === RoutedSettingsViewModel;
+ }))
+ {
+ RoutedSettingsViewModel = null;
+ }
+
+ if (RoutedSettingsViewModel && _.find(ViewModels['settings-disabled'], function (DisabledSettingsViewModel) {
+ return DisabledSettingsViewModel && DisabledSettingsViewModel === RoutedSettingsViewModel;
+ }))
+ {
+ RoutedSettingsViewModel = null;
+ }
+ }
+
+ if (RoutedSettingsViewModel)
+ {
+ if (RoutedSettingsViewModel.__builded && RoutedSettingsViewModel.__vm)
+ {
+ oSettingsScreen = RoutedSettingsViewModel.__vm;
+ }
+ else
+ {
+ oViewModelPlace = this.oViewModelPlace;
+ if (oViewModelPlace && 1 === oViewModelPlace.length)
+ {
+ RoutedSettingsViewModel = /** @type {?Function} */ RoutedSettingsViewModel;
+ oSettingsScreen = new RoutedSettingsViewModel();
+
+ oViewModelDom = $('').addClass('rl-settings-view-model').hide();
+ oViewModelDom.appendTo(oViewModelPlace);
+
+ oSettingsScreen.data = RL.data();
+ oSettingsScreen.viewModelDom = oViewModelDom;
+
+ oSettingsScreen.__rlSettingsData = RoutedSettingsViewModel.__rlSettingsData;
+
+ RoutedSettingsViewModel.__dom = oViewModelDom;
+ RoutedSettingsViewModel.__builded = true;
+ RoutedSettingsViewModel.__vm = oSettingsScreen;
+
+ ko.applyBindingAccessorsToNode(oViewModelDom[0], {
+ 'i18nInit': true,
+ 'template': function () { return {'name': RoutedSettingsViewModel.__rlSettingsData.Template}; }
+ }, oSettingsScreen);
+
+ Utils.delegateRun(oSettingsScreen, 'onBuild', [oViewModelDom]);
+ }
+ else
+ {
+ Utils.log('Cannot find sub settings view model position: SettingsSubScreen');
+ }
+ }
+
+ if (oSettingsScreen)
+ {
+ _.defer(function () {
+ // hide
+ if (self.oCurrentSubScreen)
+ {
+ Utils.delegateRun(self.oCurrentSubScreen, 'onHide');
+ self.oCurrentSubScreen.viewModelDom.hide();
+ }
+ // --
+
+ self.oCurrentSubScreen = oSettingsScreen;
+
+ // show
+ if (self.oCurrentSubScreen)
+ {
+ self.oCurrentSubScreen.viewModelDom.show();
+ Utils.delegateRun(self.oCurrentSubScreen, 'onShow');
+ Utils.delegateRun(self.oCurrentSubScreen, 'onFocus', [], 200);
+
+ _.each(self.menu(), function (oItem) {
+ oItem.selected(oSettingsScreen && oSettingsScreen.__rlSettingsData && oItem.route === oSettingsScreen.__rlSettingsData.Route);
+ });
+
+ $('#rl-content .b-settings .b-content .content').scrollTop(0);
+ }
+ // --
+
+ Utils.windowResize();
+ });
+ }
+ }
+ else
+ {
+ kn.setHash(RL.link().settings(), false, true);
+ }
+};
+
+AbstractSettings.prototype.onHide = function ()
+{
+ if (this.oCurrentSubScreen && this.oCurrentSubScreen.viewModelDom)
+ {
+ Utils.delegateRun(this.oCurrentSubScreen, 'onHide');
+ this.oCurrentSubScreen.viewModelDom.hide();
+ }
+};
+
+AbstractSettings.prototype.onBuild = function ()
+{
+ _.each(ViewModels['settings'], function (SettingsViewModel) {
+ if (SettingsViewModel && SettingsViewModel.__rlSettingsData &&
+ !_.find(ViewModels['settings-removed'], function (RemoveSettingsViewModel) {
+ return RemoveSettingsViewModel && RemoveSettingsViewModel === SettingsViewModel;
+ }))
+ {
+ this.menu.push({
+ 'route': SettingsViewModel.__rlSettingsData.Route,
+ 'label': SettingsViewModel.__rlSettingsData.Label,
+ 'selected': ko.observable(false),
+ 'disabled': !!_.find(ViewModels['settings-disabled'], function (DisabledSettingsViewModel) {
+ return DisabledSettingsViewModel && DisabledSettingsViewModel === SettingsViewModel;
+ })
+ });
+ }
+ }, this);
+
+ this.oViewModelPlace = $('#rl-content #rl-settings-subscreen');
+};
+
+AbstractSettings.prototype.routes = function ()
+{
+ var
+ DefaultViewModel = _.find(ViewModels['settings'], function (SettingsViewModel) {
+ return SettingsViewModel && SettingsViewModel.__rlSettingsData && SettingsViewModel.__rlSettingsData['IsDefault'];
+ }),
+ sDefaultRoute = DefaultViewModel ? DefaultViewModel.__rlSettingsData['Route'] : 'general',
+ oRules = {
+ 'subname': /^(.*)$/,
+ 'normalize_': function (oRequest, oVals) {
+ oVals.subname = Utils.isUnd(oVals.subname) ? sDefaultRoute : Utils.pString(oVals.subname);
+ return [oVals.subname];
+ }
+ }
+ ;
+
+ return [
+ ['{subname}/', oRules],
+ ['{subname}', oRules],
+ ['', oRules]
+ ];
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends KnoinAbstractScreen
+ */
+function LoginScreen()
+{
+ KnoinAbstractScreen.call(this, 'login', [LoginViewModel]);
+}
+
+_.extend(LoginScreen.prototype, KnoinAbstractScreen.prototype);
+
+LoginScreen.prototype.onShow = function ()
+{
+ RL.setTitle('');
+};
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends KnoinAbstractScreen
+ */
+function MailBoxScreen()
+{
+ KnoinAbstractScreen.call(this, 'mailbox', [
+ MailBoxSystemDropDownViewModel,
+ MailBoxFolderListViewModel,
+ MailBoxMessageListViewModel,
+ MailBoxMessageViewViewModel
+ ]);
+
+ this.oLastRoute = {};
+}
+
+_.extend(MailBoxScreen.prototype, KnoinAbstractScreen.prototype);
+
+/**
+ * @type {Object}
+ */
+MailBoxScreen.prototype.oLastRoute = {};
+
+MailBoxScreen.prototype.setNewTitle = function ()
+{
+ var
+ sEmail = RL.data().accountEmail(),
+ ifoldersInboxUnreadCount = RL.data().foldersInboxUnreadCount()
+ ;
+
+ RL.setTitle(('' === sEmail ? '' :
+ (0 < ifoldersInboxUnreadCount ? '(' + ifoldersInboxUnreadCount + ') ' : ' ') + sEmail + ' - ') + Utils.i18n('TITLES/MAILBOX'));
+};
+
+MailBoxScreen.prototype.onShow = function ()
+{
+ this.setNewTitle();
+ RL.data().keyScope(Enums.KeyState.MessageList);
+};
+
+/**
+ * @param {string} sFolderHash
+ * @param {number} iPage
+ * @param {string} sSearch
+ * @param {boolean=} bPreview = false
+ */
+MailBoxScreen.prototype.onRoute = function (sFolderHash, iPage, sSearch, bPreview)
+{
+ if (Utils.isUnd(bPreview) ? false : !!bPreview)
+ {
+ if (Enums.Layout.NoPreview === RL.data().layout() && !RL.data().message())
+ {
+ RL.historyBack();
+ }
+ }
+ else
+ {
+ var
+ oData = RL.data(),
+ sFolderFullNameRaw = RL.cache().getFolderFullNameRaw(sFolderHash),
+ oFolder = RL.cache().getFolderFromCacheList(sFolderFullNameRaw)
+ ;
+
+ if (oFolder)
+ {
+ oData
+ .currentFolder(oFolder)
+ .messageListPage(iPage)
+ .messageListSearch(sSearch)
+ ;
+
+ if (Enums.Layout.NoPreview === oData.layout() && oData.message())
+ {
+ oData.message(null);
+ }
+
+ RL.reloadMessageList();
+ }
+ }
+};
+
+MailBoxScreen.prototype.onStart = function ()
+{
+ var
+ oData = RL.data(),
+ fResizeFunction = function () {
+ Utils.windowResize();
+ }
+ ;
+
+ if (RL.capa(Enums.Capa.AdditionalAccounts) || RL.capa(Enums.Capa.AdditionalIdentities))
+ {
+ RL.accountsAndIdentities();
+ }
+
+ _.delay(function () {
+ if ('INBOX' !== oData.currentFolderFullNameRaw())
+ {
+ RL.folderInformation('INBOX');
+ }
+ }, 1000);
+
+ _.delay(function () {
+ RL.quota();
+ }, 5000);
+
+ _.delay(function () {
+ RL.remote().appDelayStart(Utils.emptyFunction);
+ }, 35000);
+
+ $html.toggleClass('rl-no-preview-pane', Enums.Layout.NoPreview === oData.layout());
+
+ oData.folderList.subscribe(fResizeFunction);
+ oData.messageList.subscribe(fResizeFunction);
+ oData.message.subscribe(fResizeFunction);
+
+ oData.layout.subscribe(function (nValue) {
+ $html.toggleClass('rl-no-preview-pane', Enums.Layout.NoPreview === nValue);
+ });
+
+ oData.foldersInboxUnreadCount.subscribe(function () {
+ this.setNewTitle();
+ }, this);
+};
+
+/**
+ * @return {Array}
+ */
+MailBoxScreen.prototype.routes = function ()
+{
+ var
+ fNormP = function () {
+ return ['Inbox', 1, '', true];
+ },
+ fNormS = function (oRequest, oVals) {
+ oVals[0] = Utils.pString(oVals[0]);
+ oVals[1] = Utils.pInt(oVals[1]);
+ oVals[1] = 0 >= oVals[1] ? 1 : oVals[1];
+ oVals[2] = Utils.pString(oVals[2]);
+
+ if ('' === oRequest)
+ {
+ oVals[0] = 'Inbox';
+ oVals[1] = 1;
+ }
+
+ return [decodeURI(oVals[0]), oVals[1], decodeURI(oVals[2]), false];
+ },
+ fNormD = function (oRequest, oVals) {
+ oVals[0] = Utils.pString(oVals[0]);
+ oVals[1] = Utils.pString(oVals[1]);
+
+ if ('' === oRequest)
+ {
+ oVals[0] = 'Inbox';
+ }
+
+ return [decodeURI(oVals[0]), 1, decodeURI(oVals[1]), false];
+ }
+ ;
+
+ return [
+ [/^([a-zA-Z0-9]+)\/p([1-9][0-9]*)\/(.+)\/?$/, {'normalize_': fNormS}],
+ [/^([a-zA-Z0-9]+)\/p([1-9][0-9]*)$/, {'normalize_': fNormS}],
+ [/^([a-zA-Z0-9]+)\/(.+)\/?$/, {'normalize_': fNormD}],
+ [/^message-preview$/, {'normalize_': fNormP}],
+ [/^([^\/]*)$/, {'normalize_': fNormS}]
+ ];
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends AbstractSettings
+ */
+function SettingsScreen()
+{
+ AbstractSettings.call(this, [
+ SettingsSystemDropDownViewModel,
+ SettingsMenuViewModel,
+ SettingsPaneViewModel
+ ]);
+
+ Utils.initOnStartOrLangChange(function () {
+ this.sSettingsTitle = Utils.i18n('TITLES/SETTINGS');
+ }, this, function () {
+ RL.setTitle(this.sSettingsTitle);
+ });
+}
+
+_.extend(SettingsScreen.prototype, AbstractSettings.prototype);
+
+SettingsScreen.prototype.onShow = function ()
+{
+ RL.setTitle(this.sSettingsTitle);
+ RL.data().keyScope(Enums.KeyState.Settings);
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends KnoinAbstractBoot
+ */
+function AbstractApp()
+{
+ KnoinAbstractBoot.call(this);
+
+ this.oSettings = null;
+ this.oPlugins = null;
+ this.oLocal = null;
+ this.oLink = null;
+ this.oSubs = {};
+
+ this.isLocalAutocomplete = true;
+
+ this.popupVisibilityNames = ko.observableArray([]);
+
+ this.popupVisibility = ko.computed(function () {
+ return 0 < this.popupVisibilityNames().length;
+ }, this);
+
+ this.iframe = $('').appendTo('body');
+
+ $window.on('error', function (oEvent) {
+ if (RL && oEvent && oEvent.originalEvent && oEvent.originalEvent.message &&
+ -1 === Utils.inArray(oEvent.originalEvent.message, [
+ 'Script error.', 'Uncaught Error: Error calling method on NPObject.'
+ ]))
+ {
+ RL.remote().jsError(
+ Utils.emptyFunction,
+ oEvent.originalEvent.message,
+ oEvent.originalEvent.filename,
+ oEvent.originalEvent.lineno,
+ location && location.toString ? location.toString() : '',
+ $html.attr('class'),
+ Utils.microtime() - Globals.now
+ );
+ }
+ });
+
+ $document.on('keydown', function (oEvent) {
+ if (oEvent && oEvent.ctrlKey)
+ {
+ $html.addClass('rl-ctrl-key-pressed');
+ }
+ }).on('keyup', function (oEvent) {
+ if (oEvent && !oEvent.ctrlKey)
+ {
+ $html.removeClass('rl-ctrl-key-pressed');
+ }
+ });
+}
+
+_.extend(AbstractApp.prototype, KnoinAbstractBoot.prototype);
+
+AbstractApp.prototype.oSettings = null;
+AbstractApp.prototype.oPlugins = null;
+AbstractApp.prototype.oLocal = null;
+AbstractApp.prototype.oLink = null;
+AbstractApp.prototype.oSubs = {};
+
+/**
+ * @param {string} sLink
+ * @return {boolean}
+ */
+AbstractApp.prototype.download = function (sLink)
+{
+ var
+ oLink = null,
+ oE = null,
+ sUserAgent = navigator.userAgent.toLowerCase()
+ ;
+
+ if (sUserAgent && (sUserAgent.indexOf('chrome') > -1 || sUserAgent.indexOf('chrome') > -1))
+ {
+ oLink = document.createElement('a');
+ oLink['href'] = sLink;
+
+ if (document['createEvent'])
+ {
+ oE = document['createEvent']('MouseEvents');
+ if (oE && oE['initEvent'] && oLink['dispatchEvent'])
+ {
+ oE['initEvent']('click', true, true);
+ oLink['dispatchEvent'](oE);
+ return true;
+ }
+ }
+ }
+
+ if (Globals.bMobileDevice)
+ {
+ window.open(sLink, '_self');
+ window.focus();
+ }
+ else
+ {
+ this.iframe.attr('src', sLink);
+// window.document.location.href = sLink;
+ }
+
+ return true;
+};
+
+/**
+ * @return {LinkBuilder}
+ */
+AbstractApp.prototype.link = function ()
+{
+ if (null === this.oLink)
+ {
+ this.oLink = new LinkBuilder();
+ }
+
+ return this.oLink;
+};
+
+/**
+ * @return {LocalStorage}
+ */
+AbstractApp.prototype.local = function ()
+{
+ if (null === this.oLocal)
+ {
+ this.oLocal = new LocalStorage();
+ }
+
+ return this.oLocal;
+};
+
+/**
+ * @param {string} sName
+ * @return {?}
+ */
+AbstractApp.prototype.settingsGet = function (sName)
+{
+ if (null === this.oSettings)
+ {
+ this.oSettings = Utils.isNormal(AppData) ? AppData : {};
+ }
+
+ return Utils.isUnd(this.oSettings[sName]) ? null : this.oSettings[sName];
+};
+
+/**
+ * @param {string} sName
+ * @param {?} mValue
+ */
+AbstractApp.prototype.settingsSet = function (sName, mValue)
+{
+ if (null === this.oSettings)
+ {
+ this.oSettings = Utils.isNormal(AppData) ? AppData : {};
+ }
+
+ this.oSettings[sName] = mValue;
+};
+
+AbstractApp.prototype.setTitle = function (sTitle)
+{
+ sTitle = ((Utils.isNormal(sTitle) && 0 < sTitle.length) ? sTitle + ' - ' : '') +
+ RL.settingsGet('Title') || '';
+
+ window.document.title = '_';
+ window.document.title = sTitle;
+};
+
+/**
+ * @param {boolean=} bLogout = false
+ * @param {boolean=} bClose = false
+ */
+AbstractApp.prototype.loginAndLogoutReload = function (bLogout, bClose)
+{
+ var
+ sCustomLogoutLink = Utils.pString(RL.settingsGet('CustomLogoutLink')),
+ bInIframe = !!RL.settingsGet('InIframe')
+ ;
+
+ bLogout = Utils.isUnd(bLogout) ? false : !!bLogout;
+ bClose = Utils.isUnd(bClose) ? false : !!bClose;
+
+ if (bLogout && bClose && window.close)
+ {
+ window.close();
+ }
+
+ if (bLogout && '' !== sCustomLogoutLink && window.location.href !== sCustomLogoutLink)
+ {
+ _.delay(function () {
+ if (bInIframe && window.parent)
+ {
+ window.parent.location.href = sCustomLogoutLink;
+ }
+ else
+ {
+ window.location.href = sCustomLogoutLink;
+ }
+ }, 100);
+ }
+ else
+ {
+ kn.routeOff();
+ kn.setHash(RL.link().root(), true);
+ kn.routeOff();
+
+ _.delay(function () {
+ if (bInIframe && window.parent)
+ {
+ window.parent.location.reload();
+ }
+ else
+ {
+ window.location.reload();
+ }
+ }, 100);
+ }
+};
+
+AbstractApp.prototype.historyBack = function ()
+{
+ window.history.back();
+};
+
+/**
+ * @param {string} sQuery
+ * @param {Function} fCallback
+ */
+AbstractApp.prototype.getAutocomplete = function (sQuery, fCallback)
+{
+ fCallback([], sQuery);
+};
+
+/**
+ * @param {string} sName
+ * @param {Function} fFunc
+ * @param {Object=} oContext
+ * @return {AbstractApp}
+ */
+AbstractApp.prototype.sub = function (sName, fFunc, oContext)
+{
+ if (Utils.isUnd(this.oSubs[sName]))
+ {
+ this.oSubs[sName] = [];
+ }
+
+ this.oSubs[sName].push([fFunc, oContext]);
+
+ return this;
+};
+
+/**
+ * @param {string} sName
+ * @param {Array=} aArgs
+ * @return {AbstractApp}
+ */
+AbstractApp.prototype.pub = function (sName, aArgs)
+{
+ Plugins.runHook('rl-pub', [sName, aArgs]);
+ if (!Utils.isUnd(this.oSubs[sName]))
+ {
+ _.each(this.oSubs[sName], function (aItem) {
+ if (aItem[0])
+ {
+ aItem[0].apply(aItem[1] || null, aArgs || []);
+ }
+ });
+ }
+
+ return this;
+};
+
+/**
+ * @param {string} sName
+ * @return {boolean}
+ */
+AbstractApp.prototype.capa = function (sName)
+{
+ var mCapa = this.settingsGet('Capa');
+ return Utils.isArray(mCapa) && Utils.isNormal(sName) && -1 < Utils.inArray(sName, mCapa);
+};
+
+AbstractApp.prototype.bootstart = function ()
+{
+ var self = this;
+
+ Utils.initOnStartOrLangChange(function () {
+ Utils.initNotificationLanguage();
+ }, null);
+
+ _.delay(function () {
+ Utils.windowResize();
+ }, 1000);
+
+ ssm.addState({
+ 'id': 'mobile',
+ 'maxWidth': 767,
+ 'onEnter': function() {
+ $html.addClass('ssm-state-mobile');
+ self.pub('ssm.mobile-enter');
+ },
+ 'onLeave': function() {
+ $html.removeClass('ssm-state-mobile');
+ self.pub('ssm.mobile-leave');
+ }
+ });
+
+ ssm.addState({
+ 'id': 'tablet',
+ 'minWidth': 768,
+ 'maxWidth': 999,
+ 'onEnter': function() {
+ $html.addClass('ssm-state-tablet');
+ },
+ 'onLeave': function() {
+ $html.removeClass('ssm-state-tablet');
+ }
+ });
+
+ ssm.addState({
+ 'id': 'desktop',
+ 'minWidth': 1000,
+ 'maxWidth': 1400,
+ 'onEnter': function() {
+ $html.addClass('ssm-state-desktop');
+ },
+ 'onLeave': function() {
+ $html.removeClass('ssm-state-desktop');
+ }
+ });
+
+ ssm.addState({
+ 'id': 'desktop-large',
+ 'minWidth': 1400,
+ 'onEnter': function() {
+ $html.addClass('ssm-state-desktop-large');
+ },
+ 'onLeave': function() {
+ $html.removeClass('ssm-state-desktop-large');
+ }
+ });
+
+ RL.sub('ssm.mobile-enter', function () {
+ RL.data().leftPanelDisabled(true);
+ });
+
+ RL.sub('ssm.mobile-leave', function () {
+ RL.data().leftPanelDisabled(false);
+ });
+
+ RL.data().leftPanelDisabled.subscribe(function (bValue) {
+ $html.toggleClass('rl-left-panel-disabled', bValue);
+ });
+
+ ssm.ready();
+};
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+/**
+ * @constructor
+ * @extends AbstractApp
+ */
+function RainLoopApp()
+{
+ AbstractApp.call(this);
+
+ this.oData = null;
+ this.oRemote = null;
+ this.oCache = null;
+ this.oMoveCache = {};
+
+ this.quotaDebounce = _.debounce(this.quota, 1000 * 30);
+ this.moveOrDeleteResponseHelper = _.bind(this.moveOrDeleteResponseHelper, this);
+
+ this.messagesMoveTrigger = _.debounce(this.messagesMoveTrigger, 500);
+
+ window.setInterval(function () {
+ RL.pub('interval.30s');
+ }, 30000);
+
+ window.setInterval(function () {
+ RL.pub('interval.1m');
+ }, 60000);
+
+ window.setInterval(function () {
+ RL.pub('interval.2m');
+ }, 60000 * 2);
+
+ window.setInterval(function () {
+ RL.pub('interval.3m');
+ }, 60000 * 3);
+
+ window.setInterval(function () {
+ RL.pub('interval.5m');
+ }, 60000 * 5);
+
+ window.setInterval(function () {
+ RL.pub('interval.10m');
+ }, 60000 * 10);
+
+ window.setTimeout(function () {
+ window.setInterval(function () {
+ RL.pub('interval.10m-after5m');
+ }, 60000 * 10);
+ }, 60000 * 5);
+
+ $.wakeUp(function () {
+ RL.remote().jsVersion(function (sResult, oData) {
+ if (Enums.StorageResultType.Success === sResult && oData && !oData.Result)
+ {
+ if (window.parent && !!RL.settingsGet('InIframe'))
+ {
+ window.parent.location.reload();
+ }
+ else
+ {
+ window.location.reload();
+ }
+ }
+ }, RL.settingsGet('Version'));
+ }, {}, 60 * 60 * 1000);
+}
+
+_.extend(RainLoopApp.prototype, AbstractApp.prototype);
+
+RainLoopApp.prototype.oData = null;
+RainLoopApp.prototype.oRemote = null;
+RainLoopApp.prototype.oCache = null;
+
+/**
+ * @return {WebMailDataStorage}
+ */
+RainLoopApp.prototype.data = function ()
+{
+ if (null === this.oData)
+ {
+ this.oData = new WebMailDataStorage();
+ }
+
+ return this.oData;
+};
+
+/**
+ * @return {WebMailAjaxRemoteStorage}
+ */
+RainLoopApp.prototype.remote = function ()
+{
+ if (null === this.oRemote)
+ {
+ this.oRemote = new WebMailAjaxRemoteStorage();
+ }
+
+ return this.oRemote;
+};
+
+/**
+ * @return {WebMailCacheStorage}
+ */
+RainLoopApp.prototype.cache = function ()
+{
+ if (null === this.oCache)
+ {
+ this.oCache = new WebMailCacheStorage();
+ }
+
+ return this.oCache;
+};
+
+RainLoopApp.prototype.reloadFlagsCurrentMessageListAndMessageFromCache = function ()
+{
+ var oCache = RL.cache();
+ _.each(RL.data().messageList(), function (oMessage) {
+ oCache.initMessageFlagsFromCache(oMessage);
+ });
+
+ oCache.initMessageFlagsFromCache(RL.data().message());
+};
+
+/**
+ * @param {boolean=} bDropPagePosition = false
+ * @param {boolean=} bDropCurrenFolderCache = false
+ */
+RainLoopApp.prototype.reloadMessageList = function (bDropPagePosition, bDropCurrenFolderCache)
+{
+ var
+ oRLData = RL.data(),
+ iOffset = (oRLData.messageListPage() - 1) * oRLData.messagesPerPage()
+ ;
+
+ if (Utils.isUnd(bDropCurrenFolderCache) ? false : !!bDropCurrenFolderCache)
+ {
+ RL.cache().setFolderHash(oRLData.currentFolderFullNameRaw(), '');
+ }
+
+ if (Utils.isUnd(bDropPagePosition) ? false : !!bDropPagePosition)
+ {
+ oRLData.messageListPage(1);
+ iOffset = 0;
+ }
+
+ oRLData.messageListLoading(true);
+ RL.remote().messageList(function (sResult, oData, bCached) {
+
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ {
+ oRLData.messageListError('');
+ oRLData.messageListLoading(false);
+ oRLData.setMessageList(oData, bCached);
+ }
+ else if (Enums.StorageResultType.Unload === sResult)
+ {
+ oRLData.messageListError('');
+ oRLData.messageListLoading(false);
+ }
+ else if (Enums.StorageResultType.Abort !== sResult)
+ {
+ oRLData.messageList([]);
+ oRLData.messageListLoading(false);
+ oRLData.messageListError(oData && oData.ErrorCode ?
+ Utils.getNotification(oData.ErrorCode) : Utils.i18n('NOTIFICATIONS/CANT_GET_MESSAGE_LIST')
+ );
+ }
+
+ }, oRLData.currentFolderFullNameRaw(), iOffset, oRLData.messagesPerPage(), oRLData.messageListSearch());
+};
+
+RainLoopApp.prototype.recacheInboxMessageList = function ()
+{
+ RL.remote().messageList(Utils.emptyFunction, 'INBOX', 0, RL.data().messagesPerPage(), '', true);
+};
+
+RainLoopApp.prototype.reloadMessageListHelper = function (bEmptyList)
+{
+ RL.reloadMessageList(bEmptyList);
+};
+
+/**
+ * @param {Function} fResultFunc
+ * @returns {boolean}
+ */
+RainLoopApp.prototype.contactsSync = function (fResultFunc)
+{
+ var oContacts = RL.data().contacts;
+ if (oContacts.importing() || oContacts.syncing() || !RL.data().enableContactsSync() || !RL.data().allowContactsSync())
+ {
+ return false;
+ }
+
+ oContacts.syncing(true);
+
+ RL.remote().contactsSync(function (sResult, oData) {
+
+ oContacts.syncing(false);
+
+ if (fResultFunc)
+ {
+ fResultFunc(sResult, oData);
+ }
+ });
+
+ return true;
+};
+
+RainLoopApp.prototype.messagesMoveTrigger = function ()
+{
+ var
+ self = this,
+ sSpamFolder = RL.data().spamFolder()
+ ;
+
+ _.each(this.oMoveCache, function (oItem) {
+
+ var
+ bSpam = sSpamFolder === oItem['To'],
+ bHam = !bSpam && sSpamFolder === oItem['From'] && 'INBOX' === oItem['To']
+ ;
+
+ RL.remote().messagesMove(self.moveOrDeleteResponseHelper, oItem['From'], oItem['To'], oItem['Uid'],
+ bSpam ? 'SPAM' : (bHam ? 'HAM' : ''));
+ });
+
+ this.oMoveCache = {};
+};
+
+RainLoopApp.prototype.messagesMoveHelper = function (sFromFolderFullNameRaw, sToFolderFullNameRaw, aUidForMove)
+{
+ var sH = '$$' + sFromFolderFullNameRaw + '$$' + sToFolderFullNameRaw + '$$';
+ if (!this.oMoveCache[sH])
+ {
+ this.oMoveCache[sH] = {
+ 'From': sFromFolderFullNameRaw,
+ 'To': sToFolderFullNameRaw,
+ 'Uid': []
+ };
+ }
+
+ this.oMoveCache[sH]['Uid'] = _.union(this.oMoveCache[sH]['Uid'], aUidForMove);
+ this.messagesMoveTrigger();
+};
+
+RainLoopApp.prototype.messagesCopyHelper = function (sFromFolderFullNameRaw, sToFolderFullNameRaw, aUidForCopy)
+{
+ RL.remote().messagesCopy(
+ this.moveOrDeleteResponseHelper,
+ sFromFolderFullNameRaw,
+ sToFolderFullNameRaw,
+ aUidForCopy
+ );
+};
+
+RainLoopApp.prototype.messagesDeleteHelper = function (sFromFolderFullNameRaw, aUidForRemove)
+{
+ RL.remote().messagesDelete(
+ this.moveOrDeleteResponseHelper,
+ sFromFolderFullNameRaw,
+ aUidForRemove
+ );
+};
+
+RainLoopApp.prototype.moveOrDeleteResponseHelper = function (sResult, oData)
+{
+ if (Enums.StorageResultType.Success === sResult && RL.data().currentFolder())
+ {
+ if (oData && Utils.isArray(oData.Result) && 2 === oData.Result.length)
+ {
+ RL.cache().setFolderHash(oData.Result[0], oData.Result[1]);
+ }
+ else
+ {
+ RL.cache().setFolderHash(RL.data().currentFolderFullNameRaw(), '');
+
+ if (oData && -1 < Utils.inArray(oData.ErrorCode,
+ [Enums.Notification.CantMoveMessage, Enums.Notification.CantCopyMessage]))
+ {
+ window.alert(Utils.getNotification(oData.ErrorCode));
+ }
+ }
+
+ RL.reloadMessageListHelper(0 === RL.data().messageList().length);
+ RL.quotaDebounce();
+ }
+};
+
+/**
+ * @param {string} sFromFolderFullNameRaw
+ * @param {Array} aUidForRemove
+ */
+RainLoopApp.prototype.deleteMessagesFromFolderWithoutCheck = function (sFromFolderFullNameRaw, aUidForRemove)
+{
+ this.messagesDeleteHelper(sFromFolderFullNameRaw, aUidForRemove);
+ RL.data().removeMessagesFromList(sFromFolderFullNameRaw, aUidForRemove);
+};
+
+/**
+ * @param {number} iDeleteType
+ * @param {string} sFromFolderFullNameRaw
+ * @param {Array} aUidForRemove
+ * @param {boolean=} bUseFolder = true
+ */
+RainLoopApp.prototype.deleteMessagesFromFolder = function (iDeleteType, sFromFolderFullNameRaw, aUidForRemove, bUseFolder)
+{
+ var
+ self = this,
+ oData = RL.data(),
+ oCache = RL.cache(),
+ oMoveFolder = null,
+ nSetSystemFoldersNotification = null
+ ;
+
+ switch (iDeleteType)
+ {
+ case Enums.FolderType.Spam:
+ oMoveFolder = oCache.getFolderFromCacheList(oData.spamFolder());
+ nSetSystemFoldersNotification = Enums.SetSystemFoldersNotification.Spam;
+ break;
+ case Enums.FolderType.NotSpam:
+ oMoveFolder = oCache.getFolderFromCacheList('INBOX');
+ break;
+ case Enums.FolderType.Trash:
+ oMoveFolder = oCache.getFolderFromCacheList(oData.trashFolder());
+ nSetSystemFoldersNotification = Enums.SetSystemFoldersNotification.Trash;
+ break;
+ case Enums.FolderType.Archive:
+ oMoveFolder = oCache.getFolderFromCacheList(oData.archiveFolder());
+ nSetSystemFoldersNotification = Enums.SetSystemFoldersNotification.Archive;
+ break;
+ }
+
+ bUseFolder = Utils.isUnd(bUseFolder) ? true : !!bUseFolder;
+ if (bUseFolder)
+ {
+ if ((Enums.FolderType.Spam === iDeleteType && Consts.Values.UnuseOptionValue === oData.spamFolder()) ||
+ (Enums.FolderType.Trash === iDeleteType && Consts.Values.UnuseOptionValue === oData.trashFolder()) ||
+ (Enums.FolderType.Archive === iDeleteType && Consts.Values.UnuseOptionValue === oData.archiveFolder()))
+ {
+ bUseFolder = false;
+ }
+ }
+
+ if (!oMoveFolder && bUseFolder)
+ {
+ kn.showScreenPopup(PopupsFolderSystemViewModel, [nSetSystemFoldersNotification]);
+ }
+ else if (!bUseFolder || (Enums.FolderType.Trash === iDeleteType &&
+ (sFromFolderFullNameRaw === oData.spamFolder() || sFromFolderFullNameRaw === oData.trashFolder())))
+ {
+ kn.showScreenPopup(PopupsAskViewModel, [Utils.i18n('POPUPS_ASK/DESC_WANT_DELETE_MESSAGES'), function () {
+
+ self.messagesDeleteHelper(sFromFolderFullNameRaw, aUidForRemove);
+ oData.removeMessagesFromList(sFromFolderFullNameRaw, aUidForRemove);
+
+ }]);
+ }
+ else if (oMoveFolder)
+ {
+ this.messagesMoveHelper(sFromFolderFullNameRaw, oMoveFolder.fullNameRaw, aUidForRemove);
+ oData.removeMessagesFromList(sFromFolderFullNameRaw, aUidForRemove, oMoveFolder.fullNameRaw);
+ }
+};
+
+/**
+ * @param {string} sFromFolderFullNameRaw
+ * @param {Array} aUidForMove
+ * @param {string} sToFolderFullNameRaw
+ * @param {boolean=} bCopy = false
+ */
+RainLoopApp.prototype.moveMessagesToFolder = function (sFromFolderFullNameRaw, aUidForMove, sToFolderFullNameRaw, bCopy)
+{
+ if (sFromFolderFullNameRaw !== sToFolderFullNameRaw && Utils.isArray(aUidForMove) && 0 < aUidForMove.length)
+ {
+ var
+ oFromFolder = RL.cache().getFolderFromCacheList(sFromFolderFullNameRaw),
+ oToFolder = RL.cache().getFolderFromCacheList(sToFolderFullNameRaw)
+ ;
+
+ if (oFromFolder && oToFolder)
+ {
+ if (Utils.isUnd(bCopy) ? false : !!bCopy)
+ {
+ this.messagesCopyHelper(oFromFolder.fullNameRaw, oToFolder.fullNameRaw, aUidForMove);
+ }
+ else
+ {
+ this.messagesMoveHelper(oFromFolder.fullNameRaw, oToFolder.fullNameRaw, aUidForMove);
+ }
+
+ RL.data().removeMessagesFromList(oFromFolder.fullNameRaw, aUidForMove, oToFolder.fullNameRaw, bCopy);
+ return true;
+ }
+ }
+
+ return false;
+};
+
+/**
+ * @param {Function=} fCallback
+ */
+RainLoopApp.prototype.folders = function (fCallback)
+{
+ this.data().foldersLoading(true);
+ this.remote().folders(_.bind(function (sResult, oData) {
+
+ RL.data().foldersLoading(false);
+ if (Enums.StorageResultType.Success === sResult)
+ {
+ this.data().setFolders(oData);
+ if (fCallback)
+ {
+ fCallback(true);
+ }
+ }
+ else
+ {
+ if (fCallback)
+ {
+ fCallback(false);
+ }
+ }
+ }, this));
+};
+
+RainLoopApp.prototype.reloadOpenPgpKeys = function ()
+{
+ if (RL.data().capaOpenPGP())
+ {
+ var
+ aKeys = [],
+ oEmail = new EmailModel(),
+ oOpenpgpKeyring = RL.data().openpgpKeyring,
+ oOpenpgpKeys = oOpenpgpKeyring ? oOpenpgpKeyring.getAllKeys() : []
+ ;
+
+ _.each(oOpenpgpKeys, function (oItem, iIndex) {
+ if (oItem && oItem.primaryKey)
+ {
+ var
+
+ oPrimaryUser = oItem.getPrimaryUser(),
+ sUser = (oPrimaryUser && oPrimaryUser.user) ? oPrimaryUser.user.userId.userid
+ : (oItem.users && oItem.users[0] ? oItem.users[0].userId.userid : '')
+ ;
+
+ oEmail.clear();
+ oEmail.mailsoParse(sUser);
+
+ if (oEmail.validate())
+ {
+ aKeys.push(new OpenPgpKeyModel(
+ iIndex,
+ oItem.primaryKey.getFingerprint(),
+ oItem.primaryKey.getKeyId().toHex().toLowerCase(),
+ sUser,
+ oEmail.email,
+ oItem.isPrivate(),
+ oItem.armor())
+ );
+ }
+ }
+ });
+
+ RL.data().openpgpkeys(aKeys);
+ }
+};
+
+RainLoopApp.prototype.accountsAndIdentities = function ()
+{
+ var oRainLoopData = RL.data();
+
+ oRainLoopData.accountsLoading(true);
+ oRainLoopData.identitiesLoading(true);
+
+ RL.remote().accountsAndIdentities(function (sResult, oData) {
+
+ oRainLoopData.accountsLoading(false);
+ oRainLoopData.identitiesLoading(false);
+
+ if (Enums.StorageResultType.Success === sResult && oData.Result)
+ {
+ var
+ sParentEmail = RL.settingsGet('ParentEmail'),
+ sAccountEmail = oRainLoopData.accountEmail()
+ ;
+
+ sParentEmail = '' === sParentEmail ? sAccountEmail : sParentEmail;
+
+ if (Utils.isArray(oData.Result['Accounts']))
+ {
+ oRainLoopData.accounts(_.map(oData.Result['Accounts'], function (sValue) {
+ return new AccountModel(sValue, sValue !== sParentEmail);
+ }));
+ }
+
+ if (Utils.isArray(oData.Result['Identities']))
+ {
+ oRainLoopData.identities(_.map(oData.Result['Identities'], function (oIdentityData) {
+
+ var
+ sId = Utils.pString(oIdentityData['Id']),
+ sEmail = Utils.pString(oIdentityData['Email']),
+ oIdentity = new IdentityModel(sId, sEmail, sId !== sAccountEmail)
+ ;
+
+ oIdentity.name(Utils.pString(oIdentityData['Name']));
+ oIdentity.replyTo(Utils.pString(oIdentityData['ReplyTo']));
+ oIdentity.bcc(Utils.pString(oIdentityData['Bcc']));
+
+ return oIdentity;
+ }));
+ }
+ }
+ });
+};
+
+RainLoopApp.prototype.quota = function ()
+{
+ this.remote().quota(function (sResult, oData) {
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result &&
+ Utils.isArray(oData.Result) && 1 < oData.Result.length &&
+ Utils.isPosNumeric(oData.Result[0], true) && Utils.isPosNumeric(oData.Result[1], true))
+ {
+ RL.data().userQuota(Utils.pInt(oData.Result[1]) * 1024);
+ RL.data().userUsageSize(Utils.pInt(oData.Result[0]) * 1024);
+ }
+ });
+};
+
+/**
+ * @param {string} sFolder
+ * @param {Array=} aList = []
+ */
+RainLoopApp.prototype.folderInformation = function (sFolder, aList)
+{
+ if ('' !== Utils.trim(sFolder))
+ {
+ this.remote().folderInformation(function (sResult, oData) {
+ if (Enums.StorageResultType.Success === sResult)
+ {
+ if (oData && oData.Result && oData.Result.Hash && oData.Result.Folder)
+ {
+ var
+ iUtc = moment().unix(),
+ sHash = RL.cache().getFolderHash(oData.Result.Folder),
+ oFolder = RL.cache().getFolderFromCacheList(oData.Result.Folder),
+ bCheck = false,
+ sUid = '',
+ aList = [],
+ bUnreadCountChange = false,
+ oFlags = null
+ ;
+
+ if (oFolder)
+ {
+ oFolder.interval = iUtc;
+
+ if (oData.Result.Hash)
+ {
+ RL.cache().setFolderHash(oData.Result.Folder, oData.Result.Hash);
+ }
+
+ if (Utils.isNormal(oData.Result.MessageCount))
+ {
+ oFolder.messageCountAll(oData.Result.MessageCount);
+ }
+
+ if (Utils.isNormal(oData.Result.MessageUnseenCount))
+ {
+ if (Utils.pInt(oFolder.messageCountUnread()) !== Utils.pInt(oData.Result.MessageUnseenCount))
+ {
+ bUnreadCountChange = true;
+ }
+
+ oFolder.messageCountUnread(oData.Result.MessageUnseenCount);
+ }
+
+ if (bUnreadCountChange)
+ {
+ RL.cache().clearMessageFlagsFromCacheByFolder(oFolder.fullNameRaw);
+ }
+
+ if (oData.Result.Flags)
+ {
+ for (sUid in oData.Result.Flags)
+ {
+ if (oData.Result.Flags.hasOwnProperty(sUid))
+ {
+ bCheck = true;
+ oFlags = oData.Result.Flags[sUid];
+ RL.cache().storeMessageFlagsToCacheByFolderAndUid(oFolder.fullNameRaw, sUid.toString(), [
+ !oFlags['IsSeen'], !!oFlags['IsFlagged'], !!oFlags['IsAnswered'], !!oFlags['IsForwarded'], !!oFlags['IsReadReceipt']
+ ]);
+ }
+ }
+
+ if (bCheck)
+ {
+ RL.reloadFlagsCurrentMessageListAndMessageFromCache();
+ }
+ }
+
+ RL.data().initUidNextAndNewMessages(oFolder.fullNameRaw, oData.Result.UidNext, oData.Result.NewMessages);
+
+ if (oData.Result.Hash !== sHash || '' === sHash)
+ {
+ if (oFolder.fullNameRaw === RL.data().currentFolderFullNameRaw())
+ {
+ RL.reloadMessageList();
+ }
+ else if ('INBOX' === oFolder.fullNameRaw)
+ {
+ RL.recacheInboxMessageList();
+ }
+ }
+ else if (bUnreadCountChange)
+ {
+ if (oFolder.fullNameRaw === RL.data().currentFolderFullNameRaw())
+ {
+ aList = RL.data().messageList();
+ if (Utils.isNonEmptyArray(aList))
+ {
+ RL.folderInformation(oFolder.fullNameRaw, aList);
+ }
+ }
+ }
+ }
+ }
+ }
+ }, sFolder, aList);
+ }
+};
+
+/**
+ * @param {boolean=} bBoot = false
+ */
+RainLoopApp.prototype.folderInformationMultiply = function (bBoot)
+{
+ bBoot = Utils.isUnd(bBoot) ? false : !!bBoot;
+
+ var
+ iUtc = moment().unix(),
+ aFolders = RL.data().getNextFolderNames(bBoot)
+ ;
+
+ if (Utils.isNonEmptyArray(aFolders))
+ {
+ this.remote().folderInformationMultiply(function (sResult, oData) {
+ if (Enums.StorageResultType.Success === sResult)
+ {
+ if (oData && oData.Result && oData.Result.List && Utils.isNonEmptyArray(oData.Result.List))
+ {
+ _.each(oData.Result.List, function (oItem) {
+
+ var
+ aList = [],
+ sHash = RL.cache().getFolderHash(oItem.Folder),
+ oFolder = RL.cache().getFolderFromCacheList(oItem.Folder),
+ bUnreadCountChange = false
+ ;
+
+ if (oFolder)
+ {
+ oFolder.interval = iUtc;
+
+ if (oItem.Hash)
+ {
+ RL.cache().setFolderHash(oItem.Folder, oItem.Hash);
+ }
+
+ if (Utils.isNormal(oItem.MessageCount))
+ {
+ oFolder.messageCountAll(oItem.MessageCount);
+ }
+
+ if (Utils.isNormal(oItem.MessageUnseenCount))
+ {
+ if (Utils.pInt(oFolder.messageCountUnread()) !== Utils.pInt(oItem.MessageUnseenCount))
+ {
+ bUnreadCountChange = true;
+ }
+
+ oFolder.messageCountUnread(oItem.MessageUnseenCount);
+ }
+
+ if (bUnreadCountChange)
+ {
+ RL.cache().clearMessageFlagsFromCacheByFolder(oFolder.fullNameRaw);
+ }
+
+ if (oItem.Hash !== sHash || '' === sHash)
+ {
+ if (oFolder.fullNameRaw === RL.data().currentFolderFullNameRaw())
+ {
+ RL.reloadMessageList();
+ }
+ }
+ else if (bUnreadCountChange)
+ {
+ if (oFolder.fullNameRaw === RL.data().currentFolderFullNameRaw())
+ {
+ aList = RL.data().messageList();
+ if (Utils.isNonEmptyArray(aList))
+ {
+ RL.folderInformation(oFolder.fullNameRaw, aList);
+ }
+ }
+ }
+ }
+ });
+
+ if (bBoot)
+ {
+ RL.folderInformationMultiply(true);
+ }
+ }
+ }
+ }, aFolders);
+ }
+};
+
+RainLoopApp.prototype.setMessageSeen = function (oMessage)
+{
+ if (oMessage.unseen())
+ {
+ oMessage.unseen(false);
+
+ var oFolder = RL.cache().getFolderFromCacheList(oMessage.folderFullNameRaw);
+ if (oFolder)
+ {
+ oFolder.messageCountUnread(0 <= oFolder.messageCountUnread() - 1 ?
+ oFolder.messageCountUnread() - 1 : 0);
+ }
+
+ RL.cache().storeMessageFlagsToCache(oMessage);
+ RL.reloadFlagsCurrentMessageListAndMessageFromCache();
+ }
+
+ RL.remote().messageSetSeen(Utils.emptyFunction, oMessage.folderFullNameRaw, [oMessage.uid], true);
+};
+
+RainLoopApp.prototype.googleConnect = function ()
+{
+ window.open(RL.link().socialGoogle(), 'Google', 'left=200,top=100,width=650,height=600,menubar=no,status=no,resizable=yes,scrollbars=yes');
+};
+
+RainLoopApp.prototype.twitterConnect = function ()
+{
+ window.open(RL.link().socialTwitter(), 'Twitter', 'left=200,top=100,width=650,height=350,menubar=no,status=no,resizable=yes,scrollbars=yes');
+};
+
+RainLoopApp.prototype.facebookConnect = function ()
+{
+ window.open(RL.link().socialFacebook(), 'Facebook', 'left=200,top=100,width=650,height=335,menubar=no,status=no,resizable=yes,scrollbars=yes');
+};
+
+/**
+ * @param {boolean=} bFireAllActions
+ */
+RainLoopApp.prototype.socialUsers = function (bFireAllActions)
+{
+ var oRainLoopData = RL.data();
+
+ if (bFireAllActions)
+ {
+ oRainLoopData.googleActions(true);
+ oRainLoopData.facebookActions(true);
+ oRainLoopData.twitterActions(true);
+ }
+
+ RL.remote().socialUsers(function (sResult, oData) {
+
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ {
+ oRainLoopData.googleUserName(oData.Result['Google'] || '');
+ oRainLoopData.facebookUserName(oData.Result['Facebook'] || '');
+ oRainLoopData.twitterUserName(oData.Result['Twitter'] || '');
+ }
+ else
+ {
+ oRainLoopData.googleUserName('');
+ oRainLoopData.facebookUserName('');
+ oRainLoopData.twitterUserName('');
+ }
+
+ oRainLoopData.googleLoggined('' !== oRainLoopData.googleUserName());
+ oRainLoopData.facebookLoggined('' !== oRainLoopData.facebookUserName());
+ oRainLoopData.twitterLoggined('' !== oRainLoopData.twitterUserName());
+
+ oRainLoopData.googleActions(false);
+ oRainLoopData.facebookActions(false);
+ oRainLoopData.twitterActions(false);
+ });
+};
+
+RainLoopApp.prototype.googleDisconnect = function ()
+{
+ RL.data().googleActions(true);
+ RL.remote().googleDisconnect(function () {
+ RL.socialUsers();
+ });
+};
+
+RainLoopApp.prototype.facebookDisconnect = function ()
+{
+ RL.data().facebookActions(true);
+ RL.remote().facebookDisconnect(function () {
+ RL.socialUsers();
+ });
+};
+
+RainLoopApp.prototype.twitterDisconnect = function ()
+{
+ RL.data().twitterActions(true);
+ RL.remote().twitterDisconnect(function () {
+ RL.socialUsers();
+ });
+};
+
+/**
+ * @param {Array} aSystem
+ * @param {Array} aList
+ * @param {Array=} aDisabled
+ * @param {Array=} aHeaderLines
+ * @param {?number=} iUnDeep
+ * @param {Function=} fDisableCallback
+ * @param {Function=} fVisibleCallback
+ * @param {Function=} fRenameCallback
+ * @param {boolean=} bSystem
+ * @param {boolean=} bBuildUnvisible
+ * @return {Array}
+ */
+RainLoopApp.prototype.folderListOptionsBuilder = function (aSystem, aList, aDisabled, aHeaderLines, iUnDeep, fDisableCallback, fVisibleCallback, fRenameCallback, bSystem, bBuildUnvisible)
+{
+ var
+ iIndex = 0,
+ iLen = 0,
+ /**
+ * @type {?FolderModel}
+ */
+ oItem = null,
+ bSep = false,
+ sDeepPrefix = '\u00A0\u00A0\u00A0',
+ aResult = []
+ ;
+
+ bSystem = !Utils.isNormal(bSystem) ? 0 < aSystem.length : bSystem;
+ bBuildUnvisible = Utils.isUnd(bBuildUnvisible) ? false : !!bBuildUnvisible;
+ iUnDeep = !Utils.isNormal(iUnDeep) ? 0 : iUnDeep;
+ fDisableCallback = Utils.isNormal(fDisableCallback) ? fDisableCallback : null;
+ fVisibleCallback = Utils.isNormal(fVisibleCallback) ? fVisibleCallback : null;
+ fRenameCallback = Utils.isNormal(fRenameCallback) ? fRenameCallback : null;
+
+ if (!Utils.isArray(aDisabled))
+ {
+ aDisabled = [];
+ }
+
+ if (!Utils.isArray(aHeaderLines))
+ {
+ aHeaderLines = [];
+ }
+
+ for (iIndex = 0, iLen = aHeaderLines.length; iIndex < iLen; iIndex++)
+ {
+ aResult.push({
+ 'id': aHeaderLines[iIndex][0],
+ 'name': aHeaderLines[iIndex][1],
+ 'system': false,
+ 'seporator': false,
+ 'disabled': false
+ });
+ }
+
+ bSep = true;
+ for (iIndex = 0, iLen = aSystem.length; iIndex < iLen; iIndex++)
+ {
+ oItem = aSystem[iIndex];
+ if (fVisibleCallback ? fVisibleCallback.call(null, oItem) : true)
+ {
+ if (bSep && 0 < aResult.length)
+ {
+ aResult.push({
+ 'id': '---',
+ 'name': '---',
+ 'system': false,
+ 'seporator': true,
+ 'disabled': true
+ });
+ }
+
+ bSep = false;
+ aResult.push({
+ 'id': oItem.fullNameRaw,
+ 'name': fRenameCallback ? fRenameCallback.call(null, oItem) : oItem.name(),
+ 'system': true,
+ 'seporator': false,
+ 'disabled': !oItem.selectable || -1 < Utils.inArray(oItem.fullNameRaw, aDisabled) ||
+ (fDisableCallback ? fDisableCallback.call(null, oItem) : false)
+ });
+ }
+ }
+
+ bSep = true;
+ for (iIndex = 0, iLen = aList.length; iIndex < iLen; iIndex++)
+ {
+ oItem = aList[iIndex];
+ if (oItem.subScribed() || !oItem.existen)
+ {
+ if (fVisibleCallback ? fVisibleCallback.call(null, oItem) : true)
+ {
+ if (Enums.FolderType.User === oItem.type() || !bSystem || 0 < oItem.subFolders().length)
+ {
+ if (bSep && 0 < aResult.length)
+ {
+ aResult.push({
+ 'id': '---',
+ 'name': '---',
+ 'system': false,
+ 'seporator': true,
+ 'disabled': true
+ });
+ }
+
+ bSep = false;
+ aResult.push({
+ 'id': oItem.fullNameRaw,
+ 'name': (new window.Array(oItem.deep + 1 - iUnDeep)).join(sDeepPrefix) +
+ (fRenameCallback ? fRenameCallback.call(null, oItem) : oItem.name()),
+ 'system': false,
+ 'seporator': false,
+ 'disabled': !oItem.selectable || -1 < Utils.inArray(oItem.fullNameRaw, aDisabled) ||
+ (fDisableCallback ? fDisableCallback.call(null, oItem) : false)
+ });
+ }
+ }
+ }
+
+ if (oItem.subScribed() && 0 < oItem.subFolders().length)
+ {
+ aResult = aResult.concat(RL.folderListOptionsBuilder([], oItem.subFolders(), aDisabled, [],
+ iUnDeep, fDisableCallback, fVisibleCallback, fRenameCallback, bSystem, bBuildUnvisible));
+ }
+ }
+
+ return aResult;
+};
+
+/**
+ * @param {string} sQuery
+ * @param {Function} fCallback
+ */
+RainLoopApp.prototype.getAutocomplete = function (sQuery, fCallback)
+{
+ var
+ aData = []
+ ;
+
+ RL.remote().suggestions(function (sResult, oData) {
+ if (Enums.StorageResultType.Success === sResult && oData && Utils.isArray(oData.Result))
+ {
+ aData = _.map(oData.Result, function (aItem) {
+ return aItem && aItem[0] ? new EmailModel(aItem[0], aItem[1]) : null;
+ });
+
+ fCallback(_.compact(aData));
+ }
+ else if (Enums.StorageResultType.Abort !== sResult)
+ {
+ fCallback([]);
+ }
+
+ }, sQuery);
+};
+
+/**
+ * @param {string} sQuery
+ * @param {Function} fCallback
+ */
+RainLoopApp.prototype.getContactTagsAutocomplete = function (sQuery, fCallback)
+{
+ fCallback(_.filter(RL.data().contactTags(), function (oContactTag) {
+ return oContactTag && oContactTag.filterHelper(sQuery);
+ }));
+};
+
+/**
+ * @param {string} sMailToUrl
+ * @returns {boolean}
+ */
+RainLoopApp.prototype.mailToHelper = function (sMailToUrl)
+{
+ if (sMailToUrl && 'mailto:' === sMailToUrl.toString().substr(0, 7).toLowerCase())
+ {
+ sMailToUrl = sMailToUrl.toString().substr(7);
+
+ var
+ oParams = {},
+ oEmailModel = null,
+ sEmail = sMailToUrl.replace(/\?.+$/, ''),
+ sQueryString = sMailToUrl.replace(/^[^\?]*\?/, '')
+ ;
+
+ oEmailModel = new EmailModel();
+ oEmailModel.parse(window.decodeURIComponent(sEmail));
+
+ if (oEmailModel && oEmailModel.email)
+ {
+ oParams = Utils.simpleQueryParser(sQueryString);
+ kn.showScreenPopup(PopupsComposeViewModel, [Enums.ComposeType.Empty, null, [oEmailModel],
+ Utils.isUnd(oParams.subject) ? null : Utils.pString(oParams.subject),
+ Utils.isUnd(oParams.body) ? null : Utils.plainToHtml(Utils.pString(oParams.body))
+ ]);
+ }
+
+ return true;
+ }
+
+ return false;
+};
+
+RainLoopApp.prototype.bootstart = function ()
+{
+ RL.pub('rl.bootstart');
+ AbstractApp.prototype.bootstart.call(this);
+
+ RL.data().populateDataOnStart();
+
+ var
+ sCustomLoginLink = '',
+ sJsHash = RL.settingsGet('JsHash'),
+ iContactsSyncInterval = Utils.pInt(RL.settingsGet('ContactsSyncInterval')),
+ bGoogle = RL.settingsGet('AllowGoogleSocial'),
+ bFacebook = RL.settingsGet('AllowFacebookSocial'),
+ bTwitter = RL.settingsGet('AllowTwitterSocial')
+ ;
+
+ if (!RL.settingsGet('ChangePasswordIsAllowed'))
+ {
+ Utils.removeSettingsViewModel(SettingsChangePasswordScreen);
+ }
+
+ if (!RL.settingsGet('ContactsIsAllowed'))
+ {
+ Utils.removeSettingsViewModel(SettingsContacts);
+ }
+
+ if (!RL.capa(Enums.Capa.AdditionalAccounts))
+ {
+ Utils.removeSettingsViewModel(SettingsAccounts);
+ }
+
+ if (RL.capa(Enums.Capa.AdditionalIdentities))
+ {
+ Utils.removeSettingsViewModel(SettingsIdentity);
+ }
+ else
+ {
+ Utils.removeSettingsViewModel(SettingsIdentities);
+ }
+
+ if (!RL.capa(Enums.Capa.OpenPGP))
+ {
+ Utils.removeSettingsViewModel(SettingsOpenPGP);
+ }
+
+ if (!RL.capa(Enums.Capa.TwoFactor))
+ {
+ Utils.removeSettingsViewModel(SettingsSecurity);
+ }
+
+ if (!RL.capa(Enums.Capa.Themes))
+ {
+ Utils.removeSettingsViewModel(SettingsThemes);
+ }
+
+ if (!RL.capa(Enums.Capa.Filters))
+ {
+ Utils.removeSettingsViewModel(SettingsFilters);
+ }
+
+ if (!bGoogle && !bFacebook && !bTwitter)
+ {
+ Utils.removeSettingsViewModel(SettingsSocialScreen);
+ }
+
+ Utils.initOnStartOrLangChange(function () {
+
+ $.extend(true, $.magnificPopup.defaults, {
+ 'tClose': Utils.i18n('MAGNIFIC_POPUP/CLOSE'),
+ 'tLoading': Utils.i18n('MAGNIFIC_POPUP/LOADING'),
+ 'gallery': {
+ 'tPrev': Utils.i18n('MAGNIFIC_POPUP/GALLERY_PREV'),
+ 'tNext': Utils.i18n('MAGNIFIC_POPUP/GALLERY_NEXT'),
+ 'tCounter': Utils.i18n('MAGNIFIC_POPUP/GALLERY_COUNTER')
+ },
+ 'image': {
+ 'tError': Utils.i18n('MAGNIFIC_POPUP/IMAGE_ERROR')
+ },
+ 'ajax': {
+ 'tError': Utils.i18n('MAGNIFIC_POPUP/AJAX_ERROR')
+ }
+ });
+
+ }, this);
+
+ if (window.SimplePace)
+ {
+ window.SimplePace.set(70);
+ window.SimplePace.sleep();
+ }
+
+ if (!!RL.settingsGet('Auth'))
+ {
+ this.setTitle(Utils.i18n('TITLES/LOADING'));
+
+ this.folders(_.bind(function (bValue) {
+
+ kn.hideLoading();
+
+ if (bValue)
+ {
+ if (window.$LAB && window.crypto && window.crypto.getRandomValues && RL.capa(Enums.Capa.OpenPGP))
+ {
+ window.$LAB.script(window.openpgp ? '' : RL.link().openPgpJs()).wait(function () {
+ if (window.openpgp)
+ {
+ RL.data().openpgpKeyring = new window.openpgp.Keyring();
+ RL.data().capaOpenPGP(true);
+
+ RL.pub('openpgp.init');
+
+ RL.reloadOpenPgpKeys();
+ }
+ });
+ }
+ else
+ {
+ RL.data().capaOpenPGP(false);
+ }
+
+ kn.startScreens([MailBoxScreen, SettingsScreen]);
+
+ if (bGoogle || bFacebook || bTwitter)
+ {
+ RL.socialUsers(true);
+ }
+
+ RL.sub('interval.2m', function () {
+ RL.folderInformation('INBOX');
+ });
+
+ RL.sub('interval.2m', function () {
+ var sF = RL.data().currentFolderFullNameRaw();
+ if ('INBOX' !== sF)
+ {
+ RL.folderInformation(sF);
+ }
+ });
+
+ RL.sub('interval.3m', function () {
+ RL.folderInformationMultiply();
+ });
+
+ RL.sub('interval.5m', function () {
+ RL.quota();
+ });
+
+ RL.sub('interval.10m', function () {
+ RL.folders();
+ });
+
+ iContactsSyncInterval = 5 <= iContactsSyncInterval ? iContactsSyncInterval : 20;
+ iContactsSyncInterval = 320 >= iContactsSyncInterval ? iContactsSyncInterval : 320;
+
+ window.setInterval(function () {
+ RL.contactsSync();
+ }, iContactsSyncInterval * 60000 + 5000);
+
+ _.delay(function () {
+ RL.contactsSync();
+ }, 5000);
+
+ _.delay(function () {
+ RL.folderInformationMultiply(true);
+ }, 500);
+
+ Plugins.runHook('rl-start-user-screens');
+ RL.pub('rl.bootstart-user-screens');
+
+ if (!!RL.settingsGet('AccountSignMe') && window.navigator.registerProtocolHandler)
+ {
+ _.delay(function () {
+ try {
+ window.navigator.registerProtocolHandler('mailto',
+ window.location.protocol + '//' + window.location.host + window.location.pathname + '?mailto&to=%s',
+ '' + (RL.settingsGet('Title') || 'RainLoop'));
+ } catch(e) {}
+
+ if (RL.settingsGet('MailToEmail'))
+ {
+ RL.mailToHelper(RL.settingsGet('MailToEmail'));
+ }
+ }, 500);
+ }
+ }
+ else
+ {
+ kn.startScreens([LoginScreen]);
+
+ Plugins.runHook('rl-start-login-screens');
+ RL.pub('rl.bootstart-login-screens');
+ }
+
+ if (window.SimplePace)
+ {
+ window.SimplePace.set(100);
+ }
+
+ if (!Globals.bMobileDevice)
+ {
+ _.defer(function () {
+ Utils.initLayoutResizer('#rl-left', '#rl-right', Enums.ClientSideKeyName.FolderListSize);
+ });
+ }
+
+ }, this));
+ }
+ else
+ {
+ sCustomLoginLink = Utils.pString(RL.settingsGet('CustomLoginLink'));
+ if (!sCustomLoginLink)
+ {
+ kn.hideLoading();
+ kn.startScreens([LoginScreen]);
+
+ Plugins.runHook('rl-start-login-screens');
+ RL.pub('rl.bootstart-login-screens');
+
+ if (window.SimplePace)
+ {
+ window.SimplePace.set(100);
+ }
+ }
+ else
+ {
+ kn.routeOff();
+ kn.setHash(RL.link().root(), true);
+ kn.routeOff();
+
+ _.defer(function () {
+ window.location.href = sCustomLoginLink;
+ });
+ }
+ }
+
+ if (bGoogle)
+ {
+ window['rl_' + sJsHash + '_google_service'] = function () {
+ RL.data().googleActions(true);
+ RL.socialUsers();
+ };
+ }
+
+ if (bFacebook)
+ {
+ window['rl_' + sJsHash + '_facebook_service'] = function () {
+ RL.data().facebookActions(true);
+ RL.socialUsers();
+ };
+ }
+
+ if (bTwitter)
+ {
+ window['rl_' + sJsHash + '_twitter_service'] = function () {
+ RL.data().twitterActions(true);
+ RL.socialUsers();
+ };
+ }
+
+ RL.sub('interval.1m', function () {
+ Globals.momentTrigger(!Globals.momentTrigger());
+ });
+
+ Plugins.runHook('rl-start-screens');
+ RL.pub('rl.bootstart-end');
+};
+
+/**
+ * @type {RainLoopApp}
+ */
+RL = new RainLoopApp();
+
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+$html.addClass(Globals.bMobileDevice ? 'mobile' : 'no-mobile');
+
+$window.keydown(Utils.killCtrlAandS).keyup(Utils.killCtrlAandS);
+$window.unload(function () {
+ Globals.bUnload = true;
+});
+
+$html.on('click.dropdown.data-api', function () {
+ Utils.detectDropdownVisibility();
+});
+
+// export
+window['rl'] = window['rl'] || {};
+window['rl']['addHook'] = Plugins.addHook;
+window['rl']['settingsGet'] = Plugins.mainSettingsGet;
+window['rl']['remoteRequest'] = Plugins.remoteRequest;
+window['rl']['pluginSettingsGet'] = Plugins.settingsGet;
+window['rl']['addSettingsViewModel'] = Utils.addSettingsViewModel;
+window['rl']['createCommand'] = Utils.createCommand;
+
+window['rl']['EmailModel'] = EmailModel;
+window['rl']['Enums'] = Enums;
+
+window['__RLBOOT'] = function (fCall) {
+
+ // boot
+ $(function () {
+
+ if (window['rainloopTEMPLATES'] && window['rainloopTEMPLATES'][0])
+ {
+ $('#rl-templates').html(window['rainloopTEMPLATES'][0]);
+
+ _.delay(function () {
+ window['rainloopAppData'] = {};
+ window['rainloopI18N'] = {};
+ window['rainloopTEMPLATES'] = {};
+
+ kn.setBoot(RL).bootstart();
+ $html.removeClass('no-js rl-booted-trigger').addClass('rl-booted');
+
+ }, 50);
+ }
+ else
+ {
+ fCall(false);
+ }
+
+ window['__RLBOOT'] = null;
+ });
+};
+
+
+}(window, jQuery, ko, crossroads, hasher, moment, Jua, _, ifvisible, key));
\ No newline at end of file
diff --git a/rainloop/v/0.0.0/static/js/_app.min.js b/rainloop/v/0.0.0/static/js/_app.min.js
new file mode 100644
index 000000000..b580fa7e0
--- /dev/null
+++ b/rainloop/v/0.0.0/static/js/_app.min.js
@@ -0,0 +1,11 @@
+/*! RainLoop Webmail Main Module (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+!function(e,t,s,i,o,n,a,r,l,c){"use strict";function u(){this.sBase="#/",this.sServer="./?",this.sVersion=jt.settingsGet("Version"),this.sSpecSuffix=jt.settingsGet("AuthAccountHash")||"0",this.sStaticPrefix=jt.settingsGet("StaticPrefix")||"rainloop/v/"+this.sVersion+"/static/"}function d(e,s,i,o){var n=this;n.editor=null,n.iBlurTimer=0,n.fOnBlur=s||null,n.fOnReady=i||null,n.fOnModeChange=o||null,n.$element=t(e),n.resize=r.throttle(r.bind(n.resize,n),100),n.init()}function h(e,t,i,o,n,a){this.list=e,this.listChecked=s.computed(function(){return r.filter(this.list(),function(e){return e.checked()})},this).extend({rateLimit:0}),this.isListChecked=s.computed(function(){return 00&&-1t?t:e))},this),this.body=null,this.plainRaw="",this.isHtml=s.observable(!1),this.hasImages=s.observable(!1),this.attachments=s.observableArray([]),this.isPgpSigned=s.observable(!1),this.isPgpEncrypted=s.observable(!1),this.pgpSignedVerifyStatus=s.observable(Lt.SignedVerifyStatus.None),this.pgpSignedVerifyUser=s.observable(""),this.priority=s.observable(Lt.MessagePriority.Normal),this.readReceipt=s.observable(""),this.aDraftInfo=[],this.sMessageId="",this.sInReplyTo="",this.sReferences="",this.parentUid=s.observable(0),this.threads=s.observableArray([]),this.threadsLen=s.observable(0),this.hasUnseenSubMessage=s.observable(!1),this.hasFlaggedSubMessage=s.observable(!1),this.lastInCollapsedThread=s.observable(!1),this.lastInCollapsedThreadLoading=s.observable(!1),this.threadsLenResult=s.computed(function(){var e=this.threadsLen();return 0===this.parentUid()&&e>0?e+1:""},this)}function N(){this.name=s.observable(""),this.fullName="",this.fullNameRaw="",this.fullNameHash="",this.delimiter="",this.namespace="",this.deep=0,this.interval=0,this.selectable=!1,this.existen=!0,this.type=s.observable(Lt.FolderType.User),this.focused=s.observable(!1),this.selected=s.observable(!1),this.edited=s.observable(!1),this.collapsed=s.observable(!0),this.subScribed=s.observable(!0),this.subFolders=s.observableArray([]),this.deleteAccess=s.observable(!1),this.actionBlink=s.observable(!1).extend({falseTimeout:1e3}),this.nameForEdit=s.observable(""),this.name.subscribe(function(e){this.nameForEdit(e)},this),this.edited.subscribe(function(e){e&&this.nameForEdit(this.name())},this),this.privateMessageCountAll=s.observable(0),this.privateMessageCountUnread=s.observable(0),this.collapsedPrivate=s.observable(!0)}function R(e,t){this.email=e,this.deleteAccess=s.observable(!1),this.canBeDalete=s.observable(t)}function I(e,t,i){this.id=e,this.email=s.observable(t),this.name=s.observable(""),this.replyTo=s.observable(""),this.bcc=s.observable(""),this.deleteAccess=s.observable(!1),this.canBeDalete=s.observable(i)}function L(e){this.parentList=e,this.field=s.observable(Lt.FilterConditionField.From),this.fieldOptions=[{id:Lt.FilterConditionField.From,name:"From"},{id:Lt.FilterConditionField.Recipient,name:"Recipient (To or CC)"},{id:Lt.FilterConditionField.To,name:"To"},{id:Lt.FilterConditionField.Subject,name:"Subject"}],this.type=s.observable(Lt.FilterConditionType.EqualTo),this.typeOptions=[{id:Lt.FilterConditionType.EqualTo,name:"Equal To"},{id:Lt.FilterConditionType.NotEqualTo,name:"Not Equal To"},{id:Lt.FilterConditionType.Contains,name:"Contains"},{id:Lt.FilterConditionType.NotContains,name:"Not Contains"}],this.value=s.observable(""),this.template=s.computed(function(){var e="";switch(this.type()){default:e="SettingsFiltersConditionDefault"}return e},this)}function P(){this.new=s.observable(!0),this.enabled=s.observable(!0),this.name=s.observable(""),this.conditionsType=s.observable(Lt.FilterRulesType.And),this.conditions=s.observableArray([]),this.conditions.subscribe(function(){Mt.windowResize()}),this.actionMarkAsRead=s.observable(!1),this.actionSkipOtherFilters=s.observable(!0),this.actionValue=s.observable(""),this.actionType=s.observable(Lt.FiltersAction.Move),this.actionTypeOptions=[{id:Lt.FiltersAction.None,name:"Action - None"},{id:Lt.FiltersAction.Move,name:"Action - Move to"},{id:Lt.FiltersAction.Discard,name:"Action - Discard"}],this.actionMarkAsReadVisiblity=s.computed(function(){return-1=e?1:e},this),this.contactsPagenator=s.computed(Mt.computedPagenatorHelper(this.contactsPage,this.contactsPageCount)),this.emptySelection=s.observable(!0),this.viewClearSearch=s.observable(!1),this.viewID=s.observable(""),this.viewReadOnly=s.observable(!1),this.viewProperties=s.observableArray([]),this.viewTags=s.observable(""),this.viewTags.visibility=s.observable(!1),this.viewTags.focusTrigger=s.observable(!1),this.viewTags.focusTrigger.subscribe(function(e){e||""!==this.viewTags()?e&&this.viewTags.visibility(!0):this.viewTags.visibility(!1)},this),this.viewSaveTrigger=s.observable(Lt.SaveSettingsStep.Idle),this.viewPropertiesNames=this.viewProperties.filter(function(e){return-1e)break;t[0]&&t[1]&&t[2]&&t[1]===t[2]&&("PRIVATE"===t[1]?o.privateKeys.importKey(t[0]):"PUBLIC"===t[1]&&o.publicKeys.importKey(t[0])),e--}return o.store(),jt.reloadOpenPgpKeys(),Mt.delegateRun(this,"cancelCommand"),!0}),S.constructorEnd(this)}function B(){b.call(this,"Popups","PopupsViewOpenPgpKey"),this.key=s.observable(""),this.keyDom=s.observable(null),S.constructorEnd(this)}function G(){b.call(this,"Popups","PopupsGenerateNewOpenPgpKey"),this.email=s.observable(""),this.email.focus=s.observable(""),this.email.error=s.observable(!1),this.name=s.observable(""),this.password=s.observable(""),this.keyBitLength=s.observable(2048),this.submitRequest=s.observable(!1),this.email.subscribe(function(){this.email.error(!1)},this),this.generateOpenPgpKeyCommand=Mt.createCommand(this,function(){var t=this,s="",i=null,o=jt.data().openpgpKeyring;return this.email.error(""===Mt.trim(this.email())),!o||this.email.error()?!1:(s=this.email(),""!==this.name()&&(s=this.name()+" <"+s+">"),this.submitRequest(!0),r.delay(function(){i=e.openpgp.generateKeyPair({userId:s,numBits:Mt.pInt(t.keyBitLength()),passphrase:Mt.trim(t.password())}),i&&i.privateKeyArmored&&(o.privateKeys.importKey(i.privateKeyArmored),o.publicKeys.importKey(i.publicKeyArmored),o.store(),jt.reloadOpenPgpKeys(),Mt.delegateRun(t,"cancelCommand")),t.submitRequest(!1)
+},100),!0)}),S.constructorEnd(this)}function K(){b.call(this,"Popups","PopupsComposeOpenPgp"),this.notification=s.observable(""),this.sign=s.observable(!0),this.encrypt=s.observable(!0),this.password=s.observable(""),this.password.focus=s.observable(!1),this.buttonFocus=s.observable(!1),this.from=s.observable(""),this.to=s.observableArray([]),this.text=s.observable(""),this.resultCallback=null,this.submitRequest=s.observable(!1),this.doCommand=Mt.createCommand(this,function(){var t=this,s=!0,i=jt.data(),o=null,n=[];this.submitRequest(!0),s&&this.sign()&&""===this.from()&&(this.notification(Mt.i18n("PGP_NOTIFICATIONS/SPECIFY_FROM_EMAIL")),s=!1),s&&this.sign()&&(o=i.findPrivateKeyByEmail(this.from(),this.password()),o||(this.notification(Mt.i18n("PGP_NOTIFICATIONS/NO_PRIVATE_KEY_FOUND_FOR",{EMAIL:this.from()})),s=!1)),s&&this.encrypt()&&0===this.to().length&&(this.notification(Mt.i18n("PGP_NOTIFICATIONS/SPECIFY_AT_LEAST_ONE_RECIPIENT")),s=!1),s&&this.encrypt()&&(n=[],r.each(this.to(),function(e){var o=i.findPublicKeysByEmail(e);0===o.length&&s&&(t.notification(Mt.i18n("PGP_NOTIFICATIONS/NO_PUBLIC_KEYS_FOUND_FOR",{EMAIL:e})),s=!1),n=n.concat(o)}),!s||0!==n.length&&this.to().length===n.length||(s=!1)),r.delay(function(){if(t.resultCallback&&s)try{o&&0===n.length?t.resultCallback(e.openpgp.signClearMessage([o],t.text())):o&&00&&t>0&&e>t},this),this.hasMessages=s.computed(function(){return 0'),o.after(n),o.remove()),n&&n[0]&&(n.attr("data-href",a).attr("data-theme",e[0]),n&&n[0]&&n[0].styleSheet&&!Mt.isUnd(n[0].styleSheet.cssText)?n[0].styleSheet.cssText=e[1]:n.text(e[1])),i.themeTrigger(Lt.SaveSettingsStep.TrueResult))}).always(function(){i.iTimer=e.setTimeout(function(){i.themeTrigger(Lt.SaveSettingsStep.Idle)},1e3),i.oLastAjax=null})),jt.remote().saveSettings(null,{Theme:s})},this)}function ft(){this.openpgpkeys=jt.data().openpgpkeys,this.openpgpkeysPublic=jt.data().openpgpkeysPublic,this.openpgpkeysPrivate=jt.data().openpgpkeysPrivate,this.openPgpKeyForDeletion=s.observable(null).extend({falseTimeout:3e3}).extend({toggleSubscribe:[this,function(e){e&&e.deleteAccess(!1)},function(e){e&&e.deleteAccess(!0)}]})}function bt(){this.leftPanelDisabled=s.observable(!1),this.useKeyboardShortcuts=s.observable(!0),this.keyScopeReal=s.observable(Lt.KeyState.All),this.keyScopeFake=s.observable(Lt.KeyState.All),this.keyScope=s.computed({owner:this,read:function(){return this.keyScopeFake()},write:function(e){Lt.KeyState.Menu!==e&&(Lt.KeyState.Compose===e?Mt.disableKeyFilter():Mt.restoreKeyFilter(),this.keyScopeFake(e),Ot.dropdownVisibility()&&(e=Lt.KeyState.Menu)),this.keyScopeReal(e)}}),this.keyScopeReal.subscribe(function(e){c.setScope(e)}),this.leftPanelDisabled.subscribe(function(e){jt.pub("left-panel."+(e?"off":"on"))}),Ot.dropdownVisibility.subscribe(function(e){e?(Ot.tooltipTrigger(!Ot.tooltipTrigger()),this.keyScope(Lt.KeyState.Menu)):Lt.KeyState.Menu===c.getScope()&&this.keyScope(this.keyScopeFake())
+},this),Mt.initDataConstructorBySettings(this)}function yt(){bt.call(this);var i=function(e){return function(){var t=jt.cache().getFolderFromCacheList(e());t&&t.type(Lt.FolderType.User)}},o=function(e){return function(t){var s=jt.cache().getFolderFromCacheList(t);s&&s.type(e)}};this.devEmail="",this.devPassword="",this.accountEmail=s.observable(""),this.accountIncLogin=s.observable(""),this.accountOutLogin=s.observable(""),this.projectHash=s.observable(""),this.threading=s.observable(!1),this.lastFoldersHash="",this.remoteSuggestions=!1,this.sentFolder=s.observable(""),this.draftFolder=s.observable(""),this.spamFolder=s.observable(""),this.trashFolder=s.observable(""),this.archiveFolder=s.observable(""),this.sentFolder.subscribe(i(this.sentFolder),this,"beforeChange"),this.draftFolder.subscribe(i(this.draftFolder),this,"beforeChange"),this.spamFolder.subscribe(i(this.spamFolder),this,"beforeChange"),this.trashFolder.subscribe(i(this.trashFolder),this,"beforeChange"),this.archiveFolder.subscribe(i(this.archiveFolder),this,"beforeChange"),this.sentFolder.subscribe(o(Lt.FolderType.SentItems),this),this.draftFolder.subscribe(o(Lt.FolderType.Draft),this),this.spamFolder.subscribe(o(Lt.FolderType.Spam),this),this.trashFolder.subscribe(o(Lt.FolderType.Trash),this),this.archiveFolder.subscribe(o(Lt.FolderType.Archive),this),this.draftFolderNotEnabled=s.computed(function(){return""===this.draftFolder()||It.Values.UnuseOptionValue===this.draftFolder()},this),this.displayName=s.observable(""),this.signature=s.observable(""),this.signatureToAll=s.observable(!1),this.replyTo=s.observable(""),this.enableTwoFactor=s.observable(!1),this.accounts=s.observableArray([]),this.accountsLoading=s.observable(!1).extend({throttle:100}),this.defaultIdentityID=s.observable(""),this.identities=s.observableArray([]),this.identitiesLoading=s.observable(!1).extend({throttle:100}),this.contactTags=s.observableArray([]),this.contacts=s.observableArray([]),this.contacts.loading=s.observable(!1).extend({throttle:200}),this.contacts.importing=s.observable(!1).extend({throttle:200}),this.contacts.syncing=s.observable(!1).extend({throttle:200}),this.contacts.exportingVcf=s.observable(!1).extend({throttle:200}),this.contacts.exportingCsv=s.observable(!1).extend({throttle:200}),this.allowContactsSync=s.observable(!1),this.enableContactsSync=s.observable(!1),this.contactsSyncUrl=s.observable(""),this.contactsSyncUser=s.observable(""),this.contactsSyncPass=s.observable(""),this.allowContactsSync=s.observable(!!jt.settingsGet("ContactsSyncIsAllowed")),this.enableContactsSync=s.observable(!!jt.settingsGet("EnableContactsSync")),this.contactsSyncUrl=s.observable(jt.settingsGet("ContactsSyncUrl")),this.contactsSyncUser=s.observable(jt.settingsGet("ContactsSyncUser")),this.contactsSyncPass=s.observable(jt.settingsGet("ContactsSyncPassword")),this.namespace="",this.folderList=s.observableArray([]),this.folderList.focused=s.observable(!1),this.foldersListError=s.observable(""),this.foldersLoading=s.observable(!1),this.foldersCreating=s.observable(!1),this.foldersDeleting=s.observable(!1),this.foldersRenaming=s.observable(!1),this.foldersChanging=s.computed(function(){var e=this.foldersLoading(),t=this.foldersCreating(),s=this.foldersDeleting(),i=this.foldersRenaming();return e||t||s||i},this),this.foldersInboxUnreadCount=s.observable(0),this.currentFolder=s.observable(null).extend({toggleSubscribe:[null,function(e){e&&e.selected(!1)},function(e){e&&e.selected(!0)}]}),this.currentFolderFullNameRaw=s.computed(function(){return this.currentFolder()?this.currentFolder().fullNameRaw:""},this),this.currentFolderFullName=s.computed(function(){return this.currentFolder()?this.currentFolder().fullName:""},this),this.currentFolderFullNameHash=s.computed(function(){return this.currentFolder()?this.currentFolder().fullNameHash:""},this),this.currentFolderName=s.computed(function(){return this.currentFolder()?this.currentFolder().name():""},this),this.folderListSystemNames=s.computed(function(){var e=["INBOX"],t=this.folderList(),s=this.sentFolder(),i=this.draftFolder(),o=this.spamFolder(),n=this.trashFolder(),a=this.archiveFolder();return Mt.isArray(t)&&0=e?1:e},this),this.mainMessageListSearch=s.computed({read:this.messageListSearch,write:function(e){xt.setHash(jt.link().mailBox(this.currentFolderFullNameHash(),1,Mt.trim(e.toString())))},owner:this}),this.messageListError=s.observable(""),this.messageListLoading=s.observable(!1),this.messageListIsNotCompleted=s.observable(!1),this.messageListCompleteLoadingThrottle=s.observable(!1).extend({throttle:200}),this.messageListCompleteLoading=s.computed(function(){var e=this.messageListLoading(),t=this.messageListIsNotCompleted();return e||t},this),this.messageListCompleteLoading.subscribe(function(e){this.messageListCompleteLoadingThrottle(e)},this),this.messageList.subscribe(r.debounce(function(e){r.each(e,function(e){e.newForAnimation()&&e.newForAnimation(!1)})},500)),this.staticMessageList=new E,this.message=s.observable(null),this.messageLoading=s.observable(!1),this.messageLoadingThrottle=s.observable(!1).extend({throttle:50}),this.message.focused=s.observable(!1),this.message.subscribe(function(t){t?Lt.Layout.NoPreview===this.layout()&&this.message.focused(!0):(this.message.focused(!1),this.messageFullScreenMode(!1),this.hideMessageBodies(),Lt.Layout.NoPreview===jt.data().layout()&&-10?Math.ceil(t/e*100):0},this),this.capaOpenPGP=s.observable(!1),this.openpgpkeys=s.observableArray([]),this.openpgpKeyring=null,this.openpgpkeysPublic=this.openpgpkeys.filter(function(e){return!(!e||e.isPrivate)}),this.openpgpkeysPrivate=this.openpgpkeys.filter(function(e){return!(!e||!e.isPrivate)}),this.googleActions=s.observable(!1),this.googleLoggined=s.observable(!1),this.googleUserName=s.observable(""),this.facebookActions=s.observable(!1),this.facebookLoggined=s.observable(!1),this.facebookUserName=s.observable(""),this.twitterActions=s.observable(!1),this.twitterLoggined=s.observable(!1),this.twitterUserName=s.observable(""),this.customThemeType=s.observable(Lt.CustomThemeType.Light),this.purgeMessageBodyCacheThrottle=r.throttle(this.purgeMessageBodyCache,3e4)}function St(){this.oRequests={}}function vt(){St.call(this),this.oRequests={}}function Ct(){this.bCapaGravatar=jt.capa(Lt.Capa.Gravatar)}function wt(){Ct.call(this),this.oFoldersCache={},this.oFoldersNamesCache={},this.oFolderHashCache={},this.oFolderUidNextCache={},this.oMessageListHashCache={},this.oMessageFlagsCache={},this.oNewMessage={},this.oRequestedMessage={}}function Tt(e){y.call(this,"settings",e),this.menu=s.observableArray([]),this.oCurrentSubScreen=null,this.oViewModelPlace=null}function Ft(){y.call(this,"login",[$])}function At(){y.call(this,"mailbox",[Q,et,tt,st]),this.oLastRoute={}}function Et(){Tt.call(this,[Z,it,ot]),Mt.initOnStartOrLangChange(function(){this.sSettingsTitle=Mt.i18n("TITLES/SETTINGS")},this,function(){jt.setTitle(this.sSettingsTitle)})}function Nt(){f.call(this),this.oSettings=null,this.oPlugins=null,this.oLocal=null,this.oLink=null,this.oSubs={},this.isLocalAutocomplete=!0,this.popupVisibilityNames=s.observableArray([]),this.popupVisibility=s.computed(function(){return 0').appendTo("body"),Gt.on("error",function(e){jt&&e&&e.originalEvent&&e.originalEvent.message&&-1===Mt.inArray(e.originalEvent.message,["Script error.","Uncaught Error: Error calling method on NPObject."])&&jt.remote().jsError(Mt.emptyFunction,e.originalEvent.message,e.originalEvent.filename,e.originalEvent.lineno,location&&location.toString?location.toString():"",Bt.attr("class"),Mt.microtime()-Ot.now)}),Kt.on("keydown",function(e){e&&e.ctrlKey&&Bt.addClass("rl-ctrl-key-pressed")}).on("keyup",function(e){e&&!e.ctrlKey&&Bt.removeClass("rl-ctrl-key-pressed")})}function Rt(){Nt.call(this),this.oData=null,this.oRemote=null,this.oCache=null,this.oMoveCache={},this.quotaDebounce=r.debounce(this.quota,3e4),this.moveOrDeleteResponseHelper=r.bind(this.moveOrDeleteResponseHelper,this),this.messagesMoveTrigger=r.debounce(this.messagesMoveTrigger,500),e.setInterval(function(){jt.pub("interval.30s")},3e4),e.setInterval(function(){jt.pub("interval.1m")},6e4),e.setInterval(function(){jt.pub("interval.2m")},12e4),e.setInterval(function(){jt.pub("interval.3m")},18e4),e.setInterval(function(){jt.pub("interval.5m")},3e5),e.setInterval(function(){jt.pub("interval.10m")},6e5),e.setTimeout(function(){e.setInterval(function(){jt.pub("interval.10m-after5m")},6e5)},3e5),t.wakeUp(function(){jt.remote().jsVersion(function(t,s){Lt.StorageResultType.Success===t&&s&&!s.Result&&(e.parent&&jt.settingsGet("InIframe")?e.parent.location.reload():e.location.reload())},jt.settingsGet("Version"))},{},36e5)}var It={},Lt={},Pt={},Mt={},Dt={},kt={},Ot={},_t={settings:[],"settings-removed":[],"settings-disabled":[]},Ut=[],xt=null,Vt=e.rainloopAppData||{},Ht=e.rainloopI18N||{},Bt=t("html"),Gt=t(e),Kt=t(e.document),qt=e.Notification&&e.Notification.requestPermission?e.Notification:null,jt=null,zt=t("");Ot.now=(new Date).getTime(),Ot.momentTrigger=s.observable(!0),Ot.dropdownVisibility=s.observable(!1).extend({rateLimit:0}),Ot.tooltipTrigger=s.observable(!1).extend({rateLimit:0}),Ot.langChangeTrigger=s.observable(!0),Ot.iAjaxErrorCount=0,Ot.iTokenErrorCount=0,Ot.iMessageBodyCacheCount=0,Ot.bUnload=!1,Ot.sUserAgent=(navigator.userAgent||"").toLowerCase(),Ot.bIsiOSDevice=-1n;n++)o=i[n].split("="),s[e.decodeURIComponent(o[0])]=e.decodeURIComponent(o[1]);return s},Mt.rsaEncode=function(t,s,i,o){if(e.crypto&&e.crypto.getRandomValues&&e.RSAKey&&s&&i&&o){var n=new e.RSAKey;if(n.setPublic(o,i),t=n.encrypt(Mt.fakeMd5()+":"+t+":"+Mt.fakeMd5()),!1!==t)return"rsa:"+s+":"+t}return!1},Mt.rsaEncode.supported=!!(e.crypto&&e.crypto.getRandomValues&&e.RSAKey),Mt.exportPath=function(t,s,i){for(var o=null,n=t.split("."),a=i||e;n.length&&(o=n.shift());)n.length||Mt.isUnd(s)?a=a[o]?a[o]:a[o]={}:a[o]=s},Mt.pImport=function(e,t,s){e[t]=s},Mt.pExport=function(e,t,s){return Mt.isUnd(e[t])?s:e[t]},Mt.encodeHtml=function(e){return Mt.isNormal(e)?e.toString().replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"):""},Mt.splitPlainText=function(e,t){var s="",i="",o=e,n=0,a=0;for(t=Mt.isUnd(t)?100:t;o.length>t;)i=o.substring(0,t),n=i.lastIndexOf(" "),a=i.lastIndexOf("\n"),-1!==a&&(n=a),-1===n&&(n=t),s+=i.substring(0,n)+"\n",o=o.substring(n+1);return s+o},Mt.timeOutAction=function(){var t={};return function(s,i,o){Mt.isUnd(t[s])&&(t[s]=0),e.clearTimeout(t[s]),t[s]=e.setTimeout(i,o)}}(),Mt.timeOutActionSecond=function(){var t={};return function(s,i,o){t[s]||(t[s]=e.setTimeout(function(){i(),t[s]=0},o))}}(),Mt.audio=function(){var t=!1;return function(s,i){if(!1===t)if(Ot.bIsiOSDevice)t=null;else{var o=!1,n=!1,a=e.Audio?new e.Audio:null;a&&a.canPlayType&&a.play?(o=""!==a.canPlayType('audio/mpeg; codecs="mp3"'),o||(n=""!==a.canPlayType('audio/ogg; codecs="vorbis"')),o||n?(t=a,t.preload="none",t.loop=!1,t.autoplay=!1,t.muted=!1,t.src=o?s:i):t=null):t=null}return t}}(),Mt.hos=function(e,t){return e&&Object.hasOwnProperty?Object.hasOwnProperty.call(e,t):!1},Mt.i18n=function(e,t,s){var i="",o=Mt.isUnd(Ht[e])?Mt.isUnd(s)?e:s:Ht[e];if(!Mt.isUnd(t)&&!Mt.isNull(t))for(i in t)Mt.hos(t,i)&&(o=o.replace("%"+i+"%",t[i]));return o},Mt.i18nToNode=function(e){r.defer(function(){t(".i18n",e).each(function(){var e=t(this),s="";s=e.data("i18n-text"),s?e.text(Mt.i18n(s)):(s=e.data("i18n-html"),s&&e.html(Mt.i18n(s)),s=e.data("i18n-placeholder"),s&&e.attr("placeholder",Mt.i18n(s)),s=e.data("i18n-title"),s&&e.attr("title",Mt.i18n(s)))})})},Mt.i18nToDoc=function(){e.rainloopI18N&&(Ht=e.rainloopI18N||{},Mt.i18nToNode(Kt),Ot.langChangeTrigger(!Ot.langChangeTrigger())),e.rainloopI18N={}},Mt.initOnStartOrLangChange=function(e,t,s){e&&e.call(t),s?Ot.langChangeTrigger.subscribe(function(){e&&e.call(t),s.call(t)}):e&&Ot.langChangeTrigger.subscribe(e,t)},Mt.inFocus=function(){return document.activeElement?(Mt.isUnd(document.activeElement.__inFocusCache)&&(document.activeElement.__inFocusCache=t(document.activeElement).is("input,textarea,iframe,.cke_editable")),!!document.activeElement.__inFocusCache):!1},Mt.removeInFocus=function(){if(document&&document.activeElement&&document.activeElement.blur){var e=t(document.activeElement);e.is("input,textarea")&&document.activeElement.blur()}},Mt.removeSelection=function(){if(e&&e.getSelection){var t=e.getSelection();t&&t.removeAllRanges&&t.removeAllRanges()}else document&&document.selection&&document.selection.empty&&document.selection.empty()},Mt.replySubjectAdd=function(e,t){e=Mt.trim(e.toUpperCase()),t=Mt.trim(t.replace(/[\s]+/," "));var s=0,i="",o=!1,n="",a=[],r=[],l="RE"===e,c="FWD"===e,u=!c;if(""!==t){for(o=!1,r=t.split(":"),s=0;s0);return e.replace(/[\s]+/," ")},Mt._replySubjectAdd_=function(t,s,i){var o=null,n=Mt.trim(s);return n=null===(o=new e.RegExp("^"+t+"[\\s]?\\:(.*)$","gi").exec(s))||Mt.isUnd(o[1])?null===(o=new e.RegExp("^("+t+"[\\s]?[\\[\\(]?)([\\d]+)([\\]\\)]?[\\s]?\\:.*)$","gi").exec(s))||Mt.isUnd(o[1])||Mt.isUnd(o[2])||Mt.isUnd(o[3])?t+": "+s:o[1]+(Mt.pInt(o[2])+1)+o[3]:t+"[2]: "+o[1],n=n.replace(/[\s]+/g," "),n=(Mt.isUnd(i)?!0:i)?Mt.fixLongSubject(n):n},Mt._fixLongSubject_=function(e){var t=0,s=null;e=Mt.trim(e.replace(/[\s]+/," "));do s=/^Re(\[([\d]+)\]|):[\s]{0,3}Re(\[([\d]+)\]|):/gi.exec(e),(!s||Mt.isUnd(s[0]))&&(s=null),s&&(t=0,t+=Mt.isUnd(s[2])?1:0+Mt.pInt(s[2]),t+=Mt.isUnd(s[4])?1:0+Mt.pInt(s[4]),e=e.replace(/^Re(\[[\d]+\]|):[\s]{0,3}Re(\[[\d]+\]|):/gi,"Re"+(t>0?"["+t+"]":"")+":"));while(s);return e=e.replace(/[\s]+/," ")},Mt.roundNumber=function(e,t){return Math.round(e*Math.pow(10,t))/Math.pow(10,t)},Mt.friendlySize=function(e){return e=Mt.pInt(e),e>=1073741824?Mt.roundNumber(e/1073741824,1)+"GB":e>=1048576?Mt.roundNumber(e/1048576,1)+"MB":e>=1024?Mt.roundNumber(e/1024,0)+"KB":e+"B"},Mt.log=function(t){e.console&&e.console.log&&e.console.log(t)},Mt.getNotification=function(e,t){return e=Mt.pInt(e),Lt.Notification.ClientViewError===e&&t?t:Mt.isUnd(Pt[e])?"":Pt[e]},Mt.initNotificationLanguage=function(){Pt[Lt.Notification.InvalidToken]=Mt.i18n("NOTIFICATIONS/INVALID_TOKEN"),Pt[Lt.Notification.AuthError]=Mt.i18n("NOTIFICATIONS/AUTH_ERROR"),Pt[Lt.Notification.AccessError]=Mt.i18n("NOTIFICATIONS/ACCESS_ERROR"),Pt[Lt.Notification.ConnectionError]=Mt.i18n("NOTIFICATIONS/CONNECTION_ERROR"),Pt[Lt.Notification.CaptchaError]=Mt.i18n("NOTIFICATIONS/CAPTCHA_ERROR"),Pt[Lt.Notification.SocialFacebookLoginAccessDisable]=Mt.i18n("NOTIFICATIONS/SOCIAL_FACEBOOK_LOGIN_ACCESS_DISABLE"),Pt[Lt.Notification.SocialTwitterLoginAccessDisable]=Mt.i18n("NOTIFICATIONS/SOCIAL_TWITTER_LOGIN_ACCESS_DISABLE"),Pt[Lt.Notification.SocialGoogleLoginAccessDisable]=Mt.i18n("NOTIFICATIONS/SOCIAL_GOOGLE_LOGIN_ACCESS_DISABLE"),Pt[Lt.Notification.DomainNotAllowed]=Mt.i18n("NOTIFICATIONS/DOMAIN_NOT_ALLOWED"),Pt[Lt.Notification.AccountNotAllowed]=Mt.i18n("NOTIFICATIONS/ACCOUNT_NOT_ALLOWED"),Pt[Lt.Notification.AccountTwoFactorAuthRequired]=Mt.i18n("NOTIFICATIONS/ACCOUNT_TWO_FACTOR_AUTH_REQUIRED"),Pt[Lt.Notification.AccountTwoFactorAuthError]=Mt.i18n("NOTIFICATIONS/ACCOUNT_TWO_FACTOR_AUTH_ERROR"),Pt[Lt.Notification.CouldNotSaveNewPassword]=Mt.i18n("NOTIFICATIONS/COULD_NOT_SAVE_NEW_PASSWORD"),Pt[Lt.Notification.CurrentPasswordIncorrect]=Mt.i18n("NOTIFICATIONS/CURRENT_PASSWORD_INCORRECT"),Pt[Lt.Notification.NewPasswordShort]=Mt.i18n("NOTIFICATIONS/NEW_PASSWORD_SHORT"),Pt[Lt.Notification.NewPasswordWeak]=Mt.i18n("NOTIFICATIONS/NEW_PASSWORD_WEAK"),Pt[Lt.Notification.NewPasswordForbidden]=Mt.i18n("NOTIFICATIONS/NEW_PASSWORD_FORBIDDENT"),Pt[Lt.Notification.ContactsSyncError]=Mt.i18n("NOTIFICATIONS/CONTACTS_SYNC_ERROR"),Pt[Lt.Notification.CantGetMessageList]=Mt.i18n("NOTIFICATIONS/CANT_GET_MESSAGE_LIST"),Pt[Lt.Notification.CantGetMessage]=Mt.i18n("NOTIFICATIONS/CANT_GET_MESSAGE"),Pt[Lt.Notification.CantDeleteMessage]=Mt.i18n("NOTIFICATIONS/CANT_DELETE_MESSAGE"),Pt[Lt.Notification.CantMoveMessage]=Mt.i18n("NOTIFICATIONS/CANT_MOVE_MESSAGE"),Pt[Lt.Notification.CantCopyMessage]=Mt.i18n("NOTIFICATIONS/CANT_MOVE_MESSAGE"),Pt[Lt.Notification.CantSaveMessage]=Mt.i18n("NOTIFICATIONS/CANT_SAVE_MESSAGE"),Pt[Lt.Notification.CantSendMessage]=Mt.i18n("NOTIFICATIONS/CANT_SEND_MESSAGE"),Pt[Lt.Notification.InvalidRecipients]=Mt.i18n("NOTIFICATIONS/INVALID_RECIPIENTS"),Pt[Lt.Notification.CantCreateFolder]=Mt.i18n("NOTIFICATIONS/CANT_CREATE_FOLDER"),Pt[Lt.Notification.CantRenameFolder]=Mt.i18n("NOTIFICATIONS/CANT_RENAME_FOLDER"),Pt[Lt.Notification.CantDeleteFolder]=Mt.i18n("NOTIFICATIONS/CANT_DELETE_FOLDER"),Pt[Lt.Notification.CantDeleteNonEmptyFolder]=Mt.i18n("NOTIFICATIONS/CANT_DELETE_NON_EMPTY_FOLDER"),Pt[Lt.Notification.CantSubscribeFolder]=Mt.i18n("NOTIFICATIONS/CANT_SUBSCRIBE_FOLDER"),Pt[Lt.Notification.CantUnsubscribeFolder]=Mt.i18n("NOTIFICATIONS/CANT_UNSUBSCRIBE_FOLDER"),Pt[Lt.Notification.CantSaveSettings]=Mt.i18n("NOTIFICATIONS/CANT_SAVE_SETTINGS"),Pt[Lt.Notification.CantSavePluginSettings]=Mt.i18n("NOTIFICATIONS/CANT_SAVE_PLUGIN_SETTINGS"),Pt[Lt.Notification.DomainAlreadyExists]=Mt.i18n("NOTIFICATIONS/DOMAIN_ALREADY_EXISTS"),Pt[Lt.Notification.CantInstallPackage]=Mt.i18n("NOTIFICATIONS/CANT_INSTALL_PACKAGE"),Pt[Lt.Notification.CantDeletePackage]=Mt.i18n("NOTIFICATIONS/CANT_DELETE_PACKAGE"),Pt[Lt.Notification.InvalidPluginPackage]=Mt.i18n("NOTIFICATIONS/INVALID_PLUGIN_PACKAGE"),Pt[Lt.Notification.UnsupportedPluginPackage]=Mt.i18n("NOTIFICATIONS/UNSUPPORTED_PLUGIN_PACKAGE"),Pt[Lt.Notification.LicensingServerIsUnavailable]=Mt.i18n("NOTIFICATIONS/LICENSING_SERVER_IS_UNAVAILABLE"),Pt[Lt.Notification.LicensingExpired]=Mt.i18n("NOTIFICATIONS/LICENSING_EXPIRED"),Pt[Lt.Notification.LicensingBanned]=Mt.i18n("NOTIFICATIONS/LICENSING_BANNED"),Pt[Lt.Notification.DemoSendMessageError]=Mt.i18n("NOTIFICATIONS/DEMO_SEND_MESSAGE_ERROR"),Pt[Lt.Notification.AccountAlreadyExists]=Mt.i18n("NOTIFICATIONS/ACCOUNT_ALREADY_EXISTS"),Pt[Lt.Notification.MailServerError]=Mt.i18n("NOTIFICATIONS/MAIL_SERVER_ERROR"),Pt[Lt.Notification.InvalidInputArgument]=Mt.i18n("NOTIFICATIONS/INVALID_INPUT_ARGUMENT"),Pt[Lt.Notification.UnknownNotification]=Mt.i18n("NOTIFICATIONS/UNKNOWN_ERROR"),Pt[Lt.Notification.UnknownError]=Mt.i18n("NOTIFICATIONS/UNKNOWN_ERROR")},Mt.getUploadErrorDescByCode=function(e){var t="";switch(Mt.pInt(e)){case Lt.UploadErrorCode.FileIsTooBig:t=Mt.i18n("UPLOAD/ERROR_FILE_IS_TOO_BIG");break;case Lt.UploadErrorCode.FilePartiallyUploaded:t=Mt.i18n("UPLOAD/ERROR_FILE_PARTIALLY_UPLOADED");break;case Lt.UploadErrorCode.FileNoUploaded:t=Mt.i18n("UPLOAD/ERROR_NO_FILE_UPLOADED");break;case Lt.UploadErrorCode.MissingTempFolder:t=Mt.i18n("UPLOAD/ERROR_MISSING_TEMP_FOLDER");break;case Lt.UploadErrorCode.FileOnSaveingError:t=Mt.i18n("UPLOAD/ERROR_ON_SAVING_FILE");break;case Lt.UploadErrorCode.FileType:t=Mt.i18n("UPLOAD/ERROR_FILE_TYPE");break;default:t=Mt.i18n("UPLOAD/ERROR_UNKNOWN")}return t},Mt.delegateRun=function(e,t,s,i){e&&e[t]&&(i=Mt.pInt(i),0>=i?e[t].apply(e,Mt.isArray(s)?s:[]):r.delay(function(){e[t].apply(e,Mt.isArray(s)?s:[])},i))},Mt.killCtrlAandS=function(t){if(t=t||e.event,t&&t.ctrlKey&&!t.shiftKey&&!t.altKey){var s=t.target||t.srcElement,i=t.keyCode||t.which;if(i===Lt.EventKeyCode.S)return void t.preventDefault();if(s&&s.tagName&&s.tagName.match(/INPUT|TEXTAREA/i))return;i===Lt.EventKeyCode.A&&(e.getSelection?e.getSelection().removeAllRanges():e.document.selection&&e.document.selection.clear&&e.document.selection.clear(),t.preventDefault())}},Mt.createCommand=function(e,t,i){var o=t?function(){return o.canExecute&&o.canExecute()&&t.apply(e,Array.prototype.slice.call(arguments)),!1}:function(){};return o.enabled=s.observable(!0),i=Mt.isUnd(i)?!0:i,o.canExecute=s.computed(Mt.isFunc(i)?function(){return o.enabled()&&i.call(e)}:function(){return o.enabled()&&!!i}),o},Mt.initDataConstructorBySettings=function(t){t.editorDefaultType=s.observable(Lt.EditorDefaultType.Html),t.showImages=s.observable(!1),t.interfaceAnimation=s.observable(Lt.InterfaceAnimation.Full),t.contactsAutosave=s.observable(!1),Ot.sAnimationType=Lt.InterfaceAnimation.Full,t.capaThemes=s.observable(!1),t.allowLanguagesOnSettings=s.observable(!0),t.allowLanguagesOnLogin=s.observable(!0),t.useLocalProxyForExternalImages=s.observable(!1),t.desktopNotifications=s.observable(!1),t.useThreads=s.observable(!0),t.replySameFolder=s.observable(!0),t.useCheckboxesInList=s.observable(!0),t.layout=s.observable(Lt.Layout.SidePreview),t.usePreviewPane=s.computed(function(){return Lt.Layout.NoPreview!==t.layout()}),t.interfaceAnimation.subscribe(function(e){if(Ot.bMobileDevice||e===Lt.InterfaceAnimation.None)Bt.removeClass("rl-anim rl-anim-full").addClass("no-rl-anim"),Ot.sAnimationType=Lt.InterfaceAnimation.None;else switch(e){case Lt.InterfaceAnimation.Full:Bt.removeClass("no-rl-anim").addClass("rl-anim rl-anim-full"),Ot.sAnimationType=e;break;case Lt.InterfaceAnimation.Normal:Bt.removeClass("no-rl-anim rl-anim-full").addClass("rl-anim"),Ot.sAnimationType=e
+}}),t.interfaceAnimation.valueHasMutated(),t.desktopNotificationsPermisions=s.computed(function(){t.desktopNotifications();var s=Lt.DesktopNotifications.NotSupported;if(qt&&qt.permission)switch(qt.permission.toLowerCase()){case"granted":s=Lt.DesktopNotifications.Allowed;break;case"denied":s=Lt.DesktopNotifications.Denied;break;case"default":s=Lt.DesktopNotifications.NotAllowed}else e.webkitNotifications&&e.webkitNotifications.checkPermission&&(s=e.webkitNotifications.checkPermission());return s}),t.useDesktopNotifications=s.computed({read:function(){return t.desktopNotifications()&&Lt.DesktopNotifications.Allowed===t.desktopNotificationsPermisions()},write:function(e){if(e){var s=t.desktopNotificationsPermisions();Lt.DesktopNotifications.Allowed===s?t.desktopNotifications(!0):Lt.DesktopNotifications.NotAllowed===s?qt.requestPermission(function(){t.desktopNotifications.valueHasMutated(),Lt.DesktopNotifications.Allowed===t.desktopNotificationsPermisions()?t.desktopNotifications()?t.desktopNotifications.valueHasMutated():t.desktopNotifications(!0):t.desktopNotifications()?t.desktopNotifications(!1):t.desktopNotifications.valueHasMutated()}):t.desktopNotifications(!1)}else t.desktopNotifications(!1)}}),t.language=s.observable(""),t.languages=s.observableArray([]),t.mainLanguage=s.computed({read:t.language,write:function(e){e!==t.language()?-1=t.diff(s,"hours")?i:t.format("L")===s.format("L")?Mt.i18n("MESSAGE_LIST/TODAY_AT",{TIME:s.format("LT")}):t.clone().subtract("days",1).format("L")===s.format("L")?Mt.i18n("MESSAGE_LIST/YESTERDAY_AT",{TIME:s.format("LT")}):s.format(t.year()===s.year()?"D MMM.":"LL")},e)},Mt.isFolderExpanded=function(e){var t=jt.local().get(Lt.ClientSideKeyName.ExpandedFolders);return r.isArray(t)&&-1!==r.indexOf(t,e)},Mt.setExpandedFolder=function(e,t){var s=jt.local().get(Lt.ClientSideKeyName.ExpandedFolders);r.isArray(s)||(s=[]),t?(s.push(e),s=r.uniq(s)):s=r.without(s,e),jt.local().set(Lt.ClientSideKeyName.ExpandedFolders,s)},Mt.initLayoutResizer=function(e,s,i){var o=60,n=155,a=t(e),r=t(s),l=jt.local().get(i)||null,c=function(e){e&&(a.css({width:""+e+"px"}),r.css({left:""+e+"px"}))},u=function(e){if(e)a.resizable("disable"),c(o);else{a.resizable("enable");var t=Mt.pInt(jt.local().get(i))||n;c(t>n?t:n)}},d=function(e,t){t&&t.size&&t.size.width&&(jt.local().set(i,t.size.width),r.css({left:""+t.size.width+"px"}))};null!==l&&c(l>n?l:n),a.resizable({helper:"ui-resizable-helper",minWidth:n,maxWidth:350,handles:"e",stop:d}),jt.sub("left-panel.off",function(){u(!0)}),jt.sub("left-panel.on",function(){u(!1)})},Mt.initBlockquoteSwitcher=function(e){if(e){var s=t("blockquote:not(.rl-bq-switcher)",e).filter(function(){return 0===t(this).parent().closest("blockquote",e).length});s&&0100)&&(e.addClass("rl-bq-switcher hidden-bq"),t('').insertBefore(e).click(function(){e.toggleClass("hidden-bq"),Mt.windowResize()}).after("
").before("
"))})}},Mt.removeBlockquoteSwitcher=function(e){e&&(t(e).find("blockquote.rl-bq-switcher").each(function(){t(this).removeClass("rl-bq-switcher hidden-bq")}),t(e).find(".rlBlockquoteSwitcher").each(function(){t(this).remove()}))},Mt.toggleMessageBlockquote=function(e){e&&e.find(".rlBlockquoteSwitcher").click()},Mt.extendAsViewModel=function(e,t,s){t&&(s||(s=b),t.__name=e,Dt.regViewModelHook(e,t),r.extend(t.prototype,s.prototype))},Mt.addSettingsViewModel=function(e,t,s,i,o){e.__rlSettingsData={Label:s,Template:t,Route:i,IsDefault:!!o},_t.settings.push(e)},Mt.removeSettingsViewModel=function(e){_t["settings-removed"].push(e)},Mt.disableSettingsViewModel=function(e){_t["settings-disabled"].push(e)},Mt.convertThemeName=function(e){return"@custom"===e.substr(-7)&&(e=Mt.trim(e.substring(0,e.length-7))),Mt.trim(e.replace(/[^a-zA-Z]+/g," ").replace(/([A-Z])/g," $1").replace(/[\s]+/g," "))},Mt.quoteName=function(e){return e.replace(/["]/g,'\\"')},Mt.microtime=function(){return(new Date).getTime()},Mt.convertLangName=function(e,t){return Mt.i18n("LANGS_NAMES"+(!0===t?"_EN":"")+"/LANG_"+e.toUpperCase().replace(/[^a-zA-Z0-9]+/,"_"),null,e)},Mt.fakeMd5=function(e){var t="",s="0123456789abcdefghijklmnopqrstuvwxyz";for(e=Mt.isUnd(e)?32:Mt.pInt(e);t.length>>32-t}function s(e,t){var s,i,o,n,a;return o=2147483648&e,n=2147483648&t,s=1073741824&e,i=1073741824&t,a=(1073741823&e)+(1073741823&t),s&i?2147483648^a^o^n:s|i?1073741824&a?3221225472^a^o^n:1073741824^a^o^n:a^o^n}function i(e,t,s){return e&t|~e&s}function o(e,t,s){return e&s|t&~s}function n(e,t,s){return e^t^s}function a(e,t,s){return t^(e|~s)}function r(e,o,n,a,r,l,c){return e=s(e,s(s(i(o,n,a),r),c)),s(t(e,l),o)}function l(e,i,n,a,r,l,c){return e=s(e,s(s(o(i,n,a),r),c)),s(t(e,l),i)}function c(e,i,o,a,r,l,c){return e=s(e,s(s(n(i,o,a),r),c)),s(t(e,l),i)}function u(e,i,o,n,r,l,c){return e=s(e,s(s(a(i,o,n),r),c)),s(t(e,l),i)}function d(e){for(var t,s=e.length,i=s+8,o=(i-i%64)/64,n=16*(o+1),a=Array(n-1),r=0,l=0;s>l;)t=(l-l%4)/4,r=l%4*8,a[t]=a[t]|e.charCodeAt(l)<>>29,a}function h(e){var t,s,i="",o="";for(s=0;3>=s;s++)t=e>>>8*s&255,o="0"+t.toString(16),i+=o.substr(o.length-2,2);return i}function p(e){e=e.replace(/rn/g,"n");for(var t="",s=0;si?t+=String.fromCharCode(i):i>127&&2048>i?(t+=String.fromCharCode(i>>6|192),t+=String.fromCharCode(63&i|128)):(t+=String.fromCharCode(i>>12|224),t+=String.fromCharCode(i>>6&63|128),t+=String.fromCharCode(63&i|128))}return t}var m,g,f,b,y,S,v,C,w,T=Array(),F=7,A=12,E=17,N=22,R=5,I=9,L=14,P=20,M=4,D=11,k=16,O=23,_=6,U=10,x=15,V=21;for(e=p(e),T=d(e),S=1732584193,v=4023233417,C=2562383102,w=271733878,m=0;m /g,">").replace(/")},Mt.draggeblePlace=function(){return t(' ').appendTo("#rl-hidden")},Mt.defautOptionsAfterRender=function(e,s){s&&!Mt.isUnd(s.disabled)&&e&&t(e).toggleClass("disabled",s.disabled).prop("disabled",s.disabled)},Mt.windowPopupKnockout=function(s,i,o,n){var a=null,r=e.open(""),l="__OpenerApplyBindingsUid"+Mt.fakeMd5()+"__",c=t("#"+i);e[l]=function(){if(r&&r.document.body&&c&&c[0]){var i=t(r.document.body);t("#rl-content",i).html(c.html()),t("html",r.document).addClass("external "+t("html").attr("class")),Mt.i18nToNode(i),S.prototype.applyExternal(s,t("#rl-content",i)[0]),e[l]=null,n(r)}},r.document.open(),r.document.write(''+Mt.encodeHtml(o)+' '),r.document.close(),a=r.document.createElement("script"),a.type="text/javascript",a.innerHTML="if(window&&window.opener&&window.opener['"+l+"']){window.opener['"+l+"']();window.opener['"+l+"']=null}",r.document.getElementsByTagName("head")[0].appendChild(a)},Mt.settingsSaveHelperFunction=function(e,t,s,i){return s=s||null,i=Mt.isUnd(i)?1e3:Mt.pInt(i),function(o,n,a,l,c){t.call(s,n&&n.Result?Lt.SaveSettingsStep.TrueResult:Lt.SaveSettingsStep.FalseResult),e&&e.call(s,o,n,a,l,c),r.delay(function(){t.call(s,Lt.SaveSettingsStep.Idle)},i)}},Mt.settingsSaveHelperSimpleFunction=function(e,t){return Mt.settingsSaveHelperFunction(null,e,t,1e3)},Mt.$div=t(""),Mt.htmlToPlain=function(e){var s=0,i=0,o=0,n=0,a=0,r="",l=function(e){for(var t=100,s="",i="",o=e,n=0,a=0;o.length>t;)i=o.substring(0,t),n=i.lastIndexOf(" "),a=i.lastIndexOf("\n"),-1!==a&&(n=a),-1===n&&(n=t),s+=i.substring(0,n)+"\n",o=o.substring(n+1);return s+o},c=function(e){return e=l(t.trim(e)),e="> "+e.replace(/\n/gm,"\n> "),e.replace(/(^|\n)([> ]+)/gm,function(){return arguments&&2]*>([\s\S\r\n]*)<\/div>/gim,u),e="\n"+t.trim(e)+"\n"),e}return""},d=function(){return arguments&&1 "):""},h=function(){return arguments&&1 /g,">"):""},p=function(){return arguments&&1]*>([\s\S\r\n]*)<\/pre>/gim,d).replace(/[\s]+/gm," ").replace(/((?:href|data)\s?=\s?)("[^"]+?"|'[^']+?')/gim,h).replace(/
]*>/gim,"\n").replace(/<\/h[\d]>/gi,"\n").replace(/<\/p>/gi,"\n\n").replace(/<\/li>/gi,"\n").replace(/<\/td>/gi,"\n").replace(/<\/tr>/gi,"\n").replace(/
]*>/gim,"\n_______________________________\n\n").replace(/]*>([\s\S\r\n]*)<\/div>/gim,u).replace(/]*>/gim,"\n__bq__start__\n").replace(/<\/blockquote>/gim,"\n__bq__end__\n").replace(/]*>([\s\S\r\n]*?)<\/a>/gim,p).replace(/<\/div>/gi,"\n").replace(/ /gi," ").replace(/"/gi,'"').replace(/<[^>]*>/gm,""),r=Mt.$div.html(r).text(),r=r.replace(/\n[ \t]+/gm,"\n").replace(/[\n]{3,}/gm,"\n\n").replace(/>/gi,">").replace(/</gi,"<").replace(/&/gi,"&"),s=0,a=100;a>0&&(a--,i=r.indexOf("__bq__start__",s),i>-1);)o=r.indexOf("__bq__start__",i+5),n=r.indexOf("__bq__end__",i+5),(-1===o||o>n)&&n>i?(r=r.substring(0,i)+c(r.substring(i+13,n))+r.substring(n+11),s=0):s=o>-1&&n>o?o-1:0;return r=r.replace(/__bq__start__/gm,"").replace(/__bq__end__/gm,"")},Mt.plainToHtml=function(e,t){e=e.toString().replace(/\r/g,"");var s=!1,i=!0,o=!0,n=[],a="",r=0,l=e.split("\n");do{for(i=!1,n=[],r=0;r"===a.substr(0,1),o&&!s?(i=!0,s=!0,n.push("~~~blockquote~~~"),n.push(a.substr(1))):!o&&s?(s=!1,n.push("~~~/blockquote~~~"),n.push(a)):n.push(o&&s?a.substr(1):a);s&&(s=!1,n.push("~~~/blockquote~~~")),l=n}while(i);return e=l.join("\n"),e=e.replace(/&/g,"&").replace(/>/g,">").replace(/").replace(/[\s]*~~~\/blockquote~~~/g,"
").replace(/[\-_~]{10,}/g,"
").replace(/\n/g,"
"),t?Mt.linkify(e):e},e.rainloop_Utils_htmlToPlain=Mt.htmlToPlain,e.rainloop_Utils_plainToHtml=Mt.plainToHtml,Mt.linkify=function(e){return t.fn&&t.fn.linkify&&(e=Mt.$div.html(e.replace(/&/gi,"amp_amp_12345_amp_amp")).linkify().find(".linkified").removeClass("linkified").end().html().replace(/amp_amp_12345_amp_amp/g,"&")),e},Mt.resizeAndCrop=function(t,s,i){var o=new e.Image;o.onload=function(){var e=[0,0],t=document.createElement("canvas"),o=t.getContext("2d");t.width=s,t.height=s,e=this.width>this.height?[this.width-this.height,0]:[0,this.height-this.width],o.fillStyle="#fff",o.fillRect(0,0,s,s),o.drawImage(this,e[0]/2,e[1]/2,this.width-e[0],this.height-e[1],0,0,s,s),i(t.toDataURL("image/jpeg"))},o.src=t},Mt.computedPagenatorHelper=function(e,t){return function(){var s=0,i=0,o=2,n=[],a=e(),r=t(),l=function(e,t,s){var i={current:e===a,name:Mt.isUnd(s)?e.toString():s.toString(),custom:Mt.isUnd(s)?!1:!0,title:Mt.isUnd(s)?"":e.toString(),value:e.toString()};(Mt.isUnd(t)?0:!t)?n.unshift(i):n.push(i)};if(r>1||r>0&&a>r){for(a>r?(l(r),s=r,i=r):((3>=a||a>=r-2)&&(o+=2),l(a),s=a,i=a);o>0;)if(s-=1,i+=1,s>0&&(l(s,!1),o--),r>=i)l(i,!0),o--;else if(0>=s)break;3===s?l(2,!1):s>3&&l(Math.round((s-1)/2),!1,"..."),r-2===i?l(r-1,!0):r-2>i&&l(Math.round((r+i)/2),!0,"..."),s>1&&l(1,!1),r>i&&l(r,!0)}return n}},Mt.selectElement=function(t){if(e.getSelection){var s=e.getSelection();s.removeAllRanges();var i=document.createRange();i.selectNodeContents(t),s.addRange(i)}else if(document.selection){var o=document.body.createTextRange();o.moveToElementText(t),o.select()}},Mt.disableKeyFilter=function(){e.key&&(c.filter=function(){return jt.data().useKeyboardShortcuts()})},Mt.restoreKeyFilter=function(){e.key&&(c.filter=function(e){if(jt.data().useKeyboardShortcuts()){var t=e.target||e.srcElement,s=t?t.tagName:"";return s=s.toUpperCase(),!("INPUT"===s||"SELECT"===s||"TEXTAREA"===s||t&&"DIV"===s&&"editorHtmlArea"===t.className&&t.contentEditable)}return!1})},Mt.detectDropdownVisibility=r.debounce(function(){Ot.dropdownVisibility(!!r.find(Ut,function(e){return e.hasClass("open")}))},50),Mt.triggerAutocompleteInputChange=function(e){var s=function(){t(".checkAutocomplete").trigger("change")};e?r.delay(s,100):s()},kt={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",urlsafe_encode:function(e){return kt.encode(e).replace(/[+]/g,"-").replace(/[\/]/g,"_").replace(/[=]/g,".")},encode:function(e){var t,s,i,o,n,a,r,l="",c=0;for(e=kt._utf8_encode(e);c>2,n=(3&t)<<4|s>>4,a=(15&s)<<2|i>>6,r=63&i,isNaN(s)?a=r=64:isNaN(i)&&(r=64),l=l+this._keyStr.charAt(o)+this._keyStr.charAt(n)+this._keyStr.charAt(a)+this._keyStr.charAt(r);return l},decode:function(e){var t,s,i,o,n,a,r,l="",c=0;for(e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");c>4,s=(15&n)<<4|a>>2,i=(3&a)<<6|r,l+=String.fromCharCode(t),64!==a&&(l+=String.fromCharCode(s)),64!==r&&(l+=String.fromCharCode(i));return kt._utf8_decode(l)},_utf8_encode:function(e){e=e.replace(/\r\n/g,"\n");for(var t="",s=0,i=e.length,o=0;i>s;s++)o=e.charCodeAt(s),128>o?t+=String.fromCharCode(o):o>127&&2048>o?(t+=String.fromCharCode(o>>6|192),t+=String.fromCharCode(63&o|128)):(t+=String.fromCharCode(o>>12|224),t+=String.fromCharCode(o>>6&63|128),t+=String.fromCharCode(63&o|128));return t},_utf8_decode:function(e){for(var t="",s=0,i=0,o=0,n=0;si?(t+=String.fromCharCode(i),s++):i>191&&224>i?(o=e.charCodeAt(s+1),t+=String.fromCharCode((31&i)<<6|63&o),s+=2):(o=e.charCodeAt(s+1),n=e.charCodeAt(s+2),t+=String.fromCharCode((15&i)<<12|(63&o)<<6|63&n),s+=3);return t}},s.bindingHandlers.tooltip={init:function(e,i){if(!Ot.bMobileDevice){var o=t(e),n=o.data("tooltip-class")||"",a=o.data("tooltip-placement")||"top";o.tooltip({delay:{show:500,hide:100},html:!0,container:"body",placement:a,trigger:"hover",title:function(){return o.is(".disabled")||Ot.dropdownVisibility()?"":''+Mt.i18n(s.utils.unwrapObservable(i()))+""}}).click(function(){o.tooltip("hide")}),Ot.tooltipTrigger.subscribe(function(){o.tooltip("hide")})}}},s.bindingHandlers.tooltip2={init:function(e,s){var i=t(e),o=i.data("tooltip-class")||"",n=i.data("tooltip-placement")||"top";i.tooltip({delay:{show:500,hide:100},html:!0,container:"body",placement:n,title:function(){return i.is(".disabled")||Ot.dropdownVisibility()?"":''+s()()+""}}).click(function(){i.tooltip("hide")}),Ot.tooltipTrigger.subscribe(function(){i.tooltip("hide")})}},s.bindingHandlers.tooltip3={init:function(e){var s=t(e);s.tooltip({container:"body",trigger:"hover manual",title:function(){return s.data("tooltip3-data")||""}}),Kt.click(function(){s.tooltip("hide")}),Ot.tooltipTrigger.subscribe(function(){s.tooltip("hide")})},update:function(e,i){var o=s.utils.unwrapObservable(i());""===o?t(e).data("tooltip3-data","").tooltip("hide"):t(e).data("tooltip3-data",o).tooltip("show")}},s.bindingHandlers.registrateBootstrapDropdown={init:function(e){Ut.push(t(e))}},s.bindingHandlers.openDropdownTrigger={update:function(e,i){if(s.utils.unwrapObservable(i())){var o=t(e);o.hasClass("open")||(o.find(".dropdown-toggle").dropdown("toggle"),Mt.detectDropdownVisibility()),i()(!1)}}},s.bindingHandlers.dropdownCloser={init:function(e){t(e).closest(".dropdown").on("click",".e-item",function(){t(e).dropdown("toggle")})}},s.bindingHandlers.popover={init:function(e,i){t(e).popover(s.utils.unwrapObservable(i()))}},s.bindingHandlers.csstext={init:function(e,i){e&&e.styleSheet&&!Mt.isUnd(e.styleSheet.cssText)?e.styleSheet.cssText=s.utils.unwrapObservable(i()):t(e).text(s.utils.unwrapObservable(i()))},update:function(e,i){e&&e.styleSheet&&!Mt.isUnd(e.styleSheet.cssText)?e.styleSheet.cssText=s.utils.unwrapObservable(i()):t(e).text(s.utils.unwrapObservable(i()))}},s.bindingHandlers.resizecrop={init:function(e){t(e).addClass("resizecrop").resizecrop({width:"100",height:"100",wrapperCSS:{"border-radius":"10px"}})},update:function(e,s){s()(),t(e).resizecrop({width:"100",height:"100"})}},s.bindingHandlers.onEnter={init:function(s,i,o,n){t(s).on("keypress",function(o){o&&13===e.parseInt(o.keyCode,10)&&(t(s).trigger("change"),i().call(n))})}},s.bindingHandlers.onEsc={init:function(s,i,o,n){t(s).on("keypress",function(o){o&&27===e.parseInt(o.keyCode,10)&&(t(s).trigger("change"),i().call(n))})}},s.bindingHandlers.clickOnTrue={update:function(e,i){s.utils.unwrapObservable(i())&&t(e).click()}},s.bindingHandlers.modal={init:function(e,i){t(e).toggleClass("fade",!Ot.bMobileDevice).modal({keyboard:!1,show:s.utils.unwrapObservable(i())}).on("shown",function(){Mt.windowResize()}).find(".close").click(function(){i()(!1)})},update:function(e,i){t(e).modal(s.utils.unwrapObservable(i())?"show":"hide")}},s.bindingHandlers.i18nInit={init:function(e){Mt.i18nToNode(e)}},s.bindingHandlers.i18nUpdate={update:function(e,t){s.utils.unwrapObservable(t()),Mt.i18nToNode(e)}},s.bindingHandlers.link={update:function(e,i){t(e).attr("href",s.utils.unwrapObservable(i()))}},s.bindingHandlers.title={update:function(e,i){t(e).attr("title",s.utils.unwrapObservable(i()))}},s.bindingHandlers.textF={init:function(e,i){t(e).text(s.utils.unwrapObservable(i()))}},s.bindingHandlers.initDom={init:function(e,t){t()(e)}},s.bindingHandlers.initResizeTrigger={init:function(e,i){var o=s.utils.unwrapObservable(i());t(e).css({height:o[1],"min-height":o[1]})},update:function(e,i){var o=s.utils.unwrapObservable(i()),n=Mt.pInt(o[1]),a=0,r=t(e).offset().top;r>0&&(r+=Mt.pInt(o[2]),a=Gt.height()-r,a>n&&(n=a),t(e).css({height:n,"min-height":n}))}},s.bindingHandlers.appendDom={update:function(e,i){t(e).hide().empty().append(s.utils.unwrapObservable(i())).show()}},s.bindingHandlers.draggable={init:function(i,o,n){if(!Ot.bMobileDevice){var a=100,r=3,l=n(),c=l&&l.droppableSelector?l.droppableSelector:"",u={distance:20,handle:".dragHandle",cursorAt:{top:22,left:3},refreshPositions:!0,scroll:!0};c&&(u.drag=function(s){t(c).each(function(){var i=null,o=null,n=t(this),l=n.offset(),c=l.top+n.height();e.clearInterval(n.data("timerScroll")),n.data("timerScroll",!1),s.pageX>=l.left&&s.pageX<=l.left+n.width()&&(s.pageY>=c-a&&s.pageY<=c&&(i=function(){n.scrollTop(n.scrollTop()+r),Mt.windowResize()},n.data("timerScroll",e.setInterval(i,10)),i()),s.pageY>=l.top&&s.pageY<=l.top+a&&(o=function(){n.scrollTop(n.scrollTop()-r),Mt.windowResize()},n.data("timerScroll",e.setInterval(o,10)),o()))})},u.stop=function(){t(c).each(function(){e.clearInterval(t(this).data("timerScroll")),t(this).data("timerScroll",!1)})}),u.helper=function(e){return o()(e&&e.target?s.dataFor(e.target):null)},t(i).draggable(u).on("mousedown",function(){Mt.removeInFocus()})}}},s.bindingHandlers.droppable={init:function(e,s,i){if(!Ot.bMobileDevice){var o=s(),n=i(),a=n&&n.droppableOver?n.droppableOver:null,r=n&&n.droppableOut?n.droppableOut:null,l={tolerance:"pointer",hoverClass:"droppableHover"};o&&(l.drop=function(e,t){o(e,t)},a&&(l.over=function(e,t){a(e,t)}),r&&(l.out=function(e,t){r(e,t)}),t(e).droppable(l))}}},s.bindingHandlers.nano={init:function(e){Ot.bDisableNanoScroll||t(e).addClass("nano").nanoScroller({iOSNativeScrolling:!1,preventPageScrolling:!0})}},s.bindingHandlers.saveTrigger={init:function(e){var s=t(e);s.data("save-trigger-type",s.is("input[type=text],input[type=email],input[type=password],select,textarea")?"input":"custom"),"custom"===s.data("save-trigger-type")?s.append(' ').addClass("settings-saved-trigger"):s.addClass("settings-saved-trigger-input")},update:function(e,i){var o=s.utils.unwrapObservable(i()),n=t(e);if("custom"===n.data("save-trigger-type"))switch(o.toString()){case"1":n.find(".animated,.error").hide().removeClass("visible").end().find(".success").show().addClass("visible");break;case"0":n.find(".animated,.success").hide().removeClass("visible").end().find(".error").show().addClass("visible");break;case"-2":n.find(".error,.success").hide().removeClass("visible").end().find(".animated").show().addClass("visible");break;default:n.find(".animated").hide().end().find(".error,.success").removeClass("visible")}else switch(o.toString()){case"1":n.addClass("success").removeClass("error");break;case"0":n.addClass("error").removeClass("success");break;case"-2":break;default:n.removeClass("error success")}}},s.bindingHandlers.emailsTags={init:function(e,s){var i=t(e),o=s(),n=function(e){o&&o.focusTrigger&&o.focusTrigger(e)};i.inputosaurus({parseOnBlur:!0,allowDragAndDrop:!0,focusCallback:n,inputDelimiters:[",",";"],autoCompleteSource:function(e,t){jt.getAutocomplete(e.term,function(e){t(r.map(e,function(e){return e.toLine(!1)}))})},parseHook:function(e){return r.map(e,function(e){var t=Mt.trim(e),s=null;return""!==t?(s=new v,s.mailsoParse(t),s.clearDuplicateName(),[s.toLine(!1),s]):[t,null]})},change:r.bind(function(e){i.data("EmailsTagsValue",e.target.value),o(e.target.value)},this)})},update:function(e,i,o){var n=t(e),a=o(),r=a.emailsTagsFilter||null,l=s.utils.unwrapObservable(i());n.data("EmailsTagsValue")!==l&&(n.val(l),n.data("EmailsTagsValue",l),n.inputosaurus("refresh")),r&&s.utils.unwrapObservable(r)&&n.inputosaurus("focus")}},s.bindingHandlers.contactTags={init:function(e,s){var i=t(e),o=s(),n=function(e){o&&o.focusTrigger&&o.focusTrigger(e)};i.inputosaurus({parseOnBlur:!0,allowDragAndDrop:!1,focusCallback:n,inputDelimiters:[",",";"],outputDelimiter:",",autoCompleteSource:function(e,t){jt.getContactTagsAutocomplete(e.term,function(e){t(r.map(e,function(e){return e.toLine(!1)}))})},parseHook:function(e){return r.map(e,function(e){var t=Mt.trim(e),s=null;return""!==t?(s=new T,s.name(t),[s.toLine(!1),s]):[t,null]})},change:r.bind(function(e){i.data("ContactTagsValue",e.target.value),o(e.target.value)},this)})},update:function(e,i,o){var n=t(e),a=o(),r=a.contactTagsFilter||null,l=s.utils.unwrapObservable(i());n.data("ContactTagsValue")!==l&&(n.val(l),n.data("ContactTagsValue",l),n.inputosaurus("refresh")),r&&s.utils.unwrapObservable(r)&&n.inputosaurus("focus")}},s.bindingHandlers.command={init:function(e,i,o,n){var a=t(e),r=i();if(!r||!r.enabled||!r.canExecute)throw new Error("You are not using command function");a.addClass("command"),s.bindingHandlers[a.is("form")?"submit":"click"].init.apply(n,arguments)},update:function(e,s){var i=!0,o=t(e),n=s();i=n.enabled(),o.toggleClass("command-not-enabled",!i),i&&(i=n.canExecute(),o.toggleClass("command-can-not-be-execute",!i)),o.toggleClass("command-disabled disable disabled",!i).toggleClass("no-disabled",!!i),(o.is("input")||o.is("button"))&&o.prop("disabled",!i)}},s.extenders.trimmer=function(e){var t=s.computed({read:e,write:function(t){e(Mt.trim(t.toString()))},owner:this});return t(e()),t},s.extenders.posInterer=function(e,t){var i=s.computed({read:e,write:function(s){var i=Mt.pInt(s.toString(),t);0>=i&&(i=t),i===e()&&""+i!=""+s&&e(i+1),e(i)}});return i(e()),i},s.extenders.reversible=function(e){var t=e();return e.commit=function(){t=e()},e.reverse=function(){e(t)},e.commitedValue=function(){return t},e},s.extenders.toggleSubscribe=function(e,t){return e.subscribe(t[1],t[0],"beforeChange"),e.subscribe(t[2],t[0]),e},s.extenders.falseTimeout=function(t,s){return t.iTimeout=0,t.subscribe(function(i){i&&(e.clearTimeout(t.iTimeout),t.iTimeout=e.setTimeout(function(){t(!1),t.iTimeout=0},Mt.pInt(s)))}),t},s.observable.fn.validateNone=function(){return this.hasError=s.observable(!1),this},s.observable.fn.validateEmail=function(){return this.hasError=s.observable(!1),this.subscribe(function(e){e=Mt.trim(e),this.hasError(""!==e&&!/^[^@\s]+@[^@\s]+$/.test(e))},this),this.valueHasMutated(),this},s.observable.fn.validateSimpleEmail=function(){return this.hasError=s.observable(!1),this.subscribe(function(e){e=Mt.trim(e),this.hasError(""!==e&&!/^.+@.+$/.test(e))},this),this.valueHasMutated(),this},s.observable.fn.validateFunc=function(e){return this.hasFuncError=s.observable(!1),Mt.isFunc(e)&&(this.subscribe(function(t){this.hasFuncError(!e(t))},this),this.valueHasMutated()),this},u.prototype.root=function(){return this.sBase},u.prototype.attachmentDownload=function(e){return this.sServer+"/Raw/"+this.sSpecSuffix+"/Download/"+e},u.prototype.attachmentPreview=function(e){return this.sServer+"/Raw/"+this.sSpecSuffix+"/View/"+e},u.prototype.attachmentPreviewAsPlain=function(e){return this.sServer+"/Raw/"+this.sSpecSuffix+"/ViewAsPlain/"+e},u.prototype.upload=function(){return this.sServer+"/Upload/"+this.sSpecSuffix+"/"},u.prototype.uploadContacts=function(){return this.sServer+"/UploadContacts/"+this.sSpecSuffix+"/"},u.prototype.uploadBackground=function(){return this.sServer+"/UploadBackground/"+this.sSpecSuffix+"/"},u.prototype.append=function(){return this.sServer+"/Append/"+this.sSpecSuffix+"/"},u.prototype.change=function(t){return this.sServer+"/Change/"+this.sSpecSuffix+"/"+e.encodeURIComponent(t)+"/"},u.prototype.ajax=function(e){return this.sServer+"/Ajax/"+this.sSpecSuffix+"/"+e},u.prototype.messageViewLink=function(e){return this.sServer+"/Raw/"+this.sSpecSuffix+"/ViewAsPlain/"+e},u.prototype.messageDownloadLink=function(e){return this.sServer+"/Raw/"+this.sSpecSuffix+"/Download/"+e},u.prototype.avatarLink=function(t){return this.sServer+"/Raw/0/Avatar/"+e.encodeURIComponent(t)+"/"},u.prototype.inbox=function(){return this.sBase+"mailbox/Inbox"},u.prototype.messagePreview=function(){return this.sBase+"mailbox/message-preview"},u.prototype.settings=function(e){var t=this.sBase+"settings";return Mt.isUnd(e)||""===e||(t+="/"+e),t},u.prototype.admin=function(e){var t=this.sBase;switch(e){case"AdminDomains":t+="domains";break;case"AdminSecurity":t+="security";break;case"AdminLicensing":t+="licensing"}return t},u.prototype.mailBox=function(e,t,s){t=Mt.isNormal(t)?Mt.pInt(t):1,s=Mt.pString(s);var i=this.sBase+"mailbox/";return""!==e&&(i+=encodeURI(e)),t>1&&(i=i.replace(/[\/]+$/,""),i+="/p"+t),""!==s&&(i=i.replace(/[\/]+$/,""),i+="/"+encodeURI(s)),i},u.prototype.phpInfo=function(){return this.sServer+"Info"},u.prototype.langLink=function(e){return this.sServer+"/Lang/0/"+encodeURI(e)+"/"+this.sVersion+"/"},u.prototype.exportContactsVcf=function(){return this.sServer+"/Raw/"+this.sSpecSuffix+"/ContactsVcf/"},u.prototype.exportContactsCsv=function(){return this.sServer+"/Raw/"+this.sSpecSuffix+"/ContactsCsv/"},u.prototype.emptyContactPic=function(){return this.sStaticPrefix+"css/images/empty-contact.png"},u.prototype.sound=function(e){return this.sStaticPrefix+"sounds/"+e},u.prototype.themePreviewLink=function(e){var t="rainloop/v/"+this.sVersion+"/";return"@custom"===e.substr(-7)&&(e=Mt.trim(e.substring(0,e.length-7)),t=""),t+"themes/"+encodeURI(e)+"/images/preview.png"},u.prototype.notificationMailIcon=function(){return this.sStaticPrefix+"css/images/icom-message-notification.png"},u.prototype.openPgpJs=function(){return this.sStaticPrefix+"js/openpgp.min.js"},u.prototype.socialGoogle=function(){return this.sServer+"SocialGoogle"+(""!==this.sSpecSuffix?"/"+this.sSpecSuffix+"/":"")},u.prototype.socialTwitter=function(){return this.sServer+"SocialTwitter"+(""!==this.sSpecSuffix?"/"+this.sSpecSuffix+"/":"")},u.prototype.socialFacebook=function(){return this.sServer+"SocialFacebook"+(""!==this.sSpecSuffix?"/"+this.sSpecSuffix+"/":"")},Dt.oViewModelsHooks={},Dt.oSimpleHooks={},Dt.regViewModelHook=function(e,t){t&&(t.__hookName=e)
+},Dt.addHook=function(e,t){Mt.isFunc(t)&&(Mt.isArray(Dt.oSimpleHooks[e])||(Dt.oSimpleHooks[e]=[]),Dt.oSimpleHooks[e].push(t))},Dt.runHook=function(e,t){Mt.isArray(Dt.oSimpleHooks[e])&&(t=t||[],r.each(Dt.oSimpleHooks[e],function(e){e.apply(null,t)}))},Dt.mainSettingsGet=function(e){return jt?jt.settingsGet(e):null},Dt.remoteRequest=function(e,t,s,i,o,n){jt&&jt.remote().defaultRequest(e,t,s,i,o,n)},Dt.settingsGet=function(e,t){var s=Dt.mainSettingsGet("Plugins");return s=s&&Mt.isUnd(s[e])?null:s[e],s?Mt.isUnd(s[t])?null:s[t]:null},d.prototype.blurTrigger=function(){if(this.fOnBlur){var t=this;e.clearTimeout(t.iBlurTimer),t.iBlurTimer=e.setTimeout(function(){t.fOnBlur()},200)}},d.prototype.focusTrigger=function(){this.fOnBlur&&e.clearTimeout(this.iBlurTimer)},d.prototype.isHtml=function(){return this.editor?"wysiwyg"===this.editor.mode:!1},d.prototype.checkDirty=function(){return this.editor?this.editor.checkDirty():!1},d.prototype.resetDirty=function(){this.editor&&this.editor.resetDirty()},d.prototype.getData=function(e){return this.editor?"plain"===this.editor.mode&&this.editor.plugins.plain&&this.editor.__plain?this.editor.__plain.getRawData():e?''+this.editor.getData()+"":this.editor.getData():""},d.prototype.modeToggle=function(e){this.editor&&(e?"plain"===this.editor.mode&&this.editor.setMode("wysiwyg"):"wysiwyg"===this.editor.mode&&this.editor.setMode("plain"),this.resize())},d.prototype.setHtml=function(e,t){this.editor&&(this.modeToggle(!0),this.editor.setData(e),t&&this.focus())},d.prototype.setPlain=function(e,t){if(this.editor){if(this.modeToggle(!1),"plain"===this.editor.mode&&this.editor.plugins.plain&&this.editor.__plain)return this.editor.__plain.setRawData(e);this.editor.setData(e),t&&this.focus()}},d.prototype.init=function(){if(this.$element&&this.$element[0]){var t=this,s=function(){var s=Ot.oHtmlEditorDefaultConfig,i=jt.settingsGet("Language"),o=!!jt.settingsGet("AllowHtmlEditorSourceButton");o&&s.toolbarGroups&&!s.toolbarGroups.__SourceInited&&(s.toolbarGroups.__SourceInited=!0,s.toolbarGroups.push({name:"document",groups:["mode","document","doctools"]})),s.enterMode=e.CKEDITOR.ENTER_BR,s.shiftEnterMode=e.CKEDITOR.ENTER_BR,s.language=Ot.oHtmlEditorLangsMap[i]||"en",e.CKEDITOR.env&&(e.CKEDITOR.env.isCompatible=!0),t.editor=e.CKEDITOR.appendTo(t.$element[0],s),t.editor.on("key",function(e){return e&&e.data&&9===e.data.keyCode?!1:void 0}),t.editor.on("blur",function(){t.blurTrigger()}),t.editor.on("mode",function(){t.blurTrigger(),t.fOnModeChange&&t.fOnModeChange("plain"!==t.editor.mode)}),t.editor.on("focus",function(){t.focusTrigger()}),t.fOnReady&&t.editor.on("instanceReady",function(){t.editor.setKeystroke(e.CKEDITOR.CTRL+65,"selectAll"),t.fOnReady(),t.__resizable=!0,t.resize()})};e.CKEDITOR?s():e.__initEditor=s}},d.prototype.focus=function(){this.editor&&this.editor.focus()},d.prototype.blur=function(){this.editor&&this.editor.focusManager.blur(!0)},d.prototype.resize=function(){if(this.editor&&this.__resizable)try{this.editor.resize(this.$element.width(),this.$element.innerHeight())}catch(e){}},d.prototype.clear=function(e){this.setHtml("",e)},h.prototype.itemSelected=function(e){this.isListChecked()?e||(this.oCallbacks.onItemSelect||this.emptyFunction)(e||null):e&&(this.oCallbacks.onItemSelect||this.emptyFunction)(e)},h.prototype.goDown=function(e){this.newSelectPosition(Lt.EventKeyCode.Down,!1,e)},h.prototype.goUp=function(e){this.newSelectPosition(Lt.EventKeyCode.Up,!1,e)},h.prototype.init=function(e,i,o){if(this.oContentVisible=e,this.oContentScrollable=i,o=o||"all",this.oContentVisible&&this.oContentScrollable){var n=this;t(this.oContentVisible).on("selectstart",function(e){e&&e.preventDefault&&e.preventDefault()}).on("click",this.sItemSelector,function(e){n.actionClick(s.dataFor(this),e)}).on("click",this.sItemCheckedSelector,function(e){var t=s.dataFor(this);t&&(e&&e.shiftKey?n.actionClick(t,e):(n.focusedItem(t),t.checked(!t.checked())))}),c("enter",o,function(){return n.focusedItem()&&!n.focusedItem().selected()?(n.actionClick(n.focusedItem()),!1):!0}),c("ctrl+up, command+up, ctrl+down, command+down",o,function(){return!1}),c("up, shift+up, down, shift+down, home, end, pageup, pagedown, insert, space",o,function(e,t){if(e&&t&&t.shortcut){var s=0;switch(t.shortcut){case"up":case"shift+up":s=Lt.EventKeyCode.Up;break;case"down":case"shift+down":s=Lt.EventKeyCode.Down;break;case"insert":s=Lt.EventKeyCode.Insert;break;case"space":s=Lt.EventKeyCode.Space;break;case"home":s=Lt.EventKeyCode.Home;break;case"end":s=Lt.EventKeyCode.End;break;case"pageup":s=Lt.EventKeyCode.PageUp;break;case"pagedown":s=Lt.EventKeyCode.PageDown}if(s>0)return n.newSelectPosition(s,c.shift),!1}})}},h.prototype.autoSelect=function(e){this.bAutoSelect=!!e},h.prototype.getItemUid=function(e){var t="",s=this.oCallbacks.onItemGetUid||null;return s&&e&&(t=s(e)),t.toString()},h.prototype.newSelectPosition=function(e,t,s){var i=0,o=10,n=!1,a=!1,l=null,c=this.list(),u=c?c.length:0,d=this.focusedItem();if(u>0)if(d){if(d)if(Lt.EventKeyCode.Down===e||Lt.EventKeyCode.Up===e||Lt.EventKeyCode.Insert===e||Lt.EventKeyCode.Space===e)r.each(c,function(t){if(!a)switch(e){case Lt.EventKeyCode.Up:d===t?a=!0:l=t;break;case Lt.EventKeyCode.Down:case Lt.EventKeyCode.Insert:n?(l=t,a=!0):d===t&&(n=!0)}});else if(Lt.EventKeyCode.Home===e||Lt.EventKeyCode.End===e)Lt.EventKeyCode.Home===e?l=c[0]:Lt.EventKeyCode.End===e&&(l=c[c.length-1]);else if(Lt.EventKeyCode.PageDown===e){for(;u>i;i++)if(d===c[i]){i+=o,i=i>u-1?u-1:i,l=c[i];break}}else if(Lt.EventKeyCode.PageUp===e)for(i=u;i>=0;i--)if(d===c[i]){i-=o,i=0>i?0:i,l=c[i];break}}else Lt.EventKeyCode.Down===e||Lt.EventKeyCode.Insert===e||Lt.EventKeyCode.Space===e||Lt.EventKeyCode.Home===e||Lt.EventKeyCode.PageUp===e?l=c[0]:(Lt.EventKeyCode.Up===e||Lt.EventKeyCode.End===e||Lt.EventKeyCode.PageDown===e)&&(l=c[c.length-1]);l?(this.focusedItem(l),d&&(t?(Lt.EventKeyCode.Up===e||Lt.EventKeyCode.Down===e)&&d.checked(!d.checked()):(Lt.EventKeyCode.Insert===e||Lt.EventKeyCode.Space===e)&&d.checked(!d.checked())),!this.bAutoSelect&&!s||this.isListChecked()||Lt.EventKeyCode.Space===e||this.selectedItem(l),this.scrollToFocused()):d&&(!t||Lt.EventKeyCode.Up!==e&&Lt.EventKeyCode.Down!==e?(Lt.EventKeyCode.Insert===e||Lt.EventKeyCode.Space===e)&&d.checked(!d.checked()):d.checked(!d.checked()),this.focusedItem(d))},h.prototype.scrollToFocused=function(){if(!this.oContentVisible||!this.oContentScrollable)return!1;var e=20,s=t(this.sItemFocusedSelector,this.oContentScrollable),i=s.position(),o=this.oContentVisible.height(),n=s.outerHeight();return i&&(i.top<0||i.top+n>o)?(this.oContentScrollable.scrollTop(i.top<0?this.oContentScrollable.scrollTop()+i.top-e:this.oContentScrollable.scrollTop()+i.top-o+n+e),!0):!1},h.prototype.scrollToTop=function(e){return this.oContentVisible&&this.oContentScrollable?(e?this.oContentScrollable.scrollTop(0):this.oContentScrollable.stop().animate({scrollTop:0},200),!0):!1},h.prototype.eventClickFunction=function(e,t){var s=this.getItemUid(e),i=0,o=0,n=null,a="",r=!1,l=!1,c=[],u=!1;if(t&&t.shiftKey&&""!==s&&""!==this.sLastUid&&s!==this.sLastUid)for(c=this.list(),u=e.checked(),i=0,o=c.length;o>i;i++)n=c[i],a=this.getItemUid(n),r=!1,(a===this.sLastUid||a===s)&&(r=!0),r&&(l=!l),(l||r)&&n.checked(u);this.sLastUid=""===s?"":s},h.prototype.actionClick=function(e,t){if(e){var s=!0,i=this.getItemUid(e);t&&(!t.shiftKey||t.ctrlKey||t.altKey?!t.ctrlKey||t.shiftKey||t.altKey||(s=!1,this.focusedItem(e),this.selectedItem()&&e!==this.selectedItem()&&this.selectedItem().checked(!0),e.checked(!e.checked())):(s=!1,""===this.sLastUid&&(this.sLastUid=i),e.checked(!e.checked()),this.eventClickFunction(e,t),this.focusedItem(e))),s&&(this.focusedItem(e),this.selectedItem(e),this.scrollToFocused())}},h.prototype.on=function(e,t){this.oCallbacks[e]=t},p.supported=function(){return!0},p.prototype.set=function(e,s){var i=t.cookie(It.Values.ClientSideCookieIndexName),o=!1,n=null;try{n=null===i?null:JSON.parse(i),n||(n={}),n[e]=s,t.cookie(It.Values.ClientSideCookieIndexName,JSON.stringify(n),{expires:30}),o=!0}catch(a){}return o},p.prototype.get=function(e){var s=t.cookie(It.Values.ClientSideCookieIndexName),i=null;try{i=null===s?null:JSON.parse(s),i=i&&!Mt.isUnd(i[e])?i[e]:null}catch(o){}return i},m.supported=function(){return!!e.localStorage},m.prototype.set=function(t,s){var i=e.localStorage[It.Values.ClientSideCookieIndexName]||null,o=!1,n=null;try{n=null===i?null:JSON.parse(i),n||(n={}),n[t]=s,e.localStorage[It.Values.ClientSideCookieIndexName]=JSON.stringify(n),o=!0}catch(a){}return o},m.prototype.get=function(t){var s=e.localStorage[It.Values.ClientSideCookieIndexName]||null,i=null;try{i=null===s?null:JSON.parse(s),i=i&&!Mt.isUnd(i[t])?i[t]:null}catch(o){}return i},g.prototype.oDriver=null,g.prototype.set=function(e,t){return this.oDriver?this.oDriver.set("p"+e,t):!1},g.prototype.get=function(e){return this.oDriver?this.oDriver.get("p"+e):null},f.prototype.bootstart=function(){},b.prototype.sPosition="",b.prototype.sTemplate="",b.prototype.viewModelName="",b.prototype.viewModelDom=null,b.prototype.viewModelTemplate=function(){return this.sTemplate},b.prototype.viewModelPosition=function(){return this.sPosition},b.prototype.cancelCommand=b.prototype.closeCommand=function(){},b.prototype.storeAndSetKeyScope=function(){this.sCurrentKeyScope=jt.data().keyScope(),jt.data().keyScope(this.sDefaultKeyScope)},b.prototype.restoreKeyScope=function(){jt.data().keyScope(this.sCurrentKeyScope)},b.prototype.registerPopupKeyDown=function(){var e=this;Gt.on("keydown",function(t){if(t&&e.modalVisibility&&e.modalVisibility()){if(!this.bDisabeCloseOnEsc&&Lt.EventKeyCode.Esc===t.keyCode)return Mt.delegateRun(e,"cancelCommand"),!1;if(Lt.EventKeyCode.Backspace===t.keyCode&&!Mt.inFocus())return!1}return!0})},y.prototype.oCross=null,y.prototype.sScreenName="",y.prototype.aViewModels=[],y.prototype.viewModels=function(){return this.aViewModels},y.prototype.screenName=function(){return this.sScreenName},y.prototype.routes=function(){return null},y.prototype.__cross=function(){return this.oCross},y.prototype.__start=function(){var e=this.routes(),t=null,s=null;Mt.isNonEmptyArray(e)&&(s=r.bind(this.onRoute||Mt.emptyFunction,this),t=i.create(),r.each(e,function(e){t.addRoute(e[0],s).rules=e[1]}),this.oCross=t)},S.constructorEnd=function(e){Mt.isFunc(e.__constructor_end)&&e.__constructor_end.call(e)},S.prototype.sDefaultScreenName="",S.prototype.oScreens={},S.prototype.oBoot=null,S.prototype.oCurrentScreen=null,S.prototype.hideLoading=function(){t("#rl-loading").hide()},S.prototype.routeOff=function(){o.changed.active=!1},S.prototype.routeOn=function(){o.changed.active=!0},S.prototype.setBoot=function(e){return Mt.isNormal(e)&&(this.oBoot=e),this},S.prototype.screen=function(e){return""===e||Mt.isUnd(this.oScreens[e])?null:this.oScreens[e]},S.prototype.buildViewModel=function(e,i){if(e&&!e.__builded){var o=new e(i),n=o.viewModelPosition(),a=t("#rl-content #rl-"+n.toLowerCase()),l=null;e.__builded=!0,e.__vm=o,o.data=jt.data(),o.viewModelName=e.__name,a&&1===a.length?(l=t("").addClass("rl-view-model").addClass("RL-"+o.viewModelTemplate()).hide(),l.appendTo(a),o.viewModelDom=l,e.__dom=l,"Popups"===n&&(o.cancelCommand=o.closeCommand=Mt.createCommand(o,function(){xt.hideScreenPopup(e)}),o.modalVisibility.subscribe(function(e){var t=this;e?(this.viewModelDom.show(),this.storeAndSetKeyScope(),jt.popupVisibilityNames.push(this.viewModelName),o.viewModelDom.css("z-index",3e3+jt.popupVisibilityNames().length+10),Mt.delegateRun(this,"onFocus",[],500)):(Mt.delegateRun(this,"onHide"),this.restoreKeyScope(),jt.popupVisibilityNames.remove(this.viewModelName),o.viewModelDom.css("z-index",2e3),Ot.tooltipTrigger(!Ot.tooltipTrigger()),r.delay(function(){t.viewModelDom.hide()},300))},o)),Dt.runHook("view-model-pre-build",[e.__name,o,l]),s.applyBindingAccessorsToNode(l[0],{i18nInit:!0,template:function(){return{name:o.viewModelTemplate()}}},o),Mt.delegateRun(o,"onBuild",[l]),o&&"Popups"===n&&o.registerPopupKeyDown(),Dt.runHook("view-model-post-build",[e.__name,o,l])):Mt.log("Cannot find view model position: "+n)}return e?e.__vm:null},S.prototype.applyExternal=function(e,t){e&&t&&s.applyBindings(e,t)},S.prototype.hideScreenPopup=function(e){e&&e.__vm&&e.__dom&&(e.__vm.modalVisibility(!1),Dt.runHook("view-model-on-hide",[e.__name,e.__vm]))},S.prototype.showScreenPopup=function(e,t){e&&(this.buildViewModel(e),e.__vm&&e.__dom&&(e.__vm.modalVisibility(!0),Mt.delegateRun(e.__vm,"onShow",t||[]),Dt.runHook("view-model-on-show",[e.__name,e.__vm,t||[]])))},S.prototype.isPopupVisible=function(e){return e&&e.__vm?e.__vm.modalVisibility():!1},S.prototype.screenOnRoute=function(e,t){var s=this,i=null,o=null;""===Mt.pString(e)&&(e=this.sDefaultScreenName),""!==e&&(i=this.screen(e),i||(i=this.screen(this.sDefaultScreenName),i&&(t=e+"/"+t,e=this.sDefaultScreenName)),i&&i.__started&&(i.__builded||(i.__builded=!0,Mt.isNonEmptyArray(i.viewModels())&&r.each(i.viewModels(),function(e){this.buildViewModel(e,i)},this),Mt.delegateRun(i,"onBuild")),r.defer(function(){s.oCurrentScreen&&(Mt.delegateRun(s.oCurrentScreen,"onHide"),Mt.isNonEmptyArray(s.oCurrentScreen.viewModels())&&r.each(s.oCurrentScreen.viewModels(),function(e){e.__vm&&e.__dom&&"Popups"!==e.__vm.viewModelPosition()&&(e.__dom.hide(),e.__vm.viewModelVisibility(!1),Mt.delegateRun(e.__vm,"onHide"))})),s.oCurrentScreen=i,s.oCurrentScreen&&(Mt.delegateRun(s.oCurrentScreen,"onShow"),Dt.runHook("screen-on-show",[s.oCurrentScreen.screenName(),s.oCurrentScreen]),Mt.isNonEmptyArray(s.oCurrentScreen.viewModels())&&r.each(s.oCurrentScreen.viewModels(),function(e){e.__vm&&e.__dom&&"Popups"!==e.__vm.viewModelPosition()&&(e.__dom.show(),e.__vm.viewModelVisibility(!0),Mt.delegateRun(e.__vm,"onShow"),Mt.delegateRun(e.__vm,"onFocus",[],200),Dt.runHook("view-model-on-show",[e.__name,e.__vm]))},s)),o=i.__cross(),o&&o.parse(t)})))},S.prototype.startScreens=function(e){t("#rl-content").css({visibility:"hidden"}),r.each(e,function(e){var t=new e,s=t?t.screenName():"";t&&""!==s&&(""===this.sDefaultScreenName&&(this.sDefaultScreenName=s),this.oScreens[s]=t)},this),r.each(this.oScreens,function(e){e&&!e.__started&&e.__start&&(e.__started=!0,e.__start(),Dt.runHook("screen-pre-start",[e.screenName(),e]),Mt.delegateRun(e,"onStart"),Dt.runHook("screen-post-start",[e.screenName(),e]))},this);var s=i.create();s.addRoute(/^([a-zA-Z0-9\-]*)\/?(.*)$/,r.bind(this.screenOnRoute,this)),o.initialized.add(s.parse,s),o.changed.add(s.parse,s),o.init(),t("#rl-content").css({visibility:"visible"}),r.delay(function(){Bt.removeClass("rl-started-trigger").addClass("rl-started")},50)},S.prototype.setHash=function(e,t,s){e="#"===e.substr(0,1)?e.substr(1):e,e="/"===e.substr(0,1)?e.substr(1):e,s=Mt.isUnd(s)?!1:!!s,(Mt.isUnd(t)?1:!t)?(o.changed.active=!0,o[s?"replaceHash":"setHash"](e),o.setHash(e)):(o.changed.active=!1,o[s?"replaceHash":"setHash"](e),o.changed.active=!0)},S.prototype.bootstart=function(){return this.oBoot&&this.oBoot.bootstart&&this.oBoot.bootstart(),this},xt=new S,v.newInstanceFromJson=function(e){var t=new v;return t.initByJson(e)?t:null},v.prototype.name="",v.prototype.email="",v.prototype.privateType=null,v.prototype.clear=function(){this.email="",this.name="",this.privateType=null},v.prototype.validate=function(){return""!==this.name||""!==this.email},v.prototype.hash=function(e){return"#"+(e?"":this.name)+"#"+this.email+"#"},v.prototype.clearDuplicateName=function(){this.name===this.email&&(this.name="")},v.prototype.type=function(){return null===this.privateType&&(this.email&&"@facebook.com"===this.email.substr(-13)&&(this.privateType=Lt.EmailType.Facebook),null===this.privateType&&(this.privateType=Lt.EmailType.Default)),this.privateType},v.prototype.search=function(e){return-1<(this.name+" "+this.email).toLowerCase().indexOf(e.toLowerCase())},v.prototype.parse=function(e){this.clear(),e=Mt.trim(e);var t=/(?:"([^"]+)")? ?(.*?@[^>,]+)>?,? ?/g,s=t.exec(e);s?(this.name=s[1]||"",this.email=s[2]||"",this.clearDuplicateName()):/^[^@]+@[^@]+$/.test(e)&&(this.name="",this.email=e)},v.prototype.initByJson=function(e){var t=!1;return e&&"Object/Email"===e["@Object"]&&(this.name=Mt.trim(e.Name),this.email=Mt.trim(e.Email),t=""!==this.email,this.clearDuplicateName()),t},v.prototype.toLine=function(e,t,s){var i="";return""!==this.email&&(t=Mt.isUnd(t)?!1:!!t,s=Mt.isUnd(s)?!1:!!s,e&&""!==this.name?i=t?'")+'" target="_blank" tabindex="-1">'+Mt.encodeHtml(this.name)+"":s?Mt.encodeHtml(this.name):this.name:(i=this.email,""!==this.name?t?i=Mt.encodeHtml('"'+this.name+'" <')+'")+'" target="_blank" tabindex="-1">'+Mt.encodeHtml(i)+""+Mt.encodeHtml(">"):(i='"'+this.name+'" <'+i+">",s&&(i=Mt.encodeHtml(i))):t&&(i=''+Mt.encodeHtml(this.email)+""))),i},v.prototype.mailsoParse=function(e){if(e=Mt.trim(e),""===e)return!1;for(var t=function(e,t,s){e+="";var i=e.length;return 0>t&&(t+=i),i="undefined"==typeof s?i:0>s?s+i:s+t,t>=e.length||0>t||t>i?!1:e.slice(t,i)},s=function(e,t,s,i){return 0>s&&(s+=e.length),i=void 0!==i?i:e.length,0>i&&(i=i+e.length-s),e.slice(0,s)+t.substr(0,i)+t.slice(i)+e.slice(s+i)},i="",o="",n="",a=!1,r=!1,l=!1,c=null,u=0,d=0,h=0;h0&&0===i.length&&(i=t(e,0,h)),r=!0,u=h);break;case">":r&&(d=h,o=t(e,u+1,d-u-1),e=s(e,"",u,d-u+1),d=0,h=0,u=0,r=!1);break;case"(":a||r||l||(l=!0,u=h);break;case")":l&&(d=h,n=t(e,u+1,d-u-1),e=s(e,"",u,d-u+1),d=0,h=0,u=0,l=!1);break;case"\\":h++}h++}return 0===o.length&&(c=e.match(/[^@\s]+@\S+/i),c&&c[0]?o=c[0]:i=e),o.length>0&&0===i.length&&0===n.length&&(i=e.replace(o,"")),o=Mt.trim(o).replace(/^[<]+/,"").replace(/[>]+$/,""),i=Mt.trim(i).replace(/^["']+/,"").replace(/["']+$/,""),n=Mt.trim(n).replace(/^[(]+/,"").replace(/[)]+$/,""),i=i.replace(/\\\\(.)/,"$1"),n=n.replace(/\\\\(.)/,"$1"),this.name=i,this.email=o,this.clearDuplicateName(),!0},v.prototype.inputoTagLine=function(){return 0 +$/,""),t=!0),t},F.prototype.isImage=function(){return-10?n.unix(e).format("LLL"):""},E.emailsToLine=function(e,t,s){var i=[],o=0,n=0;if(Mt.isNonEmptyArray(e))for(o=0,n=e.length;n>o;o++)i.push(e[o].toLine(t,s));return i.join(", ")},E.emailsToLineClear=function(e){var t=[],s=0,i=0;if(Mt.isNonEmptyArray(e))for(s=0,i=e.length;i>s;s++)e[s]&&e[s].email&&""!==e[s].name&&t.push(e[s].email);return t.join(", ")},E.initEmailsFromJson=function(e){var t=0,s=0,i=null,o=[];if(Mt.isNonEmptyArray(e))for(t=0,s=e.length;s>t;t++)i=v.newInstanceFromJson(e[t]),i&&o.push(i);return o},E.replyHelper=function(e,t,s){if(e&&0i;i++)Mt.isUnd(t[e[i].email])&&(t[e[i].email]=!0,s.push(e[i]))},E.prototype.clear=function(){this.folderFullNameRaw="",this.uid="",this.hash="",this.requestHash="",this.subject(""),this.subjectPrefix(""),this.subjectSuffix(""),this.size(0),this.dateTimeStampInUTC(0),this.priority(Lt.MessagePriority.Normal),this.proxy=!1,this.fromEmailString(""),this.fromClearEmailString(""),this.toEmailsString(""),this.toClearEmailsString(""),this.senderEmailsString(""),this.senderClearEmailsString(""),this.emails=[],this.from=[],this.to=[],this.cc=[],this.bcc=[],this.replyTo=[],this.deliveredTo=[],this.newForAnimation(!1),this.deleted(!1),this.unseen(!1),this.flagged(!1),this.answered(!1),this.forwarded(!1),this.isReadReceipt(!1),this.selected(!1),this.checked(!1),this.hasAttachments(!1),this.attachmentsMainType(""),this.body=null,this.isHtml(!1),this.hasImages(!1),this.attachments([]),this.isPgpSigned(!1),this.isPgpEncrypted(!1),this.pgpSignedVerifyStatus(Lt.SignedVerifyStatus.None),this.pgpSignedVerifyUser(""),this.priority(Lt.MessagePriority.Normal),this.readReceipt(""),this.aDraftInfo=[],this.sMessageId="",this.sInReplyTo="",this.sReferences="",this.parentUid(0),this.threads([]),this.threadsLen(0),this.hasUnseenSubMessage(!1),this.hasFlaggedSubMessage(!1),this.lastInCollapsedThread(!1),this.lastInCollapsedThreadLoading(!1)},E.prototype.computeSenderEmail=function(){var e=jt.data().sentFolder(),t=jt.data().draftFolder();this.senderEmailsString(this.folderFullNameRaw===e||this.folderFullNameRaw===t?this.toEmailsString():this.fromEmailString()),this.senderClearEmailsString(this.folderFullNameRaw===e||this.folderFullNameRaw===t?this.toClearEmailsString():this.fromClearEmailString())},E.prototype.initByJson=function(e){var t=!1;return e&&"Object/Message"===e["@Object"]&&(this.folderFullNameRaw=e.Folder,this.uid=e.Uid,this.hash=e.Hash,this.requestHash=e.RequestHash,this.proxy=!!e.ExternalProxy,this.size(Mt.pInt(e.Size)),this.from=E.initEmailsFromJson(e.From),this.to=E.initEmailsFromJson(e.To),this.cc=E.initEmailsFromJson(e.Cc),this.bcc=E.initEmailsFromJson(e.Bcc),this.replyTo=E.initEmailsFromJson(e.ReplyTo),this.deliveredTo=E.initEmailsFromJson(e.DeliveredTo),this.subject(e.Subject),Mt.isArray(e.SubjectParts)?(this.subjectPrefix(e.SubjectParts[0]),this.subjectSuffix(e.SubjectParts[1])):(this.subjectPrefix(""),this.subjectSuffix(this.subject())),this.dateTimeStampInUTC(Mt.pInt(e.DateTimeStampInUTC)),this.hasAttachments(!!e.HasAttachments),this.attachmentsMainType(e.AttachmentsMainType),this.fromEmailString(E.emailsToLine(this.from,!0)),this.fromClearEmailString(E.emailsToLineClear(this.from)),this.toEmailsString(E.emailsToLine(this.to,!0)),this.toClearEmailsString(E.emailsToLineClear(this.to)),this.parentUid(Mt.pInt(e.ParentThread)),this.threads(Mt.isArray(e.Threads)?e.Threads:[]),this.threadsLen(Mt.pInt(e.ThreadsLen)),this.initFlagsByJson(e),this.computeSenderEmail(),t=!0),t},E.prototype.initUpdateByMessageJson=function(e){var t=!1,s=Lt.MessagePriority.Normal;return e&&"Object/Message"===e["@Object"]&&(s=Mt.pInt(e.Priority),this.priority(-1t;t++)i=F.newInstanceFromJson(e["@Collection"][t]),i&&(""!==i.cidWithOutTags&&0 +$/,""),t=r.find(s,function(t){return e===t.cidWithOutTags})),t||null},E.prototype.findAttachmentByContentLocation=function(e){var t=null,s=this.attachments();return Mt.isNonEmptyArray(s)&&(t=r.find(s,function(t){return e===t.contentLocation})),t||null},E.prototype.messageId=function(){return this.sMessageId},E.prototype.inReplyTo=function(){return this.sInReplyTo},E.prototype.references=function(){return this.sReferences},E.prototype.fromAsSingleEmail=function(){return Mt.isArray(this.from)&&this.from[0]?this.from[0].email:""},E.prototype.viewLink=function(){return jt.link().messageViewLink(this.requestHash)},E.prototype.downloadLink=function(){return jt.link().messageDownloadLink(this.requestHash)},E.prototype.replyEmails=function(e){var t=[],s=Mt.isUnd(e)?{}:e;return E.replyHelper(this.replyTo,s,t),0===t.length&&E.replyHelper(this.from,s,t),t},E.prototype.replyAllEmails=function(e){var t=[],s=[],i=Mt.isUnd(e)?{}:e;return E.replyHelper(this.replyTo,i,t),0===t.length&&E.replyHelper(this.from,i,t),E.replyHelper(this.to,i,t),E.replyHelper(this.cc,i,s),[t,s]},E.prototype.textBodyToString=function(){return this.body?this.body.html():""},E.prototype.attachmentsToStringLine=function(){var e=r.map(this.attachments(),function(e){return e.fileName+" ("+e.friendlySize+")"});return e&&0=0&&o&&!n&&i.attr("src",o)}),s&&e.setTimeout(function(){i.print()},100))})},E.prototype.printMessage=function(){this.viewPopupMessage(!0)},E.prototype.generateUid=function(){return this.folderFullNameRaw+"/"+this.uid},E.prototype.populateByMessageListItem=function(e){return this.folderFullNameRaw=e.folderFullNameRaw,this.uid=e.uid,this.hash=e.hash,this.requestHash=e.requestHash,this.subject(e.subject()),this.subjectPrefix(this.subjectPrefix()),this.subjectSuffix(this.subjectSuffix()),this.size(e.size()),this.dateTimeStampInUTC(e.dateTimeStampInUTC()),this.priority(e.priority()),this.proxy=e.proxy,this.fromEmailString(e.fromEmailString()),this.fromClearEmailString(e.fromClearEmailString()),this.toEmailsString(e.toEmailsString()),this.toClearEmailsString(e.toClearEmailsString()),this.emails=e.emails,this.from=e.from,this.to=e.to,this.cc=e.cc,this.bcc=e.bcc,this.replyTo=e.replyTo,this.deliveredTo=e.deliveredTo,this.unseen(e.unseen()),this.flagged(e.flagged()),this.answered(e.answered()),this.forwarded(e.forwarded()),this.isReadReceipt(e.isReadReceipt()),this.selected(e.selected()),this.checked(e.checked()),this.hasAttachments(e.hasAttachments()),this.attachmentsMainType(e.attachmentsMainType()),this.moment(e.moment()),this.body=null,this.priority(Lt.MessagePriority.Normal),this.aDraftInfo=[],this.sMessageId="",this.sInReplyTo="",this.sReferences="",this.parentUid(e.parentUid()),this.threads(e.threads()),this.threadsLen(e.threadsLen()),this.computeSenderEmail(),this},E.prototype.showExternalImages=function(e){if(this.body&&this.body.data("rl-has-images")){var s="";e=Mt.isUnd(e)?!1:e,this.hasImages(!1),this.body.data("rl-has-images",!1),s=this.proxy?"data-x-additional-src":"data-x-src",t("["+s+"]",this.body).each(function(){e&&t(this).is("img")?t(this).addClass("lazy").attr("data-original",t(this).attr(s)).removeAttr(s):t(this).attr("src",t(this).attr(s)).removeAttr(s)}),s=this.proxy?"data-x-additional-style-url":"data-x-style-url",t("["+s+"]",this.body).each(function(){var e=Mt.trim(t(this).attr("style"));e=""===e?"":";"===e.substr(-1)?e+" ":e+"; ",t(this).attr("style",e+t(this).attr(s)).removeAttr(s)}),e&&(t("img.lazy",this.body).addClass("lazy-inited").lazyload({threshold:400,effect:"fadeIn",skip_invisible:!1,container:t(".RL-MailMessageView .messageView .messageItem .content")[0]}),Gt.resize()),Mt.windowResize(500)}},E.prototype.showInternalImages=function(e){if(this.body&&!this.body.data("rl-init-internal-images")){this.body.data("rl-init-internal-images",!0),e=Mt.isUnd(e)?!1:e;var s=this;t("[data-x-src-cid]",this.body).each(function(){var i=s.findAttachmentByCid(t(this).attr("data-x-src-cid"));i&&i.download&&(e&&t(this).is("img")?t(this).addClass("lazy").attr("data-original",i.linkPreview()):t(this).attr("src",i.linkPreview()))}),t("[data-x-src-location]",this.body).each(function(){var i=s.findAttachmentByContentLocation(t(this).attr("data-x-src-location"));i||(i=s.findAttachmentByCid(t(this).attr("data-x-src-location"))),i&&i.download&&(e&&t(this).is("img")?t(this).addClass("lazy").attr("data-original",i.linkPreview()):t(this).attr("src",i.linkPreview()))}),t("[data-x-style-cid]",this.body).each(function(){var e="",i="",o=s.findAttachmentByCid(t(this).attr("data-x-style-cid"));o&&o.linkPreview&&(i=t(this).attr("data-x-style-cid-name"),""!==i&&(e=Mt.trim(t(this).attr("style")),e=""===e?"":";"===e.substr(-1)?e+" ":e+"; ",t(this).attr("style",e+i+": url('"+o.linkPreview()+"')")))}),e&&!function(e,t){r.delay(function(){e.addClass("lazy-inited").lazyload({threshold:400,effect:"fadeIn",skip_invisible:!1,container:t})},300)}(t("img.lazy",s.body),t(".RL-MailMessageView .messageView .messageItem .content")[0]),Mt.windowResize(500)}},E.prototype.storeDataToDom=function(){this.body&&(this.body.data("rl-is-html",!!this.isHtml()),this.body.data("rl-has-images",!!this.hasImages()),this.body.data("rl-plain-raw",this.plainRaw),jt.data().capaOpenPGP()&&(this.body.data("rl-plain-pgp-signed",!!this.isPgpSigned()),this.body.data("rl-plain-pgp-encrypted",!!this.isPgpEncrypted()),this.body.data("rl-pgp-verify-status",this.pgpSignedVerifyStatus()),this.body.data("rl-pgp-verify-user",this.pgpSignedVerifyUser())))},E.prototype.storePgpVerifyDataToDom=function(){this.body&&jt.data().capaOpenPGP()&&(this.body.data("rl-pgp-verify-status",this.pgpSignedVerifyStatus()),this.body.data("rl-pgp-verify-user",this.pgpSignedVerifyUser()))},E.prototype.fetchDataToDom=function(){this.body&&(this.isHtml(!!this.body.data("rl-is-html")),this.hasImages(!!this.body.data("rl-has-images")),this.plainRaw=Mt.pString(this.body.data("rl-plain-raw")),jt.data().capaOpenPGP()?(this.isPgpSigned(!!this.body.data("rl-plain-pgp-signed")),this.isPgpEncrypted(!!this.body.data("rl-plain-pgp-encrypted")),this.pgpSignedVerifyStatus(this.body.data("rl-pgp-verify-status")),this.pgpSignedVerifyUser(this.body.data("rl-pgp-verify-user"))):(this.isPgpSigned(!1),this.isPgpEncrypted(!1),this.pgpSignedVerifyStatus(Lt.SignedVerifyStatus.None),this.pgpSignedVerifyUser("")))},E.prototype.verifyPgpSignedClearMessage=function(){if(this.isPgpSigned()){var s=[],i=null,o=this.from&&this.from[0]&&this.from[0].email?this.from[0].email:"",n=jt.data().findPublicKeysByEmail(o),a=null,l=null,c="";this.pgpSignedVerifyStatus(Lt.SignedVerifyStatus.Error),this.pgpSignedVerifyUser("");try{i=e.openpgp.cleartext.readArmored(this.plainRaw),i&&i.getText&&(this.pgpSignedVerifyStatus(n.length?Lt.SignedVerifyStatus.Unverified:Lt.SignedVerifyStatus.UnknownPublicKeys),s=i.verify(n),s&&0').text(c)).html(),zt.empty(),this.replacePlaneTextBody(c)))))}catch(u){}this.storePgpVerifyDataToDom()}},E.prototype.decryptPgpEncryptedMessage=function(s){if(this.isPgpEncrypted()){var i=[],o=null,n=null,a=this.from&&this.from[0]&&this.from[0].email?this.from[0].email:"",l=jt.data().findPublicKeysByEmail(a),c=jt.data().findSelfPrivateKey(s),u=null,d=null,h="";this.pgpSignedVerifyStatus(Lt.SignedVerifyStatus.Error),this.pgpSignedVerifyUser(""),c||this.pgpSignedVerifyStatus(Lt.SignedVerifyStatus.UnknownPrivateKey);try{o=e.openpgp.message.readArmored(this.plainRaw),o&&c&&o.decrypt&&(this.pgpSignedVerifyStatus(Lt.SignedVerifyStatus.Unverified),n=o.decrypt(c),n&&(i=n.verify(l),i&&0').text(h)).html(),zt.empty(),this.replacePlaneTextBody(h)))}catch(p){}this.storePgpVerifyDataToDom()}},E.prototype.replacePlaneTextBody=function(e){this.body&&this.body.html(e).addClass("b-text-part plain")},E.prototype.flagHash=function(){return[this.deleted(),this.unseen(),this.flagged(),this.answered(),this.forwarded(),this.isReadReceipt()].join("")},N.newInstanceFromJson=function(e){var t=new N;return t.initByJson(e)?t.initComputed():null},N.prototype.initComputed=function(){return this.hasSubScribedSubfolders=s.computed(function(){return!!r.find(this.subFolders(),function(e){return e.subScribed()&&!e.isSystemFolder()})},this),this.canBeEdited=s.computed(function(){return Lt.FolderType.User===this.type()&&this.existen&&this.selectable},this),this.visible=s.computed(function(){var e=this.subScribed(),t=this.hasSubScribedSubfolders();return e||t&&(!this.existen||!this.selectable)},this),this.isSystemFolder=s.computed(function(){return Lt.FolderType.User!==this.type()},this),this.hidden=s.computed(function(){var e=this.isSystemFolder(),t=this.hasSubScribedSubfolders();return e&&!t||!this.selectable&&!t},this),this.selectableForFolderList=s.computed(function(){return!this.isSystemFolder()&&this.selectable},this),this.messageCountAll=s.computed({read:this.privateMessageCountAll,write:function(e){Mt.isPosNumeric(e,!0)?this.privateMessageCountAll(e):this.privateMessageCountAll.valueHasMutated()},owner:this}),this.messageCountUnread=s.computed({read:this.privateMessageCountUnread,write:function(e){Mt.isPosNumeric(e,!0)?this.privateMessageCountUnread(e):this.privateMessageCountUnread.valueHasMutated()},owner:this}),this.printableUnreadCount=s.computed(function(){var e=this.messageCountAll(),t=this.messageCountUnread(),s=this.type();if(Lt.FolderType.Inbox===s&&jt.data().foldersInboxUnreadCount(t),e>0){if(Lt.FolderType.Draft===s)return""+e;if(t>0&&Lt.FolderType.Trash!==s&&Lt.FolderType.Archive!==s&&Lt.FolderType.SentItems!==s)return""+t}return""},this),this.canBeDeleted=s.computed(function(){var e=this.isSystemFolder();return!e&&0===this.subFolders().length&&"INBOX"!==this.fullNameRaw},this),this.canBeSubScribed=s.computed(function(){return!this.isSystemFolder()&&this.selectable&&"INBOX"!==this.fullNameRaw},this),this.visible.subscribe(function(){Mt.timeOutAction("folder-list-folder-visibility-change",function(){Gt.trigger("folder-list-folder-visibility-change")},100)}),this.localName=s.computed(function(){Ot.langChangeTrigger();var e=this.type(),t=this.name();if(this.isSystemFolder())switch(e){case Lt.FolderType.Inbox:t=Mt.i18n("FOLDER_LIST/INBOX_NAME");break;case Lt.FolderType.SentItems:t=Mt.i18n("FOLDER_LIST/SENT_NAME");break;case Lt.FolderType.Draft:t=Mt.i18n("FOLDER_LIST/DRAFTS_NAME");break;case Lt.FolderType.Spam:t=Mt.i18n("FOLDER_LIST/SPAM_NAME");break;case Lt.FolderType.Trash:t=Mt.i18n("FOLDER_LIST/TRASH_NAME");break;case Lt.FolderType.Archive:t=Mt.i18n("FOLDER_LIST/ARCHIVE_NAME")}return t},this),this.manageFolderSystemName=s.computed(function(){Ot.langChangeTrigger();var e="",t=this.type(),s=this.name();if(this.isSystemFolder())switch(t){case Lt.FolderType.Inbox:e="("+Mt.i18n("FOLDER_LIST/INBOX_NAME")+")";break;case Lt.FolderType.SentItems:e="("+Mt.i18n("FOLDER_LIST/SENT_NAME")+")";break;case Lt.FolderType.Draft:e="("+Mt.i18n("FOLDER_LIST/DRAFTS_NAME")+")";break;case Lt.FolderType.Spam:e="("+Mt.i18n("FOLDER_LIST/SPAM_NAME")+")";break;case Lt.FolderType.Trash:e="("+Mt.i18n("FOLDER_LIST/TRASH_NAME")+")";break;case Lt.FolderType.Archive:e="("+Mt.i18n("FOLDER_LIST/ARCHIVE_NAME")+")"}return(""!==e&&"("+s+")"===e||"(inbox)"===e.toLowerCase())&&(e=""),e},this),this.collapsed=s.computed({read:function(){return!this.hidden()&&this.collapsedPrivate()},write:function(e){this.collapsedPrivate(e)},owner:this}),this.hasUnreadMessages=s.computed(function(){return 0"},I.prototype.formattedNameForCompose=function(){var e=this.name();return""===e?this.email():e+" ("+this.email()+")"},I.prototype.formattedNameForEmail=function(){var e=this.name();return""===e?this.email():'"'+Mt.quoteName(e)+'" <'+this.email()+">"},L.prototype.removeSelf=function(){this.parentList.remove(this)},P.prototype.addCondition=function(){this.conditions.push(new L(this.conditions))},P.prototype.parse=function(e){var t=!1;return e&&"Object/Filter"===e["@Object"]&&(this.name(Mt.pString(e.Name)),t=!0),t},M.prototype.index=0,M.prototype.id="",M.prototype.guid="",M.prototype.user="",M.prototype.email="",M.prototype.armor="",M.prototype.isPrivate=!1,Mt.extendAsViewModel("PopupsFolderClearViewModel",D),D.prototype.clearPopup=function(){this.clearingProcess(!1),this.selectedFolder(null)},D.prototype.onShow=function(e){this.clearPopup(),e&&this.selectedFolder(e)},Mt.extendAsViewModel("PopupsFolderCreateViewModel",k),k.prototype.sNoParentText="",k.prototype.simpleFolderNameValidation=function(e){return/^[^\\\/]+$/g.test(Mt.trim(e))},k.prototype.clearPopup=function(){this.folderName(""),this.selectedParentValue(""),this.folderName.focused(!1)},k.prototype.onShow=function(){this.clearPopup()},k.prototype.onFocus=function(){this.folderName.focused(!0)},Mt.extendAsViewModel("PopupsFolderSystemViewModel",O),O.prototype.sChooseOnText="",O.prototype.sUnuseText="",O.prototype.onShow=function(e){var t="";switch(e=Mt.isUnd(e)?Lt.SetSystemFoldersNotification.None:e){case Lt.SetSystemFoldersNotification.Sent:t=Mt.i18n("POPUPS_SYSTEM_FOLDERS/NOTIFICATION_SENT");break;case Lt.SetSystemFoldersNotification.Draft:t=Mt.i18n("POPUPS_SYSTEM_FOLDERS/NOTIFICATION_DRAFTS");break;case Lt.SetSystemFoldersNotification.Spam:t=Mt.i18n("POPUPS_SYSTEM_FOLDERS/NOTIFICATION_SPAM");break;case Lt.SetSystemFoldersNotification.Trash:t=Mt.i18n("POPUPS_SYSTEM_FOLDERS/NOTIFICATION_TRASH");break;case Lt.SetSystemFoldersNotification.Archive:t=Mt.i18n("POPUPS_SYSTEM_FOLDERS/NOTIFICATION_ARCHIVE")}this.notification(t)},Mt.extendAsViewModel("PopupsComposeViewModel",_),_.prototype.openOpenPgpPopup=function(){if(this.capaOpenPGP()&&this.oEditor&&!this.oEditor.isHtml()){var e=this;xt.showScreenPopup(K,[function(t){e.editor(function(e){e.setPlain(t)})},this.oEditor.getData(),this.currentIdentityResultEmail(),this.to(),this.cc(),this.bcc()])}},_.prototype.reloadDraftFolder=function(){var e=jt.data().draftFolder();""!==e&&(jt.cache().setFolderHash(e,""),jt.data().currentFolderFullNameRaw()===e?jt.reloadMessageList(!0):jt.folderInformation(e))},_.prototype.findIdentityIdByMessage=function(e,t){var s={},i="",o=function(e){return e&&e.email&&s[e.email]?(i=s[e.email],!0):!1};if(this.bCapaAdditionalIdentities&&r.each(this.identities(),function(e){s[e.email()]=e.id}),s[jt.data().accountEmail()]=jt.data().accountEmail(),t)switch(e){case Lt.ComposeType.Empty:break;case Lt.ComposeType.Reply:case Lt.ComposeType.ReplyAll:case Lt.ComposeType.Forward:case Lt.ComposeType.ForwardAsAttachment:r.find(r.union(t.to,t.cc,t.bcc,t.deliveredTo),o);break;case Lt.ComposeType.Draft:r.find(r.union(t.from,t.replyTo),o)}return""===i&&(i=this.defaultIdentityID()),""===i&&(i=jt.data().accountEmail()),i},_.prototype.selectIdentity=function(e){e&&this.currentIdentityID(e.optValue)},_.prototype.formattedFrom=function(e){var t=jt.data().displayName(),s=jt.data().accountEmail();return""===t?s:(Mt.isUnd(e)?1:!e)?t+" ("+s+")":'"'+Mt.quoteName(t)+'" <'+s+">"},_.prototype.sendMessageResponse=function(t,s){var i=!1,o="";this.sending(!1),Lt.StorageResultType.Success===t&&s&&s.Result&&(i=!0,this.modalVisibility()&&Mt.delegateRun(this,"closeCommand")),this.modalVisibility()&&!i&&(s&&Lt.Notification.CantSaveMessage===s.ErrorCode?(this.sendSuccessButSaveError(!0),e.alert(Mt.trim(Mt.i18n("COMPOSE/SAVED_ERROR_ON_SEND")))):(o=Mt.getNotification(s&&s.ErrorCode?s.ErrorCode:Lt.Notification.CantSendMessage,s&&s.ErrorMessage?s.ErrorMessage:""),this.sendError(!0),e.alert(o||Mt.getNotification(Lt.Notification.CantSendMessage)))),this.reloadDraftFolder()},_.prototype.saveMessageResponse=function(t,s){var i=!1,o=null;this.saving(!1),Lt.StorageResultType.Success===t&&s&&s.Result&&s.Result.NewFolder&&s.Result.NewUid&&(this.bFromDraft&&(o=jt.data().message(),o&&this.draftFolder()===o.folderFullNameRaw&&this.draftUid()===o.uid&&jt.data().message(null)),this.draftFolder(s.Result.NewFolder),this.draftUid(s.Result.NewUid),this.modalVisibility()&&(this.savedTime(Math.round((new e.Date).getTime()/1e3)),this.savedOrSendingText(0 "+e;break;default:e=e+"
"+s}return e},_.prototype.editor=function(e){if(e){var t=this;!this.oEditor&&this.composeEditorArea()?r.delay(function(){t.oEditor=new d(t.composeEditorArea(),null,function(){e(t.oEditor)},function(e){t.isHtml(!!e)})},300):this.oEditor&&e(this.oEditor)}},_.prototype.onShow=function(e,s,i,o,n){xt.routeOff();var a=this,l="",c="",u="",d="",h="",p=null,m=null,g="",f="",b=[],y={},S=jt.data().accountEmail(),v=jt.data().signature(),C=jt.data().signatureToAll(),w=[],T=null,F=null,A=e||Lt.ComposeType.Empty,E=function(e,t){for(var s=0,i=e.length,o=[];i>s;s++)o.push(e[s].toLine(!!t));return o.join(", ")};if(s=s||null,s&&Mt.isNormal(s)&&(F=Mt.isArray(s)&&1===s.length?s[0]:Mt.isArray(s)?null:s),null!==S&&(y[S]=!0),this.currentIdentityID(this.findIdentityIdByMessage(A,F)),this.reset(),Mt.isNonEmptyArray(i)&&this.to(E(i)),""!==A&&F){switch(d=F.fullFormatDateValue(),h=F.subject(),T=F.aDraftInfo,p=t(F.body).clone(),Mt.removeBlockquoteSwitcher(p),m=p.find("[data-html-editor-font-wrapper=true]"),g=m&&m[0]?m.html():p.html(),A){case Lt.ComposeType.Empty:break;case Lt.ComposeType.Reply:this.to(E(F.replyEmails(y))),this.subject(Mt.replySubjectAdd("Re",h)),this.prepearMessageAttachments(F,A),this.aDraftInfo=["reply",F.uid,F.folderFullNameRaw],this.sInReplyTo=F.sMessageId,this.sReferences=Mt.trim(this.sInReplyTo+" "+F.sReferences);break;case Lt.ComposeType.ReplyAll:b=F.replyAllEmails(y),this.to(E(b[0])),this.cc(E(b[1])),this.subject(Mt.replySubjectAdd("Re",h)),this.prepearMessageAttachments(F,A),this.aDraftInfo=["reply",F.uid,F.folderFullNameRaw],this.sInReplyTo=F.sMessageId,this.sReferences=Mt.trim(this.sInReplyTo+" "+F.references());break;case Lt.ComposeType.Forward:this.subject(Mt.replySubjectAdd("Fwd",h)),this.prepearMessageAttachments(F,A),this.aDraftInfo=["forward",F.uid,F.folderFullNameRaw],this.sInReplyTo=F.sMessageId,this.sReferences=Mt.trim(this.sInReplyTo+" "+F.sReferences);break;case Lt.ComposeType.ForwardAsAttachment:this.subject(Mt.replySubjectAdd("Fwd",h)),this.prepearMessageAttachments(F,A),this.aDraftInfo=["forward",F.uid,F.folderFullNameRaw],this.sInReplyTo=F.sMessageId,this.sReferences=Mt.trim(this.sInReplyTo+" "+F.sReferences);break;case Lt.ComposeType.Draft:this.to(E(F.to)),this.cc(E(F.cc)),this.bcc(E(F.bcc)),this.bFromDraft=!0,this.draftFolder(F.folderFullNameRaw),this.draftUid(F.uid),this.subject(h),this.prepearMessageAttachments(F,A),this.aDraftInfo=Mt.isNonEmptyArray(T)&&3===T.length?T:null,this.sInReplyTo=F.sInReplyTo,this.sReferences=F.sReferences;break;case Lt.ComposeType.EditAsNew:this.to(E(F.to)),this.cc(E(F.cc)),this.bcc(E(F.bcc)),this.subject(h),this.prepearMessageAttachments(F,A),this.aDraftInfo=Mt.isNonEmptyArray(T)&&3===T.length?T:null,this.sInReplyTo=F.sInReplyTo,this.sReferences=F.sReferences}switch(A){case Lt.ComposeType.Reply:case Lt.ComposeType.ReplyAll:l=F.fromToLine(!1,!0),f=Mt.i18n("COMPOSE/REPLY_MESSAGE_TITLE",{DATETIME:d,EMAIL:l}),g="
"+f+":"+g+"
";break;case Lt.ComposeType.Forward:l=F.fromToLine(!1,!0),c=F.toToLine(!1,!0),u=F.ccToLine(!1,!0),g="
"+Mt.i18n("COMPOSE/FORWARD_MESSAGE_TOP_TITLE")+"
"+Mt.i18n("COMPOSE/FORWARD_MESSAGE_TOP_FROM")+": "+l+"
"+Mt.i18n("COMPOSE/FORWARD_MESSAGE_TOP_TO")+": "+c+(0 "+Mt.i18n("COMPOSE/FORWARD_MESSAGE_TOP_CC")+": "+u:"")+"
"+Mt.i18n("COMPOSE/FORWARD_MESSAGE_TOP_SENT")+": "+Mt.encodeHtml(d)+"
"+Mt.i18n("COMPOSE/FORWARD_MESSAGE_TOP_SUBJECT")+": "+Mt.encodeHtml(h)+"
"+g;break;case Lt.ComposeType.ForwardAsAttachment:g=""}C&&""!==v&&Lt.ComposeType.EditAsNew!==A&&Lt.ComposeType.Draft!==A&&(g=this.convertSignature(v,E(F.from,!0),g,A)),this.editor(function(e){e.setHtml(g,!1),F.isHtml()||e.modeToggle(!1)})}else Lt.ComposeType.Empty===A?(this.subject(Mt.isNormal(o)?""+o:""),g=Mt.isNormal(n)?""+n:"",C&&""!==v&&(g=this.convertSignature(v,"",Mt.convertPlainTextToHtml(g),A)),this.editor(function(e){e.setHtml(g,!1),Lt.EditorDefaultType.Html!==jt.data().editorDefaultType()&&e.modeToggle(!1)})):Mt.isNonEmptyArray(s)&&r.each(s,function(e){a.addMessageAsAttachment(e)});w=this.getAttachmentsDownloadsForUpload(),Mt.isNonEmptyArray(w)&&jt.remote().messageUploadAttachments(function(e,t){if(Lt.StorageResultType.Success===e&&t&&t.Result){var s=null,i="";if(!a.viewModelVisibility())for(i in t.Result)t.Result.hasOwnProperty(i)&&(s=a.getAttachmentById(t.Result[i]),s&&s.tempName(i))}else a.setMessageAttachmentFailedDowbloadText()},w),this.triggerForResize()},_.prototype.onFocus=function(){""===this.to()?this.to.focusTrigger(!this.to.focusTrigger()):this.oEditor&&this.oEditor.focus(),this.triggerForResize()},_.prototype.editorResize=function(){this.oEditor&&this.oEditor.resize()},_.prototype.tryToClosePopup=function(){var e=this;xt.isPopupVisible(W)||xt.showScreenPopup(W,[Mt.i18n("POPUPS_ASK/DESC_WANT_CLOSE_THIS_WINDOW"),function(){e.modalVisibility()&&Mt.delegateRun(e,"closeCommand")}])},_.prototype.onBuild=function(){this.initUploader();var s=this,i=null;c("ctrl+q, command+q",Lt.KeyState.Compose,function(){return s.identitiesDropdownTrigger(!0),!1}),c("ctrl+s, command+s",Lt.KeyState.Compose,function(){return s.saveCommand(),!1}),c("ctrl+enter, command+enter",Lt.KeyState.Compose,function(){return s.sendCommand(),!1}),c("esc",Lt.KeyState.Compose,function(){return s.modalVisibility()&&s.tryToClosePopup(),!1}),Gt.on("resize",function(){s.triggerForResize()}),this.dropboxEnabled()&&(i=document.createElement("script"),i.type="text/javascript",i.src="https://www.dropbox.com/static/api/1/dropins.js",t(i).attr("id","dropboxjs").attr("data-app-key",jt.settingsGet("DropboxApiKey")),document.body.appendChild(i)),this.driveEnabled()&&t.getScript("https://apis.google.com/js/api.js",function(){e.gapi&&s.driveVisible(!0)})},_.prototype.driveCallback=function(t,s){if(s&&e.XMLHttpRequest&&e.google&&s[e.google.picker.Response.ACTION]===e.google.picker.Action.PICKED&&s[e.google.picker.Response.DOCUMENTS]&&s[e.google.picker.Response.DOCUMENTS][0]&&s[e.google.picker.Response.DOCUMENTS][0].id){var i=this,o=new e.XMLHttpRequest;o.open("GET","https://www.googleapis.com/drive/v2/files/"+s[e.google.picker.Response.DOCUMENTS][0].id),o.setRequestHeader("Authorization","Bearer "+t),o.addEventListener("load",function(){if(o&&o.responseText){var e=JSON.parse(o.responseText),s=function(e,t,s){e&&e.exportLinks&&(e.exportLinks[t]?(e.downloadUrl=e.exportLinks[t],e.title=e.title+"."+s,e.mimeType=t):e.exportLinks["application/pdf"]&&(e.downloadUrl=e.exportLinks["application/pdf"],e.title=e.title+".pdf",e.mimeType="application/pdf"))};if(e&&!e.downloadUrl&&e.mimeType&&e.exportLinks)switch(e.mimeType.toString().toLowerCase()){case"application/vnd.google-apps.document":s(e,"application/vnd.openxmlformats-officedocument.wordprocessingml.document","docx");break;case"application/vnd.google-apps.spreadsheet":s(e,"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","xlsx");break;case"application/vnd.google-apps.drawing":s(e,"image/png","png");break;case"application/vnd.google-apps.presentation":s(e,"application/vnd.openxmlformats-officedocument.presentationml.presentation","pptx");break;default:s(e,"application/pdf","pdf")}e&&e.downloadUrl&&i.addDriveAttachment(e,t)}}),o.send()}},_.prototype.driveCreatePiker=function(t){if(e.gapi&&t&&t.access_token){var s=this;e.gapi.load("picker",{callback:function(){if(e.google&&e.google.picker){var i=(new e.google.picker.PickerBuilder).addView((new e.google.picker.DocsView).setIncludeFolders(!0)).setAppId(jt.settingsGet("GoogleClientID")).setOAuthToken(t.access_token).setCallback(r.bind(s.driveCallback,s,t.access_token)).enableFeature(e.google.picker.Feature.NAV_HIDDEN).build();i.setVisible(!0)}}})}},_.prototype.driveOpenPopup=function(){if(e.gapi){var t=this;e.gapi.load("auth",{callback:function(){var s=e.gapi.auth.getToken();s?t.driveCreatePiker(s):e.gapi.auth.authorize({client_id:jt.settingsGet("GoogleClientID"),scope:"https://www.googleapis.com/auth/drive.readonly",immediate:!0},function(s){if(s&&!s.error){var i=e.gapi.auth.getToken();i&&t.driveCreatePiker(i)}else e.gapi.auth.authorize({client_id:jt.settingsGet("GoogleClientID"),scope:"https://www.googleapis.com/auth/drive.readonly",immediate:!1},function(s){if(s&&!s.error){var i=e.gapi.auth.getToken();i&&t.driveCreatePiker(i)}})})}})}},_.prototype.getAttachmentById=function(e){for(var t=this.attachments(),s=0,i=t.length;i>s;s++)if(t[s]&&e===t[s].id)return t[s];return null},_.prototype.initUploader=function(){if(this.composeUploaderButton()){var e={},t=Mt.pInt(jt.settingsGet("AttachmentLimit")),s=new a({action:jt.link().upload(),name:"uploader",queueSize:2,multipleSizeLimit:50,disableFolderDragAndDrop:!1,clickElement:this.composeUploaderButton(),dragAndDropElement:this.composeUploaderDropPlace()});s?(s.on("onDragEnter",r.bind(function(){this.dragAndDropOver(!0)},this)).on("onDragLeave",r.bind(function(){this.dragAndDropOver(!1)},this)).on("onBodyDragEnter",r.bind(function(){this.dragAndDropVisible(!0)},this)).on("onBodyDragLeave",r.bind(function(){this.dragAndDropVisible(!1)},this)).on("onProgress",r.bind(function(t,s,i){var o=null;Mt.isUnd(e[t])?(o=this.getAttachmentById(t),o&&(e[t]=o)):o=e[t],o&&o.progress(" - "+Math.floor(s/i*100)+"%")},this)).on("onSelect",r.bind(function(e,i){this.dragAndDropOver(!1);var o=this,n=Mt.isUnd(i.FileName)?"":i.FileName.toString(),a=Mt.isNormal(i.Size)?Mt.pInt(i.Size):null,r=new A(e,n,a);return r.cancel=function(e){return function(){o.attachments.remove(function(t){return t&&t.id===e}),s&&s.cancel(e)}}(e),this.attachments.push(r),a>0&&t>0&&a>t?(r.error(Mt.i18n("UPLOAD/ERROR_FILE_IS_TOO_BIG")),!1):!0},this)).on("onStart",r.bind(function(t){var s=null;Mt.isUnd(e[t])?(s=this.getAttachmentById(t),s&&(e[t]=s)):s=e[t],s&&(s.waiting(!1),s.uploading(!0))},this)).on("onComplete",r.bind(function(t,s,i){var o="",n=null,a=null,r=this.getAttachmentById(t);a=s&&i&&i.Result&&i.Result.Attachment?i.Result.Attachment:null,n=i&&i.Result&&i.Result.ErrorCode?i.Result.ErrorCode:null,null!==n?o=Mt.getUploadErrorDescByCode(n):a||(o=Mt.i18n("UPLOAD/ERROR_UNKNOWN")),r&&(""!==o&&00&&o>0&&n>o?(s.uploading(!1),s.error(Mt.i18n("UPLOAD/ERROR_FILE_IS_TOO_BIG")),!1):(jt.remote().composeUploadExternals(function(e,t){var i=!1;s.uploading(!1),Lt.StorageResultType.Success===e&&t&&t.Result&&t.Result[s.id]&&(i=!0,s.tempName(t.Result[s.id])),i||s.error(Mt.getUploadErrorDescByCode(Lt.UploadErrorCode.FileNoUploaded))},[e.link]),!0)},_.prototype.addDriveAttachment=function(e,t){var s=this,i=function(e){return function(){s.attachments.remove(function(t){return t&&t.id===e})}},o=Mt.pInt(jt.settingsGet("AttachmentLimit")),n=null,a=e.fileSize?Mt.pInt(e.fileSize):0;return n=new A(e.downloadUrl,e.title,a),n.fromMessage=!1,n.cancel=i(e.downloadUrl),n.waiting(!1).uploading(!0),this.attachments.push(n),a>0&&o>0&&a>o?(n.uploading(!1),n.error(Mt.i18n("UPLOAD/ERROR_FILE_IS_TOO_BIG")),!1):(jt.remote().composeUploadDrive(function(e,t){var s=!1;n.uploading(!1),Lt.StorageResultType.Success===e&&t&&t.Result&&t.Result[n.id]&&(s=!0,n.tempName(t.Result[n.id][0]),n.size(Mt.pInt(t.Result[n.id][1]))),s||n.error(Mt.getUploadErrorDescByCode(Lt.UploadErrorCode.FileNoUploaded))},e.downloadUrl,t),!0)},_.prototype.prepearMessageAttachments=function(e,t){if(e){var s=this,i=Mt.isNonEmptyArray(e.attachments())?e.attachments():[],o=0,n=i.length,a=null,r=null,l=!1,c=function(e){return function(){s.attachments.remove(function(t){return t&&t.id===e})}};if(Lt.ComposeType.ForwardAsAttachment===t)this.addMessageAsAttachment(e);else for(;n>o;o++){switch(r=i[o],l=!1,t){case Lt.ComposeType.Reply:case Lt.ComposeType.ReplyAll:l=r.isLinked;break;case Lt.ComposeType.Forward:case Lt.ComposeType.Draft:case Lt.ComposeType.EditAsNew:l=!0}l&&(a=new A(r.download,r.fileName,r.estimatedSize,r.isInline,r.isLinked,r.cid,r.contentLocation),a.fromMessage=!0,a.cancel=c(r.download),a.waiting(!1).uploading(!0),this.attachments.push(a))}}},_.prototype.removeLinkedAttachments=function(){this.attachments.remove(function(e){return e&&e.isLinked})},_.prototype.setMessageAttachmentFailedDowbloadText=function(){r.each(this.attachments(),function(e){e&&e.fromMessage&&e.waiting(!1).uploading(!1).error(Mt.getUploadErrorDescByCode(Lt.UploadErrorCode.FileNoUploaded))},this)},_.prototype.isEmptyForm=function(e){e=Mt.isUnd(e)?!0:!!e;var t=e?0===this.attachments().length:0===this.attachmentsInReady().length;return 0===this.to().length&&0===this.cc().length&&0===this.bcc().length&&0===this.subject().length&&t&&(!this.oEditor||""===this.oEditor.getData())},_.prototype.reset=function(){this.to(""),this.cc(""),this.bcc(""),this.replyTo(""),this.subject(""),this.requestReadReceipt(!1),this.aDraftInfo=null,this.sInReplyTo="",this.bFromDraft=!1,this.sReferences="",this.sendError(!1),this.sendSuccessButSaveError(!1),this.savedError(!1),this.savedTime(0),this.savedOrSendingText(""),this.emptyToError(!1),this.attachmentsInProcessError(!1),this.showCcAndBcc(!1),this.attachments([]),this.dragAndDropOver(!1),this.dragAndDropVisible(!1),this.draftFolder(""),this.draftUid(""),this.sending(!1),this.saving(!1),this.oEditor&&this.oEditor.clear(!1)},_.prototype.getAttachmentsDownloadsForUpload=function(){return r.map(r.filter(this.attachments(),function(e){return e&&""===e.tempName()}),function(e){return e.id})},_.prototype.triggerForResize=function(){this.resizer(!this.resizer()),this.editorResizeThrottle()},Mt.extendAsViewModel("PopupsContactsViewModel",U),U.prototype.getPropertyPlceholder=function(e){var t="";
+switch(e){case Lt.ContactPropertyType.LastName:t="CONTACTS/PLACEHOLDER_ENTER_LAST_NAME";break;case Lt.ContactPropertyType.FirstName:t="CONTACTS/PLACEHOLDER_ENTER_FIRST_NAME";break;case Lt.ContactPropertyType.Nick:t="CONTACTS/PLACEHOLDER_ENTER_NICK_NAME"}return t},U.prototype.addNewProperty=function(e,t){this.viewProperties.push(new w(e,t||"","",!0,this.getPropertyPlceholder(e)))},U.prototype.addNewOrFocusProperty=function(e,t){var s=r.find(this.viewProperties(),function(t){return e===t.type()});s?s.focused(!0):this.addNewProperty(e,t)},U.prototype.addNewTag=function(){this.viewTags.visibility(!0),this.viewTags.focusTrigger(!0)},U.prototype.addNewEmail=function(){this.addNewProperty(Lt.ContactPropertyType.Email,"Home")},U.prototype.addNewPhone=function(){this.addNewProperty(Lt.ContactPropertyType.Phone,"Mobile")},U.prototype.addNewWeb=function(){this.addNewProperty(Lt.ContactPropertyType.Web)},U.prototype.addNewNickname=function(){this.addNewOrFocusProperty(Lt.ContactPropertyType.Nick)},U.prototype.addNewNotes=function(){this.addNewOrFocusProperty(Lt.ContactPropertyType.Note)},U.prototype.addNewBirthday=function(){this.addNewOrFocusProperty(Lt.ContactPropertyType.Birthday)},U.prototype.exportVcf=function(){jt.download(jt.link().exportContactsVcf())},U.prototype.exportCsv=function(){jt.download(jt.link().exportContactsCsv())},U.prototype.initUploader=function(){if(this.importUploaderButton()){var t=new a({action:jt.link().uploadContacts(),name:"uploader",queueSize:1,multipleSizeLimit:1,disableFolderDragAndDrop:!0,disableDragAndDrop:!0,disableMultiple:!0,disableDocumentDropPrevent:!0,clickElement:this.importUploaderButton()});t&&t.on("onStart",r.bind(function(){this.contacts.importing(!0)},this)).on("onComplete",r.bind(function(t,s,i){this.contacts.importing(!1),this.reloadContactList(),t&&s&&i&&i.Result||e.alert(Mt.i18n("CONTACTS/ERROR_IMPORT_FILE"))},this))}},U.prototype.removeCheckedOrSelectedContactsFromList=function(){var e=this,t=this.contacts,s=this.currentContact(),i=this.contacts().length,o=this.contactsCheckedOrSelected();0=i&&(this.bDropPageAfterDelete=!0),r.delay(function(){r.each(o,function(e){t.remove(e)})},500))},U.prototype.deleteSelectedContacts=function(){00?i:0),Mt.isNonEmptyArray(s.Result.Tags)&&(n=r.map(s.Result.Tags,function(e){var t=new T;return t.parse(e)?t:null}),n=r.compact(n))),t.contactsCount(i),t.contacts(o),t.contacts.loading(!1),t.contactTags(n),t.viewClearSearch(""!==t.search())},s,It.Defaults.ContactsPerPage,this.search())},U.prototype.onBuild=function(e){this.oContentVisible=t(".b-list-content",e),this.oContentScrollable=t(".content",this.oContentVisible),this.selector.init(this.oContentVisible,this.oContentScrollable,Lt.KeyState.ContactList);var i=this;c("delete",Lt.KeyState.ContactList,function(){return i.deleteCommand(),!1}),e.on("click",".e-pagenator .e-page",function(){var e=s.dataFor(this);e&&(i.contactsPage(Mt.pInt(e.value)),i.reloadContactList())}),this.initUploader()},U.prototype.onShow=function(){xt.routeOff(),this.reloadContactList(!0)},U.prototype.onHide=function(){xt.routeOn(),this.currentContact(null),this.emptySelection(!0),this.search(""),this.contactsCount(0),this.contacts([])},Mt.extendAsViewModel("PopupsAdvancedSearchViewModel",x),x.prototype.buildSearchStringValue=function(e){return-1 li"),o=s&&("tab"===s.shortcut||"right"===s.shortcut),n=i.index(i.filter(".active"));return!o&&n>0?n--:o&&n-1&&r.eq(n).removeClass("focused"),38===a&&n>0?n--:40===a&&no)?(this.oContentScrollable.scrollTop(i.top<0?this.oContentScrollable.scrollTop()+i.top-e:this.oContentScrollable.scrollTop()+i.top-o+n+e),!0):!1},et.prototype.messagesDrop=function(e,t){if(e&&t&&t.helper){var s=t.helper.data("rl-folder"),i=Bt.hasClass("rl-ctrl-key-pressed"),o=t.helper.data("rl-uids");Mt.isNormal(s)&&""!==s&&Mt.isArray(o)&&jt.moveMessagesToFolder(s,o,e.fullNameRaw,i)}},et.prototype.composeClick=function(){xt.showScreenPopup(_)},et.prototype.createFolder=function(){xt.showScreenPopup(k)},et.prototype.configureFolders=function(){xt.setHash(jt.link().settings("folders"))},et.prototype.contactsClick=function(){this.allowContacts&&xt.showScreenPopup(U)},Mt.extendAsViewModel("MailBoxMessageListViewModel",tt),tt.prototype.emptySubjectValue="",tt.prototype.searchEnterAction=function(){this.mainMessageListSearch(this.sLastSearchValue),this.inputMessageListSearchFocus(!1)},tt.prototype.printableMessageCountForDeletion=function(){var e=this.messageListCheckedOrSelectedUidsWithSubMails().length;return e>1?" ("+(100>e?e:"99+")+")":""},tt.prototype.cancelSearch=function(){this.mainMessageListSearch(""),this.inputMessageListSearchFocus(!1)},tt.prototype.moveSelectedMessagesToFolder=function(e,t){return this.canBeMoved()&&jt.moveMessagesToFolder(jt.data().currentFolderFullNameRaw(),jt.data().messageListCheckedOrSelectedUidsWithSubMails(),e,t),!1},tt.prototype.dragAndDronHelper=function(e){e&&e.checked(!0);var t=Mt.draggeblePlace(),s=jt.data().messageListCheckedOrSelectedUidsWithSubMails();return t.data("rl-folder",jt.data().currentFolderFullNameRaw()),t.data("rl-uids",s),t.find(".text").text(""+s.length),r.defer(function(){var e=jt.data().messageListCheckedOrSelectedUidsWithSubMails();t.data("rl-uids",e),t.find(".text").text(""+e.length)}),t},tt.prototype.onMessageResponse=function(e,t,s){var i=jt.data();i.hideMessageBodies(),i.messageLoading(!1),Lt.StorageResultType.Success===e&&t&&t.Result?i.setMessage(t,s):Lt.StorageResultType.Unload===e?(i.message(null),i.messageError("")):Lt.StorageResultType.Abort!==e&&(i.message(null),i.messageError(Mt.getNotification(t&&t.ErrorCode?t.ErrorCode:Lt.Notification.UnknownError)))},tt.prototype.populateMessageBody=function(e){e&&(jt.remote().message(this.onMessageResponse,e.folderFullNameRaw,e.uid)?jt.data().messageLoading(!0):Mt.log("Error: Unknown message request: "+e.folderFullNameRaw+" ~ "+e.uid+" [e-101]"))},tt.prototype.setAction=function(e,t,s){var i=[],o=null,n=jt.cache(),a=0;if(Mt.isUnd(s)&&(s=jt.data().messageListChecked()),i=r.map(s,function(e){return e.uid}),""!==e&&00?100>e?e:"99+":""},st.prototype.verifyPgpSignedClearMessage=function(e){e&&e.verifyPgpSignedClearMessage()},st.prototype.decryptPgpEncryptedMessage=function(e){e&&e.decryptPgpEncryptedMessage(this.viewPgpPassword())},st.prototype.readReceipt=function(e){e&&""!==e.readReceipt()&&(jt.remote().sendReadReceiptMessage(Mt.emptyFunction,e.folderFullNameRaw,e.uid,e.readReceipt(),Mt.i18n("READ_RECEIPT/SUBJECT",{SUBJECT:e.subject()}),Mt.i18n("READ_RECEIPT/BODY",{"READ-RECEIPT":jt.data().accountEmail()})),e.isReadReceipt(!0),jt.cache().storeMessageFlagsToCache(e),jt.reloadFlagsCurrentMessageListAndMessageFromCache())},Mt.extendAsViewModel("SettingsMenuViewModel",it),it.prototype.link=function(e){return jt.link().settings(e)},it.prototype.backToMailBoxClick=function(){xt.setHash(jt.link().inbox())},Mt.extendAsViewModel("SettingsPaneViewModel",ot),ot.prototype.onBuild=function(){var e=this;c("esc",Lt.KeyState.Settings,function(){e.backToMailBoxClick()})},ot.prototype.onShow=function(){jt.data().message(null)},ot.prototype.backToMailBoxClick=function(){xt.setHash(jt.link().inbox())},Mt.addSettingsViewModel(nt,"SettingsGeneral","SETTINGS_LABELS/LABEL_GENERAL_NAME","general",!0),nt.prototype.toggleLayout=function(){this.layout(Lt.Layout.NoPreview===this.layout()?Lt.Layout.SidePreview:Lt.Layout.NoPreview)},nt.prototype.onBuild=function(){var e=this;r.delay(function(){var s=jt.data(),i=Mt.settingsSaveHelperSimpleFunction(e.mppTrigger,e);s.language.subscribe(function(s){e.languageTrigger(Lt.SaveSettingsStep.Animate),t.ajax({url:jt.link().langLink(s),dataType:"script",cache:!0}).done(function(){Mt.i18nToDoc(),e.languageTrigger(Lt.SaveSettingsStep.TrueResult)}).fail(function(){e.languageTrigger(Lt.SaveSettingsStep.FalseResult)}).always(function(){r.delay(function(){e.languageTrigger(Lt.SaveSettingsStep.Idle)},1e3)}),jt.remote().saveSettings(Mt.emptyFunction,{Language:s})}),s.editorDefaultType.subscribe(function(e){jt.remote().saveSettings(Mt.emptyFunction,{EditorDefaultType:e})}),s.messagesPerPage.subscribe(function(e){jt.remote().saveSettings(i,{MPP:e})}),s.showImages.subscribe(function(e){jt.remote().saveSettings(Mt.emptyFunction,{ShowImages:e?"1":"0"})}),s.interfaceAnimation.subscribe(function(e){jt.remote().saveSettings(Mt.emptyFunction,{InterfaceAnimation:e})}),s.useDesktopNotifications.subscribe(function(e){Mt.timeOutAction("SaveDesktopNotifications",function(){jt.remote().saveSettings(Mt.emptyFunction,{DesktopNotifications:e?"1":"0"})},3e3)}),s.replySameFolder.subscribe(function(e){Mt.timeOutAction("SaveReplySameFolder",function(){jt.remote().saveSettings(Mt.emptyFunction,{ReplySameFolder:e?"1":"0"})},3e3)}),s.useThreads.subscribe(function(e){s.messageList([]),jt.remote().saveSettings(Mt.emptyFunction,{UseThreads:e?"1":"0"})}),s.layout.subscribe(function(e){s.messageList([]),jt.remote().saveSettings(Mt.emptyFunction,{Layout:e})}),s.useCheckboxesInList.subscribe(function(e){jt.remote().saveSettings(Mt.emptyFunction,{UseCheckboxesInList:e?"1":"0"})})},50)},nt.prototype.onShow=function(){jt.data().desktopNotifications.valueHasMutated()},nt.prototype.selectLanguage=function(){xt.showScreenPopup(j)},Mt.addSettingsViewModel(at,"SettingsContacts","SETTINGS_LABELS/LABEL_CONTACTS_NAME","contacts"),at.prototype.onBuild=function(){jt.data().contactsAutosave.subscribe(function(e){jt.remote().saveSettings(Mt.emptyFunction,{ContactsAutosave:e?"1":"0"})})},Mt.addSettingsViewModel(rt,"SettingsAccounts","SETTINGS_LABELS/LABEL_ACCOUNTS_NAME","accounts"),rt.prototype.addNewAccount=function(){xt.showScreenPopup(V)},rt.prototype.deleteAccount=function(t){if(t&&t.deleteAccess()){this.accountForDeletion(null);var s=function(e){return t===e};t&&(this.accounts.remove(s),jt.remote().accountDelete(function(t,s){Lt.StorageResultType.Success===t&&s&&s.Result&&s.Reload?(xt.routeOff(),xt.setHash(jt.link().root(),!0),xt.routeOff(),r.defer(function(){e.location.reload()})):jt.accountsAndIdentities()},t.email))}},Mt.addSettingsViewModel(lt,"SettingsIdentity","SETTINGS_LABELS/LABEL_IDENTITY_NAME","identity"),lt.prototype.onFocus=function(){if(!this.editor&&this.signatureDom()){var e=this,t=jt.data().signature();this.editor=new d(e.signatureDom(),function(){jt.data().signature((e.editor.isHtml()?":HTML:":"")+e.editor.getData())},function(){":HTML:"===t.substr(0,6)?e.editor.setHtml(t.substr(6),!1):e.editor.setPlain(t,!1)})}},lt.prototype.onBuild=function(){var e=this;r.delay(function(){var t=jt.data(),s=Mt.settingsSaveHelperSimpleFunction(e.displayNameTrigger,e),i=Mt.settingsSaveHelperSimpleFunction(e.replyTrigger,e),o=Mt.settingsSaveHelperSimpleFunction(e.signatureTrigger,e);t.displayName.subscribe(function(e){jt.remote().saveSettings(s,{DisplayName:e})}),t.replyTo.subscribe(function(e){jt.remote().saveSettings(i,{ReplyTo:e})}),t.signature.subscribe(function(e){jt.remote().saveSettings(o,{Signature:e})}),t.signatureToAll.subscribe(function(e){jt.remote().saveSettings(null,{SignatureToAll:e?"1":"0"})})},50)},Mt.addSettingsViewModel(ct,"SettingsIdentities","SETTINGS_LABELS/LABEL_IDENTITIES_NAME","identities"),ct.prototype.formattedAccountIdentity=function(){var e=this.displayName.peek(),t=this.accountEmail.peek();return""===e?t:'"'+Mt.quoteName(e)+'" <'+t+">"},ct.prototype.addNewIdentity=function(){xt.showScreenPopup(q)},ct.prototype.editIdentity=function(e){xt.showScreenPopup(q,[e])},ct.prototype.deleteIdentity=function(e){if(e&&e.deleteAccess()){this.identityForDeletion(null);var t=function(t){return e===t};e&&(this.identities.remove(t),jt.remote().identityDelete(function(){jt.accountsAndIdentities()},e.id))}},ct.prototype.onFocus=function(){if(!this.editor&&this.signatureDom()){var e=this,t=jt.data().signature();this.editor=new d(e.signatureDom(),function(){jt.data().signature((e.editor.isHtml()?":HTML:":"")+e.editor.getData())},function(){":HTML:"===t.substr(0,6)?e.editor.setHtml(t.substr(6),!1):e.editor.setPlain(t,!1)})}},ct.prototype.onBuild=function(e){var t=this;e.on("click",".identity-item .e-action",function(){var e=s.dataFor(this);e&&t.editIdentity(e)}),r.delay(function(){var e=jt.data(),s=Mt.settingsSaveHelperSimpleFunction(t.displayNameTrigger,t),i=Mt.settingsSaveHelperSimpleFunction(t.replyTrigger,t),o=Mt.settingsSaveHelperSimpleFunction(t.signatureTrigger,t),n=Mt.settingsSaveHelperSimpleFunction(t.defaultIdentityIDTrigger,t);e.defaultIdentityID.subscribe(function(e){jt.remote().saveSettings(n,{DefaultIdentityID:e})}),e.displayName.subscribe(function(e){jt.remote().saveSettings(s,{DisplayName:e})}),e.replyTo.subscribe(function(e){jt.remote().saveSettings(i,{ReplyTo:e})}),e.signature.subscribe(function(e){jt.remote().saveSettings(o,{Signature:e})}),e.signatureToAll.subscribe(function(e){jt.remote().saveSettings(null,{SignatureToAll:e?"1":"0"})})},50)},Mt.addSettingsViewModel(ut,"SettingsFilters","SETTINGS_LABELS/LABEL_FILTERS_NAME","filters"),ut.prototype.deleteFilter=function(e){this.filters.remove(e)},ut.prototype.addFilter=function(){xt.showScreenPopup(Y,[new P])},Mt.addSettingsViewModel(dt,"SettingsSecurity","SETTINGS_LABELS/LABEL_SECURITY_NAME","security"),dt.prototype.showSecret=function(){this.secreting(!0),jt.remote().showTwoFactorSecret(this.onSecretResult)},dt.prototype.hideSecret=function(){this.viewSecret(""),this.viewBackupCodes(""),this.viewUrl("")},dt.prototype.createTwoFactor=function(){this.processing(!0),jt.remote().createTwoFactor(this.onResult)},dt.prototype.enableTwoFactor=function(){this.processing(!0),jt.remote().enableTwoFactor(this.onResult,this.viewEnable())},dt.prototype.testTwoFactor=function(){xt.showScreenPopup(z)},dt.prototype.clearTwoFactor=function(){this.viewSecret(""),this.viewBackupCodes(""),this.viewUrl(""),this.clearing(!0),jt.remote().clearTwoFactor(this.onResult)},dt.prototype.onShow=function(){this.viewSecret(""),this.viewBackupCodes(""),this.viewUrl("")},dt.prototype.onResult=function(e,t){if(this.processing(!1),this.clearing(!1),Lt.StorageResultType.Success===e&&t&&t.Result?(this.viewUser(Mt.pString(t.Result.User)),this.viewEnable(!!t.Result.Enable),this.twoFactorStatus(!!t.Result.IsSet),this.viewSecret(Mt.pString(t.Result.Secret)),this.viewBackupCodes(Mt.pString(t.Result.BackupCodes).replace(/[\s]+/g," ")),this.viewUrl(Mt.pString(t.Result.Url))):(this.viewUser(""),this.viewEnable(!1),this.twoFactorStatus(!1),this.viewSecret(""),this.viewBackupCodes(""),this.viewUrl("")),this.bFirst){this.bFirst=!1;var s=this;this.viewEnable.subscribe(function(e){this.viewEnable.subs&&jt.remote().enableTwoFactor(function(e,t){Lt.StorageResultType.Success===e&&t&&t.Result||(s.viewEnable.subs=!1,s.viewEnable(!1),s.viewEnable.subs=!0)},e)},this)}},dt.prototype.onSecretResult=function(e,t){this.secreting(!1),Lt.StorageResultType.Success===e&&t&&t.Result?(this.viewSecret(Mt.pString(t.Result.Secret)),this.viewUrl(Mt.pString(t.Result.Url))):(this.viewSecret(""),this.viewUrl(""))},dt.prototype.onBuild=function(){this.processing(!0),jt.remote().getTwoFactor(this.onResult)},Mt.addSettingsViewModel(ht,"SettingsSocial","SETTINGS_LABELS/LABEL_SOCIAL_NAME","social"),Mt.addSettingsViewModel(pt,"SettingsChangePassword","SETTINGS_LABELS/LABEL_CHANGE_PASSWORD_NAME","change-password"),pt.prototype.onHide=function(){this.changeProcess(!1),this.currentPassword(""),this.newPassword(""),this.newPassword2(""),this.errorDescription(""),this.passwordMismatch(!1),this.currentPassword.error(!1)},pt.prototype.onChangePasswordResponse=function(e,t){this.changeProcess(!1),this.passwordMismatch(!1),this.errorDescription(""),this.currentPassword.error(!1),Lt.StorageResultType.Success===e&&t&&t.Result?(this.currentPassword(""),this.newPassword(""),this.newPassword2(""),this.passwordUpdateSuccess(!0),this.currentPassword.error(!1)):(t&&Lt.Notification.CurrentPasswordIncorrect===t.ErrorCode&&this.currentPassword.error(!0),this.passwordUpdateError(!0),this.errorDescription(Mt.getNotification(t&&t.ErrorCode?t.ErrorCode:Lt.Notification.CouldNotSaveNewPassword)))},Mt.addSettingsViewModel(mt,"SettingsFolders","SETTINGS_LABELS/LABEL_FOLDERS_NAME","folders"),mt.prototype.folderEditOnEnter=function(e){var t=e?Mt.trim(e.nameForEdit()):"";""!==t&&e.name()!==t&&(jt.local().set(Lt.ClientSideKeyName.FoldersLashHash,""),jt.data().foldersRenaming(!0),jt.remote().folderRename(function(e,t){jt.data().foldersRenaming(!1),Lt.StorageResultType.Success===e&&t&&t.Result||jt.data().foldersListError(t&&t.ErrorCode?Mt.getNotification(t.ErrorCode):Mt.i18n("NOTIFICATIONS/CANT_RENAME_FOLDER")),jt.folders()},e.fullNameRaw,t),jt.cache().removeFolderFromCacheList(e.fullNameRaw),e.name(t)),e.edited(!1)},mt.prototype.folderEditOnEsc=function(e){e&&e.edited(!1)},mt.prototype.onShow=function(){jt.data().foldersListError("")},mt.prototype.createFolder=function(){xt.showScreenPopup(k)},mt.prototype.systemFolder=function(){xt.showScreenPopup(O)},mt.prototype.deleteFolder=function(e){if(e&&e.canBeDeleted()&&e.deleteAccess()&&0===e.privateMessageCountAll()){this.folderForDeletion(null);var t=function(s){return e===s?!0:(s.subFolders.remove(t),!1)};e&&(jt.local().set(Lt.ClientSideKeyName.FoldersLashHash,""),jt.data().folderList.remove(t),jt.data().foldersDeleting(!0),jt.remote().folderDelete(function(e,t){jt.data().foldersDeleting(!1),Lt.StorageResultType.Success===e&&t&&t.Result||jt.data().foldersListError(t&&t.ErrorCode?Mt.getNotification(t.ErrorCode):Mt.i18n("NOTIFICATIONS/CANT_DELETE_FOLDER")),jt.folders()},e.fullNameRaw),jt.cache().removeFolderFromCacheList(e.fullNameRaw))}else 00&&(s=this.messagesBodiesDom(),s&&(s.find(".rl-cache-class").each(function(){var s=t(this);i>s.data("rl-cache-count")&&(s.addClass("rl-cache-purge"),e++)}),e>0&&r.delay(function(){s.find(".rl-cache-purge").remove()},300)))},yt.prototype.populateDataOnStart=function(){bt.prototype.populateDataOnStart.call(this),this.accountEmail(jt.settingsGet("Email")),this.accountIncLogin(jt.settingsGet("IncLogin")),this.accountOutLogin(jt.settingsGet("OutLogin")),this.projectHash(jt.settingsGet("ProjectHash")),this.defaultIdentityID(jt.settingsGet("DefaultIdentityID")),this.displayName(jt.settingsGet("DisplayName")),this.replyTo(jt.settingsGet("ReplyTo")),this.signature(jt.settingsGet("Signature")),this.signatureToAll(!!jt.settingsGet("SignatureToAll")),this.enableTwoFactor(!!jt.settingsGet("EnableTwoFactor")),this.lastFoldersHash=jt.local().get(Lt.ClientSideKeyName.FoldersLashHash)||"",this.remoteSuggestions=!!jt.settingsGet("RemoteSuggestions"),this.devEmail=jt.settingsGet("DevEmail"),this.devPassword=jt.settingsGet("DevPassword")},yt.prototype.initUidNextAndNewMessages=function(t,s,i){if("INBOX"===t&&Mt.isNormal(s)&&""!==s){if(Mt.isArray(i)&&03)l(jt.link().notificationMailIcon(),jt.data().accountEmail(),Mt.i18n("MESSAGE_LIST/NEW_MESSAGE_NOTIFICATION",{COUNT:a}));else for(;a>n;n++)l(jt.link().notificationMailIcon(),E.emailsToLine(E.initEmailsFromJson(i[n].From),!1),i[n].Subject)}jt.cache().setFolderUidNext(t,s)}},yt.prototype.folderResponseParseRec=function(e,t){var s=0,i=0,o=null,n=null,a="",r=[],l=[];for(s=0,i=t.length;i>s;s++)o=t[s],o&&(a=o.FullNameRaw,n=jt.cache().getFolderFromCacheList(a),n||(n=N.newInstanceFromJson(o),n&&(jt.cache().setFolderToCacheList(a,n),jt.cache().setFolderFullNameRaw(n.fullNameHash,a))),n&&(n.collapsed(!Mt.isFolderExpanded(n.fullNameHash)),o.Extended&&(o.Extended.Hash&&jt.cache().setFolderHash(n.fullNameRaw,o.Extended.Hash),Mt.isNormal(o.Extended.MessageCount)&&n.messageCountAll(o.Extended.MessageCount),Mt.isNormal(o.Extended.MessageUnseenCount)&&n.messageCountUnread(o.Extended.MessageUnseenCount)),r=o.SubFolders,r&&"Collection/FolderCollection"===r["@Object"]&&r["@Collection"]&&Mt.isArray(r["@Collection"])&&n.subFolders(this.folderResponseParseRec(e,r["@Collection"])),l.push(n)));return l},yt.prototype.setFolders=function(e){var t=[],s=!1,i=jt.data(),o=function(e){return""===e||It.Values.UnuseOptionValue===e||null!==jt.cache().getFolderFromCacheList(e)?e:""};e&&e.Result&&"Collection/FolderCollection"===e.Result["@Object"]&&e.Result["@Collection"]&&Mt.isArray(e.Result["@Collection"])&&(Mt.isUnd(e.Result.Namespace)||(i.namespace=e.Result.Namespace),this.threading(!!jt.settingsGet("UseImapThread")&&e.Result.IsThreadsSupported&&!0),t=this.folderResponseParseRec(i.namespace,e.Result["@Collection"]),i.folderList(t),e.Result.SystemFolders&&""==""+jt.settingsGet("SentFolder")+jt.settingsGet("DraftFolder")+jt.settingsGet("SpamFolder")+jt.settingsGet("TrashFolder")+jt.settingsGet("ArchiveFolder")+jt.settingsGet("NullFolder")&&(jt.settingsSet("SentFolder",e.Result.SystemFolders[2]||null),jt.settingsSet("DraftFolder",e.Result.SystemFolders[3]||null),jt.settingsSet("SpamFolder",e.Result.SystemFolders[4]||null),jt.settingsSet("TrashFolder",e.Result.SystemFolders[5]||null),jt.settingsSet("ArchiveFolder",e.Result.SystemFolders[12]||null),s=!0),i.sentFolder(o(jt.settingsGet("SentFolder"))),i.draftFolder(o(jt.settingsGet("DraftFolder"))),i.spamFolder(o(jt.settingsGet("SpamFolder"))),i.trashFolder(o(jt.settingsGet("TrashFolder"))),i.archiveFolder(o(jt.settingsGet("ArchiveFolder"))),s&&jt.remote().saveSystemFolders(Mt.emptyFunction,{SentFolder:i.sentFolder(),DraftFolder:i.draftFolder(),SpamFolder:i.spamFolder(),TrashFolder:i.trashFolder(),ArchiveFolder:i.archiveFolder(),NullFolder:"NullFolder"}),jt.local().set(Lt.ClientSideKeyName.FoldersLashHash,e.Result.FoldersHash))},yt.prototype.hideMessageBodies=function(){var e=this.messagesBodiesDom();e&&e.find(".b-text-part").hide()},yt.prototype.getNextFolderNames=function(e){e=Mt.isUnd(e)?!1:!!e;var t=[],s=10,i=n().unix(),o=i-300,a=[],l=function(t){r.each(t,function(t){t&&"INBOX"!==t.fullNameRaw&&t.selectable&&t.existen&&o>t.interval&&(!e||t.subScribed())&&a.push([t.interval,t.fullNameRaw]),t&&0t[0]?1:0}),r.find(a,function(e){var o=jt.cache().getFolderFromCacheList(e[1]);return o&&(o.interval=i,t.push(e[1])),s<=t.length}),r.uniq(t)},yt.prototype.removeMessagesFromList=function(e,t,s,i){s=Mt.isNormal(s)?s:"",i=Mt.isUnd(i)?!1:!!i,t=r.map(t,function(e){return Mt.pInt(e)});var o=0,n=jt.data(),a=jt.cache(),l=n.messageList(),c=jt.cache().getFolderFromCacheList(e),u=""===s?null:a.getFolderFromCacheList(s||""),d=n.currentFolderFullNameRaw(),h=n.message(),p=d===e?r.filter(l,function(e){return e&&-10&&c.messageCountUnread(0<=c.messageCountUnread()-o?c.messageCountUnread()-o:0)),u&&(u.messageCountAll(u.messageCountAll()+t.length),o>0&&u.messageCountUnread(u.messageCountUnread()+o),u.actionBlink(!0)),0 ').hide().addClass("rl-cache-class"),a.data("rl-cache-count",++Ot.iMessageBodyCacheCount),Mt.isNormal(e.Result.Html)&&""!==e.Result.Html?(i=!0,c=e.Result.Html.toString()):Mt.isNormal(e.Result.Plain)&&""!==e.Result.Plain?(i=!1,c=Mt.plainToHtml(e.Result.Plain.toString(),!1),(p.isPgpSigned()||p.isPgpEncrypted())&&jt.data().capaOpenPGP()&&(p.plainRaw=Mt.pString(e.Result.Plain),d=/---BEGIN PGP MESSAGE---/.test(p.plainRaw),d||(u=/-----BEGIN PGP SIGNED MESSAGE-----/.test(p.plainRaw)&&/-----BEGIN PGP SIGNATURE-----/.test(p.plainRaw)),zt.empty(),u&&p.isPgpSigned()?c=zt.append(t('').text(p.plainRaw)).html():d&&p.isPgpEncrypted()&&(c=zt.append(t('').text(p.plainRaw)).html()),zt.empty(),p.isPgpSigned(u),p.isPgpEncrypted(d))):i=!1,a.html(Mt.linkify(c)).addClass("b-text-part "+(i?"html":"plain")),p.isHtml(!!i),p.hasImages(!!o),p.pgpSignedVerifyStatus(Lt.SignedVerifyStatus.None),p.pgpSignedVerifyUser(""),p.body=a,p.body&&h.append(p.body),p.storeDataToDom(),n&&p.showInternalImages(!0),p.hasImages()&&this.showImages()&&p.showExternalImages(!0),this.purgeMessageBodyCacheThrottle()),this.messageActiveDom(p.body),this.hideMessageBodies(),p.body.show(),a&&Mt.initBlockquoteSwitcher(a)),jt.cache().initMessageFlagsFromCache(p),p.unseen()&&jt.setMessageSeen(p),Mt.windowResize())},yt.prototype.calculateMessageListHash=function(e){return r.map(e,function(e){return""+e.hash+"_"+e.threadsLen()+"_"+e.flagHash()}).join("|")},yt.prototype.setMessageList=function(e,t){if(e&&e.Result&&"Collection/MessageCollection"===e.Result["@Object"]&&e.Result["@Collection"]&&Mt.isArray(e.Result["@Collection"])){var s=jt.data(),i=jt.cache(),o=null,a=0,r=0,l=0,c=0,u=[],d=n().unix(),h=s.staticMessageList,p=null,m=null,g=null,f=0,b=!1;for(l=Mt.pInt(e.Result.MessageResultCount),c=Mt.pInt(e.Result.Offset),Mt.isNonEmptyArray(e.Result.LastCollapsedThreadUids)&&(o=e.Result.LastCollapsedThreadUids),g=jt.cache().getFolderFromCacheList(Mt.isNormal(e.Result.Folder)?e.Result.Folder:""),g&&!t&&(g.interval=d,jt.cache().setFolderHash(e.Result.Folder,e.Result.FolderHash),Mt.isNormal(e.Result.MessageCount)&&g.messageCountAll(e.Result.MessageCount),Mt.isNormal(e.Result.MessageUnseenCount)&&(Mt.pInt(g.messageCountUnread())!==Mt.pInt(e.Result.MessageUnseenCount)&&(b=!0),g.messageCountUnread(e.Result.MessageUnseenCount)),this.initUidNextAndNewMessages(g.fullNameRaw,e.Result.UidNext,e.Result.NewMessages)),b&&g&&jt.cache().clearMessageFlagsFromCacheByFolder(g.fullNameRaw),a=0,r=e.Result["@Collection"].length;r>a;a++)p=e.Result["@Collection"][a],p&&"Object/Message"===p["@Object"]&&(m=h[a],m&&m.initByJson(p)||(m=E.newInstanceFromJson(p)),m&&(i.hasNewMessageAndRemoveFromCache(m.folderFullNameRaw,m.uid)&&5>=f&&(f++,m.newForAnimation(!0)),m.deleted(!1),t?jt.cache().initMessageFlagsFromCache(m):jt.cache().storeMessageFlagsToCache(m),m.lastInCollapsedThread(o&&-1(new e.Date).getTime()-d),p&&l.oRequests[p]&&(l.oRequests[p].__aborted&&(o="abort"),l.oRequests[p]=null),l.defaultResponse(s,p,o,t,n,i)}),p&&00?(this.defaultRequest(e,"Message",{},null,"Message/"+kt.urlsafe_encode([t,s,jt.data().projectHash(),jt.data().threading()&&jt.data().useThreads()?"1":"0"].join(String.fromCharCode(0))),["Message"]),!0):!1},vt.prototype.composeUploadExternals=function(e,t){this.defaultRequest(e,"ComposeUploadExternals",{Externals:t},999e3)},vt.prototype.composeUploadDrive=function(e,t,s){this.defaultRequest(e,"ComposeUploadDrive",{AccessToken:s,Url:t},999e3)},vt.prototype.folderInformation=function(e,t,s){var i=!0,o=jt.cache(),n=[];Mt.isArray(s)&&0 ").addClass("rl-settings-view-model").hide(),l.appendTo(a),o.data=jt.data(),o.viewModelDom=l,o.__rlSettingsData=n.__rlSettingsData,n.__dom=l,n.__builded=!0,n.__vm=o,s.applyBindingAccessorsToNode(l[0],{i18nInit:!0,template:function(){return{name:n.__rlSettingsData.Template}}},o),Mt.delegateRun(o,"onBuild",[l])):Mt.log("Cannot find sub settings view model position: SettingsSubScreen")),o&&r.defer(function(){i.oCurrentSubScreen&&(Mt.delegateRun(i.oCurrentSubScreen,"onHide"),i.oCurrentSubScreen.viewModelDom.hide()),i.oCurrentSubScreen=o,i.oCurrentSubScreen&&(i.oCurrentSubScreen.viewModelDom.show(),Mt.delegateRun(i.oCurrentSubScreen,"onShow"),Mt.delegateRun(i.oCurrentSubScreen,"onFocus",[],200),r.each(i.menu(),function(e){e.selected(o&&o.__rlSettingsData&&e.route===o.__rlSettingsData.Route)}),t("#rl-content .b-settings .b-content .content").scrollTop(0)),Mt.windowResize()})):xt.setHash(jt.link().settings(),!1,!0)},Tt.prototype.onHide=function(){this.oCurrentSubScreen&&this.oCurrentSubScreen.viewModelDom&&(Mt.delegateRun(this.oCurrentSubScreen,"onHide"),this.oCurrentSubScreen.viewModelDom.hide())},Tt.prototype.onBuild=function(){r.each(_t.settings,function(e){e&&e.__rlSettingsData&&!r.find(_t["settings-removed"],function(t){return t&&t===e})&&this.menu.push({route:e.__rlSettingsData.Route,label:e.__rlSettingsData.Label,selected:s.observable(!1),disabled:!!r.find(_t["settings-disabled"],function(t){return t&&t===e})})},this),this.oViewModelPlace=t("#rl-content #rl-settings-subscreen")},Tt.prototype.routes=function(){var e=r.find(_t.settings,function(e){return e&&e.__rlSettingsData&&e.__rlSettingsData.IsDefault}),t=e?e.__rlSettingsData.Route:"general",s={subname:/^(.*)$/,normalize_:function(e,s){return s.subname=Mt.isUnd(s.subname)?t:Mt.pString(s.subname),[s.subname]}};return[["{subname}/",s],["{subname}",s],["",s]]},r.extend(Ft.prototype,y.prototype),Ft.prototype.onShow=function(){jt.setTitle("")},r.extend(At.prototype,y.prototype),At.prototype.oLastRoute={},At.prototype.setNewTitle=function(){var e=jt.data().accountEmail(),t=jt.data().foldersInboxUnreadCount();jt.setTitle((""===e?"":(t>0?"("+t+") ":" ")+e+" - ")+Mt.i18n("TITLES/MAILBOX"))},At.prototype.onShow=function(){this.setNewTitle(),jt.data().keyScope(Lt.KeyState.MessageList)},At.prototype.onRoute=function(e,t,s,i){if(Mt.isUnd(i)?1:!i){var o=jt.data(),n=jt.cache().getFolderFullNameRaw(e),a=jt.cache().getFolderFromCacheList(n);a&&(o.currentFolder(a).messageListPage(t).messageListSearch(s),Lt.Layout.NoPreview===o.layout()&&o.message()&&o.message(null),jt.reloadMessageList())}else Lt.Layout.NoPreview!==jt.data().layout()||jt.data().message()||jt.historyBack()},At.prototype.onStart=function(){var e=jt.data(),t=function(){Mt.windowResize()};(jt.capa(Lt.Capa.AdditionalAccounts)||jt.capa(Lt.Capa.AdditionalIdentities))&&jt.accountsAndIdentities(),r.delay(function(){"INBOX"!==e.currentFolderFullNameRaw()&&jt.folderInformation("INBOX")},1e3),r.delay(function(){jt.quota()},5e3),r.delay(function(){jt.remote().appDelayStart(Mt.emptyFunction)},35e3),Bt.toggleClass("rl-no-preview-pane",Lt.Layout.NoPreview===e.layout()),e.folderList.subscribe(t),e.messageList.subscribe(t),e.message.subscribe(t),e.layout.subscribe(function(e){Bt.toggleClass("rl-no-preview-pane",Lt.Layout.NoPreview===e)}),e.foldersInboxUnreadCount.subscribe(function(){this.setNewTitle()},this)},At.prototype.routes=function(){var e=function(){return["Inbox",1,"",!0]},t=function(e,t){return t[0]=Mt.pString(t[0]),t[1]=Mt.pInt(t[1]),t[1]=0>=t[1]?1:t[1],t[2]=Mt.pString(t[2]),""===e&&(t[0]="Inbox",t[1]=1),[decodeURI(t[0]),t[1],decodeURI(t[2]),!1]},s=function(e,t){return t[0]=Mt.pString(t[0]),t[1]=Mt.pString(t[1]),""===e&&(t[0]="Inbox"),[decodeURI(t[0]),1,decodeURI(t[1]),!1]};return[[/^([a-zA-Z0-9]+)\/p([1-9][0-9]*)\/(.+)\/?$/,{normalize_:t}],[/^([a-zA-Z0-9]+)\/p([1-9][0-9]*)$/,{normalize_:t}],[/^([a-zA-Z0-9]+)\/(.+)\/?$/,{normalize_:s}],[/^message-preview$/,{normalize_:e}],[/^([^\/]*)$/,{normalize_:t}]]},r.extend(Et.prototype,Tt.prototype),Et.prototype.onShow=function(){jt.setTitle(this.sSettingsTitle),jt.data().keyScope(Lt.KeyState.Settings)},r.extend(Nt.prototype,f.prototype),Nt.prototype.oSettings=null,Nt.prototype.oPlugins=null,Nt.prototype.oLocal=null,Nt.prototype.oLink=null,Nt.prototype.oSubs={},Nt.prototype.download=function(t){var s=null,i=null,o=navigator.userAgent.toLowerCase();return o&&(o.indexOf("chrome")>-1||o.indexOf("chrome")>-1)&&(s=document.createElement("a"),s.href=t,document.createEvent&&(i=document.createEvent("MouseEvents"),i&&i.initEvent&&s.dispatchEvent))?(i.initEvent("click",!0,!0),s.dispatchEvent(i),!0):(Ot.bMobileDevice?(e.open(t,"_self"),e.focus()):this.iframe.attr("src",t),!0)},Nt.prototype.link=function(){return null===this.oLink&&(this.oLink=new u),this.oLink},Nt.prototype.local=function(){return null===this.oLocal&&(this.oLocal=new g),this.oLocal},Nt.prototype.settingsGet=function(e){return null===this.oSettings&&(this.oSettings=Mt.isNormal(Vt)?Vt:{}),Mt.isUnd(this.oSettings[e])?null:this.oSettings[e]},Nt.prototype.settingsSet=function(e,t){null===this.oSettings&&(this.oSettings=Mt.isNormal(Vt)?Vt:{}),this.oSettings[e]=t},Nt.prototype.setTitle=function(t){t=(Mt.isNormal(t)&&0d;d++)f.push({id:o[d][0],name:o[d][1],system:!1,seporator:!1,disabled:!1});for(m=!0,d=0,h=t.length;h>d;d++)p=t[d],(r?r.call(null,p):!0)&&(m&&0d;d++)p=s[d],(p.subScribed()||!p.existen)&&(r?r.call(null,p):!0)&&(Lt.FolderType.User===p.type()||!c||0=5?o:20,o=320>=o?o:320,e.setInterval(function(){jt.contactsSync()},6e4*o+5e3),r.delay(function(){jt.contactsSync()},5e3),r.delay(function(){jt.folderInformationMultiply(!0)},500),Dt.runHook("rl-start-user-screens"),jt.pub("rl.bootstart-user-screens"),jt.settingsGet("AccountSignMe")&&e.navigator.registerProtocolHandler&&r.delay(function(){try{e.navigator.registerProtocolHandler("mailto",e.location.protocol+"//"+e.location.host+e.location.pathname+"?mailto&to=%s",""+(jt.settingsGet("Title")||"RainLoop"))}catch(t){}jt.settingsGet("MailToEmail")&&jt.mailToHelper(jt.settingsGet("MailToEmail"))},500)):(xt.startScreens([Ft]),Dt.runHook("rl-start-login-screens"),jt.pub("rl.bootstart-login-screens")),e.SimplePace&&e.SimplePace.set(100),Ot.bMobileDevice||r.defer(function(){Mt.initLayoutResizer("#rl-left","#rl-right",Lt.ClientSideKeyName.FolderListSize)})},this))):(s=Mt.pString(jt.settingsGet("CustomLoginLink")),s?(xt.routeOff(),xt.setHash(jt.link().root(),!0),xt.routeOff(),r.defer(function(){e.location.href=s})):(xt.hideLoading(),xt.startScreens([Ft]),Dt.runHook("rl-start-login-screens"),jt.pub("rl.bootstart-login-screens"),e.SimplePace&&e.SimplePace.set(100))),n&&(e["rl_"+i+"_google_service"]=function(){jt.data().googleActions(!0),jt.socialUsers()}),a&&(e["rl_"+i+"_facebook_service"]=function(){jt.data().facebookActions(!0),jt.socialUsers()}),l&&(e["rl_"+i+"_twitter_service"]=function(){jt.data().twitterActions(!0),jt.socialUsers()}),jt.sub("interval.1m",function(){Ot.momentTrigger(!Ot.momentTrigger())}),Dt.runHook("rl-start-screens"),jt.pub("rl.bootstart-end")},jt=new Rt,Bt.addClass(Ot.bMobileDevice?"mobile":"no-mobile"),Gt.keydown(Mt.killCtrlAandS).keyup(Mt.killCtrlAandS),Gt.unload(function(){Ot.bUnload=!0}),Bt.on("click.dropdown.data-api",function(){Mt.detectDropdownVisibility()}),e.rl=e.rl||{},e.rl.addHook=Dt.addHook,e.rl.settingsGet=Dt.mainSettingsGet,e.rl.remoteRequest=Dt.remoteRequest,e.rl.pluginSettingsGet=Dt.settingsGet,e.rl.addSettingsViewModel=Mt.addSettingsViewModel,e.rl.createCommand=Mt.createCommand,e.rl.EmailModel=v,e.rl.Enums=Lt,e.__RLBOOT=function(s){t(function(){e.rainloopTEMPLATES&&e.rainloopTEMPLATES[0]?(t("#rl-templates").html(e.rainloopTEMPLATES[0]),r.delay(function(){e.rainloopAppData={},e.rainloopI18N={},e.rainloopTEMPLATES={},xt.setBoot(jt).bootstart(),Bt.removeClass("no-js rl-booted-trigger").addClass("rl-booted")},50)):s(!1),e.__RLBOOT=null})}}(window,jQuery,ko,crossroads,hasher,moment,Jua,_,ifvisible,key);
\ No newline at end of file
diff --git a/rainloop/v/0.0.0/static/js/admin.js b/rainloop/v/0.0.0/static/js/admin.js
index a667aebcd..0a3363557 100644
--- a/rainloop/v/0.0.0/static/js/admin.js
+++ b/rainloop/v/0.0.0/static/js/admin.js
@@ -1,9275 +1,6663 @@
/*! RainLoop Webmail Admin Module (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
(function (window, $, ko, crossroads, hasher, _) {
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-'use strict';
+(function (module) {
+
+ 'use strict';
+
+ var
+ Globals = {},
+ window = require('../External/window.js'),
+ ko = require('../External/ko.js'),
+ $html = require('../External/$html.js')
+ ;
-var
/**
- * @type {Object}
+ * @type {?}
*/
- Consts = {},
+ Globals.now = (new window.Date()).getTime();
+
+ /**
+ * @type {?}
+ */
+ Globals.momentTrigger = ko.observable(true);
+
+ /**
+ * @type {?}
+ */
+ Globals.dropdownVisibility = ko.observable(false).extend({'rateLimit': 0});
+
+ /**
+ * @type {?}
+ */
+ Globals.tooltipTrigger = ko.observable(false).extend({'rateLimit': 0});
+
+ /**
+ * @type {?}
+ */
+ Globals.langChangeTrigger = ko.observable(true);
+
+ /**
+ * @type {number}
+ */
+ Globals.iAjaxErrorCount = 0;
+
+ /**
+ * @type {number}
+ */
+ Globals.iTokenErrorCount = 0;
+
+ /**
+ * @type {number}
+ */
+ Globals.iMessageBodyCacheCount = 0;
+
+ /**
+ * @type {boolean}
+ */
+ Globals.bUnload = false;
+
+ /**
+ * @type {string}
+ */
+ Globals.sUserAgent = (window.navigator.userAgent || '').toLowerCase();
+
+ /**
+ * @type {boolean}
+ */
+ Globals.bIsiOSDevice = -1 < Globals.sUserAgent.indexOf('iphone') || -1 < Globals.sUserAgent.indexOf('ipod') || -1 < Globals.sUserAgent.indexOf('ipad');
+
+ /**
+ * @type {boolean}
+ */
+ Globals.bIsAndroidDevice = -1 < Globals.sUserAgent.indexOf('android');
+
+ /**
+ * @type {boolean}
+ */
+ Globals.bMobileDevice = Globals.bIsiOSDevice || Globals.bIsAndroidDevice;
+
+ /**
+ * @type {boolean}
+ */
+ Globals.bDisableNanoScroll = Globals.bMobileDevice;
+
+ /**
+ * @type {boolean}
+ */
+ Globals.bAllowPdfPreview = !Globals.bMobileDevice;
+
+ /**
+ * @type {boolean}
+ */
+ Globals.bAnimationSupported = !Globals.bMobileDevice && $html.hasClass('csstransitions');
+
+ /**
+ * @type {boolean}
+ */
+ Globals.bXMLHttpRequestSupported = !!window.XMLHttpRequest;
+
+ /**
+ * @type {string}
+ */
+ Globals.sAnimationType = '';
/**
* @type {Object}
*/
- Enums = {},
+ Globals.oHtmlEditorDefaultConfig = {
+ 'title': false,
+ 'stylesSet': false,
+ 'customConfig': '',
+ 'contentsCss': '',
+ 'toolbarGroups': [
+ {name: 'spec'},
+ {name: 'styles'},
+ {name: 'basicstyles', groups: ['basicstyles', 'cleanup']},
+ {name: 'colors'},
+ {name: 'paragraph', groups: ['list', 'indent', 'blocks', 'align']},
+ {name: 'links'},
+ {name: 'insert'},
+ {name: 'others'}
+ // {name: 'document', groups: ['mode', 'document', 'doctools']}
+ ],
+
+ 'removePlugins': 'contextmenu', //blockquote
+ 'removeButtons': 'Format,Undo,Redo,Cut,Copy,Paste,Anchor,Strike,Subscript,Superscript,Image,SelectAll',
+ 'removeDialogTabs': 'link:advanced;link:target;image:advanced;images:advanced',
+
+ 'extraPlugins': 'plain',
+
+ 'allowedContent': true,
+ 'autoParagraph': false,
+
+ 'font_defaultLabel': 'Arial',
+ 'fontSize_defaultLabel': '13',
+ 'fontSize_sizes': '10/10px;12/12px;13/13px;14/14px;16/16px;18/18px;20/20px;24/24px;28/28px;36/36px;48/48px'
+ };
/**
* @type {Object}
*/
- NotificationI18N = {},
+ Globals.oHtmlEditorLangsMap = {
+ 'de': 'de',
+ 'es': 'es',
+ 'fr': 'fr',
+ 'hu': 'hu',
+ 'is': 'is',
+ 'it': 'it',
+ 'ko': 'ko',
+ 'ko-kr': 'ko',
+ 'lv': 'lv',
+ 'nl': 'nl',
+ 'no': 'no',
+ 'pl': 'pl',
+ 'pt': 'pt',
+ 'pt-pt': 'pt',
+ 'pt-br': 'pt-br',
+ 'ru': 'ru',
+ 'ro': 'ro',
+ 'zh': 'zh',
+ 'zh-cn': 'zh-cn'
+ };
- /**
- * @type {Object.}
- */
- Utils = {},
+ if (Globals.bAllowPdfPreview && window.navigator && window.navigator.mimeTypes)
+ {
+ Globals.bAllowPdfPreview = !!_.find(window.navigator.mimeTypes, function (oType) {
+ return oType && 'application/pdf' === oType.type;
+ });
+ }
- /**
- * @type {Object.}
- */
- Plugins = {},
-
- /**
- * @type {Object.}
- */
- Base64 = {},
-
- /**
- * @type {Object}
- */
- Globals = {},
-
- /**
- * @type {Object}
- */
- ViewModels = {
+ Globals.oI18N = {},
+
+ Globals.oNotificationI18N = {},
+
+ Globals.aBootstrapDropdowns = [],
+
+ Globals.aViewModels = {
'settings': [],
'settings-removed': [],
'settings-disabled': []
- },
+ };
+
+ module.exports = Globals;
+
+}(module));
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var Enums = {};
/**
- * @type {Array}
+ * @enum {string}
*/
- BootstrapDropdowns = [],
+ Enums.StorageResultType = {
+ 'Success': 'success',
+ 'Abort': 'abort',
+ 'Error': 'error',
+ 'Unload': 'unload'
+ };
/**
- * @type {*}
+ * @enum {number}
*/
- kn = null,
+ Enums.State = {
+ 'Empty': 10,
+ 'Login': 20,
+ 'Auth': 30
+ };
/**
- * @type {Object}
+ * @enum {number}
*/
- AppData = window['rainloopAppData'] || {},
+ Enums.StateType = {
+ 'Webmail': 0,
+ 'Admin': 1
+ };
/**
- * @type {Object}
+ * @enum {string}
*/
- I18n = window['rainloopI18N'] || {},
+ Enums.Capa = {
+ 'Prem': 'PREM',
+ 'TwoFactor': 'TWO_FACTOR',
+ 'OpenPGP': 'OPEN_PGP',
+ 'Prefetch': 'PREFETCH',
+ 'Gravatar': 'GRAVATAR',
+ 'Themes': 'THEMES',
+ 'Filters': 'FILTERS',
+ 'AdditionalAccounts': 'ADDITIONAL_ACCOUNTS',
+ 'AdditionalIdentities': 'ADDITIONAL_IDENTITIES'
+ };
- $html = $('html'),
+ /**
+ * @enum {string}
+ */
+ Enums.KeyState = {
+ 'All': 'all',
+ 'None': 'none',
+ 'ContactList': 'contact-list',
+ 'MessageList': 'message-list',
+ 'FolderList': 'folder-list',
+ 'MessageView': 'message-view',
+ 'Compose': 'compose',
+ 'Settings': 'settings',
+ 'Menu': 'menu',
+ 'PopupComposeOpenPGP': 'compose-open-pgp',
+ 'PopupKeyboardShortcutsHelp': 'popup-keyboard-shortcuts-help',
+ 'PopupAsk': 'popup-ask'
+ };
-// $body = $('body'),
+ /**
+ * @enum {number}
+ */
+ Enums.FolderType = {
+ 'Inbox': 10,
+ 'SentItems': 11,
+ 'Draft': 12,
+ 'Trash': 13,
+ 'Spam': 14,
+ 'Archive': 15,
+ 'NotSpam': 80,
+ 'User': 99
+ };
- $window = $(window),
+ /**
+ * @enum {string}
+ */
+ Enums.LoginSignMeTypeAsString = {
+ 'DefaultOff': 'defaultoff',
+ 'DefaultOn': 'defaulton',
+ 'Unused': 'unused'
+ };
- $document = $(window.document),
+ /**
+ * @enum {number}
+ */
+ Enums.LoginSignMeType = {
+ 'DefaultOff': 0,
+ 'DefaultOn': 1,
+ 'Unused': 2
+ };
- NotificationClass = window.Notification && window.Notification.requestPermission ? window.Notification : null
-;
+ /**
+ * @enum {string}
+ */
+ Enums.ComposeType = {
+ 'Empty': 'empty',
+ 'Reply': 'reply',
+ 'ReplyAll': 'replyall',
+ 'Forward': 'forward',
+ 'ForwardAsAttachment': 'forward-as-attachment',
+ 'Draft': 'draft',
+ 'EditAsNew': 'editasnew'
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.UploadErrorCode = {
+ 'Normal': 0,
+ 'FileIsTooBig': 1,
+ 'FilePartiallyUploaded': 2,
+ 'FileNoUploaded': 3,
+ 'MissingTempFolder': 4,
+ 'FileOnSaveingError': 5,
+ 'FileType': 98,
+ 'Unknown': 99
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.SetSystemFoldersNotification = {
+ 'None': 0,
+ 'Sent': 1,
+ 'Draft': 2,
+ 'Spam': 3,
+ 'Trash': 4,
+ 'Archive': 5
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.ClientSideKeyName = {
+ 'FoldersLashHash': 0,
+ 'MessagesInboxLastHash': 1,
+ 'MailBoxListSize': 2,
+ 'ExpandedFolders': 3,
+ 'FolderListSize': 4
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.EventKeyCode = {
+ 'Backspace': 8,
+ 'Tab': 9,
+ 'Enter': 13,
+ 'Esc': 27,
+ 'PageUp': 33,
+ 'PageDown': 34,
+ 'Left': 37,
+ 'Right': 39,
+ 'Up': 38,
+ 'Down': 40,
+ 'End': 35,
+ 'Home': 36,
+ 'Space': 32,
+ 'Insert': 45,
+ 'Delete': 46,
+ 'A': 65,
+ 'S': 83
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.MessageSetAction = {
+ 'SetSeen': 0,
+ 'UnsetSeen': 1,
+ 'SetFlag': 2,
+ 'UnsetFlag': 3
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.MessageSelectAction = {
+ 'All': 0,
+ 'None': 1,
+ 'Invert': 2,
+ 'Unseen': 3,
+ 'Seen': 4,
+ 'Flagged': 5,
+ 'Unflagged': 6
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.DesktopNotifications = {
+ 'Allowed': 0,
+ 'NotAllowed': 1,
+ 'Denied': 2,
+ 'NotSupported': 9
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.MessagePriority = {
+ 'Low': 5,
+ 'Normal': 3,
+ 'High': 1
+ };
+
+ /**
+ * @enum {string}
+ */
+ Enums.EditorDefaultType = {
+ 'Html': 'Html',
+ 'Plain': 'Plain'
+ };
+
+ /**
+ * @enum {string}
+ */
+ Enums.CustomThemeType = {
+ 'Light': 'Light',
+ 'Dark': 'Dark'
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.ServerSecure = {
+ 'None': 0,
+ 'SSL': 1,
+ 'TLS': 2
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.SearchDateType = {
+ 'All': -1,
+ 'Days3': 3,
+ 'Days7': 7,
+ 'Month': 30
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.EmailType = {
+ 'Defailt': 0,
+ 'Facebook': 1,
+ 'Google': 2
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.SaveSettingsStep = {
+ 'Animate': -2,
+ 'Idle': -1,
+ 'TrueResult': 1,
+ 'FalseResult': 0
+ };
+
+ /**
+ * @enum {string}
+ */
+ Enums.InterfaceAnimation = {
+ 'None': 'None',
+ 'Normal': 'Normal',
+ 'Full': 'Full'
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.Layout = {
+ 'NoPreview': 0,
+ 'SidePreview': 1,
+ 'BottomPreview': 2
+ };
+
+ /**
+ * @enum {string}
+ */
+ Enums.FilterConditionField = {
+ 'From': 'From',
+ 'To': 'To',
+ 'Recipient': 'Recipient',
+ 'Subject': 'Subject'
+ };
+
+ /**
+ * @enum {string}
+ */
+ Enums.FilterConditionType = {
+ 'Contains': 'Contains',
+ 'NotContains': 'NotContains',
+ 'EqualTo': 'EqualTo',
+ 'NotEqualTo': 'NotEqualTo'
+ };
+
+ /**
+ * @enum {string}
+ */
+ Enums.FiltersAction = {
+ 'None': 'None',
+ 'Move': 'Move',
+ 'Discard': 'Discard',
+ 'Forward': 'Forward',
+ };
+
+ /**
+ * @enum {string}
+ */
+ Enums.FilterRulesType = {
+ 'And': 'And',
+ 'Or': 'Or'
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.SignedVerifyStatus = {
+ 'UnknownPublicKeys': -4,
+ 'UnknownPrivateKey': -3,
+ 'Unverified': -2,
+ 'Error': -1,
+ 'None': 0,
+ 'Success': 1
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.ContactPropertyType = {
+
+ 'Unknown': 0,
+
+ 'FullName': 10,
+
+ 'FirstName': 15,
+ 'LastName': 16,
+ 'MiddleName': 16,
+ 'Nick': 18,
+
+ 'NamePrefix': 20,
+ 'NameSuffix': 21,
+
+ 'Email': 30,
+ 'Phone': 31,
+ 'Web': 32,
+
+ 'Birthday': 40,
+
+ 'Facebook': 90,
+ 'Skype': 91,
+ 'GitHub': 92,
+
+ 'Note': 110,
+
+ 'Custom': 250
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.Notification = {
+ 'InvalidToken': 101,
+ 'AuthError': 102,
+ 'AccessError': 103,
+ 'ConnectionError': 104,
+ 'CaptchaError': 105,
+ 'SocialFacebookLoginAccessDisable': 106,
+ 'SocialTwitterLoginAccessDisable': 107,
+ 'SocialGoogleLoginAccessDisable': 108,
+ 'DomainNotAllowed': 109,
+ 'AccountNotAllowed': 110,
+
+ 'AccountTwoFactorAuthRequired': 120,
+ 'AccountTwoFactorAuthError': 121,
+
+ 'CouldNotSaveNewPassword': 130,
+ 'CurrentPasswordIncorrect': 131,
+ 'NewPasswordShort': 132,
+ 'NewPasswordWeak': 133,
+ 'NewPasswordForbidden': 134,
+
+ 'ContactsSyncError': 140,
+
+ 'CantGetMessageList': 201,
+ 'CantGetMessage': 202,
+ 'CantDeleteMessage': 203,
+ 'CantMoveMessage': 204,
+ 'CantCopyMessage': 205,
+
+ 'CantSaveMessage': 301,
+ 'CantSendMessage': 302,
+ 'InvalidRecipients': 303,
+
+ 'CantCreateFolder': 400,
+ 'CantRenameFolder': 401,
+ 'CantDeleteFolder': 402,
+ 'CantSubscribeFolder': 403,
+ 'CantUnsubscribeFolder': 404,
+ 'CantDeleteNonEmptyFolder': 405,
+
+ 'CantSaveSettings': 501,
+ 'CantSavePluginSettings': 502,
+
+ 'DomainAlreadyExists': 601,
+
+ 'CantInstallPackage': 701,
+ 'CantDeletePackage': 702,
+ 'InvalidPluginPackage': 703,
+ 'UnsupportedPluginPackage': 704,
+
+ 'LicensingServerIsUnavailable': 710,
+ 'LicensingExpired': 711,
+ 'LicensingBanned': 712,
+
+ 'DemoSendMessageError': 750,
+
+ 'AccountAlreadyExists': 801,
+
+ 'MailServerError': 901,
+ 'ClientViewError': 902,
+ 'InvalidInputArgument': 903,
+ 'UnknownNotification': 999,
+ 'UnknownError': 999
+ };
+
+ module.exports = Enums;
+
+}(module));
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-/*jshint onevar: false*/
-/**
- * @type {?AdminApp}
- */
-var RL = null;
-/*jshint onevar: true*/
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @type {?}
- */
-Globals.now = (new Date()).getTime();
-
-/**
- * @type {?}
- */
-Globals.momentTrigger = ko.observable(true);
-
-/**
- * @type {?}
- */
-Globals.dropdownVisibility = ko.observable(false).extend({'rateLimit': 0});
-
-/**
- * @type {?}
- */
-Globals.tooltipTrigger = ko.observable(false).extend({'rateLimit': 0});
-
-/**
- * @type {?}
- */
-Globals.langChangeTrigger = ko.observable(true);
-
-/**
- * @type {number}
- */
-Globals.iAjaxErrorCount = 0;
-
-/**
- * @type {number}
- */
-Globals.iTokenErrorCount = 0;
-
-/**
- * @type {number}
- */
-Globals.iMessageBodyCacheCount = 0;
-
-/**
- * @type {boolean}
- */
-Globals.bUnload = false;
-
-/**
- * @type {string}
- */
-Globals.sUserAgent = (navigator.userAgent || '').toLowerCase();
-
-/**
- * @type {boolean}
- */
-Globals.bIsiOSDevice = -1 < Globals.sUserAgent.indexOf('iphone') || -1 < Globals.sUserAgent.indexOf('ipod') || -1 < Globals.sUserAgent.indexOf('ipad');
-
-/**
- * @type {boolean}
- */
-Globals.bIsAndroidDevice = -1 < Globals.sUserAgent.indexOf('android');
-
-/**
- * @type {boolean}
- */
-Globals.bMobileDevice = Globals.bIsiOSDevice || Globals.bIsAndroidDevice;
-
-/**
- * @type {boolean}
- */
-Globals.bDisableNanoScroll = Globals.bMobileDevice;
-
-/**
- * @type {boolean}
- */
-Globals.bAllowPdfPreview = !Globals.bMobileDevice;
-
-/**
- * @type {boolean}
- */
-Globals.bAnimationSupported = !Globals.bMobileDevice && $html.hasClass('csstransitions');
-
-/**
- * @type {boolean}
- */
-Globals.bXMLHttpRequestSupported = !!window.XMLHttpRequest;
-
-/**
- * @type {string}
- */
-Globals.sAnimationType = '';
-
-/**
- * @type {Object}
- */
-Globals.oHtmlEditorDefaultConfig = {
- 'title': false,
- 'stylesSet': false,
- 'customConfig': '',
- 'contentsCss': '',
- 'toolbarGroups': [
- {name: 'spec'},
- {name: 'styles'},
- {name: 'basicstyles', groups: ['basicstyles', 'cleanup']},
- {name: 'colors'},
- {name: 'paragraph', groups: ['list', 'indent', 'blocks', 'align']},
- {name: 'links'},
- {name: 'insert'},
- {name: 'others'}
-// {name: 'document', groups: ['mode', 'document', 'doctools']}
- ],
-
- 'removePlugins': 'contextmenu', //blockquote
- 'removeButtons': 'Format,Undo,Redo,Cut,Copy,Paste,Anchor,Strike,Subscript,Superscript,Image,SelectAll',
- 'removeDialogTabs': 'link:advanced;link:target;image:advanced;images:advanced',
-
- 'extraPlugins': 'plain',
-
- 'allowedContent': true,
- 'autoParagraph': false,
-
- 'font_defaultLabel': 'Arial',
- 'fontSize_defaultLabel': '13',
- 'fontSize_sizes': '10/10px;12/12px;13/13px;14/14px;16/16px;18/18px;20/20px;24/24px;28/28px;36/36px;48/48px'
-};
-
-/**
- * @type {Object}
- */
-Globals.oHtmlEditorLangsMap = {
- 'de': 'de',
- 'es': 'es',
- 'fr': 'fr',
- 'hu': 'hu',
- 'is': 'is',
- 'it': 'it',
- 'ko': 'ko',
- 'ko-kr': 'ko',
- 'lv': 'lv',
- 'nl': 'nl',
- 'no': 'no',
- 'pl': 'pl',
- 'pt': 'pt',
- 'pt-pt': 'pt',
- 'pt-br': 'pt-br',
- 'ru': 'ru',
- 'ro': 'ro',
- 'zh': 'zh',
- 'zh-cn': 'zh-cn'
-};
-
-if (Globals.bAllowPdfPreview && navigator && navigator.mimeTypes)
-{
- Globals.bAllowPdfPreview = !!_.find(navigator.mimeTypes, function (oType) {
- return oType && 'application/pdf' === oType.type;
- });
-}
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-Consts.Defaults = {};
-Consts.Values = {};
-Consts.DataImages = {};
-
-/**
- * @const
- * @type {number}
- */
-Consts.Defaults.MessagesPerPage = 20;
-
-/**
- * @const
- * @type {number}
- */
-Consts.Defaults.ContactsPerPage = 50;
-
-/**
- * @const
- * @type {Array}
- */
-Consts.Defaults.MessagesPerPageArray = [10, 20, 30, 50, 100/*, 150, 200, 300*/];
-
-/**
- * @const
- * @type {number}
- */
-Consts.Defaults.DefaultAjaxTimeout = 30000;
-
-/**
- * @const
- * @type {number}
- */
-Consts.Defaults.SearchAjaxTimeout = 300000;
-
-/**
- * @const
- * @type {number}
- */
-Consts.Defaults.SendMessageAjaxTimeout = 300000;
-
-/**
- * @const
- * @type {number}
- */
-Consts.Defaults.SaveMessageAjaxTimeout = 200000;
-
-/**
- * @const
- * @type {number}
- */
-Consts.Defaults.ContactsSyncAjaxTimeout = 200000;
-
-/**
- * @const
- * @type {string}
- */
-Consts.Values.UnuseOptionValue = '__UNUSE__';
-
-/**
- * @const
- * @type {string}
- */
-Consts.Values.ClientSideCookieIndexName = 'rlcsc';
-
-/**
- * @const
- * @type {number}
- */
-Consts.Values.ImapDefaulPort = 143;
-
-/**
- * @const
- * @type {number}
- */
-Consts.Values.ImapDefaulSecurePort = 993;
-
-/**
- * @const
- * @type {number}
- */
-Consts.Values.SmtpDefaulPort = 25;
-
-/**
- * @const
- * @type {number}
- */
-Consts.Values.SmtpDefaulSecurePort = 465;
-
-/**
- * @const
- * @type {number}
- */
-Consts.Values.MessageBodyCacheLimit = 15;
-
-/**
- * @const
- * @type {number}
- */
-Consts.Values.AjaxErrorLimit = 7;
-
-/**
- * @const
- * @type {number}
- */
-Consts.Values.TokenErrorLimit = 10;
-
-/**
- * @const
- * @type {string}
- */
-Consts.DataImages.UserDotPic = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQIW2P8DwQACgAD/il4QJ8AAAAASUVORK5CYII=';
-
-/**
- * @const
- * @type {string}
- */
-Consts.DataImages.TranspPic = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQIW2NkAAIAAAoAAggA9GkAAAAASUVORK5CYII=';
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @enum {string}
- */
-Enums.StorageResultType = {
- 'Success': 'success',
- 'Abort': 'abort',
- 'Error': 'error',
- 'Unload': 'unload'
-};
-
-/**
- * @enum {number}
- */
-Enums.State = {
- 'Empty': 10,
- 'Login': 20,
- 'Auth': 30
-};
-
-/**
- * @enum {number}
- */
-Enums.StateType = {
- 'Webmail': 0,
- 'Admin': 1
-};
-
-/**
- * @enum {string}
- */
-Enums.Capa = {
- 'Prem': 'PREM',
- 'TwoFactor': 'TWO_FACTOR',
- 'OpenPGP': 'OPEN_PGP',
- 'Prefetch': 'PREFETCH',
- 'Gravatar': 'GRAVATAR',
- 'Themes': 'THEMES',
- 'Filters': 'FILTERS',
- 'AdditionalAccounts': 'ADDITIONAL_ACCOUNTS',
- 'AdditionalIdentities': 'ADDITIONAL_IDENTITIES'
-};
-
-/**
- * @enum {string}
- */
-Enums.KeyState = {
- 'All': 'all',
- 'None': 'none',
- 'ContactList': 'contact-list',
- 'MessageList': 'message-list',
- 'FolderList': 'folder-list',
- 'MessageView': 'message-view',
- 'Compose': 'compose',
- 'Settings': 'settings',
- 'Menu': 'menu',
- 'PopupComposeOpenPGP': 'compose-open-pgp',
- 'PopupKeyboardShortcutsHelp': 'popup-keyboard-shortcuts-help',
- 'PopupAsk': 'popup-ask'
-};
-
-/**
- * @enum {number}
- */
-Enums.FolderType = {
- 'Inbox': 10,
- 'SentItems': 11,
- 'Draft': 12,
- 'Trash': 13,
- 'Spam': 14,
- 'Archive': 15,
- 'NotSpam': 80,
- 'User': 99
-};
-
-/**
- * @enum {string}
- */
-Enums.LoginSignMeTypeAsString = {
- 'DefaultOff': 'defaultoff',
- 'DefaultOn': 'defaulton',
- 'Unused': 'unused'
-};
-
-/**
- * @enum {number}
- */
-Enums.LoginSignMeType = {
- 'DefaultOff': 0,
- 'DefaultOn': 1,
- 'Unused': 2
-};
-
-/**
- * @enum {string}
- */
-Enums.ComposeType = {
- 'Empty': 'empty',
- 'Reply': 'reply',
- 'ReplyAll': 'replyall',
- 'Forward': 'forward',
- 'ForwardAsAttachment': 'forward-as-attachment',
- 'Draft': 'draft',
- 'EditAsNew': 'editasnew'
-};
-
-/**
- * @enum {number}
- */
-Enums.UploadErrorCode = {
- 'Normal': 0,
- 'FileIsTooBig': 1,
- 'FilePartiallyUploaded': 2,
- 'FileNoUploaded': 3,
- 'MissingTempFolder': 4,
- 'FileOnSaveingError': 5,
- 'FileType': 98,
- 'Unknown': 99
-};
-
-/**
- * @enum {number}
- */
-Enums.SetSystemFoldersNotification = {
- 'None': 0,
- 'Sent': 1,
- 'Draft': 2,
- 'Spam': 3,
- 'Trash': 4,
- 'Archive': 5
-};
-
-/**
- * @enum {number}
- */
-Enums.ClientSideKeyName = {
- 'FoldersLashHash': 0,
- 'MessagesInboxLastHash': 1,
- 'MailBoxListSize': 2,
- 'ExpandedFolders': 3,
- 'FolderListSize': 4
-};
-
-/**
- * @enum {number}
- */
-Enums.EventKeyCode = {
- 'Backspace': 8,
- 'Tab': 9,
- 'Enter': 13,
- 'Esc': 27,
- 'PageUp': 33,
- 'PageDown': 34,
- 'Left': 37,
- 'Right': 39,
- 'Up': 38,
- 'Down': 40,
- 'End': 35,
- 'Home': 36,
- 'Space': 32,
- 'Insert': 45,
- 'Delete': 46,
- 'A': 65,
- 'S': 83
-};
-
-/**
- * @enum {number}
- */
-Enums.MessageSetAction = {
- 'SetSeen': 0,
- 'UnsetSeen': 1,
- 'SetFlag': 2,
- 'UnsetFlag': 3
-};
-
-/**
- * @enum {number}
- */
-Enums.MessageSelectAction = {
- 'All': 0,
- 'None': 1,
- 'Invert': 2,
- 'Unseen': 3,
- 'Seen': 4,
- 'Flagged': 5,
- 'Unflagged': 6
-};
-
-/**
- * @enum {number}
- */
-Enums.DesktopNotifications = {
- 'Allowed': 0,
- 'NotAllowed': 1,
- 'Denied': 2,
- 'NotSupported': 9
-};
-
-/**
- * @enum {number}
- */
-Enums.MessagePriority = {
- 'Low': 5,
- 'Normal': 3,
- 'High': 1
-};
-
-/**
- * @enum {string}
- */
-Enums.EditorDefaultType = {
- 'Html': 'Html',
- 'Plain': 'Plain'
-};
-
-/**
- * @enum {string}
- */
-Enums.CustomThemeType = {
- 'Light': 'Light',
- 'Dark': 'Dark'
-};
-
-/**
- * @enum {number}
- */
-Enums.ServerSecure = {
- 'None': 0,
- 'SSL': 1,
- 'TLS': 2
-};
-
-/**
- * @enum {number}
- */
-Enums.SearchDateType = {
- 'All': -1,
- 'Days3': 3,
- 'Days7': 7,
- 'Month': 30
-};
-
-/**
- * @enum {number}
- */
-Enums.EmailType = {
- 'Defailt': 0,
- 'Facebook': 1,
- 'Google': 2
-};
-
-/**
- * @enum {number}
- */
-Enums.SaveSettingsStep = {
- 'Animate': -2,
- 'Idle': -1,
- 'TrueResult': 1,
- 'FalseResult': 0
-};
-
-/**
- * @enum {string}
- */
-Enums.InterfaceAnimation = {
- 'None': 'None',
- 'Normal': 'Normal',
- 'Full': 'Full'
-};
-
-/**
- * @enum {number}
- */
-Enums.Layout = {
- 'NoPreview': 0,
- 'SidePreview': 1,
- 'BottomPreview': 2
-};
-
-/**
- * @enum {string}
- */
-Enums.FilterConditionField = {
- 'From': 'From',
- 'To': 'To',
- 'Recipient': 'Recipient',
- 'Subject': 'Subject'
-};
-
-/**
- * @enum {string}
- */
-Enums.FilterConditionType = {
- 'Contains': 'Contains',
- 'NotContains': 'NotContains',
- 'EqualTo': 'EqualTo',
- 'NotEqualTo': 'NotEqualTo'
-};
-
-/**
- * @enum {string}
- */
-Enums.FiltersAction = {
- 'None': 'None',
- 'Move': 'Move',
- 'Discard': 'Discard',
- 'Forward': 'Forward',
-};
-
-/**
- * @enum {string}
- */
-Enums.FilterRulesType = {
- 'And': 'And',
- 'Or': 'Or'
-};
-
-/**
- * @enum {number}
- */
-Enums.SignedVerifyStatus = {
- 'UnknownPublicKeys': -4,
- 'UnknownPrivateKey': -3,
- 'Unverified': -2,
- 'Error': -1,
- 'None': 0,
- 'Success': 1
-};
-
-/**
- * @enum {number}
- */
-Enums.ContactPropertyType = {
-
- 'Unknown': 0,
-
- 'FullName': 10,
-
- 'FirstName': 15,
- 'LastName': 16,
- 'MiddleName': 16,
- 'Nick': 18,
-
- 'NamePrefix': 20,
- 'NameSuffix': 21,
-
- 'Email': 30,
- 'Phone': 31,
- 'Web': 32,
-
- 'Birthday': 40,
-
- 'Facebook': 90,
- 'Skype': 91,
- 'GitHub': 92,
-
- 'Note': 110,
-
- 'Custom': 250
-};
-
-/**
- * @enum {number}
- */
-Enums.Notification = {
- 'InvalidToken': 101,
- 'AuthError': 102,
- 'AccessError': 103,
- 'ConnectionError': 104,
- 'CaptchaError': 105,
- 'SocialFacebookLoginAccessDisable': 106,
- 'SocialTwitterLoginAccessDisable': 107,
- 'SocialGoogleLoginAccessDisable': 108,
- 'DomainNotAllowed': 109,
- 'AccountNotAllowed': 110,
-
- 'AccountTwoFactorAuthRequired': 120,
- 'AccountTwoFactorAuthError': 121,
-
- 'CouldNotSaveNewPassword': 130,
- 'CurrentPasswordIncorrect': 131,
- 'NewPasswordShort': 132,
- 'NewPasswordWeak': 133,
- 'NewPasswordForbidden': 134,
-
- 'ContactsSyncError': 140,
-
- 'CantGetMessageList': 201,
- 'CantGetMessage': 202,
- 'CantDeleteMessage': 203,
- 'CantMoveMessage': 204,
- 'CantCopyMessage': 205,
-
- 'CantSaveMessage': 301,
- 'CantSendMessage': 302,
- 'InvalidRecipients': 303,
-
- 'CantCreateFolder': 400,
- 'CantRenameFolder': 401,
- 'CantDeleteFolder': 402,
- 'CantSubscribeFolder': 403,
- 'CantUnsubscribeFolder': 404,
- 'CantDeleteNonEmptyFolder': 405,
-
- 'CantSaveSettings': 501,
- 'CantSavePluginSettings': 502,
-
- 'DomainAlreadyExists': 601,
-
- 'CantInstallPackage': 701,
- 'CantDeletePackage': 702,
- 'InvalidPluginPackage': 703,
- 'UnsupportedPluginPackage': 704,
-
- 'LicensingServerIsUnavailable': 710,
- 'LicensingExpired': 711,
- 'LicensingBanned': 712,
-
- 'DemoSendMessageError': 750,
-
- 'AccountAlreadyExists': 801,
-
- 'MailServerError': 901,
- 'ClientViewError': 902,
- 'InvalidInputArgument': 903,
- 'UnknownNotification': 999,
- 'UnknownError': 999
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-Utils.trim = $.trim;
-Utils.inArray = $.inArray;
-Utils.isArray = _.isArray;
-Utils.isFunc = _.isFunction;
-Utils.isUnd = _.isUndefined;
-Utils.isNull = _.isNull;
-Utils.emptyFunction = function () {};
-
-/**
- * @param {*} oValue
- * @return {boolean}
- */
-Utils.isNormal = function (oValue)
-{
- return !Utils.isUnd(oValue) && !Utils.isNull(oValue);
-};
-
-Utils.windowResize = _.debounce(function (iTimeout) {
- if (Utils.isUnd(iTimeout))
+(function (module) {
+
+ 'use strict';
+
+ var
+ Utils = {},
+
+ $ = require('../External/jquery.js'),
+ _ = require('../External/underscore.js'),
+ ko = require('../External/ko.js'),
+ key = require('../External/key.js'),
+ window = require('../External/window.js'),
+ $window = require('../External/$window.js'),
+ $doc = require('../External/$doc.js'),
+ NotificationClass = require('../External/NotificationClass.js'),
+
+ LocalStorage = require('../Storages/LocalStorage.js'),
+
+ kn = require('../Knoin/Knoin.js'),
+
+ Enums = require('./Enums.js'),
+ Globals = require('./Globals.js')
+ ;
+
+ window.console.log('---');
+ window.console.log(_);
+
+ Utils.trim = $.trim;
+ Utils.inArray = $.inArray;
+ Utils.isArray = _.isArray;
+ Utils.isFunc = _.isFunction;
+ Utils.isUnd = _.isUndefined;
+ Utils.isNull = _.isNull;
+ Utils.emptyFunction = function () {};
+
+ /**
+ * @param {*} oValue
+ * @return {boolean}
+ */
+ Utils.isNormal = function (oValue)
{
- $window.resize();
- }
- else
- {
- window.setTimeout(function () {
+ return !Utils.isUnd(oValue) && !Utils.isNull(oValue);
+ };
+
+ Utils.windowResize = _.debounce(function (iTimeout) {
+ if (Utils.isUnd(iTimeout))
+ {
$window.resize();
- }, iTimeout);
- }
-}, 50);
-
-/**
- * @param {(string|number)} mValue
- * @param {boolean=} bIncludeZero
- * @return {boolean}
- */
-Utils.isPosNumeric = function (mValue, bIncludeZero)
-{
- return Utils.isNormal(mValue) ?
- ((Utils.isUnd(bIncludeZero) ? true : !!bIncludeZero) ?
- (/^[0-9]*$/).test(mValue.toString()) :
- (/^[1-9]+[0-9]*$/).test(mValue.toString())) :
- false;
-};
-
-/**
- * @param {*} iValue
- * @param {number=} iDefault = 0
- * @return {number}
- */
-Utils.pInt = function (iValue, iDefault)
-{
- var iResult = Utils.isNormal(iValue) && '' !== iValue ? window.parseInt(iValue, 10) : (iDefault || 0);
- return window.isNaN(iResult) ? (iDefault || 0) : iResult;
-};
-
-/**
- * @param {*} mValue
- * @return {string}
- */
-Utils.pString = function (mValue)
-{
- return Utils.isNormal(mValue) ? '' + mValue : '';
-};
-
-/**
- * @param {*} aValue
- * @return {boolean}
- */
-Utils.isNonEmptyArray = function (aValue)
-{
- return Utils.isArray(aValue) && 0 < aValue.length;
-};
-
-/**
- * @param {string} sQueryString
- * @return {Object}
- */
-Utils.simpleQueryParser = function (sQueryString)
-{
- var
- oParams = {},
- aQueries = [],
- aTemp = [],
- iIndex = 0,
- iLen = 0
- ;
-
- aQueries = sQueryString.split('&');
- for (iIndex = 0, iLen = aQueries.length; iIndex < iLen; iIndex++)
- {
- aTemp = aQueries[iIndex].split('=');
- oParams[window.decodeURIComponent(aTemp[0])] = window.decodeURIComponent(aTemp[1]);
- }
-
- return oParams;
-};
-
-/**
- * @param {string} aValue
- * @param {string} sKey
- * @param {string} sLongKey
- * @return {string|boolean}
- */
-Utils.rsaEncode = function (sValue, sHash, sKey, sLongKey)
-{
- if (window.crypto && window.crypto.getRandomValues && window.RSAKey && sHash && sKey && sLongKey)
- {
- var oRsa = new window.RSAKey();
- oRsa.setPublic(sLongKey, sKey);
-
- sValue = oRsa.encrypt(Utils.fakeMd5() + ':' + sValue + ':' + Utils.fakeMd5());
- if (false !== sValue)
- {
- return 'rsa:' + sHash + ':' + sValue;
- }
- }
-
- return false;
-};
-
-Utils.rsaEncode.supported = !!(window.crypto && window.crypto.getRandomValues && window.RSAKey);
-
-/**
- * @param {string} sPath
- * @param {*=} oObject
- * @param {Object=} oObjectToExportTo
- */
-Utils.exportPath = function (sPath, oObject, oObjectToExportTo)
-{
- var
- part = null,
- parts = sPath.split('.'),
- cur = oObjectToExportTo || window
- ;
-
- for (; parts.length && (part = parts.shift());)
- {
- if (!parts.length && !Utils.isUnd(oObject))
- {
- cur[part] = oObject;
- }
- else if (cur[part])
- {
- cur = cur[part];
}
else
{
- cur = cur[part] = {};
+ window.setTimeout(function () {
+ $window.resize();
+ }, iTimeout);
}
- }
-};
+ }, 50);
-/**
- * @param {Object} oObject
- * @param {string} sName
- * @param {*} mValue
- */
-Utils.pImport = function (oObject, sName, mValue)
-{
- oObject[sName] = mValue;
-};
-
-/**
- * @param {Object} oObject
- * @param {string} sName
- * @param {*} mDefault
- * @return {*}
- */
-Utils.pExport = function (oObject, sName, mDefault)
-{
- return Utils.isUnd(oObject[sName]) ? mDefault : oObject[sName];
-};
-
-/**
- * @param {string} sText
- * @return {string}
- */
-Utils.encodeHtml = function (sText)
-{
- return Utils.isNormal(sText) ? sText.toString()
- .replace(/&/g, '&').replace(//g, '>')
- .replace(/"/g, '"').replace(/'/g, ''') : '';
-};
-
-/**
- * @param {string} sText
- * @param {number=} iLen
- * @return {string}
- */
-Utils.splitPlainText = function (sText, iLen)
-{
- var
- sPrefix = '',
- sSubText = '',
- sResult = sText,
- iSpacePos = 0,
- iNewLinePos = 0
- ;
-
- iLen = Utils.isUnd(iLen) ? 100 : iLen;
-
- while (sResult.length > iLen)
+ /**
+ * @param {(string|number)} mValue
+ * @param {boolean=} bIncludeZero
+ * @return {boolean}
+ */
+ Utils.isPosNumeric = function (mValue, bIncludeZero)
{
- sSubText = sResult.substring(0, iLen);
- iSpacePos = sSubText.lastIndexOf(' ');
- iNewLinePos = sSubText.lastIndexOf('\n');
-
- if (-1 !== iNewLinePos)
- {
- iSpacePos = iNewLinePos;
- }
-
- if (-1 === iSpacePos)
- {
- iSpacePos = iLen;
- }
-
- sPrefix += sSubText.substring(0, iSpacePos) + '\n';
- sResult = sResult.substring(iSpacePos + 1);
- }
-
- return sPrefix + sResult;
-};
-
-Utils.timeOutAction = (function () {
-
- var
- oTimeOuts = {}
- ;
-
- return function (sAction, fFunction, iTimeOut)
- {
- if (Utils.isUnd(oTimeOuts[sAction]))
- {
- oTimeOuts[sAction] = 0;
- }
-
- window.clearTimeout(oTimeOuts[sAction]);
- oTimeOuts[sAction] = window.setTimeout(fFunction, iTimeOut);
+ return Utils.isNormal(mValue) ?
+ ((Utils.isUnd(bIncludeZero) ? true : !!bIncludeZero) ?
+ (/^[0-9]*$/).test(mValue.toString()) :
+ (/^[1-9]+[0-9]*$/).test(mValue.toString())) :
+ false;
};
-}());
-Utils.timeOutActionSecond = (function () {
-
- var
- oTimeOuts = {}
- ;
-
- return function (sAction, fFunction, iTimeOut)
+ /**
+ * @param {*} iValue
+ * @param {number=} iDefault = 0
+ * @return {number}
+ */
+ Utils.pInt = function (iValue, iDefault)
{
- if (!oTimeOuts[sAction])
- {
- oTimeOuts[sAction] = window.setTimeout(function () {
- fFunction();
- oTimeOuts[sAction] = 0;
- }, iTimeOut);
- }
+ var iResult = Utils.isNormal(iValue) && '' !== iValue ? window.parseInt(iValue, 10) : (iDefault || 0);
+ return window.isNaN(iResult) ? (iDefault || 0) : iResult;
};
-}());
-Utils.audio = (function () {
+ /**
+ * @param {*} mValue
+ * @return {string}
+ */
+ Utils.pString = function (mValue)
+ {
+ return Utils.isNormal(mValue) ? '' + mValue : '';
+ };
- var
- oAudio = false
- ;
+ /**
+ * @param {*} aValue
+ * @return {boolean}
+ */
+ Utils.isNonEmptyArray = function (aValue)
+ {
+ return Utils.isArray(aValue) && 0 < aValue.length;
+ };
- return function (sMp3File, sOggFile) {
+ /**
+ * @param {string} sQueryString
+ * @return {Object}
+ */
+ Utils.simpleQueryParser = function (sQueryString)
+ {
+ var
+ oParams = {},
+ aQueries = [],
+ aTemp = [],
+ iIndex = 0,
+ iLen = 0
+ ;
- if (false === oAudio)
+ aQueries = sQueryString.split('&');
+ for (iIndex = 0, iLen = aQueries.length; iIndex < iLen; iIndex++)
{
- if (Globals.bIsiOSDevice)
+ aTemp = aQueries[iIndex].split('=');
+ oParams[window.decodeURIComponent(aTemp[0])] = window.decodeURIComponent(aTemp[1]);
+ }
+
+ return oParams;
+ };
+
+ /**
+ * @param {string} aValue
+ * @param {string} sKey
+ * @param {string} sLongKey
+ * @return {string|boolean}
+ */
+ Utils.rsaEncode = function (sValue, sHash, sKey, sLongKey)
+ {
+ if (window.crypto && window.crypto.getRandomValues && window.RSAKey && sHash && sKey && sLongKey)
+ {
+ var oRsa = new window.RSAKey();
+ oRsa.setPublic(sLongKey, sKey);
+
+ sValue = oRsa.encrypt(Utils.fakeMd5() + ':' + sValue + ':' + Utils.fakeMd5());
+ if (false !== sValue)
{
- oAudio = null;
+ return 'rsa:' + sHash + ':' + sValue;
+ }
+ }
+
+ return false;
+ };
+
+ Utils.rsaEncode.supported = !!(window.crypto && window.crypto.getRandomValues && window.RSAKey);
+
+ /**
+ * @param {string} sPath
+ * @param {*=} oObject
+ * @param {Object=} oObjectToExportTo
+ */
+ Utils.exportPath = function (sPath, oObject, oObjectToExportTo)
+ {
+ var
+ part = null,
+ parts = sPath.split('.'),
+ cur = oObjectToExportTo || window
+ ;
+
+ for (; parts.length && (part = parts.shift());)
+ {
+ if (!parts.length && !Utils.isUnd(oObject))
+ {
+ cur[part] = oObject;
+ }
+ else if (cur[part])
+ {
+ cur = cur[part];
}
else
{
- var
- bCanPlayMp3 = false,
- bCanPlayOgg = false,
- oAudioLocal = window.Audio ? new window.Audio() : null
- ;
+ cur = cur[part] = {};
+ }
+ }
+ };
- if (oAudioLocal && oAudioLocal.canPlayType && oAudioLocal.play)
+ /**
+ * @param {Object} oObject
+ * @param {string} sName
+ * @param {*} mValue
+ */
+ Utils.pImport = function (oObject, sName, mValue)
+ {
+ oObject[sName] = mValue;
+ };
+
+ /**
+ * @param {Object} oObject
+ * @param {string} sName
+ * @param {*} mDefault
+ * @return {*}
+ */
+ Utils.pExport = function (oObject, sName, mDefault)
+ {
+ return Utils.isUnd(oObject[sName]) ? mDefault : oObject[sName];
+ };
+
+ /**
+ * @param {string} sText
+ * @return {string}
+ */
+ Utils.encodeHtml = function (sText)
+ {
+ return Utils.isNormal(sText) ? sText.toString()
+ .replace(/&/g, '&').replace(//g, '>')
+ .replace(/"/g, '"').replace(/'/g, ''') : '';
+ };
+
+ /**
+ * @param {string} sText
+ * @param {number=} iLen
+ * @return {string}
+ */
+ Utils.splitPlainText = function (sText, iLen)
+ {
+ var
+ sPrefix = '',
+ sSubText = '',
+ sResult = sText,
+ iSpacePos = 0,
+ iNewLinePos = 0
+ ;
+
+ iLen = Utils.isUnd(iLen) ? 100 : iLen;
+
+ while (sResult.length > iLen)
+ {
+ sSubText = sResult.substring(0, iLen);
+ iSpacePos = sSubText.lastIndexOf(' ');
+ iNewLinePos = sSubText.lastIndexOf('\n');
+
+ if (-1 !== iNewLinePos)
+ {
+ iSpacePos = iNewLinePos;
+ }
+
+ if (-1 === iSpacePos)
+ {
+ iSpacePos = iLen;
+ }
+
+ sPrefix += sSubText.substring(0, iSpacePos) + '\n';
+ sResult = sResult.substring(iSpacePos + 1);
+ }
+
+ return sPrefix + sResult;
+ };
+
+ Utils.timeOutAction = (function () {
+
+ var
+ oTimeOuts = {}
+ ;
+
+ return function (sAction, fFunction, iTimeOut)
+ {
+ if (Utils.isUnd(oTimeOuts[sAction]))
+ {
+ oTimeOuts[sAction] = 0;
+ }
+
+ window.clearTimeout(oTimeOuts[sAction]);
+ oTimeOuts[sAction] = window.setTimeout(fFunction, iTimeOut);
+ };
+ }());
+
+ Utils.timeOutActionSecond = (function () {
+
+ var
+ oTimeOuts = {}
+ ;
+
+ return function (sAction, fFunction, iTimeOut)
+ {
+ if (!oTimeOuts[sAction])
+ {
+ oTimeOuts[sAction] = window.setTimeout(function () {
+ fFunction();
+ oTimeOuts[sAction] = 0;
+ }, iTimeOut);
+ }
+ };
+ }());
+
+ Utils.audio = (function () {
+
+ var
+ oAudio = false
+ ;
+
+ return function (sMp3File, sOggFile) {
+
+ if (false === oAudio)
+ {
+ if (Globals.bIsiOSDevice)
{
- bCanPlayMp3 = '' !== oAudioLocal.canPlayType('audio/mpeg; codecs="mp3"');
- if (!bCanPlayMp3)
- {
- bCanPlayOgg = '' !== oAudioLocal.canPlayType('audio/ogg; codecs="vorbis"');
- }
+ oAudio = null;
+ }
+ else
+ {
+ var
+ bCanPlayMp3 = false,
+ bCanPlayOgg = false,
+ oAudioLocal = window.Audio ? new window.Audio() : null
+ ;
- if (bCanPlayMp3 || bCanPlayOgg)
+ if (oAudioLocal && oAudioLocal.canPlayType && oAudioLocal.play)
{
- oAudio = oAudioLocal;
- oAudio.preload = 'none';
- oAudio.loop = false;
- oAudio.autoplay = false;
- oAudio.muted = false;
- oAudio.src = bCanPlayMp3 ? sMp3File : sOggFile;
+ bCanPlayMp3 = '' !== oAudioLocal.canPlayType('audio/mpeg; codecs="mp3"');
+ if (!bCanPlayMp3)
+ {
+ bCanPlayOgg = '' !== oAudioLocal.canPlayType('audio/ogg; codecs="vorbis"');
+ }
+
+ if (bCanPlayMp3 || bCanPlayOgg)
+ {
+ oAudio = oAudioLocal;
+ oAudio.preload = 'none';
+ oAudio.loop = false;
+ oAudio.autoplay = false;
+ oAudio.muted = false;
+ oAudio.src = bCanPlayMp3 ? sMp3File : sOggFile;
+ }
+ else
+ {
+ oAudio = null;
+ }
}
else
{
oAudio = null;
}
}
- else
- {
- oAudio = null;
- }
}
- }
- return oAudio;
+ return oAudio;
+ };
+ }());
+
+ /**
+ * @param {(Object|null|undefined)} oObject
+ * @param {string} sProp
+ * @return {boolean}
+ */
+ Utils.hos = function (oObject, sProp)
+ {
+ return oObject && window.Object && window.Object.hasOwnProperty ? window.Object.hasOwnProperty.call(oObject, sProp) : false;
};
-}());
-/**
- * @param {(Object|null|undefined)} oObject
- * @param {string} sProp
- * @return {boolean}
- */
-Utils.hos = function (oObject, sProp)
-{
- return oObject && Object.hasOwnProperty ? Object.hasOwnProperty.call(oObject, sProp) : false;
-};
-
-/**
- * @param {string} sKey
- * @param {Object=} oValueList
- * @param {string=} sDefaulValue
- * @return {string}
- */
-Utils.i18n = function (sKey, oValueList, sDefaulValue)
-{
- var
- sValueName = '',
- sResult = Utils.isUnd(I18n[sKey]) ? (Utils.isUnd(sDefaulValue) ? sKey : sDefaulValue) : I18n[sKey]
- ;
-
- if (!Utils.isUnd(oValueList) && !Utils.isNull(oValueList))
- {
- for (sValueName in oValueList)
- {
- if (Utils.hos(oValueList, sValueName))
- {
- sResult = sResult.replace('%' + sValueName + '%', oValueList[sValueName]);
- }
- }
- }
-
- return sResult;
-};
-
-/**
- * @param {Object} oElement
- */
-Utils.i18nToNode = function (oElement)
-{
- _.defer(function () {
- $('.i18n', oElement).each(function () {
- var
- jqThis = $(this),
- sKey = ''
- ;
-
- sKey = jqThis.data('i18n-text');
- if (sKey)
- {
- jqThis.text(Utils.i18n(sKey));
- }
- else
- {
- sKey = jqThis.data('i18n-html');
- if (sKey)
- {
- jqThis.html(Utils.i18n(sKey));
- }
-
- sKey = jqThis.data('i18n-placeholder');
- if (sKey)
- {
- jqThis.attr('placeholder', Utils.i18n(sKey));
- }
-
- sKey = jqThis.data('i18n-title');
- if (sKey)
- {
- jqThis.attr('title', Utils.i18n(sKey));
- }
- }
- });
- });
-};
-
-Utils.i18nToDoc = function ()
-{
- if (window.rainloopI18N)
- {
- I18n = window.rainloopI18N || {};
- Utils.i18nToNode($document);
-
- Globals.langChangeTrigger(!Globals.langChangeTrigger());
- }
-
- window.rainloopI18N = {};
-};
-
-/**
- * @param {Function} fCallback
- * @param {Object} oScope
- * @param {Function=} fLangCallback
- */
-Utils.initOnStartOrLangChange = function (fCallback, oScope, fLangCallback)
-{
- if (fCallback)
- {
- fCallback.call(oScope);
- }
-
- if (fLangCallback)
- {
- Globals.langChangeTrigger.subscribe(function () {
- if (fCallback)
- {
- fCallback.call(oScope);
- }
-
- fLangCallback.call(oScope);
- });
- }
- else if (fCallback)
- {
- Globals.langChangeTrigger.subscribe(fCallback, oScope);
- }
-};
-
-/**
- * @return {boolean}
- */
-Utils.inFocus = function ()
-{
- if (document.activeElement)
- {
- if (Utils.isUnd(document.activeElement.__inFocusCache))
- {
- document.activeElement.__inFocusCache = $(document.activeElement).is('input,textarea,iframe,.cke_editable');
- }
-
- return !!document.activeElement.__inFocusCache;
- }
-
- return false;
-};
-
-Utils.removeInFocus = function ()
-{
- if (document && document.activeElement && document.activeElement.blur)
- {
- var oA = $(document.activeElement);
- if (oA.is('input,textarea'))
- {
- document.activeElement.blur();
- }
- }
-};
-
-Utils.removeSelection = function ()
-{
- if (window && window.getSelection)
- {
- var oSel = window.getSelection();
- if (oSel && oSel.removeAllRanges)
- {
- oSel.removeAllRanges();
- }
- }
- else if (document && document.selection && document.selection.empty)
- {
- document.selection.empty();
- }
-};
-
-/**
- * @param {string} sPrefix
- * @param {string} sSubject
- * @return {string}
- */
-Utils.replySubjectAdd = function (sPrefix, sSubject)
-{
- sPrefix = Utils.trim(sPrefix.toUpperCase());
- sSubject = Utils.trim(sSubject.replace(/[\s]+/, ' '));
-
- var
- iIndex = 0,
- sResult = '',
- bDrop = false,
- sTrimmedPart = '',
- aSubject = [],
- aParts = [],
- bRe = 'RE' === sPrefix,
- bFwd = 'FWD' === sPrefix,
- bPrefixIsRe = !bFwd
- ;
-
- if ('' !== sSubject)
- {
- bDrop = false;
-
- aParts = sSubject.split(':');
- for (iIndex = 0; iIndex < aParts.length; iIndex++)
- {
- sTrimmedPart = Utils.trim(aParts[iIndex]);
- if (!bDrop &&
- (/^(RE|FWD)$/i.test(sTrimmedPart) || /^(RE|FWD)[\[\(][\d]+[\]\)]$/i.test(sTrimmedPart))
- )
- {
- if (!bRe)
- {
- bRe = !!(/^RE/i.test(sTrimmedPart));
- }
-
- if (!bFwd)
- {
- bFwd = !!(/^FWD/i.test(sTrimmedPart));
- }
- }
- else
- {
- aSubject.push(aParts[iIndex]);
- bDrop = true;
- }
- }
-
- if (0 < aSubject.length)
- {
- sResult = Utils.trim(aSubject.join(':'));
- }
- }
-
- if (bPrefixIsRe)
- {
- bRe = false;
- }
- else
- {
- bFwd = false;
- }
-
- return Utils.trim(
- (bPrefixIsRe ? 'Re: ' : 'Fwd: ') +
- (bRe ? 'Re: ' : '') +
- (bFwd ? 'Fwd: ' : '') +
- sResult
- );
-};
-
-
-/**
- * @param {string} sSubject
- * @return {string}
- */
-Utils.fixLongSubject = function (sSubject)
-{
- var
- iLimit = 30,
- mReg = /^Re([\[\(]([\d]+)[\]\)]|):[\s]{0,3}Re([\[\(]([\d]+)[\]\)]|):/ig,
- oMatch = null
- ;
-
- sSubject = Utils.trim(sSubject.replace(/[\s]+/, ' '));
-
- do
- {
- iLimit--;
-
- oMatch = mReg.exec(sSubject);
- if (!oMatch || Utils.isUnd(oMatch[0]))
- {
- oMatch = null;
- }
-
- if (oMatch)
- {
- sSubject = sSubject.replace(mReg, 'Re:');
- }
- }
- while (oMatch || 0 < iLimit);
-
- return sSubject.replace(/[\s]+/, ' ');
-};
-
-/**
- * @deprecated
- * @param {string} sPrefix
- * @param {string} sSubject
- * @param {boolean=} bFixLongSubject = true
- * @return {string}
- */
-Utils._replySubjectAdd_ = function (sPrefix, sSubject, bFixLongSubject)
-{
- var
- oMatch = null,
- sResult = Utils.trim(sSubject)
- ;
-
- if (null !== (oMatch = (new window.RegExp('^' + sPrefix + '[\\s]?\\:(.*)$', 'gi')).exec(sSubject)) && !Utils.isUnd(oMatch[1]))
- {
- sResult = sPrefix + '[2]: ' + oMatch[1];
- }
- else if (null !== (oMatch = (new window.RegExp('^(' + sPrefix + '[\\s]?[\\[\\(]?)([\\d]+)([\\]\\)]?[\\s]?\\:.*)$', 'gi')).exec(sSubject)) &&
- !Utils.isUnd(oMatch[1]) && !Utils.isUnd(oMatch[2]) && !Utils.isUnd(oMatch[3]))
- {
- sResult = oMatch[1] + (Utils.pInt(oMatch[2]) + 1) + oMatch[3];
- }
- else
- {
- sResult = sPrefix + ': ' + sSubject;
- }
-
- sResult = sResult.replace(/[\s]+/g, ' ');
- sResult = (Utils.isUnd(bFixLongSubject) ? true : bFixLongSubject) ? Utils.fixLongSubject(sResult) : sResult;
-// sResult = sResult.replace(/^(Re|Fwd)[\s]?\[[\d]+\]:/ig, '$1:');
- return sResult;
-};
-
-/**
- * @deprecated
- * @param {string} sSubject
- * @return {string}
- */
-Utils._fixLongSubject_ = function (sSubject)
-{
- var
- iCounter = 0,
- oMatch = null
- ;
-
- sSubject = Utils.trim(sSubject.replace(/[\s]+/, ' '));
-
- do
- {
- oMatch = /^Re(\[([\d]+)\]|):[\s]{0,3}Re(\[([\d]+)\]|):/ig.exec(sSubject);
- if (!oMatch || Utils.isUnd(oMatch[0]))
- {
- oMatch = null;
- }
-
- if (oMatch)
- {
- iCounter = 0;
- iCounter += Utils.isUnd(oMatch[2]) ? 1 : 0 + Utils.pInt(oMatch[2]);
- iCounter += Utils.isUnd(oMatch[4]) ? 1 : 0 + Utils.pInt(oMatch[4]);
-
- sSubject = sSubject.replace(/^Re(\[[\d]+\]|):[\s]{0,3}Re(\[[\d]+\]|):/gi, 'Re' + (0 < iCounter ? '[' + iCounter + ']' : '') + ':');
- }
-
- }
- while (oMatch);
-
- sSubject = sSubject.replace(/[\s]+/, ' ');
- return sSubject;
-};
-
-/**
- * @param {number} iNum
- * @param {number} iDec
- * @return {number}
- */
-Utils.roundNumber = function (iNum, iDec)
-{
- return Math.round(iNum * Math.pow(10, iDec)) / Math.pow(10, iDec);
-};
-
-/**
- * @param {(number|string)} iSizeInBytes
- * @return {string}
- */
-Utils.friendlySize = function (iSizeInBytes)
-{
- iSizeInBytes = Utils.pInt(iSizeInBytes);
-
- if (iSizeInBytes >= 1073741824)
- {
- return Utils.roundNumber(iSizeInBytes / 1073741824, 1) + 'GB';
- }
- else if (iSizeInBytes >= 1048576)
- {
- return Utils.roundNumber(iSizeInBytes / 1048576, 1) + 'MB';
- }
- else if (iSizeInBytes >= 1024)
- {
- return Utils.roundNumber(iSizeInBytes / 1024, 0) + 'KB';
- }
-
- return iSizeInBytes + 'B';
-};
-
-/**
- * @param {string} sDesc
- */
-Utils.log = function (sDesc)
-{
- if (window.console && window.console.log)
- {
- window.console.log(sDesc);
- }
-};
-
-/**
- * @param {number} iCode
- * @param {*=} mMessage = ''
- * @return {string}
- */
-Utils.getNotification = function (iCode, mMessage)
-{
- iCode = Utils.pInt(iCode);
- if (Enums.Notification.ClientViewError === iCode && mMessage)
- {
- return mMessage;
- }
-
- return Utils.isUnd(NotificationI18N[iCode]) ? '' : NotificationI18N[iCode];
-};
-
-Utils.initNotificationLanguage = function ()
-{
- NotificationI18N[Enums.Notification.InvalidToken] = Utils.i18n('NOTIFICATIONS/INVALID_TOKEN');
- NotificationI18N[Enums.Notification.AuthError] = Utils.i18n('NOTIFICATIONS/AUTH_ERROR');
- NotificationI18N[Enums.Notification.AccessError] = Utils.i18n('NOTIFICATIONS/ACCESS_ERROR');
- NotificationI18N[Enums.Notification.ConnectionError] = Utils.i18n('NOTIFICATIONS/CONNECTION_ERROR');
- NotificationI18N[Enums.Notification.CaptchaError] = Utils.i18n('NOTIFICATIONS/CAPTCHA_ERROR');
- NotificationI18N[Enums.Notification.SocialFacebookLoginAccessDisable] = Utils.i18n('NOTIFICATIONS/SOCIAL_FACEBOOK_LOGIN_ACCESS_DISABLE');
- NotificationI18N[Enums.Notification.SocialTwitterLoginAccessDisable] = Utils.i18n('NOTIFICATIONS/SOCIAL_TWITTER_LOGIN_ACCESS_DISABLE');
- NotificationI18N[Enums.Notification.SocialGoogleLoginAccessDisable] = Utils.i18n('NOTIFICATIONS/SOCIAL_GOOGLE_LOGIN_ACCESS_DISABLE');
- NotificationI18N[Enums.Notification.DomainNotAllowed] = Utils.i18n('NOTIFICATIONS/DOMAIN_NOT_ALLOWED');
- NotificationI18N[Enums.Notification.AccountNotAllowed] = Utils.i18n('NOTIFICATIONS/ACCOUNT_NOT_ALLOWED');
-
- NotificationI18N[Enums.Notification.AccountTwoFactorAuthRequired] = Utils.i18n('NOTIFICATIONS/ACCOUNT_TWO_FACTOR_AUTH_REQUIRED');
- NotificationI18N[Enums.Notification.AccountTwoFactorAuthError] = Utils.i18n('NOTIFICATIONS/ACCOUNT_TWO_FACTOR_AUTH_ERROR');
-
- NotificationI18N[Enums.Notification.CouldNotSaveNewPassword] = Utils.i18n('NOTIFICATIONS/COULD_NOT_SAVE_NEW_PASSWORD');
- NotificationI18N[Enums.Notification.CurrentPasswordIncorrect] = Utils.i18n('NOTIFICATIONS/CURRENT_PASSWORD_INCORRECT');
- NotificationI18N[Enums.Notification.NewPasswordShort] = Utils.i18n('NOTIFICATIONS/NEW_PASSWORD_SHORT');
- NotificationI18N[Enums.Notification.NewPasswordWeak] = Utils.i18n('NOTIFICATIONS/NEW_PASSWORD_WEAK');
- NotificationI18N[Enums.Notification.NewPasswordForbidden] = Utils.i18n('NOTIFICATIONS/NEW_PASSWORD_FORBIDDENT');
-
- NotificationI18N[Enums.Notification.ContactsSyncError] = Utils.i18n('NOTIFICATIONS/CONTACTS_SYNC_ERROR');
-
- NotificationI18N[Enums.Notification.CantGetMessageList] = Utils.i18n('NOTIFICATIONS/CANT_GET_MESSAGE_LIST');
- NotificationI18N[Enums.Notification.CantGetMessage] = Utils.i18n('NOTIFICATIONS/CANT_GET_MESSAGE');
- NotificationI18N[Enums.Notification.CantDeleteMessage] = Utils.i18n('NOTIFICATIONS/CANT_DELETE_MESSAGE');
- NotificationI18N[Enums.Notification.CantMoveMessage] = Utils.i18n('NOTIFICATIONS/CANT_MOVE_MESSAGE');
- NotificationI18N[Enums.Notification.CantCopyMessage] = Utils.i18n('NOTIFICATIONS/CANT_MOVE_MESSAGE');
-
- NotificationI18N[Enums.Notification.CantSaveMessage] = Utils.i18n('NOTIFICATIONS/CANT_SAVE_MESSAGE');
- NotificationI18N[Enums.Notification.CantSendMessage] = Utils.i18n('NOTIFICATIONS/CANT_SEND_MESSAGE');
- NotificationI18N[Enums.Notification.InvalidRecipients] = Utils.i18n('NOTIFICATIONS/INVALID_RECIPIENTS');
-
- NotificationI18N[Enums.Notification.CantCreateFolder] = Utils.i18n('NOTIFICATIONS/CANT_CREATE_FOLDER');
- NotificationI18N[Enums.Notification.CantRenameFolder] = Utils.i18n('NOTIFICATIONS/CANT_RENAME_FOLDER');
- NotificationI18N[Enums.Notification.CantDeleteFolder] = Utils.i18n('NOTIFICATIONS/CANT_DELETE_FOLDER');
- NotificationI18N[Enums.Notification.CantDeleteNonEmptyFolder] = Utils.i18n('NOTIFICATIONS/CANT_DELETE_NON_EMPTY_FOLDER');
- NotificationI18N[Enums.Notification.CantSubscribeFolder] = Utils.i18n('NOTIFICATIONS/CANT_SUBSCRIBE_FOLDER');
- NotificationI18N[Enums.Notification.CantUnsubscribeFolder] = Utils.i18n('NOTIFICATIONS/CANT_UNSUBSCRIBE_FOLDER');
-
- NotificationI18N[Enums.Notification.CantSaveSettings] = Utils.i18n('NOTIFICATIONS/CANT_SAVE_SETTINGS');
- NotificationI18N[Enums.Notification.CantSavePluginSettings] = Utils.i18n('NOTIFICATIONS/CANT_SAVE_PLUGIN_SETTINGS');
-
- NotificationI18N[Enums.Notification.DomainAlreadyExists] = Utils.i18n('NOTIFICATIONS/DOMAIN_ALREADY_EXISTS');
-
- NotificationI18N[Enums.Notification.CantInstallPackage] = Utils.i18n('NOTIFICATIONS/CANT_INSTALL_PACKAGE');
- NotificationI18N[Enums.Notification.CantDeletePackage] = Utils.i18n('NOTIFICATIONS/CANT_DELETE_PACKAGE');
- NotificationI18N[Enums.Notification.InvalidPluginPackage] = Utils.i18n('NOTIFICATIONS/INVALID_PLUGIN_PACKAGE');
- NotificationI18N[Enums.Notification.UnsupportedPluginPackage] = Utils.i18n('NOTIFICATIONS/UNSUPPORTED_PLUGIN_PACKAGE');
-
- NotificationI18N[Enums.Notification.LicensingServerIsUnavailable] = Utils.i18n('NOTIFICATIONS/LICENSING_SERVER_IS_UNAVAILABLE');
- NotificationI18N[Enums.Notification.LicensingExpired] = Utils.i18n('NOTIFICATIONS/LICENSING_EXPIRED');
- NotificationI18N[Enums.Notification.LicensingBanned] = Utils.i18n('NOTIFICATIONS/LICENSING_BANNED');
-
- NotificationI18N[Enums.Notification.DemoSendMessageError] = Utils.i18n('NOTIFICATIONS/DEMO_SEND_MESSAGE_ERROR');
-
- NotificationI18N[Enums.Notification.AccountAlreadyExists] = Utils.i18n('NOTIFICATIONS/ACCOUNT_ALREADY_EXISTS');
-
- NotificationI18N[Enums.Notification.MailServerError] = Utils.i18n('NOTIFICATIONS/MAIL_SERVER_ERROR');
- NotificationI18N[Enums.Notification.InvalidInputArgument] = Utils.i18n('NOTIFICATIONS/INVALID_INPUT_ARGUMENT');
- NotificationI18N[Enums.Notification.UnknownNotification] = Utils.i18n('NOTIFICATIONS/UNKNOWN_ERROR');
- NotificationI18N[Enums.Notification.UnknownError] = Utils.i18n('NOTIFICATIONS/UNKNOWN_ERROR');
-};
-
-/**
- * @param {*} mCode
- * @return {string}
- */
-Utils.getUploadErrorDescByCode = function (mCode)
-{
- var sResult = '';
- switch (Utils.pInt(mCode)) {
- case Enums.UploadErrorCode.FileIsTooBig:
- sResult = Utils.i18n('UPLOAD/ERROR_FILE_IS_TOO_BIG');
- break;
- case Enums.UploadErrorCode.FilePartiallyUploaded:
- sResult = Utils.i18n('UPLOAD/ERROR_FILE_PARTIALLY_UPLOADED');
- break;
- case Enums.UploadErrorCode.FileNoUploaded:
- sResult = Utils.i18n('UPLOAD/ERROR_NO_FILE_UPLOADED');
- break;
- case Enums.UploadErrorCode.MissingTempFolder:
- sResult = Utils.i18n('UPLOAD/ERROR_MISSING_TEMP_FOLDER');
- break;
- case Enums.UploadErrorCode.FileOnSaveingError:
- sResult = Utils.i18n('UPLOAD/ERROR_ON_SAVING_FILE');
- break;
- case Enums.UploadErrorCode.FileType:
- sResult = Utils.i18n('UPLOAD/ERROR_FILE_TYPE');
- break;
- default:
- sResult = Utils.i18n('UPLOAD/ERROR_UNKNOWN');
- break;
- }
-
- return sResult;
-};
-
-/**
- * @param {?} oObject
- * @param {string} sMethodName
- * @param {Array=} aParameters
- * @param {number=} nDelay
- */
-Utils.delegateRun = function (oObject, sMethodName, aParameters, nDelay)
-{
- if (oObject && oObject[sMethodName])
- {
- nDelay = Utils.pInt(nDelay);
- if (0 >= nDelay)
- {
- oObject[sMethodName].apply(oObject, Utils.isArray(aParameters) ? aParameters : []);
- }
- else
- {
- _.delay(function () {
- oObject[sMethodName].apply(oObject, Utils.isArray(aParameters) ? aParameters : []);
- }, nDelay);
- }
- }
-};
-
-/**
- * @param {?} oEvent
- */
-Utils.killCtrlAandS = function (oEvent)
-{
- oEvent = oEvent || window.event;
- if (oEvent && oEvent.ctrlKey && !oEvent.shiftKey && !oEvent.altKey)
+ /**
+ * @param {string} sKey
+ * @param {Object=} oValueList
+ * @param {string=} sDefaulValue
+ * @return {string}
+ */
+ Utils.i18n = function (sKey, oValueList, sDefaulValue)
{
var
- oSender = oEvent.target || oEvent.srcElement,
- iKey = oEvent.keyCode || oEvent.which
+ sValueName = '',
+ sResult = Utils.isUnd(Globals.oI18N[sKey]) ? (Utils.isUnd(sDefaulValue) ? sKey : sDefaulValue) : Globals.oI18N[sKey]
;
- if (iKey === Enums.EventKeyCode.S)
+ if (!Utils.isUnd(oValueList) && !Utils.isNull(oValueList))
{
- oEvent.preventDefault();
- return;
+ for (sValueName in oValueList)
+ {
+ if (Utils.hos(oValueList, sValueName))
+ {
+ sResult = sResult.replace('%' + sValueName + '%', oValueList[sValueName]);
+ }
+ }
}
- if (oSender && oSender.tagName && oSender.tagName.match(/INPUT|TEXTAREA/i))
- {
- return;
- }
+ return sResult;
+ };
- if (iKey === Enums.EventKeyCode.A)
- {
- if (window.getSelection)
- {
- window.getSelection().removeAllRanges();
- }
- else if (window.document.selection && window.document.selection.clear)
- {
- window.document.selection.clear();
- }
-
- oEvent.preventDefault();
- }
- }
-};
-
-/**
- * @param {(Object|null|undefined)} oContext
- * @param {Function} fExecute
- * @param {(Function|boolean|null)=} fCanExecute
- * @return {Function}
- */
-Utils.createCommand = function (oContext, fExecute, fCanExecute)
-{
- var
- fResult = fExecute ? function () {
- if (fResult.canExecute && fResult.canExecute())
- {
- fExecute.apply(oContext, Array.prototype.slice.call(arguments));
- }
- return false;
- } : function () {}
- ;
-
- fResult.enabled = ko.observable(true);
-
- fCanExecute = Utils.isUnd(fCanExecute) ? true : fCanExecute;
- if (Utils.isFunc(fCanExecute))
+ /**
+ * @param {Object} oElement
+ */
+ Utils.i18nToNode = function (oElement)
{
- fResult.canExecute = ko.computed(function () {
- return fResult.enabled() && fCanExecute.call(oContext);
+ _.defer(function () {
+ $('.i18n', oElement).each(function () {
+ var
+ jqThis = $(this),
+ sKey = ''
+ ;
+
+ sKey = jqThis.data('i18n-text');
+ if (sKey)
+ {
+ jqThis.text(Utils.i18n(sKey));
+ }
+ else
+ {
+ sKey = jqThis.data('i18n-html');
+ if (sKey)
+ {
+ jqThis.html(Utils.i18n(sKey));
+ }
+
+ sKey = jqThis.data('i18n-placeholder');
+ if (sKey)
+ {
+ jqThis.attr('placeholder', Utils.i18n(sKey));
+ }
+
+ sKey = jqThis.data('i18n-title');
+ if (sKey)
+ {
+ jqThis.attr('title', Utils.i18n(sKey));
+ }
+ }
+ });
});
- }
- else
+ };
+
+ Utils.i18nReload = function ()
{
- fResult.canExecute = ko.computed(function () {
- return fResult.enabled() && !!fCanExecute;
- });
- }
-
- return fResult;
-};
-
-/**
- * @param {Object} oData
- */
-Utils.initDataConstructorBySettings = function (oData)
-{
- oData.editorDefaultType = ko.observable(Enums.EditorDefaultType.Html);
- oData.showImages = ko.observable(false);
- oData.interfaceAnimation = ko.observable(Enums.InterfaceAnimation.Full);
- oData.contactsAutosave = ko.observable(false);
-
- Globals.sAnimationType = Enums.InterfaceAnimation.Full;
-
- oData.capaThemes = ko.observable(false);
- oData.allowLanguagesOnSettings = ko.observable(true);
- oData.allowLanguagesOnLogin = ko.observable(true);
-
- oData.useLocalProxyForExternalImages = ko.observable(false);
-
- oData.desktopNotifications = ko.observable(false);
- oData.useThreads = ko.observable(true);
- oData.replySameFolder = ko.observable(true);
- oData.useCheckboxesInList = ko.observable(true);
-
- oData.layout = ko.observable(Enums.Layout.SidePreview);
- oData.usePreviewPane = ko.computed(function () {
- return Enums.Layout.NoPreview !== oData.layout();
- });
-
- oData.interfaceAnimation.subscribe(function (sValue) {
- if (Globals.bMobileDevice || sValue === Enums.InterfaceAnimation.None)
+ if (window['rainloopI18N'])
{
- $html.removeClass('rl-anim rl-anim-full').addClass('no-rl-anim');
+ Globals.oI18N = window['rainloopI18N'] || {};
+
+ Utils.i18nToNode($doc);
+
+ Globals.langChangeTrigger(!Globals.langChangeTrigger());
+ }
- Globals.sAnimationType = Enums.InterfaceAnimation.None;
+ window['rainloopI18N'] = null;
+ };
+
+ /**
+ * @param {Function} fCallback
+ * @param {Object} oScope
+ * @param {Function=} fLangCallback
+ */
+ Utils.initOnStartOrLangChange = function (fCallback, oScope, fLangCallback)
+ {
+ if (fCallback)
+ {
+ fCallback.call(oScope);
+ }
+
+ if (fLangCallback)
+ {
+ Globals.langChangeTrigger.subscribe(function () {
+ if (fCallback)
+ {
+ fCallback.call(oScope);
+ }
+
+ fLangCallback.call(oScope);
+ });
+ }
+ else if (fCallback)
+ {
+ Globals.langChangeTrigger.subscribe(fCallback, oScope);
+ }
+ };
+
+ /**
+ * @return {boolean}
+ */
+ Utils.inFocus = function ()
+ {
+ if (document.activeElement)
+ {
+ if (Utils.isUnd(document.activeElement.__inFocusCache))
+ {
+ document.activeElement.__inFocusCache = $(document.activeElement).is('input,textarea,iframe,.cke_editable');
+ }
+
+ return !!document.activeElement.__inFocusCache;
+ }
+
+ return false;
+ };
+
+ Utils.removeInFocus = function ()
+ {
+ if (document && document.activeElement && document.activeElement.blur)
+ {
+ var oA = $(document.activeElement);
+ if (oA.is('input,textarea'))
+ {
+ document.activeElement.blur();
+ }
+ }
+ };
+
+ Utils.removeSelection = function ()
+ {
+ if (window && window.getSelection)
+ {
+ var oSel = window.getSelection();
+ if (oSel && oSel.removeAllRanges)
+ {
+ oSel.removeAllRanges();
+ }
+ }
+ else if (document && document.selection && document.selection.empty)
+ {
+ document.selection.empty();
+ }
+ };
+
+ /**
+ * @param {string} sPrefix
+ * @param {string} sSubject
+ * @return {string}
+ */
+ Utils.replySubjectAdd = function (sPrefix, sSubject)
+ {
+ sPrefix = Utils.trim(sPrefix.toUpperCase());
+ sSubject = Utils.trim(sSubject.replace(/[\s]+/, ' '));
+
+ var
+ iIndex = 0,
+ sResult = '',
+ bDrop = false,
+ sTrimmedPart = '',
+ aSubject = [],
+ aParts = [],
+ bRe = 'RE' === sPrefix,
+ bFwd = 'FWD' === sPrefix,
+ bPrefixIsRe = !bFwd
+ ;
+
+ if ('' !== sSubject)
+ {
+ bDrop = false;
+
+ aParts = sSubject.split(':');
+ for (iIndex = 0; iIndex < aParts.length; iIndex++)
+ {
+ sTrimmedPart = Utils.trim(aParts[iIndex]);
+ if (!bDrop &&
+ (/^(RE|FWD)$/i.test(sTrimmedPart) || /^(RE|FWD)[\[\(][\d]+[\]\)]$/i.test(sTrimmedPart))
+ )
+ {
+ if (!bRe)
+ {
+ bRe = !!(/^RE/i.test(sTrimmedPart));
+ }
+
+ if (!bFwd)
+ {
+ bFwd = !!(/^FWD/i.test(sTrimmedPart));
+ }
+ }
+ else
+ {
+ aSubject.push(aParts[iIndex]);
+ bDrop = true;
+ }
+ }
+
+ if (0 < aSubject.length)
+ {
+ sResult = Utils.trim(aSubject.join(':'));
+ }
+ }
+
+ if (bPrefixIsRe)
+ {
+ bRe = false;
}
else
{
- switch (sValue)
+ bFwd = false;
+ }
+
+ return Utils.trim(
+ (bPrefixIsRe ? 'Re: ' : 'Fwd: ') +
+ (bRe ? 'Re: ' : '') +
+ (bFwd ? 'Fwd: ' : '') +
+ sResult
+ );
+ };
+
+
+ /**
+ * @param {string} sSubject
+ * @return {string}
+ */
+ Utils.fixLongSubject = function (sSubject)
+ {
+ var
+ iLimit = 30,
+ mReg = /^Re([\[\(]([\d]+)[\]\)]|):[\s]{0,3}Re([\[\(]([\d]+)[\]\)]|):/ig,
+ oMatch = null
+ ;
+
+ sSubject = Utils.trim(sSubject.replace(/[\s]+/, ' '));
+
+ do
+ {
+ iLimit--;
+
+ oMatch = mReg.exec(sSubject);
+ if (!oMatch || Utils.isUnd(oMatch[0]))
{
- case Enums.InterfaceAnimation.Full:
- $html.removeClass('no-rl-anim').addClass('rl-anim rl-anim-full');
- Globals.sAnimationType = sValue;
- break;
- case Enums.InterfaceAnimation.Normal:
- $html.removeClass('no-rl-anim rl-anim-full').addClass('rl-anim');
- Globals.sAnimationType = sValue;
- break;
+ oMatch = null;
+ }
+
+ if (oMatch)
+ {
+ sSubject = sSubject.replace(mReg, 'Re:');
}
}
- });
+ while (oMatch || 0 < iLimit);
- oData.interfaceAnimation.valueHasMutated();
+ return sSubject.replace(/[\s]+/, ' ');
+ };
- oData.desktopNotificationsPermisions = ko.computed(function () {
- oData.desktopNotifications();
- var iResult = Enums.DesktopNotifications.NotSupported;
- if (NotificationClass && NotificationClass.permission)
+ /**
+ * @deprecated
+ * @param {string} sPrefix
+ * @param {string} sSubject
+ * @param {boolean=} bFixLongSubject = true
+ * @return {string}
+ */
+ Utils._replySubjectAdd_ = function (sPrefix, sSubject, bFixLongSubject)
+ {
+ var
+ oMatch = null,
+ sResult = Utils.trim(sSubject)
+ ;
+
+ if (null !== (oMatch = (new window.RegExp('^' + sPrefix + '[\\s]?\\:(.*)$', 'gi')).exec(sSubject)) && !Utils.isUnd(oMatch[1]))
{
- switch (NotificationClass.permission.toLowerCase())
+ sResult = sPrefix + '[2]: ' + oMatch[1];
+ }
+ else if (null !== (oMatch = (new window.RegExp('^(' + sPrefix + '[\\s]?[\\[\\(]?)([\\d]+)([\\]\\)]?[\\s]?\\:.*)$', 'gi')).exec(sSubject)) &&
+ !Utils.isUnd(oMatch[1]) && !Utils.isUnd(oMatch[2]) && !Utils.isUnd(oMatch[3]))
+ {
+ sResult = oMatch[1] + (Utils.pInt(oMatch[2]) + 1) + oMatch[3];
+ }
+ else
+ {
+ sResult = sPrefix + ': ' + sSubject;
+ }
+
+ sResult = sResult.replace(/[\s]+/g, ' ');
+ sResult = (Utils.isUnd(bFixLongSubject) ? true : bFixLongSubject) ? Utils.fixLongSubject(sResult) : sResult;
+ // sResult = sResult.replace(/^(Re|Fwd)[\s]?\[[\d]+\]:/ig, '$1:');
+ return sResult;
+ };
+
+ /**
+ * @deprecated
+ * @param {string} sSubject
+ * @return {string}
+ */
+ Utils._fixLongSubject_ = function (sSubject)
+ {
+ var
+ iCounter = 0,
+ oMatch = null
+ ;
+
+ sSubject = Utils.trim(sSubject.replace(/[\s]+/, ' '));
+
+ do
+ {
+ oMatch = /^Re(\[([\d]+)\]|):[\s]{0,3}Re(\[([\d]+)\]|):/ig.exec(sSubject);
+ if (!oMatch || Utils.isUnd(oMatch[0]))
{
- case 'granted':
- iResult = Enums.DesktopNotifications.Allowed;
- break;
- case 'denied':
- iResult = Enums.DesktopNotifications.Denied;
- break;
- case 'default':
- iResult = Enums.DesktopNotifications.NotAllowed;
- break;
+ oMatch = null;
+ }
+
+ if (oMatch)
+ {
+ iCounter = 0;
+ iCounter += Utils.isUnd(oMatch[2]) ? 1 : 0 + Utils.pInt(oMatch[2]);
+ iCounter += Utils.isUnd(oMatch[4]) ? 1 : 0 + Utils.pInt(oMatch[4]);
+
+ sSubject = sSubject.replace(/^Re(\[[\d]+\]|):[\s]{0,3}Re(\[[\d]+\]|):/gi, 'Re' + (0 < iCounter ? '[' + iCounter + ']' : '') + ':');
+ }
+
+ }
+ while (oMatch);
+
+ sSubject = sSubject.replace(/[\s]+/, ' ');
+ return sSubject;
+ };
+
+ /**
+ * @param {number} iNum
+ * @param {number} iDec
+ * @return {number}
+ */
+ Utils.roundNumber = function (iNum, iDec)
+ {
+ return window.Math.round(iNum * window.Math.pow(10, iDec)) / window.Math.pow(10, iDec);
+ };
+
+ /**
+ * @param {(number|string)} iSizeInBytes
+ * @return {string}
+ */
+ Utils.friendlySize = function (iSizeInBytes)
+ {
+ iSizeInBytes = Utils.pInt(iSizeInBytes);
+
+ if (iSizeInBytes >= 1073741824)
+ {
+ return Utils.roundNumber(iSizeInBytes / 1073741824, 1) + 'GB';
+ }
+ else if (iSizeInBytes >= 1048576)
+ {
+ return Utils.roundNumber(iSizeInBytes / 1048576, 1) + 'MB';
+ }
+ else if (iSizeInBytes >= 1024)
+ {
+ return Utils.roundNumber(iSizeInBytes / 1024, 0) + 'KB';
+ }
+
+ return iSizeInBytes + 'B';
+ };
+
+ /**
+ * @param {string} sDesc
+ */
+ Utils.log = function (sDesc)
+ {
+ if (window.console && window.console.log)
+ {
+ window.console.log(sDesc);
+ }
+ };
+
+ /**
+ * @param {number} iCode
+ * @param {*=} mMessage = ''
+ * @return {string}
+ */
+ Utils.getNotification = function (iCode, mMessage)
+ {
+ iCode = Utils.pInt(iCode);
+ if (Enums.Notification.ClientViewError === iCode && mMessage)
+ {
+ return mMessage;
+ }
+
+ return Utils.isUnd(Globals.oNotificationI18N[iCode]) ? '' : Globals.oNotificationI18N[iCode];
+ };
+
+ Utils.initNotificationLanguage = function ()
+ {
+ var oN = Globals.oNotificationI18N || {};
+ oN[Enums.Notification.InvalidToken] = Utils.i18n('NOTIFICATIONS/INVALID_TOKEN');
+ oN[Enums.Notification.AuthError] = Utils.i18n('NOTIFICATIONS/AUTH_ERROR');
+ oN[Enums.Notification.AccessError] = Utils.i18n('NOTIFICATIONS/ACCESS_ERROR');
+ oN[Enums.Notification.ConnectionError] = Utils.i18n('NOTIFICATIONS/CONNECTION_ERROR');
+ oN[Enums.Notification.CaptchaError] = Utils.i18n('NOTIFICATIONS/CAPTCHA_ERROR');
+ oN[Enums.Notification.SocialFacebookLoginAccessDisable] = Utils.i18n('NOTIFICATIONS/SOCIAL_FACEBOOK_LOGIN_ACCESS_DISABLE');
+ oN[Enums.Notification.SocialTwitterLoginAccessDisable] = Utils.i18n('NOTIFICATIONS/SOCIAL_TWITTER_LOGIN_ACCESS_DISABLE');
+ oN[Enums.Notification.SocialGoogleLoginAccessDisable] = Utils.i18n('NOTIFICATIONS/SOCIAL_GOOGLE_LOGIN_ACCESS_DISABLE');
+ oN[Enums.Notification.DomainNotAllowed] = Utils.i18n('NOTIFICATIONS/DOMAIN_NOT_ALLOWED');
+ oN[Enums.Notification.AccountNotAllowed] = Utils.i18n('NOTIFICATIONS/ACCOUNT_NOT_ALLOWED');
+
+ oN[Enums.Notification.AccountTwoFactorAuthRequired] = Utils.i18n('NOTIFICATIONS/ACCOUNT_TWO_FACTOR_AUTH_REQUIRED');
+ oN[Enums.Notification.AccountTwoFactorAuthError] = Utils.i18n('NOTIFICATIONS/ACCOUNT_TWO_FACTOR_AUTH_ERROR');
+
+ oN[Enums.Notification.CouldNotSaveNewPassword] = Utils.i18n('NOTIFICATIONS/COULD_NOT_SAVE_NEW_PASSWORD');
+ oN[Enums.Notification.CurrentPasswordIncorrect] = Utils.i18n('NOTIFICATIONS/CURRENT_PASSWORD_INCORRECT');
+ oN[Enums.Notification.NewPasswordShort] = Utils.i18n('NOTIFICATIONS/NEW_PASSWORD_SHORT');
+ oN[Enums.Notification.NewPasswordWeak] = Utils.i18n('NOTIFICATIONS/NEW_PASSWORD_WEAK');
+ oN[Enums.Notification.NewPasswordForbidden] = Utils.i18n('NOTIFICATIONS/NEW_PASSWORD_FORBIDDENT');
+
+ oN[Enums.Notification.ContactsSyncError] = Utils.i18n('NOTIFICATIONS/CONTACTS_SYNC_ERROR');
+
+ oN[Enums.Notification.CantGetMessageList] = Utils.i18n('NOTIFICATIONS/CANT_GET_MESSAGE_LIST');
+ oN[Enums.Notification.CantGetMessage] = Utils.i18n('NOTIFICATIONS/CANT_GET_MESSAGE');
+ oN[Enums.Notification.CantDeleteMessage] = Utils.i18n('NOTIFICATIONS/CANT_DELETE_MESSAGE');
+ oN[Enums.Notification.CantMoveMessage] = Utils.i18n('NOTIFICATIONS/CANT_MOVE_MESSAGE');
+ oN[Enums.Notification.CantCopyMessage] = Utils.i18n('NOTIFICATIONS/CANT_MOVE_MESSAGE');
+
+ oN[Enums.Notification.CantSaveMessage] = Utils.i18n('NOTIFICATIONS/CANT_SAVE_MESSAGE');
+ oN[Enums.Notification.CantSendMessage] = Utils.i18n('NOTIFICATIONS/CANT_SEND_MESSAGE');
+ oN[Enums.Notification.InvalidRecipients] = Utils.i18n('NOTIFICATIONS/INVALID_RECIPIENTS');
+
+ oN[Enums.Notification.CantCreateFolder] = Utils.i18n('NOTIFICATIONS/CANT_CREATE_FOLDER');
+ oN[Enums.Notification.CantRenameFolder] = Utils.i18n('NOTIFICATIONS/CANT_RENAME_FOLDER');
+ oN[Enums.Notification.CantDeleteFolder] = Utils.i18n('NOTIFICATIONS/CANT_DELETE_FOLDER');
+ oN[Enums.Notification.CantDeleteNonEmptyFolder] = Utils.i18n('NOTIFICATIONS/CANT_DELETE_NON_EMPTY_FOLDER');
+ oN[Enums.Notification.CantSubscribeFolder] = Utils.i18n('NOTIFICATIONS/CANT_SUBSCRIBE_FOLDER');
+ oN[Enums.Notification.CantUnsubscribeFolder] = Utils.i18n('NOTIFICATIONS/CANT_UNSUBSCRIBE_FOLDER');
+
+ oN[Enums.Notification.CantSaveSettings] = Utils.i18n('NOTIFICATIONS/CANT_SAVE_SETTINGS');
+ oN[Enums.Notification.CantSavePluginSettings] = Utils.i18n('NOTIFICATIONS/CANT_SAVE_PLUGIN_SETTINGS');
+
+ oN[Enums.Notification.DomainAlreadyExists] = Utils.i18n('NOTIFICATIONS/DOMAIN_ALREADY_EXISTS');
+
+ oN[Enums.Notification.CantInstallPackage] = Utils.i18n('NOTIFICATIONS/CANT_INSTALL_PACKAGE');
+ oN[Enums.Notification.CantDeletePackage] = Utils.i18n('NOTIFICATIONS/CANT_DELETE_PACKAGE');
+ oN[Enums.Notification.InvalidPluginPackage] = Utils.i18n('NOTIFICATIONS/INVALID_PLUGIN_PACKAGE');
+ oN[Enums.Notification.UnsupportedPluginPackage] = Utils.i18n('NOTIFICATIONS/UNSUPPORTED_PLUGIN_PACKAGE');
+
+ oN[Enums.Notification.LicensingServerIsUnavailable] = Utils.i18n('NOTIFICATIONS/LICENSING_SERVER_IS_UNAVAILABLE');
+ oN[Enums.Notification.LicensingExpired] = Utils.i18n('NOTIFICATIONS/LICENSING_EXPIRED');
+ oN[Enums.Notification.LicensingBanned] = Utils.i18n('NOTIFICATIONS/LICENSING_BANNED');
+
+ oN[Enums.Notification.DemoSendMessageError] = Utils.i18n('NOTIFICATIONS/DEMO_SEND_MESSAGE_ERROR');
+
+ oN[Enums.Notification.AccountAlreadyExists] = Utils.i18n('NOTIFICATIONS/ACCOUNT_ALREADY_EXISTS');
+
+ oN[Enums.Notification.MailServerError] = Utils.i18n('NOTIFICATIONS/MAIL_SERVER_ERROR');
+ oN[Enums.Notification.InvalidInputArgument] = Utils.i18n('NOTIFICATIONS/INVALID_INPUT_ARGUMENT');
+ oN[Enums.Notification.UnknownNotification] = Utils.i18n('NOTIFICATIONS/UNKNOWN_ERROR');
+ oN[Enums.Notification.UnknownError] = Utils.i18n('NOTIFICATIONS/UNKNOWN_ERROR');
+ };
+
+ /**
+ * @param {*} mCode
+ * @return {string}
+ */
+ Utils.getUploadErrorDescByCode = function (mCode)
+ {
+ var sResult = '';
+ switch (Utils.pInt(mCode)) {
+ case Enums.UploadErrorCode.FileIsTooBig:
+ sResult = Utils.i18n('UPLOAD/ERROR_FILE_IS_TOO_BIG');
+ break;
+ case Enums.UploadErrorCode.FilePartiallyUploaded:
+ sResult = Utils.i18n('UPLOAD/ERROR_FILE_PARTIALLY_UPLOADED');
+ break;
+ case Enums.UploadErrorCode.FileNoUploaded:
+ sResult = Utils.i18n('UPLOAD/ERROR_NO_FILE_UPLOADED');
+ break;
+ case Enums.UploadErrorCode.MissingTempFolder:
+ sResult = Utils.i18n('UPLOAD/ERROR_MISSING_TEMP_FOLDER');
+ break;
+ case Enums.UploadErrorCode.FileOnSaveingError:
+ sResult = Utils.i18n('UPLOAD/ERROR_ON_SAVING_FILE');
+ break;
+ case Enums.UploadErrorCode.FileType:
+ sResult = Utils.i18n('UPLOAD/ERROR_FILE_TYPE');
+ break;
+ default:
+ sResult = Utils.i18n('UPLOAD/ERROR_UNKNOWN');
+ break;
+ }
+
+ return sResult;
+ };
+
+ /**
+ * @param {?} oObject
+ * @param {string} sMethodName
+ * @param {Array=} aParameters
+ * @param {number=} nDelay
+ */
+ Utils.delegateRun = function (oObject, sMethodName, aParameters, nDelay)
+ {
+ if (oObject && oObject[sMethodName])
+ {
+ nDelay = Utils.pInt(nDelay);
+ if (0 >= nDelay)
+ {
+ oObject[sMethodName].apply(oObject, Utils.isArray(aParameters) ? aParameters : []);
+ }
+ else
+ {
+ _.delay(function () {
+ oObject[sMethodName].apply(oObject, Utils.isArray(aParameters) ? aParameters : []);
+ }, nDelay);
}
}
- else if (window.webkitNotifications && window.webkitNotifications.checkPermission)
+ };
+
+ /**
+ * @param {?} oEvent
+ */
+ Utils.killCtrlAandS = function (oEvent)
+ {
+ oEvent = oEvent || window.event;
+ if (oEvent && oEvent.ctrlKey && !oEvent.shiftKey && !oEvent.altKey)
{
- iResult = window.webkitNotifications.checkPermission();
- }
+ var
+ oSender = oEvent.target || oEvent.srcElement,
+ iKey = oEvent.keyCode || oEvent.which
+ ;
- return iResult;
- });
-
- oData.useDesktopNotifications = ko.computed({
- 'read': function () {
- return oData.desktopNotifications() &&
- Enums.DesktopNotifications.Allowed === oData.desktopNotificationsPermisions();
- },
- 'write': function (bValue) {
- if (bValue)
+ if (iKey === Enums.EventKeyCode.S)
{
- var iPermission = oData.desktopNotificationsPermisions();
- if (Enums.DesktopNotifications.Allowed === iPermission)
+ oEvent.preventDefault();
+ return;
+ }
+
+ if (oSender && oSender.tagName && oSender.tagName.match(/INPUT|TEXTAREA/i))
+ {
+ return;
+ }
+
+ if (iKey === Enums.EventKeyCode.A)
+ {
+ if (window.getSelection)
{
- oData.desktopNotifications(true);
+ window.getSelection().removeAllRanges();
}
- else if (Enums.DesktopNotifications.NotAllowed === iPermission)
+ else if (window.document.selection && window.document.selection.clear)
{
- NotificationClass.requestPermission(function () {
- oData.desktopNotifications.valueHasMutated();
- if (Enums.DesktopNotifications.Allowed === oData.desktopNotificationsPermisions())
- {
- if (oData.desktopNotifications())
+ window.document.selection.clear();
+ }
+
+ oEvent.preventDefault();
+ }
+ }
+ };
+
+ /**
+ * @param {(Object|null|undefined)} oContext
+ * @param {Function} fExecute
+ * @param {(Function|boolean|null)=} fCanExecute
+ * @return {Function}
+ */
+ Utils.createCommand = function (oContext, fExecute, fCanExecute)
+ {
+ var
+ fResult = fExecute ? function () {
+ if (fResult.canExecute && fResult.canExecute())
+ {
+ fExecute.apply(oContext, Array.prototype.slice.call(arguments));
+ }
+ return false;
+ } : function () {}
+ ;
+
+ fResult.enabled = ko.observable(true);
+
+ fCanExecute = Utils.isUnd(fCanExecute) ? true : fCanExecute;
+ if (Utils.isFunc(fCanExecute))
+ {
+ fResult.canExecute = ko.computed(function () {
+ return fResult.enabled() && fCanExecute.call(oContext);
+ });
+ }
+ else
+ {
+ fResult.canExecute = ko.computed(function () {
+ return fResult.enabled() && !!fCanExecute;
+ });
+ }
+
+ return fResult;
+ };
+
+ /**
+ * @param {Object} oData
+ */
+ Utils.initDataConstructorBySettings = function (oData)
+ {
+ oData.editorDefaultType = ko.observable(Enums.EditorDefaultType.Html);
+ oData.showImages = ko.observable(false);
+ oData.interfaceAnimation = ko.observable(Enums.InterfaceAnimation.Full);
+ oData.contactsAutosave = ko.observable(false);
+
+ Globals.sAnimationType = Enums.InterfaceAnimation.Full;
+
+ oData.capaThemes = ko.observable(false);
+ oData.allowLanguagesOnSettings = ko.observable(true);
+ oData.allowLanguagesOnLogin = ko.observable(true);
+
+ oData.useLocalProxyForExternalImages = ko.observable(false);
+
+ oData.desktopNotifications = ko.observable(false);
+ oData.useThreads = ko.observable(true);
+ oData.replySameFolder = ko.observable(true);
+ oData.useCheckboxesInList = ko.observable(true);
+
+ oData.layout = ko.observable(Enums.Layout.SidePreview);
+ oData.usePreviewPane = ko.computed(function () {
+ return Enums.Layout.NoPreview !== oData.layout();
+ });
+
+ oData.interfaceAnimation.subscribe(function (sValue) {
+ if (Globals.bMobileDevice || sValue === Enums.InterfaceAnimation.None)
+ {
+ $html.removeClass('rl-anim rl-anim-full').addClass('no-rl-anim');
+
+ Globals.sAnimationType = Enums.InterfaceAnimation.None;
+ }
+ else
+ {
+ switch (sValue)
+ {
+ case Enums.InterfaceAnimation.Full:
+ $html.removeClass('no-rl-anim').addClass('rl-anim rl-anim-full');
+ Globals.sAnimationType = sValue;
+ break;
+ case Enums.InterfaceAnimation.Normal:
+ $html.removeClass('no-rl-anim rl-anim-full').addClass('rl-anim');
+ Globals.sAnimationType = sValue;
+ break;
+ }
+ }
+ });
+
+ oData.interfaceAnimation.valueHasMutated();
+
+ oData.desktopNotificationsPermisions = ko.computed(function () {
+ oData.desktopNotifications();
+ var iResult = Enums.DesktopNotifications.NotSupported;
+ if (NotificationClass && NotificationClass.permission)
+ {
+ switch (NotificationClass.permission.toLowerCase())
+ {
+ case 'granted':
+ iResult = Enums.DesktopNotifications.Allowed;
+ break;
+ case 'denied':
+ iResult = Enums.DesktopNotifications.Denied;
+ break;
+ case 'default':
+ iResult = Enums.DesktopNotifications.NotAllowed;
+ break;
+ }
+ }
+ else if (window.webkitNotifications && window.webkitNotifications.checkPermission)
+ {
+ iResult = window.webkitNotifications.checkPermission();
+ }
+
+ return iResult;
+ });
+
+ oData.useDesktopNotifications = ko.computed({
+ 'read': function () {
+ return oData.desktopNotifications() &&
+ Enums.DesktopNotifications.Allowed === oData.desktopNotificationsPermisions();
+ },
+ 'write': function (bValue) {
+ if (bValue)
+ {
+ var iPermission = oData.desktopNotificationsPermisions();
+ if (Enums.DesktopNotifications.Allowed === iPermission)
+ {
+ oData.desktopNotifications(true);
+ }
+ else if (Enums.DesktopNotifications.NotAllowed === iPermission)
+ {
+ NotificationClass.requestPermission(function () {
+ oData.desktopNotifications.valueHasMutated();
+ if (Enums.DesktopNotifications.Allowed === oData.desktopNotificationsPermisions())
{
- oData.desktopNotifications.valueHasMutated();
+ if (oData.desktopNotifications())
+ {
+ oData.desktopNotifications.valueHasMutated();
+ }
+ else
+ {
+ oData.desktopNotifications(true);
+ }
}
else
{
- oData.desktopNotifications(true);
+ if (oData.desktopNotifications())
+ {
+ oData.desktopNotifications(false);
+ }
+ else
+ {
+ oData.desktopNotifications.valueHasMutated();
+ }
}
- }
- else
- {
- if (oData.desktopNotifications())
- {
- oData.desktopNotifications(false);
- }
- else
- {
- oData.desktopNotifications.valueHasMutated();
- }
- }
- });
+ });
+ }
+ else
+ {
+ oData.desktopNotifications(false);
+ }
}
else
{
oData.desktopNotifications(false);
}
}
- else
- {
- oData.desktopNotifications(false);
- }
- }
- });
+ });
- oData.language = ko.observable('');
- oData.languages = ko.observableArray([]);
+ oData.language = ko.observable('');
+ oData.languages = ko.observableArray([]);
- oData.mainLanguage = ko.computed({
- 'read': oData.language,
- 'write': function (sValue) {
- if (sValue !== oData.language())
- {
- if (-1 < Utils.inArray(sValue, oData.languages()))
+ oData.mainLanguage = ko.computed({
+ 'read': oData.language,
+ 'write': function (sValue) {
+ if (sValue !== oData.language())
{
- oData.language(sValue);
+ if (-1 < Utils.inArray(sValue, oData.languages()))
+ {
+ oData.language(sValue);
+ }
+ else if (0 < oData.languages().length)
+ {
+ oData.language(oData.languages()[0]);
+ }
}
- else if (0 < oData.languages().length)
+ else
{
- oData.language(oData.languages()[0]);
+ oData.language.valueHasMutated();
}
}
- else
- {
- oData.language.valueHasMutated();
- }
- }
- });
+ });
- oData.theme = ko.observable('');
- oData.themes = ko.observableArray([]);
+ oData.theme = ko.observable('');
+ oData.themes = ko.observableArray([]);
- oData.mainTheme = ko.computed({
- 'read': oData.theme,
- 'write': function (sValue) {
- if (sValue !== oData.theme())
- {
- var aThemes = oData.themes();
- if (-1 < Utils.inArray(sValue, aThemes))
+ oData.mainTheme = ko.computed({
+ 'read': oData.theme,
+ 'write': function (sValue) {
+ if (sValue !== oData.theme())
{
- oData.theme(sValue);
+ var aThemes = oData.themes();
+ if (-1 < Utils.inArray(sValue, aThemes))
+ {
+ oData.theme(sValue);
+ }
+ else if (0 < aThemes.length)
+ {
+ oData.theme(aThemes[0]);
+ }
}
- else if (0 < aThemes.length)
+ else
{
- oData.theme(aThemes[0]);
+ oData.theme.valueHasMutated();
}
}
- else
- {
- oData.theme.valueHasMutated();
- }
- }
- });
+ });
- oData.capaAdditionalAccounts = ko.observable(false);
- oData.capaAdditionalIdentities = ko.observable(false);
- oData.capaGravatar = ko.observable(false);
- oData.determineUserLanguage = ko.observable(false);
- oData.determineUserDomain = ko.observable(false);
+ oData.capaAdditionalAccounts = ko.observable(false);
+ oData.capaAdditionalIdentities = ko.observable(false);
+ oData.capaGravatar = ko.observable(false);
+ oData.determineUserLanguage = ko.observable(false);
+ oData.determineUserDomain = ko.observable(false);
- oData.messagesPerPage = ko.observable(Consts.Defaults.MessagesPerPage);//.extend({'throttle': 200});
+ oData.messagesPerPage = ko.observable(Consts.Defaults.MessagesPerPage);//.extend({'throttle': 200});
- oData.mainMessagesPerPage = oData.messagesPerPage;
- oData.mainMessagesPerPage = ko.computed({
- 'read': oData.messagesPerPage,
- 'write': function (iValue) {
- if (-1 < Utils.inArray(Utils.pInt(iValue), Consts.Defaults.MessagesPerPageArray))
- {
- if (iValue !== oData.messagesPerPage())
+ oData.mainMessagesPerPage = oData.messagesPerPage;
+ oData.mainMessagesPerPage = ko.computed({
+ 'read': oData.messagesPerPage,
+ 'write': function (iValue) {
+ if (-1 < Utils.inArray(Utils.pInt(iValue), Consts.Defaults.MessagesPerPageArray))
{
- oData.messagesPerPage(iValue);
+ if (iValue !== oData.messagesPerPage())
+ {
+ oData.messagesPerPage(iValue);
+ }
+ }
+ else
+ {
+ oData.messagesPerPage.valueHasMutated();
}
}
- else
- {
- oData.messagesPerPage.valueHasMutated();
- }
- }
- });
+ });
- oData.facebookSupported = ko.observable(false);
- oData.facebookEnable = ko.observable(false);
- oData.facebookAppID = ko.observable('');
- oData.facebookAppSecret = ko.observable('');
+ oData.facebookSupported = ko.observable(false);
+ oData.facebookEnable = ko.observable(false);
+ oData.facebookAppID = ko.observable('');
+ oData.facebookAppSecret = ko.observable('');
- oData.twitterEnable = ko.observable(false);
- oData.twitterConsumerKey = ko.observable('');
- oData.twitterConsumerSecret = ko.observable('');
+ oData.twitterEnable = ko.observable(false);
+ oData.twitterConsumerKey = ko.observable('');
+ oData.twitterConsumerSecret = ko.observable('');
- oData.googleEnable = ko.observable(false);
- oData.googleClientID = ko.observable('');
- oData.googleClientSecret = ko.observable('');
- oData.googleApiKey = ko.observable('');
+ oData.googleEnable = ko.observable(false);
+ oData.googleClientID = ko.observable('');
+ oData.googleClientSecret = ko.observable('');
+ oData.googleApiKey = ko.observable('');
- oData.dropboxEnable = ko.observable(false);
- oData.dropboxApiKey = ko.observable('');
+ oData.dropboxEnable = ko.observable(false);
+ oData.dropboxApiKey = ko.observable('');
- oData.contactsIsAllowed = ko.observable(false);
-};
+ oData.contactsIsAllowed = ko.observable(false);
+ };
-/**
- * @param {{moment:Function}} oObject
- */
-Utils.createMomentDate = function (oObject)
-{
- if (Utils.isUnd(oObject.moment))
+ /**
+ * @param {{moment:Function}} oObject
+ */
+ Utils.createMomentDate = function (oObject)
{
- oObject.moment = ko.observable(moment());
- }
-
- return ko.computed(function () {
- Globals.momentTrigger();
- var oMoment = this.moment();
- return 1970 === oMoment.year() ? '' : oMoment.fromNow();
- }, oObject);
-};
-
-/**
- * @param {{moment:Function, momentDate:Function}} oObject
- */
-Utils.createMomentShortDate = function (oObject)
-{
- return ko.computed(function () {
-
- var
- sResult = '',
- oMomentNow = moment(),
- oMoment = this.moment(),
- sMomentDate = this.momentDate()
- ;
-
- if (1970 === oMoment.year())
+ if (Utils.isUnd(oObject.moment))
{
- sResult = '';
+ oObject.moment = ko.observable(moment());
}
- else if (4 >= oMomentNow.diff(oMoment, 'hours'))
+
+ return ko.computed(function () {
+ Globals.momentTrigger();
+ var oMoment = this.moment();
+ return 1970 === oMoment.year() ? '' : oMoment.fromNow();
+ }, oObject);
+ };
+
+ /**
+ * @param {{moment:Function, momentDate:Function}} oObject
+ */
+ Utils.createMomentShortDate = function (oObject)
+ {
+ return ko.computed(function () {
+
+ var
+ sResult = '',
+ oMomentNow = moment(),
+ oMoment = this.moment(),
+ sMomentDate = this.momentDate()
+ ;
+
+ if (1970 === oMoment.year())
+ {
+ sResult = '';
+ }
+ else if (4 >= oMomentNow.diff(oMoment, 'hours'))
+ {
+ sResult = sMomentDate;
+ }
+ else if (oMomentNow.format('L') === oMoment.format('L'))
+ {
+ sResult = Utils.i18n('MESSAGE_LIST/TODAY_AT', {
+ 'TIME': oMoment.format('LT')
+ });
+ }
+ else if (oMomentNow.clone().subtract('days', 1).format('L') === oMoment.format('L'))
+ {
+ sResult = Utils.i18n('MESSAGE_LIST/YESTERDAY_AT', {
+ 'TIME': oMoment.format('LT')
+ });
+ }
+ else if (oMomentNow.year() === oMoment.year())
+ {
+ sResult = oMoment.format('D MMM.');
+ }
+ else
+ {
+ sResult = oMoment.format('LL');
+ }
+
+ return sResult;
+
+ }, oObject);
+ };
+
+ /**
+ * @param {string} sFullNameHash
+ * @return {boolean}
+ */
+ Utils.isFolderExpanded = function (sFullNameHash)
+ {
+ var aExpandedList = /** @type {Array|null} */ LocalStorage.get(Enums.ClientSideKeyName.ExpandedFolders);
+ return _.isArray(aExpandedList) && -1 !== _.indexOf(aExpandedList, sFullNameHash);
+ };
+
+ /**
+ * @param {string} sFullNameHash
+ * @param {boolean} bExpanded
+ */
+ Utils.setExpandedFolder = function (sFullNameHash, bExpanded)
+ {
+ var aExpandedList = /** @type {Array|null} */ LocalStorage.get(Enums.ClientSideKeyName.ExpandedFolders);
+ if (!_.isArray(aExpandedList))
{
- sResult = sMomentDate;
+ aExpandedList = [];
}
- else if (oMomentNow.format('L') === oMoment.format('L'))
+
+ if (bExpanded)
{
- sResult = Utils.i18n('MESSAGE_LIST/TODAY_AT', {
- 'TIME': oMoment.format('LT')
- });
- }
- else if (oMomentNow.clone().subtract('days', 1).format('L') === oMoment.format('L'))
- {
- sResult = Utils.i18n('MESSAGE_LIST/YESTERDAY_AT', {
- 'TIME': oMoment.format('LT')
- });
- }
- else if (oMomentNow.year() === oMoment.year())
- {
- sResult = oMoment.format('D MMM.');
+ aExpandedList.push(sFullNameHash);
+ aExpandedList = _.uniq(aExpandedList);
}
else
{
- sResult = oMoment.format('LL');
+ aExpandedList = _.without(aExpandedList, sFullNameHash);
+ }
+
+ LocalStorage.set(Enums.ClientSideKeyName.ExpandedFolders, aExpandedList);
+ };
+
+ Utils.initLayoutResizer = function (sLeft, sRight, sClientSideKeyName)
+ {
+ var
+ iDisabledWidth = 60,
+ iMinWidth = 155,
+ oLeft = $(sLeft),
+ oRight = $(sRight),
+
+ mLeftWidth = LocalStorage.get(sClientSideKeyName) || null,
+
+ fSetWidth = function (iWidth) {
+ if (iWidth)
+ {
+ oLeft.css({
+ 'width': '' + iWidth + 'px'
+ });
+
+ oRight.css({
+ 'left': '' + iWidth + 'px'
+ });
+ }
+ },
+
+ fDisable = function (bDisable) {
+ if (bDisable)
+ {
+ oLeft.resizable('disable');
+ fSetWidth(iDisabledWidth);
+ }
+ else
+ {
+ oLeft.resizable('enable');
+ var iWidth = Utils.pInt(LocalStorage.get(sClientSideKeyName)) || iMinWidth;
+ fSetWidth(iWidth > iMinWidth ? iWidth : iMinWidth);
+ }
+ },
+
+ fResizeFunction = function (oEvent, oObject) {
+ if (oObject && oObject.size && oObject.size.width)
+ {
+ LocalStorage.set(sClientSideKeyName, oObject.size.width);
+
+ oRight.css({
+ 'left': '' + oObject.size.width + 'px'
+ });
+ }
+ }
+ ;
+
+ if (null !== mLeftWidth)
+ {
+ fSetWidth(mLeftWidth > iMinWidth ? mLeftWidth : iMinWidth);
+ }
+
+ oLeft.resizable({
+ 'helper': 'ui-resizable-helper',
+ 'minWidth': iMinWidth,
+ 'maxWidth': 350,
+ 'handles': 'e',
+ 'stop': fResizeFunction
+ });
+
+ RL.sub('left-panel.off', function () {
+ fDisable(true);
+ });
+
+ RL.sub('left-panel.on', function () {
+ fDisable(false);
+ });
+ };
+
+ /**
+ * @param {Object} oMessageTextBody
+ */
+ Utils.initBlockquoteSwitcher = function (oMessageTextBody)
+ {
+ if (oMessageTextBody)
+ {
+ var $oList = $('blockquote:not(.rl-bq-switcher)', oMessageTextBody).filter(function () {
+ return 0 === $(this).parent().closest('blockquote', oMessageTextBody).length;
+ });
+
+ if ($oList && 0 < $oList.length)
+ {
+ $oList.each(function () {
+ var $self = $(this), iH = $self.height();
+ if (0 === iH || 100 < iH)
+ {
+ $self.addClass('rl-bq-switcher hidden-bq');
+ $('')
+ .insertBefore($self)
+ .click(function () {
+ $self.toggleClass('hidden-bq');
+ Utils.windowResize();
+ })
+ .after('
')
+ .before('
')
+ ;
+ }
+ });
+ }
+ }
+ };
+
+ /**
+ * @param {Object} oMessageTextBody
+ */
+ Utils.removeBlockquoteSwitcher = function (oMessageTextBody)
+ {
+ if (oMessageTextBody)
+ {
+ $(oMessageTextBody).find('blockquote.rl-bq-switcher').each(function () {
+ $(this).removeClass('rl-bq-switcher hidden-bq');
+ });
+
+ $(oMessageTextBody).find('.rlBlockquoteSwitcher').each(function () {
+ $(this).remove();
+ });
+ }
+ };
+
+ /**
+ * @param {Object} oMessageTextBody
+ */
+ Utils.toggleMessageBlockquote = function (oMessageTextBody)
+ {
+ if (oMessageTextBody)
+ {
+ oMessageTextBody.find('.rlBlockquoteSwitcher').click();
+ }
+ };
+
+ Utils.convertThemeName = function (sTheme)
+ {
+ if ('@custom' === sTheme.substr(-7))
+ {
+ sTheme = Utils.trim(sTheme.substring(0, sTheme.length - 7));
+ }
+
+ return Utils.trim(sTheme.replace(/[^a-zA-Z]+/g, ' ').replace(/([A-Z])/g, ' $1').replace(/[\s]+/g, ' '));
+ };
+
+ /**
+ * @param {string} sName
+ * @return {string}
+ */
+ Utils.quoteName = function (sName)
+ {
+ return sName.replace(/["]/g, '\\"');
+ };
+
+ /**
+ * @return {number}
+ */
+ Utils.microtime = function ()
+ {
+ return (new Date()).getTime();
+ };
+
+ /**
+ *
+ * @param {string} sLanguage
+ * @param {boolean=} bEng = false
+ * @return {string}
+ */
+ Utils.convertLangName = function (sLanguage, bEng)
+ {
+ return Utils.i18n('LANGS_NAMES' + (true === bEng ? '_EN' : '') + '/LANG_' +
+ sLanguage.toUpperCase().replace(/[^a-zA-Z0-9]+/, '_'), null, sLanguage);
+ };
+
+ /**
+ * @param {number=} iLen
+ * @return {string}
+ */
+ Utils.fakeMd5 = function(iLen)
+ {
+ var
+ sResult = '',
+ sLine = '0123456789abcdefghijklmnopqrstuvwxyz'
+ ;
+
+ iLen = Utils.isUnd(iLen) ? 32 : Utils.pInt(iLen);
+
+ while (sResult.length < iLen)
+ {
+ sResult += sLine.substr(window.Math.round(window.Math.random() * sLine.length), 1);
}
return sResult;
-
- }, oObject);
-};
-
-/**
- * @param {string} sFullNameHash
- * @return {boolean}
- */
-Utils.isFolderExpanded = function (sFullNameHash)
-{
- var aExpandedList = /** @type {Array|null} */ RL.local().get(Enums.ClientSideKeyName.ExpandedFolders);
- return _.isArray(aExpandedList) && -1 !== _.indexOf(aExpandedList, sFullNameHash);
-};
-
-/**
- * @param {string} sFullNameHash
- * @param {boolean} bExpanded
- */
-Utils.setExpandedFolder = function (sFullNameHash, bExpanded)
-{
- var aExpandedList = /** @type {Array|null} */ RL.local().get(Enums.ClientSideKeyName.ExpandedFolders);
- if (!_.isArray(aExpandedList))
- {
- aExpandedList = [];
- }
-
- if (bExpanded)
- {
- aExpandedList.push(sFullNameHash);
- aExpandedList = _.uniq(aExpandedList);
- }
- else
- {
- aExpandedList = _.without(aExpandedList, sFullNameHash);
- }
-
- RL.local().set(Enums.ClientSideKeyName.ExpandedFolders, aExpandedList);
-};
-
-Utils.initLayoutResizer = function (sLeft, sRight, sClientSideKeyName)
-{
- var
- iDisabledWidth = 60,
- iMinWidth = 155,
- oLeft = $(sLeft),
- oRight = $(sRight),
-
- mLeftWidth = RL.local().get(sClientSideKeyName) || null,
-
- fSetWidth = function (iWidth) {
- if (iWidth)
- {
- oLeft.css({
- 'width': '' + iWidth + 'px'
- });
-
- oRight.css({
- 'left': '' + iWidth + 'px'
- });
- }
- },
-
- fDisable = function (bDisable) {
- if (bDisable)
- {
- oLeft.resizable('disable');
- fSetWidth(iDisabledWidth);
- }
- else
- {
- oLeft.resizable('enable');
- var iWidth = Utils.pInt(RL.local().get(sClientSideKeyName)) || iMinWidth;
- fSetWidth(iWidth > iMinWidth ? iWidth : iMinWidth);
- }
- },
-
- fResizeFunction = function (oEvent, oObject) {
- if (oObject && oObject.size && oObject.size.width)
- {
- RL.local().set(sClientSideKeyName, oObject.size.width);
-
- oRight.css({
- 'left': '' + oObject.size.width + 'px'
- });
- }
- }
- ;
-
- if (null !== mLeftWidth)
- {
- fSetWidth(mLeftWidth > iMinWidth ? mLeftWidth : iMinWidth);
- }
-
- oLeft.resizable({
- 'helper': 'ui-resizable-helper',
- 'minWidth': iMinWidth,
- 'maxWidth': 350,
- 'handles': 'e',
- 'stop': fResizeFunction
- });
-
- RL.sub('left-panel.off', function () {
- fDisable(true);
- });
-
- RL.sub('left-panel.on', function () {
- fDisable(false);
- });
-};
-
-/**
- * @param {Object} oMessageTextBody
- */
-Utils.initBlockquoteSwitcher = function (oMessageTextBody)
-{
- if (oMessageTextBody)
- {
- var $oList = $('blockquote:not(.rl-bq-switcher)', oMessageTextBody).filter(function () {
- return 0 === $(this).parent().closest('blockquote', oMessageTextBody).length;
- });
-
- if ($oList && 0 < $oList.length)
- {
- $oList.each(function () {
- var $self = $(this), iH = $self.height();
- if (0 === iH || 100 < iH)
- {
- $self.addClass('rl-bq-switcher hidden-bq');
- $('')
- .insertBefore($self)
- .click(function () {
- $self.toggleClass('hidden-bq');
- Utils.windowResize();
- })
- .after('
')
- .before('
')
- ;
- }
- });
- }
- }
-};
-
-/**
- * @param {Object} oMessageTextBody
- */
-Utils.removeBlockquoteSwitcher = function (oMessageTextBody)
-{
- if (oMessageTextBody)
- {
- $(oMessageTextBody).find('blockquote.rl-bq-switcher').each(function () {
- $(this).removeClass('rl-bq-switcher hidden-bq');
- });
-
- $(oMessageTextBody).find('.rlBlockquoteSwitcher').each(function () {
- $(this).remove();
- });
- }
-};
-
-/**
- * @param {Object} oMessageTextBody
- */
-Utils.toggleMessageBlockquote = function (oMessageTextBody)
-{
- if (oMessageTextBody)
- {
- oMessageTextBody.find('.rlBlockquoteSwitcher').click();
- }
-};
-
-/**
- * @param {string} sName
- * @param {Function} ViewModelClass
- * @param {Function=} AbstractViewModel = KnoinAbstractViewModel
- */
-Utils.extendAsViewModel = function (sName, ViewModelClass, AbstractViewModel)
-{
- if (ViewModelClass)
- {
- if (!AbstractViewModel)
- {
- AbstractViewModel = KnoinAbstractViewModel;
- }
-
- ViewModelClass.__name = sName;
- Plugins.regViewModelHook(sName, ViewModelClass);
- _.extend(ViewModelClass.prototype, AbstractViewModel.prototype);
- }
-};
-
-/**
- * @param {Function} SettingsViewModelClass
- * @param {string} sLabelName
- * @param {string} sTemplate
- * @param {string} sRoute
- * @param {boolean=} bDefault
- */
-Utils.addSettingsViewModel = function (SettingsViewModelClass, sTemplate, sLabelName, sRoute, bDefault)
-{
- SettingsViewModelClass.__rlSettingsData = {
- 'Label': sLabelName,
- 'Template': sTemplate,
- 'Route': sRoute,
- 'IsDefault': !!bDefault
};
- ViewModels['settings'].push(SettingsViewModelClass);
-};
+ /* jshint ignore:start */
-/**
- * @param {Function} SettingsViewModelClass
- */
-Utils.removeSettingsViewModel = function (SettingsViewModelClass)
-{
- ViewModels['settings-removed'].push(SettingsViewModelClass);
-};
+ /**
+ * @param {string} s
+ * @return {string}
+ */
+ Utils.md5 = function(s){function L(k,d){return(k<>>(32-d))}function K(G,k){var I,d,F,H,x;F=(G&2147483648);H=(k&2147483648);I=(G&1073741824);d=(k&1073741824);x=(G&1073741823)+(k&1073741823);if(I&d){return(x^2147483648^F^H)}if(I|d){if(x&1073741824){return(x^3221225472^F^H)}else{return(x^1073741824^F^H)}}else{return(x^F^H)}}function r(d,F,k){return(d&F)|((~d)&k)}function q(d,F,k){return(d&k)|(F&(~k))}function p(d,F,k){return(d^F^k)}function n(d,F,k){return(F^(d|(~k)))}function u(G,F,aa,Z,k,H,I){G=K(G,K(K(r(F,aa,Z),k),I));return K(L(G,H),F)}function f(G,F,aa,Z,k,H,I){G=K(G,K(K(q(F,aa,Z),k),I));return K(L(G,H),F)}function D(G,F,aa,Z,k,H,I){G=K(G,K(K(p(F,aa,Z),k),I));return K(L(G,H),F)}function t(G,F,aa,Z,k,H,I){G=K(G,K(K(n(F,aa,Z),k),I));return K(L(G,H),F)}function e(G){var Z;var F=G.length;var x=F+8;var k=(x-(x%64))/64;var I=(k+1)*16;var aa=Array(I-1);var d=0;var H=0;while(H>>29;return aa}function B(x){var k="",F="",G,d;for(d=0;d<=3;d++){G=(x>>>(d*8))&255;F="0"+G.toString(16);k=k+F.substr(F.length-2,2)}return k}function J(k){k=k.replace(/rn/g,"n");var d="";for(var F=0;F127)&&(x<2048)){d+=String.fromCharCode((x>>6)|192);d+=String.fromCharCode((x&63)|128)}else{d+=String.fromCharCode((x>>12)|224);d+=String.fromCharCode(((x>>6)&63)|128);d+=String.fromCharCode((x&63)|128)}}}return d}var C=Array();var P,h,E,v,g,Y,X,W,V;var S=7,Q=12,N=17,M=22;var A=5,z=9,y=14,w=20;var o=4,m=11,l=16,j=23;var U=6,T=10,R=15,O=21;s=J(s);C=e(s);Y=1732584193;X=4023233417;W=2562383102;V=271733878;for(P=0;P>>(32-d))}function K(G,k){var I,d,F,H,x;F=(G&2147483648);H=(k&2147483648);I=(G&1073741824);d=(k&1073741824);x=(G&1073741823)+(k&1073741823);if(I&d){return(x^2147483648^F^H)}if(I|d){if(x&1073741824){return(x^3221225472^F^H)}else{return(x^1073741824^F^H)}}else{return(x^F^H)}}function r(d,F,k){return(d&F)|((~d)&k)}function q(d,F,k){return(d&k)|(F&(~k))}function p(d,F,k){return(d^F^k)}function n(d,F,k){return(F^(d|(~k)))}function u(G,F,aa,Z,k,H,I){G=K(G,K(K(r(F,aa,Z),k),I));return K(L(G,H),F)}function f(G,F,aa,Z,k,H,I){G=K(G,K(K(q(F,aa,Z),k),I));return K(L(G,H),F)}function D(G,F,aa,Z,k,H,I){G=K(G,K(K(p(F,aa,Z),k),I));return K(L(G,H),F)}function t(G,F,aa,Z,k,H,I){G=K(G,K(K(n(F,aa,Z),k),I));return K(L(G,H),F)}function e(G){var Z;var F=G.length;var x=F+8;var k=(x-(x%64))/64;var I=(k+1)*16;var aa=Array(I-1);var d=0;var H=0;while(H>>29;return aa}function B(x){var k="",F="",G,d;for(d=0;d<=3;d++){G=(x>>>(d*8))&255;F="0"+G.toString(16);k=k+F.substr(F.length-2,2)}return k}function J(k){k=k.replace(/rn/g,"n");var d="";for(var F=0;F127)&&(x<2048)){d+=String.fromCharCode((x>>6)|192);d+=String.fromCharCode((x&63)|128)}else{d+=String.fromCharCode((x>>12)|224);d+=String.fromCharCode(((x>>6)&63)|128);d+=String.fromCharCode((x&63)|128)}}}return d}var C=Array();var P,h,E,v,g,Y,X,W,V;var S=7,Q=12,N=17,M=22;var A=5,z=9,y=14,w=20;var o=4,m=11,l=16,j=23;var U=6,T=10,R=15,O=21;s=J(s);C=e(s);Y=1732584193;X=4023233417;W=2562383102;V=271733878;for(P=0;P /g, '>').replace(/');
-};
-
-Utils.draggeblePlace = function ()
-{
- return $(' ').appendTo('#rl-hidden');
-};
-
-Utils.defautOptionsAfterRender = function (oOption, oItem)
-{
- if (oItem && !Utils.isUnd(oItem.disabled) && oOption)
- {
- $(oOption)
- .toggleClass('disabled', oItem.disabled)
- .prop('disabled', oItem.disabled)
- ;
- }
-};
-
-/**
- * @param {Object} oViewModel
- * @param {string} sTemplateID
- * @param {string} sTitle
- * @param {Function=} fCallback
- */
-Utils.windowPopupKnockout = function (oViewModel, sTemplateID, sTitle, fCallback)
-{
- var
- oScript = null,
- oWin = window.open(''),
- sFunc = '__OpenerApplyBindingsUid' + Utils.fakeMd5() + '__',
- oTemplate = $('#' + sTemplateID)
- ;
-
- window[sFunc] = function () {
-
- if (oWin && oWin.document.body && oTemplate && oTemplate[0])
- {
- var oBody = $(oWin.document.body);
-
- $('#rl-content', oBody).html(oTemplate.html());
- $('html', oWin.document).addClass('external ' + $('html').attr('class'));
-
- Utils.i18nToNode(oBody);
-
- Knoin.prototype.applyExternal(oViewModel, $('#rl-content', oBody)[0]);
-
- window[sFunc] = null;
-
- fCallback(oWin);
- }
+ return sPlain.toString()
+ .replace(/&/g, '&').replace(/>/g, '>').replace(/');
};
- oWin.document.open();
- oWin.document.write('' +
-'' +
-'' +
-'' +
-'' +
-'' +
-'' + Utils.encodeHtml(sTitle) + ' ' +
-'');
- oWin.document.close();
-
- oScript = oWin.document.createElement('script');
- oScript.type = 'text/javascript';
- oScript.innerHTML = 'if(window&&window.opener&&window.opener[\'' + sFunc + '\']){window.opener[\'' + sFunc + '\']();window.opener[\'' + sFunc + '\']=null}';
- oWin.document.getElementsByTagName('head')[0].appendChild(oScript);
-};
-
-Utils.settingsSaveHelperFunction = function (fCallback, koTrigger, oContext, iTimer)
-{
- oContext = oContext || null;
- iTimer = Utils.isUnd(iTimer) ? 1000 : Utils.pInt(iTimer);
- return function (sType, mData, bCached, sRequestAction, oRequestParameters) {
- koTrigger.call(oContext, mData && mData['Result'] ? Enums.SaveSettingsStep.TrueResult : Enums.SaveSettingsStep.FalseResult);
- if (fCallback)
- {
- fCallback.call(oContext, sType, mData, bCached, sRequestAction, oRequestParameters);
- }
- _.delay(function () {
- koTrigger.call(oContext, Enums.SaveSettingsStep.Idle);
- }, iTimer);
+ Utils.draggeblePlace = function ()
+ {
+ return $(' ').appendTo('#rl-hidden');
};
-};
-Utils.settingsSaveHelperSimpleFunction = function (koTrigger, oContext)
-{
- return Utils.settingsSaveHelperFunction(null, koTrigger, oContext, 1000);
-};
-
-Utils.$div = $('');
-
-/**
- * @param {string} sHtml
- * @return {string}
- */
-Utils.htmlToPlain = function (sHtml)
-{
- var
- iPos = 0,
- iP1 = 0,
- iP2 = 0,
- iP3 = 0,
- iLimit = 0,
-
- sText = '',
-
- splitPlainText = function (sText)
+ Utils.defautOptionsAfterRender = function (oOption, oItem)
+ {
+ if (oItem && !Utils.isUnd(oItem.disabled) && oOption)
{
- var
- iLen = 100,
- sPrefix = '',
- sSubText = '',
- sResult = sText,
- iSpacePos = 0,
- iNewLinePos = 0
+ $(oOption)
+ .toggleClass('disabled', oItem.disabled)
+ .prop('disabled', oItem.disabled)
;
-
- while (sResult.length > iLen)
- {
- sSubText = sResult.substring(0, iLen);
- iSpacePos = sSubText.lastIndexOf(' ');
- iNewLinePos = sSubText.lastIndexOf('\n');
-
- if (-1 !== iNewLinePos)
- {
- iSpacePos = iNewLinePos;
- }
-
- if (-1 === iSpacePos)
- {
- iSpacePos = iLen;
- }
-
- sPrefix += sSubText.substring(0, iSpacePos) + '\n';
- sResult = sResult.substring(iSpacePos + 1);
- }
-
- return sPrefix + sResult;
- },
-
- convertBlockquote = function (sText) {
- sText = splitPlainText($.trim(sText));
- sText = '> ' + sText.replace(/\n/gm, '\n> ');
- return sText.replace(/(^|\n)([> ]+)/gm, function () {
- return (arguments && 2 < arguments.length) ? arguments[1] + $.trim(arguments[2].replace(/[\s]/, '')) + ' ' : '';
- });
- },
-
- convertDivs = function () {
- if (arguments && 1 < arguments.length)
- {
- var sText = $.trim(arguments[1]);
- if (0 < sText.length)
- {
- sText = sText.replace(/]*>([\s\S\r\n]*)<\/div>/gmi, convertDivs);
- sText = '\n' + $.trim(sText) + '\n';
- }
-
- return sText;
- }
-
- return '';
- },
-
- convertPre = function () {
- return (arguments && 1 < arguments.length) ? arguments[1].toString().replace(/[\n]/gm, '
') : '';
- },
-
- fixAttibuteValue = function () {
- return (arguments && 1 < arguments.length) ?
- '' + arguments[1] + arguments[2].replace(//g, '>') : '';
- },
-
- convertLinks = function () {
- return (arguments && 1 < arguments.length) ? $.trim(arguments[1]) : '';
}
- ;
+ };
- sText = sHtml
- .replace(/]*>([\s\S\r\n]*)<\/pre>/gmi, convertPre)
- .replace(/[\s]+/gm, ' ')
- .replace(/((?:href|data)\s?=\s?)("[^"]+?"|'[^']+?')/gmi, fixAttibuteValue)
- .replace(/
]*>/gmi, '\n')
- .replace(/<\/h[\d]>/gi, '\n')
- .replace(/<\/p>/gi, '\n\n')
- .replace(/<\/li>/gi, '\n')
- .replace(/<\/td>/gi, '\n')
- .replace(/<\/tr>/gi, '\n')
- .replace(/
]*>/gmi, '\n_______________________________\n\n')
- .replace(/]*>([\s\S\r\n]*)<\/div>/gmi, convertDivs)
- .replace(/]*>/gmi, '\n__bq__start__\n')
- .replace(/<\/blockquote>/gmi, '\n__bq__end__\n')
- .replace(/]*>([\s\S\r\n]*?)<\/a>/gmi, convertLinks)
- .replace(/<\/div>/gi, '\n')
- .replace(/ /gi, ' ')
- .replace(/"/gi, '"')
- .replace(/<[^>]*>/gm, '')
- ;
-
- sText = Utils.$div.html(sText).text();
-
- sText = sText
- .replace(/\n[ \t]+/gm, '\n')
- .replace(/[\n]{3,}/gm, '\n\n')
- .replace(/>/gi, '>')
- .replace(/</gi, '<')
- .replace(/&/gi, '&')
- ;
-
- iPos = 0;
- iLimit = 100;
-
- while (0 < iLimit)
+ /**
+ * @param {Object} oViewModel
+ * @param {string} sTemplateID
+ * @param {string} sTitle
+ * @param {Function=} fCallback
+ */
+ Utils.windowPopupKnockout = function (oViewModel, sTemplateID, sTitle, fCallback)
{
- iLimit--;
- iP1 = sText.indexOf('__bq__start__', iPos);
- if (-1 < iP1)
- {
- iP2 = sText.indexOf('__bq__start__', iP1 + 5);
- iP3 = sText.indexOf('__bq__end__', iP1 + 5);
+ var
+ oScript = null,
+ oWin = window.open(''),
+ sFunc = '__OpenerApplyBindingsUid' + Utils.fakeMd5() + '__',
+ oTemplate = $('#' + sTemplateID)
+ ;
- if ((-1 === iP2 || iP3 < iP2) && iP1 < iP3)
+ window[sFunc] = function () {
+
+ if (oWin && oWin.document.body && oTemplate && oTemplate[0])
{
- sText = sText.substring(0, iP1) +
- convertBlockquote(sText.substring(iP1 + 13, iP3)) +
- sText.substring(iP3 + 11);
+ var oBody = $(oWin.document.body);
- iPos = 0;
+ $('#rl-content', oBody).html(oTemplate.html());
+ $('html', oWin.document).addClass('external ' + $('html').attr('class'));
+
+ Utils.i18nToNode(oBody);
+
+ kn.applyExternal(oViewModel, $('#rl-content', oBody)[0]);
+
+ window[sFunc] = null;
+
+ fCallback(oWin);
}
- else if (-1 < iP2 && iP2 < iP3)
+ };
+
+ oWin.document.open();
+ oWin.document.write('' +
+ '' +
+ '' +
+ '' +
+ '' +
+ '' +
+ '' + Utils.encodeHtml(sTitle) + ' ' +
+ '');
+ oWin.document.close();
+
+ oScript = oWin.document.createElement('script');
+ oScript.type = 'text/javascript';
+ oScript.innerHTML = 'if(window&&window.opener&&window.opener[\'' + sFunc + '\']){window.opener[\'' + sFunc + '\']();window.opener[\'' + sFunc + '\']=null}';
+ oWin.document.getElementsByTagName('head')[0].appendChild(oScript);
+ };
+
+ Utils.settingsSaveHelperFunction = function (fCallback, koTrigger, oContext, iTimer)
+ {
+ oContext = oContext || null;
+ iTimer = Utils.isUnd(iTimer) ? 1000 : Utils.pInt(iTimer);
+ return function (sType, mData, bCached, sRequestAction, oRequestParameters) {
+ koTrigger.call(oContext, mData && mData['Result'] ? Enums.SaveSettingsStep.TrueResult : Enums.SaveSettingsStep.FalseResult);
+ if (fCallback)
{
- iPos = iP2 - 1;
+ fCallback.call(oContext, sType, mData, bCached, sRequestAction, oRequestParameters);
+ }
+ _.delay(function () {
+ koTrigger.call(oContext, Enums.SaveSettingsStep.Idle);
+ }, iTimer);
+ };
+ };
+
+ Utils.settingsSaveHelperSimpleFunction = function (koTrigger, oContext)
+ {
+ return Utils.settingsSaveHelperFunction(null, koTrigger, oContext, 1000);
+ };
+
+ Utils.$div = $('');
+
+ /**
+ * @param {string} sHtml
+ * @return {string}
+ */
+ Utils.htmlToPlain = function (sHtml)
+ {
+ var
+ iPos = 0,
+ iP1 = 0,
+ iP2 = 0,
+ iP3 = 0,
+ iLimit = 0,
+
+ sText = '',
+
+ splitPlainText = function (sText)
+ {
+ var
+ iLen = 100,
+ sPrefix = '',
+ sSubText = '',
+ sResult = sText,
+ iSpacePos = 0,
+ iNewLinePos = 0
+ ;
+
+ while (sResult.length > iLen)
+ {
+ sSubText = sResult.substring(0, iLen);
+ iSpacePos = sSubText.lastIndexOf(' ');
+ iNewLinePos = sSubText.lastIndexOf('\n');
+
+ if (-1 !== iNewLinePos)
+ {
+ iSpacePos = iNewLinePos;
+ }
+
+ if (-1 === iSpacePos)
+ {
+ iSpacePos = iLen;
+ }
+
+ sPrefix += sSubText.substring(0, iSpacePos) + '\n';
+ sResult = sResult.substring(iSpacePos + 1);
+ }
+
+ return sPrefix + sResult;
+ },
+
+ convertBlockquote = function (sText) {
+ sText = splitPlainText($.trim(sText));
+ sText = '> ' + sText.replace(/\n/gm, '\n> ');
+ return sText.replace(/(^|\n)([> ]+)/gm, function () {
+ return (arguments && 2 < arguments.length) ? arguments[1] + $.trim(arguments[2].replace(/[\s]/, '')) + ' ' : '';
+ });
+ },
+
+ convertDivs = function () {
+ if (arguments && 1 < arguments.length)
+ {
+ var sText = $.trim(arguments[1]);
+ if (0 < sText.length)
+ {
+ sText = sText.replace(/]*>([\s\S\r\n]*)<\/div>/gmi, convertDivs);
+ sText = '\n' + $.trim(sText) + '\n';
+ }
+
+ return sText;
+ }
+
+ return '';
+ },
+
+ convertPre = function () {
+ return (arguments && 1 < arguments.length) ? arguments[1].toString().replace(/[\n]/gm, '
') : '';
+ },
+
+ fixAttibuteValue = function () {
+ return (arguments && 1 < arguments.length) ?
+ '' + arguments[1] + arguments[2].replace(//g, '>') : '';
+ },
+
+ convertLinks = function () {
+ return (arguments && 1 < arguments.length) ? $.trim(arguments[1]) : '';
+ }
+ ;
+
+ sText = sHtml
+ .replace(/]*>([\s\S\r\n]*)<\/pre>/gmi, convertPre)
+ .replace(/[\s]+/gm, ' ')
+ .replace(/((?:href|data)\s?=\s?)("[^"]+?"|'[^']+?')/gmi, fixAttibuteValue)
+ .replace(/
]*>/gmi, '\n')
+ .replace(/<\/h[\d]>/gi, '\n')
+ .replace(/<\/p>/gi, '\n\n')
+ .replace(/<\/li>/gi, '\n')
+ .replace(/<\/td>/gi, '\n')
+ .replace(/<\/tr>/gi, '\n')
+ .replace(/
]*>/gmi, '\n_______________________________\n\n')
+ .replace(/]*>([\s\S\r\n]*)<\/div>/gmi, convertDivs)
+ .replace(/]*>/gmi, '\n__bq__start__\n')
+ .replace(/<\/blockquote>/gmi, '\n__bq__end__\n')
+ .replace(/]*>([\s\S\r\n]*?)<\/a>/gmi, convertLinks)
+ .replace(/<\/div>/gi, '\n')
+ .replace(/ /gi, ' ')
+ .replace(/"/gi, '"')
+ .replace(/<[^>]*>/gm, '')
+ ;
+
+ sText = Utils.$div.html(sText).text();
+
+ sText = sText
+ .replace(/\n[ \t]+/gm, '\n')
+ .replace(/[\n]{3,}/gm, '\n\n')
+ .replace(/>/gi, '>')
+ .replace(/</gi, '<')
+ .replace(/&/gi, '&')
+ ;
+
+ iPos = 0;
+ iLimit = 100;
+
+ while (0 < iLimit)
+ {
+ iLimit--;
+ iP1 = sText.indexOf('__bq__start__', iPos);
+ if (-1 < iP1)
+ {
+ iP2 = sText.indexOf('__bq__start__', iP1 + 5);
+ iP3 = sText.indexOf('__bq__end__', iP1 + 5);
+
+ if ((-1 === iP2 || iP3 < iP2) && iP1 < iP3)
+ {
+ sText = sText.substring(0, iP1) +
+ convertBlockquote(sText.substring(iP1 + 13, iP3)) +
+ sText.substring(iP3 + 11);
+
+ iPos = 0;
+ }
+ else if (-1 < iP2 && iP2 < iP3)
+ {
+ iPos = iP2 - 1;
+ }
+ else
+ {
+ iPos = 0;
+ }
}
else
{
- iPos = 0;
+ break;
}
}
- else
- {
- break;
- }
- }
- sText = sText
- .replace(/__bq__start__/gm, '')
- .replace(/__bq__end__/gm, '')
- ;
+ sText = sText
+ .replace(/__bq__start__/gm, '')
+ .replace(/__bq__end__/gm, '')
+ ;
- return sText;
-};
+ return sText;
+ };
-/**
- * @param {string} sPlain
- * @param {boolean} bLinkify = false
- * @return {string}
- */
-Utils.plainToHtml = function (sPlain, bLinkify)
-{
- sPlain = sPlain.toString().replace(/\r/g, '');
-
- var
- bIn = false,
- bDo = true,
- bStart = true,
- aNextText = [],
- sLine = '',
- iIndex = 0,
- aText = sPlain.split("\n")
- ;
-
- do
+ /**
+ * @param {string} sPlain
+ * @param {boolean} bLinkify = false
+ * @return {string}
+ */
+ Utils.plainToHtml = function (sPlain, bLinkify)
{
- bDo = false;
- aNextText = [];
- for (iIndex = 0; iIndex < aText.length; iIndex++)
+ sPlain = sPlain.toString().replace(/\r/g, '');
+
+ var
+ bIn = false,
+ bDo = true,
+ bStart = true,
+ aNextText = [],
+ sLine = '',
+ iIndex = 0,
+ aText = sPlain.split("\n")
+ ;
+
+ do
{
- sLine = aText[iIndex];
- bStart = '>' === sLine.substr(0, 1);
- if (bStart && !bIn)
+ bDo = false;
+ aNextText = [];
+ for (iIndex = 0; iIndex < aText.length; iIndex++)
{
- bDo = true;
- bIn = true;
- aNextText.push('~~~blockquote~~~');
- aNextText.push(sLine.substr(1));
+ sLine = aText[iIndex];
+ bStart = '>' === sLine.substr(0, 1);
+ if (bStart && !bIn)
+ {
+ bDo = true;
+ bIn = true;
+ aNextText.push('~~~blockquote~~~');
+ aNextText.push(sLine.substr(1));
+ }
+ else if (!bStart && bIn)
+ {
+ bIn = false;
+ aNextText.push('~~~/blockquote~~~');
+ aNextText.push(sLine);
+ }
+ else if (bStart && bIn)
+ {
+ aNextText.push(sLine.substr(1));
+ }
+ else
+ {
+ aNextText.push(sLine);
+ }
}
- else if (!bStart && bIn)
+
+ if (bIn)
{
bIn = false;
aNextText.push('~~~/blockquote~~~');
- aNextText.push(sLine);
}
- else if (bStart && bIn)
+
+ aText = aNextText;
+ }
+ while (bDo);
+
+ sPlain = aText.join("\n");
+
+ sPlain = sPlain
+ .replace(/&/g, '&')
+ .replace(/>/g, '>').replace(/')
+ .replace(/[\s]*~~~\/blockquote~~~/g, '
')
+ .replace(/[\-_~]{10,}/g, '
')
+ .replace(/\n/g, '
');
+
+ return bLinkify ? Utils.linkify(sPlain) : sPlain;
+ };
+
+ window.rainloop_Utils_htmlToPlain = Utils.htmlToPlain;
+ window.rainloop_Utils_plainToHtml = Utils.plainToHtml;
+
+ /**
+ * @param {string} sHtml
+ * @return {string}
+ */
+ Utils.linkify = function (sHtml)
+ {
+ if ($.fn && $.fn.linkify)
+ {
+ sHtml = Utils.$div.html(sHtml.replace(/&/ig, 'amp_amp_12345_amp_amp'))
+ .linkify()
+ .find('.linkified').removeClass('linkified').end()
+ .html()
+ .replace(/amp_amp_12345_amp_amp/g, '&')
+ ;
+ }
+
+ return sHtml;
+ };
+
+ Utils.resizeAndCrop = function (sUrl, iValue, fCallback)
+ {
+ var oTempImg = new window.Image();
+ oTempImg.onload = function() {
+
+ var
+ aDiff = [0, 0],
+ oCanvas = document.createElement('canvas'),
+ oCtx = oCanvas.getContext('2d')
+ ;
+
+ oCanvas.width = iValue;
+ oCanvas.height = iValue;
+
+ if (this.width > this.height)
{
- aNextText.push(sLine.substr(1));
+ aDiff = [this.width - this.height, 0];
}
else
{
- aNextText.push(sLine);
- }
- }
-
- if (bIn)
- {
- bIn = false;
- aNextText.push('~~~/blockquote~~~');
- }
-
- aText = aNextText;
- }
- while (bDo);
-
- sPlain = aText.join("\n");
-
- sPlain = sPlain
- .replace(/&/g, '&')
- .replace(/>/g, '>').replace(/')
- .replace(/[\s]*~~~\/blockquote~~~/g, '')
- .replace(/[\-_~]{10,}/g, '
')
- .replace(/\n/g, '
');
-
- return bLinkify ? Utils.linkify(sPlain) : sPlain;
-};
-
-window.rainloop_Utils_htmlToPlain = Utils.htmlToPlain;
-window.rainloop_Utils_plainToHtml = Utils.plainToHtml;
-
-/**
- * @param {string} sHtml
- * @return {string}
- */
-Utils.linkify = function (sHtml)
-{
- if ($.fn && $.fn.linkify)
- {
- sHtml = Utils.$div.html(sHtml.replace(/&/ig, 'amp_amp_12345_amp_amp'))
- .linkify()
- .find('.linkified').removeClass('linkified').end()
- .html()
- .replace(/amp_amp_12345_amp_amp/g, '&')
- ;
- }
-
- return sHtml;
-};
-
-Utils.resizeAndCrop = function (sUrl, iValue, fCallback)
-{
- var oTempImg = new window.Image();
- oTempImg.onload = function() {
-
- var
- aDiff = [0, 0],
- oCanvas = document.createElement('canvas'),
- oCtx = oCanvas.getContext('2d')
- ;
-
- oCanvas.width = iValue;
- oCanvas.height = iValue;
-
- if (this.width > this.height)
- {
- aDiff = [this.width - this.height, 0];
- }
- else
- {
- aDiff = [0, this.height - this.width];
- }
-
- oCtx.fillStyle = '#fff';
- oCtx.fillRect(0, 0, iValue, iValue);
- oCtx.drawImage(this, aDiff[0] / 2, aDiff[1] / 2, this.width - aDiff[0], this.height - aDiff[1], 0, 0, iValue, iValue);
-
- fCallback(oCanvas.toDataURL('image/jpeg'));
- };
-
- oTempImg.src = sUrl;
-};
-
-Utils.computedPagenatorHelper = function (koCurrentPage, koPageCount)
-{
- return function() {
- var
- iPrev = 0,
- iNext = 0,
- iLimit = 2,
- aResult = [],
- iCurrentPage = koCurrentPage(),
- iPageCount = koPageCount(),
-
- /**
- * @param {number} iIndex
- * @param {boolean=} bPush
- * @param {string=} sCustomName
- */
- fAdd = function (iIndex, bPush, sCustomName) {
-
- var oData = {
- 'current': iIndex === iCurrentPage,
- 'name': Utils.isUnd(sCustomName) ? iIndex.toString() : sCustomName.toString(),
- 'custom': Utils.isUnd(sCustomName) ? false : true,
- 'title': Utils.isUnd(sCustomName) ? '' : iIndex.toString(),
- 'value': iIndex.toString()
- };
-
- if (Utils.isUnd(bPush) ? true : !!bPush)
- {
- aResult.push(oData);
- }
- else
- {
- aResult.unshift(oData);
- }
- }
- ;
-
- if (1 < iPageCount || (0 < iPageCount && iPageCount < iCurrentPage))
-// if (0 < iPageCount && 0 < iCurrentPage)
- {
- if (iPageCount < iCurrentPage)
- {
- fAdd(iPageCount);
- iPrev = iPageCount;
- iNext = iPageCount;
- }
- else
- {
- if (3 >= iCurrentPage || iPageCount - 2 <= iCurrentPage)
- {
- iLimit += 2;
- }
-
- fAdd(iCurrentPage);
- iPrev = iCurrentPage;
- iNext = iCurrentPage;
+ aDiff = [0, this.height - this.width];
}
- while (0 < iLimit) {
+ oCtx.fillStyle = '#fff';
+ oCtx.fillRect(0, 0, iValue, iValue);
+ oCtx.drawImage(this, aDiff[0] / 2, aDiff[1] / 2, this.width - aDiff[0], this.height - aDiff[1], 0, 0, iValue, iValue);
- iPrev -= 1;
- iNext += 1;
-
- if (0 < iPrev)
- {
- fAdd(iPrev, false);
- iLimit--;
- }
-
- if (iPageCount >= iNext)
- {
- fAdd(iNext, true);
- iLimit--;
- }
- else if (0 >= iPrev)
- {
- break;
- }
- }
-
- if (3 === iPrev)
- {
- fAdd(2, false);
- }
- else if (3 < iPrev)
- {
- fAdd(Math.round((iPrev - 1) / 2), false, '...');
- }
-
- if (iPageCount - 2 === iNext)
- {
- fAdd(iPageCount - 1, true);
- }
- else if (iPageCount - 2 > iNext)
- {
- fAdd(Math.round((iPageCount + iNext) / 2), true, '...');
- }
-
- // first and last
- if (1 < iPrev)
- {
- fAdd(1, false);
- }
-
- if (iPageCount > iNext)
- {
- fAdd(iPageCount, true);
- }
- }
-
- return aResult;
- };
-};
-
-Utils.selectElement = function (element)
-{
- /* jshint onevar: false */
- if (window.getSelection)
- {
- var sel = window.getSelection();
- sel.removeAllRanges();
- var range = document.createRange();
- range.selectNodeContents(element);
- sel.addRange(range);
- }
- else if (document.selection)
- {
- var textRange = document.body.createTextRange();
- textRange.moveToElementText(element);
- textRange.select();
- }
- /* jshint onevar: true */
-};
-
-Utils.disableKeyFilter = function ()
-{
- if (window.key)
- {
- key.filter = function () {
- return RL.data().useKeyboardShortcuts();
+ fCallback(oCanvas.toDataURL('image/jpeg'));
};
- }
-};
-Utils.restoreKeyFilter = function ()
-{
- if (window.key)
- {
- key.filter = function (event) {
-
- if (RL.data().useKeyboardShortcuts())
- {
- var
- element = event.target || event.srcElement,
- tagName = element ? element.tagName : ''
- ;
-
- tagName = tagName.toUpperCase();
- return !(tagName === 'INPUT' || tagName === 'SELECT' || tagName === 'TEXTAREA' ||
- (element && tagName === 'DIV' && 'editorHtmlArea' === element.className && element.contentEditable)
- );
- }
-
- return false;
- };
- }
-};
-
-Utils.detectDropdownVisibility = _.debounce(function () {
- Globals.dropdownVisibility(!!_.find(BootstrapDropdowns, function (oItem) {
- return oItem.hasClass('open');
- }));
-}, 50);
-
-Utils.triggerAutocompleteInputChange = function (bDelay) {
-
- var fFunc = function () {
- $('.checkAutocomplete').trigger('change');
+ oTempImg.src = sUrl;
};
- if (bDelay)
+ Utils.computedPagenatorHelper = function (koCurrentPage, koPageCount)
{
- _.delay(fFunc, 100);
- }
- else
- {
- fFunc();
- }
-};
-
-
-
-/*jslint bitwise: true*/
-// Base64 encode / decode
-// http://www.webtoolkit.info/
-
-Base64 = {
-
- // private property
- _keyStr : 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
-
- // public method for urlsafe encoding
- urlsafe_encode : function (input) {
- return Base64.encode(input).replace(/[+]/g, '-').replace(/[\/]/g, '_').replace(/[=]/g, '.');
- },
-
- // public method for encoding
- encode : function (input) {
- var
- output = '',
- chr1, chr2, chr3, enc1, enc2, enc3, enc4,
- i = 0
- ;
-
- input = Base64._utf8_encode(input);
-
- while (i < input.length)
- {
- chr1 = input.charCodeAt(i++);
- chr2 = input.charCodeAt(i++);
- chr3 = input.charCodeAt(i++);
-
- enc1 = chr1 >> 2;
- enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
- enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
- enc4 = chr3 & 63;
-
- if (isNaN(chr2))
- {
- enc3 = enc4 = 64;
- }
- else if (isNaN(chr3))
- {
- enc4 = 64;
- }
-
- output = output +
- this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
- this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
- }
-
- return output;
- },
-
- // public method for decoding
- decode : function (input) {
- var
- output = '',
- chr1, chr2, chr3, enc1, enc2, enc3, enc4,
- i = 0
- ;
-
- input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
-
- while (i < input.length)
- {
- enc1 = this._keyStr.indexOf(input.charAt(i++));
- enc2 = this._keyStr.indexOf(input.charAt(i++));
- enc3 = this._keyStr.indexOf(input.charAt(i++));
- enc4 = this._keyStr.indexOf(input.charAt(i++));
-
- chr1 = (enc1 << 2) | (enc2 >> 4);
- chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
- chr3 = ((enc3 & 3) << 6) | enc4;
-
- output = output + String.fromCharCode(chr1);
-
- if (enc3 !== 64)
- {
- output = output + String.fromCharCode(chr2);
- }
-
- if (enc4 !== 64)
- {
- output = output + String.fromCharCode(chr3);
- }
- }
-
- return Base64._utf8_decode(output);
- },
-
- // private method for UTF-8 encoding
- _utf8_encode : function (string) {
-
- string = string.replace(/\r\n/g, "\n");
-
- var
- utftext = '',
- n = 0,
- l = string.length,
- c = 0
- ;
-
- for (; n < l; n++) {
-
- c = string.charCodeAt(n);
-
- if (c < 128)
- {
- utftext += String.fromCharCode(c);
- }
- else if ((c > 127) && (c < 2048))
- {
- utftext += String.fromCharCode((c >> 6) | 192);
- utftext += String.fromCharCode((c & 63) | 128);
- }
- else
- {
- utftext += String.fromCharCode((c >> 12) | 224);
- utftext += String.fromCharCode(((c >> 6) & 63) | 128);
- utftext += String.fromCharCode((c & 63) | 128);
- }
- }
-
- return utftext;
- },
-
- // private method for UTF-8 decoding
- _utf8_decode : function (utftext) {
- var
- string = '',
- i = 0,
- c = 0,
- c2 = 0,
- c3 = 0
- ;
-
- while ( i < utftext.length )
- {
- c = utftext.charCodeAt(i);
-
- if (c < 128)
- {
- string += String.fromCharCode(c);
- i++;
- }
- else if((c > 191) && (c < 224))
- {
- c2 = utftext.charCodeAt(i+1);
- string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
- i += 2;
- }
- else
- {
- c2 = utftext.charCodeAt(i+1);
- c3 = utftext.charCodeAt(i+2);
- string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
- i += 3;
- }
- }
-
- return string;
- }
-};
-
-/*jslint bitwise: false*/
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-ko.bindingHandlers.tooltip = {
- 'init': function (oElement, fValueAccessor) {
- if (!Globals.bMobileDevice)
- {
+ return function() {
var
- $oEl = $(oElement),
- sClass = $oEl.data('tooltip-class') || '',
- sPlacement = $oEl.data('tooltip-placement') || 'top'
- ;
+ iPrev = 0,
+ iNext = 0,
+ iLimit = 2,
+ aResult = [],
+ iCurrentPage = koCurrentPage(),
+ iPageCount = koPageCount(),
- $oEl.tooltip({
- 'delay': {
- 'show': 500,
- 'hide': 100
- },
- 'html': true,
- 'container': 'body',
- 'placement': sPlacement,
- 'trigger': 'hover',
- 'title': function () {
- return $oEl.is('.disabled') || Globals.dropdownVisibility() ? '' : '' +
- Utils.i18n(ko.utils.unwrapObservable(fValueAccessor())) + '';
- }
- }).click(function () {
- $oEl.tooltip('hide');
- });
+ /**
+ * @param {number} iIndex
+ * @param {boolean=} bPush
+ * @param {string=} sCustomName
+ */
+ fAdd = function (iIndex, bPush, sCustomName) {
- Globals.tooltipTrigger.subscribe(function () {
- $oEl.tooltip('hide');
- });
- }
- }
-};
-
-ko.bindingHandlers.tooltip2 = {
- 'init': function (oElement, fValueAccessor) {
- var
- $oEl = $(oElement),
- sClass = $oEl.data('tooltip-class') || '',
- sPlacement = $oEl.data('tooltip-placement') || 'top'
- ;
-
- $oEl.tooltip({
- 'delay': {
- 'show': 500,
- 'hide': 100
- },
- 'html': true,
- 'container': 'body',
- 'placement': sPlacement,
- 'title': function () {
- return $oEl.is('.disabled') || Globals.dropdownVisibility() ? '' :
- '' + fValueAccessor()() + '';
- }
- }).click(function () {
- $oEl.tooltip('hide');
- });
-
- Globals.tooltipTrigger.subscribe(function () {
- $oEl.tooltip('hide');
- });
- }
-};
-
-ko.bindingHandlers.tooltip3 = {
- 'init': function (oElement) {
-
- var $oEl = $(oElement);
-
- $oEl.tooltip({
- 'container': 'body',
- 'trigger': 'hover manual',
- 'title': function () {
- return $oEl.data('tooltip3-data') || '';
- }
- });
-
- $document.click(function () {
- $oEl.tooltip('hide');
- });
-
- Globals.tooltipTrigger.subscribe(function () {
- $oEl.tooltip('hide');
- });
- },
- 'update': function (oElement, fValueAccessor) {
- var sValue = ko.utils.unwrapObservable(fValueAccessor());
- if ('' === sValue)
- {
- $(oElement).data('tooltip3-data', '').tooltip('hide');
- }
- else
- {
- $(oElement).data('tooltip3-data', sValue).tooltip('show');
- }
- }
-};
-
-ko.bindingHandlers.registrateBootstrapDropdown = {
- 'init': function (oElement) {
- BootstrapDropdowns.push($(oElement));
- }
-};
-
-ko.bindingHandlers.openDropdownTrigger = {
- 'update': function (oElement, fValueAccessor) {
- if (ko.utils.unwrapObservable(fValueAccessor()))
- {
- var $el = $(oElement);
- if (!$el.hasClass('open'))
- {
- $el.find('.dropdown-toggle').dropdown('toggle');
- Utils.detectDropdownVisibility();
- }
-
- fValueAccessor()(false);
- }
- }
-};
-
-ko.bindingHandlers.dropdownCloser = {
- 'init': function (oElement) {
- $(oElement).closest('.dropdown').on('click', '.e-item', function () {
- $(oElement).dropdown('toggle');
- });
- }
-};
-
-ko.bindingHandlers.popover = {
- 'init': function (oElement, fValueAccessor) {
- $(oElement).popover(ko.utils.unwrapObservable(fValueAccessor()));
- }
-};
-
-ko.bindingHandlers.csstext = {
- 'init': function (oElement, fValueAccessor) {
- if (oElement && oElement.styleSheet && !Utils.isUnd(oElement.styleSheet.cssText))
- {
- oElement.styleSheet.cssText = ko.utils.unwrapObservable(fValueAccessor());
- }
- else
- {
- $(oElement).text(ko.utils.unwrapObservable(fValueAccessor()));
- }
- },
- 'update': function (oElement, fValueAccessor) {
- if (oElement && oElement.styleSheet && !Utils.isUnd(oElement.styleSheet.cssText))
- {
- oElement.styleSheet.cssText = ko.utils.unwrapObservable(fValueAccessor());
- }
- else
- {
- $(oElement).text(ko.utils.unwrapObservable(fValueAccessor()));
- }
- }
-};
-
-ko.bindingHandlers.resizecrop = {
- 'init': function (oElement) {
- $(oElement).addClass('resizecrop').resizecrop({
- 'width': '100',
- 'height': '100',
- 'wrapperCSS': {
- 'border-radius': '10px'
- }
- });
- },
- 'update': function (oElement, fValueAccessor) {
- fValueAccessor()();
- $(oElement).resizecrop({
- 'width': '100',
- 'height': '100'
- });
- }
-};
-
-ko.bindingHandlers.onEnter = {
- 'init': function (oElement, fValueAccessor, fAllBindingsAccessor, oViewModel) {
- $(oElement).on('keypress', function (oEvent) {
- if (oEvent && 13 === window.parseInt(oEvent.keyCode, 10))
- {
- $(oElement).trigger('change');
- fValueAccessor().call(oViewModel);
- }
- });
- }
-};
-
-ko.bindingHandlers.onEsc = {
- 'init': function (oElement, fValueAccessor, fAllBindingsAccessor, oViewModel) {
- $(oElement).on('keypress', function (oEvent) {
- if (oEvent && 27 === window.parseInt(oEvent.keyCode, 10))
- {
- $(oElement).trigger('change');
- fValueAccessor().call(oViewModel);
- }
- });
- }
-};
-
-ko.bindingHandlers.clickOnTrue = {
- 'update': function (oElement, fValueAccessor) {
- if (ko.utils.unwrapObservable(fValueAccessor()))
- {
- $(oElement).click();
- }
- }
-};
-
-ko.bindingHandlers.modal = {
- 'init': function (oElement, fValueAccessor) {
-
- $(oElement).toggleClass('fade', !Globals.bMobileDevice).modal({
- 'keyboard': false,
- 'show': ko.utils.unwrapObservable(fValueAccessor())
- })
- .on('shown', function () {
- Utils.windowResize();
- })
- .find('.close').click(function () {
- fValueAccessor()(false);
- });
- },
- 'update': function (oElement, fValueAccessor) {
- $(oElement).modal(ko.utils.unwrapObservable(fValueAccessor()) ? 'show' : 'hide');
- }
-};
-
-ko.bindingHandlers.i18nInit = {
- 'init': function (oElement) {
- Utils.i18nToNode(oElement);
- }
-};
-
-ko.bindingHandlers.i18nUpdate = {
- 'update': function (oElement, fValueAccessor) {
- ko.utils.unwrapObservable(fValueAccessor());
- Utils.i18nToNode(oElement);
- }
-};
-
-ko.bindingHandlers.link = {
- 'update': function (oElement, fValueAccessor) {
- $(oElement).attr('href', ko.utils.unwrapObservable(fValueAccessor()));
- }
-};
-
-ko.bindingHandlers.title = {
- 'update': function (oElement, fValueAccessor) {
- $(oElement).attr('title', ko.utils.unwrapObservable(fValueAccessor()));
- }
-};
-
-ko.bindingHandlers.textF = {
- 'init': function (oElement, fValueAccessor) {
- $(oElement).text(ko.utils.unwrapObservable(fValueAccessor()));
- }
-};
-
-ko.bindingHandlers.initDom = {
- 'init': function (oElement, fValueAccessor) {
- fValueAccessor()(oElement);
- }
-};
-
-ko.bindingHandlers.initResizeTrigger = {
- 'init': function (oElement, fValueAccessor) {
- var aValues = ko.utils.unwrapObservable(fValueAccessor());
- $(oElement).css({
- 'height': aValues[1],
- 'min-height': aValues[1]
- });
- },
- 'update': function (oElement, fValueAccessor) {
- var
- aValues = ko.utils.unwrapObservable(fValueAccessor()),
- iValue = Utils.pInt(aValues[1]),
- iSize = 0,
- iOffset = $(oElement).offset().top
- ;
-
- if (0 < iOffset)
- {
- iOffset += Utils.pInt(aValues[2]);
- iSize = $window.height() - iOffset;
-
- if (iValue < iSize)
- {
- iValue = iSize;
- }
-
- $(oElement).css({
- 'height': iValue,
- 'min-height': iValue
- });
- }
- }
-};
-
-ko.bindingHandlers.appendDom = {
- 'update': function (oElement, fValueAccessor) {
- $(oElement).hide().empty().append(ko.utils.unwrapObservable(fValueAccessor())).show();
- }
-};
-
-ko.bindingHandlers.draggable = {
- 'init': function (oElement, fValueAccessor, fAllBindingsAccessor) {
-
- if (!Globals.bMobileDevice)
- {
- var
- iTriggerZone = 100,
- iScrollSpeed = 3,
- fAllValueFunc = fAllBindingsAccessor(),
- sDroppableSelector = fAllValueFunc && fAllValueFunc['droppableSelector'] ? fAllValueFunc['droppableSelector'] : '',
- oConf = {
- 'distance': 20,
- 'handle': '.dragHandle',
- 'cursorAt': {'top': 22, 'left': 3},
- 'refreshPositions': true,
- 'scroll': true
- }
- ;
-
- if (sDroppableSelector)
- {
- oConf['drag'] = function (oEvent) {
-
- $(sDroppableSelector).each(function () {
- var
- moveUp = null,
- moveDown = null,
- $this = $(this),
- oOffset = $this.offset(),
- bottomPos = oOffset.top + $this.height()
- ;
-
- window.clearInterval($this.data('timerScroll'));
- $this.data('timerScroll', false);
-
- if (oEvent.pageX >= oOffset.left && oEvent.pageX <= oOffset.left + $this.width())
- {
- if (oEvent.pageY >= bottomPos - iTriggerZone && oEvent.pageY <= bottomPos)
- {
- moveUp = function() {
- $this.scrollTop($this.scrollTop() + iScrollSpeed);
- Utils.windowResize();
- };
-
- $this.data('timerScroll', window.setInterval(moveUp, 10));
- moveUp();
- }
-
- if (oEvent.pageY >= oOffset.top && oEvent.pageY <= oOffset.top + iTriggerZone)
- {
- moveDown = function() {
- $this.scrollTop($this.scrollTop() - iScrollSpeed);
- Utils.windowResize();
- };
-
- $this.data('timerScroll', window.setInterval(moveDown, 10));
- moveDown();
- }
- }
- });
- };
-
- oConf['stop'] = function() {
- $(sDroppableSelector).each(function () {
- window.clearInterval($(this).data('timerScroll'));
- $(this).data('timerScroll', false);
- });
- };
- }
-
- oConf['helper'] = function (oEvent) {
- return fValueAccessor()(oEvent && oEvent.target ? ko.dataFor(oEvent.target) : null);
- };
-
- $(oElement).draggable(oConf).on('mousedown', function () {
- Utils.removeInFocus();
- });
- }
- }
-};
-
-ko.bindingHandlers.droppable = {
- 'init': function (oElement, fValueAccessor, fAllBindingsAccessor) {
-
- if (!Globals.bMobileDevice)
- {
- var
- fValueFunc = fValueAccessor(),
- fAllValueFunc = fAllBindingsAccessor(),
- fOverCallback = fAllValueFunc && fAllValueFunc['droppableOver'] ? fAllValueFunc['droppableOver'] : null,
- fOutCallback = fAllValueFunc && fAllValueFunc['droppableOut'] ? fAllValueFunc['droppableOut'] : null,
- oConf = {
- 'tolerance': 'pointer',
- 'hoverClass': 'droppableHover'
- }
- ;
-
- if (fValueFunc)
- {
- oConf['drop'] = function (oEvent, oUi) {
- fValueFunc(oEvent, oUi);
- };
-
- if (fOverCallback)
- {
- oConf['over'] = function (oEvent, oUi) {
- fOverCallback(oEvent, oUi);
+ var oData = {
+ 'current': iIndex === iCurrentPage,
+ 'name': Utils.isUnd(sCustomName) ? iIndex.toString() : sCustomName.toString(),
+ 'custom': Utils.isUnd(sCustomName) ? false : true,
+ 'title': Utils.isUnd(sCustomName) ? '' : iIndex.toString(),
+ 'value': iIndex.toString()
};
- }
- if (fOutCallback)
- {
- oConf['out'] = function (oEvent, oUi) {
- fOutCallback(oEvent, oUi);
- };
- }
-
- $(oElement).droppable(oConf);
- }
- }
- }
-};
-
-ko.bindingHandlers.nano = {
- 'init': function (oElement) {
- if (!Globals.bDisableNanoScroll)
- {
- $(oElement)
- .addClass('nano')
- .nanoScroller({
- 'iOSNativeScrolling': false,
- 'preventPageScrolling': true
- })
- ;
- }
- }
-};
-
-ko.bindingHandlers.saveTrigger = {
- 'init': function (oElement) {
-
- var $oEl = $(oElement);
-
- $oEl.data('save-trigger-type', $oEl.is('input[type=text],input[type=email],input[type=password],select,textarea') ? 'input' : 'custom');
-
- if ('custom' === $oEl.data('save-trigger-type'))
- {
- $oEl.append(
- ' '
- ).addClass('settings-saved-trigger');
- }
- else
- {
- $oEl.addClass('settings-saved-trigger-input');
- }
- },
- 'update': function (oElement, fValueAccessor) {
- var
- mValue = ko.utils.unwrapObservable(fValueAccessor()),
- $oEl = $(oElement)
- ;
-
- if ('custom' === $oEl.data('save-trigger-type'))
- {
- switch (mValue.toString())
- {
- case '1':
- $oEl
- .find('.animated,.error').hide().removeClass('visible')
- .end()
- .find('.success').show().addClass('visible')
- ;
- break;
- case '0':
- $oEl
- .find('.animated,.success').hide().removeClass('visible')
- .end()
- .find('.error').show().addClass('visible')
- ;
- break;
- case '-2':
- $oEl
- .find('.error,.success').hide().removeClass('visible')
- .end()
- .find('.animated').show().addClass('visible')
- ;
- break;
- default:
- $oEl
- .find('.animated').hide()
- .end()
- .find('.error,.success').removeClass('visible')
- ;
- break;
- }
- }
- else
- {
- switch (mValue.toString())
- {
- case '1':
- $oEl.addClass('success').removeClass('error');
- break;
- case '0':
- $oEl.addClass('error').removeClass('success');
- break;
- case '-2':
-// $oEl;
- break;
- default:
- $oEl.removeClass('error success');
- break;
- }
- }
- }
-};
-
-ko.bindingHandlers.emailsTags = {
- 'init': function(oElement, fValueAccessor) {
- var
- $oEl = $(oElement),
- fValue = fValueAccessor(),
- fFocusCallback = function (bValue) {
- if (fValue && fValue.focusTrigger)
- {
- fValue.focusTrigger(bValue);
- }
- }
- ;
-
- $oEl.inputosaurus({
- 'parseOnBlur': true,
- 'allowDragAndDrop': true,
- 'focusCallback': fFocusCallback,
- 'inputDelimiters': [',', ';'],
- 'autoCompleteSource': function (oData, fResponse) {
- RL.getAutocomplete(oData.term, function (aData) {
- fResponse(_.map(aData, function (oEmailItem) {
- return oEmailItem.toLine(false);
- }));
- });
- },
- 'parseHook': function (aInput) {
- return _.map(aInput, function (sInputValue) {
-
- var
- sValue = Utils.trim(sInputValue),
- oEmail = null
- ;
-
- if ('' !== sValue)
+ if (Utils.isUnd(bPush) ? true : !!bPush)
{
- oEmail = new EmailModel();
- oEmail.mailsoParse(sValue);
- oEmail.clearDuplicateName();
- return [oEmail.toLine(false), oEmail];
- }
-
- return [sValue, null];
-
- });
- },
- 'change': _.bind(function (oEvent) {
- $oEl.data('EmailsTagsValue', oEvent.target.value);
- fValue(oEvent.target.value);
- }, this)
- });
- },
- 'update': function (oElement, fValueAccessor, fAllBindingsAccessor) {
-
- var
- $oEl = $(oElement),
- fAllValueFunc = fAllBindingsAccessor(),
- fEmailsTagsFilter = fAllValueFunc['emailsTagsFilter'] || null,
- sValue = ko.utils.unwrapObservable(fValueAccessor())
- ;
-
- if ($oEl.data('EmailsTagsValue') !== sValue)
- {
- $oEl.val(sValue);
- $oEl.data('EmailsTagsValue', sValue);
- $oEl.inputosaurus('refresh');
- }
-
- if (fEmailsTagsFilter && ko.utils.unwrapObservable(fEmailsTagsFilter))
- {
- $oEl.inputosaurus('focus');
- }
- }
-};
-
-ko.bindingHandlers.contactTags = {
- 'init': function(oElement, fValueAccessor) {
- var
- $oEl = $(oElement),
- fValue = fValueAccessor(),
- fFocusCallback = function (bValue) {
- if (fValue && fValue.focusTrigger)
- {
- fValue.focusTrigger(bValue);
- }
- }
- ;
-
- $oEl.inputosaurus({
- 'parseOnBlur': true,
- 'allowDragAndDrop': false,
- 'focusCallback': fFocusCallback,
- 'inputDelimiters': [',', ';'],
- 'outputDelimiter': ',',
- 'autoCompleteSource': function (oData, fResponse) {
- RL.getContactTagsAutocomplete(oData.term, function (aData) {
- fResponse(_.map(aData, function (oTagItem) {
- return oTagItem.toLine(false);
- }));
- });
- },
- 'parseHook': function (aInput) {
- return _.map(aInput, function (sInputValue) {
-
- var
- sValue = Utils.trim(sInputValue),
- oTag = null
- ;
-
- if ('' !== sValue)
- {
- oTag = new ContactTagModel();
- oTag.name(sValue);
- return [oTag.toLine(false), oTag];
- }
-
- return [sValue, null];
-
- });
- },
- 'change': _.bind(function (oEvent) {
- $oEl.data('ContactTagsValue', oEvent.target.value);
- fValue(oEvent.target.value);
- }, this)
- });
- },
- 'update': function (oElement, fValueAccessor, fAllBindingsAccessor) {
-
- var
- $oEl = $(oElement),
- fAllValueFunc = fAllBindingsAccessor(),
- fContactTagsFilter = fAllValueFunc['contactTagsFilter'] || null,
- sValue = ko.utils.unwrapObservable(fValueAccessor())
- ;
-
- if ($oEl.data('ContactTagsValue') !== sValue)
- {
- $oEl.val(sValue);
- $oEl.data('ContactTagsValue', sValue);
- $oEl.inputosaurus('refresh');
- }
-
- if (fContactTagsFilter && ko.utils.unwrapObservable(fContactTagsFilter))
- {
- $oEl.inputosaurus('focus');
- }
- }
-};
-
-ko.bindingHandlers.command = {
- 'init': function (oElement, fValueAccessor, fAllBindingsAccessor, oViewModel) {
- var
- jqElement = $(oElement),
- oCommand = fValueAccessor()
- ;
-
- if (!oCommand || !oCommand.enabled || !oCommand.canExecute)
- {
- throw new Error('You are not using command function');
- }
-
- jqElement.addClass('command');
- ko.bindingHandlers[jqElement.is('form') ? 'submit' : 'click'].init.apply(oViewModel, arguments);
- },
-
- 'update': function (oElement, fValueAccessor) {
-
- var
- bResult = true,
- jqElement = $(oElement),
- oCommand = fValueAccessor()
- ;
-
- bResult = oCommand.enabled();
- jqElement.toggleClass('command-not-enabled', !bResult);
-
- if (bResult)
- {
- bResult = oCommand.canExecute();
- jqElement.toggleClass('command-can-not-be-execute', !bResult);
- }
-
- jqElement.toggleClass('command-disabled disable disabled', !bResult).toggleClass('no-disabled', !!bResult);
-
- if (jqElement.is('input') || jqElement.is('button'))
- {
- jqElement.prop('disabled', !bResult);
- }
- }
-};
-
-ko.extenders.trimmer = function (oTarget)
-{
- var oResult = ko.computed({
- 'read': oTarget,
- 'write': function (sNewValue) {
- oTarget(Utils.trim(sNewValue.toString()));
- },
- 'owner': this
- });
-
- oResult(oTarget());
- return oResult;
-};
-
-ko.extenders.posInterer = function (oTarget, iDefault)
-{
- var oResult = ko.computed({
- 'read': oTarget,
- 'write': function (sNewValue) {
- var iNew = Utils.pInt(sNewValue.toString(), iDefault);
- if (0 >= iNew)
- {
- iNew = iDefault;
- }
-
- if (iNew === oTarget() && '' + iNew !== '' + sNewValue)
- {
- oTarget(iNew + 1);
- }
-
- oTarget(iNew);
- }
- });
-
- oResult(oTarget());
- return oResult;
-};
-
-ko.extenders.reversible = function (oTarget)
-{
- var mValue = oTarget();
-
- oTarget.commit = function ()
- {
- mValue = oTarget();
- };
-
- oTarget.reverse = function ()
- {
- oTarget(mValue);
- };
-
- oTarget.commitedValue = function ()
- {
- return mValue;
- };
-
- return oTarget;
-};
-
-ko.extenders.toggleSubscribe = function (oTarget, oOptions)
-{
- oTarget.subscribe(oOptions[1], oOptions[0], 'beforeChange');
- oTarget.subscribe(oOptions[2], oOptions[0]);
-
- return oTarget;
-};
-
-ko.extenders.falseTimeout = function (oTarget, iOption)
-{
- oTarget.iTimeout = 0;
- oTarget.subscribe(function (bValue) {
- if (bValue)
- {
- window.clearTimeout(oTarget.iTimeout);
- oTarget.iTimeout = window.setTimeout(function () {
- oTarget(false);
- oTarget.iTimeout = 0;
- }, Utils.pInt(iOption));
- }
- });
-
- return oTarget;
-};
-
-ko.observable.fn.validateNone = function ()
-{
- this.hasError = ko.observable(false);
- return this;
-};
-
-ko.observable.fn.validateEmail = function ()
-{
- this.hasError = ko.observable(false);
-
- this.subscribe(function (sValue) {
- sValue = Utils.trim(sValue);
- this.hasError('' !== sValue && !(/^[^@\s]+@[^@\s]+$/.test(sValue)));
- }, this);
-
- this.valueHasMutated();
- return this;
-};
-
-ko.observable.fn.validateSimpleEmail = function ()
-{
- this.hasError = ko.observable(false);
-
- this.subscribe(function (sValue) {
- sValue = Utils.trim(sValue);
- this.hasError('' !== sValue && !(/^.+@.+$/.test(sValue)));
- }, this);
-
- this.valueHasMutated();
- return this;
-};
-
-ko.observable.fn.validateFunc = function (fFunc)
-{
- this.hasFuncError = ko.observable(false);
-
- if (Utils.isFunc(fFunc))
- {
- this.subscribe(function (sValue) {
- this.hasFuncError(!fFunc(sValue));
- }, this);
-
- this.valueHasMutated();
- }
-
- return this;
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function LinkBuilder()
-{
- this.sBase = '#/';
- this.sServer = './?';
- this.sVersion = RL.settingsGet('Version');
- this.sSpecSuffix = RL.settingsGet('AuthAccountHash') || '0';
- this.sStaticPrefix = RL.settingsGet('StaticPrefix') || 'rainloop/v/' + this.sVersion + '/static/';
-}
-
-/**
- * @return {string}
- */
-LinkBuilder.prototype.root = function ()
-{
- return this.sBase;
-};
-
-/**
- * @param {string} sDownload
- * @return {string}
- */
-LinkBuilder.prototype.attachmentDownload = function (sDownload)
-{
- return this.sServer + '/Raw/' + this.sSpecSuffix + '/Download/' + sDownload;
-};
-
-/**
- * @param {string} sDownload
- * @return {string}
- */
-LinkBuilder.prototype.attachmentPreview = function (sDownload)
-{
- return this.sServer + '/Raw/' + this.sSpecSuffix + '/View/' + sDownload;
-};
-
-/**
- * @param {string} sDownload
- * @return {string}
- */
-LinkBuilder.prototype.attachmentPreviewAsPlain = function (sDownload)
-{
- return this.sServer + '/Raw/' + this.sSpecSuffix + '/ViewAsPlain/' + sDownload;
-};
-
-/**
- * @return {string}
- */
-LinkBuilder.prototype.upload = function ()
-{
- return this.sServer + '/Upload/' + this.sSpecSuffix + '/';
-};
-
-/**
- * @return {string}
- */
-LinkBuilder.prototype.uploadContacts = function ()
-{
- return this.sServer + '/UploadContacts/' + this.sSpecSuffix + '/';
-};
-
-/**
- * @return {string}
- */
-LinkBuilder.prototype.uploadBackground = function ()
-{
- return this.sServer + '/UploadBackground/' + this.sSpecSuffix + '/';
-};
-
-/**
- * @return {string}
- */
-LinkBuilder.prototype.append = function ()
-{
- return this.sServer + '/Append/' + this.sSpecSuffix + '/';
-};
-
-/**
- * @param {string} sEmail
- * @return {string}
- */
-LinkBuilder.prototype.change = function (sEmail)
-{
- return this.sServer + '/Change/' + this.sSpecSuffix + '/' + window.encodeURIComponent(sEmail) + '/';
-};
-
-/**
- * @param {string=} sAdd
- * @return {string}
- */
-LinkBuilder.prototype.ajax = function (sAdd)
-{
- return this.sServer + '/Ajax/' + this.sSpecSuffix + '/' + sAdd;
-};
-
-/**
- * @param {string} sRequestHash
- * @return {string}
- */
-LinkBuilder.prototype.messageViewLink = function (sRequestHash)
-{
- return this.sServer + '/Raw/' + this.sSpecSuffix + '/ViewAsPlain/' + sRequestHash;
-};
-
-/**
- * @param {string} sRequestHash
- * @return {string}
- */
-LinkBuilder.prototype.messageDownloadLink = function (sRequestHash)
-{
- return this.sServer + '/Raw/' + this.sSpecSuffix + '/Download/' + sRequestHash;
-};
-
-/**
- * @param {string} sEmail
- * @return {string}
- */
-LinkBuilder.prototype.avatarLink = function (sEmail)
-{
- return this.sServer + '/Raw/0/Avatar/' + window.encodeURIComponent(sEmail) + '/';
-// return '//secure.gravatar.com/avatar/' + Utils.md5(sEmail.toLowerCase()) + '.jpg?s=80&d=mm';
-};
-
-/**
- * @return {string}
- */
-LinkBuilder.prototype.inbox = function ()
-{
- return this.sBase + 'mailbox/Inbox';
-};
-
-/**
- * @return {string}
- */
-LinkBuilder.prototype.messagePreview = function ()
-{
- return this.sBase + 'mailbox/message-preview';
-};
-
-/**
- * @param {string=} sScreenName
- * @return {string}
- */
-LinkBuilder.prototype.settings = function (sScreenName)
-{
- var sResult = this.sBase + 'settings';
- if (!Utils.isUnd(sScreenName) && '' !== sScreenName)
- {
- sResult += '/' + sScreenName;
- }
-
- return sResult;
-};
-
-/**
- * @param {string} sScreenName
- * @return {string}
- */
-LinkBuilder.prototype.admin = function (sScreenName)
-{
- var sResult = this.sBase;
- switch (sScreenName) {
- case 'AdminDomains':
- sResult += 'domains';
- break;
- case 'AdminSecurity':
- sResult += 'security';
- break;
- case 'AdminLicensing':
- sResult += 'licensing';
- break;
- }
-
- return sResult;
-};
-
-/**
- * @param {string} sFolder
- * @param {number=} iPage = 1
- * @param {string=} sSearch = ''
- * @return {string}
- */
-LinkBuilder.prototype.mailBox = function (sFolder, iPage, sSearch)
-{
- iPage = Utils.isNormal(iPage) ? Utils.pInt(iPage) : 1;
- sSearch = Utils.pString(sSearch);
-
- var sResult = this.sBase + 'mailbox/';
- if ('' !== sFolder)
- {
- sResult += encodeURI(sFolder);
- }
- if (1 < iPage)
- {
- sResult = sResult.replace(/[\/]+$/, '');
- sResult += '/p' + iPage;
- }
- if ('' !== sSearch)
- {
- sResult = sResult.replace(/[\/]+$/, '');
- sResult += '/' + encodeURI(sSearch);
- }
-
- return sResult;
-};
-
-/**
- * @return {string}
- */
-LinkBuilder.prototype.phpInfo = function ()
-{
- return this.sServer + 'Info';
-};
-
-/**
- * @param {string} sLang
- * @return {string}
- */
-LinkBuilder.prototype.langLink = function (sLang)
-{
- return this.sServer + '/Lang/0/' + encodeURI(sLang) + '/' + this.sVersion + '/';
-};
-
-/**
- * @return {string}
- */
-LinkBuilder.prototype.exportContactsVcf = function ()
-{
- return this.sServer + '/Raw/' + this.sSpecSuffix + '/ContactsVcf/';
-};
-
-/**
- * @return {string}
- */
-LinkBuilder.prototype.exportContactsCsv = function ()
-{
- return this.sServer + '/Raw/' + this.sSpecSuffix + '/ContactsCsv/';
-};
-
-/**
- * @return {string}
- */
-LinkBuilder.prototype.emptyContactPic = function ()
-{
- return this.sStaticPrefix + 'css/images/empty-contact.png';
-};
-
-/**
- * @param {string} sFileName
- * @return {string}
- */
-LinkBuilder.prototype.sound = function (sFileName)
-{
- return this.sStaticPrefix + 'sounds/' + sFileName;
-};
-
-/**
- * @param {string} sTheme
- * @return {string}
- */
-LinkBuilder.prototype.themePreviewLink = function (sTheme)
-{
- var sPrefix = 'rainloop/v/' + this.sVersion + '/';
- if ('@custom' === sTheme.substr(-7))
- {
- sTheme = Utils.trim(sTheme.substring(0, sTheme.length - 7));
- sPrefix = '';
- }
-
- return sPrefix + 'themes/' + encodeURI(sTheme) + '/images/preview.png';
-};
-
-/**
- * @return {string}
- */
-LinkBuilder.prototype.notificationMailIcon = function ()
-{
- return this.sStaticPrefix + 'css/images/icom-message-notification.png';
-};
-
-/**
- * @return {string}
- */
-LinkBuilder.prototype.openPgpJs = function ()
-{
- return this.sStaticPrefix + 'js/openpgp.min.js';
-};
-
-/**
- * @return {string}
- */
-LinkBuilder.prototype.socialGoogle = function ()
-{
- return this.sServer + 'SocialGoogle' + ('' !== this.sSpecSuffix ? '/' + this.sSpecSuffix + '/' : '');
-};
-
-/**
- * @return {string}
- */
-LinkBuilder.prototype.socialTwitter = function ()
-{
- return this.sServer + 'SocialTwitter' + ('' !== this.sSpecSuffix ? '/' + this.sSpecSuffix + '/' : '');
-};
-
-/**
- * @return {string}
- */
-LinkBuilder.prototype.socialFacebook = function ()
-{
- return this.sServer + 'SocialFacebook' + ('' !== this.sSpecSuffix ? '/' + this.sSpecSuffix + '/' : '');
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @type {Object}
- */
-Plugins.oViewModelsHooks = {};
-
-/**
- * @type {Object}
- */
-Plugins.oSimpleHooks = {};
-
-/**
- * @param {string} sName
- * @param {Function} ViewModel
- */
-Plugins.regViewModelHook = function (sName, ViewModel)
-{
- if (ViewModel)
- {
- ViewModel.__hookName = sName;
- }
-};
-
-/**
- * @param {string} sName
- * @param {Function} fCallback
- */
-Plugins.addHook = function (sName, fCallback)
-{
- if (Utils.isFunc(fCallback))
- {
- if (!Utils.isArray(Plugins.oSimpleHooks[sName]))
- {
- Plugins.oSimpleHooks[sName] = [];
- }
-
- Plugins.oSimpleHooks[sName].push(fCallback);
- }
-};
-
-/**
- * @param {string} sName
- * @param {Array=} aArguments
- */
-Plugins.runHook = function (sName, aArguments)
-{
- if (Utils.isArray(Plugins.oSimpleHooks[sName]))
- {
- aArguments = aArguments || [];
-
- _.each(Plugins.oSimpleHooks[sName], function (fCallback) {
- fCallback.apply(null, aArguments);
- });
- }
-};
-
-/**
- * @param {string} sName
- * @return {?}
- */
-Plugins.mainSettingsGet = function (sName)
-{
- return RL ? RL.settingsGet(sName) : null;
-};
-
-/**
- * @param {Function} fCallback
- * @param {string} sAction
- * @param {Object=} oParameters
- * @param {?number=} iTimeout
- * @param {string=} sGetAdd = ''
- * @param {Array=} aAbortActions = []
- */
-Plugins.remoteRequest = function (fCallback, sAction, oParameters, iTimeout, sGetAdd, aAbortActions)
-{
- if (RL)
- {
- RL.remote().defaultRequest(fCallback, sAction, oParameters, iTimeout, sGetAdd, aAbortActions);
- }
-};
-
-/**
- * @param {string} sPluginSection
- * @param {string} sName
- * @return {?}
- */
-Plugins.settingsGet = function (sPluginSection, sName)
-{
- var oPlugin = Plugins.mainSettingsGet('Plugins');
- oPlugin = oPlugin && Utils.isUnd(oPlugin[sPluginSection]) ? null : oPlugin[sPluginSection];
- return oPlugin ? (Utils.isUnd(oPlugin[sName]) ? null : oPlugin[sName]) : null;
-};
-
-
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function CookieDriver()
-{
-
-}
-
-CookieDriver.supported = function ()
-{
- return true;
-};
-
-/**
- * @param {string} sKey
- * @param {*} mData
- * @returns {boolean}
- */
-CookieDriver.prototype.set = function (sKey, mData)
-{
- var
- mCokieValue = $.cookie(Consts.Values.ClientSideCookieIndexName),
- bResult = false,
- mResult = null
- ;
-
- try
- {
- mResult = null === mCokieValue ? null : JSON.parse(mCokieValue);
- if (!mResult)
- {
- mResult = {};
- }
-
- mResult[sKey] = mData;
- $.cookie(Consts.Values.ClientSideCookieIndexName, JSON.stringify(mResult), {
- 'expires': 30
- });
-
- bResult = true;
- }
- catch (oException) {}
-
- return bResult;
-};
-
-/**
- * @param {string} sKey
- * @returns {*}
- */
-CookieDriver.prototype.get = function (sKey)
-{
- var
- mCokieValue = $.cookie(Consts.Values.ClientSideCookieIndexName),
- mResult = null
- ;
-
- try
- {
- mResult = null === mCokieValue ? null : JSON.parse(mCokieValue);
- if (mResult && !Utils.isUnd(mResult[sKey]))
- {
- mResult = mResult[sKey];
- }
- else
- {
- mResult = null;
- }
- }
- catch (oException) {}
-
- return mResult;
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function LocalStorageDriver()
-{
-}
-
-LocalStorageDriver.supported = function ()
-{
- return !!window.localStorage;
-};
-
-/**
- * @param {string} sKey
- * @param {*} mData
- * @returns {boolean}
- */
-LocalStorageDriver.prototype.set = function (sKey, mData)
-{
- var
- mCookieValue = window.localStorage[Consts.Values.ClientSideCookieIndexName] || null,
- bResult = false,
- mResult = null
- ;
-
- try
- {
- mResult = null === mCookieValue ? null : JSON.parse(mCookieValue);
- if (!mResult)
- {
- mResult = {};
- }
-
- mResult[sKey] = mData;
- window.localStorage[Consts.Values.ClientSideCookieIndexName] = JSON.stringify(mResult);
-
- bResult = true;
- }
- catch (oException) {}
-
- return bResult;
-};
-
-/**
- * @param {string} sKey
- * @returns {*}
- */
-LocalStorageDriver.prototype.get = function (sKey)
-{
- var
- mCokieValue = window.localStorage[Consts.Values.ClientSideCookieIndexName] || null,
- mResult = null
- ;
-
- try
- {
- mResult = null === mCokieValue ? null : JSON.parse(mCokieValue);
- if (mResult && !Utils.isUnd(mResult[sKey]))
- {
- mResult = mResult[sKey];
- }
- else
- {
- mResult = null;
- }
- }
- catch (oException) {}
-
- return mResult;
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function LocalStorage()
-{
- var
- sStorages = [
- LocalStorageDriver,
- CookieDriver
- ],
- NextStorageDriver = _.find(sStorages, function (NextStorageDriver) {
- return NextStorageDriver.supported();
- })
- ;
-
- if (NextStorageDriver)
- {
- NextStorageDriver = /** @type {?Function} */ NextStorageDriver;
- this.oDriver = new NextStorageDriver();
- }
-}
-
-LocalStorage.prototype.oDriver = null;
-
-/**
- * @param {number} iKey
- * @param {*} mData
- * @return {boolean}
- */
-LocalStorage.prototype.set = function (iKey, mData)
-{
- return this.oDriver ? this.oDriver.set('p' + iKey, mData) : false;
-};
-
-/**
- * @param {number} iKey
- * @return {*}
- */
-LocalStorage.prototype.get = function (iKey)
-{
- return this.oDriver ? this.oDriver.get('p' + iKey) : null;
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function KnoinAbstractBoot()
-{
-
-}
-
-KnoinAbstractBoot.prototype.bootstart = function ()
-{
-
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @param {string=} sPosition = ''
- * @param {string=} sTemplate = ''
- * @constructor
- */
-function KnoinAbstractViewModel(sPosition, sTemplate)
-{
- this.bDisabeCloseOnEsc = false;
- this.sPosition = Utils.pString(sPosition);
- this.sTemplate = Utils.pString(sTemplate);
-
- this.sDefaultKeyScope = Enums.KeyState.None;
- this.sCurrentKeyScope = this.sDefaultKeyScope;
-
- this.viewModelName = '';
- this.viewModelVisibility = ko.observable(false);
- this.modalVisibility = ko.observable(false).extend({'rateLimit': 0});
-
- this.viewModelDom = null;
-}
-
-/**
- * @type {string}
- */
-KnoinAbstractViewModel.prototype.sPosition = '';
-
-/**
- * @type {string}
- */
-KnoinAbstractViewModel.prototype.sTemplate = '';
-
-/**
- * @type {string}
- */
-KnoinAbstractViewModel.prototype.viewModelName = '';
-
-/**
- * @type {?}
- */
-KnoinAbstractViewModel.prototype.viewModelDom = null;
-
-/**
- * @return {string}
- */
-KnoinAbstractViewModel.prototype.viewModelTemplate = function ()
-{
- return this.sTemplate;
-};
-
-/**
- * @return {string}
- */
-KnoinAbstractViewModel.prototype.viewModelPosition = function ()
-{
- return this.sPosition;
-};
-
-KnoinAbstractViewModel.prototype.cancelCommand = KnoinAbstractViewModel.prototype.closeCommand = function ()
-{
-};
-
-KnoinAbstractViewModel.prototype.storeAndSetKeyScope = function ()
-{
- this.sCurrentKeyScope = RL.data().keyScope();
- RL.data().keyScope(this.sDefaultKeyScope);
-};
-
-KnoinAbstractViewModel.prototype.restoreKeyScope = function ()
-{
- RL.data().keyScope(this.sCurrentKeyScope);
-};
-
-KnoinAbstractViewModel.prototype.registerPopupKeyDown = function ()
-{
- var self = this;
- $window.on('keydown', function (oEvent) {
- if (oEvent && self.modalVisibility && self.modalVisibility())
- {
- if (!this.bDisabeCloseOnEsc && Enums.EventKeyCode.Esc === oEvent.keyCode)
- {
- Utils.delegateRun(self, 'cancelCommand');
- return false;
- }
- else if (Enums.EventKeyCode.Backspace === oEvent.keyCode && !Utils.inFocus())
- {
- return false;
- }
- }
-
- return true;
- });
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @param {string} sScreenName
- * @param {?=} aViewModels = []
- * @constructor
- */
-function KnoinAbstractScreen(sScreenName, aViewModels)
-{
- this.sScreenName = sScreenName;
- this.aViewModels = Utils.isArray(aViewModels) ? aViewModels : [];
-}
-
-/**
- * @type {Array}
- */
-KnoinAbstractScreen.prototype.oCross = null;
-
-/**
- * @type {string}
- */
-KnoinAbstractScreen.prototype.sScreenName = '';
-
-/**
- * @type {Array}
- */
-KnoinAbstractScreen.prototype.aViewModels = [];
-
-/**
- * @return {Array}
- */
-KnoinAbstractScreen.prototype.viewModels = function ()
-{
- return this.aViewModels;
-};
-
-/**
- * @return {string}
- */
-KnoinAbstractScreen.prototype.screenName = function ()
-{
- return this.sScreenName;
-};
-
-KnoinAbstractScreen.prototype.routes = function ()
-{
- return null;
-};
-
-/**
- * @return {?Object}
- */
-KnoinAbstractScreen.prototype.__cross = function ()
-{
- return this.oCross;
-};
-
-KnoinAbstractScreen.prototype.__start = function ()
-{
- var
- aRoutes = this.routes(),
- oRoute = null,
- fMatcher = null
- ;
-
- if (Utils.isNonEmptyArray(aRoutes))
- {
- fMatcher = _.bind(this.onRoute || Utils.emptyFunction, this);
- oRoute = crossroads.create();
-
- _.each(aRoutes, function (aItem) {
- oRoute.addRoute(aItem[0], fMatcher).rules = aItem[1];
- });
-
- this.oCross = oRoute;
- }
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function Knoin()
-{
- this.sDefaultScreenName = '';
- this.oScreens = {};
- this.oBoot = null;
- this.oCurrentScreen = null;
-}
-
-/**
- * @param {Object} thisObject
- */
-Knoin.constructorEnd = function (thisObject)
-{
- if (Utils.isFunc(thisObject['__constructor_end']))
- {
- thisObject['__constructor_end'].call(thisObject);
- }
-};
-
-Knoin.prototype.sDefaultScreenName = '';
-Knoin.prototype.oScreens = {};
-Knoin.prototype.oBoot = null;
-Knoin.prototype.oCurrentScreen = null;
-
-Knoin.prototype.hideLoading = function ()
-{
- $('#rl-loading').hide();
-};
-
-Knoin.prototype.routeOff = function ()
-{
- hasher.changed.active = false;
-};
-
-Knoin.prototype.routeOn = function ()
-{
- hasher.changed.active = true;
-};
-
-/**
- * @param {Object} oBoot
- * @return {Knoin}
- */
-Knoin.prototype.setBoot = function (oBoot)
-{
- if (Utils.isNormal(oBoot))
- {
- this.oBoot = oBoot;
- }
-
- return this;
-};
-
-/**
- * @param {string} sScreenName
- * @return {?Object}
- */
-Knoin.prototype.screen = function (sScreenName)
-{
- return ('' !== sScreenName && !Utils.isUnd(this.oScreens[sScreenName])) ? this.oScreens[sScreenName] : null;
-};
-
-/**
- * @param {Function} ViewModelClass
- * @param {Object=} oScreen
- */
-Knoin.prototype.buildViewModel = function (ViewModelClass, oScreen)
-{
- if (ViewModelClass && !ViewModelClass.__builded)
- {
- var
- oViewModel = new ViewModelClass(oScreen),
- sPosition = oViewModel.viewModelPosition(),
- oViewModelPlace = $('#rl-content #rl-' + sPosition.toLowerCase()),
- oViewModelDom = null
- ;
-
- ViewModelClass.__builded = true;
- ViewModelClass.__vm = oViewModel;
- oViewModel.data = RL.data();
-
- oViewModel.viewModelName = ViewModelClass.__name;
-
- if (oViewModelPlace && 1 === oViewModelPlace.length)
- {
- oViewModelDom = $('').addClass('rl-view-model').addClass('RL-' + oViewModel.viewModelTemplate()).hide();
- oViewModelDom.appendTo(oViewModelPlace);
-
- oViewModel.viewModelDom = oViewModelDom;
- ViewModelClass.__dom = oViewModelDom;
-
- if ('Popups' === sPosition)
- {
- oViewModel.cancelCommand = oViewModel.closeCommand = Utils.createCommand(oViewModel, function () {
- kn.hideScreenPopup(ViewModelClass);
- });
-
- oViewModel.modalVisibility.subscribe(function (bValue) {
-
- var self = this;
- if (bValue)
- {
- this.viewModelDom.show();
- this.storeAndSetKeyScope();
-
- RL.popupVisibilityNames.push(this.viewModelName);
- oViewModel.viewModelDom.css('z-index', 3000 + RL.popupVisibilityNames().length + 10);
-
- Utils.delegateRun(this, 'onFocus', [], 500);
+ aResult.push(oData);
}
else
{
- Utils.delegateRun(this, 'onHide');
- this.restoreKeyScope();
-
- RL.popupVisibilityNames.remove(this.viewModelName);
- oViewModel.viewModelDom.css('z-index', 2000);
-
- Globals.tooltipTrigger(!Globals.tooltipTrigger());
-
- _.delay(function () {
- self.viewModelDom.hide();
- }, 300);
- }
-
- }, oViewModel);
- }
-
- Plugins.runHook('view-model-pre-build', [ViewModelClass.__name, oViewModel, oViewModelDom]);
-
- ko.applyBindingAccessorsToNode(oViewModelDom[0], {
- 'i18nInit': true,
- 'template': function () { return {'name': oViewModel.viewModelTemplate()};}
- }, oViewModel);
-
- Utils.delegateRun(oViewModel, 'onBuild', [oViewModelDom]);
- if (oViewModel && 'Popups' === sPosition)
- {
- oViewModel.registerPopupKeyDown();
- }
-
- Plugins.runHook('view-model-post-build', [ViewModelClass.__name, oViewModel, oViewModelDom]);
- }
- else
- {
- Utils.log('Cannot find view model position: ' + sPosition);
- }
- }
-
- return ViewModelClass ? ViewModelClass.__vm : null;
-};
-
-/**
- * @param {Object} oViewModel
- * @param {Object} oViewModelDom
- */
-Knoin.prototype.applyExternal = function (oViewModel, oViewModelDom)
-{
- if (oViewModel && oViewModelDom)
- {
- ko.applyBindings(oViewModel, oViewModelDom);
- }
-};
-
-/**
- * @param {Function} ViewModelClassToHide
- */
-Knoin.prototype.hideScreenPopup = function (ViewModelClassToHide)
-{
- if (ViewModelClassToHide && ViewModelClassToHide.__vm && ViewModelClassToHide.__dom)
- {
- ViewModelClassToHide.__vm.modalVisibility(false);
- Plugins.runHook('view-model-on-hide', [ViewModelClassToHide.__name, ViewModelClassToHide.__vm]);
- }
-};
-
-/**
- * @param {Function} ViewModelClassToShow
- * @param {Array=} aParameters
- */
-Knoin.prototype.showScreenPopup = function (ViewModelClassToShow, aParameters)
-{
- if (ViewModelClassToShow)
- {
- this.buildViewModel(ViewModelClassToShow);
-
- if (ViewModelClassToShow.__vm && ViewModelClassToShow.__dom)
- {
- ViewModelClassToShow.__vm.modalVisibility(true);
- Utils.delegateRun(ViewModelClassToShow.__vm, 'onShow', aParameters || []);
- Plugins.runHook('view-model-on-show', [ViewModelClassToShow.__name, ViewModelClassToShow.__vm, aParameters || []]);
- }
- }
-};
-
-/**
- * @param {Function} ViewModelClassToShow
- * @return {boolean}
- */
-Knoin.prototype.isPopupVisible = function (ViewModelClassToShow)
-{
- return ViewModelClassToShow && ViewModelClassToShow.__vm ? ViewModelClassToShow.__vm.modalVisibility() : false;
-};
-
-/**
- * @param {string} sScreenName
- * @param {string} sSubPart
- */
-Knoin.prototype.screenOnRoute = function (sScreenName, sSubPart)
-{
- var
- self = this,
- oScreen = null,
- oCross = null
- ;
-
- if ('' === Utils.pString(sScreenName))
- {
- sScreenName = this.sDefaultScreenName;
- }
-
- if ('' !== sScreenName)
- {
- oScreen = this.screen(sScreenName);
- if (!oScreen)
- {
- oScreen = this.screen(this.sDefaultScreenName);
- if (oScreen)
- {
- sSubPart = sScreenName + '/' + sSubPart;
- sScreenName = this.sDefaultScreenName;
- }
- }
-
- if (oScreen && oScreen.__started)
- {
- if (!oScreen.__builded)
- {
- oScreen.__builded = true;
-
- if (Utils.isNonEmptyArray(oScreen.viewModels()))
- {
- _.each(oScreen.viewModels(), function (ViewModelClass) {
- this.buildViewModel(ViewModelClass, oScreen);
- }, this);
- }
-
- Utils.delegateRun(oScreen, 'onBuild');
- }
-
- _.defer(function () {
-
- // hide screen
- if (self.oCurrentScreen)
- {
- Utils.delegateRun(self.oCurrentScreen, 'onHide');
-
- if (Utils.isNonEmptyArray(self.oCurrentScreen.viewModels()))
- {
- _.each(self.oCurrentScreen.viewModels(), function (ViewModelClass) {
-
- if (ViewModelClass.__vm && ViewModelClass.__dom &&
- 'Popups' !== ViewModelClass.__vm.viewModelPosition())
- {
- ViewModelClass.__dom.hide();
- ViewModelClass.__vm.viewModelVisibility(false);
- Utils.delegateRun(ViewModelClass.__vm, 'onHide');
- }
-
- });
+ aResult.unshift(oData);
}
}
- // --
-
- self.oCurrentScreen = oScreen;
-
- // show screen
- if (self.oCurrentScreen)
- {
- Utils.delegateRun(self.oCurrentScreen, 'onShow');
-
- Plugins.runHook('screen-on-show', [self.oCurrentScreen.screenName(), self.oCurrentScreen]);
-
- if (Utils.isNonEmptyArray(self.oCurrentScreen.viewModels()))
- {
- _.each(self.oCurrentScreen.viewModels(), function (ViewModelClass) {
-
- if (ViewModelClass.__vm && ViewModelClass.__dom &&
- 'Popups' !== ViewModelClass.__vm.viewModelPosition())
- {
- ViewModelClass.__dom.show();
- ViewModelClass.__vm.viewModelVisibility(true);
- Utils.delegateRun(ViewModelClass.__vm, 'onShow');
- Utils.delegateRun(ViewModelClass.__vm, 'onFocus', [], 200);
-
- Plugins.runHook('view-model-on-show', [ViewModelClass.__name, ViewModelClass.__vm]);
- }
-
- }, self);
- }
- }
- // --
-
- oCross = oScreen.__cross();
- if (oCross)
- {
- oCross.parse(sSubPart);
- }
- });
- }
- }
-};
-
-/**
- * @param {Array} aScreensClasses
- */
-Knoin.prototype.startScreens = function (aScreensClasses)
-{
- $('#rl-content').css({
- 'visibility': 'hidden'
- });
-
- _.each(aScreensClasses, function (CScreen) {
-
- var
- oScreen = new CScreen(),
- sScreenName = oScreen ? oScreen.screenName() : ''
;
- if (oScreen && '' !== sScreenName)
+ if (1 < iPageCount || (0 < iPageCount && iPageCount < iCurrentPage))
+ // if (0 < iPageCount && 0 < iCurrentPage)
{
- if ('' === this.sDefaultScreenName)
+ if (iPageCount < iCurrentPage)
{
- this.sDefaultScreenName = sScreenName;
- }
-
- this.oScreens[sScreenName] = oScreen;
- }
-
- }, this);
-
-
- _.each(this.oScreens, function (oScreen) {
- if (oScreen && !oScreen.__started && oScreen.__start)
- {
- oScreen.__started = true;
- oScreen.__start();
-
- Plugins.runHook('screen-pre-start', [oScreen.screenName(), oScreen]);
- Utils.delegateRun(oScreen, 'onStart');
- Plugins.runHook('screen-post-start', [oScreen.screenName(), oScreen]);
- }
- }, this);
-
- var oCross = crossroads.create();
- oCross.addRoute(/^([a-zA-Z0-9\-]*)\/?(.*)$/, _.bind(this.screenOnRoute, this));
-
- hasher.initialized.add(oCross.parse, oCross);
- hasher.changed.add(oCross.parse, oCross);
- hasher.init();
-
- $('#rl-content').css({
- 'visibility': 'visible'
- });
-
- _.delay(function () {
- $html.removeClass('rl-started-trigger').addClass('rl-started');
- }, 50);
-};
-
-/**
- * @param {string} sHash
- * @param {boolean=} bSilence = false
- * @param {boolean=} bReplace = false
- */
-Knoin.prototype.setHash = function (sHash, bSilence, bReplace)
-{
- sHash = '#' === sHash.substr(0, 1) ? sHash.substr(1) : sHash;
- sHash = '/' === sHash.substr(0, 1) ? sHash.substr(1) : sHash;
-
- bReplace = Utils.isUnd(bReplace) ? false : !!bReplace;
-
- if (Utils.isUnd(bSilence) ? false : !!bSilence)
- {
- hasher.changed.active = false;
- hasher[bReplace ? 'replaceHash' : 'setHash'](sHash);
- hasher.changed.active = true;
- }
- else
- {
- hasher.changed.active = true;
- hasher[bReplace ? 'replaceHash' : 'setHash'](sHash);
- hasher.setHash(sHash);
- }
-};
-
-/**
- * @return {Knoin}
- */
-Knoin.prototype.bootstart = function ()
-{
- if (this.oBoot && this.oBoot.bootstart)
- {
- this.oBoot.bootstart();
- }
-
- return this;
-};
-
-kn = new Knoin();
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @param {string=} sEmail
- * @param {string=} sName
- *
- * @constructor
- */
-function EmailModel(sEmail, sName)
-{
- this.email = sEmail || '';
- this.name = sName || '';
- this.privateType = null;
-
- this.clearDuplicateName();
-}
-
-/**
- * @static
- * @param {AjaxJsonEmail} oJsonEmail
- * @return {?EmailModel}
- */
-EmailModel.newInstanceFromJson = function (oJsonEmail)
-{
- var oEmailModel = new EmailModel();
- return oEmailModel.initByJson(oJsonEmail) ? oEmailModel : null;
-};
-
-/**
- * @type {string}
- */
-EmailModel.prototype.name = '';
-
-/**
- * @type {string}
- */
-EmailModel.prototype.email = '';
-
-/**
- * @type {(number|null)}
- */
-EmailModel.prototype.privateType = null;
-
-EmailModel.prototype.clear = function ()
-{
- this.email = '';
- this.name = '';
- this.privateType = null;
-};
-
-/**
- * @returns {boolean}
- */
-EmailModel.prototype.validate = function ()
-{
- return '' !== this.name || '' !== this.email;
-};
-
-/**
- * @param {boolean} bWithoutName = false
- * @return {string}
- */
-EmailModel.prototype.hash = function (bWithoutName)
-{
- return '#' + (bWithoutName ? '' : this.name) + '#' + this.email + '#';
-};
-
-EmailModel.prototype.clearDuplicateName = function ()
-{
- if (this.name === this.email)
- {
- this.name = '';
- }
-};
-
-/**
- * @return {number}
- */
-EmailModel.prototype.type = function ()
-{
- if (null === this.privateType)
- {
- if (this.email && '@facebook.com' === this.email.substr(-13))
- {
- this.privateType = Enums.EmailType.Facebook;
- }
-
- if (null === this.privateType)
- {
- this.privateType = Enums.EmailType.Default;
- }
- }
-
- return this.privateType;
-};
-
-/**
- * @param {string} sQuery
- * @return {boolean}
- */
-EmailModel.prototype.search = function (sQuery)
-{
- return -1 < (this.name + ' ' + this.email).toLowerCase().indexOf(sQuery.toLowerCase());
-};
-
-/**
- * @param {string} sString
- */
-EmailModel.prototype.parse = function (sString)
-{
- this.clear();
-
- sString = Utils.trim(sString);
-
- var
- mRegex = /(?:"([^"]+)")? ?(.*?@[^>,]+)>?,? ?/g,
- mMatch = mRegex.exec(sString)
- ;
-
- if (mMatch)
- {
- this.name = mMatch[1] || '';
- this.email = mMatch[2] || '';
-
- this.clearDuplicateName();
- }
- else if ((/^[^@]+@[^@]+$/).test(sString))
- {
- this.name = '';
- this.email = sString;
- }
-};
-
-/**
- * @param {AjaxJsonEmail} oJsonEmail
- * @return {boolean}
- */
-EmailModel.prototype.initByJson = function (oJsonEmail)
-{
- var bResult = false;
- if (oJsonEmail && 'Object/Email' === oJsonEmail['@Object'])
- {
- this.name = Utils.trim(oJsonEmail.Name);
- this.email = Utils.trim(oJsonEmail.Email);
-
- bResult = '' !== this.email;
- this.clearDuplicateName();
- }
-
- return bResult;
-};
-
-/**
- * @param {boolean} bFriendlyView
- * @param {boolean=} bWrapWithLink = false
- * @param {boolean=} bEncodeHtml = false
- * @return {string}
- */
-EmailModel.prototype.toLine = function (bFriendlyView, bWrapWithLink, bEncodeHtml)
-{
- var sResult = '';
- if ('' !== this.email)
- {
- bWrapWithLink = Utils.isUnd(bWrapWithLink) ? false : !!bWrapWithLink;
- bEncodeHtml = Utils.isUnd(bEncodeHtml) ? false : !!bEncodeHtml;
-
- if (bFriendlyView && '' !== this.name)
- {
- sResult = bWrapWithLink ? '') +
- '" target="_blank" tabindex="-1">' + Utils.encodeHtml(this.name) + '' :
- (bEncodeHtml ? Utils.encodeHtml(this.name) : this.name);
- }
- else
- {
- sResult = this.email;
- if ('' !== this.name)
- {
- if (bWrapWithLink)
- {
- sResult = Utils.encodeHtml('"' + this.name + '" <') +
- '') + '" target="_blank" tabindex="-1">' + Utils.encodeHtml(sResult) + '' + Utils.encodeHtml('>');
+ fAdd(iPageCount);
+ iPrev = iPageCount;
+ iNext = iPageCount;
}
else
{
- sResult = '"' + this.name + '" <' + sResult + '>';
- if (bEncodeHtml)
+ if (3 >= iCurrentPage || iPageCount - 2 <= iCurrentPage)
{
- sResult = Utils.encodeHtml(sResult);
- }
- }
- }
- else if (bWrapWithLink)
- {
- sResult = '' + Utils.encodeHtml(this.email) + '';
- }
- }
- }
-
- return sResult;
-};
-
-/**
- * @param {string} $sEmailAddress
- * @return {boolean}
- */
-EmailModel.prototype.mailsoParse = function ($sEmailAddress)
-{
- $sEmailAddress = Utils.trim($sEmailAddress);
- if ('' === $sEmailAddress)
- {
- return false;
- }
-
- var
- substr = function (str, start, len) {
- str += '';
- var end = str.length;
-
- if (start < 0) {
- start += end;
- }
-
- end = typeof len === 'undefined' ? end : (len < 0 ? len + end : len + start);
-
- return start >= str.length || start < 0 || start > end ? false : str.slice(start, end);
- },
-
- substr_replace = function (str, replace, start, length) {
- if (start < 0) {
- start = start + str.length;
- }
- length = length !== undefined ? length : str.length;
- if (length < 0) {
- length = length + str.length - start;
- }
- return str.slice(0, start) + replace.substr(0, length) + replace.slice(length) + str.slice(start + length);
- },
-
- $sName = '',
- $sEmail = '',
- $sComment = '',
-
- $bInName = false,
- $bInAddress = false,
- $bInComment = false,
-
- $aRegs = null,
-
- $iStartIndex = 0,
- $iEndIndex = 0,
- $iCurrentIndex = 0
- ;
-
- while ($iCurrentIndex < $sEmailAddress.length)
- {
- switch ($sEmailAddress.substr($iCurrentIndex, 1))
- {
- case '"':
- if ((!$bInName) && (!$bInAddress) && (!$bInComment))
- {
- $bInName = true;
- $iStartIndex = $iCurrentIndex;
- }
- else if ((!$bInAddress) && (!$bInComment))
- {
- $iEndIndex = $iCurrentIndex;
- $sName = substr($sEmailAddress, $iStartIndex + 1, $iEndIndex - $iStartIndex - 1);
- $sEmailAddress = substr_replace($sEmailAddress, '', $iStartIndex, $iEndIndex - $iStartIndex + 1);
- $iEndIndex = 0;
- $iCurrentIndex = 0;
- $iStartIndex = 0;
- $bInName = false;
- }
- break;
- case '<':
- if ((!$bInName) && (!$bInAddress) && (!$bInComment))
- {
- if ($iCurrentIndex > 0 && $sName.length === 0)
- {
- $sName = substr($sEmailAddress, 0, $iCurrentIndex);
+ iLimit += 2;
}
- $bInAddress = true;
- $iStartIndex = $iCurrentIndex;
+ fAdd(iCurrentPage);
+ iPrev = iCurrentPage;
+ iNext = iCurrentPage;
}
- break;
- case '>':
- if ($bInAddress)
- {
- $iEndIndex = $iCurrentIndex;
- $sEmail = substr($sEmailAddress, $iStartIndex + 1, $iEndIndex - $iStartIndex - 1);
- $sEmailAddress = substr_replace($sEmailAddress, '', $iStartIndex, $iEndIndex - $iStartIndex + 1);
- $iEndIndex = 0;
- $iCurrentIndex = 0;
- $iStartIndex = 0;
- $bInAddress = false;
- }
- break;
- case '(':
- if ((!$bInName) && (!$bInAddress) && (!$bInComment))
- {
- $bInComment = true;
- $iStartIndex = $iCurrentIndex;
- }
- break;
- case ')':
- if ($bInComment)
- {
- $iEndIndex = $iCurrentIndex;
- $sComment = substr($sEmailAddress, $iStartIndex + 1, $iEndIndex - $iStartIndex - 1);
- $sEmailAddress = substr_replace($sEmailAddress, '', $iStartIndex, $iEndIndex - $iStartIndex + 1);
- $iEndIndex = 0;
- $iCurrentIndex = 0;
- $iStartIndex = 0;
- $bInComment = false;
- }
- break;
- case '\\':
- $iCurrentIndex++;
- break;
- }
- $iCurrentIndex++;
- }
+ while (0 < iLimit) {
- if ($sEmail.length === 0)
+ iPrev -= 1;
+ iNext += 1;
+
+ if (0 < iPrev)
+ {
+ fAdd(iPrev, false);
+ iLimit--;
+ }
+
+ if (iPageCount >= iNext)
+ {
+ fAdd(iNext, true);
+ iLimit--;
+ }
+ else if (0 >= iPrev)
+ {
+ break;
+ }
+ }
+
+ if (3 === iPrev)
+ {
+ fAdd(2, false);
+ }
+ else if (3 < iPrev)
+ {
+ fAdd(window.Math.round((iPrev - 1) / 2), false, '...');
+ }
+
+ if (iPageCount - 2 === iNext)
+ {
+ fAdd(iPageCount - 1, true);
+ }
+ else if (iPageCount - 2 > iNext)
+ {
+ fAdd(window.Math.round((iPageCount + iNext) / 2), true, '...');
+ }
+
+ // first and last
+ if (1 < iPrev)
+ {
+ fAdd(1, false);
+ }
+
+ if (iPageCount > iNext)
+ {
+ fAdd(iPageCount, true);
+ }
+ }
+
+ return aResult;
+ };
+ };
+
+ Utils.selectElement = function (element)
{
- $aRegs = $sEmailAddress.match(/[^@\s]+@\S+/i);
- if ($aRegs && $aRegs[0])
+ /* jshint onevar: false */
+ if (window.getSelection)
{
- $sEmail = $aRegs[0];
+ var sel = window.getSelection();
+ sel.removeAllRanges();
+ var range = window.document.createRange();
+ range.selectNodeContents(element);
+ sel.addRange(range);
+ }
+ else if (window.document.selection)
+ {
+ var textRange = window.document.body.createTextRange();
+ textRange.moveToElementText(element);
+ textRange.select();
+ }
+ /* jshint onevar: true */
+ };
+
+ Utils.disableKeyFilter = function (Data)
+ {
+ if (window.key)
+ {
+ key.filter = function () {
+ return Data.useKeyboardShortcuts();
+ };
+ }
+ };
+
+ Utils.restoreKeyFilter = function (Data)
+ {
+ if (window.key)
+ {
+ key.filter = function (event) {
+
+ if (Data.useKeyboardShortcuts())
+ {
+ var
+ oElement = event.target || event.srcElement,
+ sTagName = oElement ? oElement.tagName : ''
+ ;
+
+ sTagName = sTagName.toUpperCase();
+ return !(sTagName === 'INPUT' || sTagName === 'SELECT' || sTagName === 'TEXTAREA' ||
+ (oElement && sTagName === 'DIV' && 'editorHtmlArea' === oElement.className && oElement.contentEditable)
+ );
+ }
+
+ return false;
+ };
+ }
+ };
+
+ Utils.detectDropdownVisibility = _.debounce(function () {
+ Globals.dropdownVisibility(!!_.find(Globals.aBootstrapDropdowns, function (oItem) {
+ return oItem.hasClass('open');
+ }));
+ }, 50);
+
+ Utils.triggerAutocompleteInputChange = function (bDelay) {
+
+ var fFunc = function () {
+ $('.checkAutocomplete').trigger('change');
+ };
+
+ if (bDelay)
+ {
+ _.delay(fFunc, 100);
}
else
{
- $sName = $sEmailAddress;
+ fFunc();
}
- }
+ };
- if ($sEmail.length > 0 && $sName.length === 0 && $sComment.length === 0)
- {
- $sName = $sEmailAddress.replace($sEmail, '');
- }
+ module.exports = Utils;
- $sEmail = Utils.trim($sEmail).replace(/^[<]+/, '').replace(/[>]+$/, '');
- $sName = Utils.trim($sName).replace(/^["']+/, '').replace(/["']+$/, '');
- $sComment = Utils.trim($sComment).replace(/^[(]+/, '').replace(/[)]+$/, '');
+}(module));
+// Base64 encode / decode
+// http://www.webtoolkit.info/
- // Remove backslash
- $sName = $sName.replace(/\\\\(.)/, '$1');
- $sComment = $sComment.replace(/\\\\(.)/, '$1');
+(function (module) {
- this.name = $sName;
- this.email = $sEmail;
+ 'use strict';
- this.clearDuplicateName();
- return true;
-};
+ /*jslint bitwise: true*/
+ var Base64 = {
-/**
- * @return {string}
- */
-EmailModel.prototype.inputoTagLine = function ()
-{
- return 0 < this.name.length ? this.name + ' (' + this.email + ')' : this.email;
-};
-
+ // private property
+ _keyStr : 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
+
+ // public method for urlsafe encoding
+ urlsafe_encode : function (input) {
+ return Base64.encode(input).replace(/[+]/g, '-').replace(/[\/]/g, '_').replace(/[=]/g, '.');
+ },
+
+ // public method for encoding
+ encode : function (input) {
+ var
+ output = '',
+ chr1, chr2, chr3, enc1, enc2, enc3, enc4,
+ i = 0
+ ;
+
+ input = Base64._utf8_encode(input);
+
+ while (i < input.length)
+ {
+ chr1 = input.charCodeAt(i++);
+ chr2 = input.charCodeAt(i++);
+ chr3 = input.charCodeAt(i++);
+
+ enc1 = chr1 >> 2;
+ enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
+ enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
+ enc4 = chr3 & 63;
+
+ if (isNaN(chr2))
+ {
+ enc3 = enc4 = 64;
+ }
+ else if (isNaN(chr3))
+ {
+ enc4 = 64;
+ }
+
+ output = output +
+ this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
+ this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
+ }
+
+ return output;
+ },
+
+ // public method for decoding
+ decode : function (input) {
+ var
+ output = '',
+ chr1, chr2, chr3, enc1, enc2, enc3, enc4,
+ i = 0
+ ;
+
+ input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
+
+ while (i < input.length)
+ {
+ enc1 = this._keyStr.indexOf(input.charAt(i++));
+ enc2 = this._keyStr.indexOf(input.charAt(i++));
+ enc3 = this._keyStr.indexOf(input.charAt(i++));
+ enc4 = this._keyStr.indexOf(input.charAt(i++));
+
+ chr1 = (enc1 << 2) | (enc2 >> 4);
+ chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
+ chr3 = ((enc3 & 3) << 6) | enc4;
+
+ output = output + String.fromCharCode(chr1);
+
+ if (enc3 !== 64)
+ {
+ output = output + String.fromCharCode(chr2);
+ }
+
+ if (enc4 !== 64)
+ {
+ output = output + String.fromCharCode(chr3);
+ }
+ }
+
+ return Base64._utf8_decode(output);
+ },
+
+ // private method for UTF-8 encoding
+ _utf8_encode : function (string) {
+
+ string = string.replace(/\r\n/g, "\n");
+
+ var
+ utftext = '',
+ n = 0,
+ l = string.length,
+ c = 0
+ ;
+
+ for (; n < l; n++) {
+
+ c = string.charCodeAt(n);
+
+ if (c < 128)
+ {
+ utftext += String.fromCharCode(c);
+ }
+ else if ((c > 127) && (c < 2048))
+ {
+ utftext += String.fromCharCode((c >> 6) | 192);
+ utftext += String.fromCharCode((c & 63) | 128);
+ }
+ else
+ {
+ utftext += String.fromCharCode((c >> 12) | 224);
+ utftext += String.fromCharCode(((c >> 6) & 63) | 128);
+ utftext += String.fromCharCode((c & 63) | 128);
+ }
+ }
+
+ return utftext;
+ },
+
+ // private method for UTF-8 decoding
+ _utf8_decode : function (utftext) {
+ var
+ string = '',
+ i = 0,
+ c = 0,
+ c2 = 0,
+ c3 = 0
+ ;
+
+ while ( i < utftext.length )
+ {
+ c = utftext.charCodeAt(i);
+
+ if (c < 128)
+ {
+ string += String.fromCharCode(c);
+ i++;
+ }
+ else if((c > 191) && (c < 224))
+ {
+ c2 = utftext.charCodeAt(i+1);
+ string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
+ i += 2;
+ }
+ else
+ {
+ c2 = utftext.charCodeAt(i+1);
+ c3 = utftext.charCodeAt(i+2);
+ string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
+ i += 3;
+ }
+ }
+
+ return string;
+ }
+ };
+
+ module.exports = Base64;
+ /*jslint bitwise: false*/
+
+}(module));
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-/**
- * @constructor
- */
-function ContactTagModel()
-{
- this.idContactTag = 0;
- this.name = ko.observable('');
- this.readOnly = false;
-}
+(function (module) {
-ContactTagModel.prototype.parse = function (oItem)
-{
- var bResult = false;
- if (oItem && 'Object/Tag' === oItem['@Object'])
+ 'use strict';
+
+ var
+ window = require('../External/window.js'),
+ Utils = require('./Utils.js')
+ ;
+
+ /**
+ * @constructor
+ */
+ function LinkBuilder()
{
- this.idContact = Utils.pInt(oItem['IdContactTag']);
- this.name(Utils.pString(oItem['Name']));
- this.readOnly = !!oItem['ReadOnly'];
-
- bResult = true;
+ this.sBase = '#/';
+ this.sServer = './?';
+ this.sVersion = RL.settingsGet('Version');
+ this.sSpecSuffix = RL.settingsGet('AuthAccountHash') || '0';
+ this.sStaticPrefix = RL.settingsGet('StaticPrefix') || 'rainloop/v/' + this.sVersion + '/static/';
}
- return bResult;
-};
+ /**
+ * @return {string}
+ */
+ LinkBuilder.prototype.root = function ()
+ {
+ return this.sBase;
+ };
-/**
- * @param {string} sSearch
- * @return {boolean}
- */
-ContactTagModel.prototype.filterHelper = function (sSearch)
-{
- return this.name().toLowerCase().indexOf(sSearch.toLowerCase()) !== -1;
-};
+ /**
+ * @param {string} sDownload
+ * @return {string}
+ */
+ LinkBuilder.prototype.attachmentDownload = function (sDownload)
+ {
+ return this.sServer + '/Raw/' + this.sSpecSuffix + '/Download/' + sDownload;
+ };
-/**
- * @param {boolean=} bEncodeHtml = false
- * @return {string}
- */
-ContactTagModel.prototype.toLine = function (bEncodeHtml)
-{
- return (Utils.isUnd(bEncodeHtml) ? false : !!bEncodeHtml) ?
- Utils.encodeHtml(this.name()) : this.name();
-};
-
+ /**
+ * @param {string} sDownload
+ * @return {string}
+ */
+ LinkBuilder.prototype.attachmentPreview = function (sDownload)
+ {
+ return this.sServer + '/Raw/' + this.sSpecSuffix + '/View/' + sDownload;
+ };
+
+ /**
+ * @param {string} sDownload
+ * @return {string}
+ */
+ LinkBuilder.prototype.attachmentPreviewAsPlain = function (sDownload)
+ {
+ return this.sServer + '/Raw/' + this.sSpecSuffix + '/ViewAsPlain/' + sDownload;
+ };
+
+ /**
+ * @return {string}
+ */
+ LinkBuilder.prototype.upload = function ()
+ {
+ return this.sServer + '/Upload/' + this.sSpecSuffix + '/';
+ };
+
+ /**
+ * @return {string}
+ */
+ LinkBuilder.prototype.uploadContacts = function ()
+ {
+ return this.sServer + '/UploadContacts/' + this.sSpecSuffix + '/';
+ };
+
+ /**
+ * @return {string}
+ */
+ LinkBuilder.prototype.uploadBackground = function ()
+ {
+ return this.sServer + '/UploadBackground/' + this.sSpecSuffix + '/';
+ };
+
+ /**
+ * @return {string}
+ */
+ LinkBuilder.prototype.append = function ()
+ {
+ return this.sServer + '/Append/' + this.sSpecSuffix + '/';
+ };
+
+ /**
+ * @param {string} sEmail
+ * @return {string}
+ */
+ LinkBuilder.prototype.change = function (sEmail)
+ {
+ return this.sServer + '/Change/' + this.sSpecSuffix + '/' + window.encodeURIComponent(sEmail) + '/';
+ };
+
+ /**
+ * @param {string=} sAdd
+ * @return {string}
+ */
+ LinkBuilder.prototype.ajax = function (sAdd)
+ {
+ return this.sServer + '/Ajax/' + this.sSpecSuffix + '/' + sAdd;
+ };
+
+ /**
+ * @param {string} sRequestHash
+ * @return {string}
+ */
+ LinkBuilder.prototype.messageViewLink = function (sRequestHash)
+ {
+ return this.sServer + '/Raw/' + this.sSpecSuffix + '/ViewAsPlain/' + sRequestHash;
+ };
+
+ /**
+ * @param {string} sRequestHash
+ * @return {string}
+ */
+ LinkBuilder.prototype.messageDownloadLink = function (sRequestHash)
+ {
+ return this.sServer + '/Raw/' + this.sSpecSuffix + '/Download/' + sRequestHash;
+ };
+
+ /**
+ * @param {string} sEmail
+ * @return {string}
+ */
+ LinkBuilder.prototype.avatarLink = function (sEmail)
+ {
+ return this.sServer + '/Raw/0/Avatar/' + window.encodeURIComponent(sEmail) + '/';
+ // return '//secure.gravatar.com/avatar/' + Utils.md5(sEmail.toLowerCase()) + '.jpg?s=80&d=mm';
+ };
+
+ /**
+ * @return {string}
+ */
+ LinkBuilder.prototype.inbox = function ()
+ {
+ return this.sBase + 'mailbox/Inbox';
+ };
+
+ /**
+ * @return {string}
+ */
+ LinkBuilder.prototype.messagePreview = function ()
+ {
+ return this.sBase + 'mailbox/message-preview';
+ };
+
+ /**
+ * @param {string=} sScreenName
+ * @return {string}
+ */
+ LinkBuilder.prototype.settings = function (sScreenName)
+ {
+ var sResult = this.sBase + 'settings';
+ if (!Utils.isUnd(sScreenName) && '' !== sScreenName)
+ {
+ sResult += '/' + sScreenName;
+ }
+
+ return sResult;
+ };
+
+ /**
+ * @param {string} sScreenName
+ * @return {string}
+ */
+ LinkBuilder.prototype.admin = function (sScreenName)
+ {
+ var sResult = this.sBase;
+ switch (sScreenName) {
+ case 'AdminDomains':
+ sResult += 'domains';
+ break;
+ case 'AdminSecurity':
+ sResult += 'security';
+ break;
+ case 'AdminLicensing':
+ sResult += 'licensing';
+ break;
+ }
+
+ return sResult;
+ };
+
+ /**
+ * @param {string} sFolder
+ * @param {number=} iPage = 1
+ * @param {string=} sSearch = ''
+ * @return {string}
+ */
+ LinkBuilder.prototype.mailBox = function (sFolder, iPage, sSearch)
+ {
+ iPage = Utils.isNormal(iPage) ? Utils.pInt(iPage) : 1;
+ sSearch = Utils.pString(sSearch);
+
+ var sResult = this.sBase + 'mailbox/';
+ if ('' !== sFolder)
+ {
+ sResult += encodeURI(sFolder);
+ }
+ if (1 < iPage)
+ {
+ sResult = sResult.replace(/[\/]+$/, '');
+ sResult += '/p' + iPage;
+ }
+ if ('' !== sSearch)
+ {
+ sResult = sResult.replace(/[\/]+$/, '');
+ sResult += '/' + encodeURI(sSearch);
+ }
+
+ return sResult;
+ };
+
+ /**
+ * @return {string}
+ */
+ LinkBuilder.prototype.phpInfo = function ()
+ {
+ return this.sServer + 'Info';
+ };
+
+ /**
+ * @param {string} sLang
+ * @return {string}
+ */
+ LinkBuilder.prototype.langLink = function (sLang)
+ {
+ return this.sServer + '/Lang/0/' + encodeURI(sLang) + '/' + this.sVersion + '/';
+ };
+
+ /**
+ * @return {string}
+ */
+ LinkBuilder.prototype.exportContactsVcf = function ()
+ {
+ return this.sServer + '/Raw/' + this.sSpecSuffix + '/ContactsVcf/';
+ };
+
+ /**
+ * @return {string}
+ */
+ LinkBuilder.prototype.exportContactsCsv = function ()
+ {
+ return this.sServer + '/Raw/' + this.sSpecSuffix + '/ContactsCsv/';
+ };
+
+ /**
+ * @return {string}
+ */
+ LinkBuilder.prototype.emptyContactPic = function ()
+ {
+ return this.sStaticPrefix + 'css/images/empty-contact.png';
+ };
+
+ /**
+ * @param {string} sFileName
+ * @return {string}
+ */
+ LinkBuilder.prototype.sound = function (sFileName)
+ {
+ return this.sStaticPrefix + 'sounds/' + sFileName;
+ };
+
+ /**
+ * @param {string} sTheme
+ * @return {string}
+ */
+ LinkBuilder.prototype.themePreviewLink = function (sTheme)
+ {
+ var sPrefix = 'rainloop/v/' + this.sVersion + '/';
+ if ('@custom' === sTheme.substr(-7))
+ {
+ sTheme = Utils.trim(sTheme.substring(0, sTheme.length - 7));
+ sPrefix = '';
+ }
+
+ return sPrefix + 'themes/' + encodeURI(sTheme) + '/images/preview.png';
+ };
+
+ /**
+ * @return {string}
+ */
+ LinkBuilder.prototype.notificationMailIcon = function ()
+ {
+ return this.sStaticPrefix + 'css/images/icom-message-notification.png';
+ };
+
+ /**
+ * @return {string}
+ */
+ LinkBuilder.prototype.openPgpJs = function ()
+ {
+ return this.sStaticPrefix + 'js/openpgp.min.js';
+ };
+
+ /**
+ * @return {string}
+ */
+ LinkBuilder.prototype.socialGoogle = function ()
+ {
+ return this.sServer + 'SocialGoogle' + ('' !== this.sSpecSuffix ? '/' + this.sSpecSuffix + '/' : '');
+ };
+
+ /**
+ * @return {string}
+ */
+ LinkBuilder.prototype.socialTwitter = function ()
+ {
+ return this.sServer + 'SocialTwitter' + ('' !== this.sSpecSuffix ? '/' + this.sSpecSuffix + '/' : '');
+ };
+
+ /**
+ * @return {string}
+ */
+ LinkBuilder.prototype.socialFacebook = function ()
+ {
+ return this.sServer + 'SocialFacebook' + ('' !== this.sSpecSuffix ? '/' + this.sSpecSuffix + '/' : '');
+ };
+
+ module.exports = new LinkBuilder();
+
+}(module));
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-/**
- * @constructor
- * @extends KnoinAbstractViewModel
- */
-function PopupsDomainViewModel()
-{
- KnoinAbstractViewModel.call(this, 'Popups', 'PopupsDomain');
+(function (module) {
- this.edit = ko.observable(false);
- this.saving = ko.observable(false);
- this.savingError = ko.observable('');
- this.whiteListPage = ko.observable(false);
+ 'use strict';
- this.testing = ko.observable(false);
- this.testingDone = ko.observable(false);
- this.testingImapError = ko.observable(false);
- this.testingSmtpError = ko.observable(false);
- this.testingImapErrorDesc = ko.observable('');
- this.testingSmtpErrorDesc = ko.observable('');
+ var
+ Plugins = {
+ __boot: null,
+ __remote: null,
+ __data: null
+ },
+ _ = require('../External/underscore.js'),
+ Utils = require('./Utils.js')
+ ;
- this.testingImapError.subscribe(function (bValue) {
- if (!bValue)
+ /**
+ * @type {Object}
+ */
+ Plugins.oViewModelsHooks = {};
+
+ /**
+ * @type {Object}
+ */
+ Plugins.oSimpleHooks = {};
+
+ /**
+ * @param {string} sName
+ * @param {Function} ViewModel
+ */
+ Plugins.regViewModelHook = function (sName, ViewModel)
+ {
+ if (ViewModel)
{
- this.testingImapErrorDesc('');
+ ViewModel.__hookName = sName;
}
- }, this);
+ };
- this.testingSmtpError.subscribe(function (bValue) {
- if (!bValue)
+ /**
+ * @param {string} sName
+ * @param {Function} fCallback
+ */
+ Plugins.addHook = function (sName, fCallback)
+ {
+ if (Utils.isFunc(fCallback))
{
- this.testingSmtpErrorDesc('');
+ if (!Utils.isArray(Plugins.oSimpleHooks[sName]))
+ {
+ Plugins.oSimpleHooks[sName] = [];
+ }
+
+ Plugins.oSimpleHooks[sName].push(fCallback);
}
- }, this);
+ };
- this.testingImapErrorDesc = ko.observable('');
- this.testingSmtpErrorDesc = ko.observable('');
+ /**
+ * @param {string} sName
+ * @param {Array=} aArguments
+ */
+ Plugins.runHook = function (sName, aArguments)
+ {
+ if (Utils.isArray(Plugins.oSimpleHooks[sName]))
+ {
+ aArguments = aArguments || [];
- this.imapServerFocus = ko.observable(false);
- this.smtpServerFocus = ko.observable(false);
+ _.each(Plugins.oSimpleHooks[sName], function (fCallback) {
+ fCallback.apply(null, aArguments);
+ });
+ }
+ };
- this.name = ko.observable('');
- this.name.focused = ko.observable(false);
+ /**
+ * @param {string} sName
+ * @return {?}
+ */
+ Plugins.mainSettingsGet = function (sName)
+ {
+ if (Plugins.__boot)
+ {
+ return Plugins.__boot.settingsGet(sName);
+ }
- this.imapServer = ko.observable('');
- this.imapPort = ko.observable('' + Consts.Values.ImapDefaulPort);
- this.imapSecure = ko.observable(Enums.ServerSecure.None);
- this.imapShortLogin = ko.observable(false);
- this.smtpServer = ko.observable('');
- this.smtpPort = ko.observable('' + Consts.Values.SmtpDefaulPort);
- this.smtpSecure = ko.observable(Enums.ServerSecure.None);
- this.smtpShortLogin = ko.observable(false);
- this.smtpAuth = ko.observable(true);
- this.whiteList = ko.observable('');
+ return null;
+ };
- this.headerText = ko.computed(function () {
- var sName = this.name();
- return this.edit() ? 'Edit Domain "' + sName + '"' :
- 'Add Domain' + ('' === sName ? '' : ' "' + sName + '"');
- }, this);
+ /**
+ * @param {Function} fCallback
+ * @param {string} sAction
+ * @param {Object=} oParameters
+ * @param {?number=} iTimeout
+ * @param {string=} sGetAdd = ''
+ * @param {Array=} aAbortActions = []
+ */
+ Plugins.remoteRequest = function (fCallback, sAction, oParameters, iTimeout, sGetAdd, aAbortActions)
+ {
+ if (Plugins.__remote)
+ {
+ Plugins.__remote.defaultRequest(fCallback, sAction, oParameters, iTimeout, sGetAdd, aAbortActions);
+ }
+ };
- this.domainIsComputed = ko.computed(function () {
- return '' !== this.name() &&
- '' !== this.imapServer() &&
- '' !== this.imapPort() &&
- '' !== this.smtpServer() &&
- '' !== this.smtpPort();
- }, this);
+ /**
+ * @param {string} sPluginSection
+ * @param {string} sName
+ * @return {?}
+ */
+ Plugins.settingsGet = function (sPluginSection, sName)
+ {
+ var oPlugin = Plugins.mainSettingsGet('Plugins');
+ oPlugin = oPlugin && Utils.isUnd(oPlugin[sPluginSection]) ? null : oPlugin[sPluginSection];
+ return oPlugin ? (Utils.isUnd(oPlugin[sName]) ? null : oPlugin[sName]) : null;
+ };
- this.canBeTested = ko.computed(function () {
- return !this.testing() && this.domainIsComputed();
- }, this);
+ module.exports = Plugins;
- this.canBeSaved = ko.computed(function () {
- return !this.saving() && this.domainIsComputed();
- }, this);
+}(module));
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
- this.createOrAddCommand = Utils.createCommand(this, function () {
- this.saving(true);
- RL.remote().createOrUpdateDomain(
- _.bind(this.onDomainCreateOrSaveResponse, this),
- !this.edit(),
- this.name(),
- this.imapServer(),
- Utils.pInt(this.imapPort()),
- this.imapSecure(),
- this.imapShortLogin(),
- this.smtpServer(),
- Utils.pInt(this.smtpPort()),
- this.smtpSecure(),
- this.smtpShortLogin(),
- this.smtpAuth(),
- this.whiteList()
- );
- }, this.canBeSaved);
+(function (module) {
- this.testConnectionCommand = Utils.createCommand(this, function () {
+ 'use strict';
+
+ var
+ $ = require('../../External/jquery.js'),
+ JSON = require('../../External/JSON.js'),
+ Consts = require('../../Common/Consts.js'),
+ Utils = require('../../Common/Utils.js')
+ ;
+
+ /**
+ * @constructor
+ */
+ function CookieDriver()
+ {
+
+ }
+
+ CookieDriver.supported = function ()
+ {
+ return true;
+ };
+
+ /**
+ * @param {string} sKey
+ * @param {*} mData
+ * @returns {boolean}
+ */
+ CookieDriver.prototype.set = function (sKey, mData)
+ {
+ var
+ mCokieValue = $.cookie(Consts.Values.ClientSideCookieIndexName),
+ bResult = false,
+ mResult = null
+ ;
+
+ try
+ {
+ mResult = null === mCokieValue ? null : JSON.parse(mCokieValue);
+ if (!mResult)
+ {
+ mResult = {};
+ }
+
+ mResult[sKey] = mData;
+ $.cookie(Consts.Values.ClientSideCookieIndexName, JSON.stringify(mResult), {
+ 'expires': 30
+ });
+
+ bResult = true;
+ }
+ catch (oException) {}
+
+ return bResult;
+ };
+
+ /**
+ * @param {string} sKey
+ * @returns {*}
+ */
+ CookieDriver.prototype.get = function (sKey)
+ {
+ var
+ mCokieValue = $.cookie(Consts.Values.ClientSideCookieIndexName),
+ mResult = null
+ ;
+
+ try
+ {
+ mResult = null === mCokieValue ? null : JSON.parse(mCokieValue);
+ if (mResult && !Utils.isUnd(mResult[sKey]))
+ {
+ mResult = mResult[sKey];
+ }
+ else
+ {
+ mResult = null;
+ }
+ }
+ catch (oException) {}
+
+ return mResult;
+ };
+
+ module.exports = CookieDriver;
+
+}(module));
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ window = require('../../External/window.js'),
+ JSON = require('../../External/JSON.js'),
+ Consts = require('../../Common/Consts.js'),
+ Utils = require('../../Common/Utils.js')
+ ;
+
+ /**
+ * @constructor
+ */
+ function LocalStorageDriver()
+ {
+ }
+
+ LocalStorageDriver.supported = function ()
+ {
+ return !!window.localStorage;
+ };
+
+ /**
+ * @param {string} sKey
+ * @param {*} mData
+ * @returns {boolean}
+ */
+ LocalStorageDriver.prototype.set = function (sKey, mData)
+ {
+ var
+ mCookieValue = window.localStorage[Consts.Values.ClientSideCookieIndexName] || null,
+ bResult = false,
+ mResult = null
+ ;
+
+ try
+ {
+ mResult = null === mCookieValue ? null : JSON.parse(mCookieValue);
+ if (!mResult)
+ {
+ mResult = {};
+ }
+
+ mResult[sKey] = mData;
+ window.localStorage[Consts.Values.ClientSideCookieIndexName] = JSON.stringify(mResult);
+
+ bResult = true;
+ }
+ catch (oException) {}
+
+ return bResult;
+ };
+
+ /**
+ * @param {string} sKey
+ * @returns {*}
+ */
+ LocalStorageDriver.prototype.get = function (sKey)
+ {
+ var
+ mCokieValue = window.localStorage[Consts.Values.ClientSideCookieIndexName] || null,
+ mResult = null
+ ;
+
+ try
+ {
+ mResult = null === mCokieValue ? null : JSON.parse(mCokieValue);
+ if (mResult && !Utils.isUnd(mResult[sKey]))
+ {
+ mResult = mResult[sKey];
+ }
+ else
+ {
+ mResult = null;
+ }
+ }
+ catch (oException) {}
+
+ return mResult;
+ };
+
+ module.exports = LocalStorageDriver;
+
+}(module));
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ _ = require('../External/underscore.js'),
+ CookieDriver = require('./LocalStorages/CookieDriver.js'),
+ LocalStorageDriver = require('./LocalStorages/LocalStorageDriver.js')
+ ;
+
+ /**
+ * @constructor
+ */
+ function LocalStorage()
+ {
+ var
+ NextStorageDriver = _.find([LocalStorageDriver, CookieDriver], function (NextStorageDriver) {
+ return NextStorageDriver.supported();
+ })
+ ;
+
+ if (NextStorageDriver)
+ {
+ NextStorageDriver = /** @type {?Function} */ NextStorageDriver;
+ this.oDriver = new NextStorageDriver();
+ }
+ }
+
+ LocalStorage.prototype.oDriver = null;
+
+ /**
+ * @param {number} iKey
+ * @param {*} mData
+ * @return {boolean}
+ */
+ LocalStorage.prototype.set = function (iKey, mData)
+ {
+ return this.oDriver ? this.oDriver.set('p' + iKey, mData) : false;
+ };
+
+ /**
+ * @param {number} iKey
+ * @return {*}
+ */
+ LocalStorage.prototype.get = function (iKey)
+ {
+ return this.oDriver ? this.oDriver.get('p' + iKey) : null;
+ };
+
+ module.exports = new LocalStorage();
+
+}(module));
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ window = require('../External/window.js'),
+ $ = require('../External/jquery.js'),
+ _ = require('../External/underscore.js'),
+ ko = require('../External/ko.js'),
+ hasher = require('../External/hasher.js'),
+ crossroads = require('../External/crossroads.js'),
+ $window = require('../External/$window.js'),
+ $html = require('../External/$html.js'),
+
+ Globals = require('../Common/Globals.js'),
+ Plugins = require('../Common/Plugins.js'),
+ Utils = require('../Common/Utils.js'),
+
+ RL = require('../RL.js'),
+
+ KnoinAbstractViewModel = require('../Knoin/KnoinAbstractViewModel.js')
+ ;
+
+ /**
+ * @constructor
+ */
+ function Knoin()
+ {
+ this.sDefaultScreenName = '';
+ this.oScreens = {};
+ this.oBoot = null;
+ this.oRemote = null;
+ this.oData = null;
+ this.oCurrentScreen = null;
+ }
+
+ /**
+ * @param {Object} thisObject
+ */
+ Knoin.constructorEnd = function (thisObject)
+ {
+ if (Utils.isFunc(thisObject['__constructor_end']))
+ {
+ thisObject['__constructor_end'].call(thisObject);
+ }
+ };
+
+ Knoin.prototype.sDefaultScreenName = '';
+ Knoin.prototype.oScreens = {};
+ Knoin.prototype.oBoot = null;
+ Knoin.prototype.oRemote = null;
+ Knoin.prototype.oData = null;
+ Knoin.prototype.oCurrentScreen = null;
+
+ Knoin.prototype.hideLoading = function ()
+ {
+ $('#rl-loading').hide();
+ };
+
+ Knoin.prototype.rl = function ()
+ {
+ return this.oBoot;
+ };
+
+ Knoin.prototype.remote = function ()
+ {
+ return this.oRemote;
+ };
+
+ Knoin.prototype.data = function ()
+ {
+ return this.oData;
+ };
+
+ /**
+ * @param {Object} thisObject
+ */
+ Knoin.prototype.constructorEnd = function (thisObject)
+ {
+ if (Utils.isFunc(thisObject['__constructor_end']))
+ {
+ thisObject['__constructor_end'].call(thisObject);
+ }
+ };
+
+ /**
+ * @param {string} sName
+ * @param {Function} ViewModelClass
+ * @param {Function=} AbstractViewModel = KnoinAbstractViewModel
+ */
+ Knoin.prototype.extendAsViewModel = function (sName, ViewModelClass, AbstractViewModel)
+ {
+ if (ViewModelClass)
+ {
+ if (!AbstractViewModel)
+ {
+ AbstractViewModel = KnoinAbstractViewModel;
+ }
+
+ ViewModelClass.__name = sName;
+ Plugins.regViewModelHook(sName, ViewModelClass);
+ _.extend(ViewModelClass.prototype, AbstractViewModel.prototype);
+ }
+ };
+
+ /**
+ * @param {Function} SettingsViewModelClass
+ * @param {string} sLabelName
+ * @param {string} sTemplate
+ * @param {string} sRoute
+ * @param {boolean=} bDefault
+ */
+ Knoin.prototype.addSettingsViewModel = function (SettingsViewModelClass, sTemplate, sLabelName, sRoute, bDefault)
+ {
+ SettingsViewModelClass.__rlSettingsData = {
+ 'Label': sLabelName,
+ 'Template': sTemplate,
+ 'Route': sRoute,
+ 'IsDefault': !!bDefault
+ };
+
+ Globals.aViewModels['settings'].push(SettingsViewModelClass);
+ };
+
+ /**
+ * @param {Function} SettingsViewModelClass
+ */
+ Knoin.prototype.removeSettingsViewModel = function (SettingsViewModelClass)
+ {
+ Globals.aViewModels['settings-removed'].push(SettingsViewModelClass);
+ };
+
+ /**
+ * @param {Function} SettingsViewModelClass
+ */
+ Knoin.prototype.disableSettingsViewModel = function (SettingsViewModelClass)
+ {
+ Globals.aViewModels['settings-disabled'].push(SettingsViewModelClass);
+ };
+
+ Knoin.prototype.routeOff = function ()
+ {
+ hasher.changed.active = false;
+ };
+
+ Knoin.prototype.routeOn = function ()
+ {
+ hasher.changed.active = true;
+ };
+
+ /**
+ * @param {string} sScreenName
+ * @return {?Object}
+ */
+ Knoin.prototype.screen = function (sScreenName)
+ {
+ return ('' !== sScreenName && !Utils.isUnd(this.oScreens[sScreenName])) ? this.oScreens[sScreenName] : null;
+ };
+
+ /**
+ * @param {Function} ViewModelClass
+ * @param {Object=} oScreen
+ */
+ Knoin.prototype.buildViewModel = function (ViewModelClass, oScreen)
+ {
+ if (ViewModelClass && !ViewModelClass.__builded)
+ {
+ var
+ kn = this,
+ oViewModel = new ViewModelClass(oScreen),
+ sPosition = oViewModel.viewModelPosition(),
+ oViewModelPlace = $('#rl-content #rl-' + sPosition.toLowerCase()),
+ oViewModelDom = null
+ ;
+
+ ViewModelClass.__builded = true;
+ ViewModelClass.__vm = oViewModel;
+
+ oViewModel.viewModelName = ViewModelClass.__name;
+
+ if (oViewModelPlace && 1 === oViewModelPlace.length)
+ {
+ oViewModelDom = $('').addClass('rl-view-model').addClass('RL-' + oViewModel.viewModelTemplate()).hide();
+ oViewModelDom.appendTo(oViewModelPlace);
+
+ oViewModel.viewModelDom = oViewModelDom;
+ ViewModelClass.__dom = oViewModelDom;
+
+ if ('Popups' === sPosition)
+ {
+ oViewModel.cancelCommand = oViewModel.closeCommand = Utils.createCommand(oViewModel, function () {
+ kn.hideScreenPopup(ViewModelClass);
+ });
+
+ oViewModel.modalVisibility.subscribe(function (bValue) {
+
+ var self = this;
+ if (bValue)
+ {
+ this.viewModelDom.show();
+ this.storeAndSetKeyScope(kn.data());
+
+ RL.popupVisibilityNames.push(this.viewModelName); // TODO cjs
+ oViewModel.viewModelDom.css('z-index', 3000 + RL.popupVisibilityNames().length + 10); // TODO cjs
+
+ Utils.delegateRun(this, 'onFocus', [], 500);
+ }
+ else
+ {
+ Utils.delegateRun(this, 'onHide');
+ this.restoreKeyScope(kn.data());
+
+ RL.popupVisibilityNames.remove(this.viewModelName); // TODO cjs
+ oViewModel.viewModelDom.css('z-index', 2000);
+
+ Globals.tooltipTrigger(!Globals.tooltipTrigger());
+
+ _.delay(function () {
+ self.viewModelDom.hide();
+ }, 300);
+ }
+
+ }, oViewModel);
+ }
+
+ Plugins.runHook('view-model-pre-build', [ViewModelClass.__name, oViewModel, oViewModelDom]); // TODO cjs
+
+ ko.applyBindingAccessorsToNode(oViewModelDom[0], {
+ 'i18nInit': true,
+ 'template': function () { return {'name': oViewModel.viewModelTemplate()};}
+ }, oViewModel);
+
+ Utils.delegateRun(oViewModel, 'onBuild', [oViewModelDom]);
+ if (oViewModel && 'Popups' === sPosition)
+ {
+ oViewModel.registerPopupKeyDown();
+ }
+
+ Plugins.runHook('view-model-post-build', [ViewModelClass.__name, oViewModel, oViewModelDom]); // TODO cjs
+ }
+ else
+ {
+ Utils.log('Cannot find view model position: ' + sPosition);
+ }
+ }
+
+ return ViewModelClass ? ViewModelClass.__vm : null;
+ };
+
+ /**
+ * @param {Object} oViewModel
+ * @param {Object} oViewModelDom
+ */
+ Knoin.prototype.applyExternal = function (oViewModel, oViewModelDom)
+ {
+ if (oViewModel && oViewModelDom)
+ {
+ ko.applyBindings(oViewModel, oViewModelDom);
+ }
+ };
+
+ /**
+ * @param {Function} ViewModelClassToHide
+ */
+ Knoin.prototype.hideScreenPopup = function (ViewModelClassToHide)
+ {
+ if (ViewModelClassToHide && ViewModelClassToHide.__vm && ViewModelClassToHide.__dom)
+ {
+ ViewModelClassToHide.__vm.modalVisibility(false);
+ Plugins.runHook('view-model-on-hide', [ViewModelClassToHide.__name, ViewModelClassToHide.__vm]); // TODO cjs
+ }
+ };
+
+ /**
+ * @param {Function} ViewModelClassToShow
+ * @param {Array=} aParameters
+ */
+ Knoin.prototype.showScreenPopup = function (ViewModelClassToShow, aParameters)
+ {
+ if (ViewModelClassToShow)
+ {
+ this.buildViewModel(ViewModelClassToShow);
+
+ if (ViewModelClassToShow.__vm && ViewModelClassToShow.__dom)
+ {
+ ViewModelClassToShow.__vm.modalVisibility(true);
+ Utils.delegateRun(ViewModelClassToShow.__vm, 'onShow', aParameters || []);
+ Plugins.runHook('view-model-on-show', [ViewModelClassToShow.__name, ViewModelClassToShow.__vm, aParameters || []]); // TODO cjs
+ }
+ }
+ };
+
+ /**
+ * @param {Function} ViewModelClassToShow
+ * @return {boolean}
+ */
+ Knoin.prototype.isPopupVisible = function (ViewModelClassToShow)
+ {
+ return ViewModelClassToShow && ViewModelClassToShow.__vm ? ViewModelClassToShow.__vm.modalVisibility() : false;
+ };
+
+ /**
+ * @param {string} sScreenName
+ * @param {string} sSubPart
+ */
+ Knoin.prototype.screenOnRoute = function (sScreenName, sSubPart)
+ {
+ var
+ self = this,
+ oScreen = null,
+ oCross = null
+ ;
+
+ if ('' === Utils.pString(sScreenName))
+ {
+ sScreenName = this.sDefaultScreenName;
+ }
+
+ if ('' !== sScreenName)
+ {
+ oScreen = this.screen(sScreenName);
+ if (!oScreen)
+ {
+ oScreen = this.screen(this.sDefaultScreenName);
+ if (oScreen)
+ {
+ sSubPart = sScreenName + '/' + sSubPart;
+ sScreenName = this.sDefaultScreenName;
+ }
+ }
+
+ if (oScreen && oScreen.__started)
+ {
+ if (!oScreen.__builded)
+ {
+ oScreen.__builded = true;
+
+ if (Utils.isNonEmptyArray(oScreen.viewModels()))
+ {
+ _.each(oScreen.viewModels(), function (ViewModelClass) {
+ this.buildViewModel(ViewModelClass, oScreen);
+ }, this);
+ }
+
+ Utils.delegateRun(oScreen, 'onBuild');
+ }
+
+ _.defer(function () {
+
+ // hide screen
+ if (self.oCurrentScreen)
+ {
+ Utils.delegateRun(self.oCurrentScreen, 'onHide');
+
+ if (Utils.isNonEmptyArray(self.oCurrentScreen.viewModels()))
+ {
+ _.each(self.oCurrentScreen.viewModels(), function (ViewModelClass) {
+
+ if (ViewModelClass.__vm && ViewModelClass.__dom &&
+ 'Popups' !== ViewModelClass.__vm.viewModelPosition())
+ {
+ ViewModelClass.__dom.hide();
+ ViewModelClass.__vm.viewModelVisibility(false);
+ Utils.delegateRun(ViewModelClass.__vm, 'onHide');
+ }
+
+ });
+ }
+ }
+ // --
+
+ self.oCurrentScreen = oScreen;
+
+ // show screen
+ if (self.oCurrentScreen)
+ {
+ Utils.delegateRun(self.oCurrentScreen, 'onShow');
+
+ Plugins.runHook('screen-on-show', [self.oCurrentScreen.screenName(), self.oCurrentScreen]); // TODO cjs
+
+ if (Utils.isNonEmptyArray(self.oCurrentScreen.viewModels()))
+ {
+ _.each(self.oCurrentScreen.viewModels(), function (ViewModelClass) {
+
+ if (ViewModelClass.__vm && ViewModelClass.__dom &&
+ 'Popups' !== ViewModelClass.__vm.viewModelPosition())
+ {
+ ViewModelClass.__dom.show();
+ ViewModelClass.__vm.viewModelVisibility(true);
+ Utils.delegateRun(ViewModelClass.__vm, 'onShow');
+ Utils.delegateRun(ViewModelClass.__vm, 'onFocus', [], 200);
+
+ Plugins.runHook('view-model-on-show', [ViewModelClass.__name, ViewModelClass.__vm]); // TODO cjs
+ }
+
+ }, self);
+ }
+ }
+ // --
+
+ oCross = oScreen.__cross();
+ if (oCross)
+ {
+ oCross.parse(sSubPart);
+ }
+ });
+ }
+ }
+ };
+
+ /**
+ * @param {Array} aScreensClasses
+ */
+ Knoin.prototype.startScreens = function (aScreensClasses)
+ {
+ $('#rl-content').css({
+ 'visibility': 'hidden'
+ });
+
+ _.each(aScreensClasses, function (CScreen) {
+
+ var
+ oScreen = new CScreen(),
+ sScreenName = oScreen ? oScreen.screenName() : ''
+ ;
+
+ if (oScreen && '' !== sScreenName)
+ {
+ if ('' === this.sDefaultScreenName)
+ {
+ this.sDefaultScreenName = sScreenName;
+ }
+
+ this.oScreens[sScreenName] = oScreen;
+ }
+
+ }, this);
+
+
+ _.each(this.oScreens, function (oScreen) {
+ if (oScreen && !oScreen.__started && oScreen.__start)
+ {
+ oScreen.__started = true;
+ oScreen.__start();
+
+ Plugins.runHook('screen-pre-start', [oScreen.screenName(), oScreen]); // TODO cjs
+ Utils.delegateRun(oScreen, 'onStart');
+ Plugins.runHook('screen-post-start', [oScreen.screenName(), oScreen]); // TODO cjs
+ }
+ }, this);
+
+ var oCross = crossroads.create();
+ oCross.addRoute(/^([a-zA-Z0-9\-]*)\/?(.*)$/, _.bind(this.screenOnRoute, this));
+
+ hasher.initialized.add(oCross.parse, oCross);
+ hasher.changed.add(oCross.parse, oCross);
+ hasher.init();
+
+ $('#rl-content').css({
+ 'visibility': 'visible'
+ });
+
+ _.delay(function () {
+ $html.removeClass('rl-started-trigger').addClass('rl-started');
+ }, 50);
+ };
+
+ /**
+ * @param {string} sHash
+ * @param {boolean=} bSilence = false
+ * @param {boolean=} bReplace = false
+ */
+ Knoin.prototype.setHash = function (sHash, bSilence, bReplace)
+ {
+ sHash = '#' === sHash.substr(0, 1) ? sHash.substr(1) : sHash;
+ sHash = '/' === sHash.substr(0, 1) ? sHash.substr(1) : sHash;
+
+ bReplace = Utils.isUnd(bReplace) ? false : !!bReplace;
+
+ if (Utils.isUnd(bSilence) ? false : !!bSilence)
+ {
+ hasher.changed.active = false;
+ hasher[bReplace ? 'replaceHash' : 'setHash'](sHash);
+ hasher.changed.active = true;
+ }
+ else
+ {
+ hasher.changed.active = true;
+ hasher[bReplace ? 'replaceHash' : 'setHash'](sHash);
+ hasher.setHash(sHash);
+ }
+ };
+
+ /**
+ * @return {Knoin}
+ */
+ Knoin.prototype.bootstart = function (RL, Remote, Data)
+ {
+ this.oBoot = RL;
+ this.oData = Data;
+ this.oRemote = Remote;
+
+ Plugins.__boot = this.oBoot;
+ Plugins.__data = this.oData;
+ Plugins.__remote = this.oRemote;
+
+ $html.addClass(Globals.bMobileDevice ? 'mobile' : 'no-mobile');
+
+ $window.keydown(Utils.killCtrlAandS).keyup(Utils.killCtrlAandS);
+ $window.unload(function () {
+ Globals.bUnload = true;
+ });
+
+ $html.on('click.dropdown.data-api', function () {
+ Utils.detectDropdownVisibility();
+ });
+
+ // export
+ window['rl'] = window['rl'] || {};
+ window['rl']['addHook'] = Plugins.addHook;
+ window['rl']['settingsGet'] = Plugins.mainSettingsGet;
+ window['rl']['remoteRequest'] = Plugins.remoteRequest;
+ window['rl']['pluginSettingsGet'] = Plugins.settingsGet;
+ window['rl']['addSettingsViewModel'] = _.bind(this.addSettingsViewModel, this);
+ window['rl']['createCommand'] = Utils.createCommand;
+
+ window['rl']['EmailModel'] = require('../Models/EmailModel.js');
+ window['rl']['Enums'] = require('../Common/Enums.js');
+
+ window['__RLBOOT'] = function (fCall) {
+
+ // boot
+ $(function () {
+
+ if (window['rainloopTEMPLATES'] && window['rainloopTEMPLATES'][0])
+ {
+ $('#rl-templates').html(window['rainloopTEMPLATES'][0]);
+
+ _.delay(function () {
+
+ RL.bootstart();
+ $html.removeClass('no-js rl-booted-trigger').addClass('rl-booted');
+
+ }, 50);
+ }
+ else
+ {
+ fCall(false);
+ }
+
+ window['__RLBOOT'] = null;
+ });
+ };
+ };
+
+ module.exports = new Knoin();
+
+}(module));
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ Enums = require('../Common/Enums.js'),
+ Utils = require('../Common/Utils.js')
+ ;
+
+ /**
+ * @param {string=} sEmail
+ * @param {string=} sName
+ *
+ * @constructor
+ */
+ function EmailModel(sEmail, sName)
+ {
+ this.email = sEmail || '';
+ this.name = sName || '';
+ this.privateType = null;
+
+ this.clearDuplicateName();
+ }
+
+ /**
+ * @static
+ * @param {AjaxJsonEmail} oJsonEmail
+ * @return {?EmailModel}
+ */
+ EmailModel.newInstanceFromJson = function (oJsonEmail)
+ {
+ var oEmailModel = new EmailModel();
+ return oEmailModel.initByJson(oJsonEmail) ? oEmailModel : null;
+ };
+
+ /**
+ * @type {string}
+ */
+ EmailModel.prototype.name = '';
+
+ /**
+ * @type {string}
+ */
+ EmailModel.prototype.email = '';
+
+ /**
+ * @type {(number|null)}
+ */
+ EmailModel.prototype.privateType = null;
+
+ EmailModel.prototype.clear = function ()
+ {
+ this.email = '';
+ this.name = '';
+ this.privateType = null;
+ };
+
+ /**
+ * @returns {boolean}
+ */
+ EmailModel.prototype.validate = function ()
+ {
+ return '' !== this.name || '' !== this.email;
+ };
+
+ /**
+ * @param {boolean} bWithoutName = false
+ * @return {string}
+ */
+ EmailModel.prototype.hash = function (bWithoutName)
+ {
+ return '#' + (bWithoutName ? '' : this.name) + '#' + this.email + '#';
+ };
+
+ EmailModel.prototype.clearDuplicateName = function ()
+ {
+ if (this.name === this.email)
+ {
+ this.name = '';
+ }
+ };
+
+ /**
+ * @return {number}
+ */
+ EmailModel.prototype.type = function ()
+ {
+ if (null === this.privateType)
+ {
+ if (this.email && '@facebook.com' === this.email.substr(-13))
+ {
+ this.privateType = Enums.EmailType.Facebook;
+ }
+
+ if (null === this.privateType)
+ {
+ this.privateType = Enums.EmailType.Default;
+ }
+ }
+
+ return this.privateType;
+ };
+
+ /**
+ * @param {string} sQuery
+ * @return {boolean}
+ */
+ EmailModel.prototype.search = function (sQuery)
+ {
+ return -1 < (this.name + ' ' + this.email).toLowerCase().indexOf(sQuery.toLowerCase());
+ };
+
+ /**
+ * @param {string} sString
+ */
+ EmailModel.prototype.parse = function (sString)
+ {
+ this.clear();
+
+ sString = Utils.trim(sString);
+
+ var
+ mRegex = /(?:"([^"]+)")? ?(.*?@[^>,]+)>?,? ?/g,
+ mMatch = mRegex.exec(sString)
+ ;
+
+ if (mMatch)
+ {
+ this.name = mMatch[1] || '';
+ this.email = mMatch[2] || '';
+
+ this.clearDuplicateName();
+ }
+ else if ((/^[^@]+@[^@]+$/).test(sString))
+ {
+ this.name = '';
+ this.email = sString;
+ }
+ };
+
+ /**
+ * @param {AjaxJsonEmail} oJsonEmail
+ * @return {boolean}
+ */
+ EmailModel.prototype.initByJson = function (oJsonEmail)
+ {
+ var bResult = false;
+ if (oJsonEmail && 'Object/Email' === oJsonEmail['@Object'])
+ {
+ this.name = Utils.trim(oJsonEmail.Name);
+ this.email = Utils.trim(oJsonEmail.Email);
+
+ bResult = '' !== this.email;
+ this.clearDuplicateName();
+ }
+
+ return bResult;
+ };
+
+ /**
+ * @param {boolean} bFriendlyView
+ * @param {boolean=} bWrapWithLink = false
+ * @param {boolean=} bEncodeHtml = false
+ * @return {string}
+ */
+ EmailModel.prototype.toLine = function (bFriendlyView, bWrapWithLink, bEncodeHtml)
+ {
+ var sResult = '';
+ if ('' !== this.email)
+ {
+ bWrapWithLink = Utils.isUnd(bWrapWithLink) ? false : !!bWrapWithLink;
+ bEncodeHtml = Utils.isUnd(bEncodeHtml) ? false : !!bEncodeHtml;
+
+ if (bFriendlyView && '' !== this.name)
+ {
+ sResult = bWrapWithLink ? '') +
+ '" target="_blank" tabindex="-1">' + Utils.encodeHtml(this.name) + '' :
+ (bEncodeHtml ? Utils.encodeHtml(this.name) : this.name);
+ }
+ else
+ {
+ sResult = this.email;
+ if ('' !== this.name)
+ {
+ if (bWrapWithLink)
+ {
+ sResult = Utils.encodeHtml('"' + this.name + '" <') +
+ '') + '" target="_blank" tabindex="-1">' + Utils.encodeHtml(sResult) + '' + Utils.encodeHtml('>');
+ }
+ else
+ {
+ sResult = '"' + this.name + '" <' + sResult + '>';
+ if (bEncodeHtml)
+ {
+ sResult = Utils.encodeHtml(sResult);
+ }
+ }
+ }
+ else if (bWrapWithLink)
+ {
+ sResult = '' + Utils.encodeHtml(this.email) + '';
+ }
+ }
+ }
+
+ return sResult;
+ };
+
+ /**
+ * @param {string} $sEmailAddress
+ * @return {boolean}
+ */
+ EmailModel.prototype.mailsoParse = function ($sEmailAddress)
+ {
+ $sEmailAddress = Utils.trim($sEmailAddress);
+ if ('' === $sEmailAddress)
+ {
+ return false;
+ }
+
+ var
+ substr = function (str, start, len) {
+ str += '';
+ var end = str.length;
+
+ if (start < 0) {
+ start += end;
+ }
+
+ end = typeof len === 'undefined' ? end : (len < 0 ? len + end : len + start);
+
+ return start >= str.length || start < 0 || start > end ? false : str.slice(start, end);
+ },
+
+ substr_replace = function (str, replace, start, length) {
+ if (start < 0) {
+ start = start + str.length;
+ }
+ length = length !== undefined ? length : str.length;
+ if (length < 0) {
+ length = length + str.length - start;
+ }
+ return str.slice(0, start) + replace.substr(0, length) + replace.slice(length) + str.slice(start + length);
+ },
+
+ $sName = '',
+ $sEmail = '',
+ $sComment = '',
+
+ $bInName = false,
+ $bInAddress = false,
+ $bInComment = false,
+
+ $aRegs = null,
+
+ $iStartIndex = 0,
+ $iEndIndex = 0,
+ $iCurrentIndex = 0
+ ;
+
+ while ($iCurrentIndex < $sEmailAddress.length)
+ {
+ switch ($sEmailAddress.substr($iCurrentIndex, 1))
+ {
+ case '"':
+ if ((!$bInName) && (!$bInAddress) && (!$bInComment))
+ {
+ $bInName = true;
+ $iStartIndex = $iCurrentIndex;
+ }
+ else if ((!$bInAddress) && (!$bInComment))
+ {
+ $iEndIndex = $iCurrentIndex;
+ $sName = substr($sEmailAddress, $iStartIndex + 1, $iEndIndex - $iStartIndex - 1);
+ $sEmailAddress = substr_replace($sEmailAddress, '', $iStartIndex, $iEndIndex - $iStartIndex + 1);
+ $iEndIndex = 0;
+ $iCurrentIndex = 0;
+ $iStartIndex = 0;
+ $bInName = false;
+ }
+ break;
+ case '<':
+ if ((!$bInName) && (!$bInAddress) && (!$bInComment))
+ {
+ if ($iCurrentIndex > 0 && $sName.length === 0)
+ {
+ $sName = substr($sEmailAddress, 0, $iCurrentIndex);
+ }
+
+ $bInAddress = true;
+ $iStartIndex = $iCurrentIndex;
+ }
+ break;
+ case '>':
+ if ($bInAddress)
+ {
+ $iEndIndex = $iCurrentIndex;
+ $sEmail = substr($sEmailAddress, $iStartIndex + 1, $iEndIndex - $iStartIndex - 1);
+ $sEmailAddress = substr_replace($sEmailAddress, '', $iStartIndex, $iEndIndex - $iStartIndex + 1);
+ $iEndIndex = 0;
+ $iCurrentIndex = 0;
+ $iStartIndex = 0;
+ $bInAddress = false;
+ }
+ break;
+ case '(':
+ if ((!$bInName) && (!$bInAddress) && (!$bInComment))
+ {
+ $bInComment = true;
+ $iStartIndex = $iCurrentIndex;
+ }
+ break;
+ case ')':
+ if ($bInComment)
+ {
+ $iEndIndex = $iCurrentIndex;
+ $sComment = substr($sEmailAddress, $iStartIndex + 1, $iEndIndex - $iStartIndex - 1);
+ $sEmailAddress = substr_replace($sEmailAddress, '', $iStartIndex, $iEndIndex - $iStartIndex + 1);
+ $iEndIndex = 0;
+ $iCurrentIndex = 0;
+ $iStartIndex = 0;
+ $bInComment = false;
+ }
+ break;
+ case '\\':
+ $iCurrentIndex++;
+ break;
+ }
+
+ $iCurrentIndex++;
+ }
+
+ if ($sEmail.length === 0)
+ {
+ $aRegs = $sEmailAddress.match(/[^@\s]+@\S+/i);
+ if ($aRegs && $aRegs[0])
+ {
+ $sEmail = $aRegs[0];
+ }
+ else
+ {
+ $sName = $sEmailAddress;
+ }
+ }
+
+ if ($sEmail.length > 0 && $sName.length === 0 && $sComment.length === 0)
+ {
+ $sName = $sEmailAddress.replace($sEmail, '');
+ }
+
+ $sEmail = Utils.trim($sEmail).replace(/^[<]+/, '').replace(/[>]+$/, '');
+ $sName = Utils.trim($sName).replace(/^["']+/, '').replace(/["']+$/, '');
+ $sComment = Utils.trim($sComment).replace(/^[(]+/, '').replace(/[)]+$/, '');
+
+ // Remove backslash
+ $sName = $sName.replace(/\\\\(.)/, '$1');
+ $sComment = $sComment.replace(/\\\\(.)/, '$1');
+
+ this.name = $sName;
+ this.email = $sEmail;
+
+ this.clearDuplicateName();
+ return true;
+ };
+
+ /**
+ * @return {string}
+ */
+ EmailModel.prototype.inputoTagLine = function ()
+ {
+ return 0 < this.name.length ? this.name + ' (' + this.email + ')' : this.email;
+ };
+
+ module.exports = EmailModel;
+
+}(module));
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ ko = require('../External/ko.js'),
+ Utils = require('../Common/Utils.js')
+ ;
+
+ /**
+ * @constructor
+ */
+ function ContactTagModel()
+ {
+ this.idContactTag = 0;
+ this.name = ko.observable('');
+ this.readOnly = false;
+ }
+
+ ContactTagModel.prototype.parse = function (oItem)
+ {
+ var bResult = false;
+ if (oItem && 'Object/Tag' === oItem['@Object'])
+ {
+ this.idContact = Utils.pInt(oItem['IdContactTag']);
+ this.name(Utils.pString(oItem['Name']));
+ this.readOnly = !!oItem['ReadOnly'];
+
+ bResult = true;
+ }
+
+ return bResult;
+ };
+
+ /**
+ * @param {string} sSearch
+ * @return {boolean}
+ */
+ ContactTagModel.prototype.filterHelper = function (sSearch)
+ {
+ return this.name().toLowerCase().indexOf(sSearch.toLowerCase()) !== -1;
+ };
+
+ /**
+ * @param {boolean=} bEncodeHtml = false
+ * @return {string}
+ */
+ ContactTagModel.prototype.toLine = function (bEncodeHtml)
+ {
+ return (Utils.isUnd(bEncodeHtml) ? false : !!bEncodeHtml) ?
+ Utils.encodeHtml(this.name()) : this.name();
+ };
+
+ module.exports = ContactTagModel;
+
+}(module));
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ _ = require('../../External/underscore.js'),
+ ko = require('../../External/ko.js'),
+
+ Enums = require('../../Common/Enums.js'),
+ Consts = require('../../Common/Consts.js'),
+ Utils = require('../../Common/Utils.js'),
+
+ Remote = require('../../Storages/AdminAjaxRemoteStorage.js'),
+
+ kn = require('../../Knoin/Knoin.js'),
+ KnoinAbstractViewModel = require('../../Knoin/KnoinAbstractViewModel.js')
+ ;
+
+ /**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+ function PopupsDomainViewModel()
+ {
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsDomain');
+
+ this.edit = ko.observable(false);
+ this.saving = ko.observable(false);
+ this.savingError = ko.observable('');
+ this.whiteListPage = ko.observable(false);
+
+ this.testing = ko.observable(false);
+ this.testingDone = ko.observable(false);
+ this.testingImapError = ko.observable(false);
+ this.testingSmtpError = ko.observable(false);
+ this.testingImapErrorDesc = ko.observable('');
+ this.testingSmtpErrorDesc = ko.observable('');
+
+ this.testingImapError.subscribe(function (bValue) {
+ if (!bValue)
+ {
+ this.testingImapErrorDesc('');
+ }
+ }, this);
+
+ this.testingSmtpError.subscribe(function (bValue) {
+ if (!bValue)
+ {
+ this.testingSmtpErrorDesc('');
+ }
+ }, this);
+
+ this.testingImapErrorDesc = ko.observable('');
+ this.testingSmtpErrorDesc = ko.observable('');
+
+ this.imapServerFocus = ko.observable(false);
+ this.smtpServerFocus = ko.observable(false);
+
+ this.name = ko.observable('');
+ this.name.focused = ko.observable(false);
+
+ this.imapServer = ko.observable('');
+ this.imapPort = ko.observable('' + Consts.Values.ImapDefaulPort);
+ this.imapSecure = ko.observable(Enums.ServerSecure.None);
+ this.imapShortLogin = ko.observable(false);
+ this.smtpServer = ko.observable('');
+ this.smtpPort = ko.observable('' + Consts.Values.SmtpDefaulPort);
+ this.smtpSecure = ko.observable(Enums.ServerSecure.None);
+ this.smtpShortLogin = ko.observable(false);
+ this.smtpAuth = ko.observable(true);
+ this.whiteList = ko.observable('');
+
+ this.headerText = ko.computed(function () {
+ var sName = this.name();
+ return this.edit() ? 'Edit Domain "' + sName + '"' :
+ 'Add Domain' + ('' === sName ? '' : ' "' + sName + '"');
+ }, this);
+
+ this.domainIsComputed = ko.computed(function () {
+ return '' !== this.name() &&
+ '' !== this.imapServer() &&
+ '' !== this.imapPort() &&
+ '' !== this.smtpServer() &&
+ '' !== this.smtpPort();
+ }, this);
+
+ this.canBeTested = ko.computed(function () {
+ return !this.testing() && this.domainIsComputed();
+ }, this);
+
+ this.canBeSaved = ko.computed(function () {
+ return !this.saving() && this.domainIsComputed();
+ }, this);
+
+ this.createOrAddCommand = Utils.createCommand(this, function () {
+ this.saving(true);
+ Remote.createOrUpdateDomain(
+ _.bind(this.onDomainCreateOrSaveResponse, this),
+ !this.edit(),
+ this.name(),
+ this.imapServer(),
+ Utils.pInt(this.imapPort()),
+ this.imapSecure(),
+ this.imapShortLogin(),
+ this.smtpServer(),
+ Utils.pInt(this.smtpPort()),
+ this.smtpSecure(),
+ this.smtpShortLogin(),
+ this.smtpAuth(),
+ this.whiteList()
+ );
+ }, this.canBeSaved);
+
+ this.testConnectionCommand = Utils.createCommand(this, function () {
+ this.whiteListPage(false);
+ this.testingDone(false);
+ this.testingImapError(false);
+ this.testingSmtpError(false);
+ this.testing(true);
+ Remote.testConnectionForDomain(
+ _.bind(this.onTestConnectionResponse, this),
+ this.name(),
+ this.imapServer(),
+ Utils.pInt(this.imapPort()),
+ this.imapSecure(),
+ this.smtpServer(),
+ Utils.pInt(this.smtpPort()),
+ this.smtpSecure(),
+ this.smtpAuth()
+ );
+ }, this.canBeTested);
+
+ this.whiteListCommand = Utils.createCommand(this, function () {
+ this.whiteListPage(!this.whiteListPage());
+ });
+
+ // smart form improvements
+ this.imapServerFocus.subscribe(function (bValue) {
+ if (bValue && '' !== this.name() && '' === this.imapServer())
+ {
+ this.imapServer(this.name().replace(/[.]?[*][.]?/g, ''));
+ }
+ }, this);
+
+ this.smtpServerFocus.subscribe(function (bValue) {
+ if (bValue && '' !== this.imapServer() && '' === this.smtpServer())
+ {
+ this.smtpServer(this.imapServer().replace(/imap/ig, 'smtp'));
+ }
+ }, this);
+
+ this.imapSecure.subscribe(function (sValue) {
+ var iPort = Utils.pInt(this.imapPort());
+ sValue = Utils.pString(sValue);
+ switch (sValue)
+ {
+ case '0':
+ if (993 === iPort)
+ {
+ this.imapPort('143');
+ }
+ break;
+ case '1':
+ if (143 === iPort)
+ {
+ this.imapPort('993');
+ }
+ break;
+ }
+ }, this);
+
+ this.smtpSecure.subscribe(function (sValue) {
+ var iPort = Utils.pInt(this.smtpPort());
+ sValue = Utils.pString(sValue);
+ switch (sValue)
+ {
+ case '0':
+ if (465 === iPort || 587 === iPort)
+ {
+ this.smtpPort('25');
+ }
+ break;
+ case '1':
+ if (25 === iPort || 587 === iPort)
+ {
+ this.smtpPort('465');
+ }
+ break;
+ case '2':
+ if (25 === iPort || 465 === iPort)
+ {
+ this.smtpPort('587');
+ }
+ break;
+ }
+ }, this);
+
+ kn.constructorEnd(this);
+ }
+
+ kn.extendAsViewModel('PopupsDomainViewModel', PopupsDomainViewModel);
+
+ PopupsDomainViewModel.prototype.onTestConnectionResponse = function (sResult, oData)
+ {
+ this.testing(false);
+ if (Enums.StorageResultType.Success === sResult && oData.Result)
+ {
+ this.testingDone(true);
+ this.testingImapError(true !== oData.Result.Imap);
+ this.testingSmtpError(true !== oData.Result.Smtp);
+
+ if (this.testingImapError() && oData.Result.Imap)
+ {
+ this.testingImapErrorDesc(oData.Result.Imap);
+ }
+
+ if (this.testingSmtpError() && oData.Result.Smtp)
+ {
+ this.testingSmtpErrorDesc(oData.Result.Smtp);
+ }
+ }
+ else
+ {
+ this.testingImapError(true);
+ this.testingSmtpError(true);
+ }
+ };
+
+ PopupsDomainViewModel.prototype.onDomainCreateOrSaveResponse = function (sResult, oData)
+ {
+ this.saving(false);
+ if (Enums.StorageResultType.Success === sResult && oData)
+ {
+ if (oData.Result)
+ {
+ RL.reloadDomainList();
+ this.closeCommand();
+ }
+ else if (Enums.Notification.DomainAlreadyExists === oData.ErrorCode)
+ {
+ this.savingError('Domain already exists');
+ }
+ }
+ else
+ {
+ this.savingError('Unknown error');
+ }
+ };
+
+ PopupsDomainViewModel.prototype.onHide = function ()
+ {
this.whiteListPage(false);
+ };
+
+ PopupsDomainViewModel.prototype.onShow = function (oDomain)
+ {
+ this.saving(false);
+ this.whiteListPage(false);
+
+ this.testing(false);
this.testingDone(false);
this.testingImapError(false);
this.testingSmtpError(false);
- this.testing(true);
- RL.remote().testConnectionForDomain(
- _.bind(this.onTestConnectionResponse, this),
- this.name(),
- this.imapServer(),
- Utils.pInt(this.imapPort()),
- this.imapSecure(),
- this.smtpServer(),
- Utils.pInt(this.smtpPort()),
- this.smtpSecure(),
- this.smtpAuth()
- );
- }, this.canBeTested);
- this.whiteListCommand = Utils.createCommand(this, function () {
- this.whiteListPage(!this.whiteListPage());
- });
-
- // smart form improvements
- this.imapServerFocus.subscribe(function (bValue) {
- if (bValue && '' !== this.name() && '' === this.imapServer())
+ this.clearForm();
+ if (oDomain)
{
- this.imapServer(this.name().replace(/[.]?[*][.]?/g, ''));
- }
- }, this);
+ this.edit(true);
- this.smtpServerFocus.subscribe(function (bValue) {
- if (bValue && '' !== this.imapServer() && '' === this.smtpServer())
- {
- this.smtpServer(this.imapServer().replace(/imap/ig, 'smtp'));
- }
- }, this);
-
- this.imapSecure.subscribe(function (sValue) {
- var iPort = Utils.pInt(this.imapPort());
- sValue = Utils.pString(sValue);
- switch (sValue)
- {
- case '0':
- if (993 === iPort)
- {
- this.imapPort('143');
- }
- break;
- case '1':
- if (143 === iPort)
- {
- this.imapPort('993');
- }
- break;
- }
- }, this);
-
- this.smtpSecure.subscribe(function (sValue) {
- var iPort = Utils.pInt(this.smtpPort());
- sValue = Utils.pString(sValue);
- switch (sValue)
- {
- case '0':
- if (465 === iPort || 587 === iPort)
- {
- this.smtpPort('25');
- }
- break;
- case '1':
- if (25 === iPort || 587 === iPort)
- {
- this.smtpPort('465');
- }
- break;
- case '2':
- if (25 === iPort || 465 === iPort)
- {
- this.smtpPort('587');
- }
- break;
- }
- }, this);
-
- Knoin.constructorEnd(this);
-}
-
-Utils.extendAsViewModel('PopupsDomainViewModel', PopupsDomainViewModel);
-
-PopupsDomainViewModel.prototype.onTestConnectionResponse = function (sResult, oData)
-{
- this.testing(false);
- if (Enums.StorageResultType.Success === sResult && oData.Result)
- {
- this.testingDone(true);
- this.testingImapError(true !== oData.Result.Imap);
- this.testingSmtpError(true !== oData.Result.Smtp);
-
- if (this.testingImapError() && oData.Result.Imap)
- {
- this.testingImapErrorDesc(oData.Result.Imap);
- }
-
- if (this.testingSmtpError() && oData.Result.Smtp)
- {
- this.testingSmtpErrorDesc(oData.Result.Smtp);
- }
- }
- else
- {
- this.testingImapError(true);
- this.testingSmtpError(true);
- }
-};
-
-PopupsDomainViewModel.prototype.onDomainCreateOrSaveResponse = function (sResult, oData)
-{
- this.saving(false);
- if (Enums.StorageResultType.Success === sResult && oData)
- {
- if (oData.Result)
- {
- RL.reloadDomainList();
- this.closeCommand();
- }
- else if (Enums.Notification.DomainAlreadyExists === oData.ErrorCode)
- {
- this.savingError('Domain already exists');
- }
- }
- else
- {
- this.savingError('Unknown error');
- }
-};
-
-PopupsDomainViewModel.prototype.onHide = function ()
-{
- this.whiteListPage(false);
-};
-
-PopupsDomainViewModel.prototype.onShow = function (oDomain)
-{
- this.saving(false);
- this.whiteListPage(false);
-
- this.testing(false);
- this.testingDone(false);
- this.testingImapError(false);
- this.testingSmtpError(false);
-
- this.clearForm();
- if (oDomain)
- {
- this.edit(true);
-
- this.name(Utils.trim(oDomain.Name));
- this.imapServer(Utils.trim(oDomain.IncHost));
- this.imapPort('' + Utils.pInt(oDomain.IncPort));
- this.imapSecure(Utils.trim(oDomain.IncSecure));
- this.imapShortLogin(!!oDomain.IncShortLogin);
- this.smtpServer(Utils.trim(oDomain.OutHost));
- this.smtpPort('' + Utils.pInt(oDomain.OutPort));
- this.smtpSecure(Utils.trim(oDomain.OutSecure));
- this.smtpShortLogin(!!oDomain.OutShortLogin);
- this.smtpAuth(!!oDomain.OutAuth);
- this.whiteList(Utils.trim(oDomain.WhiteList));
- }
-};
-
-PopupsDomainViewModel.prototype.onFocus = function ()
-{
- if ('' === this.name())
- {
- this.name.focused(true);
- }
-};
-
-PopupsDomainViewModel.prototype.clearForm = function ()
-{
- this.edit(false);
- this.whiteListPage(false);
-
- this.savingError('');
-
- this.name('');
- this.name.focused(false);
-
- this.imapServer('');
- this.imapPort('' + Consts.Values.ImapDefaulPort);
- this.imapSecure(Enums.ServerSecure.None);
- this.imapShortLogin(false);
- this.smtpServer('');
- this.smtpPort('' + Consts.Values.SmtpDefaulPort);
- this.smtpSecure(Enums.ServerSecure.None);
- this.smtpShortLogin(false);
- this.smtpAuth(true);
- this.whiteList('');
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends KnoinAbstractViewModel
- */
-function PopupsPluginViewModel()
-{
- KnoinAbstractViewModel.call(this, 'Popups', 'PopupsPlugin');
-
- var self = this;
-
- this.onPluginSettingsUpdateResponse = _.bind(this.onPluginSettingsUpdateResponse, this);
-
- this.saveError = ko.observable('');
-
- this.name = ko.observable('');
- this.readme = ko.observable('');
-
- this.configures = ko.observableArray([]);
-
- this.hasReadme = ko.computed(function () {
- return '' !== this.readme();
- }, this);
-
- this.hasConfiguration = ko.computed(function () {
- return 0 < this.configures().length;
- }, this);
-
- this.readmePopoverConf = {
- 'placement': 'top',
- 'trigger': 'hover',
- 'title': 'About',
- 'content': function () {
- return self.readme();
+ this.name(Utils.trim(oDomain.Name));
+ this.imapServer(Utils.trim(oDomain.IncHost));
+ this.imapPort('' + Utils.pInt(oDomain.IncPort));
+ this.imapSecure(Utils.trim(oDomain.IncSecure));
+ this.imapShortLogin(!!oDomain.IncShortLogin);
+ this.smtpServer(Utils.trim(oDomain.OutHost));
+ this.smtpPort('' + Utils.pInt(oDomain.OutPort));
+ this.smtpSecure(Utils.trim(oDomain.OutSecure));
+ this.smtpShortLogin(!!oDomain.OutShortLogin);
+ this.smtpAuth(!!oDomain.OutAuth);
+ this.whiteList(Utils.trim(oDomain.WhiteList));
}
};
-
- this.saveCommand = Utils.createCommand(this, function () {
-
- var oList = {};
-
- oList['Name'] = this.name();
-
- _.each(this.configures(), function (oItem) {
-
- var mValue = oItem.value();
- if (false === mValue || true === mValue)
- {
- mValue = mValue ? '1' : '0';
- }
-
- oList['_' + oItem['Name']] = mValue;
-
- }, this);
-
- this.saveError('');
- RL.remote().pluginSettingsUpdate(this.onPluginSettingsUpdateResponse, oList);
-
- }, this.hasConfiguration);
- this.bDisabeCloseOnEsc = true;
- this.sDefaultKeyScope = Enums.KeyState.All;
-
- this.tryToClosePopup = _.debounce(_.bind(this.tryToClosePopup, this), 200);
-
- Knoin.constructorEnd(this);
-}
-
-Utils.extendAsViewModel('PopupsPluginViewModel', PopupsPluginViewModel);
-
-PopupsPluginViewModel.prototype.onPluginSettingsUpdateResponse = function (sResult, oData)
-{
- if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ PopupsDomainViewModel.prototype.onFocus = function ()
{
- this.cancelCommand();
- }
- else
- {
- this.saveError('');
- if (oData && oData.ErrorCode)
+ if ('' === this.name())
{
- this.saveError(Utils.getNotification(oData.ErrorCode));
+ this.name.focused(true);
+ }
+ };
+
+ PopupsDomainViewModel.prototype.clearForm = function ()
+ {
+ this.edit(false);
+ this.whiteListPage(false);
+
+ this.savingError('');
+
+ this.name('');
+ this.name.focused(false);
+
+ this.imapServer('');
+ this.imapPort('' + Consts.Values.ImapDefaulPort);
+ this.imapSecure(Enums.ServerSecure.None);
+ this.imapShortLogin(false);
+ this.smtpServer('');
+ this.smtpPort('' + Consts.Values.SmtpDefaulPort);
+ this.smtpSecure(Enums.ServerSecure.None);
+ this.smtpShortLogin(false);
+ this.smtpAuth(true);
+ this.whiteList('');
+ };
+
+ module.exports = new PopupsDomainViewModel();
+
+}(module));
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ _ = require('../../External/underscore.js'),
+ ko = require('../../External/ko.js'),
+ key = require('../../External/key.js'),
+
+ Enums = require('../../Common/Enums.js'),
+ Utils = require('../../Common/Utils.js'),
+
+ Remote = require('../../Storages/AdminAjaxRemoteStorage.js'),
+
+ kn = require('../../Knoin/Knoin.js'),
+ KnoinAbstractViewModel = require('../../Knoin/KnoinAbstractViewModel.js')
+ ;
+
+ /**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+ function PopupsPluginViewModel()
+ {
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsPlugin');
+
+ var self = this;
+
+ this.onPluginSettingsUpdateResponse = _.bind(this.onPluginSettingsUpdateResponse, this);
+
+ this.saveError = ko.observable('');
+
+ this.name = ko.observable('');
+ this.readme = ko.observable('');
+
+ this.configures = ko.observableArray([]);
+
+ this.hasReadme = ko.computed(function () {
+ return '' !== this.readme();
+ }, this);
+
+ this.hasConfiguration = ko.computed(function () {
+ return 0 < this.configures().length;
+ }, this);
+
+ this.readmePopoverConf = {
+ 'placement': 'top',
+ 'trigger': 'hover',
+ 'title': 'About',
+ 'content': function () {
+ return self.readme();
+ }
+ };
+
+ this.saveCommand = Utils.createCommand(this, function () {
+
+ var oList = {};
+
+ oList['Name'] = this.name();
+
+ _.each(this.configures(), function (oItem) {
+
+ var mValue = oItem.value();
+ if (false === mValue || true === mValue)
+ {
+ mValue = mValue ? '1' : '0';
+ }
+
+ oList['_' + oItem['Name']] = mValue;
+
+ }, this);
+
+ this.saveError('');
+ Remote.pluginSettingsUpdate(this.onPluginSettingsUpdateResponse, oList);
+
+ }, this.hasConfiguration);
+
+ this.bDisabeCloseOnEsc = true;
+ this.sDefaultKeyScope = Enums.KeyState.All;
+
+ this.tryToClosePopup = _.debounce(_.bind(this.tryToClosePopup, this), 200);
+
+ kn.constructorEnd(this);
+ }
+
+ kn.extendAsViewModel('PopupsPluginViewModel', PopupsPluginViewModel);
+
+ PopupsPluginViewModel.prototype.onPluginSettingsUpdateResponse = function (sResult, oData)
+ {
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ {
+ this.cancelCommand();
}
else
{
- this.saveError(Utils.getNotification(Enums.Notification.CantSavePluginSettings));
- }
- }
-};
-
-PopupsPluginViewModel.prototype.onShow = function (oPlugin)
-{
- this.name();
- this.readme();
- this.configures([]);
-
- if (oPlugin)
- {
- this.name(oPlugin['Name']);
- this.readme(oPlugin['Readme']);
-
- var aConfig = oPlugin['Config'];
- if (Utils.isNonEmptyArray(aConfig))
- {
- this.configures(_.map(aConfig, function (aItem) {
- return {
- 'value': ko.observable(aItem[0]),
- 'Name': aItem[1],
- 'Type': aItem[2],
- 'Label': aItem[3],
- 'Default': aItem[4],
- 'Desc': aItem[5]
- };
- }));
- }
- }
-};
-
-PopupsPluginViewModel.prototype.tryToClosePopup = function ()
-{
- var self = this;
- if (!kn.isPopupVisible(PopupsAskViewModel))
- {
- kn.showScreenPopup(PopupsAskViewModel, [Utils.i18n('POPUPS_ASK/DESC_WANT_CLOSE_THIS_WINDOW'), function () {
- if (self.modalVisibility())
+ this.saveError('');
+ if (oData && oData.ErrorCode)
{
- Utils.delegateRun(self, 'cancelCommand');
+ this.saveError(Utils.getNotification(oData.ErrorCode));
+ }
+ else
+ {
+ this.saveError(Utils.getNotification(Enums.Notification.CantSavePluginSettings));
}
- }]);
- }
-};
-
-PopupsPluginViewModel.prototype.onBuild = function ()
-{
- key('esc', Enums.KeyState.All, _.bind(function () {
- if (this.modalVisibility())
- {
- this.tryToClosePopup();
}
- return false;
- }, this));
-};
-
+ };
+
+ PopupsPluginViewModel.prototype.onShow = function (oPlugin)
+ {
+ this.name();
+ this.readme();
+ this.configures([]);
+
+ if (oPlugin)
+ {
+ this.name(oPlugin['Name']);
+ this.readme(oPlugin['Readme']);
+
+ var aConfig = oPlugin['Config'];
+ if (Utils.isNonEmptyArray(aConfig))
+ {
+ this.configures(_.map(aConfig, function (aItem) {
+ return {
+ 'value': ko.observable(aItem[0]),
+ 'Name': aItem[1],
+ 'Type': aItem[2],
+ 'Label': aItem[3],
+ 'Default': aItem[4],
+ 'Desc': aItem[5]
+ };
+ }));
+ }
+ }
+ };
+
+ PopupsPluginViewModel.prototype.tryToClosePopup = function ()
+ {
+ var self = this;
+ if (!kn.isPopupVisible(PopupsAskViewModel))
+ {
+ kn.showScreenPopup(PopupsAskViewModel, [Utils.i18n('POPUPS_ASK/DESC_WANT_CLOSE_THIS_WINDOW'), function () {
+ if (self.modalVisibility())
+ {
+ Utils.delegateRun(self, 'cancelCommand');
+ }
+ }]);
+ }
+ };
+
+ PopupsPluginViewModel.prototype.onBuild = function ()
+ {
+ key('esc', Enums.KeyState.All, _.bind(function () {
+ if (this.modalVisibility())
+ {
+ this.tryToClosePopup();
+ }
+ return false;
+ }, this));
+ };
+
+ module.exports = new PopupsPluginViewModel();
+
+}(module));
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-/**
- * @constructor
- * @extends KnoinAbstractViewModel
- */
-function PopupsActivateViewModel()
-{
- KnoinAbstractViewModel.call(this, 'Popups', 'PopupsActivate');
+(function (module) {
- var self = this;
+ 'use strict';
- this.domain = ko.observable('');
- this.key = ko.observable('');
- this.key.focus = ko.observable(false);
- this.activationSuccessed = ko.observable(false);
+ var
+ ko = require('../../External/ko.js'),
+ Enums = require('../../Common/Enums.js'),
+ Utils = require('../../Common/Utils.js'),
- this.licenseTrigger = RL.data().licenseTrigger;
-
- this.activateProcess = ko.observable(false);
- this.activateText = ko.observable('');
- this.activateText.isError = ko.observable(false);
+ Data = require('../../Storages/AdminDataStorage.js'),
+ Remote = require('../../Storages/AdminAjaxRemoteStorage.js'),
+
+ kn = require('../../Knoin/Knoin.js'),
+ KnoinAbstractViewModel = require('../../Knoin/KnoinAbstractViewModel.js')
+ ;
- this.key.subscribe(function () {
- this.activateText('');
- this.activateText.isError(false);
- }, this);
+ /**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+ function PopupsActivateViewModel()
+ {
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsActivate');
- this.activationSuccessed.subscribe(function (bValue) {
- if (bValue)
- {
- this.licenseTrigger(!this.licenseTrigger());
- }
- }, this);
+ var self = this;
- this.activateCommand = Utils.createCommand(this, function () {
+ this.domain = ko.observable('');
+ this.key = ko.observable('');
+ this.key.focus = ko.observable(false);
+ this.activationSuccessed = ko.observable(false);
- this.activateProcess(true);
- if (this.validateSubscriptionKey())
- {
- RL.remote().licensingActivate(function (sResult, oData) {
+ this.licenseTrigger = Data.licenseTrigger;
- self.activateProcess(false);
- if (Enums.StorageResultType.Success === sResult && oData.Result)
- {
- if (true === oData.Result)
+ this.activateProcess = ko.observable(false);
+ this.activateText = ko.observable('');
+ this.activateText.isError = ko.observable(false);
+
+ this.key.subscribe(function () {
+ this.activateText('');
+ this.activateText.isError(false);
+ }, this);
+
+ this.activationSuccessed.subscribe(function (bValue) {
+ if (bValue)
+ {
+ this.licenseTrigger(!this.licenseTrigger());
+ }
+ }, this);
+
+ this.activateCommand = Utils.createCommand(this, function () {
+
+ this.activateProcess(true);
+ if (this.validateSubscriptionKey())
+ {
+ Remote.licensingActivate(function (sResult, oData) {
+
+ self.activateProcess(false);
+ if (Enums.StorageResultType.Success === sResult && oData.Result)
{
- self.activationSuccessed(true);
- self.activateText('Subscription Key Activated Successfully');
- self.activateText.isError(false);
+ if (true === oData.Result)
+ {
+ self.activationSuccessed(true);
+ self.activateText('Subscription Key Activated Successfully');
+ self.activateText.isError(false);
+ }
+ else
+ {
+ self.activateText(oData.Result);
+ self.activateText.isError(true);
+ self.key.focus(true);
+ }
}
- else
+ else if (oData.ErrorCode)
{
- self.activateText(oData.Result);
+ self.activateText(Utils.getNotification(oData.ErrorCode));
+ self.activateText.isError(true);
+ self.key.focus(true);
+ }
+ else
+ {
+ self.activateText(Utils.getNotification(Enums.Notification.UnknownError));
self.activateText.isError(true);
self.key.focus(true);
}
- }
- else if (oData.ErrorCode)
- {
- self.activateText(Utils.getNotification(oData.ErrorCode));
- self.activateText.isError(true);
- self.key.focus(true);
- }
- else
- {
- self.activateText(Utils.getNotification(Enums.Notification.UnknownError));
- self.activateText.isError(true);
- self.key.focus(true);
- }
- }, this.domain(), this.key());
- }
- else
- {
- this.activateProcess(false);
- this.activateText('Invalid Subscription Key');
- this.activateText.isError(true);
- this.key.focus(true);
- }
-
- }, function () {
- return !this.activateProcess() && '' !== this.domain() && '' !== this.key() && !this.activationSuccessed();
- });
-
- Knoin.constructorEnd(this);
-}
-
-Utils.extendAsViewModel('PopupsActivateViewModel', PopupsActivateViewModel);
-
-PopupsActivateViewModel.prototype.onShow = function ()
-{
- this.domain(RL.settingsGet('AdminDomain'));
- if (!this.activateProcess())
- {
- this.key('');
- this.activateText('');
- this.activateText.isError(false);
- this.activationSuccessed(false);
- }
-};
-
-PopupsActivateViewModel.prototype.onFocus = function ()
-{
- if (!this.activateProcess())
- {
- this.key.focus(true);
- }
-};
-
-/**
- * @returns {boolean}
- */
-PopupsActivateViewModel.prototype.validateSubscriptionKey = function ()
-{
- var sValue = this.key();
- return '' === sValue || !!/^RL[\d]+-[A-Z0-9\-]+Z$/.test(Utils.trim(sValue));
-};
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends KnoinAbstractViewModel
- */
-function PopupsLanguagesViewModel()
-{
- KnoinAbstractViewModel.call(this, 'Popups', 'PopupsLanguages');
-
- this.exp = ko.observable(false);
-
- this.languages = ko.computed(function () {
- return _.map(RL.data().languages(), function (sLanguage) {
- return {
- 'key': sLanguage,
- 'selected': ko.observable(false),
- 'fullName': Utils.convertLangName(sLanguage)
- };
- });
- });
-
- RL.data().mainLanguage.subscribe(function () {
- this.resetMainLanguage();
- }, this);
-
- Knoin.constructorEnd(this);
-}
-
-Utils.extendAsViewModel('PopupsLanguagesViewModel', PopupsLanguagesViewModel);
-
-PopupsLanguagesViewModel.prototype.languageEnName = function (sLanguage)
-{
- return Utils.convertLangName(sLanguage, true);
-};
-
-PopupsLanguagesViewModel.prototype.resetMainLanguage = function ()
-{
- var sCurrent = RL.data().mainLanguage();
- _.each(this.languages(), function (oItem) {
- oItem['selected'](oItem['key'] === sCurrent);
- });
-};
-
-PopupsLanguagesViewModel.prototype.onShow = function ()
-{
- this.exp(true);
-
- this.resetMainLanguage();
-};
-
-PopupsLanguagesViewModel.prototype.onHide = function ()
-{
- this.exp(false);
-};
-
-PopupsLanguagesViewModel.prototype.changeLanguage = function (sLang)
-{
- RL.data().mainLanguage(sLang);
- this.cancelCommand();
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends KnoinAbstractViewModel
- */
-function PopupsAskViewModel()
-{
- KnoinAbstractViewModel.call(this, 'Popups', 'PopupsAsk');
-
- this.askDesc = ko.observable('');
- this.yesButton = ko.observable('');
- this.noButton = ko.observable('');
-
- this.yesFocus = ko.observable(false);
- this.noFocus = ko.observable(false);
-
- this.fYesAction = null;
- this.fNoAction = null;
-
- this.bDisabeCloseOnEsc = true;
- this.sDefaultKeyScope = Enums.KeyState.PopupAsk;
-
- Knoin.constructorEnd(this);
-}
-
-Utils.extendAsViewModel('PopupsAskViewModel', PopupsAskViewModel);
-
-PopupsAskViewModel.prototype.clearPopup = function ()
-{
- this.askDesc('');
- this.yesButton(Utils.i18n('POPUPS_ASK/BUTTON_YES'));
- this.noButton(Utils.i18n('POPUPS_ASK/BUTTON_NO'));
-
- this.yesFocus(false);
- this.noFocus(false);
-
- this.fYesAction = null;
- this.fNoAction = null;
-};
-
-PopupsAskViewModel.prototype.yesClick = function ()
-{
- this.cancelCommand();
-
- if (Utils.isFunc(this.fYesAction))
- {
- this.fYesAction.call(null);
- }
-};
-
-PopupsAskViewModel.prototype.noClick = function ()
-{
- this.cancelCommand();
-
- if (Utils.isFunc(this.fNoAction))
- {
- this.fNoAction.call(null);
- }
-};
-
-/**
- * @param {string} sAskDesc
- * @param {Function=} fYesFunc
- * @param {Function=} fNoFunc
- * @param {string=} sYesButton
- * @param {string=} sNoButton
- */
-PopupsAskViewModel.prototype.onShow = function (sAskDesc, fYesFunc, fNoFunc, sYesButton, sNoButton)
-{
- this.clearPopup();
-
- this.fYesAction = fYesFunc || null;
- this.fNoAction = fNoFunc || null;
-
- this.askDesc(sAskDesc || '');
- if (sYesButton)
- {
- this.yesButton(sYesButton);
- }
-
- if (sYesButton)
- {
- this.yesButton(sNoButton);
- }
-};
-
-PopupsAskViewModel.prototype.onFocus = function ()
-{
- this.yesFocus(true);
-};
-
-PopupsAskViewModel.prototype.onBuild = function ()
-{
- key('tab, shift+tab, right, left', Enums.KeyState.PopupAsk, _.bind(function () {
- if (this.yesFocus())
- {
- this.noFocus(true);
- }
- else
- {
- this.yesFocus(true);
- }
- return false;
- }, this));
-
- key('esc', Enums.KeyState.PopupAsk, _.bind(function () {
- this.noClick();
- return false;
- }, this));
-};
-
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends KnoinAbstractViewModel
- */
-function AdminLoginViewModel()
-{
- KnoinAbstractViewModel.call(this, 'Center', 'AdminLogin');
-
- this.login = ko.observable('');
- this.password = ko.observable('');
-
- this.loginError = ko.observable(false);
- this.passwordError = ko.observable(false);
-
- this.loginFocus = ko.observable(false);
-
- this.login.subscribe(function () {
- this.loginError(false);
- }, this);
-
- this.password.subscribe(function () {
- this.passwordError(false);
- }, this);
-
- this.submitRequest = ko.observable(false);
- this.submitError = ko.observable('');
-
- this.submitCommand = Utils.createCommand(this, function () {
-
- Utils.triggerAutocompleteInputChange();
-
- this.loginError('' === Utils.trim(this.login()));
- this.passwordError('' === Utils.trim(this.password()));
-
- if (this.loginError() || this.passwordError())
- {
- return false;
- }
-
- this.submitRequest(true);
-
- RL.remote().adminLogin(_.bind(function (sResult, oData) {
-
- if (Enums.StorageResultType.Success === sResult && oData && 'AdminLogin' === oData.Action)
- {
- if (oData.Result)
- {
- RL.loginAndLogoutReload();
- }
- else if (oData.ErrorCode)
- {
- this.submitRequest(false);
- this.submitError(Utils.getNotification(oData.ErrorCode));
- }
+ }, this.domain(), this.key());
}
else
{
- this.submitRequest(false);
- this.submitError(Utils.getNotification(Enums.Notification.UnknownError));
+ this.activateProcess(false);
+ this.activateText('Invalid Subscription Key');
+ this.activateText.isError(true);
+ this.key.focus(true);
}
- }, this), this.login(), this.password());
-
- return true;
-
- }, function () {
- return !this.submitRequest();
- });
-
- Knoin.constructorEnd(this);
-}
-
-Utils.extendAsViewModel('AdminLoginViewModel', AdminLoginViewModel);
-
-AdminLoginViewModel.prototype.onShow = function ()
-{
- kn.routeOff();
-
- _.delay(_.bind(function () {
- this.loginFocus(true);
- }, this), 100);
-
-};
-
-AdminLoginViewModel.prototype.onHide = function ()
-{
- this.loginFocus(false);
-};
-
-AdminLoginViewModel.prototype.onBuild = function ()
-{
- Utils.triggerAutocompleteInputChange(true);
-};
-
-AdminLoginViewModel.prototype.submitForm = function ()
-{
- this.submitCommand();
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @param {?} oScreen
- *
- * @constructor
- * @extends KnoinAbstractViewModel
- */
-function AdminMenuViewModel(oScreen)
-{
- KnoinAbstractViewModel.call(this, 'Left', 'AdminMenu');
-
- this.leftPanelDisabled = RL.data().leftPanelDisabled;
-
- this.menu = oScreen.menu;
-
- Knoin.constructorEnd(this);
-}
-
-Utils.extendAsViewModel('AdminMenuViewModel', AdminMenuViewModel);
-
-AdminMenuViewModel.prototype.link = function (sRoute)
-{
- return '#/' + sRoute;
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends KnoinAbstractViewModel
- */
-function AdminPaneViewModel()
-{
- KnoinAbstractViewModel.call(this, 'Right', 'AdminPane');
-
- this.adminDomain = ko.observable(RL.settingsGet('AdminDomain'));
- this.version = ko.observable(RL.settingsGet('Version'));
-
- this.adminManLoadingVisibility = RL.data().adminManLoadingVisibility;
-
- Knoin.constructorEnd(this);
-}
-
-Utils.extendAsViewModel('AdminPaneViewModel', AdminPaneViewModel);
-
-AdminPaneViewModel.prototype.logoutClick = function ()
-{
- RL.remote().adminLogout(function () {
- RL.loginAndLogoutReload();
- });
-};
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function AdminGeneral()
-{
- var oData = RL.data();
-
- this.mainLanguage = oData.mainLanguage;
- this.mainTheme = oData.mainTheme;
-
- this.language = oData.language;
- this.theme = oData.theme;
-
- this.allowLanguagesOnSettings = oData.allowLanguagesOnSettings;
- this.capaThemes = oData.capaThemes;
- this.capaGravatar = oData.capaGravatar;
- this.capaAdditionalAccounts = oData.capaAdditionalAccounts;
- this.capaAdditionalIdentities = oData.capaAdditionalIdentities;
-
- this.mainAttachmentLimit = ko.observable(Utils.pInt(RL.settingsGet('AttachmentLimit')) / (1024 * 1024)).extend({'posInterer': 25});
- this.uploadData = RL.settingsGet('PhpUploadSizes');
- this.uploadDataDesc = this.uploadData && (this.uploadData['upload_max_filesize'] || this.uploadData['post_max_size']) ?
- [
- this.uploadData['upload_max_filesize'] ? 'upload_max_filesize = ' + this.uploadData['upload_max_filesize'] + '; ' : '',
- this.uploadData['post_max_size'] ? 'post_max_size = ' + this.uploadData['post_max_size'] : ''
- ].join('')
- : '';
-
- this.themesOptions = ko.computed(function () {
- return _.map(oData.themes(), function (sTheme) {
- return {
- 'optValue': sTheme,
- 'optText': Utils.convertThemeName(sTheme)
- };
- });
- });
-
- this.mainLanguageFullName = ko.computed(function () {
- return Utils.convertLangName(this.mainLanguage());
- }, this);
-
- this.weakPassword = !!RL.settingsGet('WeakPassword');
-
- this.attachmentLimitTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
- this.languageTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
- this.themeTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
-}
-
-Utils.addSettingsViewModel(AdminGeneral, 'AdminSettingsGeneral', 'General', 'general', true);
-
-AdminGeneral.prototype.onBuild = function ()
-{
- var self = this;
- _.delay(function () {
-
- var
- f1 = Utils.settingsSaveHelperSimpleFunction(self.attachmentLimitTrigger, self),
- f2 = Utils.settingsSaveHelperSimpleFunction(self.languageTrigger, self),
- f3 = Utils.settingsSaveHelperSimpleFunction(self.themeTrigger, self)
- ;
-
- self.mainAttachmentLimit.subscribe(function (sValue) {
- RL.remote().saveAdminConfig(f1, {
- 'AttachmentLimit': Utils.pInt(sValue)
- });
+ }, function () {
+ return !this.activateProcess() && '' !== this.domain() && '' !== this.key() && !this.activationSuccessed();
});
- self.language.subscribe(function (sValue) {
- RL.remote().saveAdminConfig(f2, {
- 'Language': Utils.trim(sValue)
- });
- });
-
- self.theme.subscribe(function (sValue) {
- RL.remote().saveAdminConfig(f3, {
- 'Theme': Utils.trim(sValue)
- });
- });
-
- self.capaAdditionalAccounts.subscribe(function (bValue) {
- RL.remote().saveAdminConfig(null, {
- 'CapaAdditionalAccounts': bValue ? '1' : '0'
- });
- });
-
- self.capaAdditionalIdentities.subscribe(function (bValue) {
- RL.remote().saveAdminConfig(null, {
- 'CapaAdditionalIdentities': bValue ? '1' : '0'
- });
- });
-
- self.capaGravatar.subscribe(function (bValue) {
- RL.remote().saveAdminConfig(null, {
- 'CapaGravatar': bValue ? '1' : '0'
- });
- });
-
- self.capaThemes.subscribe(function (bValue) {
- RL.remote().saveAdminConfig(null, {
- 'CapaThemes': bValue ? '1' : '0'
- });
- });
-
- self.allowLanguagesOnSettings.subscribe(function (bValue) {
- RL.remote().saveAdminConfig(null, {
- 'AllowLanguagesOnSettings': bValue ? '1' : '0'
- });
- });
-
- }, 50);
-};
-
-AdminGeneral.prototype.selectLanguage = function ()
-{
- kn.showScreenPopup(PopupsLanguagesViewModel);
-};
-
-/**
- * @return {string}
- */
-AdminGeneral.prototype.phpInfoLink = function ()
-{
- return RL.link().phpInfo();
-};
-
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function AdminLogin()
-{
- var oData = RL.data();
-
- this.determineUserLanguage = oData.determineUserLanguage;
- this.determineUserDomain = oData.determineUserDomain;
-
- this.defaultDomain = ko.observable(RL.settingsGet('LoginDefaultDomain'));
-
- this.allowLanguagesOnLogin = oData.allowLanguagesOnLogin;
- this.defaultDomainTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
-}
-
-Utils.addSettingsViewModel(AdminLogin, 'AdminSettingsLogin', 'Login', 'login');
-
-AdminLogin.prototype.onBuild = function ()
-{
- var self = this;
- _.delay(function () {
-
- var f1 = Utils.settingsSaveHelperSimpleFunction(self.defaultDomainTrigger, self);
-
- self.determineUserLanguage.subscribe(function (bValue) {
- RL.remote().saveAdminConfig(null, {
- 'DetermineUserLanguage': bValue ? '1' : '0'
- });
- });
-
- self.determineUserDomain.subscribe(function (bValue) {
- RL.remote().saveAdminConfig(null, {
- 'DetermineUserDomain': bValue ? '1' : '0'
- });
- });
-
- self.allowLanguagesOnLogin.subscribe(function (bValue) {
- RL.remote().saveAdminConfig(null, {
- 'AllowLanguagesOnLogin': bValue ? '1' : '0'
- });
- });
-
- self.defaultDomain.subscribe(function (sValue) {
- RL.remote().saveAdminConfig(f1, {
- 'LoginDefaultDomain': Utils.trim(sValue)
- });
- });
-
- }, 50);
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function AdminBranding()
-{
- this.title = ko.observable(RL.settingsGet('Title'));
- this.title.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
-
- this.loadingDesc = ko.observable(RL.settingsGet('LoadingDescription'));
- this.loadingDesc.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
-
- this.loginLogo = ko.observable(RL.settingsGet('LoginLogo'));
- this.loginLogo.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
-
- this.loginDescription = ko.observable(RL.settingsGet('LoginDescription'));
- this.loginDescription.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
-
- this.loginCss = ko.observable(RL.settingsGet('LoginCss'));
- this.loginCss.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
-}
-
-Utils.addSettingsViewModel(AdminBranding, 'AdminSettingsBranding', 'Branding', 'branding');
-
-AdminBranding.prototype.onBuild = function ()
-{
- var self = this;
- _.delay(function () {
-
- var
- f1 = Utils.settingsSaveHelperSimpleFunction(self.title.trigger, self),
- f2 = Utils.settingsSaveHelperSimpleFunction(self.loadingDesc.trigger, self),
- f3 = Utils.settingsSaveHelperSimpleFunction(self.loginLogo.trigger, self),
- f4 = Utils.settingsSaveHelperSimpleFunction(self.loginDescription.trigger, self),
- f5 = Utils.settingsSaveHelperSimpleFunction(self.loginCss.trigger, self)
- ;
-
- self.title.subscribe(function (sValue) {
- RL.remote().saveAdminConfig(f1, {
- 'Title': Utils.trim(sValue)
- });
- });
-
- self.loadingDesc.subscribe(function (sValue) {
- RL.remote().saveAdminConfig(f2, {
- 'LoadingDescription': Utils.trim(sValue)
- });
- });
-
- self.loginLogo.subscribe(function (sValue) {
- RL.remote().saveAdminConfig(f3, {
- 'LoginLogo': Utils.trim(sValue)
- });
- });
-
- self.loginDescription.subscribe(function (sValue) {
- RL.remote().saveAdminConfig(f4, {
- 'LoginDescription': Utils.trim(sValue)
- });
- });
-
- self.loginCss.subscribe(function (sValue) {
- RL.remote().saveAdminConfig(f5, {
- 'LoginCss': Utils.trim(sValue)
- });
- });
-
- }, 50);
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function AdminContacts()
-{
-// var oData = RL.data();
-
- this.defautOptionsAfterRender = Utils.defautOptionsAfterRender;
- this.enableContacts = ko.observable(!!RL.settingsGet('ContactsEnable'));
- this.contactsSharing = ko.observable(!!RL.settingsGet('ContactsSharing'));
- this.contactsSync = ko.observable(!!RL.settingsGet('ContactsSync'));
-
- var
- aTypes = ['sqlite', 'mysql', 'pgsql'],
- aSupportedTypes = [],
- getTypeName = function(sName) {
- switch (sName)
- {
- case 'sqlite':
- sName = 'SQLite';
- break;
- case 'mysql':
- sName = 'MySQL';
- break;
- case 'pgsql':
- sName = 'PostgreSQL';
- break;
- }
-
- return sName;
- }
- ;
-
- if (!!RL.settingsGet('SQLiteIsSupported'))
- {
- aSupportedTypes.push('sqlite');
+ kn.constructorEnd(this);
}
- if (!!RL.settingsGet('MySqlIsSupported'))
+
+ kn.extendAsViewModel('PopupsActivateViewModel', PopupsActivateViewModel);
+
+ PopupsActivateViewModel.prototype.onShow = function ()
{
- aSupportedTypes.push('mysql');
- }
- if (!!RL.settingsGet('PostgreSqlIsSupported'))
- {
- aSupportedTypes.push('pgsql');
- }
-
- this.contactsSupported = 0 < aSupportedTypes.length;
-
- this.contactsTypes = ko.observableArray([]);
- this.contactsTypesOptions = this.contactsTypes.map(function (sValue) {
- var bDisabled = -1 === Utils.inArray(sValue, aSupportedTypes);
- return {
- 'id': sValue,
- 'name': getTypeName(sValue) + (bDisabled ? ' (not supported)' : ''),
- 'disabled': bDisabled
- };
- });
-
- this.contactsTypes(aTypes);
- this.contactsType = ko.observable('');
-
- this.mainContactsType = ko.computed({
- 'owner': this,
- 'read': this.contactsType,
- 'write': function (sValue) {
- if (sValue !== this.contactsType())
- {
- if (-1 < Utils.inArray(sValue, aSupportedTypes))
- {
- this.contactsType(sValue);
- }
- else if (0 < aSupportedTypes.length)
- {
- this.contactsType('');
- }
- }
- else
- {
- this.contactsType.valueHasMutated();
- }
- }
- });
-
- this.contactsType.subscribe(function () {
- this.testContactsSuccess(false);
- this.testContactsError(false);
- this.testContactsErrorMessage('');
- }, this);
-
- this.pdoDsn = ko.observable(RL.settingsGet('ContactsPdoDsn'));
- this.pdoUser = ko.observable(RL.settingsGet('ContactsPdoUser'));
- this.pdoPassword = ko.observable(RL.settingsGet('ContactsPdoPassword'));
-
- this.pdoDsnTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
- this.pdoUserTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
- this.pdoPasswordTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
- this.contactsTypeTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
-
- this.testing = ko.observable(false);
- this.testContactsSuccess = ko.observable(false);
- this.testContactsError = ko.observable(false);
- this.testContactsErrorMessage = ko.observable('');
-
- this.testContactsCommand = Utils.createCommand(this, function () {
-
- this.testContactsSuccess(false);
- this.testContactsError(false);
- this.testContactsErrorMessage('');
- this.testing(true);
-
- RL.remote().testContacts(this.onTestContactsResponse, {
- 'ContactsPdoType': this.contactsType(),
- 'ContactsPdoDsn': this.pdoDsn(),
- 'ContactsPdoUser': this.pdoUser(),
- 'ContactsPdoPassword': this.pdoPassword()
- });
-
- }, function () {
- return '' !== this.pdoDsn() && '' !== this.pdoUser();
- });
-
- this.contactsType(RL.settingsGet('ContactsPdoType'));
-
- this.onTestContactsResponse = _.bind(this.onTestContactsResponse, this);
-}
-
-Utils.addSettingsViewModel(AdminContacts, 'AdminSettingsContacts', 'Contacts', 'contacts');
-
-AdminContacts.prototype.onTestContactsResponse = function (sResult, oData)
-{
- this.testContactsSuccess(false);
- this.testContactsError(false);
- this.testContactsErrorMessage('');
-
- if (Enums.StorageResultType.Success === sResult && oData && oData.Result && oData.Result.Result)
- {
- this.testContactsSuccess(true);
- }
- else
- {
- this.testContactsError(true);
- if (oData && oData.Result)
+ this.domain(RL.settingsGet('AdminDomain'));
+ if (!this.activateProcess())
{
- this.testContactsErrorMessage(oData.Result.Message || '');
- }
- else
- {
- this.testContactsErrorMessage('');
- }
- }
-
- this.testing(false);
-};
-
-AdminContacts.prototype.onShow = function ()
-{
- this.testContactsSuccess(false);
- this.testContactsError(false);
- this.testContactsErrorMessage('');
-};
-
-AdminContacts.prototype.onBuild = function ()
-{
- var self = this;
- _.delay(function () {
-
- var
- f1 = Utils.settingsSaveHelperSimpleFunction(self.pdoDsnTrigger, self),
- f3 = Utils.settingsSaveHelperSimpleFunction(self.pdoUserTrigger, self),
- f4 = Utils.settingsSaveHelperSimpleFunction(self.pdoPasswordTrigger, self),
- f5 = Utils.settingsSaveHelperSimpleFunction(self.contactsTypeTrigger, self)
- ;
-
- self.enableContacts.subscribe(function (bValue) {
- RL.remote().saveAdminConfig(null, {
- 'ContactsEnable': bValue ? '1' : '0'
- });
- });
-
- self.contactsSharing.subscribe(function (bValue) {
- RL.remote().saveAdminConfig(null, {
- 'ContactsSharing': bValue ? '1' : '0'
- });
- });
-
- self.contactsSync.subscribe(function (bValue) {
- RL.remote().saveAdminConfig(null, {
- 'ContactsSync': bValue ? '1' : '0'
- });
- });
-
- self.contactsType.subscribe(function (sValue) {
- RL.remote().saveAdminConfig(f5, {
- 'ContactsPdoType': sValue
- });
- });
-
- self.pdoDsn.subscribe(function (sValue) {
- RL.remote().saveAdminConfig(f1, {
- 'ContactsPdoDsn': Utils.trim(sValue)
- });
- });
-
- self.pdoUser.subscribe(function (sValue) {
- RL.remote().saveAdminConfig(f3, {
- 'ContactsPdoUser': Utils.trim(sValue)
- });
- });
-
- self.pdoPassword.subscribe(function (sValue) {
- RL.remote().saveAdminConfig(f4, {
- 'ContactsPdoPassword': Utils.trim(sValue)
- });
- });
-
- self.contactsType(RL.settingsGet('ContactsPdoType'));
-
- }, 50);
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function AdminDomains()
-{
- var oData = RL.data();
-
- this.domains = oData.domains;
- this.domainsLoading = oData.domainsLoading;
-
- this.iDomainForDeletionTimeout = 0;
-
- this.visibility = ko.computed(function () {
- return oData.domainsLoading() ? 'visible' : 'hidden';
- }, this);
-
- this.domainForDeletion = ko.observable(null).extend({'toggleSubscribe': [this,
- function (oPrev) {
- if (oPrev)
- {
- oPrev.deleteAccess(false);
- }
- }, function (oNext) {
- if (oNext)
- {
- oNext.deleteAccess(true);
- this.startDomainForDeletionTimeout();
- }
- }
- ]});
-}
-
-Utils.addSettingsViewModel(AdminDomains, 'AdminSettingsDomains', 'Domains', 'domains');
-
-AdminDomains.prototype.startDomainForDeletionTimeout = function ()
-{
- var self = this;
- window.clearInterval(this.iDomainForDeletionTimeout);
- this.iDomainForDeletionTimeout = window.setTimeout(function () {
- self.domainForDeletion(null);
- }, 1000 * 3);
-};
-
-AdminDomains.prototype.createDomain = function ()
-{
- kn.showScreenPopup(PopupsDomainViewModel);
-};
-
-AdminDomains.prototype.deleteDomain = function (oDomain)
-{
- this.domains.remove(oDomain);
- RL.remote().domainDelete(_.bind(this.onDomainListChangeRequest, this), oDomain.name);
-};
-
-AdminDomains.prototype.disableDomain = function (oDomain)
-{
- oDomain.disabled(!oDomain.disabled());
- RL.remote().domainDisable(_.bind(this.onDomainListChangeRequest, this), oDomain.name, oDomain.disabled());
-};
-
-AdminDomains.prototype.onBuild = function (oDom)
-{
- var self = this;
- oDom
- .on('click', '.b-admin-domains-list-table .e-item .e-action', function () {
- var oDomainItem = ko.dataFor(this);
- if (oDomainItem)
- {
- RL.remote().domain(_.bind(self.onDomainLoadRequest, self), oDomainItem.name);
- }
- })
- ;
-
- RL.reloadDomainList();
-};
-
-AdminDomains.prototype.onDomainLoadRequest = function (sResult, oData)
-{
- if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
- {
- kn.showScreenPopup(PopupsDomainViewModel, [oData.Result]);
- }
-};
-
-AdminDomains.prototype.onDomainListChangeRequest = function ()
-{
- RL.reloadDomainList();
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function AdminSecurity()
-{
- this.useLocalProxyForExternalImages = RL.data().useLocalProxyForExternalImages;
-
- this.capaOpenPGP = ko.observable(RL.capa(Enums.Capa.OpenPGP));
- this.capaTwoFactorAuth = ko.observable(RL.capa(Enums.Capa.TwoFactor));
-
- this.adminLogin = ko.observable(RL.settingsGet('AdminLogin'));
- this.adminPassword = ko.observable('');
- this.adminPasswordNew = ko.observable('');
- this.adminPasswordNew2 = ko.observable('');
- this.adminPasswordNewError = ko.observable(false);
-
- this.adminPasswordUpdateError = ko.observable(false);
- this.adminPasswordUpdateSuccess = ko.observable(false);
-
- this.adminPassword.subscribe(function () {
- this.adminPasswordUpdateError(false);
- this.adminPasswordUpdateSuccess(false);
- }, this);
-
- this.adminPasswordNew.subscribe(function () {
- this.adminPasswordUpdateError(false);
- this.adminPasswordUpdateSuccess(false);
- this.adminPasswordNewError(false);
- }, this);
-
- this.adminPasswordNew2.subscribe(function () {
- this.adminPasswordUpdateError(false);
- this.adminPasswordUpdateSuccess(false);
- this.adminPasswordNewError(false);
- }, this);
-
- this.saveNewAdminPasswordCommand = Utils.createCommand(this, function () {
-
- if (this.adminPasswordNew() !== this.adminPasswordNew2())
- {
- this.adminPasswordNewError(true);
- return false;
- }
-
- this.adminPasswordUpdateError(false);
- this.adminPasswordUpdateSuccess(false);
-
- RL.remote().saveNewAdminPassword(this.onNewAdminPasswordResponse, {
- 'Password': this.adminPassword(),
- 'NewPassword': this.adminPasswordNew()
- });
-
- }, function () {
- return '' !== this.adminPassword() && '' !== this.adminPasswordNew() && '' !== this.adminPasswordNew2();
- });
-
- this.onNewAdminPasswordResponse = _.bind(this.onNewAdminPasswordResponse, this);
-}
-
-Utils.addSettingsViewModel(AdminSecurity, 'AdminSettingsSecurity', 'Security', 'security');
-
-AdminSecurity.prototype.onNewAdminPasswordResponse = function (sResult, oData)
-{
- if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
- {
- this.adminPassword('');
- this.adminPasswordNew('');
- this.adminPasswordNew2('');
-
- this.adminPasswordUpdateSuccess(true);
- }
- else
- {
- this.adminPasswordUpdateError(true);
- }
-};
-
-AdminSecurity.prototype.onBuild = function ()
-{
- this.capaOpenPGP.subscribe(function (bValue) {
- RL.remote().saveAdminConfig(Utils.emptyFunction, {
- 'CapaOpenPGP': bValue ? '1' : '0'
- });
- });
-
- this.capaTwoFactorAuth.subscribe(function (bValue) {
- RL.remote().saveAdminConfig(Utils.emptyFunction, {
- 'CapaTwoFactorAuth': bValue ? '1' : '0'
- });
- });
-
- this.useLocalProxyForExternalImages.subscribe(function (bValue) {
- RL.remote().saveAdminConfig(null, {
- 'UseLocalProxyForExternalImages': bValue ? '1' : '0'
- });
- });
-};
-
-AdminSecurity.prototype.onHide = function ()
-{
- this.adminPassword('');
- this.adminPasswordNew('');
- this.adminPasswordNew2('');
-};
-
-/**
- * @return {string}
- */
-AdminSecurity.prototype.phpInfoLink = function ()
-{
- return RL.link().phpInfo();
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function AdminSocial()
-{
- var oData = RL.data();
-
- this.googleEnable = oData.googleEnable;
- this.googleClientID = oData.googleClientID;
- this.googleApiKey = oData.googleApiKey;
- this.googleClientSecret = oData.googleClientSecret;
- this.googleTrigger1 = ko.observable(Enums.SaveSettingsStep.Idle);
- this.googleTrigger2 = ko.observable(Enums.SaveSettingsStep.Idle);
- this.googleTrigger3 = ko.observable(Enums.SaveSettingsStep.Idle);
-
- this.facebookSupported = oData.facebookSupported;
- this.facebookEnable = oData.facebookEnable;
- this.facebookAppID = oData.facebookAppID;
- this.facebookAppSecret = oData.facebookAppSecret;
- this.facebookTrigger1 = ko.observable(Enums.SaveSettingsStep.Idle);
- this.facebookTrigger2 = ko.observable(Enums.SaveSettingsStep.Idle);
-
- this.twitterEnable = oData.twitterEnable;
- this.twitterConsumerKey = oData.twitterConsumerKey;
- this.twitterConsumerSecret = oData.twitterConsumerSecret;
- this.twitterTrigger1 = ko.observable(Enums.SaveSettingsStep.Idle);
- this.twitterTrigger2 = ko.observable(Enums.SaveSettingsStep.Idle);
-
- this.dropboxEnable = oData.dropboxEnable;
- this.dropboxApiKey = oData.dropboxApiKey;
- this.dropboxTrigger1 = ko.observable(Enums.SaveSettingsStep.Idle);
-}
-
-Utils.addSettingsViewModel(AdminSocial, 'AdminSettingsSocial', 'Social', 'social');
-
-AdminSocial.prototype.onBuild = function ()
-{
- var self = this;
- _.delay(function () {
-
- var
- f1 = Utils.settingsSaveHelperSimpleFunction(self.facebookTrigger1, self),
- f2 = Utils.settingsSaveHelperSimpleFunction(self.facebookTrigger2, self),
- f3 = Utils.settingsSaveHelperSimpleFunction(self.twitterTrigger1, self),
- f4 = Utils.settingsSaveHelperSimpleFunction(self.twitterTrigger2, self),
- f5 = Utils.settingsSaveHelperSimpleFunction(self.googleTrigger1, self),
- f6 = Utils.settingsSaveHelperSimpleFunction(self.googleTrigger2, self),
- f7 = Utils.settingsSaveHelperSimpleFunction(self.googleTrigger3, self),
- f8 = Utils.settingsSaveHelperSimpleFunction(self.dropboxTrigger1, self)
- ;
-
- self.facebookEnable.subscribe(function (bValue) {
- if (self.facebookSupported())
- {
- RL.remote().saveAdminConfig(Utils.emptyFunction, {
- 'FacebookEnable': bValue ? '1' : '0'
- });
- }
- });
-
- self.facebookAppID.subscribe(function (sValue) {
- if (self.facebookSupported())
- {
- RL.remote().saveAdminConfig(f1, {
- 'FacebookAppID': Utils.trim(sValue)
- });
- }
- });
-
- self.facebookAppSecret.subscribe(function (sValue) {
- if (self.facebookSupported())
- {
- RL.remote().saveAdminConfig(f2, {
- 'FacebookAppSecret': Utils.trim(sValue)
- });
- }
- });
-
- self.twitterEnable.subscribe(function (bValue) {
- RL.remote().saveAdminConfig(Utils.emptyFunction, {
- 'TwitterEnable': bValue ? '1' : '0'
- });
- });
-
- self.twitterConsumerKey.subscribe(function (sValue) {
- RL.remote().saveAdminConfig(f3, {
- 'TwitterConsumerKey': Utils.trim(sValue)
- });
- });
-
- self.twitterConsumerSecret.subscribe(function (sValue) {
- RL.remote().saveAdminConfig(f4, {
- 'TwitterConsumerSecret': Utils.trim(sValue)
- });
- });
-
- self.googleEnable.subscribe(function (bValue) {
- RL.remote().saveAdminConfig(Utils.emptyFunction, {
- 'GoogleEnable': bValue ? '1' : '0'
- });
- });
-
- self.googleClientID.subscribe(function (sValue) {
- RL.remote().saveAdminConfig(f5, {
- 'GoogleClientID': Utils.trim(sValue)
- });
- });
-
- self.googleClientSecret.subscribe(function (sValue) {
- RL.remote().saveAdminConfig(f6, {
- 'GoogleClientSecret': Utils.trim(sValue)
- });
- });
-
- self.googleApiKey.subscribe(function (sValue) {
- RL.remote().saveAdminConfig(f7, {
- 'GoogleApiKey': Utils.trim(sValue)
- });
- });
-
- self.dropboxEnable.subscribe(function (bValue) {
- RL.remote().saveAdminConfig(Utils.emptyFunction, {
- 'DropboxEnable': bValue ? '1' : '0'
- });
- });
-
- self.dropboxApiKey.subscribe(function (sValue) {
- RL.remote().saveAdminConfig(f8, {
- 'DropboxApiKey': Utils.trim(sValue)
- });
- });
-
- }, 50);
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function AdminPlugins()
-{
- var oData = RL.data();
-
- this.enabledPlugins = ko.observable(!!RL.settingsGet('EnabledPlugins'));
-
- this.pluginsError = ko.observable('');
-
- this.plugins = oData.plugins;
- this.pluginsLoading = oData.pluginsLoading;
-
- this.visibility = ko.computed(function () {
- return oData.pluginsLoading() ? 'visible' : 'hidden';
- }, this);
-
- this.onPluginLoadRequest = _.bind(this.onPluginLoadRequest, this);
- this.onPluginDisableRequest = _.bind(this.onPluginDisableRequest, this);
-}
-
-Utils.addSettingsViewModel(AdminPlugins, 'AdminSettingsPlugins', 'Plugins', 'plugins');
-
-AdminPlugins.prototype.disablePlugin = function (oPlugin)
-{
- oPlugin.disabled(!oPlugin.disabled());
- RL.remote().pluginDisable(this.onPluginDisableRequest, oPlugin.name, oPlugin.disabled());
-};
-
-AdminPlugins.prototype.configurePlugin = function (oPlugin)
-{
- RL.remote().plugin(this.onPluginLoadRequest, oPlugin.name);
-};
-
-AdminPlugins.prototype.onBuild = function (oDom)
-{
- var self = this;
-
- oDom
- .on('click', '.e-item .configure-plugin-action', function () {
- var oPlugin = ko.dataFor(this);
- if (oPlugin)
- {
- self.configurePlugin(oPlugin);
- }
- })
- .on('click', '.e-item .disabled-plugin', function () {
- var oPlugin = ko.dataFor(this);
- if (oPlugin)
- {
- self.disablePlugin(oPlugin);
- }
- })
- ;
-
- this.enabledPlugins.subscribe(function (bValue) {
- RL.remote().saveAdminConfig(Utils.emptyFunction, {
- 'EnabledPlugins': bValue ? '1' : '0'
- });
- });
-};
-
-AdminPlugins.prototype.onShow = function ()
-{
- this.pluginsError('');
- RL.reloadPluginList();
-};
-
-AdminPlugins.prototype.onPluginLoadRequest = function (sResult, oData)
-{
- if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
- {
- kn.showScreenPopup(PopupsPluginViewModel, [oData.Result]);
- }
-};
-
-AdminPlugins.prototype.onPluginDisableRequest = function (sResult, oData)
-{
- if (Enums.StorageResultType.Success === sResult && oData)
- {
- if (!oData.Result && oData.ErrorCode)
- {
- if (Enums.Notification.UnsupportedPluginPackage === oData.ErrorCode && oData.ErrorMessage && '' !== oData.ErrorMessage)
- {
- this.pluginsError(oData.ErrorMessage);
- }
- else
- {
- this.pluginsError(Utils.getNotification(oData.ErrorCode));
- }
- }
- }
-
- RL.reloadPluginList();
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function AdminPackages()
-{
- var oData = RL.data();
-
- this.packagesError = ko.observable('');
-
- this.packages = oData.packages;
- this.packagesLoading = oData.packagesLoading;
- this.packagesReal = oData.packagesReal;
- this.packagesMainUpdatable = oData.packagesMainUpdatable;
-
- this.packagesCurrent = this.packages.filter(function (oItem) {
- return oItem && '' !== oItem['installed'] && !oItem['compare'];
- });
-
- this.packagesAvailableForUpdate = this.packages.filter(function (oItem) {
- return oItem && '' !== oItem['installed'] && !!oItem['compare'];
- });
-
- this.packagesAvailableForInstallation = this.packages.filter(function (oItem) {
- return oItem && '' === oItem['installed'];
- });
-
- this.visibility = ko.computed(function () {
- return oData.packagesLoading() ? 'visible' : 'hidden';
- }, this);
-}
-
-Utils.addSettingsViewModel(AdminPackages, 'AdminSettingsPackages', 'Packages', 'packages');
-
-AdminPackages.prototype.onShow = function ()
-{
- this.packagesError('');
-};
-
-AdminPackages.prototype.onBuild = function ()
-{
- RL.reloadPackagesList();
-};
-
-AdminPackages.prototype.requestHelper = function (oPackage, bInstall)
-{
- var self = this;
- return function (sResult, oData) {
-
- if (Enums.StorageResultType.Success !== sResult || !oData || !oData.Result)
- {
- if (oData && oData.ErrorCode)
- {
- self.packagesError(Utils.getNotification(oData.ErrorCode));
- }
- else
- {
- self.packagesError(Utils.getNotification(
- bInstall ? Enums.Notification.CantInstallPackage : Enums.Notification.CantDeletePackage));
- }
- }
-
- _.each(RL.data().packages(), function (oItem) {
- if (oItem && oPackage && oItem['loading']() && oPackage['file'] === oItem['file'])
- {
- oPackage['loading'](false);
- oItem['loading'](false);
- }
- });
-
- if (Enums.StorageResultType.Success === sResult && oData && oData.Result && oData.Result['Reload'])
- {
- window.location.reload();
- }
- else
- {
- RL.reloadPackagesList();
+ this.key('');
+ this.activateText('');
+ this.activateText.isError(false);
+ this.activationSuccessed(false);
}
};
-};
-AdminPackages.prototype.deletePackage = function (oPackage)
-{
- if (oPackage)
+ PopupsActivateViewModel.prototype.onFocus = function ()
{
- oPackage['loading'](true);
- RL.remote().packageDelete(this.requestHelper(oPackage, false), oPackage);
- }
-};
+ if (!this.activateProcess())
+ {
+ this.key.focus(true);
+ }
+ };
-AdminPackages.prototype.installPackage = function (oPackage)
-{
- if (oPackage)
+ /**
+ * @returns {boolean}
+ */
+ PopupsActivateViewModel.prototype.validateSubscriptionKey = function ()
{
- oPackage['loading'](true);
- RL.remote().packageInstall(this.requestHelper(oPackage, true), oPackage);
+ var sValue = this.key();
+ return '' === sValue || !!/^RL[\d]+-[A-Z0-9\-]+Z$/.test(Utils.trim(sValue));
+ };
+
+ module.exports = new PopupsActivateViewModel();
+
+}(module));
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ _ = require('../../External/underscore.js'),
+ ko = require('../../External/ko.js'),
+
+ Utils = require('../../Common/Utils.js'),
+
+ Data = require('../../Storages/WebMailDataStorage.js'),
+
+ kn = require('../../Knoin/Knoin.js'),
+ KnoinAbstractViewModel = require('../../Knoin/KnoinAbstractViewModel.js')
+ ;
+
+ /**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+ function PopupsLanguagesViewModel()
+ {
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsLanguages');
+
+ this.exp = ko.observable(false);
+
+ this.languages = ko.computed(function () {
+ return _.map(Data.languages(), function (sLanguage) {
+ return {
+ 'key': sLanguage,
+ 'selected': ko.observable(false),
+ 'fullName': Utils.convertLangName(sLanguage)
+ };
+ });
+ });
+
+ Data.mainLanguage.subscribe(function () {
+ this.resetMainLanguage();
+ }, this);
+
+ kn.constructorEnd(this);
}
-};
+
+ kn.extendAsViewModel('PopupsLanguagesViewModel', PopupsLanguagesViewModel);
+
+ PopupsLanguagesViewModel.prototype.languageEnName = function (sLanguage)
+ {
+ return Utils.convertLangName(sLanguage, true);
+ };
+
+ PopupsLanguagesViewModel.prototype.resetMainLanguage = function ()
+ {
+ var sCurrent = Data.mainLanguage();
+ _.each(this.languages(), function (oItem) {
+ oItem['selected'](oItem['key'] === sCurrent);
+ });
+ };
+
+ PopupsLanguagesViewModel.prototype.onShow = function ()
+ {
+ this.exp(true);
+
+ this.resetMainLanguage();
+ };
+
+ PopupsLanguagesViewModel.prototype.onHide = function ()
+ {
+ this.exp(false);
+ };
+
+ PopupsLanguagesViewModel.prototype.changeLanguage = function (sLang)
+ {
+ Data.mainLanguage(sLang);
+ this.cancelCommand();
+ };
+
+ module.exports = new PopupsLanguagesViewModel();
+
+}(module));
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ ko = require('../../External/ko.js'),
+ key = require('../../External/key.js'),
+ Enums = require('../../Common/Enums.js'),
+ Utils = require('../../Common/Utils.js'),
+ kn = require('../../Knoin/Knoin.js'),
+ KnoinAbstractViewModel = require('../../Knoin/KnoinAbstractViewModel.js')
+ ;
+
+ /**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+ function PopupsAskViewModel()
+ {
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsAsk');
+
+ this.askDesc = ko.observable('');
+ this.yesButton = ko.observable('');
+ this.noButton = ko.observable('');
+
+ this.yesFocus = ko.observable(false);
+ this.noFocus = ko.observable(false);
+
+ this.fYesAction = null;
+ this.fNoAction = null;
+
+ this.bDisabeCloseOnEsc = true;
+ this.sDefaultKeyScope = Enums.KeyState.PopupAsk;
+
+ kn.constructorEnd(this);
+ }
+
+ kn.extendAsViewModel('PopupsAskViewModel', PopupsAskViewModel);
+
+ PopupsAskViewModel.prototype.clearPopup = function ()
+ {
+ this.askDesc('');
+ this.yesButton(Utils.i18n('POPUPS_ASK/BUTTON_YES'));
+ this.noButton(Utils.i18n('POPUPS_ASK/BUTTON_NO'));
+
+ this.yesFocus(false);
+ this.noFocus(false);
+
+ this.fYesAction = null;
+ this.fNoAction = null;
+ };
+
+ PopupsAskViewModel.prototype.yesClick = function ()
+ {
+ this.cancelCommand();
+
+ if (Utils.isFunc(this.fYesAction))
+ {
+ this.fYesAction.call(null);
+ }
+ };
+
+ PopupsAskViewModel.prototype.noClick = function ()
+ {
+ this.cancelCommand();
+
+ if (Utils.isFunc(this.fNoAction))
+ {
+ this.fNoAction.call(null);
+ }
+ };
+
+ /**
+ * @param {string} sAskDesc
+ * @param {Function=} fYesFunc
+ * @param {Function=} fNoFunc
+ * @param {string=} sYesButton
+ * @param {string=} sNoButton
+ */
+ PopupsAskViewModel.prototype.onShow = function (sAskDesc, fYesFunc, fNoFunc, sYesButton, sNoButton)
+ {
+ this.clearPopup();
+
+ this.fYesAction = fYesFunc || null;
+ this.fNoAction = fNoFunc || null;
+
+ this.askDesc(sAskDesc || '');
+ if (sYesButton)
+ {
+ this.yesButton(sYesButton);
+ }
+
+ if (sYesButton)
+ {
+ this.yesButton(sNoButton);
+ }
+ };
+
+ PopupsAskViewModel.prototype.onFocus = function ()
+ {
+ this.yesFocus(true);
+ };
+
+ PopupsAskViewModel.prototype.onBuild = function ()
+ {
+ key('tab, shift+tab, right, left', Enums.KeyState.PopupAsk, _.bind(function () {
+ if (this.yesFocus())
+ {
+ this.noFocus(true);
+ }
+ else
+ {
+ this.yesFocus(true);
+ }
+ return false;
+ }, this));
+
+ key('esc', Enums.KeyState.PopupAsk, _.bind(function () {
+ this.noClick();
+ return false;
+ }, this));
+ };
+
+ module.exports = new PopupsAskViewModel();
+
+}(module));
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ _ = require('../External/underscore.js'),
+ ko = require('../External/ko.js'),
+
+ Enums = require('../Common/Enums.js'),
+ Utils = require('../Common/Utils.js'),
+
+ Remote = require('../Storages/AdminAjaxRemoteStorage.js'),
+
+ kn = require('../Knoin/Knoin.js'),
+ KnoinAbstractViewModel = require('../Knoin/KnoinAbstractViewModel.js')
+ ;
+
+ /**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+ function AdminLoginViewModel()
+ {
+ KnoinAbstractViewModel.call(this, 'Center', 'AdminLogin');
+
+ this.login = ko.observable('');
+ this.password = ko.observable('');
+
+ this.loginError = ko.observable(false);
+ this.passwordError = ko.observable(false);
+
+ this.loginFocus = ko.observable(false);
+
+ this.login.subscribe(function () {
+ this.loginError(false);
+ }, this);
+
+ this.password.subscribe(function () {
+ this.passwordError(false);
+ }, this);
+
+ this.submitRequest = ko.observable(false);
+ this.submitError = ko.observable('');
+
+ this.submitCommand = Utils.createCommand(this, function () {
+
+ Utils.triggerAutocompleteInputChange();
+
+ this.loginError('' === Utils.trim(this.login()));
+ this.passwordError('' === Utils.trim(this.password()));
+
+ if (this.loginError() || this.passwordError())
+ {
+ return false;
+ }
+
+ this.submitRequest(true);
+
+ Remote.adminLogin(_.bind(function (sResult, oData) {
+
+ if (Enums.StorageResultType.Success === sResult && oData && 'AdminLogin' === oData.Action)
+ {
+ if (oData.Result)
+ {
+ RL.loginAndLogoutReload();
+ }
+ else if (oData.ErrorCode)
+ {
+ this.submitRequest(false);
+ this.submitError(Utils.getNotification(oData.ErrorCode));
+ }
+ }
+ else
+ {
+ this.submitRequest(false);
+ this.submitError(Utils.getNotification(Enums.Notification.UnknownError));
+ }
+
+ }, this), this.login(), this.password());
+
+ return true;
+
+ }, function () {
+ return !this.submitRequest();
+ });
+
+ kn.constructorEnd(this);
+ }
+
+ kn.extendAsViewModel('AdminLoginViewModel', AdminLoginViewModel);
+
+ AdminLoginViewModel.prototype.onShow = function ()
+ {
+ kn.routeOff();
+
+ _.delay(_.bind(function () {
+ this.loginFocus(true);
+ }, this), 100);
+
+ };
+
+ AdminLoginViewModel.prototype.onHide = function ()
+ {
+ this.loginFocus(false);
+ };
+
+ AdminLoginViewModel.prototype.onBuild = function ()
+ {
+ Utils.triggerAutocompleteInputChange(true);
+ };
+
+ AdminLoginViewModel.prototype.submitForm = function ()
+ {
+ this.submitCommand();
+ };
+
+ module.exports = new AdminLoginViewModel();
+
+}(module));
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ kn = require('../Knoin/Knoin.js'),
+ Data = require('../Storages/AdminDataStorage.js'),
+ KnoinAbstractViewModel = require('../Knoin/KnoinAbstractViewModel.js')
+ ;
+
+ /**
+ * @param {?} oScreen
+ *
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+ function AdminMenuViewModel(oScreen)
+ {
+ KnoinAbstractViewModel.call(this, 'Left', 'AdminMenu');
+
+ this.leftPanelDisabled = Data.leftPanelDisabled;
+
+ this.menu = oScreen.menu;
+
+ kn.constructorEnd(this);
+ }
+
+ kn.extendAsViewModel('AdminMenuViewModel', AdminMenuViewModel);
+
+ AdminMenuViewModel.prototype.link = function (sRoute)
+ {
+ return '#/' + sRoute;
+ };
+
+ module.exports = new AdminMenuViewModel();
+
+}(module));
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-/**
- * @constructor
- */
-function AdminLicensing()
-{
- this.licensing = RL.data().licensing;
- this.licensingProcess = RL.data().licensingProcess;
- this.licenseValid = RL.data().licenseValid;
- this.licenseExpired = RL.data().licenseExpired;
- this.licenseError = RL.data().licenseError;
- this.licenseTrigger = RL.data().licenseTrigger;
+(function (module) {
- this.adminDomain = ko.observable('');
- this.subscriptionEnabled = ko.observable(!!RL.settingsGet('SubscriptionEnabled'));
+ 'use strict';
- this.licenseTrigger.subscribe(function () {
- if (this.subscriptionEnabled())
- {
- RL.reloadLicensing(true);
- }
- }, this);
-}
-
-Utils.addSettingsViewModel(AdminLicensing, 'AdminSettingsLicensing', 'Licensing', 'licensing');
-
-AdminLicensing.prototype.onBuild = function ()
-{
- if (this.subscriptionEnabled())
- {
- RL.reloadLicensing(false);
- }
-};
-
-AdminLicensing.prototype.onShow = function ()
-{
- this.adminDomain(RL.settingsGet('AdminDomain'));
-};
-
-AdminLicensing.prototype.showActivationForm = function ()
-{
- kn.showScreenPopup(PopupsActivateViewModel);
-};
-
-/**
- * @returns {string}
- */
-AdminLicensing.prototype.licenseExpiredMomentValue = function ()
-{
var
- iTime = this.licenseExpired(),
- oDate = moment.unix(iTime)
+ ko = require('../External/ko.js'),
+
+ Data = require('../Storages/AdminDataStorage.js'),
+ Remote = require('../Storages/AdminAjaxRemoteStorage.js'),
+
+ RL = require('../RL.js'),
+
+ kn = require('../Knoin/Knoin.js'),
+ KnoinAbstractViewModel = require('../Knoin/KnoinAbstractViewModel.js')
;
- return iTime && 1898625600 === iTime ? 'Never' : (oDate.format('LL') + ' (' + oDate.from(moment()) + ')');
-};
+ /**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+ function AdminPaneViewModel()
+ {
+ KnoinAbstractViewModel.call(this, 'Right', 'AdminPane');
+
+ this.adminDomain = ko.observable(RL().settingsGet('AdminDomain'));
+ this.version = ko.observable(RL().settingsGet('Version'));
+
+ this.adminManLoadingVisibility = Data.adminManLoadingVisibility;
+
+ kn.constructorEnd(this);
+ }
+
+ kn.extendAsViewModel('AdminPaneViewModel', AdminPaneViewModel);
+
+ AdminPaneViewModel.prototype.logoutClick = function ()
+ {
+ Remote.adminLogout(function () {
+ RL().loginAndLogoutReload();
+ });
+ };
+
+ module.exports = new AdminPaneViewModel();
+
+}(module));
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-/**
- * @constructor
- */
-function AdminAbout()
-{
- var oData = RL.data();
+(function (module) {
- this.version = ko.observable(RL.settingsGet('Version'));
- this.access = ko.observable(!!RL.settingsGet('CoreAccess'));
- this.errorDesc = ko.observable('');
+ 'use strict';
- this.coreReal = oData.coreReal;
- this.coreUpdatable = oData.coreUpdatable;
- this.coreAccess = oData.coreAccess;
- this.coreChecking = oData.coreChecking;
- this.coreUpdating = oData.coreUpdating;
- this.coreRemoteVersion = oData.coreRemoteVersion;
- this.coreRemoteRelease = oData.coreRemoteRelease;
- this.coreVersionCompare = oData.coreVersionCompare;
+ var
+ ko = require('../External/ko.js'),
+ key = require('../External/key.js'),
- this.statusType = ko.computed(function () {
+ Enums = require('../Common/Enums.js'),
+ Globals = require('../Common/Globals.js'),
+ Utils = require('../Common/Utils.js'),
+ RL = require('../RL.js')
+ ;
+
+ /**
+ * @constructor
+ */
+ function AbstractData()
+ {
+ var self = this;
+
+ this.leftPanelDisabled = ko.observable(false);
+ this.useKeyboardShortcuts = ko.observable(true);
+
+ this.keyScopeReal = ko.observable(Enums.KeyState.All);
+ this.keyScopeFake = ko.observable(Enums.KeyState.All);
+
+ this.keyScope = ko.computed({
+ 'owner': this,
+ 'read': function () {
+ return this.keyScopeFake();
+ },
+ 'write': function (sValue) {
+
+ if (Enums.KeyState.Menu !== sValue)
+ {
+ if (Enums.KeyState.Compose === sValue)
+ {
+ Utils.disableKeyFilter(self);
+ }
+ else
+ {
+ Utils.restoreKeyFilter(self);
+ }
+
+ this.keyScopeFake(sValue);
+ if (Globals.dropdownVisibility())
+ {
+ sValue = Enums.KeyState.Menu;
+ }
+ }
+
+ this.keyScopeReal(sValue);
+ }
+ });
+
+ this.keyScopeReal.subscribe(function (sValue) {
+ // window.console.log(sValue);
+ key.setScope(sValue);
+ });
+
+ this.leftPanelDisabled.subscribe(function (bValue) {
+ RL().pub('left-panel.' + (bValue ? 'off' : 'on'));
+ });
+
+ Globals.dropdownVisibility.subscribe(function (bValue) {
+ if (bValue)
+ {
+ Globals.tooltipTrigger(!Globals.tooltipTrigger());
+ this.keyScope(Enums.KeyState.Menu);
+ }
+ else if (Enums.KeyState.Menu === key.getScope())
+ {
+ this.keyScope(this.keyScopeFake());
+ }
+ }, this);
+
+ Utils.initDataConstructorBySettings(this);
+ }
+
+ AbstractData.prototype.populateDataOnStart = function()
+ {
var
- sType = '',
- iVersionCompare = this.coreVersionCompare(),
- bChecking = this.coreChecking(),
- bUpdating = this.coreUpdating(),
- bReal = this.coreReal()
+ mLayout = Utils.pInt(RL().settingsGet('Layout')), // TODO cjs
+ aLanguages = RL().settingsGet('Languages'),
+ aThemes = RL().settingsGet('Themes')
;
- if (bChecking)
+ if (Utils.isArray(aLanguages))
{
- sType = 'checking';
- }
- else if (bUpdating)
- {
- sType = 'updating';
- }
- else if (bReal && 0 === iVersionCompare)
- {
- sType = 'up-to-date';
- }
- else if (bReal && -1 === iVersionCompare)
- {
- sType = 'available';
- }
- else if (!bReal)
- {
- sType = 'error';
- this.errorDesc('Cannot access the repository at the moment.');
+ this.languages(aLanguages);
}
- return sType;
+ if (Utils.isArray(aThemes))
+ {
+ this.themes(aThemes);
+ }
- }, this);
-}
+ this.mainLanguage(RL().settingsGet('Language'));
+ this.mainTheme(RL().settingsGet('Theme'));
-Utils.addSettingsViewModel(AdminAbout, 'AdminSettingsAbout', 'About', 'about');
+ this.capaAdditionalAccounts(RL().capa(Enums.Capa.AdditionalAccounts));
+ this.capaAdditionalIdentities(RL().capa(Enums.Capa.AdditionalIdentities));
+ this.capaGravatar(RL().capa(Enums.Capa.Gravatar));
+ this.determineUserLanguage(!!RL().settingsGet('DetermineUserLanguage'));
+ this.determineUserDomain(!!RL().settingsGet('DetermineUserDomain'));
-AdminAbout.prototype.onBuild = function ()
-{
- if (this.access())
- {
- RL.reloadCoreData();
- }
-};
+ this.capaThemes(RL().capa(Enums.Capa.Themes));
+ this.allowLanguagesOnLogin(!!RL().settingsGet('AllowLanguagesOnLogin'));
+ this.allowLanguagesOnSettings(!!RL().settingsGet('AllowLanguagesOnSettings'));
+ this.useLocalProxyForExternalImages(!!RL().settingsGet('UseLocalProxyForExternalImages'));
-AdminAbout.prototype.updateCoreData = function ()
-{
- if (!this.coreUpdating())
- {
- RL.updateCoreData();
- }
-};
-
+ this.editorDefaultType(RL().settingsGet('EditorDefaultType'));
+ this.showImages(!!RL().settingsGet('ShowImages'));
+ this.contactsAutosave(!!RL().settingsGet('ContactsAutosave'));
+ this.interfaceAnimation(RL().settingsGet('InterfaceAnimation'));
+
+ this.mainMessagesPerPage(RL().settingsGet('MPP'));
+
+ this.desktopNotifications(!!RL().settingsGet('DesktopNotifications'));
+ this.useThreads(!!RL().settingsGet('UseThreads'));
+ this.replySameFolder(!!RL().settingsGet('ReplySameFolder'));
+ this.useCheckboxesInList(!!RL().settingsGet('UseCheckboxesInList'));
+
+ this.layout(Enums.Layout.SidePreview);
+ if (-1 < Utils.inArray(mLayout, [Enums.Layout.NoPreview, Enums.Layout.SidePreview, Enums.Layout.BottomPreview]))
+ {
+ this.layout(mLayout);
+ }
+ this.facebookSupported(!!RL().settingsGet('SupportedFacebookSocial'));
+ this.facebookEnable(!!RL().settingsGet('AllowFacebookSocial'));
+ this.facebookAppID(RL().settingsGet('FacebookAppID'));
+ this.facebookAppSecret(RL().settingsGet('FacebookAppSecret'));
+
+ this.twitterEnable(!!RL().settingsGet('AllowTwitterSocial'));
+ this.twitterConsumerKey(RL().settingsGet('TwitterConsumerKey'));
+ this.twitterConsumerSecret(RL().settingsGet('TwitterConsumerSecret'));
+
+ this.googleEnable(!!RL().settingsGet('AllowGoogleSocial'));
+ this.googleClientID(RL().settingsGet('GoogleClientID'));
+ this.googleClientSecret(RL().settingsGet('GoogleClientSecret'));
+ this.googleApiKey(RL().settingsGet('GoogleApiKey'));
+
+ this.dropboxEnable(!!RL().settingsGet('AllowDropboxSocial'));
+ this.dropboxApiKey(RL().settingsGet('DropboxApiKey'));
+
+ this.contactsIsAllowed(!!RL().settingsGet('ContactsIsAllowed'));
+ };
+
+ module.exports = AbstractData;
+
+}(module));
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-/**
- * @constructor
- */
-function AbstractData()
-{
- this.leftPanelDisabled = ko.observable(false);
- this.useKeyboardShortcuts = ko.observable(true);
+(function (module) {
- this.keyScopeReal = ko.observable(Enums.KeyState.All);
- this.keyScopeFake = ko.observable(Enums.KeyState.All);
+ 'use strict';
- this.keyScope = ko.computed({
- 'owner': this,
- 'read': function () {
- return this.keyScopeFake();
- },
- 'write': function (sValue) {
+ var
+ $ = require('../External/jquery.js'),
+ _ = require('../External/underscore.js'),
+ ko = require('../External/ko.js'),
+
+ Globals = require('../Common/Globals.js'),
+ Utils = require('../Common/Utils.js'),
+ LinkBuilder = require('../Common/LinkBuilder.js'),
- if (Enums.KeyState.Menu !== sValue)
+ kn = require('../Knoin/Knoin.js'),
+ KnoinAbstractScreen = require('../Knoin/KnoinAbstractScreen.js')
+ ;
+
+ /**
+ * @param {Array} aViewModels
+ * @constructor
+ * @extends KnoinAbstractScreen
+ */
+ function AbstractSettings(aViewModels)
+ {
+ KnoinAbstractScreen.call(this, 'settings', aViewModels);
+
+ this.menu = ko.observableArray([]);
+
+ this.oCurrentSubScreen = null;
+ this.oViewModelPlace = null;
+ }
+
+ _.extend(AbstractSettings.prototype, KnoinAbstractScreen.prototype);
+
+ AbstractSettings.prototype.onRoute = function (sSubName)
+ {
+ var
+ self = this,
+ oSettingsScreen = null,
+ RoutedSettingsViewModel = null,
+ oViewModelPlace = null,
+ oViewModelDom = null
+ ;
+
+ RoutedSettingsViewModel = _.find(Globals.aViewModels['settings'], function (SettingsViewModel) {
+ return SettingsViewModel && SettingsViewModel.__rlSettingsData &&
+ sSubName === SettingsViewModel.__rlSettingsData.Route;
+ });
+
+ if (RoutedSettingsViewModel)
+ {
+ if (_.find(Globals.aViewModels['settings-removed'], function (DisabledSettingsViewModel) {
+ return DisabledSettingsViewModel && DisabledSettingsViewModel === RoutedSettingsViewModel;
+ }))
{
- if (Enums.KeyState.Compose === sValue)
+ RoutedSettingsViewModel = null;
+ }
+
+ if (RoutedSettingsViewModel && _.find(Globals.aViewModels['settings-disabled'], function (DisabledSettingsViewModel) {
+ return DisabledSettingsViewModel && DisabledSettingsViewModel === RoutedSettingsViewModel;
+ }))
+ {
+ RoutedSettingsViewModel = null;
+ }
+ }
+
+ if (RoutedSettingsViewModel)
+ {
+ if (RoutedSettingsViewModel.__builded && RoutedSettingsViewModel.__vm)
+ {
+ oSettingsScreen = RoutedSettingsViewModel.__vm;
+ }
+ else
+ {
+ oViewModelPlace = this.oViewModelPlace;
+ if (oViewModelPlace && 1 === oViewModelPlace.length)
{
- Utils.disableKeyFilter();
+ RoutedSettingsViewModel = /** @type {?Function} */ RoutedSettingsViewModel;
+ oSettingsScreen = new RoutedSettingsViewModel();
+
+ oViewModelDom = $('').addClass('rl-settings-view-model').hide();
+ oViewModelDom.appendTo(oViewModelPlace);
+
+ oSettingsScreen.viewModelDom = oViewModelDom;
+
+ oSettingsScreen.__rlSettingsData = RoutedSettingsViewModel.__rlSettingsData;
+
+ RoutedSettingsViewModel.__dom = oViewModelDom;
+ RoutedSettingsViewModel.__builded = true;
+ RoutedSettingsViewModel.__vm = oSettingsScreen;
+
+ ko.applyBindingAccessorsToNode(oViewModelDom[0], {
+ 'i18nInit': true,
+ 'template': function () { return {'name': RoutedSettingsViewModel.__rlSettingsData.Template}; }
+ }, oSettingsScreen);
+
+ Utils.delegateRun(oSettingsScreen, 'onBuild', [oViewModelDom]);
}
else
{
- Utils.restoreKeyFilter();
- }
-
- this.keyScopeFake(sValue);
- if (Globals.dropdownVisibility())
- {
- sValue = Enums.KeyState.Menu;
+ Utils.log('Cannot find sub settings view model position: SettingsSubScreen');
}
}
- this.keyScopeReal(sValue);
+ if (oSettingsScreen)
+ {
+ _.defer(function () {
+ // hide
+ if (self.oCurrentSubScreen)
+ {
+ Utils.delegateRun(self.oCurrentSubScreen, 'onHide');
+ self.oCurrentSubScreen.viewModelDom.hide();
+ }
+ // --
+
+ self.oCurrentSubScreen = oSettingsScreen;
+
+ // show
+ if (self.oCurrentSubScreen)
+ {
+ self.oCurrentSubScreen.viewModelDom.show();
+ Utils.delegateRun(self.oCurrentSubScreen, 'onShow');
+ Utils.delegateRun(self.oCurrentSubScreen, 'onFocus', [], 200);
+
+ _.each(self.menu(), function (oItem) {
+ oItem.selected(oSettingsScreen && oSettingsScreen.__rlSettingsData && oItem.route === oSettingsScreen.__rlSettingsData.Route);
+ });
+
+ $('#rl-content .b-settings .b-content .content').scrollTop(0);
+ }
+ // --
+
+ Utils.windowResize();
+ });
+ }
}
- });
-
- this.keyScopeReal.subscribe(function (sValue) {
-// window.console.log(sValue);
- key.setScope(sValue);
- });
-
- this.leftPanelDisabled.subscribe(function (bValue) {
- RL.pub('left-panel.' + (bValue ? 'off' : 'on'));
- });
-
- Globals.dropdownVisibility.subscribe(function (bValue) {
- if (bValue)
+ else
{
- Globals.tooltipTrigger(!Globals.tooltipTrigger());
- this.keyScope(Enums.KeyState.Menu);
+ kn.setHash(LinkBuilder.settings(), false, true); // TODO cjs
}
- else if (Enums.KeyState.Menu === key.getScope())
+ };
+
+ AbstractSettings.prototype.onHide = function ()
+ {
+ if (this.oCurrentSubScreen && this.oCurrentSubScreen.viewModelDom)
{
- this.keyScope(this.keyScopeFake());
+ Utils.delegateRun(this.oCurrentSubScreen, 'onHide');
+ this.oCurrentSubScreen.viewModelDom.hide();
}
- }, this);
+ };
- Utils.initDataConstructorBySettings(this);
-}
+ AbstractSettings.prototype.onBuild = function ()
+ {
+ _.each(Globals.aViewModels['settings'], function (SettingsViewModel) {
+ if (SettingsViewModel && SettingsViewModel.__rlSettingsData &&
+ !_.find(Globals.aViewModels['settings-removed'], function (RemoveSettingsViewModel) {
+ return RemoveSettingsViewModel && RemoveSettingsViewModel === SettingsViewModel;
+ }))
+ {
+ this.menu.push({
+ 'route': SettingsViewModel.__rlSettingsData.Route,
+ 'label': SettingsViewModel.__rlSettingsData.Label,
+ 'selected': ko.observable(false),
+ 'disabled': !!_.find(Globals.aViewModels['settings-disabled'], function (DisabledSettingsViewModel) {
+ return DisabledSettingsViewModel && DisabledSettingsViewModel === SettingsViewModel;
+ })
+ });
+ }
+ }, this);
+
+ this.oViewModelPlace = $('#rl-content #rl-settings-subscreen');
+ };
+
+ AbstractSettings.prototype.routes = function ()
+ {
+ var
+ DefaultViewModel = _.find(Globals.aViewModels['settings'], function (SettingsViewModel) {
+ return SettingsViewModel && SettingsViewModel.__rlSettingsData && SettingsViewModel.__rlSettingsData['IsDefault'];
+ }),
+ sDefaultRoute = DefaultViewModel ? DefaultViewModel.__rlSettingsData['Route'] : 'general',
+ oRules = {
+ 'subname': /^(.*)$/,
+ 'normalize_': function (oRequest, oVals) {
+ oVals.subname = Utils.isUnd(oVals.subname) ? sDefaultRoute : Utils.pString(oVals.subname);
+ return [oVals.subname];
+ }
+ }
+ ;
+
+ return [
+ ['{subname}/', oRules],
+ ['{subname}', oRules],
+ ['', oRules]
+ ];
+ };
+
+ module.exports = AbstractSettings;
+
+}(module));
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
-AbstractData.prototype.populateDataOnStart = function()
-{
var
- mLayout = Utils.pInt(RL.settingsGet('Layout')),
- aLanguages = RL.settingsGet('Languages'),
- aThemes = RL.settingsGet('Themes')
+ _ = require('../External/underscore.js'),
+ KnoinAbstractScreen = require('../Knoin/KnoinAbstractScreen.js'),
+ AdminLoginViewModel = require('../ViewModels/AdminLoginViewModel.js')
+ ;
+
+ /**
+ * @constructor
+ * @extends KnoinAbstractScreen
+ */
+ function AdminLoginScreen()
+ {
+ KnoinAbstractScreen.call(this, 'login', [AdminLoginViewModel]);
+ }
+
+ _.extend(AdminLoginScreen.prototype, KnoinAbstractScreen.prototype);
+
+ AdminLoginScreen.prototype.onShow = function ()
+ {
+ RL.setTitle(''); // TODO cjs
+ };
+
+ module.exports = AdminLoginScreen;
+
+}(module));
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ _ = require('../External/underscore.js'),
+ AbstractSettings = require('./AbstractSettings.js'),
+ AdminMenuViewModel = require('../ViewModels/AdminMenuViewModel.js'),
+ AdminPaneViewModel = require('../ViewModels/AdminPaneViewModel.js')
;
- if (Utils.isArray(aLanguages))
+ /**
+ * @constructor
+ * @extends AbstractSettings
+ */
+ function AdminSettingsScreen()
{
- this.languages(aLanguages);
+ AbstractSettings.call(this, [
+ AdminMenuViewModel,
+ AdminPaneViewModel
+ ]);
}
- if (Utils.isArray(aThemes))
+ _.extend(AdminSettingsScreen.prototype, AbstractSettings.prototype);
+
+ AdminSettingsScreen.prototype.onShow = function ()
{
- this.themes(aThemes);
- }
+ RL.setTitle(''); // TODO cjs
+ };
- this.mainLanguage(RL.settingsGet('Language'));
- this.mainTheme(RL.settingsGet('Theme'));
+ module.exports = AdminSettingsScreen;
- this.capaAdditionalAccounts(RL.capa(Enums.Capa.AdditionalAccounts));
- this.capaAdditionalIdentities(RL.capa(Enums.Capa.AdditionalIdentities));
- this.capaGravatar(RL.capa(Enums.Capa.Gravatar));
- this.determineUserLanguage(!!RL.settingsGet('DetermineUserLanguage'));
- this.determineUserDomain(!!RL.settingsGet('DetermineUserDomain'));
-
- this.capaThemes(RL.capa(Enums.Capa.Themes));
- this.allowLanguagesOnLogin(!!RL.settingsGet('AllowLanguagesOnLogin'));
- this.allowLanguagesOnSettings(!!RL.settingsGet('AllowLanguagesOnSettings'));
- this.useLocalProxyForExternalImages(!!RL.settingsGet('UseLocalProxyForExternalImages'));
-
- this.editorDefaultType(RL.settingsGet('EditorDefaultType'));
- this.showImages(!!RL.settingsGet('ShowImages'));
- this.contactsAutosave(!!RL.settingsGet('ContactsAutosave'));
- this.interfaceAnimation(RL.settingsGet('InterfaceAnimation'));
-
- this.mainMessagesPerPage(RL.settingsGet('MPP'));
-
- this.desktopNotifications(!!RL.settingsGet('DesktopNotifications'));
- this.useThreads(!!RL.settingsGet('UseThreads'));
- this.replySameFolder(!!RL.settingsGet('ReplySameFolder'));
- this.useCheckboxesInList(!!RL.settingsGet('UseCheckboxesInList'));
-
- this.layout(Enums.Layout.SidePreview);
- if (-1 < Utils.inArray(mLayout, [Enums.Layout.NoPreview, Enums.Layout.SidePreview, Enums.Layout.BottomPreview]))
- {
- this.layout(mLayout);
- }
- this.facebookSupported(!!RL.settingsGet('SupportedFacebookSocial'));
- this.facebookEnable(!!RL.settingsGet('AllowFacebookSocial'));
- this.facebookAppID(RL.settingsGet('FacebookAppID'));
- this.facebookAppSecret(RL.settingsGet('FacebookAppSecret'));
-
- this.twitterEnable(!!RL.settingsGet('AllowTwitterSocial'));
- this.twitterConsumerKey(RL.settingsGet('TwitterConsumerKey'));
- this.twitterConsumerSecret(RL.settingsGet('TwitterConsumerSecret'));
-
- this.googleEnable(!!RL.settingsGet('AllowGoogleSocial'));
- this.googleClientID(RL.settingsGet('GoogleClientID'));
- this.googleClientSecret(RL.settingsGet('GoogleClientSecret'));
- this.googleApiKey(RL.settingsGet('GoogleApiKey'));
-
- this.dropboxEnable(!!RL.settingsGet('AllowDropboxSocial'));
- this.dropboxApiKey(RL.settingsGet('DropboxApiKey'));
-
- this.contactsIsAllowed(!!RL.settingsGet('ContactsIsAllowed'));
-};
-
+}(module));
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-/**
- * @constructor
- * @extends AbstractData
- */
-function AdminDataStorage()
-{
- AbstractData.call(this);
+(function (module) {
- this.domainsLoading = ko.observable(false).extend({'throttle': 100});
- this.domains = ko.observableArray([]);
+ 'use strict';
- this.pluginsLoading = ko.observable(false).extend({'throttle': 100});
- this.plugins = ko.observableArray([]);
-
- this.packagesReal = ko.observable(true);
- this.packagesMainUpdatable = ko.observable(true);
- this.packagesLoading = ko.observable(false).extend({'throttle': 100});
- this.packages = ko.observableArray([]);
-
- this.coreReal = ko.observable(true);
- this.coreUpdatable = ko.observable(true);
- this.coreAccess = ko.observable(true);
- this.coreChecking = ko.observable(false).extend({'throttle': 100});
- this.coreUpdating = ko.observable(false).extend({'throttle': 100});
- this.coreRemoteVersion = ko.observable('');
- this.coreRemoteRelease = ko.observable('');
- this.coreVersionCompare = ko.observable(-2);
-
- this.licensing = ko.observable(false);
- this.licensingProcess = ko.observable(false);
- this.licenseValid = ko.observable(false);
- this.licenseExpired = ko.observable(0);
- this.licenseError = ko.observable('');
-
- this.licenseTrigger = ko.observable(false);
-
- this.adminManLoading = ko.computed(function () {
- return '000' !== [this.domainsLoading() ? '1' : '0', this.pluginsLoading() ? '1' : '0', this.packagesLoading() ? '1' : '0'].join('');
- }, this);
-
- this.adminManLoadingVisibility = ko.computed(function () {
- return this.adminManLoading() ? 'visible' : 'hidden';
- }, this).extend({'rateLimit': 300});
-}
-
-_.extend(AdminDataStorage.prototype, AbstractData.prototype);
-
-AdminDataStorage.prototype.populateDataOnStart = function()
-{
- AbstractData.prototype.populateDataOnStart.call(this);
-};
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function AbstractAjaxRemoteStorage()
-{
- this.oRequests = {};
-}
-
-AbstractAjaxRemoteStorage.prototype.oRequests = {};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sRequestAction
- * @param {string} sType
- * @param {?AjaxJsonDefaultResponse} oData
- * @param {boolean} bCached
- * @param {*=} oRequestParameters
- */
-AbstractAjaxRemoteStorage.prototype.defaultResponse = function (fCallback, sRequestAction, sType, oData, bCached, oRequestParameters)
-{
var
- fCall = function () {
- if (Enums.StorageResultType.Success !== sType && Globals.bUnload)
- {
- sType = Enums.StorageResultType.Unload;
- }
+ $ = require('../External/jquery.js'),
+ _ = require('../External/underscore.js'),
+ ko = require('../External/ko.js'),
+ window = require('../External/window.js'),
+ $html = require('../External/$html.js'),
+ $window = require('../External/$window.js'),
+ $doc = require('../External/$doc.js'),
+ AppData = require('../External/AppData.js'),
- if (Enums.StorageResultType.Success === sType && oData && !oData.Result)
- {
- if (oData && -1 < Utils.inArray(oData.ErrorCode, [
- Enums.Notification.AuthError, Enums.Notification.AccessError,
- Enums.Notification.ConnectionError, Enums.Notification.DomainNotAllowed, Enums.Notification.AccountNotAllowed,
- Enums.Notification.MailServerError, Enums.Notification.UnknownNotification, Enums.Notification.UnknownError
+ Globals = require('../Common/Globals.js'),
+ Utils = require('../Common/Utils.js'),
+ Plugins = require('../Common/Plugins.js'),
+ LinkBuilder = require('../Common/LinkBuilder.js'),
+
+ kn = require('../Knoin/Knoin.js'),
+ KnoinAbstractBoot = require('../Knoin/KnoinAbstractBoot.js')
+ ;
+
+ /**
+ * @param {*} Remote
+ * @constructor
+ * @extends KnoinAbstractBoot
+ */
+ function AbstractApp(Remote)
+ {
+ KnoinAbstractBoot.call(this);
+
+ this.oSettings = null;
+ this.oPlugins = null;
+ this.oLocal = null;
+ this.oLink = null;
+ this.oSubs = {};
+
+ this.isLocalAutocomplete = true;
+
+ this.popupVisibilityNames = ko.observableArray([]);
+
+ this.popupVisibility = ko.computed(function () {
+ return 0 < this.popupVisibilityNames().length;
+ }, this);
+
+ this.iframe = $('').appendTo('body');
+
+ $window.on('error', function (oEvent) {
+ if (oEvent && oEvent.originalEvent && oEvent.originalEvent.message &&
+ -1 === Utils.inArray(oEvent.originalEvent.message, [
+ 'Script error.', 'Uncaught Error: Error calling method on NPObject.'
]))
- {
- Globals.iAjaxErrorCount++;
- }
-
- if (oData && Enums.Notification.InvalidToken === oData.ErrorCode)
- {
- Globals.iTokenErrorCount++;
- }
-
- if (Consts.Values.TokenErrorLimit < Globals.iTokenErrorCount)
- {
- RL.loginAndLogoutReload(true);
- }
-
- if (oData.Logout || Consts.Values.AjaxErrorLimit < Globals.iAjaxErrorCount)
- {
- if (window.__rlah_clear)
- {
- window.__rlah_clear();
- }
-
- RL.loginAndLogoutReload(true);
- }
- }
- else if (Enums.StorageResultType.Success === sType && oData && oData.Result)
{
- Globals.iAjaxErrorCount = 0;
- Globals.iTokenErrorCount = 0;
- }
-
- if (fCallback)
- {
- Plugins.runHook('ajax-default-response', [sRequestAction, Enums.StorageResultType.Success === sType ? oData : null, sType, bCached, oRequestParameters]);
-
- fCallback(
- sType,
- Enums.StorageResultType.Success === sType ? oData : null,
- bCached,
- sRequestAction,
- oRequestParameters
+ Remote.jsError(
+ Utils.emptyFunction,
+ oEvent.originalEvent.message,
+ oEvent.originalEvent.filename,
+ oEvent.originalEvent.lineno,
+ window.location && window.location.toString ? window.location.toString() : '',
+ $html.attr('class'),
+ Utils.microtime() - Globals.now
);
}
- }
- ;
+ });
- switch (sType)
- {
- case 'success':
- sType = Enums.StorageResultType.Success;
- break;
- case 'abort':
- sType = Enums.StorageResultType.Abort;
- break;
- default:
- sType = Enums.StorageResultType.Error;
- break;
- }
-
- if (Enums.StorageResultType.Error === sType)
- {
- _.delay(fCall, 300);
- }
- else
- {
- fCall();
- }
-};
-
-/**
- * @param {?Function} fResultCallback
- * @param {Object} oParameters
- * @param {?number=} iTimeOut = 20000
- * @param {string=} sGetAdd = ''
- * @param {Array=} aAbortActions = []
- * @return {jQuery.jqXHR}
- */
-AbstractAjaxRemoteStorage.prototype.ajaxRequest = function (fResultCallback, oParameters, iTimeOut, sGetAdd, aAbortActions)
-{
- var
- self = this,
- bPost = '' === sGetAdd,
- oHeaders = {},
- iStart = (new window.Date()).getTime(),
- oDefAjax = null,
- sAction = ''
- ;
-
- oParameters = oParameters || {};
- iTimeOut = Utils.isNormal(iTimeOut) ? iTimeOut : 20000;
- sGetAdd = Utils.isUnd(sGetAdd) ? '' : Utils.pString(sGetAdd);
- aAbortActions = Utils.isArray(aAbortActions) ? aAbortActions : [];
-
- sAction = oParameters.Action || '';
-
- if (sAction && 0 < aAbortActions.length)
- {
- _.each(aAbortActions, function (sActionToAbort) {
- if (self.oRequests[sActionToAbort])
+ $doc.on('keydown', function (oEvent) {
+ if (oEvent && oEvent.ctrlKey)
{
- self.oRequests[sActionToAbort].__aborted = true;
- if (self.oRequests[sActionToAbort].abort)
- {
- self.oRequests[sActionToAbort].abort();
- }
- self.oRequests[sActionToAbort] = null;
+ $html.addClass('rl-ctrl-key-pressed');
+ }
+ }).on('keyup', function (oEvent) {
+ if (oEvent && !oEvent.ctrlKey)
+ {
+ $html.removeClass('rl-ctrl-key-pressed');
}
});
}
- if (bPost)
+ _.extend(AbstractApp.prototype, KnoinAbstractBoot.prototype);
+
+ AbstractApp.prototype.oSettings = null;
+ AbstractApp.prototype.oPlugins = null;
+ AbstractApp.prototype.oLocal = null;
+ AbstractApp.prototype.oLink = null;
+ AbstractApp.prototype.oSubs = {};
+
+ /**
+ * @param {string} sLink
+ * @return {boolean}
+ */
+ AbstractApp.prototype.download = function (sLink)
{
- oParameters['XToken'] = RL.settingsGet('Token');
- }
+ var
+ oE = null,
+ oLink = null,
+ sUserAgent = window.navigator.userAgent.toLowerCase()
+ ;
- oDefAjax = $.ajax({
- 'type': bPost ? 'POST' : 'GET',
- 'url': RL.link().ajax(sGetAdd),
- 'async': true,
- 'dataType': 'json',
- 'data': bPost ? oParameters : {},
- 'headers': oHeaders,
- 'timeout': iTimeOut,
- 'global': true
- });
-
- oDefAjax.always(function (oData, sType) {
-
- var bCached = false;
- if (oData && oData['Time'])
+ if (sUserAgent && (sUserAgent.indexOf('chrome') > -1 || sUserAgent.indexOf('chrome') > -1))
{
- bCached = Utils.pInt(oData['Time']) > (new window.Date()).getTime() - iStart;
- }
+ oLink = window.document.createElement('a');
+ oLink['href'] = sLink;
- if (sAction && self.oRequests[sAction])
- {
- if (self.oRequests[sAction].__aborted)
+ if (window.document['createEvent'])
{
- sType = 'abort';
- }
-
- self.oRequests[sAction] = null;
- }
-
- self.defaultResponse(fResultCallback, sAction, sType, oData, bCached, oParameters);
- });
-
- if (sAction && 0 < aAbortActions.length && -1 < Utils.inArray(sAction, aAbortActions))
- {
- if (this.oRequests[sAction])
- {
- this.oRequests[sAction].__aborted = true;
- if (this.oRequests[sAction].abort)
- {
- this.oRequests[sAction].abort();
- }
- this.oRequests[sAction] = null;
- }
-
- this.oRequests[sAction] = oDefAjax;
- }
-
- return oDefAjax;
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sAction
- * @param {Object=} oParameters
- * @param {?number=} iTimeout
- * @param {string=} sGetAdd = ''
- * @param {Array=} aAbortActions = []
- */
-AbstractAjaxRemoteStorage.prototype.defaultRequest = function (fCallback, sAction, oParameters, iTimeout, sGetAdd, aAbortActions)
-{
- oParameters = oParameters || {};
- oParameters.Action = sAction;
-
- sGetAdd = Utils.pString(sGetAdd);
-
- Plugins.runHook('ajax-default-request', [sAction, oParameters, sGetAdd]);
-
- this.ajaxRequest(fCallback, oParameters,
- Utils.isUnd(iTimeout) ? Consts.Defaults.DefaultAjaxTimeout : Utils.pInt(iTimeout), sGetAdd, aAbortActions);
-};
-
-/**
- * @param {?Function} fCallback
- */
-AbstractAjaxRemoteStorage.prototype.noop = function (fCallback)
-{
- this.defaultRequest(fCallback, 'Noop');
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sMessage
- * @param {string} sFileName
- * @param {number} iLineNo
- * @param {string} sLocation
- * @param {string} sHtmlCapa
- * @param {number} iTime
- */
-AbstractAjaxRemoteStorage.prototype.jsError = function (fCallback, sMessage, sFileName, iLineNo, sLocation, sHtmlCapa, iTime)
-{
- this.defaultRequest(fCallback, 'JsError', {
- 'Message': sMessage,
- 'FileName': sFileName,
- 'LineNo': iLineNo,
- 'Location': sLocation,
- 'HtmlCapa': sHtmlCapa,
- 'TimeOnPage': iTime
- });
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sType
- * @param {Array=} mData = null
- * @param {boolean=} bIsError = false
- */
-AbstractAjaxRemoteStorage.prototype.jsInfo = function (fCallback, sType, mData, bIsError)
-{
- this.defaultRequest(fCallback, 'JsInfo', {
- 'Type': sType,
- 'Data': mData,
- 'IsError': (Utils.isUnd(bIsError) ? false : !!bIsError) ? '1' : '0'
- });
-};
-
-/**
- * @param {?Function} fCallback
- */
-AbstractAjaxRemoteStorage.prototype.getPublicKey = function (fCallback)
-{
- this.defaultRequest(fCallback, 'GetPublicKey');
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sVersion
- */
-AbstractAjaxRemoteStorage.prototype.jsVersion = function (fCallback, sVersion)
-{
- this.defaultRequest(fCallback, 'Version', {
- 'Version': sVersion
- });
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends AbstractAjaxRemoteStorage
- */
-function AdminAjaxRemoteStorage()
-{
- AbstractAjaxRemoteStorage.call(this);
-
- this.oRequests = {};
-}
-
-_.extend(AdminAjaxRemoteStorage.prototype, AbstractAjaxRemoteStorage.prototype);
-
-/**
- * @param {?Function} fCallback
- * @param {string} sLogin
- * @param {string} sPassword
- */
-AdminAjaxRemoteStorage.prototype.adminLogin = function (fCallback, sLogin, sPassword)
-{
- this.defaultRequest(fCallback, 'AdminLogin', {
- 'Login': sLogin,
- 'Password': sPassword
- });
-};
-
-/**
- * @param {?Function} fCallback
- */
-AdminAjaxRemoteStorage.prototype.adminLogout = function (fCallback)
-{
- this.defaultRequest(fCallback, 'AdminLogout');
-};
-
-/**
- * @param {?Function} fCallback
- * @param {?} oData
- */
-AdminAjaxRemoteStorage.prototype.saveAdminConfig = function (fCallback, oData)
-{
- this.defaultRequest(fCallback, 'AdminSettingsUpdate', oData);
-};
-
-/**
- * @param {?Function} fCallback
- */
-AdminAjaxRemoteStorage.prototype.domainList = function (fCallback)
-{
- this.defaultRequest(fCallback, 'AdminDomainList');
-};
-
-/**
- * @param {?Function} fCallback
- */
-AdminAjaxRemoteStorage.prototype.pluginList = function (fCallback)
-{
- this.defaultRequest(fCallback, 'AdminPluginList');
-};
-
-/**
- * @param {?Function} fCallback
- */
-AdminAjaxRemoteStorage.prototype.packagesList = function (fCallback)
-{
- this.defaultRequest(fCallback, 'AdminPackagesList');
-};
-
-/**
- * @param {?Function} fCallback
- */
-AdminAjaxRemoteStorage.prototype.coreData = function (fCallback)
-{
- this.defaultRequest(fCallback, 'AdminCoreData');
-};
-
-/**
- * @param {?Function} fCallback
- */
-AdminAjaxRemoteStorage.prototype.updateCoreData = function (fCallback)
-{
- this.defaultRequest(fCallback, 'AdminUpdateCoreData', {}, 90000);
-};
-
-/**
- * @param {?Function} fCallback
- * @param {Object} oPackage
- */
-AdminAjaxRemoteStorage.prototype.packageInstall = function (fCallback, oPackage)
-{
- this.defaultRequest(fCallback, 'AdminPackageInstall', {
- 'Id': oPackage.id,
- 'Type': oPackage.type,
- 'File': oPackage.file
- }, 60000);
-};
-
-/**
- * @param {?Function} fCallback
- * @param {Object} oPackage
- */
-AdminAjaxRemoteStorage.prototype.packageDelete = function (fCallback, oPackage)
-{
- this.defaultRequest(fCallback, 'AdminPackageDelete', {
- 'Id': oPackage.id
- });
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sName
- */
-AdminAjaxRemoteStorage.prototype.domain = function (fCallback, sName)
-{
- this.defaultRequest(fCallback, 'AdminDomainLoad', {
- 'Name': sName
- });
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sName
- */
-AdminAjaxRemoteStorage.prototype.plugin = function (fCallback, sName)
-{
- this.defaultRequest(fCallback, 'AdminPluginLoad', {
- 'Name': sName
- });
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sName
- */
-AdminAjaxRemoteStorage.prototype.domainDelete = function (fCallback, sName)
-{
- this.defaultRequest(fCallback, 'AdminDomainDelete', {
- 'Name': sName
- });
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sName
- * @param {boolean} bDisabled
- */
-AdminAjaxRemoteStorage.prototype.domainDisable = function (fCallback, sName, bDisabled)
-{
- return this.defaultRequest(fCallback, 'AdminDomainDisable', {
- 'Name': sName,
- 'Disabled': !!bDisabled ? '1' : '0'
- });
-};
-
-/**
- * @param {?Function} fCallback
- * @param {Object} oConfig
- */
-AdminAjaxRemoteStorage.prototype.pluginSettingsUpdate = function (fCallback, oConfig)
-{
- return this.defaultRequest(fCallback, 'AdminPluginSettingsUpdate', oConfig);
-};
-
-/**
- * @param {?Function} fCallback
- * @param {boolean} bForce
- */
-AdminAjaxRemoteStorage.prototype.licensing = function (fCallback, bForce)
-{
- return this.defaultRequest(fCallback, 'AdminLicensing', {
- 'Force' : bForce ? '1' : '0'
- });
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sDomain
- * @param {string} sKey
- */
-AdminAjaxRemoteStorage.prototype.licensingActivate = function (fCallback, sDomain, sKey)
-{
- return this.defaultRequest(fCallback, 'AdminLicensingActivate', {
- 'Domain' : sDomain,
- 'Key' : sKey
- });
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sName
- * @param {boolean} bDisabled
- */
-AdminAjaxRemoteStorage.prototype.pluginDisable = function (fCallback, sName, bDisabled)
-{
- return this.defaultRequest(fCallback, 'AdminPluginDisable', {
- 'Name': sName,
- 'Disabled': !!bDisabled ? '1' : '0'
- });
-};
-
-AdminAjaxRemoteStorage.prototype.createOrUpdateDomain = function (fCallback,
- bCreate, sName, sIncHost, iIncPort, sIncSecure, bIncShortLogin,
- sOutHost, iOutPort, sOutSecure, bOutShortLogin, bOutAuth, sWhiteList)
-{
- this.defaultRequest(fCallback, 'AdminDomainSave', {
- 'Create': bCreate ? '1' : '0',
- 'Name': sName,
- 'IncHost': sIncHost,
- 'IncPort': iIncPort,
- 'IncSecure': sIncSecure,
- 'IncShortLogin': bIncShortLogin ? '1' : '0',
- 'OutHost': sOutHost,
- 'OutPort': iOutPort,
- 'OutSecure': sOutSecure,
- 'OutShortLogin': bOutShortLogin ? '1' : '0',
- 'OutAuth': bOutAuth ? '1' : '0',
- 'WhiteList': sWhiteList
- });
-};
-
-AdminAjaxRemoteStorage.prototype.testConnectionForDomain = function (fCallback, sName,
- sIncHost, iIncPort, sIncSecure,
- sOutHost, iOutPort, sOutSecure, bOutAuth)
-{
- this.defaultRequest(fCallback, 'AdminDomainTest', {
- 'Name': sName,
- 'IncHost': sIncHost,
- 'IncPort': iIncPort,
- 'IncSecure': sIncSecure,
- 'OutHost': sOutHost,
- 'OutPort': iOutPort,
- 'OutSecure': sOutSecure,
- 'OutAuth': bOutAuth ? '1' : '0'
- });
-};
-
-/**
- * @param {?Function} fCallback
- * @param {?} oData
- */
-AdminAjaxRemoteStorage.prototype.testContacts = function (fCallback, oData)
-{
- this.defaultRequest(fCallback, 'AdminContactsTest', oData);
-};
-
-/**
- * @param {?Function} fCallback
- * @param {?} oData
- */
-AdminAjaxRemoteStorage.prototype.saveNewAdminPassword = function (fCallback, oData)
-{
- this.defaultRequest(fCallback, 'AdminPasswordUpdate', oData);
-};
-
-/**
- * @param {?Function} fCallback
- */
-AdminAjaxRemoteStorage.prototype.adminPing = function (fCallback)
-{
- this.defaultRequest(fCallback, 'AdminPing');
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function AbstractCacheStorage()
-{
- this.bCapaGravatar = RL.capa(Enums.Capa.Gravatar);
-}
-
-/**
- * @type {Object}
- */
-AbstractCacheStorage.prototype.oServices = {};
-
-/**
- * @type {boolean}
- */
-AbstractCacheStorage.prototype.bCapaGravatar = false;
-
-AbstractCacheStorage.prototype.clear = function ()
-{
- this.bCapaGravatar = !!this.bCapaGravatar; // TODO
-};
-
-/**
- * @param {string} sEmail
- * @return {string}
- */
-AbstractCacheStorage.prototype.getUserPic = function (sEmail, fCallback)
-{
- sEmail = Utils.trim(sEmail);
- fCallback(this.bCapaGravatar && '' !== sEmail ? RL.link().avatarLink(sEmail) : '', sEmail);
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends AbstractCacheStorage
- */
-function AdminCacheStorage()
-{
- AbstractCacheStorage.call(this);
-}
-
-_.extend(AdminCacheStorage.prototype, AbstractCacheStorage.prototype);
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @param {Array} aViewModels
- * @constructor
- * @extends KnoinAbstractScreen
- */
-function AbstractSettings(aViewModels)
-{
- KnoinAbstractScreen.call(this, 'settings', aViewModels);
-
- this.menu = ko.observableArray([]);
-
- this.oCurrentSubScreen = null;
- this.oViewModelPlace = null;
-}
-
-_.extend(AbstractSettings.prototype, KnoinAbstractScreen.prototype);
-
-AbstractSettings.prototype.onRoute = function (sSubName)
-{
- var
- self = this,
- oSettingsScreen = null,
- RoutedSettingsViewModel = null,
- oViewModelPlace = null,
- oViewModelDom = null
- ;
-
- RoutedSettingsViewModel = _.find(ViewModels['settings'], function (SettingsViewModel) {
- return SettingsViewModel && SettingsViewModel.__rlSettingsData &&
- sSubName === SettingsViewModel.__rlSettingsData.Route;
- });
-
- if (RoutedSettingsViewModel)
- {
- if (_.find(ViewModels['settings-removed'], function (DisabledSettingsViewModel) {
- return DisabledSettingsViewModel && DisabledSettingsViewModel === RoutedSettingsViewModel;
- }))
- {
- RoutedSettingsViewModel = null;
- }
-
- if (RoutedSettingsViewModel && _.find(ViewModels['settings-disabled'], function (DisabledSettingsViewModel) {
- return DisabledSettingsViewModel && DisabledSettingsViewModel === RoutedSettingsViewModel;
- }))
- {
- RoutedSettingsViewModel = null;
- }
- }
-
- if (RoutedSettingsViewModel)
- {
- if (RoutedSettingsViewModel.__builded && RoutedSettingsViewModel.__vm)
- {
- oSettingsScreen = RoutedSettingsViewModel.__vm;
- }
- else
- {
- oViewModelPlace = this.oViewModelPlace;
- if (oViewModelPlace && 1 === oViewModelPlace.length)
- {
- RoutedSettingsViewModel = /** @type {?Function} */ RoutedSettingsViewModel;
- oSettingsScreen = new RoutedSettingsViewModel();
-
- oViewModelDom = $('').addClass('rl-settings-view-model').hide();
- oViewModelDom.appendTo(oViewModelPlace);
-
- oSettingsScreen.data = RL.data();
- oSettingsScreen.viewModelDom = oViewModelDom;
-
- oSettingsScreen.__rlSettingsData = RoutedSettingsViewModel.__rlSettingsData;
-
- RoutedSettingsViewModel.__dom = oViewModelDom;
- RoutedSettingsViewModel.__builded = true;
- RoutedSettingsViewModel.__vm = oSettingsScreen;
-
- ko.applyBindingAccessorsToNode(oViewModelDom[0], {
- 'i18nInit': true,
- 'template': function () { return {'name': RoutedSettingsViewModel.__rlSettingsData.Template}; }
- }, oSettingsScreen);
-
- Utils.delegateRun(oSettingsScreen, 'onBuild', [oViewModelDom]);
- }
- else
- {
- Utils.log('Cannot find sub settings view model position: SettingsSubScreen');
- }
- }
-
- if (oSettingsScreen)
- {
- _.defer(function () {
- // hide
- if (self.oCurrentSubScreen)
+ oE = window.document['createEvent']('MouseEvents');
+ if (oE && oE['initEvent'] && oLink['dispatchEvent'])
{
- Utils.delegateRun(self.oCurrentSubScreen, 'onHide');
- self.oCurrentSubScreen.viewModelDom.hide();
+ oE['initEvent']('click', true, true);
+ oLink['dispatchEvent'](oE);
+ return true;
}
- // --
+ }
+ }
- self.oCurrentSubScreen = oSettingsScreen;
+ if (Globals.bMobileDevice)
+ {
+ window.open(sLink, '_self');
+ window.focus();
+ }
+ else
+ {
+ this.iframe.attr('src', sLink);
+ // window.document.location.href = sLink;
+ }
- // show
- if (self.oCurrentSubScreen)
+ return true;
+ };
+
+ /**
+ * @param {string} sName
+ * @return {?}
+ */
+ AbstractApp.prototype.settingsGet = function (sName)
+ {
+ if (null === this.oSettings)
+ {
+ this.oSettings = Utils.isNormal(AppData) ? AppData : {};
+ }
+
+ return Utils.isUnd(this.oSettings[sName]) ? null : this.oSettings[sName];
+ };
+
+ /**
+ * @param {string} sName
+ * @param {?} mValue
+ */
+ AbstractApp.prototype.settingsSet = function (sName, mValue)
+ {
+ if (null === this.oSettings)
+ {
+ this.oSettings = Utils.isNormal(AppData) ? AppData : {};
+ }
+
+ this.oSettings[sName] = mValue;
+ };
+
+ AbstractApp.prototype.setTitle = function (sTitle)
+ {
+ sTitle = ((Utils.isNormal(sTitle) && 0 < sTitle.length) ? sTitle + ' - ' : '') +
+ this.settingsGet('Title') || '';
+
+ window.document.title = '_';
+ window.document.title = sTitle;
+ };
+
+ /**
+ * @param {boolean=} bLogout = false
+ * @param {boolean=} bClose = false
+ */
+ AbstractApp.prototype.loginAndLogoutReload = function (bLogout, bClose)
+ {
+ var
+ sCustomLogoutLink = Utils.pString(this.settingsGet('CustomLogoutLink')),
+ bInIframe = !!this.settingsGet('InIframe')
+ ;
+
+ bLogout = Utils.isUnd(bLogout) ? false : !!bLogout;
+ bClose = Utils.isUnd(bClose) ? false : !!bClose;
+
+ if (bLogout && bClose && window.close)
+ {
+ window.close();
+ }
+
+ if (bLogout && '' !== sCustomLogoutLink && window.location.href !== sCustomLogoutLink)
+ {
+ _.delay(function () {
+ if (bInIframe && window.parent)
{
- self.oCurrentSubScreen.viewModelDom.show();
- Utils.delegateRun(self.oCurrentSubScreen, 'onShow');
- Utils.delegateRun(self.oCurrentSubScreen, 'onFocus', [], 200);
-
- _.each(self.menu(), function (oItem) {
- oItem.selected(oSettingsScreen && oSettingsScreen.__rlSettingsData && oItem.route === oSettingsScreen.__rlSettingsData.Route);
- });
-
- $('#rl-content .b-settings .b-content .content').scrollTop(0);
- }
- // --
-
- Utils.windowResize();
- });
- }
- }
- else
- {
- kn.setHash(RL.link().settings(), false, true);
- }
-};
-
-AbstractSettings.prototype.onHide = function ()
-{
- if (this.oCurrentSubScreen && this.oCurrentSubScreen.viewModelDom)
- {
- Utils.delegateRun(this.oCurrentSubScreen, 'onHide');
- this.oCurrentSubScreen.viewModelDom.hide();
- }
-};
-
-AbstractSettings.prototype.onBuild = function ()
-{
- _.each(ViewModels['settings'], function (SettingsViewModel) {
- if (SettingsViewModel && SettingsViewModel.__rlSettingsData &&
- !_.find(ViewModels['settings-removed'], function (RemoveSettingsViewModel) {
- return RemoveSettingsViewModel && RemoveSettingsViewModel === SettingsViewModel;
- }))
- {
- this.menu.push({
- 'route': SettingsViewModel.__rlSettingsData.Route,
- 'label': SettingsViewModel.__rlSettingsData.Label,
- 'selected': ko.observable(false),
- 'disabled': !!_.find(ViewModels['settings-disabled'], function (DisabledSettingsViewModel) {
- return DisabledSettingsViewModel && DisabledSettingsViewModel === SettingsViewModel;
- })
- });
- }
- }, this);
-
- this.oViewModelPlace = $('#rl-content #rl-settings-subscreen');
-};
-
-AbstractSettings.prototype.routes = function ()
-{
- var
- DefaultViewModel = _.find(ViewModels['settings'], function (SettingsViewModel) {
- return SettingsViewModel && SettingsViewModel.__rlSettingsData && SettingsViewModel.__rlSettingsData['IsDefault'];
- }),
- sDefaultRoute = DefaultViewModel ? DefaultViewModel.__rlSettingsData['Route'] : 'general',
- oRules = {
- 'subname': /^(.*)$/,
- 'normalize_': function (oRequest, oVals) {
- oVals.subname = Utils.isUnd(oVals.subname) ? sDefaultRoute : Utils.pString(oVals.subname);
- return [oVals.subname];
- }
- }
- ;
-
- return [
- ['{subname}/', oRules],
- ['{subname}', oRules],
- ['', oRules]
- ];
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends KnoinAbstractScreen
- */
-function AdminLoginScreen()
-{
- KnoinAbstractScreen.call(this, 'login', [AdminLoginViewModel]);
-}
-
-_.extend(AdminLoginScreen.prototype, KnoinAbstractScreen.prototype);
-
-AdminLoginScreen.prototype.onShow = function ()
-{
- RL.setTitle('');
-};
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends AbstractSettings
- */
-function AdminSettingsScreen()
-{
- AbstractSettings.call(this, [
- AdminMenuViewModel,
- AdminPaneViewModel
- ]);
-}
-
-_.extend(AdminSettingsScreen.prototype, AbstractSettings.prototype);
-
-AdminSettingsScreen.prototype.onShow = function ()
-{
- RL.setTitle('');
-};
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends KnoinAbstractBoot
- */
-function AbstractApp()
-{
- KnoinAbstractBoot.call(this);
-
- this.oSettings = null;
- this.oPlugins = null;
- this.oLocal = null;
- this.oLink = null;
- this.oSubs = {};
-
- this.isLocalAutocomplete = true;
-
- this.popupVisibilityNames = ko.observableArray([]);
-
- this.popupVisibility = ko.computed(function () {
- return 0 < this.popupVisibilityNames().length;
- }, this);
-
- this.iframe = $('').appendTo('body');
-
- $window.on('error', function (oEvent) {
- if (RL && oEvent && oEvent.originalEvent && oEvent.originalEvent.message &&
- -1 === Utils.inArray(oEvent.originalEvent.message, [
- 'Script error.', 'Uncaught Error: Error calling method on NPObject.'
- ]))
- {
- RL.remote().jsError(
- Utils.emptyFunction,
- oEvent.originalEvent.message,
- oEvent.originalEvent.filename,
- oEvent.originalEvent.lineno,
- location && location.toString ? location.toString() : '',
- $html.attr('class'),
- Utils.microtime() - Globals.now
- );
- }
- });
-
- $document.on('keydown', function (oEvent) {
- if (oEvent && oEvent.ctrlKey)
- {
- $html.addClass('rl-ctrl-key-pressed');
- }
- }).on('keyup', function (oEvent) {
- if (oEvent && !oEvent.ctrlKey)
- {
- $html.removeClass('rl-ctrl-key-pressed');
- }
- });
-}
-
-_.extend(AbstractApp.prototype, KnoinAbstractBoot.prototype);
-
-AbstractApp.prototype.oSettings = null;
-AbstractApp.prototype.oPlugins = null;
-AbstractApp.prototype.oLocal = null;
-AbstractApp.prototype.oLink = null;
-AbstractApp.prototype.oSubs = {};
-
-/**
- * @param {string} sLink
- * @return {boolean}
- */
-AbstractApp.prototype.download = function (sLink)
-{
- var
- oLink = null,
- oE = null,
- sUserAgent = navigator.userAgent.toLowerCase()
- ;
-
- if (sUserAgent && (sUserAgent.indexOf('chrome') > -1 || sUserAgent.indexOf('chrome') > -1))
- {
- oLink = document.createElement('a');
- oLink['href'] = sLink;
-
- if (document['createEvent'])
- {
- oE = document['createEvent']('MouseEvents');
- if (oE && oE['initEvent'] && oLink['dispatchEvent'])
- {
- oE['initEvent']('click', true, true);
- oLink['dispatchEvent'](oE);
- return true;
- }
- }
- }
-
- if (Globals.bMobileDevice)
- {
- window.open(sLink, '_self');
- window.focus();
- }
- else
- {
- this.iframe.attr('src', sLink);
-// window.document.location.href = sLink;
- }
-
- return true;
-};
-
-/**
- * @return {LinkBuilder}
- */
-AbstractApp.prototype.link = function ()
-{
- if (null === this.oLink)
- {
- this.oLink = new LinkBuilder();
- }
-
- return this.oLink;
-};
-
-/**
- * @return {LocalStorage}
- */
-AbstractApp.prototype.local = function ()
-{
- if (null === this.oLocal)
- {
- this.oLocal = new LocalStorage();
- }
-
- return this.oLocal;
-};
-
-/**
- * @param {string} sName
- * @return {?}
- */
-AbstractApp.prototype.settingsGet = function (sName)
-{
- if (null === this.oSettings)
- {
- this.oSettings = Utils.isNormal(AppData) ? AppData : {};
- }
-
- return Utils.isUnd(this.oSettings[sName]) ? null : this.oSettings[sName];
-};
-
-/**
- * @param {string} sName
- * @param {?} mValue
- */
-AbstractApp.prototype.settingsSet = function (sName, mValue)
-{
- if (null === this.oSettings)
- {
- this.oSettings = Utils.isNormal(AppData) ? AppData : {};
- }
-
- this.oSettings[sName] = mValue;
-};
-
-AbstractApp.prototype.setTitle = function (sTitle)
-{
- sTitle = ((Utils.isNormal(sTitle) && 0 < sTitle.length) ? sTitle + ' - ' : '') +
- RL.settingsGet('Title') || '';
-
- window.document.title = '_';
- window.document.title = sTitle;
-};
-
-/**
- * @param {boolean=} bLogout = false
- * @param {boolean=} bClose = false
- */
-AbstractApp.prototype.loginAndLogoutReload = function (bLogout, bClose)
-{
- var
- sCustomLogoutLink = Utils.pString(RL.settingsGet('CustomLogoutLink')),
- bInIframe = !!RL.settingsGet('InIframe')
- ;
-
- bLogout = Utils.isUnd(bLogout) ? false : !!bLogout;
- bClose = Utils.isUnd(bClose) ? false : !!bClose;
-
- if (bLogout && bClose && window.close)
- {
- window.close();
- }
-
- if (bLogout && '' !== sCustomLogoutLink && window.location.href !== sCustomLogoutLink)
- {
- _.delay(function () {
- if (bInIframe && window.parent)
- {
- window.parent.location.href = sCustomLogoutLink;
- }
- else
- {
- window.location.href = sCustomLogoutLink;
- }
- }, 100);
- }
- else
- {
- kn.routeOff();
- kn.setHash(RL.link().root(), true);
- kn.routeOff();
-
- _.delay(function () {
- if (bInIframe && window.parent)
- {
- window.parent.location.reload();
- }
- else
- {
- window.location.reload();
- }
- }, 100);
- }
-};
-
-AbstractApp.prototype.historyBack = function ()
-{
- window.history.back();
-};
-
-/**
- * @param {string} sQuery
- * @param {Function} fCallback
- */
-AbstractApp.prototype.getAutocomplete = function (sQuery, fCallback)
-{
- fCallback([], sQuery);
-};
-
-/**
- * @param {string} sName
- * @param {Function} fFunc
- * @param {Object=} oContext
- * @return {AbstractApp}
- */
-AbstractApp.prototype.sub = function (sName, fFunc, oContext)
-{
- if (Utils.isUnd(this.oSubs[sName]))
- {
- this.oSubs[sName] = [];
- }
-
- this.oSubs[sName].push([fFunc, oContext]);
-
- return this;
-};
-
-/**
- * @param {string} sName
- * @param {Array=} aArgs
- * @return {AbstractApp}
- */
-AbstractApp.prototype.pub = function (sName, aArgs)
-{
- Plugins.runHook('rl-pub', [sName, aArgs]);
- if (!Utils.isUnd(this.oSubs[sName]))
- {
- _.each(this.oSubs[sName], function (aItem) {
- if (aItem[0])
- {
- aItem[0].apply(aItem[1] || null, aArgs || []);
- }
- });
- }
-
- return this;
-};
-
-/**
- * @param {string} sName
- * @return {boolean}
- */
-AbstractApp.prototype.capa = function (sName)
-{
- var mCapa = this.settingsGet('Capa');
- return Utils.isArray(mCapa) && Utils.isNormal(sName) && -1 < Utils.inArray(sName, mCapa);
-};
-
-AbstractApp.prototype.bootstart = function ()
-{
- var self = this;
-
- Utils.initOnStartOrLangChange(function () {
- Utils.initNotificationLanguage();
- }, null);
-
- _.delay(function () {
- Utils.windowResize();
- }, 1000);
-
- ssm.addState({
- 'id': 'mobile',
- 'maxWidth': 767,
- 'onEnter': function() {
- $html.addClass('ssm-state-mobile');
- self.pub('ssm.mobile-enter');
- },
- 'onLeave': function() {
- $html.removeClass('ssm-state-mobile');
- self.pub('ssm.mobile-leave');
- }
- });
-
- ssm.addState({
- 'id': 'tablet',
- 'minWidth': 768,
- 'maxWidth': 999,
- 'onEnter': function() {
- $html.addClass('ssm-state-tablet');
- },
- 'onLeave': function() {
- $html.removeClass('ssm-state-tablet');
- }
- });
-
- ssm.addState({
- 'id': 'desktop',
- 'minWidth': 1000,
- 'maxWidth': 1400,
- 'onEnter': function() {
- $html.addClass('ssm-state-desktop');
- },
- 'onLeave': function() {
- $html.removeClass('ssm-state-desktop');
- }
- });
-
- ssm.addState({
- 'id': 'desktop-large',
- 'minWidth': 1400,
- 'onEnter': function() {
- $html.addClass('ssm-state-desktop-large');
- },
- 'onLeave': function() {
- $html.removeClass('ssm-state-desktop-large');
- }
- });
-
- RL.sub('ssm.mobile-enter', function () {
- RL.data().leftPanelDisabled(true);
- });
-
- RL.sub('ssm.mobile-leave', function () {
- RL.data().leftPanelDisabled(false);
- });
-
- RL.data().leftPanelDisabled.subscribe(function (bValue) {
- $html.toggleClass('rl-left-panel-disabled', bValue);
- });
-
- ssm.ready();
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends AbstractApp
- */
-function AdminApp()
-{
- AbstractApp.call(this);
-
- this.oData = null;
- this.oRemote = null;
- this.oCache = null;
-}
-
-_.extend(AdminApp.prototype, AbstractApp.prototype);
-
-AdminApp.prototype.oData = null;
-AdminApp.prototype.oRemote = null;
-AdminApp.prototype.oCache = null;
-
-/**
- * @return {AdminDataStorage}
- */
-AdminApp.prototype.data = function ()
-{
- if (null === this.oData)
- {
- this.oData = new AdminDataStorage();
- }
-
- return this.oData;
-};
-
-/**
- * @return {AdminAjaxRemoteStorage}
- */
-AdminApp.prototype.remote = function ()
-{
- if (null === this.oRemote)
- {
- this.oRemote = new AdminAjaxRemoteStorage();
- }
-
- return this.oRemote;
-};
-
-/**
- * @return {AdminCacheStorage}
- */
-AdminApp.prototype.cache = function ()
-{
- if (null === this.oCache)
- {
- this.oCache = new AdminCacheStorage();
- }
-
- return this.oCache;
-};
-
-AdminApp.prototype.reloadDomainList = function ()
-{
- RL.data().domainsLoading(true);
- RL.remote().domainList(function (sResult, oData) {
- RL.data().domainsLoading(false);
- if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
- {
- var aList = _.map(oData.Result, function (bEnabled, sName) {
- return {
- 'name': sName,
- 'disabled': ko.observable(!bEnabled),
- 'deleteAccess': ko.observable(false)
- };
- }, this);
-
- RL.data().domains(aList);
- }
- });
-};
-
-AdminApp.prototype.reloadPluginList = function ()
-{
- RL.data().pluginsLoading(true);
- RL.remote().pluginList(function (sResult, oData) {
- RL.data().pluginsLoading(false);
- if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
- {
- var aList = _.map(oData.Result, function (oItem) {
- return {
- 'name': oItem['Name'],
- 'disabled': ko.observable(!oItem['Enabled']),
- 'configured': ko.observable(!!oItem['Configured'])
- };
- }, this);
-
- RL.data().plugins(aList);
- }
- });
-};
-
-AdminApp.prototype.reloadPackagesList = function ()
-{
- RL.data().packagesLoading(true);
- RL.data().packagesReal(true);
-
- RL.remote().packagesList(function (sResult, oData) {
-
- RL.data().packagesLoading(false);
-
- if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
- {
- RL.data().packagesReal(!!oData.Result.Real);
- RL.data().packagesMainUpdatable(!!oData.Result.MainUpdatable);
-
- var
- aList = [],
- aLoading = {}
- ;
-
- _.each(RL.data().packages(), function (oItem) {
- if (oItem && oItem['loading']())
- {
- aLoading[oItem['file']] = oItem;
- }
- });
-
- if (Utils.isArray(oData.Result.List))
- {
- aList = _.compact(_.map(oData.Result.List, function (oItem) {
- if (oItem)
- {
- oItem['loading'] = ko.observable(!Utils.isUnd(aLoading[oItem['file']]));
- return 'core' === oItem['type'] && !oItem['canBeInstalled'] ? null : oItem;
- }
- return null;
- }));
- }
-
- RL.data().packages(aList);
- }
- else
- {
- RL.data().packagesReal(false);
- }
- });
-};
-
-AdminApp.prototype.updateCoreData = function ()
-{
- var oRainData = RL.data();
-
- oRainData.coreUpdating(true);
- RL.remote().updateCoreData(function (sResult, oData) {
-
- oRainData.coreUpdating(false);
- oRainData.coreRemoteVersion('');
- oRainData.coreRemoteRelease('');
- oRainData.coreVersionCompare(-2);
-
- if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
- {
- oRainData.coreReal(true);
- window.location.reload();
- }
- else
- {
- oRainData.coreReal(false);
- }
- });
-
-};
-
-AdminApp.prototype.reloadCoreData = function ()
-{
- var oRainData = RL.data();
-
- oRainData.coreChecking(true);
- oRainData.coreReal(true);
-
- RL.remote().coreData(function (sResult, oData) {
-
- oRainData.coreChecking(false);
-
- if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
- {
- oRainData.coreReal(!!oData.Result.Real);
- oRainData.coreUpdatable(!!oData.Result.Updatable);
- oRainData.coreAccess(!!oData.Result.Access);
- oRainData.coreRemoteVersion(oData.Result.RemoteVersion || '');
- oRainData.coreRemoteRelease(oData.Result.RemoteRelease || '');
- oRainData.coreVersionCompare(Utils.pInt(oData.Result.VersionCompare));
- }
- else
- {
- oRainData.coreReal(false);
- oRainData.coreRemoteVersion('');
- oRainData.coreRemoteRelease('');
- oRainData.coreVersionCompare(-2);
- }
- });
-};
-
-/**
- *
- * @param {boolean=} bForce = false
- */
-AdminApp.prototype.reloadLicensing = function (bForce)
-{
- bForce = Utils.isUnd(bForce) ? false : !!bForce;
-
- RL.data().licensingProcess(true);
- RL.data().licenseError('');
-
- RL.remote().licensing(function (sResult, oData) {
- RL.data().licensingProcess(false);
- if (Enums.StorageResultType.Success === sResult && oData && oData.Result && Utils.isNormal(oData.Result['Expired']))
- {
- RL.data().licenseValid(true);
- RL.data().licenseExpired(Utils.pInt(oData.Result['Expired']));
- RL.data().licenseError('');
-
- RL.data().licensing(true);
- }
- else
- {
- if (oData && oData.ErrorCode && -1 < Utils.inArray(Utils.pInt(oData.ErrorCode), [
- Enums.Notification.LicensingServerIsUnavailable,
- Enums.Notification.LicensingExpired
- ]))
- {
- RL.data().licenseError(Utils.getNotification(Utils.pInt(oData.ErrorCode)));
- RL.data().licensing(true);
- }
- else
- {
- if (Enums.StorageResultType.Abort === sResult)
- {
- RL.data().licenseError(Utils.getNotification(Enums.Notification.LicensingServerIsUnavailable));
- RL.data().licensing(true);
+ window.parent.location.href = sCustomLogoutLink;
}
else
{
- RL.data().licensing(false);
+ window.location.href = sCustomLogoutLink;
}
- }
- }
- }, bForce);
-};
-
-AdminApp.prototype.bootstart = function ()
-{
- AbstractApp.prototype.bootstart.call(this);
-
- RL.data().populateDataOnStart();
-
- kn.hideLoading();
-
- if (!RL.settingsGet('AllowAdminPanel'))
- {
- kn.routeOff();
- kn.setHash(RL.link().root(), true);
- kn.routeOff();
-
- _.defer(function () {
- window.location.href = '/';
- });
- }
- else
- {
-// Utils.removeSettingsViewModel(AdminAbout);
-
- if (!RL.capa(Enums.Capa.Prem))
- {
- Utils.removeSettingsViewModel(AdminBranding);
- }
-
- if (!!RL.settingsGet('Auth'))
- {
-// TODO
-// if (!RL.settingsGet('AllowPackages') && AdminPackages)
-// {
-// Utils.disableSettingsViewModel(AdminPackages);
-// }
-
- kn.startScreens([AdminSettingsScreen]);
+ }, 100);
}
else
{
- kn.startScreens([AdminLoginScreen]);
- }
- }
-
- if (window.SimplePace)
- {
- window.SimplePace.set(100);
- }
-};
-
-/**
- * @type {AdminApp}
- */
-RL = new AdminApp();
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-$html.addClass(Globals.bMobileDevice ? 'mobile' : 'no-mobile');
-
-$window.keydown(Utils.killCtrlAandS).keyup(Utils.killCtrlAandS);
-$window.unload(function () {
- Globals.bUnload = true;
-});
-
-$html.on('click.dropdown.data-api', function () {
- Utils.detectDropdownVisibility();
-});
-
-// export
-window['rl'] = window['rl'] || {};
-window['rl']['addHook'] = Plugins.addHook;
-window['rl']['settingsGet'] = Plugins.mainSettingsGet;
-window['rl']['remoteRequest'] = Plugins.remoteRequest;
-window['rl']['pluginSettingsGet'] = Plugins.settingsGet;
-window['rl']['addSettingsViewModel'] = Utils.addSettingsViewModel;
-window['rl']['createCommand'] = Utils.createCommand;
-
-window['rl']['EmailModel'] = EmailModel;
-window['rl']['Enums'] = Enums;
-
-window['__RLBOOT'] = function (fCall) {
-
- // boot
- $(function () {
-
- if (window['rainloopTEMPLATES'] && window['rainloopTEMPLATES'][0])
- {
- $('#rl-templates').html(window['rainloopTEMPLATES'][0]);
+ kn.routeOff();
+ kn.setHash(LinkBuilder.root(), true);
+ kn.routeOff();
_.delay(function () {
- window['rainloopAppData'] = {};
- window['rainloopI18N'] = {};
- window['rainloopTEMPLATES'] = {};
+ if (bInIframe && window.parent)
+ {
+ window.parent.location.reload();
+ }
+ else
+ {
+ window.location.reload();
+ }
+ }, 100);
+ }
+ };
- kn.setBoot(RL).bootstart();
- $html.removeClass('no-js rl-booted-trigger').addClass('rl-booted');
-
- }, 50);
+ AbstractApp.prototype.historyBack = function ()
+ {
+ window.history.back();
+ };
+
+ /**
+ * @param {string} sQuery
+ * @param {Function} fCallback
+ */
+ AbstractApp.prototype.getAutocomplete = function (sQuery, fCallback)
+ {
+ fCallback([], sQuery);
+ };
+
+ /**
+ * @param {string} sName
+ * @param {Function} fFunc
+ * @param {Object=} oContext
+ * @return {AbstractApp}
+ */
+ AbstractApp.prototype.sub = function (sName, fFunc, oContext)
+ {
+ if (Utils.isUnd(this.oSubs[sName]))
+ {
+ this.oSubs[sName] = [];
+ }
+
+ this.oSubs[sName].push([fFunc, oContext]);
+
+ return this;
+ };
+
+ /**
+ * @param {string} sName
+ * @param {Array=} aArgs
+ * @return {AbstractApp}
+ */
+ AbstractApp.prototype.pub = function (sName, aArgs)
+ {
+ Plugins.runHook('rl-pub', [sName, aArgs]);
+ if (!Utils.isUnd(this.oSubs[sName]))
+ {
+ _.each(this.oSubs[sName], function (aItem) {
+ if (aItem[0])
+ {
+ aItem[0].apply(aItem[1] || null, aArgs || []);
+ }
+ });
+ }
+
+ return this;
+ };
+
+ /**
+ * @param {string} sName
+ * @return {boolean}
+ */
+ AbstractApp.prototype.capa = function (sName)
+ {
+ var mCapa = this.settingsGet('Capa');
+ return Utils.isArray(mCapa) && Utils.isNormal(sName) && -1 < Utils.inArray(sName, mCapa);
+ };
+
+ AbstractApp.prototype.bootstart = function (Data)
+ {
+ var
+ self = this,
+ ssm = require('../External/ssm.js')
+ ;
+
+ Utils.initOnStartOrLangChange(function () {
+ Utils.initNotificationLanguage();
+ }, null);
+
+ _.delay(function () {
+ Utils.windowResize();
+ }, 1000);
+
+ ssm.addState({
+ 'id': 'mobile',
+ 'maxWidth': 767,
+ 'onEnter': function() {
+ $html.addClass('ssm-state-mobile');
+ self.pub('ssm.mobile-enter');
+ },
+ 'onLeave': function() {
+ $html.removeClass('ssm-state-mobile');
+ self.pub('ssm.mobile-leave');
+ }
+ });
+
+ ssm.addState({
+ 'id': 'tablet',
+ 'minWidth': 768,
+ 'maxWidth': 999,
+ 'onEnter': function() {
+ $html.addClass('ssm-state-tablet');
+ },
+ 'onLeave': function() {
+ $html.removeClass('ssm-state-tablet');
+ }
+ });
+
+ ssm.addState({
+ 'id': 'desktop',
+ 'minWidth': 1000,
+ 'maxWidth': 1400,
+ 'onEnter': function() {
+ $html.addClass('ssm-state-desktop');
+ },
+ 'onLeave': function() {
+ $html.removeClass('ssm-state-desktop');
+ }
+ });
+
+ ssm.addState({
+ 'id': 'desktop-large',
+ 'minWidth': 1400,
+ 'onEnter': function() {
+ $html.addClass('ssm-state-desktop-large');
+ },
+ 'onLeave': function() {
+ $html.removeClass('ssm-state-desktop-large');
+ }
+ });
+
+ this.sub('ssm.mobile-enter', function () {
+ Data.leftPanelDisabled(true);
+ });
+
+ this.sub('ssm.mobile-leave', function () {
+ Data.leftPanelDisabled(false);
+ });
+
+ Data.leftPanelDisabled.subscribe(function (bValue) {
+ $html.toggleClass('rl-left-panel-disabled', bValue);
+ });
+
+ ssm.ready();
+ };
+
+ module.exports = AbstractApp;
+
+}(module));
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ ko = require('../External/ko.js'),
+ _ = require('../External/underscore.js'),
+ window = require('../External/window.js'),
+
+ Enums = require('../Common/Enums.js'),
+ Utils = require('../Common/Utils.js'),
+ LinkBuilder = require('../Common/LinkBuilder.js'),
+
+ kn = require('../Knoin/Knoin.js'),
+
+ Data = require('../Storages/AdminDataStorage.js'),
+ Remote = require('../Storages/AdminAjaxRemoteStorage.js'),
+
+ AbstractApp = require('./AbstractApp.js')
+ ;
+
+ /**
+ * @constructor
+ * @extends AbstractApp
+ */
+ function AdminApp()
+ {
+ AbstractApp.call(this, Remote);
+
+ this.oData = null;
+ this.oRemote = null;
+ this.oCache = null;
+ }
+
+ _.extend(AdminApp.prototype, AbstractApp.prototype);
+
+ AdminApp.prototype.oData = null;
+ AdminApp.prototype.oRemote = null;
+ AdminApp.prototype.oCache = null;
+
+ /**
+ * @return {AdminDataStorage}
+ */
+ AdminApp.prototype.data = function ()
+ {
+ if (null === this.oData)
+ {
+ this.oData = new AdminDataStorage(); // TODO cjs
+ }
+
+ return this.oData;
+ };
+
+ /**
+ * @return {AdminAjaxRemoteStorage}
+ */
+ AdminApp.prototype.remote = function ()
+ {
+ if (null === this.oRemote)
+ {
+ this.oRemote = new AdminAjaxRemoteStorage(); // TODO cjs
+ }
+
+ return this.oRemote;
+ };
+
+ AdminApp.prototype.reloadDomainList = function ()
+ {
+ // TODO cjs
+ Data.domainsLoading(true);
+ Remote.domainList(function (sResult, oData) {
+ Data.domainsLoading(false);
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ {
+ var aList = _.map(oData.Result, function (bEnabled, sName) {
+ return {
+ 'name': sName,
+ 'disabled': ko.observable(!bEnabled),
+ 'deleteAccess': ko.observable(false)
+ };
+ }, this);
+
+ Data.domains(aList);
+ }
+ });
+ };
+
+ AdminApp.prototype.reloadPluginList = function ()
+ {
+ // TODO cjs
+ Data.pluginsLoading(true);
+ Remote.pluginList(function (sResult, oData) {
+ Data.pluginsLoading(false);
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ {
+ var aList = _.map(oData.Result, function (oItem) {
+ return {
+ 'name': oItem['Name'],
+ 'disabled': ko.observable(!oItem['Enabled']),
+ 'configured': ko.observable(!!oItem['Configured'])
+ };
+ }, this);
+
+ Data.plugins(aList);
+ }
+ });
+ };
+
+ AdminApp.prototype.reloadPackagesList = function ()
+ {
+ // TODO cjs
+ Data.packagesLoading(true);
+ Data.packagesReal(true);
+
+ Remote.packagesList(function (sResult, oData) {
+
+ Data.packagesLoading(false);
+
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ {
+ Data.packagesReal(!!oData.Result.Real);
+ Data.packagesMainUpdatable(!!oData.Result.MainUpdatable);
+
+ var
+ aList = [],
+ aLoading = {}
+ ;
+
+ _.each(Data.packages(), function (oItem) {
+ if (oItem && oItem['loading']())
+ {
+ aLoading[oItem['file']] = oItem;
+ }
+ });
+
+ if (Utils.isArray(oData.Result.List))
+ {
+ aList = _.compact(_.map(oData.Result.List, function (oItem) {
+ if (oItem)
+ {
+ oItem['loading'] = ko.observable(!Utils.isUnd(aLoading[oItem['file']]));
+ return 'core' === oItem['type'] && !oItem['canBeInstalled'] ? null : oItem;
+ }
+ return null;
+ }));
+ }
+
+ Data.packages(aList);
+ }
+ else
+ {
+ Data.packagesReal(false);
+ }
+ });
+ };
+
+ AdminApp.prototype.updateCoreData = function ()
+ {
+ Data.coreUpdating(true);
+ Remote.updateCoreData(function (sResult, oData) {
+
+ Data.coreUpdating(false);
+ Data.coreRemoteVersion('');
+ Data.coreRemoteRelease('');
+ Data.coreVersionCompare(-2);
+
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ {
+ Data.coreReal(true);
+ window.location.reload();
+ }
+ else
+ {
+ Data.coreReal(false);
+ }
+ });
+
+ };
+
+ AdminApp.prototype.reloadCoreData = function ()
+ {
+ Data.coreChecking(true);
+ Data.coreReal(true);
+
+ Remote.coreData(function (sResult, oData) {
+
+ Data.coreChecking(false);
+
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ {
+ Data.coreReal(!!oData.Result.Real);
+ Data.coreUpdatable(!!oData.Result.Updatable);
+ Data.coreAccess(!!oData.Result.Access);
+ Data.coreRemoteVersion(oData.Result.RemoteVersion || '');
+ Data.coreRemoteRelease(oData.Result.RemoteRelease || '');
+ Data.coreVersionCompare(Utils.pInt(oData.Result.VersionCompare));
+ }
+ else
+ {
+ Data.coreReal(false);
+ Data.coreRemoteVersion('');
+ Data.coreRemoteRelease('');
+ Data.coreVersionCompare(-2);
+ }
+ });
+ };
+
+ /**
+ *
+ * @param {boolean=} bForce = false
+ */
+ AdminApp.prototype.reloadLicensing = function (bForce)
+ {
+ bForce = Utils.isUnd(bForce) ? false : !!bForce;
+
+ // TODO cjs
+ Data.licensingProcess(true);
+ Data.licenseError('');
+
+ Remote.licensing(function (sResult, oData) {
+ Data.licensingProcess(false);
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result && Utils.isNormal(oData.Result['Expired']))
+ {
+ Data.licenseValid(true);
+ Data.licenseExpired(Utils.pInt(oData.Result['Expired']));
+ Data.licenseError('');
+
+ Data.licensing(true);
+ }
+ else
+ {
+ if (oData && oData.ErrorCode && -1 < Utils.inArray(Utils.pInt(oData.ErrorCode), [
+ Enums.Notification.LicensingServerIsUnavailable,
+ Enums.Notification.LicensingExpired
+ ]))
+ {
+ Data.licenseError(Utils.getNotification(Utils.pInt(oData.ErrorCode)));
+ Data.licensing(true);
+ }
+ else
+ {
+ if (Enums.StorageResultType.Abort === sResult)
+ {
+ Data.licenseError(Utils.getNotification(Enums.Notification.LicensingServerIsUnavailable));
+ Data.licensing(true);
+ }
+ else
+ {
+ Data.licensing(false);
+ }
+ }
+ }
+ }, bForce);
+ };
+
+ AdminApp.prototype.bootstart = function ()
+ {
+ AbstractApp.prototype.bootstart.call(this, Data);
+
+ Data.populateDataOnStart();
+
+ kn.hideLoading();
+
+ if (!RL.settingsGet('AllowAdminPanel'))
+ {
+ kn.routeOff();
+ kn.setHash(LinkBuilder.root(), true);
+ kn.routeOff();
+
+ _.defer(function () {
+ window.location.href = '/';
+ });
}
else
{
- fCall(false);
+ // kn.removeSettingsViewModel(AdminAbout);
+
+ if (!RL.capa(Enums.Capa.Prem))
+ {
+ kn.removeSettingsViewModel(AdminBranding);
+ }
+
+ if (!!RL.settingsGet('Auth'))
+ {
+ // TODO
+ // if (!RL.settingsGet('AllowPackages') && AdminPackages)
+ // {
+ // kn.disableSettingsViewModel(AdminPackages);
+ // }
+
+ kn.startScreens([AdminSettingsScreen]);
+ }
+ else
+ {
+ kn.startScreens([AdminLoginScreen]);
+ }
}
- window['__RLBOOT'] = null;
- });
-};
+ if (window.SimplePace)
+ {
+ window.SimplePace.set(100);
+ }
+ };
+ module.exports = new AdminApp();
+
+}(module));
}(window, jQuery, ko, crossroads, hasher, _));
\ No newline at end of file
diff --git a/rainloop/v/0.0.0/static/js/app.js b/rainloop/v/0.0.0/static/js/app.js
index a47a2226a..01b564d4b 100644
--- a/rainloop/v/0.0.0/static/js/app.js
+++ b/rainloop/v/0.0.0/static/js/app.js
@@ -1,3064 +1,6688 @@
-/*! RainLoop Webmail Main Module (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-(function (window, $, ko, crossroads, hasher, moment, Jua, _, ifvisible, key) {
-
-'use strict';
-
-var
- /**
- * @type {Object}
- */
- Consts = {},
-
- /**
- * @type {Object}
- */
- Enums = {},
-
- /**
- * @type {Object}
- */
- NotificationI18N = {},
-
- /**
- * @type {Object.}
- */
- Utils = {},
-
- /**
- * @type {Object.}
- */
- Plugins = {},
-
- /**
- * @type {Object.}
- */
- Base64 = {},
-
- /**
- * @type {Object}
- */
- Globals = {},
-
- /**
- * @type {Object}
- */
- ViewModels = {
- 'settings': [],
- 'settings-removed': [],
- 'settings-disabled': []
- },
-
- /**
- * @type {Array}
- */
- BootstrapDropdowns = [],
-
- /**
- * @type {*}
- */
- kn = null,
-
- /**
- * @type {Object}
- */
- AppData = window['rainloopAppData'] || {},
-
- /**
- * @type {Object}
- */
- I18n = window['rainloopI18N'] || {},
-
- $html = $('html'),
-
-// $body = $('body'),
-
- $window = $(window),
-
- $document = $(window.document),
-
- NotificationClass = window.Notification && window.Notification.requestPermission ? window.Notification : null
-;
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/*jshint onevar: false*/
-/**
- * @type {?RainLoopApp}
- */
-var
- RL = null,
-
- $proxyDiv = $('')
-;
-/*jshint onevar: true*/
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @type {?}
- */
-Globals.now = (new Date()).getTime();
-
-/**
- * @type {?}
- */
-Globals.momentTrigger = ko.observable(true);
-
-/**
- * @type {?}
- */
-Globals.dropdownVisibility = ko.observable(false).extend({'rateLimit': 0});
-
-/**
- * @type {?}
- */
-Globals.tooltipTrigger = ko.observable(false).extend({'rateLimit': 0});
-
-/**
- * @type {?}
- */
-Globals.langChangeTrigger = ko.observable(true);
-
-/**
- * @type {number}
- */
-Globals.iAjaxErrorCount = 0;
-
-/**
- * @type {number}
- */
-Globals.iTokenErrorCount = 0;
-
-/**
- * @type {number}
- */
-Globals.iMessageBodyCacheCount = 0;
-
-/**
- * @type {boolean}
- */
-Globals.bUnload = false;
-
-/**
- * @type {string}
- */
-Globals.sUserAgent = (navigator.userAgent || '').toLowerCase();
-
-/**
- * @type {boolean}
- */
-Globals.bIsiOSDevice = -1 < Globals.sUserAgent.indexOf('iphone') || -1 < Globals.sUserAgent.indexOf('ipod') || -1 < Globals.sUserAgent.indexOf('ipad');
-
-/**
- * @type {boolean}
- */
-Globals.bIsAndroidDevice = -1 < Globals.sUserAgent.indexOf('android');
-
-/**
- * @type {boolean}
- */
-Globals.bMobileDevice = Globals.bIsiOSDevice || Globals.bIsAndroidDevice;
-
-/**
- * @type {boolean}
- */
-Globals.bDisableNanoScroll = Globals.bMobileDevice;
-
-/**
- * @type {boolean}
- */
-Globals.bAllowPdfPreview = !Globals.bMobileDevice;
-
-/**
- * @type {boolean}
- */
-Globals.bAnimationSupported = !Globals.bMobileDevice && $html.hasClass('csstransitions');
-
-/**
- * @type {boolean}
- */
-Globals.bXMLHttpRequestSupported = !!window.XMLHttpRequest;
-
-/**
- * @type {string}
- */
-Globals.sAnimationType = '';
-
-/**
- * @type {Object}
- */
-Globals.oHtmlEditorDefaultConfig = {
- 'title': false,
- 'stylesSet': false,
- 'customConfig': '',
- 'contentsCss': '',
- 'toolbarGroups': [
- {name: 'spec'},
- {name: 'styles'},
- {name: 'basicstyles', groups: ['basicstyles', 'cleanup']},
- {name: 'colors'},
- {name: 'paragraph', groups: ['list', 'indent', 'blocks', 'align']},
- {name: 'links'},
- {name: 'insert'},
- {name: 'others'}
-// {name: 'document', groups: ['mode', 'document', 'doctools']}
- ],
-
- 'removePlugins': 'contextmenu', //blockquote
- 'removeButtons': 'Format,Undo,Redo,Cut,Copy,Paste,Anchor,Strike,Subscript,Superscript,Image,SelectAll',
- 'removeDialogTabs': 'link:advanced;link:target;image:advanced;images:advanced',
-
- 'extraPlugins': 'plain',
-
- 'allowedContent': true,
- 'autoParagraph': false,
-
- 'font_defaultLabel': 'Arial',
- 'fontSize_defaultLabel': '13',
- 'fontSize_sizes': '10/10px;12/12px;13/13px;14/14px;16/16px;18/18px;20/20px;24/24px;28/28px;36/36px;48/48px'
-};
-
-/**
- * @type {Object}
- */
-Globals.oHtmlEditorLangsMap = {
- 'de': 'de',
- 'es': 'es',
- 'fr': 'fr',
- 'hu': 'hu',
- 'is': 'is',
- 'it': 'it',
- 'ko': 'ko',
- 'ko-kr': 'ko',
- 'lv': 'lv',
- 'nl': 'nl',
- 'no': 'no',
- 'pl': 'pl',
- 'pt': 'pt',
- 'pt-pt': 'pt',
- 'pt-br': 'pt-br',
- 'ru': 'ru',
- 'ro': 'ro',
- 'zh': 'zh',
- 'zh-cn': 'zh-cn'
-};
-
-if (Globals.bAllowPdfPreview && navigator && navigator.mimeTypes)
-{
- Globals.bAllowPdfPreview = !!_.find(navigator.mimeTypes, function (oType) {
- return oType && 'application/pdf' === oType.type;
- });
-}
+(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o').appendTo('body');
- sValue = oRsa.encrypt(Utils.fakeMd5() + ':' + sValue + ':' + Utils.fakeMd5());
- if (false !== sValue)
- {
- return 'rsa:' + sHash + ':' + sValue;
- }
+ $window.on('error', function (oEvent) {
+ if (oEvent && oEvent.originalEvent && oEvent.originalEvent.message &&
+ -1 === Utils.inArray(oEvent.originalEvent.message, [
+ 'Script error.', 'Uncaught Error: Error calling method on NPObject.'
+ ]))
+ {
+ Remote.jsError(
+ Utils.emptyFunction,
+ oEvent.originalEvent.message,
+ oEvent.originalEvent.filename,
+ oEvent.originalEvent.lineno,
+ window.location && window.location.toString ? window.location.toString() : '',
+ $html.attr('class'),
+ Utils.microtime() - Globals.now
+ );
+ }
+ });
+
+ $doc.on('keydown', function (oEvent) {
+ if (oEvent && oEvent.ctrlKey)
+ {
+ $html.addClass('rl-ctrl-key-pressed');
+ }
+ }).on('keyup', function (oEvent) {
+ if (oEvent && !oEvent.ctrlKey)
+ {
+ $html.removeClass('rl-ctrl-key-pressed');
+ }
+ });
}
- return false;
-};
+ _.extend(AbstractApp.prototype, KnoinAbstractBoot.prototype);
-Utils.rsaEncode.supported = !!(window.crypto && window.crypto.getRandomValues && window.RSAKey);
-
-/**
- * @param {string} sPath
- * @param {*=} oObject
- * @param {Object=} oObjectToExportTo
- */
-Utils.exportPath = function (sPath, oObject, oObjectToExportTo)
-{
- var
- part = null,
- parts = sPath.split('.'),
- cur = oObjectToExportTo || window
- ;
-
- for (; parts.length && (part = parts.shift());)
+ AbstractApp.prototype.remote = function ()
{
- if (!parts.length && !Utils.isUnd(oObject))
+ return null;
+ };
+
+ AbstractApp.prototype.data = function ()
+ {
+ return null;
+ };
+
+ AbstractApp.prototype.setupSettings = function ()
+ {
+ return true;
+ };
+
+ /**
+ * @param {string} sLink
+ * @return {boolean}
+ */
+ AbstractApp.prototype.download = function (sLink)
+ {
+ var
+ oE = null,
+ oLink = null,
+ sUserAgent = window.navigator.userAgent.toLowerCase()
+ ;
+
+ if (sUserAgent && (sUserAgent.indexOf('chrome') > -1 || sUserAgent.indexOf('chrome') > -1))
{
- cur[part] = oObject;
+ oLink = window.document.createElement('a');
+ oLink['href'] = sLink;
+
+ if (window.document['createEvent'])
+ {
+ oE = window.document['createEvent']('MouseEvents');
+ if (oE && oE['initEvent'] && oLink['dispatchEvent'])
+ {
+ oE['initEvent']('click', true, true);
+ oLink['dispatchEvent'](oE);
+ return true;
+ }
+ }
}
- else if (cur[part])
+
+ if (Globals.bMobileDevice)
{
- cur = cur[part];
+ window.open(sLink, '_self');
+ window.focus();
}
else
{
- cur = cur[part] = {};
- }
- }
-};
-
-/**
- * @param {Object} oObject
- * @param {string} sName
- * @param {*} mValue
- */
-Utils.pImport = function (oObject, sName, mValue)
-{
- oObject[sName] = mValue;
-};
-
-/**
- * @param {Object} oObject
- * @param {string} sName
- * @param {*} mDefault
- * @return {*}
- */
-Utils.pExport = function (oObject, sName, mDefault)
-{
- return Utils.isUnd(oObject[sName]) ? mDefault : oObject[sName];
-};
-
-/**
- * @param {string} sText
- * @return {string}
- */
-Utils.encodeHtml = function (sText)
-{
- return Utils.isNormal(sText) ? sText.toString()
- .replace(/&/g, '&').replace(//g, '>')
- .replace(/"/g, '"').replace(/'/g, ''') : '';
-};
-
-/**
- * @param {string} sText
- * @param {number=} iLen
- * @return {string}
- */
-Utils.splitPlainText = function (sText, iLen)
-{
- var
- sPrefix = '',
- sSubText = '',
- sResult = sText,
- iSpacePos = 0,
- iNewLinePos = 0
- ;
-
- iLen = Utils.isUnd(iLen) ? 100 : iLen;
-
- while (sResult.length > iLen)
- {
- sSubText = sResult.substring(0, iLen);
- iSpacePos = sSubText.lastIndexOf(' ');
- iNewLinePos = sSubText.lastIndexOf('\n');
-
- if (-1 !== iNewLinePos)
- {
- iSpacePos = iNewLinePos;
+ this.iframe.attr('src', sLink);
+ // window.document.location.href = sLink;
}
- if (-1 === iSpacePos)
- {
- iSpacePos = iLen;
- }
-
- sPrefix += sSubText.substring(0, iSpacePos) + '\n';
- sResult = sResult.substring(iSpacePos + 1);
- }
-
- return sPrefix + sResult;
-};
-
-Utils.timeOutAction = (function () {
-
- var
- oTimeOuts = {}
- ;
-
- return function (sAction, fFunction, iTimeOut)
- {
- if (Utils.isUnd(oTimeOuts[sAction]))
- {
- oTimeOuts[sAction] = 0;
- }
-
- window.clearTimeout(oTimeOuts[sAction]);
- oTimeOuts[sAction] = window.setTimeout(fFunction, iTimeOut);
+ return true;
};
-}());
-Utils.timeOutActionSecond = (function () {
-
- var
- oTimeOuts = {}
- ;
-
- return function (sAction, fFunction, iTimeOut)
+ AbstractApp.prototype.setTitle = function (sTitle)
{
- if (!oTimeOuts[sAction])
+ sTitle = ((Utils.isNormal(sTitle) && 0 < sTitle.length) ? sTitle + ' - ' : '') +
+ AppSettings.settingsGet('Title') || '';
+
+ window.document.title = '_';
+ window.document.title = sTitle;
+ };
+
+ /**
+ * @param {boolean=} bLogout = false
+ * @param {boolean=} bClose = false
+ */
+ AbstractApp.prototype.loginAndLogoutReload = function (bLogout, bClose)
+ {
+ var
+ sCustomLogoutLink = Utils.pString(AppSettings.settingsGet('CustomLogoutLink')),
+ bInIframe = !!AppSettings.settingsGet('InIframe')
+ ;
+
+ bLogout = Utils.isUnd(bLogout) ? false : !!bLogout;
+ bClose = Utils.isUnd(bClose) ? false : !!bClose;
+
+ if (bLogout && bClose && window.close)
{
- oTimeOuts[sAction] = window.setTimeout(function () {
- fFunction();
- oTimeOuts[sAction] = 0;
- }, iTimeOut);
+ window.close();
+ }
+
+ if (bLogout && '' !== sCustomLogoutLink && window.location.href !== sCustomLogoutLink)
+ {
+ _.delay(function () {
+ if (bInIframe && window.parent)
+ {
+ window.parent.location.href = sCustomLogoutLink;
+ }
+ else
+ {
+ window.location.href = sCustomLogoutLink;
+ }
+ }, 100);
+ }
+ else
+ {
+ kn.routeOff();
+ kn.setHash(LinkBuilder.root(), true);
+ kn.routeOff();
+
+ _.delay(function () {
+ if (bInIframe && window.parent)
+ {
+ window.parent.location.reload();
+ }
+ else
+ {
+ window.location.reload();
+ }
+ }, 100);
}
};
-}());
-Utils.audio = (function () {
+ AbstractApp.prototype.historyBack = function ()
+ {
+ window.history.back();
+ };
+
+ /**
+ * @param {string} sQuery
+ * @param {Function} fCallback
+ */
+ AbstractApp.prototype.getAutocomplete = function (sQuery, fCallback)
+ {
+ fCallback([], sQuery);
+ };
+
+ AbstractApp.prototype.bootstart = function ()
+ {
+ Events.pub('rl.bootstart');
+
+ var ssm = require('../External/ssm.js');
+
+ Utils.initOnStartOrLangChange(function () {
+ Utils.initNotificationLanguage();
+ }, null);
+
+ _.delay(function () {
+ Utils.windowResize();
+ }, 1000);
+
+ ssm.addState({
+ 'id': 'mobile',
+ 'maxWidth': 767,
+ 'onEnter': function() {
+ $html.addClass('ssm-state-mobile');
+ Events.pub('ssm.mobile-enter');
+ },
+ 'onLeave': function() {
+ $html.removeClass('ssm-state-mobile');
+ Events.pub('ssm.mobile-leave');
+ }
+ });
+
+ ssm.addState({
+ 'id': 'tablet',
+ 'minWidth': 768,
+ 'maxWidth': 999,
+ 'onEnter': function() {
+ $html.addClass('ssm-state-tablet');
+ },
+ 'onLeave': function() {
+ $html.removeClass('ssm-state-tablet');
+ }
+ });
+
+ ssm.addState({
+ 'id': 'desktop',
+ 'minWidth': 1000,
+ 'maxWidth': 1400,
+ 'onEnter': function() {
+ $html.addClass('ssm-state-desktop');
+ },
+ 'onLeave': function() {
+ $html.removeClass('ssm-state-desktop');
+ }
+ });
+
+ ssm.addState({
+ 'id': 'desktop-large',
+ 'minWidth': 1400,
+ 'onEnter': function() {
+ $html.addClass('ssm-state-desktop-large');
+ },
+ 'onLeave': function() {
+ $html.removeClass('ssm-state-desktop-large');
+ }
+ });
+
+ Events.sub('ssm.mobile-enter', function () {
+ Globals.leftPanelDisabled(true);
+ });
+
+ Events.sub('ssm.mobile-leave', function () {
+ Globals.leftPanelDisabled(false);
+ });
+
+ Globals.leftPanelDisabled.subscribe(function (bValue) {
+ $html.toggleClass('rl-left-panel-disabled', bValue);
+ });
+
+ ssm.ready();
+ };
+
+ module.exports = AbstractApp;
+
+}(module));
+},{"../Common/Events.js":8,"../Common/Globals.js":9,"../Common/LinkBuilder.js":10,"../Common/Utils.js":14,"../External/$doc.js":16,"../External/$html.js":17,"../External/$window.js":18,"../External/jquery.js":26,"../External/ssm.js":30,"../External/underscore.js":31,"../External/window.js":32,"../Knoin/Knoin.js":33,"../Knoin/KnoinAbstractBoot.js":34,"../Storages/AppSettings.js":61}],3:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
var
- oAudio = false
+ window = require('../External/window.js'),
+ $ = require('../External/jquery.js'),
+ $window = require('../External/$window.js'),
+ $html = require('../External/$html.js'),
+
+ Globals = require('../Common/Globals.js'),
+ Plugins = require('../Common/Plugins.js'),
+ Utils = require('../Common/Utils.js')
;
- return function (sMp3File, sOggFile) {
+ module.exports = function (RL) {
- if (false === oAudio)
+ Globals.__RL = RL;
+
+ RL.setupSettings();
+
+ Plugins.__boot = RL;
+ Plugins.__remote = RL.remote();
+ Plugins.__data = RL.data();
+
+ $html.addClass(Globals.bMobileDevice ? 'mobile' : 'no-mobile');
+
+ $window.keydown(Utils.killCtrlAandS).keyup(Utils.killCtrlAandS);
+ $window.unload(function () {
+ Globals.bUnload = true;
+ });
+
+ $html.on('click.dropdown.data-api', function () {
+ Utils.detectDropdownVisibility();
+ });
+
+ // export
+ window['rl'] = window['rl'] || {};
+ window['rl']['addHook'] = Plugins.addHook;
+ window['rl']['settingsGet'] = Plugins.mainSettingsGet;
+ window['rl']['remoteRequest'] = Plugins.remoteRequest;
+ window['rl']['pluginSettingsGet'] = Plugins.settingsGet;
+ window['rl']['createCommand'] = Utils.createCommand;
+
+ window['rl']['EmailModel'] = require('../Models/EmailModel.js');
+ window['rl']['Enums'] = require('../Common/Enums.js');
+
+ window['__RLBOOT'] = function (fCall) {
+
+ // boot
+ $(function () {
+
+ if (window['rainloopTEMPLATES'] && window['rainloopTEMPLATES'][0])
+ {
+ $('#rl-templates').html(window['rainloopTEMPLATES'][0]);
+
+ _.delay(function () {
+
+ RL.bootstart();
+ $html.removeClass('no-js rl-booted-trigger').addClass('rl-booted');
+
+ }, 50);
+ }
+ else
+ {
+ fCall(false);
+ }
+
+ window['__RLBOOT'] = null;
+ });
+ };
+
+ };
+
+}(module));
+},{"../Common/Enums.js":7,"../Common/Globals.js":9,"../Common/Plugins.js":12,"../Common/Utils.js":14,"../External/$html.js":17,"../External/$window.js":18,"../External/jquery.js":26,"../External/window.js":32,"../Models/EmailModel.js":39}],4:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ window = require('../External/window.js'),
+ $ = require('../External/jquery.js'),
+ _ = require('../External/underscore.js'),
+ moment = require('../External/moment.js'),
+
+ Enums = require('../Common/Enums.js'),
+ Globals = require('../Common/Globals.js'),
+ Consts = require('../Common/Consts.js'),
+ Plugins = require('../Common/Plugins.js'),
+ Utils = require('../Common/Utils.js'),
+ LinkBuilder = require('../Common/LinkBuilder.js'),
+ Events = require('../Common/Events.js'),
+
+ kn = require('../Knoin/Knoin.js'),
+
+ LocalStorage = require('../Storages/LocalStorage.js'),
+ AppSettings = require('../Storages/AppSettings.js'),
+ Data = require('../Storages/WebMailDataStorage.js'),
+ Cache = require('../Storages/WebMailCacheStorage.js'),
+ Remote = require('../Storages/WebMailAjaxRemoteStorage.js'),
+
+ FolderModel = require('../Models/FolderModel.js'),
+ MessageModel = require('../Models/MessageModel.js'),
+ AccountModel = require('../Models/AccountModel.js'),
+ IdentityModel = require('../Models/IdentityModel.js'),
+
+ PopupsFolderSystemViewModel = require('../ViewModels/Popups/PopupsAskViewModel.js'),
+ PopupsAskViewModel = require('../ViewModels/Popups/PopupsAskViewModel.js'),
+ PopupsComposeViewModel = require('../ViewModels/Popups/PopupsComposeViewModel.js'),
+
+ MailBoxScreen = require('../Screens/MailBoxScreen.js'),
+ SettingsScreen = require('../Screens/SettingsScreen.js'),
+ LoginScreen = require('../Screens/LoginScreen.js'),
+
+ AbstractApp = require('./AbstractApp.js')
+ ;
+
+ /**
+ * @constructor
+ * @extends AbstractApp
+ */
+ function RainLoopApp()
+ {
+ AbstractApp.call(this, Remote);
+
+ this.oMoveCache = {};
+
+ this.quotaDebounce = _.debounce(this.quota, 1000 * 30);
+ this.moveOrDeleteResponseHelper = _.bind(this.moveOrDeleteResponseHelper, this);
+
+ this.messagesMoveTrigger = _.debounce(this.messagesMoveTrigger, 500);
+
+ var self = this;
+
+ window.setInterval(function () {
+ Events.pub('interval.30s');
+ }, 30000);
+
+ window.setInterval(function () {
+ Events.pub('interval.1m');
+ }, 60000);
+
+ window.setInterval(function () {
+ Events.pub('interval.2m');
+ }, 60000 * 2);
+
+ window.setInterval(function () {
+ Events.pub('interval.3m');
+ }, 60000 * 3);
+
+ window.setInterval(function () {
+ Events.pub('interval.5m');
+ }, 60000 * 5);
+
+ window.setInterval(function () {
+ Events.pub('interval.10m');
+ }, 60000 * 10);
+
+ window.setTimeout(function () {
+ window.setInterval(function () {
+ Events.pub('interval.10m-after5m');
+ }, 60000 * 10);
+ }, 60000 * 5);
+
+ $.wakeUp(function () {
+ Remote.jsVersion(function (sResult, oData) {
+ if (Enums.StorageResultType.Success === sResult && oData && !oData.Result)
+ {
+ if (window.parent && !!self.settingsGet('InIframe'))
+ {
+ window.parent.location.reload();
+ }
+ else
+ {
+ window.location.reload();
+ }
+ }
+ }, self.settingsGet('Version'));
+ }, {}, 60 * 60 * 1000);
+
+
+ this.socialUsers = _.bind(this.socialUsers, this);
+ }
+
+ _.extend(RainLoopApp.prototype, AbstractApp.prototype);
+
+ RainLoopApp.prototype.remote = function ()
+ {
+ return Remote;
+ };
+
+ RainLoopApp.prototype.data = function ()
+ {
+ return Data;
+ };
+
+ RainLoopApp.prototype.setupSettings = function ()
+ {
+ var
+ SettingsGeneral = require('../Settings/SettingsGeneral.js'),
+ SettingsContacts = require('../Settings/SettingsContacts.js'),
+ SettingsAccounts = require('../Settings/SettingsAccounts.js'),
+ SettingsIdentity = require('../Settings/SettingsIdentity.js'),
+ SettingsIdentities = require('../Settings/SettingsIdentities.js'),
+ SettingsFilters = require('../Settings/SettingsFilters.js'),
+ SettingsSecurity = require('../Settings/SettingsSecurity.js'),
+ SettingsSocial = require('../Settings/SettingsSocial.js'),
+ SettingsChangePassword = require('../Settings/SettingsChangePassword.js'),
+ SettingsFolders = require('../Settings/SettingsFolders.js'),
+ SettingsThemes = require('../Settings/SettingsThemes.js'),
+ SettingsOpenPGP = require('../Settings/SettingsOpenPGP.js')
+ ;
+
+ kn.addSettingsViewModel(SettingsGeneral,
+ 'SettingsGeneral', 'SETTINGS_LABELS/LABEL_GENERAL_NAME', 'general', true);
+
+ if (AppSettings.settingsGet('ContactsIsAllowed'))
{
- if (Globals.bIsiOSDevice)
+ kn.addSettingsViewModel(SettingsContacts,
+ 'SettingsContacts', 'SETTINGS_LABELS/LABEL_CONTACTS_NAME', 'contacts');
+ }
+
+ if (AppSettings.capa(Enums.Capa.AdditionalAccounts))
+ {
+ kn.addSettingsViewModel(SettingsAccounts,
+ 'SettingsAccounts', 'SETTINGS_LABELS/LABEL_ACCOUNTS_NAME', 'accounts');
+ }
+
+ if (AppSettings.capa(Enums.Capa.AdditionalIdentities))
+ {
+ kn.addSettingsViewModel(SettingsIdentities,
+ 'SettingsIdentities', 'SETTINGS_LABELS/LABEL_IDENTITIES_NAME', 'identities');
+ }
+ else
+ {
+ kn.addSettingsViewModel(SettingsIdentity,
+ 'SettingsIdentity', 'SETTINGS_LABELS/LABEL_IDENTITY_NAME', 'identity');
+ }
+
+ if (AppSettings.capa(Enums.Capa.Filters))
+ {
+ kn.addSettingsViewModel(SettingsFilters,
+ 'SettingsFilters', 'SETTINGS_LABELS/LABEL_FILTERS_NAME', 'filters');
+ }
+
+ if (AppSettings.capa(Enums.Capa.TwoFactor))
+ {
+ kn.addSettingsViewModel(SettingsSecurity,
+ 'SettingsSecurity', 'SETTINGS_LABELS/LABEL_SECURITY_NAME', 'security');
+ }
+
+ if (!AppSettings.settingsGet('AllowGoogleSocial') &&
+ !AppSettings.settingsGet('AllowFacebookSocial') &&
+ !AppSettings.settingsGet('AllowTwitterSocial'))
+ {
+ kn.addSettingsViewModel(SettingsSocial,
+ 'SettingsSocial', 'SETTINGS_LABELS/LABEL_SOCIAL_NAME', 'social');
+ }
+
+ if (AppSettings.settingsGet('ChangePasswordIsAllowed'))
+ {
+ kn.addSettingsViewModel(SettingsChangePassword,
+ 'SettingsChangePassword', 'SETTINGS_LABELS/LABEL_CHANGE_PASSWORD_NAME', 'change-password');
+ }
+
+ kn.addSettingsViewModel(SettingsFolders,
+ 'SettingsFolders', 'SETTINGS_LABELS/LABEL_FOLDERS_NAME', 'folders');
+
+ if (AppSettings.capa(Enums.Capa.Themes))
+ {
+ kn.addSettingsViewModel(SettingsThemes,
+ 'SettingsThemes', 'SETTINGS_LABELS/LABEL_THEMES_NAME', 'themes');
+ }
+
+ if (AppSettings.capa(Enums.Capa.OpenPGP))
+ {
+ kn.addSettingsViewModel(SettingsOpenPGP,
+ 'SettingsOpenPGP', 'SETTINGS_LABELS/LABEL_OPEN_PGP_NAME', 'openpgp');
+ }
+
+ return true;
+ };
+
+ RainLoopApp.prototype.reloadFlagsCurrentMessageListAndMessageFromCache = function ()
+ {
+ _.each(Data.messageList(), function (oMessage) {
+ Cache.initMessageFlagsFromCache(oMessage);
+ });
+
+ Cache.initMessageFlagsFromCache(Data.message());
+ };
+
+ /**
+ * @param {boolean=} bDropPagePosition = false
+ * @param {boolean=} bDropCurrenFolderCache = false
+ */
+ RainLoopApp.prototype.reloadMessageList = function (bDropPagePosition, bDropCurrenFolderCache)
+ {
+ var
+ self = this,
+ iOffset = (Data.messageListPage() - 1) * Data.messagesPerPage()
+ ;
+
+ if (Utils.isUnd(bDropCurrenFolderCache) ? false : !!bDropCurrenFolderCache)
+ {
+ Cache.setFolderHash(Data.currentFolderFullNameRaw(), '');
+ }
+
+ if (Utils.isUnd(bDropPagePosition) ? false : !!bDropPagePosition)
+ {
+ Data.messageListPage(1);
+ iOffset = 0;
+ }
+
+ Data.messageListLoading(true);
+ Remote.messageList(function (sResult, oData, bCached) {
+
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
{
- oAudio = null;
+ Data.messageListError('');
+ Data.messageListLoading(false);
+ self.setMessageList(oData, bCached);
+ }
+ else if (Enums.StorageResultType.Unload === sResult)
+ {
+ Data.messageListError('');
+ Data.messageListLoading(false);
+ }
+ else if (Enums.StorageResultType.Abort !== sResult)
+ {
+ Data.messageList([]);
+ Data.messageListLoading(false);
+ Data.messageListError(oData && oData.ErrorCode ?
+ Utils.getNotification(oData.ErrorCode) : Utils.i18n('NOTIFICATIONS/CANT_GET_MESSAGE_LIST')
+ );
+ }
+
+ }, Data.currentFolderFullNameRaw(), iOffset, Data.messagesPerPage(), Data.messageListSearch());
+ };
+
+ RainLoopApp.prototype.recacheInboxMessageList = function ()
+ {
+ Remote.messageList(Utils.emptyFunction, 'INBOX', 0, Data.messagesPerPage(), '', true);
+ };
+
+ RainLoopApp.prototype.reloadMessageListHelper = function (bEmptyList)
+ {
+ self.reloadMessageList(bEmptyList);
+ };
+
+ /**
+ * @param {Function} fResultFunc
+ * @returns {boolean}
+ */
+ RainLoopApp.prototype.contactsSync = function (fResultFunc)
+ {
+ var oContacts = Data.contacts;
+ if (oContacts.importing() || oContacts.syncing() || !Data.enableContactsSync() || !Data.allowContactsSync())
+ {
+ return false;
+ }
+
+ oContacts.syncing(true);
+
+ Remote.contactsSync(function (sResult, oData) {
+
+ oContacts.syncing(false);
+
+ if (fResultFunc)
+ {
+ fResultFunc(sResult, oData);
+ }
+ });
+
+ return true;
+ };
+
+ RainLoopApp.prototype.messagesMoveTrigger = function ()
+ {
+ var
+ self = this,
+ sSpamFolder = Data.spamFolder()
+ ;
+
+ _.each(this.oMoveCache, function (oItem) {
+
+ var
+ bSpam = sSpamFolder === oItem['To'],
+ bHam = !bSpam && sSpamFolder === oItem['From'] && 'INBOX' === oItem['To']
+ ;
+
+ Remote.messagesMove(self.moveOrDeleteResponseHelper, oItem['From'], oItem['To'], oItem['Uid'],
+ bSpam ? 'SPAM' : (bHam ? 'HAM' : ''));
+ });
+
+ this.oMoveCache = {};
+ };
+
+ RainLoopApp.prototype.messagesMoveHelper = function (sFromFolderFullNameRaw, sToFolderFullNameRaw, aUidForMove)
+ {
+ var sH = '$$' + sFromFolderFullNameRaw + '$$' + sToFolderFullNameRaw + '$$';
+ if (!this.oMoveCache[sH])
+ {
+ this.oMoveCache[sH] = {
+ 'From': sFromFolderFullNameRaw,
+ 'To': sToFolderFullNameRaw,
+ 'Uid': []
+ };
+ }
+
+ this.oMoveCache[sH]['Uid'] = _.union(this.oMoveCache[sH]['Uid'], aUidForMove);
+ this.messagesMoveTrigger();
+ };
+
+ RainLoopApp.prototype.messagesCopyHelper = function (sFromFolderFullNameRaw, sToFolderFullNameRaw, aUidForCopy)
+ {
+ Remote.messagesCopy(
+ this.moveOrDeleteResponseHelper,
+ sFromFolderFullNameRaw,
+ sToFolderFullNameRaw,
+ aUidForCopy
+ );
+ };
+
+ RainLoopApp.prototype.messagesDeleteHelper = function (sFromFolderFullNameRaw, aUidForRemove)
+ {
+ Remote.messagesDelete(
+ this.moveOrDeleteResponseHelper,
+ sFromFolderFullNameRaw,
+ aUidForRemove
+ );
+ };
+
+ RainLoopApp.prototype.moveOrDeleteResponseHelper = function (sResult, oData)
+ {
+ if (Enums.StorageResultType.Success === sResult && Data.currentFolder())
+ {
+ if (oData && Utils.isArray(oData.Result) && 2 === oData.Result.length)
+ {
+ Cache.setFolderHash(oData.Result[0], oData.Result[1]);
}
else
+ {
+ Cache.setFolderHash(Data.currentFolderFullNameRaw(), '');
+
+ if (oData && -1 < Utils.inArray(oData.ErrorCode,
+ [Enums.Notification.CantMoveMessage, Enums.Notification.CantCopyMessage]))
+ {
+ window.alert(Utils.getNotification(oData.ErrorCode));
+ }
+ }
+
+ this.reloadMessageListHelper(0 === Data.messageList().length);
+ this.quotaDebounce();
+ }
+ };
+
+ /**
+ * @param {string} sFromFolderFullNameRaw
+ * @param {Array} aUidForRemove
+ */
+ RainLoopApp.prototype.deleteMessagesFromFolderWithoutCheck = function (sFromFolderFullNameRaw, aUidForRemove)
+ {
+ this.messagesDeleteHelper(sFromFolderFullNameRaw, aUidForRemove);
+ Data.removeMessagesFromList(sFromFolderFullNameRaw, aUidForRemove);
+ };
+
+ /**
+ * @param {number} iDeleteType
+ * @param {string} sFromFolderFullNameRaw
+ * @param {Array} aUidForRemove
+ * @param {boolean=} bUseFolder = true
+ */
+ RainLoopApp.prototype.deleteMessagesFromFolder = function (iDeleteType, sFromFolderFullNameRaw, aUidForRemove, bUseFolder)
+ {
+ var
+ self = this,
+ oMoveFolder = null,
+ nSetSystemFoldersNotification = null
+ ;
+
+ switch (iDeleteType)
+ {
+ case Enums.FolderType.Spam:
+ oMoveFolder = Cache.getFolderFromCacheList(Data.spamFolder());
+ nSetSystemFoldersNotification = Enums.SetSystemFoldersNotification.Spam;
+ break;
+ case Enums.FolderType.NotSpam:
+ oMoveFolder = Cache.getFolderFromCacheList('INBOX');
+ break;
+ case Enums.FolderType.Trash:
+ oMoveFolder = Cache.getFolderFromCacheList(Data.trashFolder());
+ nSetSystemFoldersNotification = Enums.SetSystemFoldersNotification.Trash;
+ break;
+ case Enums.FolderType.Archive:
+ oMoveFolder = Cache.getFolderFromCacheList(Data.archiveFolder());
+ nSetSystemFoldersNotification = Enums.SetSystemFoldersNotification.Archive;
+ break;
+ }
+
+ bUseFolder = Utils.isUnd(bUseFolder) ? true : !!bUseFolder;
+ if (bUseFolder)
+ {
+ if ((Enums.FolderType.Spam === iDeleteType && Consts.Values.UnuseOptionValue === Data.spamFolder()) ||
+ (Enums.FolderType.Trash === iDeleteType && Consts.Values.UnuseOptionValue === Data.trashFolder()) ||
+ (Enums.FolderType.Archive === iDeleteType && Consts.Values.UnuseOptionValue === Data.archiveFolder()))
+ {
+ bUseFolder = false;
+ }
+ }
+
+ if (!oMoveFolder && bUseFolder)
+ {
+ kn.showScreenPopup(PopupsFolderSystemViewModel, [nSetSystemFoldersNotification]);
+ }
+ else if (!bUseFolder || (Enums.FolderType.Trash === iDeleteType &&
+ (sFromFolderFullNameRaw === Data.spamFolder() || sFromFolderFullNameRaw === Data.trashFolder())))
+ {
+ kn.showScreenPopup(PopupsAskViewModel, [Utils.i18n('POPUPS_ASK/DESC_WANT_DELETE_MESSAGES'), function () {
+
+ self.messagesDeleteHelper(sFromFolderFullNameRaw, aUidForRemove);
+ Data.removeMessagesFromList(sFromFolderFullNameRaw, aUidForRemove);
+
+ }]);
+ }
+ else if (oMoveFolder)
+ {
+ this.messagesMoveHelper(sFromFolderFullNameRaw, oMoveFolder.fullNameRaw, aUidForRemove);
+ Data.removeMessagesFromList(sFromFolderFullNameRaw, aUidForRemove, oMoveFolder.fullNameRaw);
+ }
+ };
+
+ /**
+ * @param {string} sFromFolderFullNameRaw
+ * @param {Array} aUidForMove
+ * @param {string} sToFolderFullNameRaw
+ * @param {boolean=} bCopy = false
+ */
+ RainLoopApp.prototype.moveMessagesToFolder = function (sFromFolderFullNameRaw, aUidForMove, sToFolderFullNameRaw, bCopy)
+ {
+ if (sFromFolderFullNameRaw !== sToFolderFullNameRaw && Utils.isArray(aUidForMove) && 0 < aUidForMove.length)
+ {
+ var
+ oFromFolder = Cache.getFolderFromCacheList(sFromFolderFullNameRaw),
+ oToFolder = Cache.getFolderFromCacheList(sToFolderFullNameRaw)
+ ;
+
+ if (oFromFolder && oToFolder)
+ {
+ if (Utils.isUnd(bCopy) ? false : !!bCopy)
+ {
+ this.messagesCopyHelper(oFromFolder.fullNameRaw, oToFolder.fullNameRaw, aUidForMove);
+ }
+ else
+ {
+ this.messagesMoveHelper(oFromFolder.fullNameRaw, oToFolder.fullNameRaw, aUidForMove);
+ }
+
+ Data.removeMessagesFromList(oFromFolder.fullNameRaw, aUidForMove, oToFolder.fullNameRaw, bCopy);
+ return true;
+ }
+ }
+
+ return false;
+ };
+
+ /**
+ * @param {Function=} fCallback
+ */
+ RainLoopApp.prototype.folders = function (fCallback)
+ {
+ Data.foldersLoading(true);
+ Remote.folders(_.bind(function (sResult, oData) {
+
+ Data.foldersLoading(false);
+ if (Enums.StorageResultType.Success === sResult)
+ {
+ this.setFolders(oData);
+ if (fCallback)
+ {
+ fCallback(true);
+ }
+ }
+ else
+ {
+ if (fCallback)
+ {
+ fCallback(false);
+ }
+ }
+ }, this));
+ };
+
+ RainLoopApp.prototype.reloadOpenPgpKeys = function ()
+ {
+ if (Data.capaOpenPGP())
+ {
+ var
+ aKeys = [],
+ oEmail = new EmailModel(),
+ oOpenpgpKeyring = Data.openpgpKeyring,
+ oOpenpgpKeys = oOpenpgpKeyring ? oOpenpgpKeyring.getAllKeys() : []
+ ;
+
+ _.each(oOpenpgpKeys, function (oItem, iIndex) {
+ if (oItem && oItem.primaryKey)
+ {
+ var
+
+ oPrimaryUser = oItem.getPrimaryUser(),
+ sUser = (oPrimaryUser && oPrimaryUser.user) ? oPrimaryUser.user.userId.userid
+ : (oItem.users && oItem.users[0] ? oItem.users[0].userId.userid : '')
+ ;
+
+ oEmail.clear();
+ oEmail.mailsoParse(sUser);
+
+ if (oEmail.validate())
+ {
+ aKeys.push(new OpenPgpKeyModel(
+ iIndex,
+ oItem.primaryKey.getFingerprint(),
+ oItem.primaryKey.getKeyId().toHex().toLowerCase(),
+ sUser,
+ oEmail.email,
+ oItem.isPrivate(),
+ oItem.armor())
+ );
+ }
+ }
+ });
+
+ Data.openpgpkeys(aKeys);
+ }
+ };
+
+ RainLoopApp.prototype.accountsAndIdentities = function ()
+ {
+ Data.accountsLoading(true);
+ Data.identitiesLoading(true);
+
+ Remote.accountsAndIdentities(function (sResult, oData) {
+
+ Data.accountsLoading(false);
+ Data.identitiesLoading(false);
+
+ if (Enums.StorageResultType.Success === sResult && oData.Result)
{
var
- bCanPlayMp3 = false,
- bCanPlayOgg = false,
- oAudioLocal = window.Audio ? new window.Audio() : null
+ sParentEmail = AppSettings.settingsGet('ParentEmail'),
+ sAccountEmail = Data.accountEmail()
;
- if (oAudioLocal && oAudioLocal.canPlayType && oAudioLocal.play)
+ sParentEmail = '' === sParentEmail ? sAccountEmail : sParentEmail;
+
+ if (Utils.isArray(oData.Result['Accounts']))
{
- bCanPlayMp3 = '' !== oAudioLocal.canPlayType('audio/mpeg; codecs="mp3"');
- if (!bCanPlayMp3)
+ Data.accounts(_.map(oData.Result['Accounts'], function (sValue) {
+ return new AccountModel(sValue, sValue !== sParentEmail);
+ }));
+ }
+
+ if (Utils.isArray(oData.Result['Identities']))
+ {
+ Data.identities(_.map(oData.Result['Identities'], function (oIdentityData) {
+
+ var
+ sId = Utils.pString(oIdentityData['Id']),
+ sEmail = Utils.pString(oIdentityData['Email']),
+ oIdentity = new IdentityModel(sId, sEmail, sId !== sAccountEmail)
+ ;
+
+ oIdentity.name(Utils.pString(oIdentityData['Name']));
+ oIdentity.replyTo(Utils.pString(oIdentityData['ReplyTo']));
+ oIdentity.bcc(Utils.pString(oIdentityData['Bcc']));
+
+ return oIdentity;
+ }));
+ }
+ }
+ });
+ };
+
+ RainLoopApp.prototype.quota = function ()
+ {
+ Remote.quota(function (sResult, oData) {
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result &&
+ Utils.isArray(oData.Result) && 1 < oData.Result.length &&
+ Utils.isPosNumeric(oData.Result[0], true) && Utils.isPosNumeric(oData.Result[1], true))
+ {
+ Data.userQuota(Utils.pInt(oData.Result[1]) * 1024);
+ Data.userUsageSize(Utils.pInt(oData.Result[0]) * 1024);
+ }
+ });
+ };
+
+ /**
+ * @param {string} sFolder
+ * @param {Array=} aList = []
+ */
+ RainLoopApp.prototype.folderInformation = function (sFolder, aList)
+ {
+ if ('' !== Utils.trim(sFolder))
+ {
+ var self = this;
+ Remote.folderInformation(function (sResult, oData) {
+ if (Enums.StorageResultType.Success === sResult)
+ {
+ if (oData && oData.Result && oData.Result.Hash && oData.Result.Folder)
{
- bCanPlayOgg = '' !== oAudioLocal.canPlayType('audio/ogg; codecs="vorbis"');
+ var
+ iUtc = moment().unix(),
+ sHash = Cache.getFolderHash(oData.Result.Folder),
+ oFolder = Cache.getFolderFromCacheList(oData.Result.Folder),
+ bCheck = false,
+ sUid = '',
+ aList = [],
+ bUnreadCountChange = false,
+ oFlags = null
+ ;
+
+ if (oFolder)
+ {
+ oFolder.interval = iUtc;
+
+ if (oData.Result.Hash)
+ {
+ Cache.setFolderHash(oData.Result.Folder, oData.Result.Hash);
+ }
+
+ if (Utils.isNormal(oData.Result.MessageCount))
+ {
+ oFolder.messageCountAll(oData.Result.MessageCount);
+ }
+
+ if (Utils.isNormal(oData.Result.MessageUnseenCount))
+ {
+ if (Utils.pInt(oFolder.messageCountUnread()) !== Utils.pInt(oData.Result.MessageUnseenCount))
+ {
+ bUnreadCountChange = true;
+ }
+
+ oFolder.messageCountUnread(oData.Result.MessageUnseenCount);
+ }
+
+ if (bUnreadCountChange)
+ {
+ Cache.clearMessageFlagsFromCacheByFolder(oFolder.fullNameRaw);
+ }
+
+ if (oData.Result.Flags)
+ {
+ for (sUid in oData.Result.Flags)
+ {
+ if (oData.Result.Flags.hasOwnProperty(sUid))
+ {
+ bCheck = true;
+ oFlags = oData.Result.Flags[sUid];
+ Cache.storeMessageFlagsToCacheByFolderAndUid(oFolder.fullNameRaw, sUid.toString(), [
+ !oFlags['IsSeen'], !!oFlags['IsFlagged'], !!oFlags['IsAnswered'], !!oFlags['IsForwarded'], !!oFlags['IsReadReceipt']
+ ]);
+ }
+ }
+
+ if (bCheck)
+ {
+ self.reloadFlagsCurrentMessageListAndMessageFromCache();
+ }
+ }
+
+ Data.initUidNextAndNewMessages(oFolder.fullNameRaw, oData.Result.UidNext, oData.Result.NewMessages);
+
+ if (oData.Result.Hash !== sHash || '' === sHash)
+ {
+ if (oFolder.fullNameRaw === Data.currentFolderFullNameRaw())
+ {
+ self.reloadMessageList();
+ }
+ else if ('INBOX' === oFolder.fullNameRaw)
+ {
+ self.recacheInboxMessageList();
+ }
+ }
+ else if (bUnreadCountChange)
+ {
+ if (oFolder.fullNameRaw === Data.currentFolderFullNameRaw())
+ {
+ aList = Data.messageList();
+ if (Utils.isNonEmptyArray(aList))
+ {
+ self.folderInformation(oFolder.fullNameRaw, aList);
+ }
+ }
+ }
+ }
+ }
+ }
+ }, sFolder, aList);
+ }
+ };
+
+ /**
+ * @param {boolean=} bBoot = false
+ */
+ RainLoopApp.prototype.folderInformationMultiply = function (bBoot)
+ {
+ bBoot = Utils.isUnd(bBoot) ? false : !!bBoot;
+
+ var
+ self = this,
+ iUtc = moment().unix(),
+ aFolders = Data.getNextFolderNames(bBoot)
+ ;
+
+ if (Utils.isNonEmptyArray(aFolders))
+ {
+ Remote.folderInformationMultiply(function (sResult, oData) {
+ if (Enums.StorageResultType.Success === sResult)
+ {
+ if (oData && oData.Result && oData.Result.List && Utils.isNonEmptyArray(oData.Result.List))
+ {
+ _.each(oData.Result.List, function (oItem) {
+
+ var
+ aList = [],
+ sHash = Cache.getFolderHash(oItem.Folder),
+ oFolder = Cache.getFolderFromCacheList(oItem.Folder),
+ bUnreadCountChange = false
+ ;
+
+ if (oFolder)
+ {
+ oFolder.interval = iUtc;
+
+ if (oItem.Hash)
+ {
+ Cache.setFolderHash(oItem.Folder, oItem.Hash);
+ }
+
+ if (Utils.isNormal(oItem.MessageCount))
+ {
+ oFolder.messageCountAll(oItem.MessageCount);
+ }
+
+ if (Utils.isNormal(oItem.MessageUnseenCount))
+ {
+ if (Utils.pInt(oFolder.messageCountUnread()) !== Utils.pInt(oItem.MessageUnseenCount))
+ {
+ bUnreadCountChange = true;
+ }
+
+ oFolder.messageCountUnread(oItem.MessageUnseenCount);
+ }
+
+ if (bUnreadCountChange)
+ {
+ Cache.clearMessageFlagsFromCacheByFolder(oFolder.fullNameRaw);
+ }
+
+ if (oItem.Hash !== sHash || '' === sHash)
+ {
+ if (oFolder.fullNameRaw === Data.currentFolderFullNameRaw())
+ {
+ self.reloadMessageList();
+ }
+ }
+ else if (bUnreadCountChange)
+ {
+ if (oFolder.fullNameRaw === Data.currentFolderFullNameRaw())
+ {
+ aList = Data.messageList();
+ if (Utils.isNonEmptyArray(aList))
+ {
+ self.folderInformation(oFolder.fullNameRaw, aList);
+ }
+ }
+ }
+ }
+ });
+
+ if (bBoot)
+ {
+ self.folderInformationMultiply(true);
+ }
+ }
+ }
+ }, aFolders);
+ }
+ };
+
+ RainLoopApp.prototype.setMessageSeen = function (oMessage)
+ {
+ if (oMessage.unseen())
+ {
+ oMessage.unseen(false);
+
+ var oFolder = Cache.getFolderFromCacheList(oMessage.folderFullNameRaw);
+ if (oFolder)
+ {
+ oFolder.messageCountUnread(0 <= oFolder.messageCountUnread() - 1 ?
+ oFolder.messageCountUnread() - 1 : 0);
+ }
+
+ Cache.storeMessageFlagsToCache(oMessage);
+ this.reloadFlagsCurrentMessageListAndMessageFromCache();
+ }
+
+ Remote.messageSetSeen(Utils.emptyFunction, oMessage.folderFullNameRaw, [oMessage.uid], true);
+ };
+
+ RainLoopApp.prototype.googleConnect = function ()
+ {
+ window.open(LinkBuilder.socialGoogle(), 'Google', 'left=200,top=100,width=650,height=600,menubar=no,status=no,resizable=yes,scrollbars=yes');
+ };
+
+ RainLoopApp.prototype.twitterConnect = function ()
+ {
+ window.open(LinkBuilder.socialTwitter(), 'Twitter', 'left=200,top=100,width=650,height=350,menubar=no,status=no,resizable=yes,scrollbars=yes');
+ };
+
+ RainLoopApp.prototype.facebookConnect = function ()
+ {
+ window.open(LinkBuilder.socialFacebook(), 'Facebook', 'left=200,top=100,width=650,height=335,menubar=no,status=no,resizable=yes,scrollbars=yes');
+ };
+
+ /**
+ * @param {boolean=} bFireAllActions
+ */
+ RainLoopApp.prototype.socialUsers = function (bFireAllActions)
+ {
+ if (bFireAllActions)
+ {
+ Data.googleActions(true);
+ Data.facebookActions(true);
+ Data.twitterActions(true);
+ }
+
+ Remote.socialUsers(function (sResult, oData) {
+
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ {
+ Data.googleUserName(oData.Result['Google'] || '');
+ Data.facebookUserName(oData.Result['Facebook'] || '');
+ Data.twitterUserName(oData.Result['Twitter'] || '');
+ }
+ else
+ {
+ Data.googleUserName('');
+ Data.facebookUserName('');
+ Data.twitterUserName('');
+ }
+
+ Data.googleLoggined('' !== Data.googleUserName());
+ Data.facebookLoggined('' !== Data.facebookUserName());
+ Data.twitterLoggined('' !== Data.twitterUserName());
+
+ Data.googleActions(false);
+ Data.facebookActions(false);
+ Data.twitterActions(false);
+ });
+ };
+
+ RainLoopApp.prototype.googleDisconnect = function ()
+ {
+ Data.googleActions(true);
+ Remote.googleDisconnect(this.socialUsers);
+ };
+
+ RainLoopApp.prototype.facebookDisconnect = function ()
+ {
+ Data.facebookActions(true);
+ Remote.facebookDisconnect(this.socialUsers);
+ };
+
+ RainLoopApp.prototype.twitterDisconnect = function ()
+ {
+ Data.twitterActions(true);
+ Remote.twitterDisconnect(this.socialUsers);
+ };
+
+ /**
+ * @param {string} sQuery
+ * @param {Function} fCallback
+ */
+ RainLoopApp.prototype.getAutocomplete = function (sQuery, fCallback)
+ {
+ var
+ aData = []
+ ;
+
+ Remote.suggestions(function (sResult, oData) {
+ if (Enums.StorageResultType.Success === sResult && oData && Utils.isArray(oData.Result))
+ {
+ aData = _.map(oData.Result, function (aItem) {
+ return aItem && aItem[0] ? new EmailModel(aItem[0], aItem[1]) : null;
+ });
+
+ fCallback(_.compact(aData));
+ }
+ else if (Enums.StorageResultType.Abort !== sResult)
+ {
+ fCallback([]);
+ }
+
+ }, sQuery);
+ };
+
+ /**
+ * @param {string} sQuery
+ * @param {Function} fCallback
+ */
+ RainLoopApp.prototype.getContactTagsAutocomplete = function (sQuery, fCallback)
+ {
+ fCallback(_.filter(Data.contactTags(), function (oContactTag) {
+ return oContactTag && oContactTag.filterHelper(sQuery);
+ }));
+ };
+
+ RainLoopApp.prototype.setMessageList = function (oData, bCached)
+ {
+ if (oData && oData.Result && 'Collection/MessageCollection' === oData.Result['@Object'] &&
+ oData.Result['@Collection'] && Utils.isArray(oData.Result['@Collection']))
+ {
+ var
+ mLastCollapsedThreadUids = null,
+ iIndex = 0,
+ iLen = 0,
+ iCount = 0,
+ iOffset = 0,
+ aList = [],
+ iUtc = moment().unix(),
+ aStaticList = Data.staticMessageList,
+ oJsonMessage = null,
+ oMessage = null,
+ oFolder = null,
+ iNewCount = 0,
+ bUnreadCountChange = false
+ ;
+
+ iCount = Utils.pInt(oData.Result.MessageResultCount);
+ iOffset = Utils.pInt(oData.Result.Offset);
+
+ if (Utils.isNonEmptyArray(oData.Result.LastCollapsedThreadUids))
+ {
+ mLastCollapsedThreadUids = oData.Result.LastCollapsedThreadUids;
+ }
+
+ oFolder = Cache.getFolderFromCacheList(
+ Utils.isNormal(oData.Result.Folder) ? oData.Result.Folder : '');
+
+ if (oFolder && !bCached)
+ {
+ oFolder.interval = iUtc;
+
+ Cache.setFolderHash(oData.Result.Folder, oData.Result.FolderHash);
+
+ if (Utils.isNormal(oData.Result.MessageCount))
+ {
+ oFolder.messageCountAll(oData.Result.MessageCount);
+ }
+
+ if (Utils.isNormal(oData.Result.MessageUnseenCount))
+ {
+ if (Utils.pInt(oFolder.messageCountUnread()) !== Utils.pInt(oData.Result.MessageUnseenCount))
+ {
+ bUnreadCountChange = true;
}
- if (bCanPlayMp3 || bCanPlayOgg)
+ oFolder.messageCountUnread(oData.Result.MessageUnseenCount);
+ }
+
+ Data.initUidNextAndNewMessages(oFolder.fullNameRaw, oData.Result.UidNext, oData.Result.NewMessages);
+ }
+
+ if (bUnreadCountChange && oFolder)
+ {
+ Cache.clearMessageFlagsFromCacheByFolder(oFolder.fullNameRaw);
+ }
+
+ for (iIndex = 0, iLen = oData.Result['@Collection'].length; iIndex < iLen; iIndex++)
+ {
+ oJsonMessage = oData.Result['@Collection'][iIndex];
+ if (oJsonMessage && 'Object/Message' === oJsonMessage['@Object'])
+ {
+ oMessage = aStaticList[iIndex];
+ if (!oMessage || !oMessage.initByJson(oJsonMessage))
{
- oAudio = oAudioLocal;
- oAudio.preload = 'none';
- oAudio.loop = false;
- oAudio.autoplay = false;
- oAudio.muted = false;
- oAudio.src = bCanPlayMp3 ? sMp3File : sOggFile;
+ oMessage = MessageModel.newInstanceFromJson(oJsonMessage);
+ }
+
+ if (oMessage)
+ {
+ if (Cache.hasNewMessageAndRemoveFromCache(oMessage.folderFullNameRaw, oMessage.uid) && 5 >= iNewCount)
+ {
+ iNewCount++;
+ oMessage.newForAnimation(true);
+ }
+
+ oMessage.deleted(false);
+
+ if (bCached)
+ {
+ Cache.initMessageFlagsFromCache(oMessage);
+ }
+ else
+ {
+ Cache.storeMessageFlagsToCache(oMessage);
+ }
+
+ oMessage.lastInCollapsedThread(mLastCollapsedThreadUids && -1 < Utils.inArray(Utils.pInt(oMessage.uid), mLastCollapsedThreadUids) ? true : false);
+
+ aList.push(oMessage);
+ }
+ }
+ }
+
+ Data.messageListCount(iCount);
+ Data.messageListSearch(Utils.isNormal(oData.Result.Search) ? oData.Result.Search : '');
+ Data.messageListPage(window.Math.ceil((iOffset / Data.messagesPerPage()) + 1));
+ Data.messageListEndFolder(Utils.isNormal(oData.Result.Folder) ? oData.Result.Folder : '');
+ Data.messageListEndSearch(Utils.isNormal(oData.Result.Search) ? oData.Result.Search : '');
+ Data.messageListEndPage(Data.messageListPage());
+
+ Data.messageList(aList);
+ Data.messageListIsNotCompleted(false);
+
+ if (aStaticList.length < aList.length)
+ {
+ Data.staticMessageList = aList;
+ }
+
+ Cache.clearNewMessageCache();
+
+ if (oFolder && (bCached || bUnreadCountChange || Data.useThreads()))
+ {
+ this.folderInformation(oFolder.fullNameRaw, aList);
+ }
+ }
+ else
+ {
+ Data.messageListCount(0);
+ Data.messageList([]);
+ Data.messageListError(Utils.getNotification(
+ oData && oData.ErrorCode ? oData.ErrorCode : Enums.Notification.CantGetMessageList
+ ));
+ }
+ };
+
+ /**
+ * @param {string} sNamespace
+ * @param {Array} aFolders
+ * @return {Array}
+ */
+ RainLoopApp.prototype.folderResponseParseRec = function (sNamespace, aFolders)
+ {
+ var
+ iIndex = 0,
+ iLen = 0,
+ oFolder = null,
+ oCacheFolder = null,
+ sFolderFullNameRaw = '',
+ aSubFolders = [],
+ aList = []
+ ;
+
+ for (iIndex = 0, iLen = aFolders.length; iIndex < iLen; iIndex++)
+ {
+ oFolder = aFolders[iIndex];
+ if (oFolder)
+ {
+ sFolderFullNameRaw = oFolder.FullNameRaw;
+
+ oCacheFolder = Cache.getFolderFromCacheList(sFolderFullNameRaw);
+ if (!oCacheFolder)
+ {
+ oCacheFolder = FolderModel.newInstanceFromJson(oFolder);
+ if (oCacheFolder)
+ {
+ Cache.setFolderToCacheList(sFolderFullNameRaw, oCacheFolder);
+ Cache.setFolderFullNameRaw(oCacheFolder.fullNameHash, sFolderFullNameRaw);
+ }
+ }
+
+ if (oCacheFolder)
+ {
+ if (Globals.__RL)
+ {
+ oCacheFolder.collapsed(!Globals.__RL.isFolderExpanded(oCacheFolder.fullNameHash));
+ }
+
+ if (oFolder.Extended)
+ {
+ if (oFolder.Extended.Hash)
+ {
+ Cache.setFolderHash(oCacheFolder.fullNameRaw, oFolder.Extended.Hash);
+ }
+
+ if (Utils.isNormal(oFolder.Extended.MessageCount))
+ {
+ oCacheFolder.messageCountAll(oFolder.Extended.MessageCount);
+ }
+
+ if (Utils.isNormal(oFolder.Extended.MessageUnseenCount))
+ {
+ oCacheFolder.messageCountUnread(oFolder.Extended.MessageUnseenCount);
+ }
+ }
+
+ aSubFolders = oFolder['SubFolders'];
+ if (aSubFolders && 'Collection/FolderCollection' === aSubFolders['@Object'] &&
+ aSubFolders['@Collection'] && Utils.isArray(aSubFolders['@Collection']))
+ {
+ oCacheFolder.subFolders(
+ this.folderResponseParseRec(sNamespace, aSubFolders['@Collection']));
+ }
+
+ aList.push(oCacheFolder);
+ }
+ }
+ }
+
+ return aList;
+ };
+
+ /**
+ * @param {*} oData
+ */
+ RainLoopApp.prototype.setFolders = function (oData)
+ {
+ var
+ aList = [],
+ bUpdate = false,
+ fNormalizeFolder = function (sFolderFullNameRaw) {
+ return ('' === sFolderFullNameRaw || Consts.Values.UnuseOptionValue === sFolderFullNameRaw ||
+ null !== Cache.getFolderFromCacheList(sFolderFullNameRaw)) ? sFolderFullNameRaw : '';
+ }
+ ;
+
+ if (oData && oData.Result && 'Collection/FolderCollection' === oData.Result['@Object'] &&
+ oData.Result['@Collection'] && Utils.isArray(oData.Result['@Collection']))
+ {
+ if (!Utils.isUnd(oData.Result.Namespace))
+ {
+ Data.namespace = oData.Result.Namespace;
+ }
+
+ Data.threading(!!AppSettings.settingsGet('UseImapThread') && oData.Result.IsThreadsSupported && true);
+
+ aList = this.folderResponseParseRec(Data.namespace, oData.Result['@Collection']);
+ Data.folderList(aList);
+
+ if (oData.Result['SystemFolders'] &&
+ '' === '' + AppSettings.settingsGet('SentFolder') + AppSettings.settingsGet('DraftFolder') +
+ AppSettings.settingsGet('SpamFolder') + AppSettings.settingsGet('TrashFolder') + AppSettings.settingsGet('ArchiveFolder') +
+ AppSettings.settingsGet('NullFolder'))
+ {
+ // TODO Magic Numbers
+ AppSettings.settingsSet('SentFolder', oData.Result['SystemFolders'][2] || null);
+ AppSettings.settingsSet('DraftFolder', oData.Result['SystemFolders'][3] || null);
+ AppSettings.settingsSet('SpamFolder', oData.Result['SystemFolders'][4] || null);
+ AppSettings.settingsSet('TrashFolder', oData.Result['SystemFolders'][5] || null);
+ AppSettings.settingsSet('ArchiveFolder', oData.Result['SystemFolders'][12] || null);
+
+ bUpdate = true;
+ }
+
+ Data.sentFolder(fNormalizeFolder(AppSettings.settingsGet('SentFolder')));
+ Data.draftFolder(fNormalizeFolder(AppSettings.settingsGet('DraftFolder')));
+ Data.spamFolder(fNormalizeFolder(AppSettings.settingsGet('SpamFolder')));
+ Data.trashFolder(fNormalizeFolder(AppSettings.settingsGet('TrashFolder')));
+ Data.archiveFolder(fNormalizeFolder(AppSettings.settingsGet('ArchiveFolder')));
+
+ if (bUpdate)
+ {
+ Remote.saveSystemFolders(Utils.emptyFunction, {
+ 'SentFolder': Data.sentFolder(),
+ 'DraftFolder': Data.draftFolder(),
+ 'SpamFolder': Data.spamFolder(),
+ 'TrashFolder': Data.trashFolder(),
+ 'ArchiveFolder': Data.archiveFolder(),
+ 'NullFolder': 'NullFolder'
+ });
+ }
+
+ LocalStorage.set(Enums.ClientSideKeyName.FoldersLashHash, oData.Result.FoldersHash);
+ }
+ };
+
+ /**
+ * @param {string} sFullNameHash
+ * @return {boolean}
+ */
+ RainLoopApp.prototype.isFolderExpanded = function (sFullNameHash)
+ {
+ var aExpandedList = /** @type {Array|null} */ LocalStorage.get(Enums.ClientSideKeyName.ExpandedFolders);
+ return _.isArray(aExpandedList) && -1 !== _.indexOf(aExpandedList, sFullNameHash);
+ };
+
+ /**
+ * @param {string} sFullNameHash
+ * @param {boolean} bExpanded
+ */
+ RainLoopApp.prototype.setExpandedFolder = function (sFullNameHash, bExpanded)
+ {
+ var aExpandedList = /** @type {Array|null} */ LocalStorage.get(Enums.ClientSideKeyName.ExpandedFolders);
+ if (!_.isArray(aExpandedList))
+ {
+ aExpandedList = [];
+ }
+
+ if (bExpanded)
+ {
+ aExpandedList.push(sFullNameHash);
+ aExpandedList = _.uniq(aExpandedList);
+ }
+ else
+ {
+ aExpandedList = _.without(aExpandedList, sFullNameHash);
+ }
+
+ LocalStorage.set(Enums.ClientSideKeyName.ExpandedFolders, aExpandedList);
+ };
+
+ RainLoopApp.prototype.initLayoutResizer = function (sLeft, sRight, sClientSideKeyName)
+ {
+ var
+ iDisabledWidth = 60,
+ iMinWidth = 155,
+ oLeft = $(sLeft),
+ oRight = $(sRight),
+
+ mLeftWidth = LocalStorage.get(sClientSideKeyName) || null,
+
+ fSetWidth = function (iWidth) {
+ if (iWidth)
+ {
+ oLeft.css({
+ 'width': '' + iWidth + 'px'
+ });
+
+ oRight.css({
+ 'left': '' + iWidth + 'px'
+ });
+ }
+ },
+
+ fDisable = function (bDisable) {
+ if (bDisable)
+ {
+ oLeft.resizable('disable');
+ fSetWidth(iDisabledWidth);
+ }
+ else
+ {
+ oLeft.resizable('enable');
+ var iWidth = Utils.pInt(LocalStorage.get(sClientSideKeyName)) || iMinWidth;
+ fSetWidth(iWidth > iMinWidth ? iWidth : iMinWidth);
+ }
+ },
+
+ fResizeFunction = function (oEvent, oObject) {
+ if (oObject && oObject.size && oObject.size.width)
+ {
+ LocalStorage.set(sClientSideKeyName, oObject.size.width);
+
+ oRight.css({
+ 'left': '' + oObject.size.width + 'px'
+ });
+ }
+ }
+ ;
+
+ if (null !== mLeftWidth)
+ {
+ fSetWidth(mLeftWidth > iMinWidth ? mLeftWidth : iMinWidth);
+ }
+
+ oLeft.resizable({
+ 'helper': 'ui-resizable-helper',
+ 'minWidth': iMinWidth,
+ 'maxWidth': 350,
+ 'handles': 'e',
+ 'stop': fResizeFunction
+ });
+
+ Events.sub('left-panel.off', function () {
+ fDisable(true);
+ });
+
+ Events.sub('left-panel.on', function () {
+ fDisable(false);
+ });
+ };
+
+ /**
+ * @param {string} sMailToUrl
+ * @returns {boolean}
+ */
+ RainLoopApp.prototype.mailToHelper = function (sMailToUrl)
+ {
+ if (sMailToUrl && 'mailto:' === sMailToUrl.toString().substr(0, 7).toLowerCase())
+ {
+ sMailToUrl = sMailToUrl.toString().substr(7);
+
+ var
+ oParams = {},
+ oEmailModel = null,
+ sEmail = sMailToUrl.replace(/\?.+$/, ''),
+ sQueryString = sMailToUrl.replace(/^[^\?]*\?/, '')
+ ;
+
+ oEmailModel = new EmailModel();
+ oEmailModel.parse(window.decodeURIComponent(sEmail));
+
+ if (oEmailModel && oEmailModel.email)
+ {
+ oParams = Utils.simpleQueryParser(sQueryString);
+ kn.showScreenPopup(PopupsComposeViewModel, [Enums.ComposeType.Empty, null, [oEmailModel],
+ Utils.isUnd(oParams.subject) ? null : Utils.pString(oParams.subject),
+ Utils.isUnd(oParams.body) ? null : Utils.plainToHtml(Utils.pString(oParams.body))
+ ]);
+ }
+
+ return true;
+ }
+
+ return false;
+ };
+
+ RainLoopApp.prototype.bootstart = function ()
+ {
+ AbstractApp.prototype.bootstart.call(this);
+
+ Data.populateDataOnStart();
+
+ var
+ self = this,
+ sCustomLoginLink = '',
+ sJsHash = AppSettings.settingsGet('JsHash'),
+ iContactsSyncInterval = Utils.pInt(AppSettings.settingsGet('ContactsSyncInterval')),
+ bGoogle = AppSettings.settingsGet('AllowGoogleSocial'),
+ bFacebook = AppSettings.settingsGet('AllowFacebookSocial'),
+ bTwitter = AppSettings.settingsGet('AllowTwitterSocial')
+ ;
+
+ Utils.initOnStartOrLangChange(function () {
+
+ $.extend(true, $.magnificPopup.defaults, {
+ 'tClose': Utils.i18n('MAGNIFIC_POPUP/CLOSE'),
+ 'tLoading': Utils.i18n('MAGNIFIC_POPUP/LOADING'),
+ 'gallery': {
+ 'tPrev': Utils.i18n('MAGNIFIC_POPUP/GALLERY_PREV'),
+ 'tNext': Utils.i18n('MAGNIFIC_POPUP/GALLERY_NEXT'),
+ 'tCounter': Utils.i18n('MAGNIFIC_POPUP/GALLERY_COUNTER')
+ },
+ 'image': {
+ 'tError': Utils.i18n('MAGNIFIC_POPUP/IMAGE_ERROR')
+ },
+ 'ajax': {
+ 'tError': Utils.i18n('MAGNIFIC_POPUP/AJAX_ERROR')
+ }
+ });
+
+ }, this);
+
+ if (window.SimplePace)
+ {
+ window.SimplePace.set(70);
+ window.SimplePace.sleep();
+ }
+
+ Globals.leftPanelDisabled.subscribe(function (bValue) {
+ Events.pub('left-panel.' + (bValue ? 'off' : 'on'));
+ });
+
+ if (!!AppSettings.settingsGet('Auth'))
+ {
+ this.setTitle(Utils.i18n('TITLES/LOADING'));
+
+ this.folders(_.bind(function (bValue) {
+
+ kn.hideLoading();
+
+ if (bValue)
+ {
+ if (window.$LAB && window.crypto && window.crypto.getRandomValues && AppSettings.capa(Enums.Capa.OpenPGP))
+ {
+ window.$LAB.script(window.openpgp ? '' : LinkBuilder.openPgpJs()).wait(function () {
+ if (window.openpgp)
+ {
+ Data.openpgpKeyring = new window.openpgp.Keyring();
+ Data.capaOpenPGP(true);
+
+ Events.pub('openpgp.init');
+
+ self.reloadOpenPgpKeys();
+ }
+ });
+ }
+ else
+ {
+ Data.capaOpenPGP(false);
+ }
+
+ kn.startScreens([MailBoxScreen, SettingsScreen]);
+
+ if (bGoogle || bFacebook || bTwitter)
+ {
+ self.socialUsers(true);
+ }
+
+ Events.sub('interval.2m', function () {
+ self.folderInformation('INBOX');
+ });
+
+ Events.sub('interval.2m', function () {
+ var sF = Data.currentFolderFullNameRaw();
+ if ('INBOX' !== sF)
+ {
+ self.folderInformation(sF);
+ }
+ });
+
+ Events.sub('interval.3m', function () {
+ self.folderInformationMultiply();
+ });
+
+ Events.sub('interval.5m', function () {
+ self.quota();
+ });
+
+ Events.sub('interval.10m', function () {
+ self.folders();
+ });
+
+ iContactsSyncInterval = 5 <= iContactsSyncInterval ? iContactsSyncInterval : 20;
+ iContactsSyncInterval = 320 >= iContactsSyncInterval ? iContactsSyncInterval : 320;
+
+ window.setInterval(function () {
+ self.contactsSync();
+ }, iContactsSyncInterval * 60000 + 5000);
+
+ _.delay(function () {
+ self.contactsSync();
+ }, 5000);
+
+ _.delay(function () {
+ self.folderInformationMultiply(true);
+ }, 500);
+
+ Plugins.runHook('rl-start-user-screens');
+ Events.pub('rl.bootstart-user-screens');
+
+ if (!!AppSettings.settingsGet('AccountSignMe') && window.navigator.registerProtocolHandler)
+ {
+ _.delay(function () {
+ try {
+ window.navigator.registerProtocolHandler('mailto',
+ window.location.protocol + '//' + window.location.host + window.location.pathname + '?mailto&to=%s',
+ '' + (AppSettings.settingsGet('Title') || 'RainLoop'));
+ } catch(e) {}
+
+ if (AppSettings.settingsGet('MailToEmail'))
+ {
+ self.mailToHelper(AppSettings.settingsGet('MailToEmail'));
+ }
+ }, 500);
+ }
+ }
+ else
+ {
+ kn.startScreens([LoginScreen]);
+
+ Plugins.runHook('rl-start-login-screens');
+ Events.pub('rl.bootstart-login-screens');
+ }
+
+ if (window.SimplePace)
+ {
+ window.SimplePace.set(100);
+ }
+
+ if (!Globals.bMobileDevice)
+ {
+ _.defer(function () {
+ self.initLayoutResizer('#rl-left', '#rl-right', Enums.ClientSideKeyName.FolderListSize);
+ });
+ }
+
+ }, this));
+ }
+ else
+ {
+ sCustomLoginLink = Utils.pString(AppSettings.settingsGet('CustomLoginLink'));
+ if (!sCustomLoginLink)
+ {
+ kn.hideLoading();
+ kn.startScreens([LoginScreen]);
+
+ Plugins.runHook('rl-start-login-screens');
+ Events.pub('rl.bootstart-login-screens');
+
+ if (window.SimplePace)
+ {
+ window.SimplePace.set(100);
+ }
+ }
+ else
+ {
+ kn.routeOff();
+ kn.setHash(LinkBuilder.root(), true);
+ kn.routeOff();
+
+ _.defer(function () {
+ window.location.href = sCustomLoginLink;
+ });
+ }
+ }
+
+ if (bGoogle)
+ {
+ window['rl_' + sJsHash + '_google_service'] = function () {
+ Data.googleActions(true);
+ self.socialUsers();
+ };
+ }
+
+ if (bFacebook)
+ {
+ window['rl_' + sJsHash + '_facebook_service'] = function () {
+ Data.facebookActions(true);
+ self.socialUsers();
+ };
+ }
+
+ if (bTwitter)
+ {
+ window['rl_' + sJsHash + '_twitter_service'] = function () {
+ Data.twitterActions(true);
+ self.socialUsers();
+ };
+ }
+
+ Events.sub('interval.1m', function () {
+ Globals.momentTrigger(!Globals.momentTrigger());
+ });
+
+ Plugins.runHook('rl-start-screens');
+ Events.pub('rl.bootstart-end');
+ };
+
+ module.exports = new RainLoopApp();
+
+}(module));
+},{"../Common/Consts.js":6,"../Common/Enums.js":7,"../Common/Events.js":8,"../Common/Globals.js":9,"../Common/LinkBuilder.js":10,"../Common/Plugins.js":12,"../Common/Utils.js":14,"../External/jquery.js":26,"../External/moment.js":29,"../External/underscore.js":31,"../External/window.js":32,"../Knoin/Knoin.js":33,"../Models/AccountModel.js":37,"../Models/FolderModel.js":40,"../Models/IdentityModel.js":41,"../Models/MessageModel.js":42,"../Screens/LoginScreen.js":44,"../Screens/MailBoxScreen.js":45,"../Screens/SettingsScreen.js":46,"../Settings/SettingsAccounts.js":47,"../Settings/SettingsChangePassword.js":48,"../Settings/SettingsContacts.js":49,"../Settings/SettingsFilters.js":50,"../Settings/SettingsFolders.js":51,"../Settings/SettingsGeneral.js":52,"../Settings/SettingsIdentities.js":53,"../Settings/SettingsIdentity.js":54,"../Settings/SettingsOpenPGP.js":55,"../Settings/SettingsSecurity.js":56,"../Settings/SettingsSocial.js":57,"../Settings/SettingsThemes.js":58,"../Storages/AppSettings.js":61,"../Storages/LocalStorage.js":62,"../Storages/WebMailAjaxRemoteStorage.js":65,"../Storages/WebMailCacheStorage.js":66,"../Storages/WebMailDataStorage.js":67,"../ViewModels/Popups/PopupsAskViewModel.js":76,"../ViewModels/Popups/PopupsComposeViewModel.js":78,"./AbstractApp.js":2}],5:[function(require,module,exports){
+// Base64 encode / decode
+// http://www.webtoolkit.info/
+
+(function (module) {
+
+ 'use strict';
+
+ /*jslint bitwise: true*/
+ var Base64 = {
+
+ // private property
+ _keyStr : 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
+
+ // public method for urlsafe encoding
+ urlsafe_encode : function (input) {
+ return Base64.encode(input).replace(/[+]/g, '-').replace(/[\/]/g, '_').replace(/[=]/g, '.');
+ },
+
+ // public method for encoding
+ encode : function (input) {
+ var
+ output = '',
+ chr1, chr2, chr3, enc1, enc2, enc3, enc4,
+ i = 0
+ ;
+
+ input = Base64._utf8_encode(input);
+
+ while (i < input.length)
+ {
+ chr1 = input.charCodeAt(i++);
+ chr2 = input.charCodeAt(i++);
+ chr3 = input.charCodeAt(i++);
+
+ enc1 = chr1 >> 2;
+ enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
+ enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
+ enc4 = chr3 & 63;
+
+ if (isNaN(chr2))
+ {
+ enc3 = enc4 = 64;
+ }
+ else if (isNaN(chr3))
+ {
+ enc4 = 64;
+ }
+
+ output = output +
+ this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
+ this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
+ }
+
+ return output;
+ },
+
+ // public method for decoding
+ decode : function (input) {
+ var
+ output = '',
+ chr1, chr2, chr3, enc1, enc2, enc3, enc4,
+ i = 0
+ ;
+
+ input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
+
+ while (i < input.length)
+ {
+ enc1 = this._keyStr.indexOf(input.charAt(i++));
+ enc2 = this._keyStr.indexOf(input.charAt(i++));
+ enc3 = this._keyStr.indexOf(input.charAt(i++));
+ enc4 = this._keyStr.indexOf(input.charAt(i++));
+
+ chr1 = (enc1 << 2) | (enc2 >> 4);
+ chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
+ chr3 = ((enc3 & 3) << 6) | enc4;
+
+ output = output + String.fromCharCode(chr1);
+
+ if (enc3 !== 64)
+ {
+ output = output + String.fromCharCode(chr2);
+ }
+
+ if (enc4 !== 64)
+ {
+ output = output + String.fromCharCode(chr3);
+ }
+ }
+
+ return Base64._utf8_decode(output);
+ },
+
+ // private method for UTF-8 encoding
+ _utf8_encode : function (string) {
+
+ string = string.replace(/\r\n/g, "\n");
+
+ var
+ utftext = '',
+ n = 0,
+ l = string.length,
+ c = 0
+ ;
+
+ for (; n < l; n++) {
+
+ c = string.charCodeAt(n);
+
+ if (c < 128)
+ {
+ utftext += String.fromCharCode(c);
+ }
+ else if ((c > 127) && (c < 2048))
+ {
+ utftext += String.fromCharCode((c >> 6) | 192);
+ utftext += String.fromCharCode((c & 63) | 128);
+ }
+ else
+ {
+ utftext += String.fromCharCode((c >> 12) | 224);
+ utftext += String.fromCharCode(((c >> 6) & 63) | 128);
+ utftext += String.fromCharCode((c & 63) | 128);
+ }
+ }
+
+ return utftext;
+ },
+
+ // private method for UTF-8 decoding
+ _utf8_decode : function (utftext) {
+ var
+ string = '',
+ i = 0,
+ c = 0,
+ c2 = 0,
+ c3 = 0
+ ;
+
+ while ( i < utftext.length )
+ {
+ c = utftext.charCodeAt(i);
+
+ if (c < 128)
+ {
+ string += String.fromCharCode(c);
+ i++;
+ }
+ else if((c > 191) && (c < 224))
+ {
+ c2 = utftext.charCodeAt(i+1);
+ string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
+ i += 2;
+ }
+ else
+ {
+ c2 = utftext.charCodeAt(i+1);
+ c3 = utftext.charCodeAt(i+2);
+ string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
+ i += 3;
+ }
+ }
+
+ return string;
+ }
+ };
+
+ module.exports = Base64;
+ /*jslint bitwise: false*/
+
+}(module));
+},{}],6:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var Consts = {};
+
+ Consts.Values = {};
+ Consts.DataImages = {};
+ Consts.Defaults = {};
+
+ /**
+ * @const
+ * @type {number}
+ */
+ Consts.Defaults.MessagesPerPage = 20;
+
+ /**
+ * @const
+ * @type {number}
+ */
+ Consts.Defaults.ContactsPerPage = 50;
+
+ /**
+ * @const
+ * @type {Array}
+ */
+ Consts.Defaults.MessagesPerPageArray = [10, 20, 30, 50, 100/*, 150, 200, 300*/];
+
+ /**
+ * @const
+ * @type {number}
+ */
+ Consts.Defaults.DefaultAjaxTimeout = 30000;
+
+ /**
+ * @const
+ * @type {number}
+ */
+ Consts.Defaults.SearchAjaxTimeout = 300000;
+
+ /**
+ * @const
+ * @type {number}
+ */
+ Consts.Defaults.SendMessageAjaxTimeout = 300000;
+
+ /**
+ * @const
+ * @type {number}
+ */
+ Consts.Defaults.SaveMessageAjaxTimeout = 200000;
+
+ /**
+ * @const
+ * @type {number}
+ */
+ Consts.Defaults.ContactsSyncAjaxTimeout = 200000;
+
+ /**
+ * @const
+ * @type {string}
+ */
+ Consts.Values.UnuseOptionValue = '__UNUSE__';
+
+ /**
+ * @const
+ * @type {string}
+ */
+ Consts.Values.ClientSideCookieIndexName = 'rlcsc';
+
+ /**
+ * @const
+ * @type {number}
+ */
+ Consts.Values.ImapDefaulPort = 143;
+
+ /**
+ * @const
+ * @type {number}
+ */
+ Consts.Values.ImapDefaulSecurePort = 993;
+
+ /**
+ * @const
+ * @type {number}
+ */
+ Consts.Values.SmtpDefaulPort = 25;
+
+ /**
+ * @const
+ * @type {number}
+ */
+ Consts.Values.SmtpDefaulSecurePort = 465;
+
+ /**
+ * @const
+ * @type {number}
+ */
+ Consts.Values.MessageBodyCacheLimit = 15;
+
+ /**
+ * @const
+ * @type {number}
+ */
+ Consts.Values.AjaxErrorLimit = 7;
+
+ /**
+ * @const
+ * @type {number}
+ */
+ Consts.Values.TokenErrorLimit = 10;
+
+ /**
+ * @const
+ * @type {string}
+ */
+ Consts.DataImages.UserDotPic = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQIW2P8DwQACgAD/il4QJ8AAAAASUVORK5CYII=';
+
+ /**
+ * @const
+ * @type {string}
+ */
+ Consts.DataImages.TranspPic = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQIW2NkAAIAAAoAAggA9GkAAAAASUVORK5CYII=';
+
+ module.exports = Consts;
+
+}(module));
+},{}],7:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var Enums = {};
+
+ /**
+ * @enum {string}
+ */
+ Enums.StorageResultType = {
+ 'Success': 'success',
+ 'Abort': 'abort',
+ 'Error': 'error',
+ 'Unload': 'unload'
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.State = {
+ 'Empty': 10,
+ 'Login': 20,
+ 'Auth': 30
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.StateType = {
+ 'Webmail': 0,
+ 'Admin': 1
+ };
+
+ /**
+ * @enum {string}
+ */
+ Enums.Capa = {
+ 'Prem': 'PREM',
+ 'TwoFactor': 'TWO_FACTOR',
+ 'OpenPGP': 'OPEN_PGP',
+ 'Prefetch': 'PREFETCH',
+ 'Gravatar': 'GRAVATAR',
+ 'Themes': 'THEMES',
+ 'Filters': 'FILTERS',
+ 'AdditionalAccounts': 'ADDITIONAL_ACCOUNTS',
+ 'AdditionalIdentities': 'ADDITIONAL_IDENTITIES'
+ };
+
+ /**
+ * @enum {string}
+ */
+ Enums.KeyState = {
+ 'All': 'all',
+ 'None': 'none',
+ 'ContactList': 'contact-list',
+ 'MessageList': 'message-list',
+ 'FolderList': 'folder-list',
+ 'MessageView': 'message-view',
+ 'Compose': 'compose',
+ 'Settings': 'settings',
+ 'Menu': 'menu',
+ 'PopupComposeOpenPGP': 'compose-open-pgp',
+ 'PopupKeyboardShortcutsHelp': 'popup-keyboard-shortcuts-help',
+ 'PopupAsk': 'popup-ask'
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.FolderType = {
+ 'Inbox': 10,
+ 'SentItems': 11,
+ 'Draft': 12,
+ 'Trash': 13,
+ 'Spam': 14,
+ 'Archive': 15,
+ 'NotSpam': 80,
+ 'User': 99
+ };
+
+ /**
+ * @enum {string}
+ */
+ Enums.LoginSignMeTypeAsString = {
+ 'DefaultOff': 'defaultoff',
+ 'DefaultOn': 'defaulton',
+ 'Unused': 'unused'
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.LoginSignMeType = {
+ 'DefaultOff': 0,
+ 'DefaultOn': 1,
+ 'Unused': 2
+ };
+
+ /**
+ * @enum {string}
+ */
+ Enums.ComposeType = {
+ 'Empty': 'empty',
+ 'Reply': 'reply',
+ 'ReplyAll': 'replyall',
+ 'Forward': 'forward',
+ 'ForwardAsAttachment': 'forward-as-attachment',
+ 'Draft': 'draft',
+ 'EditAsNew': 'editasnew'
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.UploadErrorCode = {
+ 'Normal': 0,
+ 'FileIsTooBig': 1,
+ 'FilePartiallyUploaded': 2,
+ 'FileNoUploaded': 3,
+ 'MissingTempFolder': 4,
+ 'FileOnSaveingError': 5,
+ 'FileType': 98,
+ 'Unknown': 99
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.SetSystemFoldersNotification = {
+ 'None': 0,
+ 'Sent': 1,
+ 'Draft': 2,
+ 'Spam': 3,
+ 'Trash': 4,
+ 'Archive': 5
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.ClientSideKeyName = {
+ 'FoldersLashHash': 0,
+ 'MessagesInboxLastHash': 1,
+ 'MailBoxListSize': 2,
+ 'ExpandedFolders': 3,
+ 'FolderListSize': 4
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.EventKeyCode = {
+ 'Backspace': 8,
+ 'Tab': 9,
+ 'Enter': 13,
+ 'Esc': 27,
+ 'PageUp': 33,
+ 'PageDown': 34,
+ 'Left': 37,
+ 'Right': 39,
+ 'Up': 38,
+ 'Down': 40,
+ 'End': 35,
+ 'Home': 36,
+ 'Space': 32,
+ 'Insert': 45,
+ 'Delete': 46,
+ 'A': 65,
+ 'S': 83
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.MessageSetAction = {
+ 'SetSeen': 0,
+ 'UnsetSeen': 1,
+ 'SetFlag': 2,
+ 'UnsetFlag': 3
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.MessageSelectAction = {
+ 'All': 0,
+ 'None': 1,
+ 'Invert': 2,
+ 'Unseen': 3,
+ 'Seen': 4,
+ 'Flagged': 5,
+ 'Unflagged': 6
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.DesktopNotifications = {
+ 'Allowed': 0,
+ 'NotAllowed': 1,
+ 'Denied': 2,
+ 'NotSupported': 9
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.MessagePriority = {
+ 'Low': 5,
+ 'Normal': 3,
+ 'High': 1
+ };
+
+ /**
+ * @enum {string}
+ */
+ Enums.EditorDefaultType = {
+ 'Html': 'Html',
+ 'Plain': 'Plain'
+ };
+
+ /**
+ * @enum {string}
+ */
+ Enums.CustomThemeType = {
+ 'Light': 'Light',
+ 'Dark': 'Dark'
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.ServerSecure = {
+ 'None': 0,
+ 'SSL': 1,
+ 'TLS': 2
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.SearchDateType = {
+ 'All': -1,
+ 'Days3': 3,
+ 'Days7': 7,
+ 'Month': 30
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.EmailType = {
+ 'Defailt': 0,
+ 'Facebook': 1,
+ 'Google': 2
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.SaveSettingsStep = {
+ 'Animate': -2,
+ 'Idle': -1,
+ 'TrueResult': 1,
+ 'FalseResult': 0
+ };
+
+ /**
+ * @enum {string}
+ */
+ Enums.InterfaceAnimation = {
+ 'None': 'None',
+ 'Normal': 'Normal',
+ 'Full': 'Full'
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.Layout = {
+ 'NoPreview': 0,
+ 'SidePreview': 1,
+ 'BottomPreview': 2
+ };
+
+ /**
+ * @enum {string}
+ */
+ Enums.FilterConditionField = {
+ 'From': 'From',
+ 'To': 'To',
+ 'Recipient': 'Recipient',
+ 'Subject': 'Subject'
+ };
+
+ /**
+ * @enum {string}
+ */
+ Enums.FilterConditionType = {
+ 'Contains': 'Contains',
+ 'NotContains': 'NotContains',
+ 'EqualTo': 'EqualTo',
+ 'NotEqualTo': 'NotEqualTo'
+ };
+
+ /**
+ * @enum {string}
+ */
+ Enums.FiltersAction = {
+ 'None': 'None',
+ 'Move': 'Move',
+ 'Discard': 'Discard',
+ 'Forward': 'Forward',
+ };
+
+ /**
+ * @enum {string}
+ */
+ Enums.FilterRulesType = {
+ 'And': 'And',
+ 'Or': 'Or'
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.SignedVerifyStatus = {
+ 'UnknownPublicKeys': -4,
+ 'UnknownPrivateKey': -3,
+ 'Unverified': -2,
+ 'Error': -1,
+ 'None': 0,
+ 'Success': 1
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.ContactPropertyType = {
+
+ 'Unknown': 0,
+
+ 'FullName': 10,
+
+ 'FirstName': 15,
+ 'LastName': 16,
+ 'MiddleName': 16,
+ 'Nick': 18,
+
+ 'NamePrefix': 20,
+ 'NameSuffix': 21,
+
+ 'Email': 30,
+ 'Phone': 31,
+ 'Web': 32,
+
+ 'Birthday': 40,
+
+ 'Facebook': 90,
+ 'Skype': 91,
+ 'GitHub': 92,
+
+ 'Note': 110,
+
+ 'Custom': 250
+ };
+
+ /**
+ * @enum {number}
+ */
+ Enums.Notification = {
+ 'InvalidToken': 101,
+ 'AuthError': 102,
+ 'AccessError': 103,
+ 'ConnectionError': 104,
+ 'CaptchaError': 105,
+ 'SocialFacebookLoginAccessDisable': 106,
+ 'SocialTwitterLoginAccessDisable': 107,
+ 'SocialGoogleLoginAccessDisable': 108,
+ 'DomainNotAllowed': 109,
+ 'AccountNotAllowed': 110,
+
+ 'AccountTwoFactorAuthRequired': 120,
+ 'AccountTwoFactorAuthError': 121,
+
+ 'CouldNotSaveNewPassword': 130,
+ 'CurrentPasswordIncorrect': 131,
+ 'NewPasswordShort': 132,
+ 'NewPasswordWeak': 133,
+ 'NewPasswordForbidden': 134,
+
+ 'ContactsSyncError': 140,
+
+ 'CantGetMessageList': 201,
+ 'CantGetMessage': 202,
+ 'CantDeleteMessage': 203,
+ 'CantMoveMessage': 204,
+ 'CantCopyMessage': 205,
+
+ 'CantSaveMessage': 301,
+ 'CantSendMessage': 302,
+ 'InvalidRecipients': 303,
+
+ 'CantCreateFolder': 400,
+ 'CantRenameFolder': 401,
+ 'CantDeleteFolder': 402,
+ 'CantSubscribeFolder': 403,
+ 'CantUnsubscribeFolder': 404,
+ 'CantDeleteNonEmptyFolder': 405,
+
+ 'CantSaveSettings': 501,
+ 'CantSavePluginSettings': 502,
+
+ 'DomainAlreadyExists': 601,
+
+ 'CantInstallPackage': 701,
+ 'CantDeletePackage': 702,
+ 'InvalidPluginPackage': 703,
+ 'UnsupportedPluginPackage': 704,
+
+ 'LicensingServerIsUnavailable': 710,
+ 'LicensingExpired': 711,
+ 'LicensingBanned': 712,
+
+ 'DemoSendMessageError': 750,
+
+ 'AccountAlreadyExists': 801,
+
+ 'MailServerError': 901,
+ 'ClientViewError': 902,
+ 'InvalidInputArgument': 903,
+ 'UnknownNotification': 999,
+ 'UnknownError': 999
+ };
+
+ module.exports = Enums;
+
+}(module));
+},{}],8:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ _ = require('../External/underscore.js'),
+
+ Utils = require('./Utils.js'),
+ Plugins = require('./Plugins.js')
+ ;
+
+ /**
+ * @constructor
+ */
+ function Events()
+ {
+ this.oSubs = {};
+ }
+
+ Events.prototype.oSubs = {};
+
+ /**
+ * @param {string} sName
+ * @param {Function} fFunc
+ * @param {Object=} oContext
+ * @return {Events}
+ */
+ Events.prototype.sub = function (sName, fFunc, oContext)
+ {
+ if (Utils.isUnd(this.oSubs[sName]))
+ {
+ this.oSubs[sName] = [];
+ }
+
+ this.oSubs[sName].push([fFunc, oContext]);
+
+ return this;
+ };
+
+ /**
+ * @param {string} sName
+ * @param {Array=} aArgs
+ * @return {Events}
+ */
+ Events.prototype.pub = function (sName, aArgs)
+ {
+ Plugins.runHook('rl-pub', [sName, aArgs]);
+
+ if (!Utils.isUnd(this.oSubs[sName]))
+ {
+ _.each(this.oSubs[sName], function (aItem) {
+ if (aItem[0])
+ {
+ aItem[0].apply(aItem[1] || null, aArgs || []);
+ }
+ });
+ }
+
+ return this;
+ };
+
+ module.exports = new Events();
+
+}(module));
+},{"../External/underscore.js":31,"./Plugins.js":12,"./Utils.js":14}],9:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ Globals = {},
+ window = require('../External/window.js'),
+ ko = require('../External/ko.js'),
+ key = require('../External/key.js'),
+ $html = require('../External/$html.js'),
+
+ Enums = require('../Common/Enums.js')
+ ;
+
+ /**
+ * @type {?}
+ */
+ Globals.now = (new window.Date()).getTime();
+
+ /**
+ * @type {?}
+ */
+ Globals.momentTrigger = ko.observable(true);
+
+ /**
+ * @type {?}
+ */
+ Globals.dropdownVisibility = ko.observable(false).extend({'rateLimit': 0});
+
+ /**
+ * @type {?}
+ */
+ Globals.tooltipTrigger = ko.observable(false).extend({'rateLimit': 0});
+
+ /**
+ * @type {?}
+ */
+ Globals.langChangeTrigger = ko.observable(true);
+
+ /**
+ * @type {boolean}
+ */
+ Globals.useKeyboardShortcuts = ko.observable(true);
+
+ /**
+ * @type {number}
+ */
+ Globals.iAjaxErrorCount = 0;
+
+ /**
+ * @type {number}
+ */
+ Globals.iTokenErrorCount = 0;
+
+ /**
+ * @type {number}
+ */
+ Globals.iMessageBodyCacheCount = 0;
+
+ /**
+ * @type {boolean}
+ */
+ Globals.bUnload = false;
+
+ /**
+ * @type {string}
+ */
+ Globals.sUserAgent = (window.navigator.userAgent || '').toLowerCase();
+
+ /**
+ * @type {boolean}
+ */
+ Globals.bIsiOSDevice = -1 < Globals.sUserAgent.indexOf('iphone') || -1 < Globals.sUserAgent.indexOf('ipod') || -1 < Globals.sUserAgent.indexOf('ipad');
+
+ /**
+ * @type {boolean}
+ */
+ Globals.bIsAndroidDevice = -1 < Globals.sUserAgent.indexOf('android');
+
+ /**
+ * @type {boolean}
+ */
+ Globals.bMobileDevice = Globals.bIsiOSDevice || Globals.bIsAndroidDevice;
+
+ /**
+ * @type {boolean}
+ */
+ Globals.bDisableNanoScroll = Globals.bMobileDevice;
+
+ /**
+ * @type {boolean}
+ */
+ Globals.bAllowPdfPreview = !Globals.bMobileDevice;
+
+ /**
+ * @type {boolean}
+ */
+ Globals.bAnimationSupported = !Globals.bMobileDevice && $html.hasClass('csstransitions');
+
+ /**
+ * @type {boolean}
+ */
+ Globals.bXMLHttpRequestSupported = !!window.XMLHttpRequest;
+
+ /**
+ * @type {string}
+ */
+ Globals.sAnimationType = '';
+
+ /**
+ * @type {*}
+ */
+ Globals.__RL = null;
+
+ /**
+ * @type {Object}
+ */
+ Globals.oHtmlEditorDefaultConfig = {
+ 'title': false,
+ 'stylesSet': false,
+ 'customConfig': '',
+ 'contentsCss': '',
+ 'toolbarGroups': [
+ {name: 'spec'},
+ {name: 'styles'},
+ {name: 'basicstyles', groups: ['basicstyles', 'cleanup']},
+ {name: 'colors'},
+ {name: 'paragraph', groups: ['list', 'indent', 'blocks', 'align']},
+ {name: 'links'},
+ {name: 'insert'},
+ {name: 'others'}
+ // {name: 'document', groups: ['mode', 'document', 'doctools']}
+ ],
+
+ 'removePlugins': 'contextmenu', //blockquote
+ 'removeButtons': 'Format,Undo,Redo,Cut,Copy,Paste,Anchor,Strike,Subscript,Superscript,Image,SelectAll',
+ 'removeDialogTabs': 'link:advanced;link:target;image:advanced;images:advanced',
+
+ 'extraPlugins': 'plain',
+
+ 'allowedContent': true,
+ 'autoParagraph': false,
+
+ 'font_defaultLabel': 'Arial',
+ 'fontSize_defaultLabel': '13',
+ 'fontSize_sizes': '10/10px;12/12px;13/13px;14/14px;16/16px;18/18px;20/20px;24/24px;28/28px;36/36px;48/48px'
+ };
+
+ /**
+ * @type {Object}
+ */
+ Globals.oHtmlEditorLangsMap = {
+ 'de': 'de',
+ 'es': 'es',
+ 'fr': 'fr',
+ 'hu': 'hu',
+ 'is': 'is',
+ 'it': 'it',
+ 'ko': 'ko',
+ 'ko-kr': 'ko',
+ 'lv': 'lv',
+ 'nl': 'nl',
+ 'no': 'no',
+ 'pl': 'pl',
+ 'pt': 'pt',
+ 'pt-pt': 'pt',
+ 'pt-br': 'pt-br',
+ 'ru': 'ru',
+ 'ro': 'ro',
+ 'zh': 'zh',
+ 'zh-cn': 'zh-cn'
+ };
+
+ if (Globals.bAllowPdfPreview && window.navigator && window.navigator.mimeTypes)
+ {
+ Globals.bAllowPdfPreview = !!_.find(window.navigator.mimeTypes, function (oType) {
+ return oType && 'application/pdf' === oType.type;
+ });
+ }
+
+ Globals.oI18N = window['rainloopI18N'] || {};
+
+ Globals.oNotificationI18N = {};
+
+ Globals.aBootstrapDropdowns = [];
+
+ Globals.aViewModels = {
+ 'settings': [],
+ 'settings-removed': [],
+ 'settings-disabled': []
+ };
+
+ Globals.leftPanelDisabled = ko.observable(false);
+
+ // popups
+ Globals.popupVisibilityNames = ko.observableArray([]);
+
+ Globals.popupVisibility = ko.computed(function () {
+ return 0 < Globals.popupVisibilityNames().length;
+ }, this);
+
+ // keys
+ Globals.keyScopeReal = ko.observable(Enums.KeyState.All);
+ Globals.keyScopeFake = ko.observable(Enums.KeyState.All);
+
+ Globals.keyScope = ko.computed({
+ 'owner': this,
+ 'read': function () {
+ return Globals.keyScopeFake();
+ },
+ 'write': function (sValue) {
+
+ if (Enums.KeyState.Menu !== sValue)
+ {
+ if (Enums.KeyState.Compose === sValue)
+ {
+ // disableKeyFilter
+ key.filter = function () {
+ return Globals.useKeyboardShortcuts();
+ };
+ }
+ else
+ {
+ // restoreKeyFilter
+ key.filter = function (event) {
+
+ if (Globals.useKeyboardShortcuts())
+ {
+ var
+ oElement = event.target || event.srcElement,
+ sTagName = oElement ? oElement.tagName : ''
+ ;
+
+ sTagName = sTagName.toUpperCase();
+ return !(sTagName === 'INPUT' || sTagName === 'SELECT' || sTagName === 'TEXTAREA' ||
+ (oElement && sTagName === 'DIV' && 'editorHtmlArea' === oElement.className && oElement.contentEditable)
+ );
+ }
+
+ return false;
+ };
+ }
+
+ Globals.keyScopeFake(sValue);
+ if (Globals.dropdownVisibility())
+ {
+ sValue = Enums.KeyState.Menu;
+ }
+ }
+
+ Globals.keyScopeReal(sValue);
+ }
+ });
+
+ Globals.keyScopeReal.subscribe(function (sValue) {
+// window.console.log(sValue);
+ key.setScope(sValue);
+ });
+
+ Globals.dropdownVisibility.subscribe(function (bValue) {
+ if (bValue)
+ {
+ Globals.tooltipTrigger(!Globals.tooltipTrigger());
+ Globals.keyScope(Enums.KeyState.Menu);
+ }
+ else if (Enums.KeyState.Menu === key.getScope())
+ {
+ Globals.keyScope(Globals.keyScopeFake());
+ }
+ });
+
+ module.exports = Globals;
+
+}(module));
+},{"../Common/Enums.js":7,"../External/$html.js":17,"../External/key.js":27,"../External/ko.js":28,"../External/window.js":32}],10:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ window = require('../External/window.js'),
+ Utils = require('./Utils.js'),
+ AppSettings = require('../Storages/AppSettings.js')
+ ;
+
+ /**
+ * @constructor
+ */
+ function LinkBuilder()
+ {
+ this.sBase = '#/';
+ this.sServer = './?';
+ this.sVersion = AppSettings.settingsGet('Version');
+ this.sSpecSuffix = AppSettings.settingsGet('AuthAccountHash') || '0';
+ this.sStaticPrefix = AppSettings.settingsGet('StaticPrefix') || 'rainloop/v/' + this.sVersion + '/static/';
+ }
+
+ /**
+ * @return {string}
+ */
+ LinkBuilder.prototype.root = function ()
+ {
+ return this.sBase;
+ };
+
+ /**
+ * @param {string} sDownload
+ * @return {string}
+ */
+ LinkBuilder.prototype.attachmentDownload = function (sDownload)
+ {
+ return this.sServer + '/Raw/' + this.sSpecSuffix + '/Download/' + sDownload;
+ };
+
+ /**
+ * @param {string} sDownload
+ * @return {string}
+ */
+ LinkBuilder.prototype.attachmentPreview = function (sDownload)
+ {
+ return this.sServer + '/Raw/' + this.sSpecSuffix + '/View/' + sDownload;
+ };
+
+ /**
+ * @param {string} sDownload
+ * @return {string}
+ */
+ LinkBuilder.prototype.attachmentPreviewAsPlain = function (sDownload)
+ {
+ return this.sServer + '/Raw/' + this.sSpecSuffix + '/ViewAsPlain/' + sDownload;
+ };
+
+ /**
+ * @return {string}
+ */
+ LinkBuilder.prototype.upload = function ()
+ {
+ return this.sServer + '/Upload/' + this.sSpecSuffix + '/';
+ };
+
+ /**
+ * @return {string}
+ */
+ LinkBuilder.prototype.uploadContacts = function ()
+ {
+ return this.sServer + '/UploadContacts/' + this.sSpecSuffix + '/';
+ };
+
+ /**
+ * @return {string}
+ */
+ LinkBuilder.prototype.uploadBackground = function ()
+ {
+ return this.sServer + '/UploadBackground/' + this.sSpecSuffix + '/';
+ };
+
+ /**
+ * @return {string}
+ */
+ LinkBuilder.prototype.append = function ()
+ {
+ return this.sServer + '/Append/' + this.sSpecSuffix + '/';
+ };
+
+ /**
+ * @param {string} sEmail
+ * @return {string}
+ */
+ LinkBuilder.prototype.change = function (sEmail)
+ {
+ return this.sServer + '/Change/' + this.sSpecSuffix + '/' + window.encodeURIComponent(sEmail) + '/';
+ };
+
+ /**
+ * @param {string=} sAdd
+ * @return {string}
+ */
+ LinkBuilder.prototype.ajax = function (sAdd)
+ {
+ return this.sServer + '/Ajax/' + this.sSpecSuffix + '/' + sAdd;
+ };
+
+ /**
+ * @param {string} sRequestHash
+ * @return {string}
+ */
+ LinkBuilder.prototype.messageViewLink = function (sRequestHash)
+ {
+ return this.sServer + '/Raw/' + this.sSpecSuffix + '/ViewAsPlain/' + sRequestHash;
+ };
+
+ /**
+ * @param {string} sRequestHash
+ * @return {string}
+ */
+ LinkBuilder.prototype.messageDownloadLink = function (sRequestHash)
+ {
+ return this.sServer + '/Raw/' + this.sSpecSuffix + '/Download/' + sRequestHash;
+ };
+
+ /**
+ * @param {string} sEmail
+ * @return {string}
+ */
+ LinkBuilder.prototype.avatarLink = function (sEmail)
+ {
+ return this.sServer + '/Raw/0/Avatar/' + window.encodeURIComponent(sEmail) + '/';
+ // return '//secure.gravatar.com/avatar/' + Utils.md5(sEmail.toLowerCase()) + '.jpg?s=80&d=mm';
+ };
+
+ /**
+ * @return {string}
+ */
+ LinkBuilder.prototype.inbox = function ()
+ {
+ return this.sBase + 'mailbox/Inbox';
+ };
+
+ /**
+ * @return {string}
+ */
+ LinkBuilder.prototype.messagePreview = function ()
+ {
+ return this.sBase + 'mailbox/message-preview';
+ };
+
+ /**
+ * @param {string=} sScreenName
+ * @return {string}
+ */
+ LinkBuilder.prototype.settings = function (sScreenName)
+ {
+ var sResult = this.sBase + 'settings';
+ if (!Utils.isUnd(sScreenName) && '' !== sScreenName)
+ {
+ sResult += '/' + sScreenName;
+ }
+
+ return sResult;
+ };
+
+ /**
+ * @param {string} sScreenName
+ * @return {string}
+ */
+ LinkBuilder.prototype.admin = function (sScreenName)
+ {
+ var sResult = this.sBase;
+ switch (sScreenName) {
+ case 'AdminDomains':
+ sResult += 'domains';
+ break;
+ case 'AdminSecurity':
+ sResult += 'security';
+ break;
+ case 'AdminLicensing':
+ sResult += 'licensing';
+ break;
+ }
+
+ return sResult;
+ };
+
+ /**
+ * @param {string} sFolder
+ * @param {number=} iPage = 1
+ * @param {string=} sSearch = ''
+ * @return {string}
+ */
+ LinkBuilder.prototype.mailBox = function (sFolder, iPage, sSearch)
+ {
+ iPage = Utils.isNormal(iPage) ? Utils.pInt(iPage) : 1;
+ sSearch = Utils.pString(sSearch);
+
+ var sResult = this.sBase + 'mailbox/';
+ if ('' !== sFolder)
+ {
+ sResult += encodeURI(sFolder);
+ }
+ if (1 < iPage)
+ {
+ sResult = sResult.replace(/[\/]+$/, '');
+ sResult += '/p' + iPage;
+ }
+ if ('' !== sSearch)
+ {
+ sResult = sResult.replace(/[\/]+$/, '');
+ sResult += '/' + encodeURI(sSearch);
+ }
+
+ return sResult;
+ };
+
+ /**
+ * @return {string}
+ */
+ LinkBuilder.prototype.phpInfo = function ()
+ {
+ return this.sServer + 'Info';
+ };
+
+ /**
+ * @param {string} sLang
+ * @return {string}
+ */
+ LinkBuilder.prototype.langLink = function (sLang)
+ {
+ return this.sServer + '/Lang/0/' + encodeURI(sLang) + '/' + this.sVersion + '/';
+ };
+
+ /**
+ * @return {string}
+ */
+ LinkBuilder.prototype.exportContactsVcf = function ()
+ {
+ return this.sServer + '/Raw/' + this.sSpecSuffix + '/ContactsVcf/';
+ };
+
+ /**
+ * @return {string}
+ */
+ LinkBuilder.prototype.exportContactsCsv = function ()
+ {
+ return this.sServer + '/Raw/' + this.sSpecSuffix + '/ContactsCsv/';
+ };
+
+ /**
+ * @return {string}
+ */
+ LinkBuilder.prototype.emptyContactPic = function ()
+ {
+ return this.sStaticPrefix + 'css/images/empty-contact.png';
+ };
+
+ /**
+ * @param {string} sFileName
+ * @return {string}
+ */
+ LinkBuilder.prototype.sound = function (sFileName)
+ {
+ return this.sStaticPrefix + 'sounds/' + sFileName;
+ };
+
+ /**
+ * @param {string} sTheme
+ * @return {string}
+ */
+ LinkBuilder.prototype.themePreviewLink = function (sTheme)
+ {
+ var sPrefix = 'rainloop/v/' + this.sVersion + '/';
+ if ('@custom' === sTheme.substr(-7))
+ {
+ sTheme = Utils.trim(sTheme.substring(0, sTheme.length - 7));
+ sPrefix = '';
+ }
+
+ return sPrefix + 'themes/' + encodeURI(sTheme) + '/images/preview.png';
+ };
+
+ /**
+ * @return {string}
+ */
+ LinkBuilder.prototype.notificationMailIcon = function ()
+ {
+ return this.sStaticPrefix + 'css/images/icom-message-notification.png';
+ };
+
+ /**
+ * @return {string}
+ */
+ LinkBuilder.prototype.openPgpJs = function ()
+ {
+ return this.sStaticPrefix + 'js/openpgp.min.js';
+ };
+
+ /**
+ * @return {string}
+ */
+ LinkBuilder.prototype.socialGoogle = function ()
+ {
+ return this.sServer + 'SocialGoogle' + ('' !== this.sSpecSuffix ? '/' + this.sSpecSuffix + '/' : '');
+ };
+
+ /**
+ * @return {string}
+ */
+ LinkBuilder.prototype.socialTwitter = function ()
+ {
+ return this.sServer + 'SocialTwitter' + ('' !== this.sSpecSuffix ? '/' + this.sSpecSuffix + '/' : '');
+ };
+
+ /**
+ * @return {string}
+ */
+ LinkBuilder.prototype.socialFacebook = function ()
+ {
+ return this.sServer + 'SocialFacebook' + ('' !== this.sSpecSuffix ? '/' + this.sSpecSuffix + '/' : '');
+ };
+
+ module.exports = new LinkBuilder();
+
+}(module));
+},{"../External/window.js":32,"../Storages/AppSettings.js":61,"./Utils.js":14}],11:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ window = require('../External/window.js'),
+ Globals = require('./Globals.js'),
+ AppSettings = require('../Storages/AppSettings.js')
+ ;
+
+ /**
+ * @constructor
+ * @param {Object} oElement
+ * @param {Function=} fOnBlur
+ * @param {Function=} fOnReady
+ * @param {Function=} fOnModeChange
+ */
+ function NewHtmlEditorWrapper(oElement, fOnBlur, fOnReady, fOnModeChange)
+ {
+ var self = this;
+ self.editor = null;
+ self.iBlurTimer = 0;
+ self.fOnBlur = fOnBlur || null;
+ self.fOnReady = fOnReady || null;
+ self.fOnModeChange = fOnModeChange || null;
+
+ self.$element = $(oElement);
+
+ self.resize = _.throttle(_.bind(self.resize, self), 100);
+
+ self.init();
+ }
+
+ NewHtmlEditorWrapper.prototype.blurTrigger = function ()
+ {
+ if (this.fOnBlur)
+ {
+ var self = this;
+ window.clearTimeout(self.iBlurTimer);
+ self.iBlurTimer = window.setTimeout(function () {
+ self.fOnBlur();
+ }, 200);
+ }
+ };
+
+ NewHtmlEditorWrapper.prototype.focusTrigger = function ()
+ {
+ if (this.fOnBlur)
+ {
+ window.clearTimeout(this.iBlurTimer);
+ }
+ };
+
+ /**
+ * @return {boolean}
+ */
+ NewHtmlEditorWrapper.prototype.isHtml = function ()
+ {
+ return this.editor ? 'wysiwyg' === this.editor.mode : false;
+ };
+
+ /**
+ * @return {boolean}
+ */
+ NewHtmlEditorWrapper.prototype.checkDirty = function ()
+ {
+ return this.editor ? this.editor.checkDirty() : false;
+ };
+
+ NewHtmlEditorWrapper.prototype.resetDirty = function ()
+ {
+ if (this.editor)
+ {
+ this.editor.resetDirty();
+ }
+ };
+
+ /**
+ * @return {string}
+ */
+ NewHtmlEditorWrapper.prototype.getData = function (bWrapIsHtml)
+ {
+ if (this.editor)
+ {
+ if ('plain' === this.editor.mode && this.editor.plugins.plain && this.editor.__plain)
+ {
+ return this.editor.__plain.getRawData();
+ }
+
+ return bWrapIsHtml ?
+ '' +
+ this.editor.getData() + '' : this.editor.getData();
+ }
+
+ return '';
+ };
+
+ NewHtmlEditorWrapper.prototype.modeToggle = function (bPlain)
+ {
+ if (this.editor)
+ {
+ if (bPlain)
+ {
+ if ('plain' === this.editor.mode)
+ {
+ this.editor.setMode('wysiwyg');
+ }
+ }
+ else
+ {
+ if ('wysiwyg' === this.editor.mode)
+ {
+ this.editor.setMode('plain');
+ }
+ }
+
+ this.resize();
+ }
+ };
+
+ NewHtmlEditorWrapper.prototype.setHtml = function (sHtml, bFocus)
+ {
+ if (this.editor)
+ {
+ this.modeToggle(true);
+ this.editor.setData(sHtml);
+
+ if (bFocus)
+ {
+ this.focus();
+ }
+ }
+ };
+
+ NewHtmlEditorWrapper.prototype.setPlain = function (sPlain, bFocus)
+ {
+ if (this.editor)
+ {
+ this.modeToggle(false);
+ if ('plain' === this.editor.mode && this.editor.plugins.plain && this.editor.__plain)
+ {
+ return this.editor.__plain.setRawData(sPlain);
+ }
+ else
+ {
+ this.editor.setData(sPlain);
+ }
+
+ if (bFocus)
+ {
+ this.focus();
+ }
+ }
+ };
+
+ NewHtmlEditorWrapper.prototype.init = function ()
+ {
+ if (this.$element && this.$element[0])
+ {
+ var
+ self = this,
+ fInit = function () {
+
+ var
+ oConfig = Globals.oHtmlEditorDefaultConfig,
+ sLanguage = AppSettings.settingsGet('Language'),
+ bSource = !!AppSettings.settingsGet('AllowHtmlEditorSourceButton')
+ ;
+
+ if (bSource && oConfig.toolbarGroups && !oConfig.toolbarGroups.__SourceInited)
+ {
+ oConfig.toolbarGroups.__SourceInited = true;
+ oConfig.toolbarGroups.push({name: 'document', groups: ['mode', 'document', 'doctools']});
+ }
+
+ oConfig.enterMode = window.CKEDITOR.ENTER_BR;
+ oConfig.shiftEnterMode = window.CKEDITOR.ENTER_BR;
+
+ oConfig.language = Globals.oHtmlEditorLangsMap[sLanguage] || 'en';
+ if (window.CKEDITOR.env)
+ {
+ window.CKEDITOR.env.isCompatible = true;
+ }
+
+ self.editor = window.CKEDITOR.appendTo(self.$element[0], oConfig);
+
+ self.editor.on('key', function(oEvent) {
+ if (oEvent && oEvent.data && 9 /* Tab */ === oEvent.data.keyCode)
+ {
+ return false;
+ }
+ });
+
+ self.editor.on('blur', function() {
+ self.blurTrigger();
+ });
+
+ self.editor.on('mode', function() {
+
+ self.blurTrigger();
+
+ if (self.fOnModeChange)
+ {
+ self.fOnModeChange('plain' !== self.editor.mode);
+ }
+ });
+
+ self.editor.on('focus', function() {
+ self.focusTrigger();
+ });
+
+ if (self.fOnReady)
+ {
+ self.editor.on('instanceReady', function () {
+
+ self.editor.setKeystroke(window.CKEDITOR.CTRL + 65 /* A */, 'selectAll');
+
+ self.fOnReady();
+ self.__resizable = true;
+ self.resize();
+ });
+ }
+ }
+ ;
+
+ if (window.CKEDITOR)
+ {
+ fInit();
+ }
+ else
+ {
+ window.__initEditor = fInit;
+ }
+ }
+ };
+
+ NewHtmlEditorWrapper.prototype.focus = function ()
+ {
+ if (this.editor)
+ {
+ this.editor.focus();
+ }
+ };
+
+ NewHtmlEditorWrapper.prototype.blur = function ()
+ {
+ if (this.editor)
+ {
+ this.editor.focusManager.blur(true);
+ }
+ };
+
+ NewHtmlEditorWrapper.prototype.resize = function ()
+ {
+ if (this.editor && this.__resizable)
+ {
+ try
+ {
+ this.editor.resize(this.$element.width(), this.$element.innerHeight());
+ }
+ catch (e) {}
+ }
+ };
+
+ NewHtmlEditorWrapper.prototype.clear = function (bFocus)
+ {
+ this.setHtml('', bFocus);
+ };
+
+
+ module.exports = NewHtmlEditorWrapper;
+
+}(module));
+},{"../External/window.js":32,"../Storages/AppSettings.js":61,"./Globals.js":9}],12:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ Plugins = {
+ __boot: null,
+ __remote: null,
+ __data: null
+ },
+ _ = require('../External/underscore.js'),
+ Utils = require('./Utils.js')
+ ;
+
+ /**
+ * @type {Object}
+ */
+ Plugins.oViewModelsHooks = {};
+
+ /**
+ * @type {Object}
+ */
+ Plugins.oSimpleHooks = {};
+
+ /**
+ * @param {string} sName
+ * @param {Function} ViewModel
+ */
+ Plugins.regViewModelHook = function (sName, ViewModel)
+ {
+ if (ViewModel)
+ {
+ ViewModel.__hookName = sName;
+ }
+ };
+
+ /**
+ * @param {string} sName
+ * @param {Function} fCallback
+ */
+ Plugins.addHook = function (sName, fCallback)
+ {
+ if (Utils.isFunc(fCallback))
+ {
+ if (!Utils.isArray(Plugins.oSimpleHooks[sName]))
+ {
+ Plugins.oSimpleHooks[sName] = [];
+ }
+
+ Plugins.oSimpleHooks[sName].push(fCallback);
+ }
+ };
+
+ /**
+ * @param {string} sName
+ * @param {Array=} aArguments
+ */
+ Plugins.runHook = function (sName, aArguments)
+ {
+ if (Utils.isArray(Plugins.oSimpleHooks[sName]))
+ {
+ aArguments = aArguments || [];
+
+ _.each(Plugins.oSimpleHooks[sName], function (fCallback) {
+ fCallback.apply(null, aArguments);
+ });
+ }
+ };
+
+ /**
+ * @param {string} sName
+ * @return {?}
+ */
+ Plugins.mainSettingsGet = function (sName)
+ {
+ if (Plugins.__boot)
+ {
+ return Plugins.__boot.settingsGet(sName);
+ }
+
+ return null;
+ };
+
+ /**
+ * @param {Function} fCallback
+ * @param {string} sAction
+ * @param {Object=} oParameters
+ * @param {?number=} iTimeout
+ * @param {string=} sGetAdd = ''
+ * @param {Array=} aAbortActions = []
+ */
+ Plugins.remoteRequest = function (fCallback, sAction, oParameters, iTimeout, sGetAdd, aAbortActions)
+ {
+ if (Plugins.__remote)
+ {
+ Plugins.__remote.defaultRequest(fCallback, sAction, oParameters, iTimeout, sGetAdd, aAbortActions);
+ }
+ };
+
+ /**
+ * @param {string} sPluginSection
+ * @param {string} sName
+ * @return {?}
+ */
+ Plugins.settingsGet = function (sPluginSection, sName)
+ {
+ var oPlugin = Plugins.mainSettingsGet('Plugins');
+ oPlugin = oPlugin && Utils.isUnd(oPlugin[sPluginSection]) ? null : oPlugin[sPluginSection];
+ return oPlugin ? (Utils.isUnd(oPlugin[sName]) ? null : oPlugin[sName]) : null;
+ };
+
+ module.exports = Plugins;
+
+}(module));
+},{"../External/underscore.js":31,"./Utils.js":14}],13:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ $ = require('../External/jquery.js'),
+ _ = require('../External/underscore.js'),
+ ko = require('../External/ko.js'),
+ key = require('../External/key.js'),
+
+ Enums = require('./Enums.js'),
+ Utils = require('./Utils.js')
+ ;
+
+ /**
+ * @constructor
+ * @param {koProperty} oKoList
+ * @param {koProperty} oKoSelectedItem
+ * @param {string} sItemSelector
+ * @param {string} sItemSelectedSelector
+ * @param {string} sItemCheckedSelector
+ * @param {string} sItemFocusedSelector
+ */
+ function Selector(oKoList, oKoSelectedItem,
+ sItemSelector, sItemSelectedSelector, sItemCheckedSelector, sItemFocusedSelector)
+ {
+ this.list = oKoList;
+
+ this.listChecked = ko.computed(function () {
+ return _.filter(this.list(), function (oItem) {
+ return oItem.checked();
+ });
+ }, this).extend({'rateLimit': 0});
+
+ this.isListChecked = ko.computed(function () {
+ return 0 < this.listChecked().length;
+ }, this);
+
+ this.focusedItem = ko.observable(null);
+ this.selectedItem = oKoSelectedItem;
+ this.selectedItemUseCallback = true;
+
+ this.itemSelectedThrottle = _.debounce(_.bind(this.itemSelected, this), 300);
+
+ this.listChecked.subscribe(function (aItems) {
+ if (0 < aItems.length)
+ {
+ if (null === this.selectedItem())
+ {
+ this.selectedItem.valueHasMutated();
+ }
+ else
+ {
+ this.selectedItem(null);
+ }
+ }
+ else if (this.bAutoSelect && this.focusedItem())
+ {
+ this.selectedItem(this.focusedItem());
+ }
+ }, this);
+
+ this.selectedItem.subscribe(function (oItem) {
+
+ if (oItem)
+ {
+ if (this.isListChecked())
+ {
+ _.each(this.listChecked(), function (oSubItem) {
+ oSubItem.checked(false);
+ });
+ }
+
+ if (this.selectedItemUseCallback)
+ {
+ this.itemSelectedThrottle(oItem);
+ }
+ }
+ else if (this.selectedItemUseCallback)
+ {
+ this.itemSelected(null);
+ }
+
+ }, this);
+
+ this.selectedItem.extend({'toggleSubscribe': [null,
+ function (oPrev) {
+ if (oPrev)
+ {
+ oPrev.selected(false);
+ }
+ }, function (oNext) {
+ if (oNext)
+ {
+ oNext.selected(true);
+ }
+ }
+ ]});
+
+ this.focusedItem.extend({'toggleSubscribe': [null,
+ function (oPrev) {
+ if (oPrev)
+ {
+ oPrev.focused(false);
+ }
+ }, function (oNext) {
+ if (oNext)
+ {
+ oNext.focused(true);
+ }
+ }
+ ]});
+
+ this.oContentVisible = null;
+ this.oContentScrollable = null;
+
+ this.sItemSelector = sItemSelector;
+ this.sItemSelectedSelector = sItemSelectedSelector;
+ this.sItemCheckedSelector = sItemCheckedSelector;
+ this.sItemFocusedSelector = sItemFocusedSelector;
+
+ this.sLastUid = '';
+ this.bAutoSelect = true;
+ this.oCallbacks = {};
+
+ this.emptyFunction = function () {};
+
+ this.focusedItem.subscribe(function (oItem) {
+ if (oItem)
+ {
+ this.sLastUid = this.getItemUid(oItem);
+ }
+ }, this);
+
+ var
+ aCache = [],
+ aCheckedCache = [],
+ mFocused = null,
+ mSelected = null
+ ;
+
+ this.list.subscribe(function (aItems) {
+
+ var self = this;
+ if (Utils.isArray(aItems))
+ {
+ _.each(aItems, function (oItem) {
+ if (oItem)
+ {
+ var sUid = self.getItemUid(oItem);
+
+ aCache.push(sUid);
+ if (oItem.checked())
+ {
+ aCheckedCache.push(sUid);
+ }
+ if (null === mFocused && oItem.focused())
+ {
+ mFocused = sUid;
+ }
+ if (null === mSelected && oItem.selected())
+ {
+ mSelected = sUid;
+ }
+ }
+ });
+ }
+ }, this, 'beforeChange');
+
+ this.list.subscribe(function (aItems) {
+
+ var
+ self = this,
+ oTemp = null,
+ bGetNext = false,
+ aUids = [],
+ mNextFocused = mFocused,
+ bChecked = false,
+ bSelected = false,
+ iLen = 0
+ ;
+
+ this.selectedItemUseCallback = false;
+
+ this.focusedItem(null);
+ this.selectedItem(null);
+
+ if (Utils.isArray(aItems))
+ {
+ iLen = aCheckedCache.length;
+
+ _.each(aItems, function (oItem) {
+
+ var sUid = self.getItemUid(oItem);
+ aUids.push(sUid);
+
+ if (null !== mFocused && mFocused === sUid)
+ {
+ self.focusedItem(oItem);
+ mFocused = null;
+ }
+
+ if (0 < iLen && -1 < Utils.inArray(sUid, aCheckedCache))
+ {
+ bChecked = true;
+ oItem.checked(true);
+ iLen--;
+ }
+
+ if (!bChecked && null !== mSelected && mSelected === sUid)
+ {
+ bSelected = true;
+ self.selectedItem(oItem);
+ mSelected = null;
+ }
+ });
+
+ this.selectedItemUseCallback = true;
+
+ if (!bChecked && !bSelected && this.bAutoSelect)
+ {
+ if (self.focusedItem())
+ {
+ self.selectedItem(self.focusedItem());
+ }
+ else if (0 < aItems.length)
+ {
+ if (null !== mNextFocused)
+ {
+ bGetNext = false;
+ mNextFocused = _.find(aCache, function (sUid) {
+ if (bGetNext && -1 < Utils.inArray(sUid, aUids))
+ {
+ return sUid;
+ }
+ else if (mNextFocused === sUid)
+ {
+ bGetNext = true;
+ }
+ return false;
+ });
+
+ if (mNextFocused)
+ {
+ oTemp = _.find(aItems, function (oItem) {
+ return mNextFocused === self.getItemUid(oItem);
+ });
+ }
+ }
+
+ self.selectedItem(oTemp || null);
+ self.focusedItem(self.selectedItem());
+ }
+ }
+ }
+
+ aCache = [];
+ aCheckedCache = [];
+ mFocused = null;
+ mSelected = null;
+
+ }, this);
+ }
+
+ Selector.prototype.itemSelected = function (oItem)
+ {
+ if (this.isListChecked())
+ {
+ if (!oItem)
+ {
+ (this.oCallbacks['onItemSelect'] || this.emptyFunction)(oItem || null);
+ }
+ }
+ else
+ {
+ if (oItem)
+ {
+ (this.oCallbacks['onItemSelect'] || this.emptyFunction)(oItem);
+ }
+ }
+ };
+
+ Selector.prototype.goDown = function (bForceSelect)
+ {
+ this.newSelectPosition(Enums.EventKeyCode.Down, false, bForceSelect);
+ };
+
+ Selector.prototype.goUp = function (bForceSelect)
+ {
+ this.newSelectPosition(Enums.EventKeyCode.Up, false, bForceSelect);
+ };
+
+ Selector.prototype.init = function (oContentVisible, oContentScrollable, sKeyScope)
+ {
+ this.oContentVisible = oContentVisible;
+ this.oContentScrollable = oContentScrollable;
+
+ sKeyScope = sKeyScope || 'all';
+
+ if (this.oContentVisible && this.oContentScrollable)
+ {
+ var
+ self = this
+ ;
+
+ $(this.oContentVisible)
+ .on('selectstart', function (oEvent) {
+ if (oEvent && oEvent.preventDefault)
+ {
+ oEvent.preventDefault();
+ }
+ })
+ .on('click', this.sItemSelector, function (oEvent) {
+ self.actionClick(ko.dataFor(this), oEvent);
+ })
+ .on('click', this.sItemCheckedSelector, function (oEvent) {
+ var oItem = ko.dataFor(this);
+ if (oItem)
+ {
+ if (oEvent && oEvent.shiftKey)
+ {
+ self.actionClick(oItem, oEvent);
+ }
+ else
+ {
+ self.focusedItem(oItem);
+ oItem.checked(!oItem.checked());
+ }
+ }
+ })
+ ;
+
+ key('enter', sKeyScope, function () {
+ if (self.focusedItem() && !self.focusedItem().selected())
+ {
+ self.actionClick(self.focusedItem());
+ return false;
+ }
+
+ return true;
+ });
+
+ key('ctrl+up, command+up, ctrl+down, command+down', sKeyScope, function () {
+ return false;
+ });
+
+ key('up, shift+up, down, shift+down, home, end, pageup, pagedown, insert, space', sKeyScope, function (event, handler) {
+ if (event && handler && handler.shortcut)
+ {
+ // TODO
+ var iKey = 0;
+ switch (handler.shortcut)
+ {
+ case 'up':
+ case 'shift+up':
+ iKey = Enums.EventKeyCode.Up;
+ break;
+ case 'down':
+ case 'shift+down':
+ iKey = Enums.EventKeyCode.Down;
+ break;
+ case 'insert':
+ iKey = Enums.EventKeyCode.Insert;
+ break;
+ case 'space':
+ iKey = Enums.EventKeyCode.Space;
+ break;
+ case 'home':
+ iKey = Enums.EventKeyCode.Home;
+ break;
+ case 'end':
+ iKey = Enums.EventKeyCode.End;
+ break;
+ case 'pageup':
+ iKey = Enums.EventKeyCode.PageUp;
+ break;
+ case 'pagedown':
+ iKey = Enums.EventKeyCode.PageDown;
+ break;
+ }
+
+ if (0 < iKey)
+ {
+ self.newSelectPosition(iKey, key.shift);
+ return false;
+ }
+ }
+ });
+ }
+ };
+
+ Selector.prototype.autoSelect = function (bValue)
+ {
+ this.bAutoSelect = !!bValue;
+ };
+
+ /**
+ * @param {Object} oItem
+ * @returns {string}
+ */
+ Selector.prototype.getItemUid = function (oItem)
+ {
+ var
+ sUid = '',
+ fGetItemUidCallback = this.oCallbacks['onItemGetUid'] || null
+ ;
+
+ if (fGetItemUidCallback && oItem)
+ {
+ sUid = fGetItemUidCallback(oItem);
+ }
+
+ return sUid.toString();
+ };
+
+ /**
+ * @param {number} iEventKeyCode
+ * @param {boolean} bShiftKey
+ * @param {boolean=} bForceSelect = false
+ */
+ Selector.prototype.newSelectPosition = function (iEventKeyCode, bShiftKey, bForceSelect)
+ {
+ var
+ iIndex = 0,
+ iPageStep = 10,
+ bNext = false,
+ bStop = false,
+ oResult = null,
+ aList = this.list(),
+ iListLen = aList ? aList.length : 0,
+ oFocused = this.focusedItem()
+ ;
+
+ if (0 < iListLen)
+ {
+ if (!oFocused)
+ {
+ if (Enums.EventKeyCode.Down === iEventKeyCode || Enums.EventKeyCode.Insert === iEventKeyCode || Enums.EventKeyCode.Space === iEventKeyCode || Enums.EventKeyCode.Home === iEventKeyCode || Enums.EventKeyCode.PageUp === iEventKeyCode)
+ {
+ oResult = aList[0];
+ }
+ else if (Enums.EventKeyCode.Up === iEventKeyCode || Enums.EventKeyCode.End === iEventKeyCode || Enums.EventKeyCode.PageDown === iEventKeyCode)
+ {
+ oResult = aList[aList.length - 1];
+ }
+ }
+ else if (oFocused)
+ {
+ if (Enums.EventKeyCode.Down === iEventKeyCode || Enums.EventKeyCode.Up === iEventKeyCode || Enums.EventKeyCode.Insert === iEventKeyCode || Enums.EventKeyCode.Space === iEventKeyCode)
+ {
+ _.each(aList, function (oItem) {
+ if (!bStop)
+ {
+ switch (iEventKeyCode) {
+ case Enums.EventKeyCode.Up:
+ if (oFocused === oItem)
+ {
+ bStop = true;
+ }
+ else
+ {
+ oResult = oItem;
+ }
+ break;
+ case Enums.EventKeyCode.Down:
+ case Enums.EventKeyCode.Insert:
+ if (bNext)
+ {
+ oResult = oItem;
+ bStop = true;
+ }
+ else if (oFocused === oItem)
+ {
+ bNext = true;
+ }
+ break;
+ }
+ }
+ });
+ }
+ else if (Enums.EventKeyCode.Home === iEventKeyCode || Enums.EventKeyCode.End === iEventKeyCode)
+ {
+ if (Enums.EventKeyCode.Home === iEventKeyCode)
+ {
+ oResult = aList[0];
+ }
+ else if (Enums.EventKeyCode.End === iEventKeyCode)
+ {
+ oResult = aList[aList.length - 1];
+ }
+ }
+ else if (Enums.EventKeyCode.PageDown === iEventKeyCode)
+ {
+ for (; iIndex < iListLen; iIndex++)
+ {
+ if (oFocused === aList[iIndex])
+ {
+ iIndex += iPageStep;
+ iIndex = iListLen - 1 < iIndex ? iListLen - 1 : iIndex;
+ oResult = aList[iIndex];
+ break;
+ }
+ }
+ }
+ else if (Enums.EventKeyCode.PageUp === iEventKeyCode)
+ {
+ for (iIndex = iListLen; iIndex >= 0; iIndex--)
+ {
+ if (oFocused === aList[iIndex])
+ {
+ iIndex -= iPageStep;
+ iIndex = 0 > iIndex ? 0 : iIndex;
+ oResult = aList[iIndex];
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ if (oResult)
+ {
+ this.focusedItem(oResult);
+
+ if (oFocused)
+ {
+ if (bShiftKey)
+ {
+ if (Enums.EventKeyCode.Up === iEventKeyCode || Enums.EventKeyCode.Down === iEventKeyCode)
+ {
+ oFocused.checked(!oFocused.checked());
+ }
+ }
+ else if (Enums.EventKeyCode.Insert === iEventKeyCode || Enums.EventKeyCode.Space === iEventKeyCode)
+ {
+ oFocused.checked(!oFocused.checked());
+ }
+ }
+
+ if ((this.bAutoSelect || !!bForceSelect) &&
+ !this.isListChecked() && Enums.EventKeyCode.Space !== iEventKeyCode)
+ {
+ this.selectedItem(oResult);
+ }
+
+ this.scrollToFocused();
+ }
+ else if (oFocused)
+ {
+ if (bShiftKey && (Enums.EventKeyCode.Up === iEventKeyCode || Enums.EventKeyCode.Down === iEventKeyCode))
+ {
+ oFocused.checked(!oFocused.checked());
+ }
+ else if (Enums.EventKeyCode.Insert === iEventKeyCode || Enums.EventKeyCode.Space === iEventKeyCode)
+ {
+ oFocused.checked(!oFocused.checked());
+ }
+
+ this.focusedItem(oFocused);
+ }
+ };
+
+ /**
+ * @return {boolean}
+ */
+ Selector.prototype.scrollToFocused = function ()
+ {
+ if (!this.oContentVisible || !this.oContentScrollable)
+ {
+ return false;
+ }
+
+ var
+ iOffset = 20,
+ oFocused = $(this.sItemFocusedSelector, this.oContentScrollable),
+ oPos = oFocused.position(),
+ iVisibleHeight = this.oContentVisible.height(),
+ iFocusedHeight = oFocused.outerHeight()
+ ;
+
+ if (oPos && (oPos.top < 0 || oPos.top + iFocusedHeight > iVisibleHeight))
+ {
+ if (oPos.top < 0)
+ {
+ this.oContentScrollable.scrollTop(this.oContentScrollable.scrollTop() + oPos.top - iOffset);
+ }
+ else
+ {
+ this.oContentScrollable.scrollTop(this.oContentScrollable.scrollTop() + oPos.top - iVisibleHeight + iFocusedHeight + iOffset);
+ }
+
+ return true;
+ }
+
+ return false;
+ };
+
+ /**
+ * @param {boolean=} bFast = false
+ * @return {boolean}
+ */
+ Selector.prototype.scrollToTop = function (bFast)
+ {
+ if (!this.oContentVisible || !this.oContentScrollable)
+ {
+ return false;
+ }
+
+ if (bFast)
+ {
+ this.oContentScrollable.scrollTop(0);
+ }
+ else
+ {
+ this.oContentScrollable.stop().animate({'scrollTop': 0}, 200);
+ }
+
+ return true;
+ };
+
+ Selector.prototype.eventClickFunction = function (oItem, oEvent)
+ {
+ var
+ sUid = this.getItemUid(oItem),
+ iIndex = 0,
+ iLength = 0,
+ oListItem = null,
+ sLineUid = '',
+ bChangeRange = false,
+ bIsInRange = false,
+ aList = [],
+ bChecked = false
+ ;
+
+ if (oEvent && oEvent.shiftKey)
+ {
+ if ('' !== sUid && '' !== this.sLastUid && sUid !== this.sLastUid)
+ {
+ aList = this.list();
+ bChecked = oItem.checked();
+
+ for (iIndex = 0, iLength = aList.length; iIndex < iLength; iIndex++)
+ {
+ oListItem = aList[iIndex];
+ sLineUid = this.getItemUid(oListItem);
+
+ bChangeRange = false;
+ if (sLineUid === this.sLastUid || sLineUid === sUid)
+ {
+ bChangeRange = true;
+ }
+
+ if (bChangeRange)
+ {
+ bIsInRange = !bIsInRange;
+ }
+
+ if (bIsInRange || bChangeRange)
+ {
+ oListItem.checked(bChecked);
+ }
+ }
+ }
+ }
+
+ this.sLastUid = '' === sUid ? '' : sUid;
+ };
+
+ /**
+ * @param {Object} oItem
+ * @param {Object=} oEvent
+ */
+ Selector.prototype.actionClick = function (oItem, oEvent)
+ {
+ if (oItem)
+ {
+ var
+ bClick = true,
+ sUid = this.getItemUid(oItem)
+ ;
+
+ if (oEvent)
+ {
+ if (oEvent.shiftKey && !oEvent.ctrlKey && !oEvent.altKey)
+ {
+ bClick = false;
+ if ('' === this.sLastUid)
+ {
+ this.sLastUid = sUid;
+ }
+
+ oItem.checked(!oItem.checked());
+ this.eventClickFunction(oItem, oEvent);
+
+ this.focusedItem(oItem);
+ }
+ else if (oEvent.ctrlKey && !oEvent.shiftKey && !oEvent.altKey)
+ {
+ bClick = false;
+ this.focusedItem(oItem);
+
+ if (this.selectedItem() && oItem !== this.selectedItem())
+ {
+ this.selectedItem().checked(true);
+ }
+
+ oItem.checked(!oItem.checked());
+ }
+ }
+
+ if (bClick)
+ {
+ this.focusedItem(oItem);
+ this.selectedItem(oItem);
+
+ this.scrollToFocused();
+ }
+ }
+ };
+
+ Selector.prototype.on = function (sEventName, fCallback)
+ {
+ this.oCallbacks[sEventName] = fCallback;
+ };
+
+ module.exports = Selector;
+
+}(module));
+},{"../External/jquery.js":26,"../External/key.js":27,"../External/ko.js":28,"../External/underscore.js":31,"./Enums.js":7,"./Utils.js":14}],14:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ Utils = {},
+
+ $ = require('../External/jquery.js'),
+ _ = require('../External/underscore.js'),
+ ko = require('../External/ko.js'),
+ window = require('../External/window.js'),
+ $window = require('../External/$window.js'),
+ $html = require('../External/$html.js'),
+ $doc = require('../External/$doc.js'),
+ NotificationClass = require('../External/NotificationClass.js'),
+
+ Enums = require('./Enums.js'),
+ Consts = require('./Consts.js'),
+ Globals = require('./Globals.js')
+ ;
+
+ Utils.trim = $.trim;
+ Utils.inArray = $.inArray;
+ Utils.isArray = _.isArray;
+ Utils.isFunc = _.isFunction;
+ Utils.isUnd = _.isUndefined;
+ Utils.isNull = _.isNull;
+ Utils.emptyFunction = function () {};
+
+ /**
+ * @param {*} oValue
+ * @return {boolean}
+ */
+ Utils.isNormal = function (oValue)
+ {
+ return !Utils.isUnd(oValue) && !Utils.isNull(oValue);
+ };
+
+ Utils.windowResize = _.debounce(function (iTimeout) {
+ if (Utils.isUnd(iTimeout))
+ {
+ $window.resize();
+ }
+ else
+ {
+ window.setTimeout(function () {
+ $window.resize();
+ }, iTimeout);
+ }
+ }, 50);
+
+ /**
+ * @param {(string|number)} mValue
+ * @param {boolean=} bIncludeZero
+ * @return {boolean}
+ */
+ Utils.isPosNumeric = function (mValue, bIncludeZero)
+ {
+ return Utils.isNormal(mValue) ?
+ ((Utils.isUnd(bIncludeZero) ? true : !!bIncludeZero) ?
+ (/^[0-9]*$/).test(mValue.toString()) :
+ (/^[1-9]+[0-9]*$/).test(mValue.toString())) :
+ false;
+ };
+
+ /**
+ * @param {*} iValue
+ * @param {number=} iDefault = 0
+ * @return {number}
+ */
+ Utils.pInt = function (iValue, iDefault)
+ {
+ var iResult = Utils.isNormal(iValue) && '' !== iValue ? window.parseInt(iValue, 10) : (iDefault || 0);
+ return window.isNaN(iResult) ? (iDefault || 0) : iResult;
+ };
+
+ /**
+ * @param {*} mValue
+ * @return {string}
+ */
+ Utils.pString = function (mValue)
+ {
+ return Utils.isNormal(mValue) ? '' + mValue : '';
+ };
+
+ /**
+ * @param {*} aValue
+ * @return {boolean}
+ */
+ Utils.isNonEmptyArray = function (aValue)
+ {
+ return Utils.isArray(aValue) && 0 < aValue.length;
+ };
+
+ /**
+ * @param {string} sQueryString
+ * @return {Object}
+ */
+ Utils.simpleQueryParser = function (sQueryString)
+ {
+ var
+ oParams = {},
+ aQueries = [],
+ aTemp = [],
+ iIndex = 0,
+ iLen = 0
+ ;
+
+ aQueries = sQueryString.split('&');
+ for (iIndex = 0, iLen = aQueries.length; iIndex < iLen; iIndex++)
+ {
+ aTemp = aQueries[iIndex].split('=');
+ oParams[window.decodeURIComponent(aTemp[0])] = window.decodeURIComponent(aTemp[1]);
+ }
+
+ return oParams;
+ };
+
+ /**
+ * @param {string} aValue
+ * @param {string} sKey
+ * @param {string} sLongKey
+ * @return {string|boolean}
+ */
+ Utils.rsaEncode = function (sValue, sHash, sKey, sLongKey)
+ {
+ if (window.crypto && window.crypto.getRandomValues && window.RSAKey && sHash && sKey && sLongKey)
+ {
+ var oRsa = new window.RSAKey();
+ oRsa.setPublic(sLongKey, sKey);
+
+ sValue = oRsa.encrypt(Utils.fakeMd5() + ':' + sValue + ':' + Utils.fakeMd5());
+ if (false !== sValue)
+ {
+ return 'rsa:' + sHash + ':' + sValue;
+ }
+ }
+
+ return false;
+ };
+
+ Utils.rsaEncode.supported = !!(window.crypto && window.crypto.getRandomValues && window.RSAKey);
+
+ /**
+ * @param {string} sPath
+ * @param {*=} oObject
+ * @param {Object=} oObjectToExportTo
+ */
+ Utils.exportPath = function (sPath, oObject, oObjectToExportTo)
+ {
+ var
+ sPart = null,
+ aParts = sPath.split('.'),
+ oCur = oObjectToExportTo || window
+ ;
+
+ for (; aParts.length && (sPart = aParts.shift());)
+ {
+ if (!aParts.length && !Utils.isUnd(oObject))
+ {
+ oCur[sPart] = oObject;
+ }
+ else if (oCur[sPart])
+ {
+ oCur = oCur[sPart];
+ }
+ else
+ {
+ oCur = oCur[sPart] = {};
+ }
+ }
+ };
+
+ /**
+ * @param {Object} oObject
+ * @param {string} sName
+ * @param {*} mValue
+ */
+ Utils.pImport = function (oObject, sName, mValue)
+ {
+ oObject[sName] = mValue;
+ };
+
+ /**
+ * @param {Object} oObject
+ * @param {string} sName
+ * @param {*} mDefault
+ * @return {*}
+ */
+ Utils.pExport = function (oObject, sName, mDefault)
+ {
+ return Utils.isUnd(oObject[sName]) ? mDefault : oObject[sName];
+ };
+
+ /**
+ * @param {string} sText
+ * @return {string}
+ */
+ Utils.encodeHtml = function (sText)
+ {
+ return Utils.isNormal(sText) ? sText.toString()
+ .replace(/&/g, '&').replace(//g, '>')
+ .replace(/"/g, '"').replace(/'/g, ''') : '';
+ };
+
+ /**
+ * @param {string} sText
+ * @param {number=} iLen
+ * @return {string}
+ */
+ Utils.splitPlainText = function (sText, iLen)
+ {
+ var
+ sPrefix = '',
+ sSubText = '',
+ sResult = sText,
+ iSpacePos = 0,
+ iNewLinePos = 0
+ ;
+
+ iLen = Utils.isUnd(iLen) ? 100 : iLen;
+
+ while (sResult.length > iLen)
+ {
+ sSubText = sResult.substring(0, iLen);
+ iSpacePos = sSubText.lastIndexOf(' ');
+ iNewLinePos = sSubText.lastIndexOf('\n');
+
+ if (-1 !== iNewLinePos)
+ {
+ iSpacePos = iNewLinePos;
+ }
+
+ if (-1 === iSpacePos)
+ {
+ iSpacePos = iLen;
+ }
+
+ sPrefix += sSubText.substring(0, iSpacePos) + '\n';
+ sResult = sResult.substring(iSpacePos + 1);
+ }
+
+ return sPrefix + sResult;
+ };
+
+ Utils.timeOutAction = (function () {
+
+ var
+ oTimeOuts = {}
+ ;
+
+ return function (sAction, fFunction, iTimeOut)
+ {
+ if (Utils.isUnd(oTimeOuts[sAction]))
+ {
+ oTimeOuts[sAction] = 0;
+ }
+
+ window.clearTimeout(oTimeOuts[sAction]);
+ oTimeOuts[sAction] = window.setTimeout(fFunction, iTimeOut);
+ };
+ }());
+
+ Utils.timeOutActionSecond = (function () {
+
+ var
+ oTimeOuts = {}
+ ;
+
+ return function (sAction, fFunction, iTimeOut)
+ {
+ if (!oTimeOuts[sAction])
+ {
+ oTimeOuts[sAction] = window.setTimeout(function () {
+ fFunction();
+ oTimeOuts[sAction] = 0;
+ }, iTimeOut);
+ }
+ };
+ }());
+
+ Utils.audio = (function () {
+
+ var
+ oAudio = false
+ ;
+
+ return function (sMp3File, sOggFile) {
+
+ if (false === oAudio)
+ {
+ if (Globals.bIsiOSDevice)
+ {
+ oAudio = null;
+ }
+ else
+ {
+ var
+ bCanPlayMp3 = false,
+ bCanPlayOgg = false,
+ oAudioLocal = window.Audio ? new window.Audio() : null
+ ;
+
+ if (oAudioLocal && oAudioLocal.canPlayType && oAudioLocal.play)
+ {
+ bCanPlayMp3 = '' !== oAudioLocal.canPlayType('audio/mpeg; codecs="mp3"');
+ if (!bCanPlayMp3)
+ {
+ bCanPlayOgg = '' !== oAudioLocal.canPlayType('audio/ogg; codecs="vorbis"');
+ }
+
+ if (bCanPlayMp3 || bCanPlayOgg)
+ {
+ oAudio = oAudioLocal;
+ oAudio.preload = 'none';
+ oAudio.loop = false;
+ oAudio.autoplay = false;
+ oAudio.muted = false;
+ oAudio.src = bCanPlayMp3 ? sMp3File : sOggFile;
+ }
+ else
+ {
+ oAudio = null;
+ }
}
else
{
oAudio = null;
}
}
- else
- {
- oAudio = null;
- }
}
- }
- return oAudio;
+ return oAudio;
+ };
+ }());
+
+ /**
+ * @param {(Object|null|undefined)} oObject
+ * @param {string} sProp
+ * @return {boolean}
+ */
+ Utils.hos = function (oObject, sProp)
+ {
+ return oObject && window.Object && window.Object.hasOwnProperty ? window.Object.hasOwnProperty.call(oObject, sProp) : false;
};
-}());
-/**
- * @param {(Object|null|undefined)} oObject
- * @param {string} sProp
- * @return {boolean}
- */
-Utils.hos = function (oObject, sProp)
-{
- return oObject && Object.hasOwnProperty ? Object.hasOwnProperty.call(oObject, sProp) : false;
-};
-
-/**
- * @param {string} sKey
- * @param {Object=} oValueList
- * @param {string=} sDefaulValue
- * @return {string}
- */
-Utils.i18n = function (sKey, oValueList, sDefaulValue)
-{
- var
- sValueName = '',
- sResult = Utils.isUnd(I18n[sKey]) ? (Utils.isUnd(sDefaulValue) ? sKey : sDefaulValue) : I18n[sKey]
- ;
-
- if (!Utils.isUnd(oValueList) && !Utils.isNull(oValueList))
- {
- for (sValueName in oValueList)
- {
- if (Utils.hos(oValueList, sValueName))
- {
- sResult = sResult.replace('%' + sValueName + '%', oValueList[sValueName]);
- }
- }
- }
-
- return sResult;
-};
-
-/**
- * @param {Object} oElement
- */
-Utils.i18nToNode = function (oElement)
-{
- _.defer(function () {
- $('.i18n', oElement).each(function () {
- var
- jqThis = $(this),
- sKey = ''
- ;
-
- sKey = jqThis.data('i18n-text');
- if (sKey)
- {
- jqThis.text(Utils.i18n(sKey));
- }
- else
- {
- sKey = jqThis.data('i18n-html');
- if (sKey)
- {
- jqThis.html(Utils.i18n(sKey));
- }
-
- sKey = jqThis.data('i18n-placeholder');
- if (sKey)
- {
- jqThis.attr('placeholder', Utils.i18n(sKey));
- }
-
- sKey = jqThis.data('i18n-title');
- if (sKey)
- {
- jqThis.attr('title', Utils.i18n(sKey));
- }
- }
- });
- });
-};
-
-Utils.i18nToDoc = function ()
-{
- if (window.rainloopI18N)
- {
- I18n = window.rainloopI18N || {};
- Utils.i18nToNode($document);
-
- Globals.langChangeTrigger(!Globals.langChangeTrigger());
- }
-
- window.rainloopI18N = {};
-};
-
-/**
- * @param {Function} fCallback
- * @param {Object} oScope
- * @param {Function=} fLangCallback
- */
-Utils.initOnStartOrLangChange = function (fCallback, oScope, fLangCallback)
-{
- if (fCallback)
- {
- fCallback.call(oScope);
- }
-
- if (fLangCallback)
- {
- Globals.langChangeTrigger.subscribe(function () {
- if (fCallback)
- {
- fCallback.call(oScope);
- }
-
- fLangCallback.call(oScope);
- });
- }
- else if (fCallback)
- {
- Globals.langChangeTrigger.subscribe(fCallback, oScope);
- }
-};
-
-/**
- * @return {boolean}
- */
-Utils.inFocus = function ()
-{
- if (document.activeElement)
- {
- if (Utils.isUnd(document.activeElement.__inFocusCache))
- {
- document.activeElement.__inFocusCache = $(document.activeElement).is('input,textarea,iframe,.cke_editable');
- }
-
- return !!document.activeElement.__inFocusCache;
- }
-
- return false;
-};
-
-Utils.removeInFocus = function ()
-{
- if (document && document.activeElement && document.activeElement.blur)
- {
- var oA = $(document.activeElement);
- if (oA.is('input,textarea'))
- {
- document.activeElement.blur();
- }
- }
-};
-
-Utils.removeSelection = function ()
-{
- if (window && window.getSelection)
- {
- var oSel = window.getSelection();
- if (oSel && oSel.removeAllRanges)
- {
- oSel.removeAllRanges();
- }
- }
- else if (document && document.selection && document.selection.empty)
- {
- document.selection.empty();
- }
-};
-
-/**
- * @param {string} sPrefix
- * @param {string} sSubject
- * @return {string}
- */
-Utils.replySubjectAdd = function (sPrefix, sSubject)
-{
- sPrefix = Utils.trim(sPrefix.toUpperCase());
- sSubject = Utils.trim(sSubject.replace(/[\s]+/, ' '));
-
- var
- iIndex = 0,
- sResult = '',
- bDrop = false,
- sTrimmedPart = '',
- aSubject = [],
- aParts = [],
- bRe = 'RE' === sPrefix,
- bFwd = 'FWD' === sPrefix,
- bPrefixIsRe = !bFwd
- ;
-
- if ('' !== sSubject)
- {
- bDrop = false;
-
- aParts = sSubject.split(':');
- for (iIndex = 0; iIndex < aParts.length; iIndex++)
- {
- sTrimmedPart = Utils.trim(aParts[iIndex]);
- if (!bDrop &&
- (/^(RE|FWD)$/i.test(sTrimmedPart) || /^(RE|FWD)[\[\(][\d]+[\]\)]$/i.test(sTrimmedPart))
- )
- {
- if (!bRe)
- {
- bRe = !!(/^RE/i.test(sTrimmedPart));
- }
-
- if (!bFwd)
- {
- bFwd = !!(/^FWD/i.test(sTrimmedPart));
- }
- }
- else
- {
- aSubject.push(aParts[iIndex]);
- bDrop = true;
- }
- }
-
- if (0 < aSubject.length)
- {
- sResult = Utils.trim(aSubject.join(':'));
- }
- }
-
- if (bPrefixIsRe)
- {
- bRe = false;
- }
- else
- {
- bFwd = false;
- }
-
- return Utils.trim(
- (bPrefixIsRe ? 'Re: ' : 'Fwd: ') +
- (bRe ? 'Re: ' : '') +
- (bFwd ? 'Fwd: ' : '') +
- sResult
- );
-};
-
-
-/**
- * @param {string} sSubject
- * @return {string}
- */
-Utils.fixLongSubject = function (sSubject)
-{
- var
- iLimit = 30,
- mReg = /^Re([\[\(]([\d]+)[\]\)]|):[\s]{0,3}Re([\[\(]([\d]+)[\]\)]|):/ig,
- oMatch = null
- ;
-
- sSubject = Utils.trim(sSubject.replace(/[\s]+/, ' '));
-
- do
- {
- iLimit--;
-
- oMatch = mReg.exec(sSubject);
- if (!oMatch || Utils.isUnd(oMatch[0]))
- {
- oMatch = null;
- }
-
- if (oMatch)
- {
- sSubject = sSubject.replace(mReg, 'Re:');
- }
- }
- while (oMatch || 0 < iLimit);
-
- return sSubject.replace(/[\s]+/, ' ');
-};
-
-/**
- * @deprecated
- * @param {string} sPrefix
- * @param {string} sSubject
- * @param {boolean=} bFixLongSubject = true
- * @return {string}
- */
-Utils._replySubjectAdd_ = function (sPrefix, sSubject, bFixLongSubject)
-{
- var
- oMatch = null,
- sResult = Utils.trim(sSubject)
- ;
-
- if (null !== (oMatch = (new window.RegExp('^' + sPrefix + '[\\s]?\\:(.*)$', 'gi')).exec(sSubject)) && !Utils.isUnd(oMatch[1]))
- {
- sResult = sPrefix + '[2]: ' + oMatch[1];
- }
- else if (null !== (oMatch = (new window.RegExp('^(' + sPrefix + '[\\s]?[\\[\\(]?)([\\d]+)([\\]\\)]?[\\s]?\\:.*)$', 'gi')).exec(sSubject)) &&
- !Utils.isUnd(oMatch[1]) && !Utils.isUnd(oMatch[2]) && !Utils.isUnd(oMatch[3]))
- {
- sResult = oMatch[1] + (Utils.pInt(oMatch[2]) + 1) + oMatch[3];
- }
- else
- {
- sResult = sPrefix + ': ' + sSubject;
- }
-
- sResult = sResult.replace(/[\s]+/g, ' ');
- sResult = (Utils.isUnd(bFixLongSubject) ? true : bFixLongSubject) ? Utils.fixLongSubject(sResult) : sResult;
-// sResult = sResult.replace(/^(Re|Fwd)[\s]?\[[\d]+\]:/ig, '$1:');
- return sResult;
-};
-
-/**
- * @deprecated
- * @param {string} sSubject
- * @return {string}
- */
-Utils._fixLongSubject_ = function (sSubject)
-{
- var
- iCounter = 0,
- oMatch = null
- ;
-
- sSubject = Utils.trim(sSubject.replace(/[\s]+/, ' '));
-
- do
- {
- oMatch = /^Re(\[([\d]+)\]|):[\s]{0,3}Re(\[([\d]+)\]|):/ig.exec(sSubject);
- if (!oMatch || Utils.isUnd(oMatch[0]))
- {
- oMatch = null;
- }
-
- if (oMatch)
- {
- iCounter = 0;
- iCounter += Utils.isUnd(oMatch[2]) ? 1 : 0 + Utils.pInt(oMatch[2]);
- iCounter += Utils.isUnd(oMatch[4]) ? 1 : 0 + Utils.pInt(oMatch[4]);
-
- sSubject = sSubject.replace(/^Re(\[[\d]+\]|):[\s]{0,3}Re(\[[\d]+\]|):/gi, 'Re' + (0 < iCounter ? '[' + iCounter + ']' : '') + ':');
- }
-
- }
- while (oMatch);
-
- sSubject = sSubject.replace(/[\s]+/, ' ');
- return sSubject;
-};
-
-/**
- * @param {number} iNum
- * @param {number} iDec
- * @return {number}
- */
-Utils.roundNumber = function (iNum, iDec)
-{
- return Math.round(iNum * Math.pow(10, iDec)) / Math.pow(10, iDec);
-};
-
-/**
- * @param {(number|string)} iSizeInBytes
- * @return {string}
- */
-Utils.friendlySize = function (iSizeInBytes)
-{
- iSizeInBytes = Utils.pInt(iSizeInBytes);
-
- if (iSizeInBytes >= 1073741824)
- {
- return Utils.roundNumber(iSizeInBytes / 1073741824, 1) + 'GB';
- }
- else if (iSizeInBytes >= 1048576)
- {
- return Utils.roundNumber(iSizeInBytes / 1048576, 1) + 'MB';
- }
- else if (iSizeInBytes >= 1024)
- {
- return Utils.roundNumber(iSizeInBytes / 1024, 0) + 'KB';
- }
-
- return iSizeInBytes + 'B';
-};
-
-/**
- * @param {string} sDesc
- */
-Utils.log = function (sDesc)
-{
- if (window.console && window.console.log)
- {
- window.console.log(sDesc);
- }
-};
-
-/**
- * @param {number} iCode
- * @param {*=} mMessage = ''
- * @return {string}
- */
-Utils.getNotification = function (iCode, mMessage)
-{
- iCode = Utils.pInt(iCode);
- if (Enums.Notification.ClientViewError === iCode && mMessage)
- {
- return mMessage;
- }
-
- return Utils.isUnd(NotificationI18N[iCode]) ? '' : NotificationI18N[iCode];
-};
-
-Utils.initNotificationLanguage = function ()
-{
- NotificationI18N[Enums.Notification.InvalidToken] = Utils.i18n('NOTIFICATIONS/INVALID_TOKEN');
- NotificationI18N[Enums.Notification.AuthError] = Utils.i18n('NOTIFICATIONS/AUTH_ERROR');
- NotificationI18N[Enums.Notification.AccessError] = Utils.i18n('NOTIFICATIONS/ACCESS_ERROR');
- NotificationI18N[Enums.Notification.ConnectionError] = Utils.i18n('NOTIFICATIONS/CONNECTION_ERROR');
- NotificationI18N[Enums.Notification.CaptchaError] = Utils.i18n('NOTIFICATIONS/CAPTCHA_ERROR');
- NotificationI18N[Enums.Notification.SocialFacebookLoginAccessDisable] = Utils.i18n('NOTIFICATIONS/SOCIAL_FACEBOOK_LOGIN_ACCESS_DISABLE');
- NotificationI18N[Enums.Notification.SocialTwitterLoginAccessDisable] = Utils.i18n('NOTIFICATIONS/SOCIAL_TWITTER_LOGIN_ACCESS_DISABLE');
- NotificationI18N[Enums.Notification.SocialGoogleLoginAccessDisable] = Utils.i18n('NOTIFICATIONS/SOCIAL_GOOGLE_LOGIN_ACCESS_DISABLE');
- NotificationI18N[Enums.Notification.DomainNotAllowed] = Utils.i18n('NOTIFICATIONS/DOMAIN_NOT_ALLOWED');
- NotificationI18N[Enums.Notification.AccountNotAllowed] = Utils.i18n('NOTIFICATIONS/ACCOUNT_NOT_ALLOWED');
-
- NotificationI18N[Enums.Notification.AccountTwoFactorAuthRequired] = Utils.i18n('NOTIFICATIONS/ACCOUNT_TWO_FACTOR_AUTH_REQUIRED');
- NotificationI18N[Enums.Notification.AccountTwoFactorAuthError] = Utils.i18n('NOTIFICATIONS/ACCOUNT_TWO_FACTOR_AUTH_ERROR');
-
- NotificationI18N[Enums.Notification.CouldNotSaveNewPassword] = Utils.i18n('NOTIFICATIONS/COULD_NOT_SAVE_NEW_PASSWORD');
- NotificationI18N[Enums.Notification.CurrentPasswordIncorrect] = Utils.i18n('NOTIFICATIONS/CURRENT_PASSWORD_INCORRECT');
- NotificationI18N[Enums.Notification.NewPasswordShort] = Utils.i18n('NOTIFICATIONS/NEW_PASSWORD_SHORT');
- NotificationI18N[Enums.Notification.NewPasswordWeak] = Utils.i18n('NOTIFICATIONS/NEW_PASSWORD_WEAK');
- NotificationI18N[Enums.Notification.NewPasswordForbidden] = Utils.i18n('NOTIFICATIONS/NEW_PASSWORD_FORBIDDENT');
-
- NotificationI18N[Enums.Notification.ContactsSyncError] = Utils.i18n('NOTIFICATIONS/CONTACTS_SYNC_ERROR');
-
- NotificationI18N[Enums.Notification.CantGetMessageList] = Utils.i18n('NOTIFICATIONS/CANT_GET_MESSAGE_LIST');
- NotificationI18N[Enums.Notification.CantGetMessage] = Utils.i18n('NOTIFICATIONS/CANT_GET_MESSAGE');
- NotificationI18N[Enums.Notification.CantDeleteMessage] = Utils.i18n('NOTIFICATIONS/CANT_DELETE_MESSAGE');
- NotificationI18N[Enums.Notification.CantMoveMessage] = Utils.i18n('NOTIFICATIONS/CANT_MOVE_MESSAGE');
- NotificationI18N[Enums.Notification.CantCopyMessage] = Utils.i18n('NOTIFICATIONS/CANT_MOVE_MESSAGE');
-
- NotificationI18N[Enums.Notification.CantSaveMessage] = Utils.i18n('NOTIFICATIONS/CANT_SAVE_MESSAGE');
- NotificationI18N[Enums.Notification.CantSendMessage] = Utils.i18n('NOTIFICATIONS/CANT_SEND_MESSAGE');
- NotificationI18N[Enums.Notification.InvalidRecipients] = Utils.i18n('NOTIFICATIONS/INVALID_RECIPIENTS');
-
- NotificationI18N[Enums.Notification.CantCreateFolder] = Utils.i18n('NOTIFICATIONS/CANT_CREATE_FOLDER');
- NotificationI18N[Enums.Notification.CantRenameFolder] = Utils.i18n('NOTIFICATIONS/CANT_RENAME_FOLDER');
- NotificationI18N[Enums.Notification.CantDeleteFolder] = Utils.i18n('NOTIFICATIONS/CANT_DELETE_FOLDER');
- NotificationI18N[Enums.Notification.CantDeleteNonEmptyFolder] = Utils.i18n('NOTIFICATIONS/CANT_DELETE_NON_EMPTY_FOLDER');
- NotificationI18N[Enums.Notification.CantSubscribeFolder] = Utils.i18n('NOTIFICATIONS/CANT_SUBSCRIBE_FOLDER');
- NotificationI18N[Enums.Notification.CantUnsubscribeFolder] = Utils.i18n('NOTIFICATIONS/CANT_UNSUBSCRIBE_FOLDER');
-
- NotificationI18N[Enums.Notification.CantSaveSettings] = Utils.i18n('NOTIFICATIONS/CANT_SAVE_SETTINGS');
- NotificationI18N[Enums.Notification.CantSavePluginSettings] = Utils.i18n('NOTIFICATIONS/CANT_SAVE_PLUGIN_SETTINGS');
-
- NotificationI18N[Enums.Notification.DomainAlreadyExists] = Utils.i18n('NOTIFICATIONS/DOMAIN_ALREADY_EXISTS');
-
- NotificationI18N[Enums.Notification.CantInstallPackage] = Utils.i18n('NOTIFICATIONS/CANT_INSTALL_PACKAGE');
- NotificationI18N[Enums.Notification.CantDeletePackage] = Utils.i18n('NOTIFICATIONS/CANT_DELETE_PACKAGE');
- NotificationI18N[Enums.Notification.InvalidPluginPackage] = Utils.i18n('NOTIFICATIONS/INVALID_PLUGIN_PACKAGE');
- NotificationI18N[Enums.Notification.UnsupportedPluginPackage] = Utils.i18n('NOTIFICATIONS/UNSUPPORTED_PLUGIN_PACKAGE');
-
- NotificationI18N[Enums.Notification.LicensingServerIsUnavailable] = Utils.i18n('NOTIFICATIONS/LICENSING_SERVER_IS_UNAVAILABLE');
- NotificationI18N[Enums.Notification.LicensingExpired] = Utils.i18n('NOTIFICATIONS/LICENSING_EXPIRED');
- NotificationI18N[Enums.Notification.LicensingBanned] = Utils.i18n('NOTIFICATIONS/LICENSING_BANNED');
-
- NotificationI18N[Enums.Notification.DemoSendMessageError] = Utils.i18n('NOTIFICATIONS/DEMO_SEND_MESSAGE_ERROR');
-
- NotificationI18N[Enums.Notification.AccountAlreadyExists] = Utils.i18n('NOTIFICATIONS/ACCOUNT_ALREADY_EXISTS');
-
- NotificationI18N[Enums.Notification.MailServerError] = Utils.i18n('NOTIFICATIONS/MAIL_SERVER_ERROR');
- NotificationI18N[Enums.Notification.InvalidInputArgument] = Utils.i18n('NOTIFICATIONS/INVALID_INPUT_ARGUMENT');
- NotificationI18N[Enums.Notification.UnknownNotification] = Utils.i18n('NOTIFICATIONS/UNKNOWN_ERROR');
- NotificationI18N[Enums.Notification.UnknownError] = Utils.i18n('NOTIFICATIONS/UNKNOWN_ERROR');
-};
-
-/**
- * @param {*} mCode
- * @return {string}
- */
-Utils.getUploadErrorDescByCode = function (mCode)
-{
- var sResult = '';
- switch (Utils.pInt(mCode)) {
- case Enums.UploadErrorCode.FileIsTooBig:
- sResult = Utils.i18n('UPLOAD/ERROR_FILE_IS_TOO_BIG');
- break;
- case Enums.UploadErrorCode.FilePartiallyUploaded:
- sResult = Utils.i18n('UPLOAD/ERROR_FILE_PARTIALLY_UPLOADED');
- break;
- case Enums.UploadErrorCode.FileNoUploaded:
- sResult = Utils.i18n('UPLOAD/ERROR_NO_FILE_UPLOADED');
- break;
- case Enums.UploadErrorCode.MissingTempFolder:
- sResult = Utils.i18n('UPLOAD/ERROR_MISSING_TEMP_FOLDER');
- break;
- case Enums.UploadErrorCode.FileOnSaveingError:
- sResult = Utils.i18n('UPLOAD/ERROR_ON_SAVING_FILE');
- break;
- case Enums.UploadErrorCode.FileType:
- sResult = Utils.i18n('UPLOAD/ERROR_FILE_TYPE');
- break;
- default:
- sResult = Utils.i18n('UPLOAD/ERROR_UNKNOWN');
- break;
- }
-
- return sResult;
-};
-
-/**
- * @param {?} oObject
- * @param {string} sMethodName
- * @param {Array=} aParameters
- * @param {number=} nDelay
- */
-Utils.delegateRun = function (oObject, sMethodName, aParameters, nDelay)
-{
- if (oObject && oObject[sMethodName])
- {
- nDelay = Utils.pInt(nDelay);
- if (0 >= nDelay)
- {
- oObject[sMethodName].apply(oObject, Utils.isArray(aParameters) ? aParameters : []);
- }
- else
- {
- _.delay(function () {
- oObject[sMethodName].apply(oObject, Utils.isArray(aParameters) ? aParameters : []);
- }, nDelay);
- }
- }
-};
-
-/**
- * @param {?} oEvent
- */
-Utils.killCtrlAandS = function (oEvent)
-{
- oEvent = oEvent || window.event;
- if (oEvent && oEvent.ctrlKey && !oEvent.shiftKey && !oEvent.altKey)
+ /**
+ * @param {string} sKey
+ * @param {Object=} oValueList
+ * @param {string=} sDefaulValue
+ * @return {string}
+ */
+ Utils.i18n = function (sKey, oValueList, sDefaulValue)
{
var
- oSender = oEvent.target || oEvent.srcElement,
- iKey = oEvent.keyCode || oEvent.which
+ sValueName = '',
+ sResult = Utils.isUnd(Globals.oI18N[sKey]) ? (Utils.isUnd(sDefaulValue) ? sKey : sDefaulValue) : Globals.oI18N[sKey]
;
- if (iKey === Enums.EventKeyCode.S)
+ if (!Utils.isUnd(oValueList) && !Utils.isNull(oValueList))
{
- oEvent.preventDefault();
- return;
+ for (sValueName in oValueList)
+ {
+ if (Utils.hos(oValueList, sValueName))
+ {
+ sResult = sResult.replace('%' + sValueName + '%', oValueList[sValueName]);
+ }
+ }
}
- if (oSender && oSender.tagName && oSender.tagName.match(/INPUT|TEXTAREA/i))
- {
- return;
- }
+ return sResult;
+ };
- if (iKey === Enums.EventKeyCode.A)
- {
- if (window.getSelection)
- {
- window.getSelection().removeAllRanges();
- }
- else if (window.document.selection && window.document.selection.clear)
- {
- window.document.selection.clear();
- }
-
- oEvent.preventDefault();
- }
- }
-};
-
-/**
- * @param {(Object|null|undefined)} oContext
- * @param {Function} fExecute
- * @param {(Function|boolean|null)=} fCanExecute
- * @return {Function}
- */
-Utils.createCommand = function (oContext, fExecute, fCanExecute)
-{
- var
- fResult = fExecute ? function () {
- if (fResult.canExecute && fResult.canExecute())
- {
- fExecute.apply(oContext, Array.prototype.slice.call(arguments));
- }
- return false;
- } : function () {}
- ;
-
- fResult.enabled = ko.observable(true);
-
- fCanExecute = Utils.isUnd(fCanExecute) ? true : fCanExecute;
- if (Utils.isFunc(fCanExecute))
+ /**
+ * @param {Object} oElement
+ */
+ Utils.i18nToNode = function (oElement)
{
- fResult.canExecute = ko.computed(function () {
- return fResult.enabled() && fCanExecute.call(oContext);
+ _.defer(function () {
+ $('.i18n', oElement).each(function () {
+ var
+ jqThis = $(this),
+ sKey = ''
+ ;
+
+ sKey = jqThis.data('i18n-text');
+ if (sKey)
+ {
+ jqThis.text(Utils.i18n(sKey));
+ }
+ else
+ {
+ sKey = jqThis.data('i18n-html');
+ if (sKey)
+ {
+ jqThis.html(Utils.i18n(sKey));
+ }
+
+ sKey = jqThis.data('i18n-placeholder');
+ if (sKey)
+ {
+ jqThis.attr('placeholder', Utils.i18n(sKey));
+ }
+
+ sKey = jqThis.data('i18n-title');
+ if (sKey)
+ {
+ jqThis.attr('title', Utils.i18n(sKey));
+ }
+ }
+ });
});
- }
- else
+ };
+
+ Utils.i18nReload = function ()
{
- fResult.canExecute = ko.computed(function () {
- return fResult.enabled() && !!fCanExecute;
- });
- }
-
- return fResult;
-};
-
-/**
- * @param {Object} oData
- */
-Utils.initDataConstructorBySettings = function (oData)
-{
- oData.editorDefaultType = ko.observable(Enums.EditorDefaultType.Html);
- oData.showImages = ko.observable(false);
- oData.interfaceAnimation = ko.observable(Enums.InterfaceAnimation.Full);
- oData.contactsAutosave = ko.observable(false);
-
- Globals.sAnimationType = Enums.InterfaceAnimation.Full;
-
- oData.capaThemes = ko.observable(false);
- oData.allowLanguagesOnSettings = ko.observable(true);
- oData.allowLanguagesOnLogin = ko.observable(true);
-
- oData.useLocalProxyForExternalImages = ko.observable(false);
-
- oData.desktopNotifications = ko.observable(false);
- oData.useThreads = ko.observable(true);
- oData.replySameFolder = ko.observable(true);
- oData.useCheckboxesInList = ko.observable(true);
-
- oData.layout = ko.observable(Enums.Layout.SidePreview);
- oData.usePreviewPane = ko.computed(function () {
- return Enums.Layout.NoPreview !== oData.layout();
- });
-
- oData.interfaceAnimation.subscribe(function (sValue) {
- if (Globals.bMobileDevice || sValue === Enums.InterfaceAnimation.None)
+ if (window['rainloopI18N'])
{
- $html.removeClass('rl-anim rl-anim-full').addClass('no-rl-anim');
+ Globals.oI18N = window['rainloopI18N'] || {};
+
+ Utils.i18nToNode($doc);
+
+ Globals.langChangeTrigger(!Globals.langChangeTrigger());
+ }
- Globals.sAnimationType = Enums.InterfaceAnimation.None;
+ window['rainloopI18N'] = null;
+ };
+
+ /**
+ * @param {Function} fCallback
+ * @param {Object} oScope
+ * @param {Function=} fLangCallback
+ */
+ Utils.initOnStartOrLangChange = function (fCallback, oScope, fLangCallback)
+ {
+ if (fCallback)
+ {
+ fCallback.call(oScope);
+ }
+
+ if (fLangCallback)
+ {
+ Globals.langChangeTrigger.subscribe(function () {
+ if (fCallback)
+ {
+ fCallback.call(oScope);
+ }
+
+ fLangCallback.call(oScope);
+ });
+ }
+ else if (fCallback)
+ {
+ Globals.langChangeTrigger.subscribe(fCallback, oScope);
+ }
+ };
+
+ /**
+ * @return {boolean}
+ */
+ Utils.inFocus = function ()
+ {
+ if (document.activeElement)
+ {
+ if (Utils.isUnd(document.activeElement.__inFocusCache))
+ {
+ document.activeElement.__inFocusCache = $(document.activeElement).is('input,textarea,iframe,.cke_editable');
+ }
+
+ return !!document.activeElement.__inFocusCache;
+ }
+
+ return false;
+ };
+
+ Utils.removeInFocus = function ()
+ {
+ if (document && document.activeElement && document.activeElement.blur)
+ {
+ var oA = $(document.activeElement);
+ if (oA.is('input,textarea'))
+ {
+ document.activeElement.blur();
+ }
+ }
+ };
+
+ Utils.removeSelection = function ()
+ {
+ if (window && window.getSelection)
+ {
+ var oSel = window.getSelection();
+ if (oSel && oSel.removeAllRanges)
+ {
+ oSel.removeAllRanges();
+ }
+ }
+ else if (document && document.selection && document.selection.empty)
+ {
+ document.selection.empty();
+ }
+ };
+
+ /**
+ * @param {string} sPrefix
+ * @param {string} sSubject
+ * @return {string}
+ */
+ Utils.replySubjectAdd = function (sPrefix, sSubject)
+ {
+ sPrefix = Utils.trim(sPrefix.toUpperCase());
+ sSubject = Utils.trim(sSubject.replace(/[\s]+/, ' '));
+
+ var
+ iIndex = 0,
+ sResult = '',
+ bDrop = false,
+ sTrimmedPart = '',
+ aSubject = [],
+ aParts = [],
+ bRe = 'RE' === sPrefix,
+ bFwd = 'FWD' === sPrefix,
+ bPrefixIsRe = !bFwd
+ ;
+
+ if ('' !== sSubject)
+ {
+ bDrop = false;
+
+ aParts = sSubject.split(':');
+ for (iIndex = 0; iIndex < aParts.length; iIndex++)
+ {
+ sTrimmedPart = Utils.trim(aParts[iIndex]);
+ if (!bDrop &&
+ (/^(RE|FWD)$/i.test(sTrimmedPart) || /^(RE|FWD)[\[\(][\d]+[\]\)]$/i.test(sTrimmedPart))
+ )
+ {
+ if (!bRe)
+ {
+ bRe = !!(/^RE/i.test(sTrimmedPart));
+ }
+
+ if (!bFwd)
+ {
+ bFwd = !!(/^FWD/i.test(sTrimmedPart));
+ }
+ }
+ else
+ {
+ aSubject.push(aParts[iIndex]);
+ bDrop = true;
+ }
+ }
+
+ if (0 < aSubject.length)
+ {
+ sResult = Utils.trim(aSubject.join(':'));
+ }
+ }
+
+ if (bPrefixIsRe)
+ {
+ bRe = false;
}
else
{
- switch (sValue)
+ bFwd = false;
+ }
+
+ return Utils.trim(
+ (bPrefixIsRe ? 'Re: ' : 'Fwd: ') +
+ (bRe ? 'Re: ' : '') +
+ (bFwd ? 'Fwd: ' : '') +
+ sResult
+ );
+ };
+
+
+ /**
+ * @param {string} sSubject
+ * @return {string}
+ */
+ Utils.fixLongSubject = function (sSubject)
+ {
+ var
+ iLimit = 30,
+ mReg = /^Re([\[\(]([\d]+)[\]\)]|):[\s]{0,3}Re([\[\(]([\d]+)[\]\)]|):/ig,
+ oMatch = null
+ ;
+
+ sSubject = Utils.trim(sSubject.replace(/[\s]+/, ' '));
+
+ do
+ {
+ iLimit--;
+
+ oMatch = mReg.exec(sSubject);
+ if (!oMatch || Utils.isUnd(oMatch[0]))
{
- case Enums.InterfaceAnimation.Full:
- $html.removeClass('no-rl-anim').addClass('rl-anim rl-anim-full');
- Globals.sAnimationType = sValue;
- break;
- case Enums.InterfaceAnimation.Normal:
- $html.removeClass('no-rl-anim rl-anim-full').addClass('rl-anim');
- Globals.sAnimationType = sValue;
- break;
+ oMatch = null;
+ }
+
+ if (oMatch)
+ {
+ sSubject = sSubject.replace(mReg, 'Re:');
}
}
- });
+ while (oMatch || 0 < iLimit);
- oData.interfaceAnimation.valueHasMutated();
+ return sSubject.replace(/[\s]+/, ' ');
+ };
- oData.desktopNotificationsPermisions = ko.computed(function () {
- oData.desktopNotifications();
- var iResult = Enums.DesktopNotifications.NotSupported;
- if (NotificationClass && NotificationClass.permission)
+ /**
+ * @deprecated
+ * @param {string} sPrefix
+ * @param {string} sSubject
+ * @param {boolean=} bFixLongSubject = true
+ * @return {string}
+ */
+ Utils._replySubjectAdd_ = function (sPrefix, sSubject, bFixLongSubject)
+ {
+ var
+ oMatch = null,
+ sResult = Utils.trim(sSubject)
+ ;
+
+ if (null !== (oMatch = (new window.RegExp('^' + sPrefix + '[\\s]?\\:(.*)$', 'gi')).exec(sSubject)) && !Utils.isUnd(oMatch[1]))
{
- switch (NotificationClass.permission.toLowerCase())
+ sResult = sPrefix + '[2]: ' + oMatch[1];
+ }
+ else if (null !== (oMatch = (new window.RegExp('^(' + sPrefix + '[\\s]?[\\[\\(]?)([\\d]+)([\\]\\)]?[\\s]?\\:.*)$', 'gi')).exec(sSubject)) &&
+ !Utils.isUnd(oMatch[1]) && !Utils.isUnd(oMatch[2]) && !Utils.isUnd(oMatch[3]))
+ {
+ sResult = oMatch[1] + (Utils.pInt(oMatch[2]) + 1) + oMatch[3];
+ }
+ else
+ {
+ sResult = sPrefix + ': ' + sSubject;
+ }
+
+ sResult = sResult.replace(/[\s]+/g, ' ');
+ sResult = (Utils.isUnd(bFixLongSubject) ? true : bFixLongSubject) ? Utils.fixLongSubject(sResult) : sResult;
+ // sResult = sResult.replace(/^(Re|Fwd)[\s]?\[[\d]+\]:/ig, '$1:');
+ return sResult;
+ };
+
+ /**
+ * @deprecated
+ * @param {string} sSubject
+ * @return {string}
+ */
+ Utils._fixLongSubject_ = function (sSubject)
+ {
+ var
+ iCounter = 0,
+ oMatch = null
+ ;
+
+ sSubject = Utils.trim(sSubject.replace(/[\s]+/, ' '));
+
+ do
+ {
+ oMatch = /^Re(\[([\d]+)\]|):[\s]{0,3}Re(\[([\d]+)\]|):/ig.exec(sSubject);
+ if (!oMatch || Utils.isUnd(oMatch[0]))
{
- case 'granted':
- iResult = Enums.DesktopNotifications.Allowed;
- break;
- case 'denied':
- iResult = Enums.DesktopNotifications.Denied;
- break;
- case 'default':
- iResult = Enums.DesktopNotifications.NotAllowed;
- break;
+ oMatch = null;
+ }
+
+ if (oMatch)
+ {
+ iCounter = 0;
+ iCounter += Utils.isUnd(oMatch[2]) ? 1 : 0 + Utils.pInt(oMatch[2]);
+ iCounter += Utils.isUnd(oMatch[4]) ? 1 : 0 + Utils.pInt(oMatch[4]);
+
+ sSubject = sSubject.replace(/^Re(\[[\d]+\]|):[\s]{0,3}Re(\[[\d]+\]|):/gi, 'Re' + (0 < iCounter ? '[' + iCounter + ']' : '') + ':');
+ }
+
+ }
+ while (oMatch);
+
+ sSubject = sSubject.replace(/[\s]+/, ' ');
+ return sSubject;
+ };
+
+ /**
+ * @param {number} iNum
+ * @param {number} iDec
+ * @return {number}
+ */
+ Utils.roundNumber = function (iNum, iDec)
+ {
+ return window.Math.round(iNum * window.Math.pow(10, iDec)) / window.Math.pow(10, iDec);
+ };
+
+ /**
+ * @param {(number|string)} iSizeInBytes
+ * @return {string}
+ */
+ Utils.friendlySize = function (iSizeInBytes)
+ {
+ iSizeInBytes = Utils.pInt(iSizeInBytes);
+
+ if (iSizeInBytes >= 1073741824)
+ {
+ return Utils.roundNumber(iSizeInBytes / 1073741824, 1) + 'GB';
+ }
+ else if (iSizeInBytes >= 1048576)
+ {
+ return Utils.roundNumber(iSizeInBytes / 1048576, 1) + 'MB';
+ }
+ else if (iSizeInBytes >= 1024)
+ {
+ return Utils.roundNumber(iSizeInBytes / 1024, 0) + 'KB';
+ }
+
+ return iSizeInBytes + 'B';
+ };
+
+ /**
+ * @param {string} sDesc
+ */
+ Utils.log = function (sDesc)
+ {
+ if (window.console && window.console.log)
+ {
+ window.console.log(sDesc);
+ }
+ };
+
+ /**
+ * @param {number} iCode
+ * @param {*=} mMessage = ''
+ * @return {string}
+ */
+ Utils.getNotification = function (iCode, mMessage)
+ {
+ iCode = Utils.pInt(iCode);
+ if (Enums.Notification.ClientViewError === iCode && mMessage)
+ {
+ return mMessage;
+ }
+
+ return Utils.isUnd(Globals.oNotificationI18N[iCode]) ? '' : Globals.oNotificationI18N[iCode];
+ };
+
+ Utils.initNotificationLanguage = function ()
+ {
+ var oN = Globals.oNotificationI18N || {};
+ oN[Enums.Notification.InvalidToken] = Utils.i18n('NOTIFICATIONS/INVALID_TOKEN');
+ oN[Enums.Notification.AuthError] = Utils.i18n('NOTIFICATIONS/AUTH_ERROR');
+ oN[Enums.Notification.AccessError] = Utils.i18n('NOTIFICATIONS/ACCESS_ERROR');
+ oN[Enums.Notification.ConnectionError] = Utils.i18n('NOTIFICATIONS/CONNECTION_ERROR');
+ oN[Enums.Notification.CaptchaError] = Utils.i18n('NOTIFICATIONS/CAPTCHA_ERROR');
+ oN[Enums.Notification.SocialFacebookLoginAccessDisable] = Utils.i18n('NOTIFICATIONS/SOCIAL_FACEBOOK_LOGIN_ACCESS_DISABLE');
+ oN[Enums.Notification.SocialTwitterLoginAccessDisable] = Utils.i18n('NOTIFICATIONS/SOCIAL_TWITTER_LOGIN_ACCESS_DISABLE');
+ oN[Enums.Notification.SocialGoogleLoginAccessDisable] = Utils.i18n('NOTIFICATIONS/SOCIAL_GOOGLE_LOGIN_ACCESS_DISABLE');
+ oN[Enums.Notification.DomainNotAllowed] = Utils.i18n('NOTIFICATIONS/DOMAIN_NOT_ALLOWED');
+ oN[Enums.Notification.AccountNotAllowed] = Utils.i18n('NOTIFICATIONS/ACCOUNT_NOT_ALLOWED');
+
+ oN[Enums.Notification.AccountTwoFactorAuthRequired] = Utils.i18n('NOTIFICATIONS/ACCOUNT_TWO_FACTOR_AUTH_REQUIRED');
+ oN[Enums.Notification.AccountTwoFactorAuthError] = Utils.i18n('NOTIFICATIONS/ACCOUNT_TWO_FACTOR_AUTH_ERROR');
+
+ oN[Enums.Notification.CouldNotSaveNewPassword] = Utils.i18n('NOTIFICATIONS/COULD_NOT_SAVE_NEW_PASSWORD');
+ oN[Enums.Notification.CurrentPasswordIncorrect] = Utils.i18n('NOTIFICATIONS/CURRENT_PASSWORD_INCORRECT');
+ oN[Enums.Notification.NewPasswordShort] = Utils.i18n('NOTIFICATIONS/NEW_PASSWORD_SHORT');
+ oN[Enums.Notification.NewPasswordWeak] = Utils.i18n('NOTIFICATIONS/NEW_PASSWORD_WEAK');
+ oN[Enums.Notification.NewPasswordForbidden] = Utils.i18n('NOTIFICATIONS/NEW_PASSWORD_FORBIDDENT');
+
+ oN[Enums.Notification.ContactsSyncError] = Utils.i18n('NOTIFICATIONS/CONTACTS_SYNC_ERROR');
+
+ oN[Enums.Notification.CantGetMessageList] = Utils.i18n('NOTIFICATIONS/CANT_GET_MESSAGE_LIST');
+ oN[Enums.Notification.CantGetMessage] = Utils.i18n('NOTIFICATIONS/CANT_GET_MESSAGE');
+ oN[Enums.Notification.CantDeleteMessage] = Utils.i18n('NOTIFICATIONS/CANT_DELETE_MESSAGE');
+ oN[Enums.Notification.CantMoveMessage] = Utils.i18n('NOTIFICATIONS/CANT_MOVE_MESSAGE');
+ oN[Enums.Notification.CantCopyMessage] = Utils.i18n('NOTIFICATIONS/CANT_MOVE_MESSAGE');
+
+ oN[Enums.Notification.CantSaveMessage] = Utils.i18n('NOTIFICATIONS/CANT_SAVE_MESSAGE');
+ oN[Enums.Notification.CantSendMessage] = Utils.i18n('NOTIFICATIONS/CANT_SEND_MESSAGE');
+ oN[Enums.Notification.InvalidRecipients] = Utils.i18n('NOTIFICATIONS/INVALID_RECIPIENTS');
+
+ oN[Enums.Notification.CantCreateFolder] = Utils.i18n('NOTIFICATIONS/CANT_CREATE_FOLDER');
+ oN[Enums.Notification.CantRenameFolder] = Utils.i18n('NOTIFICATIONS/CANT_RENAME_FOLDER');
+ oN[Enums.Notification.CantDeleteFolder] = Utils.i18n('NOTIFICATIONS/CANT_DELETE_FOLDER');
+ oN[Enums.Notification.CantDeleteNonEmptyFolder] = Utils.i18n('NOTIFICATIONS/CANT_DELETE_NON_EMPTY_FOLDER');
+ oN[Enums.Notification.CantSubscribeFolder] = Utils.i18n('NOTIFICATIONS/CANT_SUBSCRIBE_FOLDER');
+ oN[Enums.Notification.CantUnsubscribeFolder] = Utils.i18n('NOTIFICATIONS/CANT_UNSUBSCRIBE_FOLDER');
+
+ oN[Enums.Notification.CantSaveSettings] = Utils.i18n('NOTIFICATIONS/CANT_SAVE_SETTINGS');
+ oN[Enums.Notification.CantSavePluginSettings] = Utils.i18n('NOTIFICATIONS/CANT_SAVE_PLUGIN_SETTINGS');
+
+ oN[Enums.Notification.DomainAlreadyExists] = Utils.i18n('NOTIFICATIONS/DOMAIN_ALREADY_EXISTS');
+
+ oN[Enums.Notification.CantInstallPackage] = Utils.i18n('NOTIFICATIONS/CANT_INSTALL_PACKAGE');
+ oN[Enums.Notification.CantDeletePackage] = Utils.i18n('NOTIFICATIONS/CANT_DELETE_PACKAGE');
+ oN[Enums.Notification.InvalidPluginPackage] = Utils.i18n('NOTIFICATIONS/INVALID_PLUGIN_PACKAGE');
+ oN[Enums.Notification.UnsupportedPluginPackage] = Utils.i18n('NOTIFICATIONS/UNSUPPORTED_PLUGIN_PACKAGE');
+
+ oN[Enums.Notification.LicensingServerIsUnavailable] = Utils.i18n('NOTIFICATIONS/LICENSING_SERVER_IS_UNAVAILABLE');
+ oN[Enums.Notification.LicensingExpired] = Utils.i18n('NOTIFICATIONS/LICENSING_EXPIRED');
+ oN[Enums.Notification.LicensingBanned] = Utils.i18n('NOTIFICATIONS/LICENSING_BANNED');
+
+ oN[Enums.Notification.DemoSendMessageError] = Utils.i18n('NOTIFICATIONS/DEMO_SEND_MESSAGE_ERROR');
+
+ oN[Enums.Notification.AccountAlreadyExists] = Utils.i18n('NOTIFICATIONS/ACCOUNT_ALREADY_EXISTS');
+
+ oN[Enums.Notification.MailServerError] = Utils.i18n('NOTIFICATIONS/MAIL_SERVER_ERROR');
+ oN[Enums.Notification.InvalidInputArgument] = Utils.i18n('NOTIFICATIONS/INVALID_INPUT_ARGUMENT');
+ oN[Enums.Notification.UnknownNotification] = Utils.i18n('NOTIFICATIONS/UNKNOWN_ERROR');
+ oN[Enums.Notification.UnknownError] = Utils.i18n('NOTIFICATIONS/UNKNOWN_ERROR');
+ };
+
+ /**
+ * @param {*} mCode
+ * @return {string}
+ */
+ Utils.getUploadErrorDescByCode = function (mCode)
+ {
+ var sResult = '';
+ switch (Utils.pInt(mCode)) {
+ case Enums.UploadErrorCode.FileIsTooBig:
+ sResult = Utils.i18n('UPLOAD/ERROR_FILE_IS_TOO_BIG');
+ break;
+ case Enums.UploadErrorCode.FilePartiallyUploaded:
+ sResult = Utils.i18n('UPLOAD/ERROR_FILE_PARTIALLY_UPLOADED');
+ break;
+ case Enums.UploadErrorCode.FileNoUploaded:
+ sResult = Utils.i18n('UPLOAD/ERROR_NO_FILE_UPLOADED');
+ break;
+ case Enums.UploadErrorCode.MissingTempFolder:
+ sResult = Utils.i18n('UPLOAD/ERROR_MISSING_TEMP_FOLDER');
+ break;
+ case Enums.UploadErrorCode.FileOnSaveingError:
+ sResult = Utils.i18n('UPLOAD/ERROR_ON_SAVING_FILE');
+ break;
+ case Enums.UploadErrorCode.FileType:
+ sResult = Utils.i18n('UPLOAD/ERROR_FILE_TYPE');
+ break;
+ default:
+ sResult = Utils.i18n('UPLOAD/ERROR_UNKNOWN');
+ break;
+ }
+
+ return sResult;
+ };
+
+ /**
+ * @param {?} oObject
+ * @param {string} sMethodName
+ * @param {Array=} aParameters
+ * @param {number=} nDelay
+ */
+ Utils.delegateRun = function (oObject, sMethodName, aParameters, nDelay)
+ {
+ if (oObject && oObject[sMethodName])
+ {
+ nDelay = Utils.pInt(nDelay);
+ if (0 >= nDelay)
+ {
+ oObject[sMethodName].apply(oObject, Utils.isArray(aParameters) ? aParameters : []);
+ }
+ else
+ {
+ _.delay(function () {
+ oObject[sMethodName].apply(oObject, Utils.isArray(aParameters) ? aParameters : []);
+ }, nDelay);
}
}
- else if (window.webkitNotifications && window.webkitNotifications.checkPermission)
+ };
+
+ /**
+ * @param {?} oEvent
+ */
+ Utils.killCtrlAandS = function (oEvent)
+ {
+ oEvent = oEvent || window.event;
+ if (oEvent && oEvent.ctrlKey && !oEvent.shiftKey && !oEvent.altKey)
{
- iResult = window.webkitNotifications.checkPermission();
- }
+ var
+ oSender = oEvent.target || oEvent.srcElement,
+ iKey = oEvent.keyCode || oEvent.which
+ ;
- return iResult;
- });
-
- oData.useDesktopNotifications = ko.computed({
- 'read': function () {
- return oData.desktopNotifications() &&
- Enums.DesktopNotifications.Allowed === oData.desktopNotificationsPermisions();
- },
- 'write': function (bValue) {
- if (bValue)
+ if (iKey === Enums.EventKeyCode.S)
{
- var iPermission = oData.desktopNotificationsPermisions();
- if (Enums.DesktopNotifications.Allowed === iPermission)
+ oEvent.preventDefault();
+ return;
+ }
+
+ if (oSender && oSender.tagName && oSender.tagName.match(/INPUT|TEXTAREA/i))
+ {
+ return;
+ }
+
+ if (iKey === Enums.EventKeyCode.A)
+ {
+ if (window.getSelection)
{
- oData.desktopNotifications(true);
+ window.getSelection().removeAllRanges();
}
- else if (Enums.DesktopNotifications.NotAllowed === iPermission)
+ else if (window.document.selection && window.document.selection.clear)
{
- NotificationClass.requestPermission(function () {
- oData.desktopNotifications.valueHasMutated();
- if (Enums.DesktopNotifications.Allowed === oData.desktopNotificationsPermisions())
- {
- if (oData.desktopNotifications())
+ window.document.selection.clear();
+ }
+
+ oEvent.preventDefault();
+ }
+ }
+ };
+
+ /**
+ * @param {(Object|null|undefined)} oContext
+ * @param {Function} fExecute
+ * @param {(Function|boolean|null)=} fCanExecute
+ * @return {Function}
+ */
+ Utils.createCommand = function (oContext, fExecute, fCanExecute)
+ {
+ var
+ fResult = fExecute ? function () {
+ if (fResult.canExecute && fResult.canExecute())
+ {
+ fExecute.apply(oContext, Array.prototype.slice.call(arguments));
+ }
+ return false;
+ } : function () {}
+ ;
+
+ fResult.enabled = ko.observable(true);
+
+ fCanExecute = Utils.isUnd(fCanExecute) ? true : fCanExecute;
+ if (Utils.isFunc(fCanExecute))
+ {
+ fResult.canExecute = ko.computed(function () {
+ return fResult.enabled() && fCanExecute.call(oContext);
+ });
+ }
+ else
+ {
+ fResult.canExecute = ko.computed(function () {
+ return fResult.enabled() && !!fCanExecute;
+ });
+ }
+
+ return fResult;
+ };
+
+ /**
+ * @param {Object} oData
+ */
+ Utils.initDataConstructorBySettings = function (oData)
+ {
+ oData.editorDefaultType = ko.observable(Enums.EditorDefaultType.Html);
+ oData.showImages = ko.observable(false);
+ oData.interfaceAnimation = ko.observable(Enums.InterfaceAnimation.Full);
+ oData.contactsAutosave = ko.observable(false);
+
+ Globals.sAnimationType = Enums.InterfaceAnimation.Full;
+
+ oData.capaThemes = ko.observable(false);
+ oData.allowLanguagesOnSettings = ko.observable(true);
+ oData.allowLanguagesOnLogin = ko.observable(true);
+
+ oData.useLocalProxyForExternalImages = ko.observable(false);
+
+ oData.desktopNotifications = ko.observable(false);
+ oData.useThreads = ko.observable(true);
+ oData.replySameFolder = ko.observable(true);
+ oData.useCheckboxesInList = ko.observable(true);
+
+ oData.layout = ko.observable(Enums.Layout.SidePreview);
+ oData.usePreviewPane = ko.computed(function () {
+ return Enums.Layout.NoPreview !== oData.layout();
+ });
+
+ oData.interfaceAnimation.subscribe(function (sValue) {
+ if (Globals.bMobileDevice || sValue === Enums.InterfaceAnimation.None)
+ {
+ $html.removeClass('rl-anim rl-anim-full').addClass('no-rl-anim');
+
+ Globals.sAnimationType = Enums.InterfaceAnimation.None;
+ }
+ else
+ {
+ switch (sValue)
+ {
+ case Enums.InterfaceAnimation.Full:
+ $html.removeClass('no-rl-anim').addClass('rl-anim rl-anim-full');
+ Globals.sAnimationType = sValue;
+ break;
+ case Enums.InterfaceAnimation.Normal:
+ $html.removeClass('no-rl-anim rl-anim-full').addClass('rl-anim');
+ Globals.sAnimationType = sValue;
+ break;
+ }
+ }
+ });
+
+ oData.interfaceAnimation.valueHasMutated();
+
+ oData.desktopNotificationsPermisions = ko.computed(function () {
+ oData.desktopNotifications();
+ var iResult = Enums.DesktopNotifications.NotSupported;
+ if (NotificationClass && NotificationClass.permission)
+ {
+ switch (NotificationClass.permission.toLowerCase())
+ {
+ case 'granted':
+ iResult = Enums.DesktopNotifications.Allowed;
+ break;
+ case 'denied':
+ iResult = Enums.DesktopNotifications.Denied;
+ break;
+ case 'default':
+ iResult = Enums.DesktopNotifications.NotAllowed;
+ break;
+ }
+ }
+ else if (window.webkitNotifications && window.webkitNotifications.checkPermission)
+ {
+ iResult = window.webkitNotifications.checkPermission();
+ }
+
+ return iResult;
+ });
+
+ oData.useDesktopNotifications = ko.computed({
+ 'read': function () {
+ return oData.desktopNotifications() &&
+ Enums.DesktopNotifications.Allowed === oData.desktopNotificationsPermisions();
+ },
+ 'write': function (bValue) {
+ if (bValue)
+ {
+ var iPermission = oData.desktopNotificationsPermisions();
+ if (Enums.DesktopNotifications.Allowed === iPermission)
+ {
+ oData.desktopNotifications(true);
+ }
+ else if (Enums.DesktopNotifications.NotAllowed === iPermission)
+ {
+ NotificationClass.requestPermission(function () {
+ oData.desktopNotifications.valueHasMutated();
+ if (Enums.DesktopNotifications.Allowed === oData.desktopNotificationsPermisions())
{
- oData.desktopNotifications.valueHasMutated();
+ if (oData.desktopNotifications())
+ {
+ oData.desktopNotifications.valueHasMutated();
+ }
+ else
+ {
+ oData.desktopNotifications(true);
+ }
}
else
{
- oData.desktopNotifications(true);
+ if (oData.desktopNotifications())
+ {
+ oData.desktopNotifications(false);
+ }
+ else
+ {
+ oData.desktopNotifications.valueHasMutated();
+ }
}
- }
- else
- {
- if (oData.desktopNotifications())
- {
- oData.desktopNotifications(false);
- }
- else
- {
- oData.desktopNotifications.valueHasMutated();
- }
- }
- });
+ });
+ }
+ else
+ {
+ oData.desktopNotifications(false);
+ }
}
else
{
oData.desktopNotifications(false);
}
}
- else
- {
- oData.desktopNotifications(false);
- }
- }
- });
-
- oData.language = ko.observable('');
- oData.languages = ko.observableArray([]);
-
- oData.mainLanguage = ko.computed({
- 'read': oData.language,
- 'write': function (sValue) {
- if (sValue !== oData.language())
- {
- if (-1 < Utils.inArray(sValue, oData.languages()))
- {
- oData.language(sValue);
- }
- else if (0 < oData.languages().length)
- {
- oData.language(oData.languages()[0]);
- }
- }
- else
- {
- oData.language.valueHasMutated();
- }
- }
- });
-
- oData.theme = ko.observable('');
- oData.themes = ko.observableArray([]);
-
- oData.mainTheme = ko.computed({
- 'read': oData.theme,
- 'write': function (sValue) {
- if (sValue !== oData.theme())
- {
- var aThemes = oData.themes();
- if (-1 < Utils.inArray(sValue, aThemes))
- {
- oData.theme(sValue);
- }
- else if (0 < aThemes.length)
- {
- oData.theme(aThemes[0]);
- }
- }
- else
- {
- oData.theme.valueHasMutated();
- }
- }
- });
-
- oData.capaAdditionalAccounts = ko.observable(false);
- oData.capaAdditionalIdentities = ko.observable(false);
- oData.capaGravatar = ko.observable(false);
- oData.determineUserLanguage = ko.observable(false);
- oData.determineUserDomain = ko.observable(false);
-
- oData.messagesPerPage = ko.observable(Consts.Defaults.MessagesPerPage);//.extend({'throttle': 200});
-
- oData.mainMessagesPerPage = oData.messagesPerPage;
- oData.mainMessagesPerPage = ko.computed({
- 'read': oData.messagesPerPage,
- 'write': function (iValue) {
- if (-1 < Utils.inArray(Utils.pInt(iValue), Consts.Defaults.MessagesPerPageArray))
- {
- if (iValue !== oData.messagesPerPage())
- {
- oData.messagesPerPage(iValue);
- }
- }
- else
- {
- oData.messagesPerPage.valueHasMutated();
- }
- }
- });
-
- oData.facebookSupported = ko.observable(false);
- oData.facebookEnable = ko.observable(false);
- oData.facebookAppID = ko.observable('');
- oData.facebookAppSecret = ko.observable('');
-
- oData.twitterEnable = ko.observable(false);
- oData.twitterConsumerKey = ko.observable('');
- oData.twitterConsumerSecret = ko.observable('');
-
- oData.googleEnable = ko.observable(false);
- oData.googleClientID = ko.observable('');
- oData.googleClientSecret = ko.observable('');
- oData.googleApiKey = ko.observable('');
-
- oData.dropboxEnable = ko.observable(false);
- oData.dropboxApiKey = ko.observable('');
-
- oData.contactsIsAllowed = ko.observable(false);
-};
-
-/**
- * @param {{moment:Function}} oObject
- */
-Utils.createMomentDate = function (oObject)
-{
- if (Utils.isUnd(oObject.moment))
- {
- oObject.moment = ko.observable(moment());
- }
-
- return ko.computed(function () {
- Globals.momentTrigger();
- var oMoment = this.moment();
- return 1970 === oMoment.year() ? '' : oMoment.fromNow();
- }, oObject);
-};
-
-/**
- * @param {{moment:Function, momentDate:Function}} oObject
- */
-Utils.createMomentShortDate = function (oObject)
-{
- return ko.computed(function () {
-
- var
- sResult = '',
- oMomentNow = moment(),
- oMoment = this.moment(),
- sMomentDate = this.momentDate()
- ;
-
- if (1970 === oMoment.year())
- {
- sResult = '';
- }
- else if (4 >= oMomentNow.diff(oMoment, 'hours'))
- {
- sResult = sMomentDate;
- }
- else if (oMomentNow.format('L') === oMoment.format('L'))
- {
- sResult = Utils.i18n('MESSAGE_LIST/TODAY_AT', {
- 'TIME': oMoment.format('LT')
- });
- }
- else if (oMomentNow.clone().subtract('days', 1).format('L') === oMoment.format('L'))
- {
- sResult = Utils.i18n('MESSAGE_LIST/YESTERDAY_AT', {
- 'TIME': oMoment.format('LT')
- });
- }
- else if (oMomentNow.year() === oMoment.year())
- {
- sResult = oMoment.format('D MMM.');
- }
- else
- {
- sResult = oMoment.format('LL');
- }
-
- return sResult;
-
- }, oObject);
-};
-
-/**
- * @param {string} sFullNameHash
- * @return {boolean}
- */
-Utils.isFolderExpanded = function (sFullNameHash)
-{
- var aExpandedList = /** @type {Array|null} */ RL.local().get(Enums.ClientSideKeyName.ExpandedFolders);
- return _.isArray(aExpandedList) && -1 !== _.indexOf(aExpandedList, sFullNameHash);
-};
-
-/**
- * @param {string} sFullNameHash
- * @param {boolean} bExpanded
- */
-Utils.setExpandedFolder = function (sFullNameHash, bExpanded)
-{
- var aExpandedList = /** @type {Array|null} */ RL.local().get(Enums.ClientSideKeyName.ExpandedFolders);
- if (!_.isArray(aExpandedList))
- {
- aExpandedList = [];
- }
-
- if (bExpanded)
- {
- aExpandedList.push(sFullNameHash);
- aExpandedList = _.uniq(aExpandedList);
- }
- else
- {
- aExpandedList = _.without(aExpandedList, sFullNameHash);
- }
-
- RL.local().set(Enums.ClientSideKeyName.ExpandedFolders, aExpandedList);
-};
-
-Utils.initLayoutResizer = function (sLeft, sRight, sClientSideKeyName)
-{
- var
- iDisabledWidth = 60,
- iMinWidth = 155,
- oLeft = $(sLeft),
- oRight = $(sRight),
-
- mLeftWidth = RL.local().get(sClientSideKeyName) || null,
-
- fSetWidth = function (iWidth) {
- if (iWidth)
- {
- oLeft.css({
- 'width': '' + iWidth + 'px'
- });
-
- oRight.css({
- 'left': '' + iWidth + 'px'
- });
- }
- },
-
- fDisable = function (bDisable) {
- if (bDisable)
- {
- oLeft.resizable('disable');
- fSetWidth(iDisabledWidth);
- }
- else
- {
- oLeft.resizable('enable');
- var iWidth = Utils.pInt(RL.local().get(sClientSideKeyName)) || iMinWidth;
- fSetWidth(iWidth > iMinWidth ? iWidth : iMinWidth);
- }
- },
-
- fResizeFunction = function (oEvent, oObject) {
- if (oObject && oObject.size && oObject.size.width)
- {
- RL.local().set(sClientSideKeyName, oObject.size.width);
-
- oRight.css({
- 'left': '' + oObject.size.width + 'px'
- });
- }
- }
- ;
-
- if (null !== mLeftWidth)
- {
- fSetWidth(mLeftWidth > iMinWidth ? mLeftWidth : iMinWidth);
- }
-
- oLeft.resizable({
- 'helper': 'ui-resizable-helper',
- 'minWidth': iMinWidth,
- 'maxWidth': 350,
- 'handles': 'e',
- 'stop': fResizeFunction
- });
-
- RL.sub('left-panel.off', function () {
- fDisable(true);
- });
-
- RL.sub('left-panel.on', function () {
- fDisable(false);
- });
-};
-
-/**
- * @param {Object} oMessageTextBody
- */
-Utils.initBlockquoteSwitcher = function (oMessageTextBody)
-{
- if (oMessageTextBody)
- {
- var $oList = $('blockquote:not(.rl-bq-switcher)', oMessageTextBody).filter(function () {
- return 0 === $(this).parent().closest('blockquote', oMessageTextBody).length;
});
- if ($oList && 0 < $oList.length)
- {
- $oList.each(function () {
- var $self = $(this), iH = $self.height();
- if (0 === iH || 100 < iH)
+ oData.language = ko.observable('');
+ oData.languages = ko.observableArray([]);
+
+ oData.mainLanguage = ko.computed({
+ 'read': oData.language,
+ 'write': function (sValue) {
+ if (sValue !== oData.language())
{
- $self.addClass('rl-bq-switcher hidden-bq');
- $('')
- .insertBefore($self)
- .click(function () {
- $self.toggleClass('hidden-bq');
- Utils.windowResize();
- })
- .after('
')
- .before('
')
- ;
- }
- });
- }
- }
-};
-
-/**
- * @param {Object} oMessageTextBody
- */
-Utils.removeBlockquoteSwitcher = function (oMessageTextBody)
-{
- if (oMessageTextBody)
- {
- $(oMessageTextBody).find('blockquote.rl-bq-switcher').each(function () {
- $(this).removeClass('rl-bq-switcher hidden-bq');
- });
-
- $(oMessageTextBody).find('.rlBlockquoteSwitcher').each(function () {
- $(this).remove();
- });
- }
-};
-
-/**
- * @param {Object} oMessageTextBody
- */
-Utils.toggleMessageBlockquote = function (oMessageTextBody)
-{
- if (oMessageTextBody)
- {
- oMessageTextBody.find('.rlBlockquoteSwitcher').click();
- }
-};
-
-/**
- * @param {string} sName
- * @param {Function} ViewModelClass
- * @param {Function=} AbstractViewModel = KnoinAbstractViewModel
- */
-Utils.extendAsViewModel = function (sName, ViewModelClass, AbstractViewModel)
-{
- if (ViewModelClass)
- {
- if (!AbstractViewModel)
- {
- AbstractViewModel = KnoinAbstractViewModel;
- }
-
- ViewModelClass.__name = sName;
- Plugins.regViewModelHook(sName, ViewModelClass);
- _.extend(ViewModelClass.prototype, AbstractViewModel.prototype);
- }
-};
-
-/**
- * @param {Function} SettingsViewModelClass
- * @param {string} sLabelName
- * @param {string} sTemplate
- * @param {string} sRoute
- * @param {boolean=} bDefault
- */
-Utils.addSettingsViewModel = function (SettingsViewModelClass, sTemplate, sLabelName, sRoute, bDefault)
-{
- SettingsViewModelClass.__rlSettingsData = {
- 'Label': sLabelName,
- 'Template': sTemplate,
- 'Route': sRoute,
- 'IsDefault': !!bDefault
- };
-
- ViewModels['settings'].push(SettingsViewModelClass);
-};
-
-/**
- * @param {Function} SettingsViewModelClass
- */
-Utils.removeSettingsViewModel = function (SettingsViewModelClass)
-{
- ViewModels['settings-removed'].push(SettingsViewModelClass);
-};
-
-/**
- * @param {Function} SettingsViewModelClass
- */
-Utils.disableSettingsViewModel = function (SettingsViewModelClass)
-{
- ViewModels['settings-disabled'].push(SettingsViewModelClass);
-};
-
-Utils.convertThemeName = function (sTheme)
-{
- if ('@custom' === sTheme.substr(-7))
- {
- sTheme = Utils.trim(sTheme.substring(0, sTheme.length - 7));
- }
-
- return Utils.trim(sTheme.replace(/[^a-zA-Z]+/g, ' ').replace(/([A-Z])/g, ' $1').replace(/[\s]+/g, ' '));
-};
-
-/**
- * @param {string} sName
- * @return {string}
- */
-Utils.quoteName = function (sName)
-{
- return sName.replace(/["]/g, '\\"');
-};
-
-/**
- * @return {number}
- */
-Utils.microtime = function ()
-{
- return (new Date()).getTime();
-};
-
-/**
- *
- * @param {string} sLanguage
- * @param {boolean=} bEng = false
- * @return {string}
- */
-Utils.convertLangName = function (sLanguage, bEng)
-{
- return Utils.i18n('LANGS_NAMES' + (true === bEng ? '_EN' : '') + '/LANG_' +
- sLanguage.toUpperCase().replace(/[^a-zA-Z0-9]+/, '_'), null, sLanguage);
-};
-
-/**
- * @param {number=} iLen
- * @return {string}
- */
-Utils.fakeMd5 = function(iLen)
-{
- var
- sResult = '',
- sLine = '0123456789abcdefghijklmnopqrstuvwxyz'
- ;
-
- iLen = Utils.isUnd(iLen) ? 32 : Utils.pInt(iLen);
-
- while (sResult.length < iLen)
- {
- sResult += sLine.substr(Math.round(Math.random() * sLine.length), 1);
- }
-
- return sResult;
-};
-
-/* jshint ignore:start */
-
-/**
- * @param {string} s
- * @return {string}
- */
-Utils.md5 = function(s){function L(k,d){return(k<>>(32-d))}function K(G,k){var I,d,F,H,x;F=(G&2147483648);H=(k&2147483648);I=(G&1073741824);d=(k&1073741824);x=(G&1073741823)+(k&1073741823);if(I&d){return(x^2147483648^F^H)}if(I|d){if(x&1073741824){return(x^3221225472^F^H)}else{return(x^1073741824^F^H)}}else{return(x^F^H)}}function r(d,F,k){return(d&F)|((~d)&k)}function q(d,F,k){return(d&k)|(F&(~k))}function p(d,F,k){return(d^F^k)}function n(d,F,k){return(F^(d|(~k)))}function u(G,F,aa,Z,k,H,I){G=K(G,K(K(r(F,aa,Z),k),I));return K(L(G,H),F)}function f(G,F,aa,Z,k,H,I){G=K(G,K(K(q(F,aa,Z),k),I));return K(L(G,H),F)}function D(G,F,aa,Z,k,H,I){G=K(G,K(K(p(F,aa,Z),k),I));return K(L(G,H),F)}function t(G,F,aa,Z,k,H,I){G=K(G,K(K(n(F,aa,Z),k),I));return K(L(G,H),F)}function e(G){var Z;var F=G.length;var x=F+8;var k=(x-(x%64))/64;var I=(k+1)*16;var aa=Array(I-1);var d=0;var H=0;while(H>>29;return aa}function B(x){var k="",F="",G,d;for(d=0;d<=3;d++){G=(x>>>(d*8))&255;F="0"+G.toString(16);k=k+F.substr(F.length-2,2)}return k}function J(k){k=k.replace(/rn/g,"n");var d="";for(var F=0;F127)&&(x<2048)){d+=String.fromCharCode((x>>6)|192);d+=String.fromCharCode((x&63)|128)}else{d+=String.fromCharCode((x>>12)|224);d+=String.fromCharCode(((x>>6)&63)|128);d+=String.fromCharCode((x&63)|128)}}}return d}var C=Array();var P,h,E,v,g,Y,X,W,V;var S=7,Q=12,N=17,M=22;var A=5,z=9,y=14,w=20;var o=4,m=11,l=16,j=23;var U=6,T=10,R=15,O=21;s=J(s);C=e(s);Y=1732584193;X=4023233417;W=2562383102;V=271733878;for(P=0;P /g, '>').replace(/');
-};
-
-Utils.draggeblePlace = function ()
-{
- return $(' ').appendTo('#rl-hidden');
-};
-
-Utils.defautOptionsAfterRender = function (oOption, oItem)
-{
- if (oItem && !Utils.isUnd(oItem.disabled) && oOption)
- {
- $(oOption)
- .toggleClass('disabled', oItem.disabled)
- .prop('disabled', oItem.disabled)
- ;
- }
-};
-
-/**
- * @param {Object} oViewModel
- * @param {string} sTemplateID
- * @param {string} sTitle
- * @param {Function=} fCallback
- */
-Utils.windowPopupKnockout = function (oViewModel, sTemplateID, sTitle, fCallback)
-{
- var
- oScript = null,
- oWin = window.open(''),
- sFunc = '__OpenerApplyBindingsUid' + Utils.fakeMd5() + '__',
- oTemplate = $('#' + sTemplateID)
- ;
-
- window[sFunc] = function () {
-
- if (oWin && oWin.document.body && oTemplate && oTemplate[0])
- {
- var oBody = $(oWin.document.body);
-
- $('#rl-content', oBody).html(oTemplate.html());
- $('html', oWin.document).addClass('external ' + $('html').attr('class'));
-
- Utils.i18nToNode(oBody);
-
- Knoin.prototype.applyExternal(oViewModel, $('#rl-content', oBody)[0]);
-
- window[sFunc] = null;
-
- fCallback(oWin);
- }
- };
-
- oWin.document.open();
- oWin.document.write('' +
-'' +
-'' +
-'' +
-'' +
-'' +
-'' + Utils.encodeHtml(sTitle) + ' ' +
-'');
- oWin.document.close();
-
- oScript = oWin.document.createElement('script');
- oScript.type = 'text/javascript';
- oScript.innerHTML = 'if(window&&window.opener&&window.opener[\'' + sFunc + '\']){window.opener[\'' + sFunc + '\']();window.opener[\'' + sFunc + '\']=null}';
- oWin.document.getElementsByTagName('head')[0].appendChild(oScript);
-};
-
-Utils.settingsSaveHelperFunction = function (fCallback, koTrigger, oContext, iTimer)
-{
- oContext = oContext || null;
- iTimer = Utils.isUnd(iTimer) ? 1000 : Utils.pInt(iTimer);
- return function (sType, mData, bCached, sRequestAction, oRequestParameters) {
- koTrigger.call(oContext, mData && mData['Result'] ? Enums.SaveSettingsStep.TrueResult : Enums.SaveSettingsStep.FalseResult);
- if (fCallback)
- {
- fCallback.call(oContext, sType, mData, bCached, sRequestAction, oRequestParameters);
- }
- _.delay(function () {
- koTrigger.call(oContext, Enums.SaveSettingsStep.Idle);
- }, iTimer);
- };
-};
-
-Utils.settingsSaveHelperSimpleFunction = function (koTrigger, oContext)
-{
- return Utils.settingsSaveHelperFunction(null, koTrigger, oContext, 1000);
-};
-
-Utils.$div = $('');
-
-/**
- * @param {string} sHtml
- * @return {string}
- */
-Utils.htmlToPlain = function (sHtml)
-{
- var
- iPos = 0,
- iP1 = 0,
- iP2 = 0,
- iP3 = 0,
- iLimit = 0,
-
- sText = '',
-
- splitPlainText = function (sText)
- {
- var
- iLen = 100,
- sPrefix = '',
- sSubText = '',
- sResult = sText,
- iSpacePos = 0,
- iNewLinePos = 0
- ;
-
- while (sResult.length > iLen)
- {
- sSubText = sResult.substring(0, iLen);
- iSpacePos = sSubText.lastIndexOf(' ');
- iNewLinePos = sSubText.lastIndexOf('\n');
-
- if (-1 !== iNewLinePos)
- {
- iSpacePos = iNewLinePos;
- }
-
- if (-1 === iSpacePos)
- {
- iSpacePos = iLen;
- }
-
- sPrefix += sSubText.substring(0, iSpacePos) + '\n';
- sResult = sResult.substring(iSpacePos + 1);
- }
-
- return sPrefix + sResult;
- },
-
- convertBlockquote = function (sText) {
- sText = splitPlainText($.trim(sText));
- sText = '> ' + sText.replace(/\n/gm, '\n> ');
- return sText.replace(/(^|\n)([> ]+)/gm, function () {
- return (arguments && 2 < arguments.length) ? arguments[1] + $.trim(arguments[2].replace(/[\s]/, '')) + ' ' : '';
- });
- },
-
- convertDivs = function () {
- if (arguments && 1 < arguments.length)
- {
- var sText = $.trim(arguments[1]);
- if (0 < sText.length)
- {
- sText = sText.replace(/]*>([\s\S\r\n]*)<\/div>/gmi, convertDivs);
- sText = '\n' + $.trim(sText) + '\n';
- }
-
- return sText;
- }
-
- return '';
- },
-
- convertPre = function () {
- return (arguments && 1 < arguments.length) ? arguments[1].toString().replace(/[\n]/gm, '
') : '';
- },
-
- fixAttibuteValue = function () {
- return (arguments && 1 < arguments.length) ?
- '' + arguments[1] + arguments[2].replace(//g, '>') : '';
- },
-
- convertLinks = function () {
- return (arguments && 1 < arguments.length) ? $.trim(arguments[1]) : '';
- }
- ;
-
- sText = sHtml
- .replace(/]*>([\s\S\r\n]*)<\/pre>/gmi, convertPre)
- .replace(/[\s]+/gm, ' ')
- .replace(/((?:href|data)\s?=\s?)("[^"]+?"|'[^']+?')/gmi, fixAttibuteValue)
- .replace(/
]*>/gmi, '\n')
- .replace(/<\/h[\d]>/gi, '\n')
- .replace(/<\/p>/gi, '\n\n')
- .replace(/<\/li>/gi, '\n')
- .replace(/<\/td>/gi, '\n')
- .replace(/<\/tr>/gi, '\n')
- .replace(/
]*>/gmi, '\n_______________________________\n\n')
- .replace(/]*>([\s\S\r\n]*)<\/div>/gmi, convertDivs)
- .replace(/]*>/gmi, '\n__bq__start__\n')
- .replace(/<\/blockquote>/gmi, '\n__bq__end__\n')
- .replace(/]*>([\s\S\r\n]*?)<\/a>/gmi, convertLinks)
- .replace(/<\/div>/gi, '\n')
- .replace(/ /gi, ' ')
- .replace(/"/gi, '"')
- .replace(/<[^>]*>/gm, '')
- ;
-
- sText = Utils.$div.html(sText).text();
-
- sText = sText
- .replace(/\n[ \t]+/gm, '\n')
- .replace(/[\n]{3,}/gm, '\n\n')
- .replace(/>/gi, '>')
- .replace(/</gi, '<')
- .replace(/&/gi, '&')
- ;
-
- iPos = 0;
- iLimit = 100;
-
- while (0 < iLimit)
- {
- iLimit--;
- iP1 = sText.indexOf('__bq__start__', iPos);
- if (-1 < iP1)
- {
- iP2 = sText.indexOf('__bq__start__', iP1 + 5);
- iP3 = sText.indexOf('__bq__end__', iP1 + 5);
-
- if ((-1 === iP2 || iP3 < iP2) && iP1 < iP3)
- {
- sText = sText.substring(0, iP1) +
- convertBlockquote(sText.substring(iP1 + 13, iP3)) +
- sText.substring(iP3 + 11);
-
- iPos = 0;
- }
- else if (-1 < iP2 && iP2 < iP3)
- {
- iPos = iP2 - 1;
- }
- else
- {
- iPos = 0;
- }
- }
- else
- {
- break;
- }
- }
-
- sText = sText
- .replace(/__bq__start__/gm, '')
- .replace(/__bq__end__/gm, '')
- ;
-
- return sText;
-};
-
-/**
- * @param {string} sPlain
- * @param {boolean} bLinkify = false
- * @return {string}
- */
-Utils.plainToHtml = function (sPlain, bLinkify)
-{
- sPlain = sPlain.toString().replace(/\r/g, '');
-
- var
- bIn = false,
- bDo = true,
- bStart = true,
- aNextText = [],
- sLine = '',
- iIndex = 0,
- aText = sPlain.split("\n")
- ;
-
- do
- {
- bDo = false;
- aNextText = [];
- for (iIndex = 0; iIndex < aText.length; iIndex++)
- {
- sLine = aText[iIndex];
- bStart = '>' === sLine.substr(0, 1);
- if (bStart && !bIn)
- {
- bDo = true;
- bIn = true;
- aNextText.push('~~~blockquote~~~');
- aNextText.push(sLine.substr(1));
- }
- else if (!bStart && bIn)
- {
- bIn = false;
- aNextText.push('~~~/blockquote~~~');
- aNextText.push(sLine);
- }
- else if (bStart && bIn)
- {
- aNextText.push(sLine.substr(1));
- }
- else
- {
- aNextText.push(sLine);
- }
- }
-
- if (bIn)
- {
- bIn = false;
- aNextText.push('~~~/blockquote~~~');
- }
-
- aText = aNextText;
- }
- while (bDo);
-
- sPlain = aText.join("\n");
-
- sPlain = sPlain
- .replace(/&/g, '&')
- .replace(/>/g, '>').replace(/')
- .replace(/[\s]*~~~\/blockquote~~~/g, '
')
- .replace(/[\-_~]{10,}/g, '
')
- .replace(/\n/g, '
');
-
- return bLinkify ? Utils.linkify(sPlain) : sPlain;
-};
-
-window.rainloop_Utils_htmlToPlain = Utils.htmlToPlain;
-window.rainloop_Utils_plainToHtml = Utils.plainToHtml;
-
-/**
- * @param {string} sHtml
- * @return {string}
- */
-Utils.linkify = function (sHtml)
-{
- if ($.fn && $.fn.linkify)
- {
- sHtml = Utils.$div.html(sHtml.replace(/&/ig, 'amp_amp_12345_amp_amp'))
- .linkify()
- .find('.linkified').removeClass('linkified').end()
- .html()
- .replace(/amp_amp_12345_amp_amp/g, '&')
- ;
- }
-
- return sHtml;
-};
-
-Utils.resizeAndCrop = function (sUrl, iValue, fCallback)
-{
- var oTempImg = new window.Image();
- oTempImg.onload = function() {
-
- var
- aDiff = [0, 0],
- oCanvas = document.createElement('canvas'),
- oCtx = oCanvas.getContext('2d')
- ;
-
- oCanvas.width = iValue;
- oCanvas.height = iValue;
-
- if (this.width > this.height)
- {
- aDiff = [this.width - this.height, 0];
- }
- else
- {
- aDiff = [0, this.height - this.width];
- }
-
- oCtx.fillStyle = '#fff';
- oCtx.fillRect(0, 0, iValue, iValue);
- oCtx.drawImage(this, aDiff[0] / 2, aDiff[1] / 2, this.width - aDiff[0], this.height - aDiff[1], 0, 0, iValue, iValue);
-
- fCallback(oCanvas.toDataURL('image/jpeg'));
- };
-
- oTempImg.src = sUrl;
-};
-
-Utils.computedPagenatorHelper = function (koCurrentPage, koPageCount)
-{
- return function() {
- var
- iPrev = 0,
- iNext = 0,
- iLimit = 2,
- aResult = [],
- iCurrentPage = koCurrentPage(),
- iPageCount = koPageCount(),
-
- /**
- * @param {number} iIndex
- * @param {boolean=} bPush
- * @param {string=} sCustomName
- */
- fAdd = function (iIndex, bPush, sCustomName) {
-
- var oData = {
- 'current': iIndex === iCurrentPage,
- 'name': Utils.isUnd(sCustomName) ? iIndex.toString() : sCustomName.toString(),
- 'custom': Utils.isUnd(sCustomName) ? false : true,
- 'title': Utils.isUnd(sCustomName) ? '' : iIndex.toString(),
- 'value': iIndex.toString()
- };
-
- if (Utils.isUnd(bPush) ? true : !!bPush)
- {
- aResult.push(oData);
+ if (-1 < Utils.inArray(sValue, oData.languages()))
+ {
+ oData.language(sValue);
+ }
+ else if (0 < oData.languages().length)
+ {
+ oData.language(oData.languages()[0]);
+ }
}
else
{
- aResult.unshift(oData);
+ oData.language.valueHasMutated();
}
}
- ;
+ });
- if (1 < iPageCount || (0 < iPageCount && iPageCount < iCurrentPage))
-// if (0 < iPageCount && 0 < iCurrentPage)
+ oData.theme = ko.observable('');
+ oData.themes = ko.observableArray([]);
+
+ oData.mainTheme = ko.computed({
+ 'read': oData.theme,
+ 'write': function (sValue) {
+ if (sValue !== oData.theme())
+ {
+ var aThemes = oData.themes();
+ if (-1 < Utils.inArray(sValue, aThemes))
+ {
+ oData.theme(sValue);
+ }
+ else if (0 < aThemes.length)
+ {
+ oData.theme(aThemes[0]);
+ }
+ }
+ else
+ {
+ oData.theme.valueHasMutated();
+ }
+ }
+ });
+
+ oData.capaAdditionalAccounts = ko.observable(false);
+ oData.capaAdditionalIdentities = ko.observable(false);
+ oData.capaGravatar = ko.observable(false);
+ oData.determineUserLanguage = ko.observable(false);
+ oData.determineUserDomain = ko.observable(false);
+
+ oData.messagesPerPage = ko.observable(Consts.Defaults.MessagesPerPage);//.extend({'throttle': 200});
+
+ oData.mainMessagesPerPage = oData.messagesPerPage;
+ oData.mainMessagesPerPage = ko.computed({
+ 'read': oData.messagesPerPage,
+ 'write': function (iValue) {
+ if (-1 < Utils.inArray(Utils.pInt(iValue), Consts.Defaults.MessagesPerPageArray))
+ {
+ if (iValue !== oData.messagesPerPage())
+ {
+ oData.messagesPerPage(iValue);
+ }
+ }
+ else
+ {
+ oData.messagesPerPage.valueHasMutated();
+ }
+ }
+ });
+
+ oData.facebookSupported = ko.observable(false);
+ oData.facebookEnable = ko.observable(false);
+ oData.facebookAppID = ko.observable('');
+ oData.facebookAppSecret = ko.observable('');
+
+ oData.twitterEnable = ko.observable(false);
+ oData.twitterConsumerKey = ko.observable('');
+ oData.twitterConsumerSecret = ko.observable('');
+
+ oData.googleEnable = ko.observable(false);
+ oData.googleClientID = ko.observable('');
+ oData.googleClientSecret = ko.observable('');
+ oData.googleApiKey = ko.observable('');
+
+ oData.dropboxEnable = ko.observable(false);
+ oData.dropboxApiKey = ko.observable('');
+
+ oData.contactsIsAllowed = ko.observable(false);
+ };
+
+ /**
+ * @param {{moment:Function}} oObject
+ */
+ Utils.createMomentDate = function (oObject)
+ {
+ if (Utils.isUnd(oObject.moment))
{
- if (iPageCount < iCurrentPage)
+ oObject.moment = ko.observable(moment());
+ }
+
+ return ko.computed(function () {
+ Globals.momentTrigger();
+ var oMoment = this.moment();
+ return 1970 === oMoment.year() ? '' : oMoment.fromNow();
+ }, oObject);
+ };
+
+ /**
+ * @param {{moment:Function, momentDate:Function}} oObject
+ */
+ Utils.createMomentShortDate = function (oObject)
+ {
+ return ko.computed(function () {
+
+ var
+ sResult = '',
+ oMomentNow = moment(),
+ oMoment = this.moment(),
+ sMomentDate = this.momentDate()
+ ;
+
+ if (1970 === oMoment.year())
{
- fAdd(iPageCount);
- iPrev = iPageCount;
- iNext = iPageCount;
+ sResult = '';
+ }
+ else if (4 >= oMomentNow.diff(oMoment, 'hours'))
+ {
+ sResult = sMomentDate;
+ }
+ else if (oMomentNow.format('L') === oMoment.format('L'))
+ {
+ sResult = Utils.i18n('MESSAGE_LIST/TODAY_AT', {
+ 'TIME': oMoment.format('LT')
+ });
+ }
+ else if (oMomentNow.clone().subtract('days', 1).format('L') === oMoment.format('L'))
+ {
+ sResult = Utils.i18n('MESSAGE_LIST/YESTERDAY_AT', {
+ 'TIME': oMoment.format('LT')
+ });
+ }
+ else if (oMomentNow.year() === oMoment.year())
+ {
+ sResult = oMoment.format('D MMM.');
}
else
{
- if (3 >= iCurrentPage || iPageCount - 2 <= iCurrentPage)
- {
- iLimit += 2;
- }
-
- fAdd(iCurrentPage);
- iPrev = iCurrentPage;
- iNext = iCurrentPage;
+ sResult = oMoment.format('LL');
}
- while (0 < iLimit) {
+ return sResult;
- iPrev -= 1;
- iNext += 1;
+ }, oObject);
+ };
- if (0 < iPrev)
+ /**
+ * @param {Object} oMessageTextBody
+ */
+ Utils.initBlockquoteSwitcher = function (oMessageTextBody)
+ {
+ if (oMessageTextBody)
+ {
+ var $oList = $('blockquote:not(.rl-bq-switcher)', oMessageTextBody).filter(function () {
+ return 0 === $(this).parent().closest('blockquote', oMessageTextBody).length;
+ });
+
+ if ($oList && 0 < $oList.length)
+ {
+ $oList.each(function () {
+ var $self = $(this), iH = $self.height();
+ if (0 === iH || 100 < iH)
+ {
+ $self.addClass('rl-bq-switcher hidden-bq');
+ $('')
+ .insertBefore($self)
+ .click(function () {
+ $self.toggleClass('hidden-bq');
+ Utils.windowResize();
+ })
+ .after('
')
+ .before('
')
+ ;
+ }
+ });
+ }
+ }
+ };
+
+ /**
+ * @param {Object} oMessageTextBody
+ */
+ Utils.removeBlockquoteSwitcher = function (oMessageTextBody)
+ {
+ if (oMessageTextBody)
+ {
+ $(oMessageTextBody).find('blockquote.rl-bq-switcher').each(function () {
+ $(this).removeClass('rl-bq-switcher hidden-bq');
+ });
+
+ $(oMessageTextBody).find('.rlBlockquoteSwitcher').each(function () {
+ $(this).remove();
+ });
+ }
+ };
+
+ /**
+ * @param {Object} oMessageTextBody
+ */
+ Utils.toggleMessageBlockquote = function (oMessageTextBody)
+ {
+ if (oMessageTextBody)
+ {
+ oMessageTextBody.find('.rlBlockquoteSwitcher').click();
+ }
+ };
+
+ Utils.convertThemeName = function (sTheme)
+ {
+ if ('@custom' === sTheme.substr(-7))
+ {
+ sTheme = Utils.trim(sTheme.substring(0, sTheme.length - 7));
+ }
+
+ return Utils.trim(sTheme.replace(/[^a-zA-Z]+/g, ' ').replace(/([A-Z])/g, ' $1').replace(/[\s]+/g, ' '));
+ };
+
+ /**
+ * @param {string} sName
+ * @return {string}
+ */
+ Utils.quoteName = function (sName)
+ {
+ return sName.replace(/["]/g, '\\"');
+ };
+
+ /**
+ * @return {number}
+ */
+ Utils.microtime = function ()
+ {
+ return (new Date()).getTime();
+ };
+
+ /**
+ *
+ * @param {string} sLanguage
+ * @param {boolean=} bEng = false
+ * @return {string}
+ */
+ Utils.convertLangName = function (sLanguage, bEng)
+ {
+ return Utils.i18n('LANGS_NAMES' + (true === bEng ? '_EN' : '') + '/LANG_' +
+ sLanguage.toUpperCase().replace(/[^a-zA-Z0-9]+/, '_'), null, sLanguage);
+ };
+
+ /**
+ * @param {number=} iLen
+ * @return {string}
+ */
+ Utils.fakeMd5 = function(iLen)
+ {
+ var
+ sResult = '',
+ sLine = '0123456789abcdefghijklmnopqrstuvwxyz'
+ ;
+
+ iLen = Utils.isUnd(iLen) ? 32 : Utils.pInt(iLen);
+
+ while (sResult.length < iLen)
+ {
+ sResult += sLine.substr(window.Math.round(window.Math.random() * sLine.length), 1);
+ }
+
+ return sResult;
+ };
+
+ /* jshint ignore:start */
+
+ /**
+ * @param {string} s
+ * @return {string}
+ */
+ Utils.md5 = function(s){function L(k,d){return(k<>>(32-d))}function K(G,k){var I,d,F,H,x;F=(G&2147483648);H=(k&2147483648);I=(G&1073741824);d=(k&1073741824);x=(G&1073741823)+(k&1073741823);if(I&d){return(x^2147483648^F^H)}if(I|d){if(x&1073741824){return(x^3221225472^F^H)}else{return(x^1073741824^F^H)}}else{return(x^F^H)}}function r(d,F,k){return(d&F)|((~d)&k)}function q(d,F,k){return(d&k)|(F&(~k))}function p(d,F,k){return(d^F^k)}function n(d,F,k){return(F^(d|(~k)))}function u(G,F,aa,Z,k,H,I){G=K(G,K(K(r(F,aa,Z),k),I));return K(L(G,H),F)}function f(G,F,aa,Z,k,H,I){G=K(G,K(K(q(F,aa,Z),k),I));return K(L(G,H),F)}function D(G,F,aa,Z,k,H,I){G=K(G,K(K(p(F,aa,Z),k),I));return K(L(G,H),F)}function t(G,F,aa,Z,k,H,I){G=K(G,K(K(n(F,aa,Z),k),I));return K(L(G,H),F)}function e(G){var Z;var F=G.length;var x=F+8;var k=(x-(x%64))/64;var I=(k+1)*16;var aa=Array(I-1);var d=0;var H=0;while(H>>29;return aa}function B(x){var k="",F="",G,d;for(d=0;d<=3;d++){G=(x>>>(d*8))&255;F="0"+G.toString(16);k=k+F.substr(F.length-2,2)}return k}function J(k){k=k.replace(/rn/g,"n");var d="";for(var F=0;F127)&&(x<2048)){d+=String.fromCharCode((x>>6)|192);d+=String.fromCharCode((x&63)|128)}else{d+=String.fromCharCode((x>>12)|224);d+=String.fromCharCode(((x>>6)&63)|128);d+=String.fromCharCode((x&63)|128)}}}return d}var C=Array();var P,h,E,v,g,Y,X,W,V;var S=7,Q=12,N=17,M=22;var A=5,z=9,y=14,w=20;var o=4,m=11,l=16,j=23;var U=6,T=10,R=15,O=21;s=J(s);C=e(s);Y=1732584193;X=4023233417;W=2562383102;V=271733878;for(P=0;P /g, '>').replace(/');
+ };
+
+ Utils.draggeblePlace = function ()
+ {
+ return $(' ').appendTo('#rl-hidden');
+ };
+
+ Utils.defautOptionsAfterRender = function (oOption, oItem)
+ {
+ if (oItem && !Utils.isUnd(oItem.disabled) && oOption)
+ {
+ $(oOption)
+ .toggleClass('disabled', oItem.disabled)
+ .prop('disabled', oItem.disabled)
+ ;
+ }
+ };
+
+ /**
+ * @param {Object} oViewModel
+ * @param {string} sTemplateID
+ * @param {string} sTitle
+ * @param {Function=} fCallback
+ */
+ Utils.windowPopupKnockout = function (oViewModel, sTemplateID, sTitle, fCallback)
+ {
+ var
+ oScript = null,
+ oWin = window.open(''),
+ sFunc = '__OpenerApplyBindingsUid' + Utils.fakeMd5() + '__',
+ oTemplate = $('#' + sTemplateID)
+ ;
+
+ window[sFunc] = function () {
+
+ if (oWin && oWin.document.body && oTemplate && oTemplate[0])
+ {
+ var oBody = $(oWin.document.body);
+
+ $('#rl-content', oBody).html(oTemplate.html());
+ $('html', oWin.document).addClass('external ' + $('html').attr('class'));
+
+ Utils.i18nToNode(oBody);
+
+ if (oViewModel && $('#rl-content', oBody)[0])
{
- fAdd(iPrev, false);
- iLimit--;
+ ko.applyBindings(oViewModel, $('#rl-content', oBody)[0]);
}
- if (iPageCount >= iNext)
+ window[sFunc] = null;
+
+ fCallback(oWin);
+ }
+ };
+
+ oWin.document.open();
+ oWin.document.write('' +
+ '' +
+ '' +
+ '' +
+ '' +
+ '' +
+ '' + Utils.encodeHtml(sTitle) + ' ' +
+ '');
+ oWin.document.close();
+
+ oScript = oWin.document.createElement('script');
+ oScript.type = 'text/javascript';
+ oScript.innerHTML = 'if(window&&window.opener&&window.opener[\'' + sFunc + '\']){window.opener[\'' + sFunc + '\']();window.opener[\'' + sFunc + '\']=null}';
+ oWin.document.getElementsByTagName('head')[0].appendChild(oScript);
+ };
+
+ Utils.settingsSaveHelperFunction = function (fCallback, koTrigger, oContext, iTimer)
+ {
+ oContext = oContext || null;
+ iTimer = Utils.isUnd(iTimer) ? 1000 : Utils.pInt(iTimer);
+ return function (sType, mData, bCached, sRequestAction, oRequestParameters) {
+ koTrigger.call(oContext, mData && mData['Result'] ? Enums.SaveSettingsStep.TrueResult : Enums.SaveSettingsStep.FalseResult);
+ if (fCallback)
+ {
+ fCallback.call(oContext, sType, mData, bCached, sRequestAction, oRequestParameters);
+ }
+ _.delay(function () {
+ koTrigger.call(oContext, Enums.SaveSettingsStep.Idle);
+ }, iTimer);
+ };
+ };
+
+ Utils.settingsSaveHelperSimpleFunction = function (koTrigger, oContext)
+ {
+ return Utils.settingsSaveHelperFunction(null, koTrigger, oContext, 1000);
+ };
+
+ Utils.$div = $('');
+
+ /**
+ * @param {string} sHtml
+ * @return {string}
+ */
+ Utils.htmlToPlain = function (sHtml)
+ {
+ var
+ iPos = 0,
+ iP1 = 0,
+ iP2 = 0,
+ iP3 = 0,
+ iLimit = 0,
+
+ sText = '',
+
+ splitPlainText = function (sText)
+ {
+ var
+ iLen = 100,
+ sPrefix = '',
+ sSubText = '',
+ sResult = sText,
+ iSpacePos = 0,
+ iNewLinePos = 0
+ ;
+
+ while (sResult.length > iLen)
{
- fAdd(iNext, true);
- iLimit--;
+ sSubText = sResult.substring(0, iLen);
+ iSpacePos = sSubText.lastIndexOf(' ');
+ iNewLinePos = sSubText.lastIndexOf('\n');
+
+ if (-1 !== iNewLinePos)
+ {
+ iSpacePos = iNewLinePos;
+ }
+
+ if (-1 === iSpacePos)
+ {
+ iSpacePos = iLen;
+ }
+
+ sPrefix += sSubText.substring(0, iSpacePos) + '\n';
+ sResult = sResult.substring(iSpacePos + 1);
}
- else if (0 >= iPrev)
+
+ return sPrefix + sResult;
+ },
+
+ convertBlockquote = function (sText) {
+ sText = splitPlainText($.trim(sText));
+ sText = '> ' + sText.replace(/\n/gm, '\n> ');
+ return sText.replace(/(^|\n)([> ]+)/gm, function () {
+ return (arguments && 2 < arguments.length) ? arguments[1] + $.trim(arguments[2].replace(/[\s]/, '')) + ' ' : '';
+ });
+ },
+
+ convertDivs = function () {
+ if (arguments && 1 < arguments.length)
{
- break;
+ var sText = $.trim(arguments[1]);
+ if (0 < sText.length)
+ {
+ sText = sText.replace(/]*>([\s\S\r\n]*)<\/div>/gmi, convertDivs);
+ sText = '\n' + $.trim(sText) + '\n';
+ }
+
+ return sText;
+ }
+
+ return '';
+ },
+
+ convertPre = function () {
+ return (arguments && 1 < arguments.length) ? arguments[1].toString().replace(/[\n]/gm, '
') : '';
+ },
+
+ fixAttibuteValue = function () {
+ return (arguments && 1 < arguments.length) ?
+ '' + arguments[1] + arguments[2].replace(//g, '>') : '';
+ },
+
+ convertLinks = function () {
+ return (arguments && 1 < arguments.length) ? $.trim(arguments[1]) : '';
+ }
+ ;
+
+ sText = sHtml
+ .replace(/]*>([\s\S\r\n]*)<\/pre>/gmi, convertPre)
+ .replace(/[\s]+/gm, ' ')
+ .replace(/((?:href|data)\s?=\s?)("[^"]+?"|'[^']+?')/gmi, fixAttibuteValue)
+ .replace(/
]*>/gmi, '\n')
+ .replace(/<\/h[\d]>/gi, '\n')
+ .replace(/<\/p>/gi, '\n\n')
+ .replace(/<\/li>/gi, '\n')
+ .replace(/<\/td>/gi, '\n')
+ .replace(/<\/tr>/gi, '\n')
+ .replace(/
]*>/gmi, '\n_______________________________\n\n')
+ .replace(/]*>([\s\S\r\n]*)<\/div>/gmi, convertDivs)
+ .replace(/]*>/gmi, '\n__bq__start__\n')
+ .replace(/<\/blockquote>/gmi, '\n__bq__end__\n')
+ .replace(/]*>([\s\S\r\n]*?)<\/a>/gmi, convertLinks)
+ .replace(/<\/div>/gi, '\n')
+ .replace(/ /gi, ' ')
+ .replace(/"/gi, '"')
+ .replace(/<[^>]*>/gm, '')
+ ;
+
+ sText = Utils.$div.html(sText).text();
+
+ sText = sText
+ .replace(/\n[ \t]+/gm, '\n')
+ .replace(/[\n]{3,}/gm, '\n\n')
+ .replace(/>/gi, '>')
+ .replace(/</gi, '<')
+ .replace(/&/gi, '&')
+ ;
+
+ iPos = 0;
+ iLimit = 100;
+
+ while (0 < iLimit)
+ {
+ iLimit--;
+ iP1 = sText.indexOf('__bq__start__', iPos);
+ if (-1 < iP1)
+ {
+ iP2 = sText.indexOf('__bq__start__', iP1 + 5);
+ iP3 = sText.indexOf('__bq__end__', iP1 + 5);
+
+ if ((-1 === iP2 || iP3 < iP2) && iP1 < iP3)
+ {
+ sText = sText.substring(0, iP1) +
+ convertBlockquote(sText.substring(iP1 + 13, iP3)) +
+ sText.substring(iP3 + 11);
+
+ iPos = 0;
+ }
+ else if (-1 < iP2 && iP2 < iP3)
+ {
+ iPos = iP2 - 1;
+ }
+ else
+ {
+ iPos = 0;
+ }
+ }
+ else
+ {
+ break;
+ }
+ }
+
+ sText = sText
+ .replace(/__bq__start__/gm, '')
+ .replace(/__bq__end__/gm, '')
+ ;
+
+ return sText;
+ };
+
+ /**
+ * @param {string} sPlain
+ * @param {boolean} bLinkify = false
+ * @return {string}
+ */
+ Utils.plainToHtml = function (sPlain, bLinkify)
+ {
+ sPlain = sPlain.toString().replace(/\r/g, '');
+
+ var
+ bIn = false,
+ bDo = true,
+ bStart = true,
+ aNextText = [],
+ sLine = '',
+ iIndex = 0,
+ aText = sPlain.split("\n")
+ ;
+
+ do
+ {
+ bDo = false;
+ aNextText = [];
+ for (iIndex = 0; iIndex < aText.length; iIndex++)
+ {
+ sLine = aText[iIndex];
+ bStart = '>' === sLine.substr(0, 1);
+ if (bStart && !bIn)
+ {
+ bDo = true;
+ bIn = true;
+ aNextText.push('~~~blockquote~~~');
+ aNextText.push(sLine.substr(1));
+ }
+ else if (!bStart && bIn)
+ {
+ bIn = false;
+ aNextText.push('~~~/blockquote~~~');
+ aNextText.push(sLine);
+ }
+ else if (bStart && bIn)
+ {
+ aNextText.push(sLine.substr(1));
+ }
+ else
+ {
+ aNextText.push(sLine);
}
}
- if (3 === iPrev)
+ if (bIn)
{
- fAdd(2, false);
- }
- else if (3 < iPrev)
- {
- fAdd(Math.round((iPrev - 1) / 2), false, '...');
+ bIn = false;
+ aNextText.push('~~~/blockquote~~~');
}
- if (iPageCount - 2 === iNext)
+ aText = aNextText;
+ }
+ while (bDo);
+
+ sPlain = aText.join("\n");
+
+ sPlain = sPlain
+ .replace(/&/g, '&')
+ .replace(/>/g, '>').replace(/')
+ .replace(/[\s]*~~~\/blockquote~~~/g, '
')
+ .replace(/[\-_~]{10,}/g, '
')
+ .replace(/\n/g, '
');
+
+ return bLinkify ? Utils.linkify(sPlain) : sPlain;
+ };
+
+ window.rainloop_Utils_htmlToPlain = Utils.htmlToPlain;
+ window.rainloop_Utils_plainToHtml = Utils.plainToHtml;
+
+ /**
+ * @param {string} sHtml
+ * @return {string}
+ */
+ Utils.linkify = function (sHtml)
+ {
+ if ($.fn && $.fn.linkify)
+ {
+ sHtml = Utils.$div.html(sHtml.replace(/&/ig, 'amp_amp_12345_amp_amp'))
+ .linkify()
+ .find('.linkified').removeClass('linkified').end()
+ .html()
+ .replace(/amp_amp_12345_amp_amp/g, '&')
+ ;
+ }
+
+ return sHtml;
+ };
+
+ Utils.resizeAndCrop = function (sUrl, iValue, fCallback)
+ {
+ var oTempImg = new window.Image();
+ oTempImg.onload = function() {
+
+ var
+ aDiff = [0, 0],
+ oCanvas = document.createElement('canvas'),
+ oCtx = oCanvas.getContext('2d')
+ ;
+
+ oCanvas.width = iValue;
+ oCanvas.height = iValue;
+
+ if (this.width > this.height)
{
- fAdd(iPageCount - 1, true);
+ aDiff = [this.width - this.height, 0];
}
- else if (iPageCount - 2 > iNext)
+ else
{
- fAdd(Math.round((iPageCount + iNext) / 2), true, '...');
+ aDiff = [0, this.height - this.width];
}
- // first and last
- if (1 < iPrev)
+ oCtx.fillStyle = '#fff';
+ oCtx.fillRect(0, 0, iValue, iValue);
+ oCtx.drawImage(this, aDiff[0] / 2, aDiff[1] / 2, this.width - aDiff[0], this.height - aDiff[1], 0, 0, iValue, iValue);
+
+ fCallback(oCanvas.toDataURL('image/jpeg'));
+ };
+
+ oTempImg.src = sUrl;
+ };
+
+ /**
+ * @param {Array} aSystem
+ * @param {Array} aList
+ * @param {Array=} aDisabled
+ * @param {Array=} aHeaderLines
+ * @param {?number=} iUnDeep
+ * @param {Function=} fDisableCallback
+ * @param {Function=} fVisibleCallback
+ * @param {Function=} fRenameCallback
+ * @param {boolean=} bSystem
+ * @param {boolean=} bBuildUnvisible
+ * @return {Array}
+ */
+ Utils.folderListOptionsBuilder = function (aSystem, aList, aDisabled, aHeaderLines, iUnDeep, fDisableCallback, fVisibleCallback, fRenameCallback, bSystem, bBuildUnvisible)
+ {
+ var
+ /**
+ * @type {?FolderModel}
+ */
+ oItem = null,
+ bSep = false,
+ iIndex = 0,
+ iLen = 0,
+ sDeepPrefix = '\u00A0\u00A0\u00A0',
+ aResult = []
+ ;
+
+ bSystem = !Utils.isNormal(bSystem) ? 0 < aSystem.length : bSystem;
+ bBuildUnvisible = Utils.isUnd(bBuildUnvisible) ? false : !!bBuildUnvisible;
+ iUnDeep = !Utils.isNormal(iUnDeep) ? 0 : iUnDeep;
+ fDisableCallback = Utils.isNormal(fDisableCallback) ? fDisableCallback : null;
+ fVisibleCallback = Utils.isNormal(fVisibleCallback) ? fVisibleCallback : null;
+ fRenameCallback = Utils.isNormal(fRenameCallback) ? fRenameCallback : null;
+
+ if (!Utils.isArray(aDisabled))
+ {
+ aDisabled = [];
+ }
+
+ if (!Utils.isArray(aHeaderLines))
+ {
+ aHeaderLines = [];
+ }
+
+ for (iIndex = 0, iLen = aHeaderLines.length; iIndex < iLen; iIndex++)
+ {
+ aResult.push({
+ 'id': aHeaderLines[iIndex][0],
+ 'name': aHeaderLines[iIndex][1],
+ 'system': false,
+ 'seporator': false,
+ 'disabled': false
+ });
+ }
+
+ bSep = true;
+ for (iIndex = 0, iLen = aSystem.length; iIndex < iLen; iIndex++)
+ {
+ oItem = aSystem[iIndex];
+ if (fVisibleCallback ? fVisibleCallback.call(null, oItem) : true)
{
- fAdd(1, false);
+ if (bSep && 0 < aResult.length)
+ {
+ aResult.push({
+ 'id': '---',
+ 'name': '---',
+ 'system': false,
+ 'seporator': true,
+ 'disabled': true
+ });
+ }
+
+ bSep = false;
+ aResult.push({
+ 'id': oItem.fullNameRaw,
+ 'name': fRenameCallback ? fRenameCallback.call(null, oItem) : oItem.name(),
+ 'system': true,
+ 'seporator': false,
+ 'disabled': !oItem.selectable || -1 < Utils.inArray(oItem.fullNameRaw, aDisabled) ||
+ (fDisableCallback ? fDisableCallback.call(null, oItem) : false)
+ });
+ }
+ }
+
+ bSep = true;
+ for (iIndex = 0, iLen = aList.length; iIndex < iLen; iIndex++)
+ {
+ oItem = aList[iIndex];
+ if (oItem.subScribed() || !oItem.existen)
+ {
+ if (fVisibleCallback ? fVisibleCallback.call(null, oItem) : true)
+ {
+ if (Enums.FolderType.User === oItem.type() || !bSystem || 0 < oItem.subFolders().length)
+ {
+ if (bSep && 0 < aResult.length)
+ {
+ aResult.push({
+ 'id': '---',
+ 'name': '---',
+ 'system': false,
+ 'seporator': true,
+ 'disabled': true
+ });
+ }
+
+ bSep = false;
+ aResult.push({
+ 'id': oItem.fullNameRaw,
+ 'name': (new window.Array(oItem.deep + 1 - iUnDeep)).join(sDeepPrefix) +
+ (fRenameCallback ? fRenameCallback.call(null, oItem) : oItem.name()),
+ 'system': false,
+ 'seporator': false,
+ 'disabled': !oItem.selectable || -1 < Utils.inArray(oItem.fullNameRaw, aDisabled) ||
+ (fDisableCallback ? fDisableCallback.call(null, oItem) : false)
+ });
+ }
+ }
}
- if (iPageCount > iNext)
+ if (oItem.subScribed() && 0 < oItem.subFolders().length)
{
- fAdd(iPageCount, true);
+ aResult = aResult.concat(Utils.folderListOptionsBuilder([], oItem.subFolders(), aDisabled, [],
+ iUnDeep, fDisableCallback, fVisibleCallback, fRenameCallback, bSystem, bBuildUnvisible));
}
}
return aResult;
};
-};
-Utils.selectElement = function (element)
-{
- /* jshint onevar: false */
- if (window.getSelection)
+ Utils.computedPagenatorHelper = function (koCurrentPage, koPageCount)
{
- var sel = window.getSelection();
- sel.removeAllRanges();
- var range = document.createRange();
- range.selectNodeContents(element);
- sel.addRange(range);
- }
- else if (document.selection)
- {
- var textRange = document.body.createTextRange();
- textRange.moveToElementText(element);
- textRange.select();
- }
- /* jshint onevar: true */
-};
+ return function() {
+ var
+ iPrev = 0,
+ iNext = 0,
+ iLimit = 2,
+ aResult = [],
+ iCurrentPage = koCurrentPage(),
+ iPageCount = koPageCount(),
-Utils.disableKeyFilter = function ()
-{
- if (window.key)
- {
- key.filter = function () {
- return RL.data().useKeyboardShortcuts();
- };
- }
-};
+ /**
+ * @param {number} iIndex
+ * @param {boolean=} bPush
+ * @param {string=} sCustomName
+ */
+ fAdd = function (iIndex, bPush, sCustomName) {
-Utils.restoreKeyFilter = function ()
-{
- if (window.key)
- {
- key.filter = function (event) {
+ var oData = {
+ 'current': iIndex === iCurrentPage,
+ 'name': Utils.isUnd(sCustomName) ? iIndex.toString() : sCustomName.toString(),
+ 'custom': Utils.isUnd(sCustomName) ? false : true,
+ 'title': Utils.isUnd(sCustomName) ? '' : iIndex.toString(),
+ 'value': iIndex.toString()
+ };
- if (RL.data().useKeyboardShortcuts())
+ if (Utils.isUnd(bPush) ? true : !!bPush)
+ {
+ aResult.push(oData);
+ }
+ else
+ {
+ aResult.unshift(oData);
+ }
+ }
+ ;
+
+ if (1 < iPageCount || (0 < iPageCount && iPageCount < iCurrentPage))
+ // if (0 < iPageCount && 0 < iCurrentPage)
{
- var
- element = event.target || event.srcElement,
- tagName = element ? element.tagName : ''
- ;
+ if (iPageCount < iCurrentPage)
+ {
+ fAdd(iPageCount);
+ iPrev = iPageCount;
+ iNext = iPageCount;
+ }
+ else
+ {
+ if (3 >= iCurrentPage || iPageCount - 2 <= iCurrentPage)
+ {
+ iLimit += 2;
+ }
- tagName = tagName.toUpperCase();
- return !(tagName === 'INPUT' || tagName === 'SELECT' || tagName === 'TEXTAREA' ||
- (element && tagName === 'DIV' && 'editorHtmlArea' === element.className && element.contentEditable)
- );
+ fAdd(iCurrentPage);
+ iPrev = iCurrentPage;
+ iNext = iCurrentPage;
+ }
+
+ while (0 < iLimit) {
+
+ iPrev -= 1;
+ iNext += 1;
+
+ if (0 < iPrev)
+ {
+ fAdd(iPrev, false);
+ iLimit--;
+ }
+
+ if (iPageCount >= iNext)
+ {
+ fAdd(iNext, true);
+ iLimit--;
+ }
+ else if (0 >= iPrev)
+ {
+ break;
+ }
+ }
+
+ if (3 === iPrev)
+ {
+ fAdd(2, false);
+ }
+ else if (3 < iPrev)
+ {
+ fAdd(window.Math.round((iPrev - 1) / 2), false, '...');
+ }
+
+ if (iPageCount - 2 === iNext)
+ {
+ fAdd(iPageCount - 1, true);
+ }
+ else if (iPageCount - 2 > iNext)
+ {
+ fAdd(window.Math.round((iPageCount + iNext) / 2), true, '...');
+ }
+
+ // first and last
+ if (1 < iPrev)
+ {
+ fAdd(1, false);
+ }
+
+ if (iPageCount > iNext)
+ {
+ fAdd(iPageCount, true);
+ }
}
- return false;
+ return aResult;
};
- }
-};
-
-Utils.detectDropdownVisibility = _.debounce(function () {
- Globals.dropdownVisibility(!!_.find(BootstrapDropdowns, function (oItem) {
- return oItem.hasClass('open');
- }));
-}, 50);
-
-Utils.triggerAutocompleteInputChange = function (bDelay) {
-
- var fFunc = function () {
- $('.checkAutocomplete').trigger('change');
};
- if (bDelay)
+ Utils.selectElement = function (element)
{
- _.delay(fFunc, 100);
- }
- else
- {
- fFunc();
- }
-};
+ /* jshint onevar: false */
+ if (window.getSelection)
+ {
+ var sel = window.getSelection();
+ sel.removeAllRanges();
+ var range = window.document.createRange();
+ range.selectNodeContents(element);
+ sel.addRange(range);
+ }
+ else if (window.document.selection)
+ {
+ var textRange = window.document.body.createTextRange();
+ textRange.moveToElementText(element);
+ textRange.select();
+ }
+ /* jshint onevar: true */
+ };
+ Utils.detectDropdownVisibility = _.debounce(function () {
+ Globals.dropdownVisibility(!!_.find(Globals.aBootstrapDropdowns, function (oItem) {
+ return oItem.hasClass('open');
+ }));
+ }, 50);
+ Utils.triggerAutocompleteInputChange = function (bDelay) {
+
+ var fFunc = function () {
+ $('.checkAutocomplete').trigger('change');
+ };
+
+ if (bDelay)
+ {
+ _.delay(fFunc, 100);
+ }
+ else
+ {
+ fFunc();
+ }
+ };
+
+ module.exports = Utils;
+
+}(module));
+},{"../External/$doc.js":16,"../External/$html.js":17,"../External/$window.js":18,"../External/NotificationClass.js":22,"../External/jquery.js":26,"../External/ko.js":28,"../External/underscore.js":31,"../External/window.js":32,"./Consts.js":6,"./Enums.js":7,"./Globals.js":9}],15:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-/*jslint bitwise: true*/
-// Base64 encode / decode
-// http://www.webtoolkit.info/
-
-Base64 = {
-
- // private property
- _keyStr : 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
-
- // public method for urlsafe encoding
- urlsafe_encode : function (input) {
- return Base64.encode(input).replace(/[+]/g, '-').replace(/[\/]/g, '_').replace(/[=]/g, '.');
- },
-
- // public method for encoding
- encode : function (input) {
- var
- output = '',
- chr1, chr2, chr3, enc1, enc2, enc3, enc4,
- i = 0
- ;
-
- input = Base64._utf8_encode(input);
-
- while (i < input.length)
- {
- chr1 = input.charCodeAt(i++);
- chr2 = input.charCodeAt(i++);
- chr3 = input.charCodeAt(i++);
-
- enc1 = chr1 >> 2;
- enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
- enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
- enc4 = chr3 & 63;
-
- if (isNaN(chr2))
- {
- enc3 = enc4 = 64;
- }
- else if (isNaN(chr3))
- {
- enc4 = 64;
- }
-
- output = output +
- this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
- this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
- }
-
- return output;
- },
-
- // public method for decoding
- decode : function (input) {
- var
- output = '',
- chr1, chr2, chr3, enc1, enc2, enc3, enc4,
- i = 0
- ;
-
- input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
-
- while (i < input.length)
- {
- enc1 = this._keyStr.indexOf(input.charAt(i++));
- enc2 = this._keyStr.indexOf(input.charAt(i++));
- enc3 = this._keyStr.indexOf(input.charAt(i++));
- enc4 = this._keyStr.indexOf(input.charAt(i++));
-
- chr1 = (enc1 << 2) | (enc2 >> 4);
- chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
- chr3 = ((enc3 & 3) << 6) | enc4;
-
- output = output + String.fromCharCode(chr1);
-
- if (enc3 !== 64)
- {
- output = output + String.fromCharCode(chr2);
- }
-
- if (enc4 !== 64)
- {
- output = output + String.fromCharCode(chr3);
- }
- }
-
- return Base64._utf8_decode(output);
- },
-
- // private method for UTF-8 encoding
- _utf8_encode : function (string) {
-
- string = string.replace(/\r\n/g, "\n");
-
- var
- utftext = '',
- n = 0,
- l = string.length,
- c = 0
- ;
-
- for (; n < l; n++) {
-
- c = string.charCodeAt(n);
-
- if (c < 128)
- {
- utftext += String.fromCharCode(c);
- }
- else if ((c > 127) && (c < 2048))
- {
- utftext += String.fromCharCode((c >> 6) | 192);
- utftext += String.fromCharCode((c & 63) | 128);
- }
- else
- {
- utftext += String.fromCharCode((c >> 12) | 224);
- utftext += String.fromCharCode(((c >> 6) & 63) | 128);
- utftext += String.fromCharCode((c & 63) | 128);
- }
- }
-
- return utftext;
- },
-
- // private method for UTF-8 decoding
- _utf8_decode : function (utftext) {
- var
- string = '',
- i = 0,
- c = 0,
- c2 = 0,
- c3 = 0
- ;
-
- while ( i < utftext.length )
- {
- c = utftext.charCodeAt(i);
-
- if (c < 128)
- {
- string += String.fromCharCode(c);
- i++;
- }
- else if((c > 191) && (c < 224))
- {
- c2 = utftext.charCodeAt(i+1);
- string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
- i += 2;
- }
- else
- {
- c2 = utftext.charCodeAt(i+1);
- c3 = utftext.charCodeAt(i+2);
- string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
- i += 3;
- }
- }
-
- return string;
- }
-};
+'use strict';
+
+module.exports = require('./jquery.js')('');
-/*jslint bitwise: false*/
+},{"./jquery.js":26}],16:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+'use strict';
+
+module.exports = require('./jquery.js')(window.document);
+
+},{"./jquery.js":26}],17:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+'use strict';
+
+module.exports = require('./jquery.js')('html');
+
+},{"./jquery.js":26}],18:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+'use strict';
+
+module.exports = require('./jquery.js')(window);
+
+},{"./jquery.js":26}],19:[function(require,module,exports){
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-ko.bindingHandlers.tooltip = {
- 'init': function (oElement, fValueAccessor) {
- if (!Globals.bMobileDevice)
- {
+'use strict';
+
+module.exports = require('./window.js')['rainloopAppData'] || {};
+},{"./window.js":32}],20:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+'use strict';
+
+module.exports = JSON;
+},{}],21:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+'use strict';
+
+module.exports = Jua;
+},{}],22:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+'use strict';
+
+var window = require('./window.js');
+module.exports = window.Notification && window.Notification.requestPermission ? window.Notification : null;
+},{"./window.js":32}],23:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+'use strict';
+
+module.exports = crossroads;
+},{}],24:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+'use strict';
+
+module.exports = hasher;
+},{}],25:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+'use strict';
+
+module.exports = ifvisible;
+},{}],26:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+'use strict';
+
+module.exports = $;
+},{}],27:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+'use strict';
+
+module.exports = key;
+},{}],28:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ window = require('./window.js'),
+ _ = require('./underscore.js'),
+ $ = require('./jquery.js'),
+ $window = require('./$window.js'),
+ $doc = require('./$doc.js')
+ ;
+
+ ko.bindingHandlers.tooltip = {
+ 'init': function (oElement, fValueAccessor) {
+
+ var
+ Globals = require('../Common/Globals.js'),
+ Utils = require('../Common/Utils.js')
+ ;
+
+ if (!Globals.bMobileDevice)
+ {
+ var
+ $oEl = $(oElement),
+ sClass = $oEl.data('tooltip-class') || '',
+ sPlacement = $oEl.data('tooltip-placement') || 'top'
+ ;
+
+ $oEl.tooltip({
+ 'delay': {
+ 'show': 500,
+ 'hide': 100
+ },
+ 'html': true,
+ 'container': 'body',
+ 'placement': sPlacement,
+ 'trigger': 'hover',
+ 'title': function () {
+ return $oEl.is('.disabled') || Globals.dropdownVisibility() ? '' : '' +
+ Utils.i18n(ko.utils.unwrapObservable(fValueAccessor())) + '';
+ }
+ }).click(function () {
+ $oEl.tooltip('hide');
+ });
+
+ Globals.tooltipTrigger.subscribe(function () {
+ $oEl.tooltip('hide');
+ });
+ }
+ }
+ };
+
+ ko.bindingHandlers.tooltip2 = {
+ 'init': function (oElement, fValueAccessor) {
var
$oEl = $(oElement),
sClass = $oEl.data('tooltip-class') || '',
- sPlacement = $oEl.data('tooltip-placement') || 'top'
+ sPlacement = $oEl.data('tooltip-placement') || 'top',
+ Globals = require('../Common/Globals.js')
;
$oEl.tooltip({
@@ -3069,10 +6693,9 @@ ko.bindingHandlers.tooltip = {
'html': true,
'container': 'body',
'placement': sPlacement,
- 'trigger': 'hover',
'title': function () {
- return $oEl.is('.disabled') || Globals.dropdownVisibility() ? '' : '' +
- Utils.i18n(ko.utils.unwrapObservable(fValueAccessor())) + '';
+ return $oEl.is('.disabled') || Globals.dropdownVisibility() ? '' :
+ '' + fValueAccessor()() + '';
}
}).click(function () {
$oEl.tooltip('hide');
@@ -3082,11086 +6705,11127 @@ ko.bindingHandlers.tooltip = {
$oEl.tooltip('hide');
});
}
- }
-};
+ };
-ko.bindingHandlers.tooltip2 = {
- 'init': function (oElement, fValueAccessor) {
- var
- $oEl = $(oElement),
- sClass = $oEl.data('tooltip-class') || '',
- sPlacement = $oEl.data('tooltip-placement') || 'top'
- ;
+ ko.bindingHandlers.tooltip3 = {
+ 'init': function (oElement) {
- $oEl.tooltip({
- 'delay': {
- 'show': 500,
- 'hide': 100
- },
- 'html': true,
- 'container': 'body',
- 'placement': sPlacement,
- 'title': function () {
- return $oEl.is('.disabled') || Globals.dropdownVisibility() ? '' :
- '' + fValueAccessor()() + '';
- }
- }).click(function () {
- $oEl.tooltip('hide');
- });
-
- Globals.tooltipTrigger.subscribe(function () {
- $oEl.tooltip('hide');
- });
- }
-};
-
-ko.bindingHandlers.tooltip3 = {
- 'init': function (oElement) {
-
- var $oEl = $(oElement);
-
- $oEl.tooltip({
- 'container': 'body',
- 'trigger': 'hover manual',
- 'title': function () {
- return $oEl.data('tooltip3-data') || '';
- }
- });
-
- $document.click(function () {
- $oEl.tooltip('hide');
- });
-
- Globals.tooltipTrigger.subscribe(function () {
- $oEl.tooltip('hide');
- });
- },
- 'update': function (oElement, fValueAccessor) {
- var sValue = ko.utils.unwrapObservable(fValueAccessor());
- if ('' === sValue)
- {
- $(oElement).data('tooltip3-data', '').tooltip('hide');
- }
- else
- {
- $(oElement).data('tooltip3-data', sValue).tooltip('show');
- }
- }
-};
-
-ko.bindingHandlers.registrateBootstrapDropdown = {
- 'init': function (oElement) {
- BootstrapDropdowns.push($(oElement));
- }
-};
-
-ko.bindingHandlers.openDropdownTrigger = {
- 'update': function (oElement, fValueAccessor) {
- if (ko.utils.unwrapObservable(fValueAccessor()))
- {
- var $el = $(oElement);
- if (!$el.hasClass('open'))
- {
- $el.find('.dropdown-toggle').dropdown('toggle');
- Utils.detectDropdownVisibility();
- }
-
- fValueAccessor()(false);
- }
- }
-};
-
-ko.bindingHandlers.dropdownCloser = {
- 'init': function (oElement) {
- $(oElement).closest('.dropdown').on('click', '.e-item', function () {
- $(oElement).dropdown('toggle');
- });
- }
-};
-
-ko.bindingHandlers.popover = {
- 'init': function (oElement, fValueAccessor) {
- $(oElement).popover(ko.utils.unwrapObservable(fValueAccessor()));
- }
-};
-
-ko.bindingHandlers.csstext = {
- 'init': function (oElement, fValueAccessor) {
- if (oElement && oElement.styleSheet && !Utils.isUnd(oElement.styleSheet.cssText))
- {
- oElement.styleSheet.cssText = ko.utils.unwrapObservable(fValueAccessor());
- }
- else
- {
- $(oElement).text(ko.utils.unwrapObservable(fValueAccessor()));
- }
- },
- 'update': function (oElement, fValueAccessor) {
- if (oElement && oElement.styleSheet && !Utils.isUnd(oElement.styleSheet.cssText))
- {
- oElement.styleSheet.cssText = ko.utils.unwrapObservable(fValueAccessor());
- }
- else
- {
- $(oElement).text(ko.utils.unwrapObservable(fValueAccessor()));
- }
- }
-};
-
-ko.bindingHandlers.resizecrop = {
- 'init': function (oElement) {
- $(oElement).addClass('resizecrop').resizecrop({
- 'width': '100',
- 'height': '100',
- 'wrapperCSS': {
- 'border-radius': '10px'
- }
- });
- },
- 'update': function (oElement, fValueAccessor) {
- fValueAccessor()();
- $(oElement).resizecrop({
- 'width': '100',
- 'height': '100'
- });
- }
-};
-
-ko.bindingHandlers.onEnter = {
- 'init': function (oElement, fValueAccessor, fAllBindingsAccessor, oViewModel) {
- $(oElement).on('keypress', function (oEvent) {
- if (oEvent && 13 === window.parseInt(oEvent.keyCode, 10))
- {
- $(oElement).trigger('change');
- fValueAccessor().call(oViewModel);
- }
- });
- }
-};
-
-ko.bindingHandlers.onEsc = {
- 'init': function (oElement, fValueAccessor, fAllBindingsAccessor, oViewModel) {
- $(oElement).on('keypress', function (oEvent) {
- if (oEvent && 27 === window.parseInt(oEvent.keyCode, 10))
- {
- $(oElement).trigger('change');
- fValueAccessor().call(oViewModel);
- }
- });
- }
-};
-
-ko.bindingHandlers.clickOnTrue = {
- 'update': function (oElement, fValueAccessor) {
- if (ko.utils.unwrapObservable(fValueAccessor()))
- {
- $(oElement).click();
- }
- }
-};
-
-ko.bindingHandlers.modal = {
- 'init': function (oElement, fValueAccessor) {
-
- $(oElement).toggleClass('fade', !Globals.bMobileDevice).modal({
- 'keyboard': false,
- 'show': ko.utils.unwrapObservable(fValueAccessor())
- })
- .on('shown', function () {
- Utils.windowResize();
- })
- .find('.close').click(function () {
- fValueAccessor()(false);
- });
- },
- 'update': function (oElement, fValueAccessor) {
- $(oElement).modal(ko.utils.unwrapObservable(fValueAccessor()) ? 'show' : 'hide');
- }
-};
-
-ko.bindingHandlers.i18nInit = {
- 'init': function (oElement) {
- Utils.i18nToNode(oElement);
- }
-};
-
-ko.bindingHandlers.i18nUpdate = {
- 'update': function (oElement, fValueAccessor) {
- ko.utils.unwrapObservable(fValueAccessor());
- Utils.i18nToNode(oElement);
- }
-};
-
-ko.bindingHandlers.link = {
- 'update': function (oElement, fValueAccessor) {
- $(oElement).attr('href', ko.utils.unwrapObservable(fValueAccessor()));
- }
-};
-
-ko.bindingHandlers.title = {
- 'update': function (oElement, fValueAccessor) {
- $(oElement).attr('title', ko.utils.unwrapObservable(fValueAccessor()));
- }
-};
-
-ko.bindingHandlers.textF = {
- 'init': function (oElement, fValueAccessor) {
- $(oElement).text(ko.utils.unwrapObservable(fValueAccessor()));
- }
-};
-
-ko.bindingHandlers.initDom = {
- 'init': function (oElement, fValueAccessor) {
- fValueAccessor()(oElement);
- }
-};
-
-ko.bindingHandlers.initResizeTrigger = {
- 'init': function (oElement, fValueAccessor) {
- var aValues = ko.utils.unwrapObservable(fValueAccessor());
- $(oElement).css({
- 'height': aValues[1],
- 'min-height': aValues[1]
- });
- },
- 'update': function (oElement, fValueAccessor) {
- var
- aValues = ko.utils.unwrapObservable(fValueAccessor()),
- iValue = Utils.pInt(aValues[1]),
- iSize = 0,
- iOffset = $(oElement).offset().top
- ;
-
- if (0 < iOffset)
- {
- iOffset += Utils.pInt(aValues[2]);
- iSize = $window.height() - iOffset;
-
- if (iValue < iSize)
- {
- iValue = iSize;
- }
-
- $(oElement).css({
- 'height': iValue,
- 'min-height': iValue
- });
- }
- }
-};
-
-ko.bindingHandlers.appendDom = {
- 'update': function (oElement, fValueAccessor) {
- $(oElement).hide().empty().append(ko.utils.unwrapObservable(fValueAccessor())).show();
- }
-};
-
-ko.bindingHandlers.draggable = {
- 'init': function (oElement, fValueAccessor, fAllBindingsAccessor) {
-
- if (!Globals.bMobileDevice)
- {
var
- iTriggerZone = 100,
- iScrollSpeed = 3,
- fAllValueFunc = fAllBindingsAccessor(),
- sDroppableSelector = fAllValueFunc && fAllValueFunc['droppableSelector'] ? fAllValueFunc['droppableSelector'] : '',
- oConf = {
- 'distance': 20,
- 'handle': '.dragHandle',
- 'cursorAt': {'top': 22, 'left': 3},
- 'refreshPositions': true,
- 'scroll': true
- }
+ $oEl = $(oElement),
+ Globals = require('../Common/Globals.js')
;
- if (sDroppableSelector)
- {
- oConf['drag'] = function (oEvent) {
-
- $(sDroppableSelector).each(function () {
- var
- moveUp = null,
- moveDown = null,
- $this = $(this),
- oOffset = $this.offset(),
- bottomPos = oOffset.top + $this.height()
- ;
-
- window.clearInterval($this.data('timerScroll'));
- $this.data('timerScroll', false);
-
- if (oEvent.pageX >= oOffset.left && oEvent.pageX <= oOffset.left + $this.width())
- {
- if (oEvent.pageY >= bottomPos - iTriggerZone && oEvent.pageY <= bottomPos)
- {
- moveUp = function() {
- $this.scrollTop($this.scrollTop() + iScrollSpeed);
- Utils.windowResize();
- };
-
- $this.data('timerScroll', window.setInterval(moveUp, 10));
- moveUp();
- }
-
- if (oEvent.pageY >= oOffset.top && oEvent.pageY <= oOffset.top + iTriggerZone)
- {
- moveDown = function() {
- $this.scrollTop($this.scrollTop() - iScrollSpeed);
- Utils.windowResize();
- };
-
- $this.data('timerScroll', window.setInterval(moveDown, 10));
- moveDown();
- }
- }
- });
- };
-
- oConf['stop'] = function() {
- $(sDroppableSelector).each(function () {
- window.clearInterval($(this).data('timerScroll'));
- $(this).data('timerScroll', false);
- });
- };
- }
-
- oConf['helper'] = function (oEvent) {
- return fValueAccessor()(oEvent && oEvent.target ? ko.dataFor(oEvent.target) : null);
- };
-
- $(oElement).draggable(oConf).on('mousedown', function () {
- Utils.removeInFocus();
+ $oEl.tooltip({
+ 'container': 'body',
+ 'trigger': 'hover manual',
+ 'title': function () {
+ return $oEl.data('tooltip3-data') || '';
+ }
});
- }
- }
-};
-ko.bindingHandlers.droppable = {
- 'init': function (oElement, fValueAccessor, fAllBindingsAccessor) {
+ $doc.click(function () {
+ $oEl.tooltip('hide');
+ });
- if (!Globals.bMobileDevice)
- {
- var
- fValueFunc = fValueAccessor(),
- fAllValueFunc = fAllBindingsAccessor(),
- fOverCallback = fAllValueFunc && fAllValueFunc['droppableOver'] ? fAllValueFunc['droppableOver'] : null,
- fOutCallback = fAllValueFunc && fAllValueFunc['droppableOut'] ? fAllValueFunc['droppableOut'] : null,
- oConf = {
- 'tolerance': 'pointer',
- 'hoverClass': 'droppableHover'
- }
- ;
-
- if (fValueFunc)
- {
- oConf['drop'] = function (oEvent, oUi) {
- fValueFunc(oEvent, oUi);
- };
-
- if (fOverCallback)
- {
- oConf['over'] = function (oEvent, oUi) {
- fOverCallback(oEvent, oUi);
- };
- }
-
- if (fOutCallback)
- {
- oConf['out'] = function (oEvent, oUi) {
- fOutCallback(oEvent, oUi);
- };
- }
-
- $(oElement).droppable(oConf);
- }
- }
- }
-};
-
-ko.bindingHandlers.nano = {
- 'init': function (oElement) {
- if (!Globals.bDisableNanoScroll)
- {
- $(oElement)
- .addClass('nano')
- .nanoScroller({
- 'iOSNativeScrolling': false,
- 'preventPageScrolling': true
- })
- ;
- }
- }
-};
-
-ko.bindingHandlers.saveTrigger = {
- 'init': function (oElement) {
-
- var $oEl = $(oElement);
-
- $oEl.data('save-trigger-type', $oEl.is('input[type=text],input[type=email],input[type=password],select,textarea') ? 'input' : 'custom');
-
- if ('custom' === $oEl.data('save-trigger-type'))
- {
- $oEl.append(
- ' '
- ).addClass('settings-saved-trigger');
- }
- else
- {
- $oEl.addClass('settings-saved-trigger-input');
- }
- },
- 'update': function (oElement, fValueAccessor) {
- var
- mValue = ko.utils.unwrapObservable(fValueAccessor()),
- $oEl = $(oElement)
- ;
-
- if ('custom' === $oEl.data('save-trigger-type'))
- {
- switch (mValue.toString())
- {
- case '1':
- $oEl
- .find('.animated,.error').hide().removeClass('visible')
- .end()
- .find('.success').show().addClass('visible')
- ;
- break;
- case '0':
- $oEl
- .find('.animated,.success').hide().removeClass('visible')
- .end()
- .find('.error').show().addClass('visible')
- ;
- break;
- case '-2':
- $oEl
- .find('.error,.success').hide().removeClass('visible')
- .end()
- .find('.animated').show().addClass('visible')
- ;
- break;
- default:
- $oEl
- .find('.animated').hide()
- .end()
- .find('.error,.success').removeClass('visible')
- ;
- break;
- }
- }
- else
- {
- switch (mValue.toString())
- {
- case '1':
- $oEl.addClass('success').removeClass('error');
- break;
- case '0':
- $oEl.addClass('error').removeClass('success');
- break;
- case '-2':
-// $oEl;
- break;
- default:
- $oEl.removeClass('error success');
- break;
- }
- }
- }
-};
-
-ko.bindingHandlers.emailsTags = {
- 'init': function(oElement, fValueAccessor) {
- var
- $oEl = $(oElement),
- fValue = fValueAccessor(),
- fFocusCallback = function (bValue) {
- if (fValue && fValue.focusTrigger)
- {
- fValue.focusTrigger(bValue);
- }
- }
- ;
-
- $oEl.inputosaurus({
- 'parseOnBlur': true,
- 'allowDragAndDrop': true,
- 'focusCallback': fFocusCallback,
- 'inputDelimiters': [',', ';'],
- 'autoCompleteSource': function (oData, fResponse) {
- RL.getAutocomplete(oData.term, function (aData) {
- fResponse(_.map(aData, function (oEmailItem) {
- return oEmailItem.toLine(false);
- }));
- });
- },
- 'parseHook': function (aInput) {
- return _.map(aInput, function (sInputValue) {
-
- var
- sValue = Utils.trim(sInputValue),
- oEmail = null
- ;
-
- if ('' !== sValue)
- {
- oEmail = new EmailModel();
- oEmail.mailsoParse(sValue);
- oEmail.clearDuplicateName();
- return [oEmail.toLine(false), oEmail];
- }
-
- return [sValue, null];
-
- });
- },
- 'change': _.bind(function (oEvent) {
- $oEl.data('EmailsTagsValue', oEvent.target.value);
- fValue(oEvent.target.value);
- }, this)
- });
- },
- 'update': function (oElement, fValueAccessor, fAllBindingsAccessor) {
-
- var
- $oEl = $(oElement),
- fAllValueFunc = fAllBindingsAccessor(),
- fEmailsTagsFilter = fAllValueFunc['emailsTagsFilter'] || null,
- sValue = ko.utils.unwrapObservable(fValueAccessor())
- ;
-
- if ($oEl.data('EmailsTagsValue') !== sValue)
- {
- $oEl.val(sValue);
- $oEl.data('EmailsTagsValue', sValue);
- $oEl.inputosaurus('refresh');
- }
-
- if (fEmailsTagsFilter && ko.utils.unwrapObservable(fEmailsTagsFilter))
- {
- $oEl.inputosaurus('focus');
- }
- }
-};
-
-ko.bindingHandlers.contactTags = {
- 'init': function(oElement, fValueAccessor) {
- var
- $oEl = $(oElement),
- fValue = fValueAccessor(),
- fFocusCallback = function (bValue) {
- if (fValue && fValue.focusTrigger)
- {
- fValue.focusTrigger(bValue);
- }
- }
- ;
-
- $oEl.inputosaurus({
- 'parseOnBlur': true,
- 'allowDragAndDrop': false,
- 'focusCallback': fFocusCallback,
- 'inputDelimiters': [',', ';'],
- 'outputDelimiter': ',',
- 'autoCompleteSource': function (oData, fResponse) {
- RL.getContactTagsAutocomplete(oData.term, function (aData) {
- fResponse(_.map(aData, function (oTagItem) {
- return oTagItem.toLine(false);
- }));
- });
- },
- 'parseHook': function (aInput) {
- return _.map(aInput, function (sInputValue) {
-
- var
- sValue = Utils.trim(sInputValue),
- oTag = null
- ;
-
- if ('' !== sValue)
- {
- oTag = new ContactTagModel();
- oTag.name(sValue);
- return [oTag.toLine(false), oTag];
- }
-
- return [sValue, null];
-
- });
- },
- 'change': _.bind(function (oEvent) {
- $oEl.data('ContactTagsValue', oEvent.target.value);
- fValue(oEvent.target.value);
- }, this)
- });
- },
- 'update': function (oElement, fValueAccessor, fAllBindingsAccessor) {
-
- var
- $oEl = $(oElement),
- fAllValueFunc = fAllBindingsAccessor(),
- fContactTagsFilter = fAllValueFunc['contactTagsFilter'] || null,
- sValue = ko.utils.unwrapObservable(fValueAccessor())
- ;
-
- if ($oEl.data('ContactTagsValue') !== sValue)
- {
- $oEl.val(sValue);
- $oEl.data('ContactTagsValue', sValue);
- $oEl.inputosaurus('refresh');
- }
-
- if (fContactTagsFilter && ko.utils.unwrapObservable(fContactTagsFilter))
- {
- $oEl.inputosaurus('focus');
- }
- }
-};
-
-ko.bindingHandlers.command = {
- 'init': function (oElement, fValueAccessor, fAllBindingsAccessor, oViewModel) {
- var
- jqElement = $(oElement),
- oCommand = fValueAccessor()
- ;
-
- if (!oCommand || !oCommand.enabled || !oCommand.canExecute)
- {
- throw new Error('You are not using command function');
- }
-
- jqElement.addClass('command');
- ko.bindingHandlers[jqElement.is('form') ? 'submit' : 'click'].init.apply(oViewModel, arguments);
- },
-
- 'update': function (oElement, fValueAccessor) {
-
- var
- bResult = true,
- jqElement = $(oElement),
- oCommand = fValueAccessor()
- ;
-
- bResult = oCommand.enabled();
- jqElement.toggleClass('command-not-enabled', !bResult);
-
- if (bResult)
- {
- bResult = oCommand.canExecute();
- jqElement.toggleClass('command-can-not-be-execute', !bResult);
- }
-
- jqElement.toggleClass('command-disabled disable disabled', !bResult).toggleClass('no-disabled', !!bResult);
-
- if (jqElement.is('input') || jqElement.is('button'))
- {
- jqElement.prop('disabled', !bResult);
- }
- }
-};
-
-ko.extenders.trimmer = function (oTarget)
-{
- var oResult = ko.computed({
- 'read': oTarget,
- 'write': function (sNewValue) {
- oTarget(Utils.trim(sNewValue.toString()));
+ Globals.tooltipTrigger.subscribe(function () {
+ $oEl.tooltip('hide');
+ });
},
- 'owner': this
- });
-
- oResult(oTarget());
- return oResult;
-};
-
-ko.extenders.posInterer = function (oTarget, iDefault)
-{
- var oResult = ko.computed({
- 'read': oTarget,
- 'write': function (sNewValue) {
- var iNew = Utils.pInt(sNewValue.toString(), iDefault);
- if (0 >= iNew)
+ 'update': function (oElement, fValueAccessor) {
+ var sValue = ko.utils.unwrapObservable(fValueAccessor());
+ if ('' === sValue)
{
- iNew = iDefault;
- }
-
- if (iNew === oTarget() && '' + iNew !== '' + sNewValue)
- {
- oTarget(iNew + 1);
- }
-
- oTarget(iNew);
- }
- });
-
- oResult(oTarget());
- return oResult;
-};
-
-ko.extenders.reversible = function (oTarget)
-{
- var mValue = oTarget();
-
- oTarget.commit = function ()
- {
- mValue = oTarget();
- };
-
- oTarget.reverse = function ()
- {
- oTarget(mValue);
- };
-
- oTarget.commitedValue = function ()
- {
- return mValue;
- };
-
- return oTarget;
-};
-
-ko.extenders.toggleSubscribe = function (oTarget, oOptions)
-{
- oTarget.subscribe(oOptions[1], oOptions[0], 'beforeChange');
- oTarget.subscribe(oOptions[2], oOptions[0]);
-
- return oTarget;
-};
-
-ko.extenders.falseTimeout = function (oTarget, iOption)
-{
- oTarget.iTimeout = 0;
- oTarget.subscribe(function (bValue) {
- if (bValue)
- {
- window.clearTimeout(oTarget.iTimeout);
- oTarget.iTimeout = window.setTimeout(function () {
- oTarget(false);
- oTarget.iTimeout = 0;
- }, Utils.pInt(iOption));
- }
- });
-
- return oTarget;
-};
-
-ko.observable.fn.validateNone = function ()
-{
- this.hasError = ko.observable(false);
- return this;
-};
-
-ko.observable.fn.validateEmail = function ()
-{
- this.hasError = ko.observable(false);
-
- this.subscribe(function (sValue) {
- sValue = Utils.trim(sValue);
- this.hasError('' !== sValue && !(/^[^@\s]+@[^@\s]+$/.test(sValue)));
- }, this);
-
- this.valueHasMutated();
- return this;
-};
-
-ko.observable.fn.validateSimpleEmail = function ()
-{
- this.hasError = ko.observable(false);
-
- this.subscribe(function (sValue) {
- sValue = Utils.trim(sValue);
- this.hasError('' !== sValue && !(/^.+@.+$/.test(sValue)));
- }, this);
-
- this.valueHasMutated();
- return this;
-};
-
-ko.observable.fn.validateFunc = function (fFunc)
-{
- this.hasFuncError = ko.observable(false);
-
- if (Utils.isFunc(fFunc))
- {
- this.subscribe(function (sValue) {
- this.hasFuncError(!fFunc(sValue));
- }, this);
-
- this.valueHasMutated();
- }
-
- return this;
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function LinkBuilder()
-{
- this.sBase = '#/';
- this.sServer = './?';
- this.sVersion = RL.settingsGet('Version');
- this.sSpecSuffix = RL.settingsGet('AuthAccountHash') || '0';
- this.sStaticPrefix = RL.settingsGet('StaticPrefix') || 'rainloop/v/' + this.sVersion + '/static/';
-}
-
-/**
- * @return {string}
- */
-LinkBuilder.prototype.root = function ()
-{
- return this.sBase;
-};
-
-/**
- * @param {string} sDownload
- * @return {string}
- */
-LinkBuilder.prototype.attachmentDownload = function (sDownload)
-{
- return this.sServer + '/Raw/' + this.sSpecSuffix + '/Download/' + sDownload;
-};
-
-/**
- * @param {string} sDownload
- * @return {string}
- */
-LinkBuilder.prototype.attachmentPreview = function (sDownload)
-{
- return this.sServer + '/Raw/' + this.sSpecSuffix + '/View/' + sDownload;
-};
-
-/**
- * @param {string} sDownload
- * @return {string}
- */
-LinkBuilder.prototype.attachmentPreviewAsPlain = function (sDownload)
-{
- return this.sServer + '/Raw/' + this.sSpecSuffix + '/ViewAsPlain/' + sDownload;
-};
-
-/**
- * @return {string}
- */
-LinkBuilder.prototype.upload = function ()
-{
- return this.sServer + '/Upload/' + this.sSpecSuffix + '/';
-};
-
-/**
- * @return {string}
- */
-LinkBuilder.prototype.uploadContacts = function ()
-{
- return this.sServer + '/UploadContacts/' + this.sSpecSuffix + '/';
-};
-
-/**
- * @return {string}
- */
-LinkBuilder.prototype.uploadBackground = function ()
-{
- return this.sServer + '/UploadBackground/' + this.sSpecSuffix + '/';
-};
-
-/**
- * @return {string}
- */
-LinkBuilder.prototype.append = function ()
-{
- return this.sServer + '/Append/' + this.sSpecSuffix + '/';
-};
-
-/**
- * @param {string} sEmail
- * @return {string}
- */
-LinkBuilder.prototype.change = function (sEmail)
-{
- return this.sServer + '/Change/' + this.sSpecSuffix + '/' + window.encodeURIComponent(sEmail) + '/';
-};
-
-/**
- * @param {string=} sAdd
- * @return {string}
- */
-LinkBuilder.prototype.ajax = function (sAdd)
-{
- return this.sServer + '/Ajax/' + this.sSpecSuffix + '/' + sAdd;
-};
-
-/**
- * @param {string} sRequestHash
- * @return {string}
- */
-LinkBuilder.prototype.messageViewLink = function (sRequestHash)
-{
- return this.sServer + '/Raw/' + this.sSpecSuffix + '/ViewAsPlain/' + sRequestHash;
-};
-
-/**
- * @param {string} sRequestHash
- * @return {string}
- */
-LinkBuilder.prototype.messageDownloadLink = function (sRequestHash)
-{
- return this.sServer + '/Raw/' + this.sSpecSuffix + '/Download/' + sRequestHash;
-};
-
-/**
- * @param {string} sEmail
- * @return {string}
- */
-LinkBuilder.prototype.avatarLink = function (sEmail)
-{
- return this.sServer + '/Raw/0/Avatar/' + window.encodeURIComponent(sEmail) + '/';
-// return '//secure.gravatar.com/avatar/' + Utils.md5(sEmail.toLowerCase()) + '.jpg?s=80&d=mm';
-};
-
-/**
- * @return {string}
- */
-LinkBuilder.prototype.inbox = function ()
-{
- return this.sBase + 'mailbox/Inbox';
-};
-
-/**
- * @return {string}
- */
-LinkBuilder.prototype.messagePreview = function ()
-{
- return this.sBase + 'mailbox/message-preview';
-};
-
-/**
- * @param {string=} sScreenName
- * @return {string}
- */
-LinkBuilder.prototype.settings = function (sScreenName)
-{
- var sResult = this.sBase + 'settings';
- if (!Utils.isUnd(sScreenName) && '' !== sScreenName)
- {
- sResult += '/' + sScreenName;
- }
-
- return sResult;
-};
-
-/**
- * @param {string} sScreenName
- * @return {string}
- */
-LinkBuilder.prototype.admin = function (sScreenName)
-{
- var sResult = this.sBase;
- switch (sScreenName) {
- case 'AdminDomains':
- sResult += 'domains';
- break;
- case 'AdminSecurity':
- sResult += 'security';
- break;
- case 'AdminLicensing':
- sResult += 'licensing';
- break;
- }
-
- return sResult;
-};
-
-/**
- * @param {string} sFolder
- * @param {number=} iPage = 1
- * @param {string=} sSearch = ''
- * @return {string}
- */
-LinkBuilder.prototype.mailBox = function (sFolder, iPage, sSearch)
-{
- iPage = Utils.isNormal(iPage) ? Utils.pInt(iPage) : 1;
- sSearch = Utils.pString(sSearch);
-
- var sResult = this.sBase + 'mailbox/';
- if ('' !== sFolder)
- {
- sResult += encodeURI(sFolder);
- }
- if (1 < iPage)
- {
- sResult = sResult.replace(/[\/]+$/, '');
- sResult += '/p' + iPage;
- }
- if ('' !== sSearch)
- {
- sResult = sResult.replace(/[\/]+$/, '');
- sResult += '/' + encodeURI(sSearch);
- }
-
- return sResult;
-};
-
-/**
- * @return {string}
- */
-LinkBuilder.prototype.phpInfo = function ()
-{
- return this.sServer + 'Info';
-};
-
-/**
- * @param {string} sLang
- * @return {string}
- */
-LinkBuilder.prototype.langLink = function (sLang)
-{
- return this.sServer + '/Lang/0/' + encodeURI(sLang) + '/' + this.sVersion + '/';
-};
-
-/**
- * @return {string}
- */
-LinkBuilder.prototype.exportContactsVcf = function ()
-{
- return this.sServer + '/Raw/' + this.sSpecSuffix + '/ContactsVcf/';
-};
-
-/**
- * @return {string}
- */
-LinkBuilder.prototype.exportContactsCsv = function ()
-{
- return this.sServer + '/Raw/' + this.sSpecSuffix + '/ContactsCsv/';
-};
-
-/**
- * @return {string}
- */
-LinkBuilder.prototype.emptyContactPic = function ()
-{
- return this.sStaticPrefix + 'css/images/empty-contact.png';
-};
-
-/**
- * @param {string} sFileName
- * @return {string}
- */
-LinkBuilder.prototype.sound = function (sFileName)
-{
- return this.sStaticPrefix + 'sounds/' + sFileName;
-};
-
-/**
- * @param {string} sTheme
- * @return {string}
- */
-LinkBuilder.prototype.themePreviewLink = function (sTheme)
-{
- var sPrefix = 'rainloop/v/' + this.sVersion + '/';
- if ('@custom' === sTheme.substr(-7))
- {
- sTheme = Utils.trim(sTheme.substring(0, sTheme.length - 7));
- sPrefix = '';
- }
-
- return sPrefix + 'themes/' + encodeURI(sTheme) + '/images/preview.png';
-};
-
-/**
- * @return {string}
- */
-LinkBuilder.prototype.notificationMailIcon = function ()
-{
- return this.sStaticPrefix + 'css/images/icom-message-notification.png';
-};
-
-/**
- * @return {string}
- */
-LinkBuilder.prototype.openPgpJs = function ()
-{
- return this.sStaticPrefix + 'js/openpgp.min.js';
-};
-
-/**
- * @return {string}
- */
-LinkBuilder.prototype.socialGoogle = function ()
-{
- return this.sServer + 'SocialGoogle' + ('' !== this.sSpecSuffix ? '/' + this.sSpecSuffix + '/' : '');
-};
-
-/**
- * @return {string}
- */
-LinkBuilder.prototype.socialTwitter = function ()
-{
- return this.sServer + 'SocialTwitter' + ('' !== this.sSpecSuffix ? '/' + this.sSpecSuffix + '/' : '');
-};
-
-/**
- * @return {string}
- */
-LinkBuilder.prototype.socialFacebook = function ()
-{
- return this.sServer + 'SocialFacebook' + ('' !== this.sSpecSuffix ? '/' + this.sSpecSuffix + '/' : '');
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @type {Object}
- */
-Plugins.oViewModelsHooks = {};
-
-/**
- * @type {Object}
- */
-Plugins.oSimpleHooks = {};
-
-/**
- * @param {string} sName
- * @param {Function} ViewModel
- */
-Plugins.regViewModelHook = function (sName, ViewModel)
-{
- if (ViewModel)
- {
- ViewModel.__hookName = sName;
- }
-};
-
-/**
- * @param {string} sName
- * @param {Function} fCallback
- */
-Plugins.addHook = function (sName, fCallback)
-{
- if (Utils.isFunc(fCallback))
- {
- if (!Utils.isArray(Plugins.oSimpleHooks[sName]))
- {
- Plugins.oSimpleHooks[sName] = [];
- }
-
- Plugins.oSimpleHooks[sName].push(fCallback);
- }
-};
-
-/**
- * @param {string} sName
- * @param {Array=} aArguments
- */
-Plugins.runHook = function (sName, aArguments)
-{
- if (Utils.isArray(Plugins.oSimpleHooks[sName]))
- {
- aArguments = aArguments || [];
-
- _.each(Plugins.oSimpleHooks[sName], function (fCallback) {
- fCallback.apply(null, aArguments);
- });
- }
-};
-
-/**
- * @param {string} sName
- * @return {?}
- */
-Plugins.mainSettingsGet = function (sName)
-{
- return RL ? RL.settingsGet(sName) : null;
-};
-
-/**
- * @param {Function} fCallback
- * @param {string} sAction
- * @param {Object=} oParameters
- * @param {?number=} iTimeout
- * @param {string=} sGetAdd = ''
- * @param {Array=} aAbortActions = []
- */
-Plugins.remoteRequest = function (fCallback, sAction, oParameters, iTimeout, sGetAdd, aAbortActions)
-{
- if (RL)
- {
- RL.remote().defaultRequest(fCallback, sAction, oParameters, iTimeout, sGetAdd, aAbortActions);
- }
-};
-
-/**
- * @param {string} sPluginSection
- * @param {string} sName
- * @return {?}
- */
-Plugins.settingsGet = function (sPluginSection, sName)
-{
- var oPlugin = Plugins.mainSettingsGet('Plugins');
- oPlugin = oPlugin && Utils.isUnd(oPlugin[sPluginSection]) ? null : oPlugin[sPluginSection];
- return oPlugin ? (Utils.isUnd(oPlugin[sName]) ? null : oPlugin[sName]) : null;
-};
-
-
-
-
-/**
- * @constructor
- * @param {Object} oElement
- * @param {Function=} fOnBlur
- * @param {Function=} fOnReady
- * @param {Function=} fOnModeChange
- */
-function NewHtmlEditorWrapper(oElement, fOnBlur, fOnReady, fOnModeChange)
-{
- var self = this;
- self.editor = null;
- self.iBlurTimer = 0;
- self.fOnBlur = fOnBlur || null;
- self.fOnReady = fOnReady || null;
- self.fOnModeChange = fOnModeChange || null;
-
- self.$element = $(oElement);
-
- self.resize = _.throttle(_.bind(self.resize, self), 100);
-
- self.init();
-}
-
-NewHtmlEditorWrapper.prototype.blurTrigger = function ()
-{
- if (this.fOnBlur)
- {
- var self = this;
- window.clearTimeout(self.iBlurTimer);
- self.iBlurTimer = window.setTimeout(function () {
- self.fOnBlur();
- }, 200);
- }
-};
-
-NewHtmlEditorWrapper.prototype.focusTrigger = function ()
-{
- if (this.fOnBlur)
- {
- window.clearTimeout(this.iBlurTimer);
- }
-};
-
-/**
- * @return {boolean}
- */
-NewHtmlEditorWrapper.prototype.isHtml = function ()
-{
- return this.editor ? 'wysiwyg' === this.editor.mode : false;
-};
-
-/**
- * @return {boolean}
- */
-NewHtmlEditorWrapper.prototype.checkDirty = function ()
-{
- return this.editor ? this.editor.checkDirty() : false;
-};
-
-NewHtmlEditorWrapper.prototype.resetDirty = function ()
-{
- if (this.editor)
- {
- this.editor.resetDirty();
- }
-};
-
-/**
- * @return {string}
- */
-NewHtmlEditorWrapper.prototype.getData = function (bWrapIsHtml)
-{
- if (this.editor)
- {
- if ('plain' === this.editor.mode && this.editor.plugins.plain && this.editor.__plain)
- {
- return this.editor.__plain.getRawData();
- }
-
- return bWrapIsHtml ?
- '' +
- this.editor.getData() + '' : this.editor.getData();
- }
-
- return '';
-};
-
-NewHtmlEditorWrapper.prototype.modeToggle = function (bPlain)
-{
- if (this.editor)
- {
- if (bPlain)
- {
- if ('plain' === this.editor.mode)
- {
- this.editor.setMode('wysiwyg');
- }
- }
- else
- {
- if ('wysiwyg' === this.editor.mode)
- {
- this.editor.setMode('plain');
- }
- }
-
- this.resize();
- }
-};
-
-NewHtmlEditorWrapper.prototype.setHtml = function (sHtml, bFocus)
-{
- if (this.editor)
- {
- this.modeToggle(true);
- this.editor.setData(sHtml);
-
- if (bFocus)
- {
- this.focus();
- }
- }
-};
-
-NewHtmlEditorWrapper.prototype.setPlain = function (sPlain, bFocus)
-{
- if (this.editor)
- {
- this.modeToggle(false);
- if ('plain' === this.editor.mode && this.editor.plugins.plain && this.editor.__plain)
- {
- return this.editor.__plain.setRawData(sPlain);
- }
- else
- {
- this.editor.setData(sPlain);
- }
-
- if (bFocus)
- {
- this.focus();
- }
- }
-};
-
-NewHtmlEditorWrapper.prototype.init = function ()
-{
- if (this.$element && this.$element[0])
- {
- var
- self = this,
- fInit = function () {
-
- var
- oConfig = Globals.oHtmlEditorDefaultConfig,
- sLanguage = RL.settingsGet('Language'),
- bSource = !!RL.settingsGet('AllowHtmlEditorSourceButton')
- ;
-
- if (bSource && oConfig.toolbarGroups && !oConfig.toolbarGroups.__SourceInited)
- {
- oConfig.toolbarGroups.__SourceInited = true;
- oConfig.toolbarGroups.push({name: 'document', groups: ['mode', 'document', 'doctools']});
- }
-
- oConfig.enterMode = window.CKEDITOR.ENTER_BR;
- oConfig.shiftEnterMode = window.CKEDITOR.ENTER_BR;
-
- oConfig.language = Globals.oHtmlEditorLangsMap[sLanguage] || 'en';
- if (window.CKEDITOR.env)
- {
- window.CKEDITOR.env.isCompatible = true;
- }
-
- self.editor = window.CKEDITOR.appendTo(self.$element[0], oConfig);
-
- self.editor.on('key', function(oEvent) {
- if (oEvent && oEvent.data && 9 /* Tab */ === oEvent.data.keyCode)
- {
- return false;
- }
- });
-
- self.editor.on('blur', function() {
- self.blurTrigger();
- });
-
- self.editor.on('mode', function() {
-
- self.blurTrigger();
-
- if (self.fOnModeChange)
- {
- self.fOnModeChange('plain' !== self.editor.mode);
- }
- });
-
- self.editor.on('focus', function() {
- self.focusTrigger();
- });
-
- if (self.fOnReady)
- {
- self.editor.on('instanceReady', function () {
-
- self.editor.setKeystroke(window.CKEDITOR.CTRL + 65 /* A */, 'selectAll');
-
- self.fOnReady();
- self.__resizable = true;
- self.resize();
- });
- }
- }
- ;
-
- if (window.CKEDITOR)
- {
- fInit();
- }
- else
- {
- window.__initEditor = fInit;
- }
- }
-};
-
-NewHtmlEditorWrapper.prototype.focus = function ()
-{
- if (this.editor)
- {
- this.editor.focus();
- }
-};
-
-NewHtmlEditorWrapper.prototype.blur = function ()
-{
- if (this.editor)
- {
- this.editor.focusManager.blur(true);
- }
-};
-
-NewHtmlEditorWrapper.prototype.resize = function ()
-{
- if (this.editor && this.__resizable)
- {
- try
- {
- this.editor.resize(this.$element.width(), this.$element.innerHeight());
- }
- catch (e) {}
- }
-};
-
-NewHtmlEditorWrapper.prototype.clear = function (bFocus)
-{
- this.setHtml('', bFocus);
-};
-
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @param {koProperty} oKoList
- * @param {koProperty} oKoSelectedItem
- * @param {string} sItemSelector
- * @param {string} sItemSelectedSelector
- * @param {string} sItemCheckedSelector
- * @param {string} sItemFocusedSelector
- */
-function Selector(oKoList, oKoSelectedItem,
- sItemSelector, sItemSelectedSelector, sItemCheckedSelector, sItemFocusedSelector)
-{
- this.list = oKoList;
-
- this.listChecked = ko.computed(function () {
- return _.filter(this.list(), function (oItem) {
- return oItem.checked();
- });
- }, this).extend({'rateLimit': 0});
-
- this.isListChecked = ko.computed(function () {
- return 0 < this.listChecked().length;
- }, this);
-
- this.focusedItem = ko.observable(null);
- this.selectedItem = oKoSelectedItem;
- this.selectedItemUseCallback = true;
-
- this.itemSelectedThrottle = _.debounce(_.bind(this.itemSelected, this), 300);
-
- this.listChecked.subscribe(function (aItems) {
- if (0 < aItems.length)
- {
- if (null === this.selectedItem())
- {
- this.selectedItem.valueHasMutated();
+ $(oElement).data('tooltip3-data', '').tooltip('hide');
}
else
{
- this.selectedItem(null);
+ $(oElement).data('tooltip3-data', sValue).tooltip('show');
}
}
- else if (this.bAutoSelect && this.focusedItem())
- {
- this.selectedItem(this.focusedItem());
+ };
+
+ ko.bindingHandlers.registrateBootstrapDropdown = {
+ 'init': function (oElement) {
+
+ var
+ Globals = require('../Common/Globals.js')
+ ;
+
+ Globals.aBootstrapDropdowns.push($(oElement));
}
- }, this);
+ };
- this.selectedItem.subscribe(function (oItem) {
-
- if (oItem)
- {
- if (this.isListChecked())
+ ko.bindingHandlers.openDropdownTrigger = {
+ 'update': function (oElement, fValueAccessor) {
+ if (ko.utils.unwrapObservable(fValueAccessor()))
{
- _.each(this.listChecked(), function (oSubItem) {
- oSubItem.checked(false);
+ var
+ $el = $(oElement),
+ Utils = require('../Common/Utils.js')
+ ;
+
+ if (!$el.hasClass('open'))
+ {
+ $el.find('.dropdown-toggle').dropdown('toggle');
+ Utils.detectDropdownVisibility();
+ }
+
+ fValueAccessor()(false);
+ }
+ }
+ };
+
+ ko.bindingHandlers.dropdownCloser = {
+ 'init': function (oElement) {
+ $(oElement).closest('.dropdown').on('click', '.e-item', function () {
+ $(oElement).dropdown('toggle');
+ });
+ }
+ };
+
+ ko.bindingHandlers.popover = {
+ 'init': function (oElement, fValueAccessor) {
+ $(oElement).popover(ko.utils.unwrapObservable(fValueAccessor()));
+ }
+ };
+
+ ko.bindingHandlers.csstext = {
+ 'init': function (oElement, fValueAccessor) {
+
+ var
+ Utils = require('../Common/Utils.js')
+ ;
+
+ if (oElement && oElement.styleSheet && !Utils.isUnd(oElement.styleSheet.cssText))
+ {
+ oElement.styleSheet.cssText = ko.utils.unwrapObservable(fValueAccessor());
+ }
+ else
+ {
+ $(oElement).text(ko.utils.unwrapObservable(fValueAccessor()));
+ }
+ },
+ 'update': function (oElement, fValueAccessor) {
+
+ var
+ Utils = require('../Common/Utils.js')
+ ;
+
+ if (oElement && oElement.styleSheet && !Utils.isUnd(oElement.styleSheet.cssText))
+ {
+ oElement.styleSheet.cssText = ko.utils.unwrapObservable(fValueAccessor());
+ }
+ else
+ {
+ $(oElement).text(ko.utils.unwrapObservable(fValueAccessor()));
+ }
+ }
+ };
+
+ ko.bindingHandlers.resizecrop = {
+ 'init': function (oElement) {
+ $(oElement).addClass('resizecrop').resizecrop({
+ 'width': '100',
+ 'height': '100',
+ 'wrapperCSS': {
+ 'border-radius': '10px'
+ }
+ });
+ },
+ 'update': function (oElement, fValueAccessor) {
+ fValueAccessor()();
+ $(oElement).resizecrop({
+ 'width': '100',
+ 'height': '100'
+ });
+ }
+ };
+
+ ko.bindingHandlers.onEnter = {
+ 'init': function (oElement, fValueAccessor, fAllBindingsAccessor, oViewModel) {
+ $(oElement).on('keypress', function (oEvent) {
+ if (oEvent && 13 === window.parseInt(oEvent.keyCode, 10))
+ {
+ $(oElement).trigger('change');
+ fValueAccessor().call(oViewModel);
+ }
+ });
+ }
+ };
+
+ ko.bindingHandlers.onEsc = {
+ 'init': function (oElement, fValueAccessor, fAllBindingsAccessor, oViewModel) {
+ $(oElement).on('keypress', function (oEvent) {
+ if (oEvent && 27 === window.parseInt(oEvent.keyCode, 10))
+ {
+ $(oElement).trigger('change');
+ fValueAccessor().call(oViewModel);
+ }
+ });
+ }
+ };
+
+ ko.bindingHandlers.clickOnTrue = {
+ 'update': function (oElement, fValueAccessor) {
+ if (ko.utils.unwrapObservable(fValueAccessor()))
+ {
+ $(oElement).click();
+ }
+ }
+ };
+
+ ko.bindingHandlers.modal = {
+ 'init': function (oElement, fValueAccessor) {
+
+ var
+ Globals = require('../Common/Globals.js'),
+ Utils = require('../Common/Utils.js')
+ ;
+
+ $(oElement).toggleClass('fade', !Globals.bMobileDevice).modal({
+ 'keyboard': false,
+ 'show': ko.utils.unwrapObservable(fValueAccessor())
+ })
+ .on('shown', function () {
+ Utils.windowResize();
+ })
+ .find('.close').click(function () {
+ fValueAccessor()(false);
+ });
+ },
+ 'update': function (oElement, fValueAccessor) {
+ $(oElement).modal(ko.utils.unwrapObservable(fValueAccessor()) ? 'show' : 'hide');
+ }
+ };
+
+ ko.bindingHandlers.i18nInit = {
+ 'init': function (oElement) {
+ var
+ Utils = require('../Common/Utils.js')
+ ;
+ Utils.i18nToNode(oElement);
+ }
+ };
+
+ ko.bindingHandlers.i18nUpdate = {
+ 'update': function (oElement, fValueAccessor) {
+ var
+ Utils = require('../Common/Utils.js')
+ ;
+ ko.utils.unwrapObservable(fValueAccessor());
+ Utils.i18nToNode(oElement);
+ }
+ };
+
+ ko.bindingHandlers.link = {
+ 'update': function (oElement, fValueAccessor) {
+ $(oElement).attr('href', ko.utils.unwrapObservable(fValueAccessor()));
+ }
+ };
+
+ ko.bindingHandlers.title = {
+ 'update': function (oElement, fValueAccessor) {
+ $(oElement).attr('title', ko.utils.unwrapObservable(fValueAccessor()));
+ }
+ };
+
+ ko.bindingHandlers.textF = {
+ 'init': function (oElement, fValueAccessor) {
+ $(oElement).text(ko.utils.unwrapObservable(fValueAccessor()));
+ }
+ };
+
+ ko.bindingHandlers.initDom = {
+ 'init': function (oElement, fValueAccessor) {
+ fValueAccessor()(oElement);
+ }
+ };
+
+ ko.bindingHandlers.initResizeTrigger = {
+ 'init': function (oElement, fValueAccessor) {
+ var aValues = ko.utils.unwrapObservable(fValueAccessor());
+ $(oElement).css({
+ 'height': aValues[1],
+ 'min-height': aValues[1]
+ });
+ },
+ 'update': function (oElement, fValueAccessor) {
+ var
+ Utils = require('../Common/Utils.js'),
+ aValues = ko.utils.unwrapObservable(fValueAccessor()),
+ iValue = Utils.pInt(aValues[1]),
+ iSize = 0,
+ iOffset = $(oElement).offset().top
+ ;
+
+ if (0 < iOffset)
+ {
+ iOffset += Utils.pInt(aValues[2]);
+ iSize = $window.height() - iOffset;
+
+ if (iValue < iSize)
+ {
+ iValue = iSize;
+ }
+
+ $(oElement).css({
+ 'height': iValue,
+ 'min-height': iValue
});
}
-
- if (this.selectedItemUseCallback)
- {
- this.itemSelectedThrottle(oItem);
- }
}
- else if (this.selectedItemUseCallback)
- {
- this.itemSelected(null);
+ };
+
+ ko.bindingHandlers.appendDom = {
+ 'update': function (oElement, fValueAccessor) {
+ $(oElement).hide().empty().append(ko.utils.unwrapObservable(fValueAccessor())).show();
}
+ };
- }, this);
+ ko.bindingHandlers.draggable = {
+ 'init': function (oElement, fValueAccessor, fAllBindingsAccessor) {
- this.selectedItem.extend({'toggleSubscribe': [null,
- function (oPrev) {
- if (oPrev)
+ var
+ Globals = require('../Common/Globals.js'),
+ Utils = require('../Common/Utils.js')
+ ;
+
+ if (!Globals.bMobileDevice)
{
- oPrev.selected(false);
- }
- }, function (oNext) {
- if (oNext)
- {
- oNext.selected(true);
- }
- }
- ]});
+ var
+ iTriggerZone = 100,
+ iScrollSpeed = 3,
+ fAllValueFunc = fAllBindingsAccessor(),
+ sDroppableSelector = fAllValueFunc && fAllValueFunc['droppableSelector'] ? fAllValueFunc['droppableSelector'] : '',
+ oConf = {
+ 'distance': 20,
+ 'handle': '.dragHandle',
+ 'cursorAt': {'top': 22, 'left': 3},
+ 'refreshPositions': true,
+ 'scroll': true
+ }
+ ;
- this.focusedItem.extend({'toggleSubscribe': [null,
- function (oPrev) {
- if (oPrev)
- {
- oPrev.focused(false);
- }
- }, function (oNext) {
- if (oNext)
- {
- oNext.focused(true);
- }
- }
- ]});
-
- this.oContentVisible = null;
- this.oContentScrollable = null;
-
- this.sItemSelector = sItemSelector;
- this.sItemSelectedSelector = sItemSelectedSelector;
- this.sItemCheckedSelector = sItemCheckedSelector;
- this.sItemFocusedSelector = sItemFocusedSelector;
-
- this.sLastUid = '';
- this.bAutoSelect = true;
- this.oCallbacks = {};
-
- this.emptyFunction = function () {};
-
- this.focusedItem.subscribe(function (oItem) {
- if (oItem)
- {
- this.sLastUid = this.getItemUid(oItem);
- }
- }, this);
-
- var
- aCache = [],
- aCheckedCache = [],
- mFocused = null,
- mSelected = null
- ;
-
- this.list.subscribe(function (aItems) {
-
- var self = this;
- if (Utils.isArray(aItems))
- {
- _.each(aItems, function (oItem) {
- if (oItem)
+ if (sDroppableSelector)
{
- var sUid = self.getItemUid(oItem);
+ oConf['drag'] = function (oEvent) {
- aCache.push(sUid);
- if (oItem.checked())
- {
- aCheckedCache.push(sUid);
+ $(sDroppableSelector).each(function () {
+ var
+ moveUp = null,
+ moveDown = null,
+ $this = $(this),
+ oOffset = $this.offset(),
+ bottomPos = oOffset.top + $this.height()
+ ;
+
+ window.clearInterval($this.data('timerScroll'));
+ $this.data('timerScroll', false);
+
+ if (oEvent.pageX >= oOffset.left && oEvent.pageX <= oOffset.left + $this.width())
+ {
+ if (oEvent.pageY >= bottomPos - iTriggerZone && oEvent.pageY <= bottomPos)
+ {
+ moveUp = function() {
+ $this.scrollTop($this.scrollTop() + iScrollSpeed);
+ Utils.windowResize();
+ };
+
+ $this.data('timerScroll', window.setInterval(moveUp, 10));
+ moveUp();
+ }
+
+ if (oEvent.pageY >= oOffset.top && oEvent.pageY <= oOffset.top + iTriggerZone)
+ {
+ moveDown = function() {
+ $this.scrollTop($this.scrollTop() - iScrollSpeed);
+ Utils.windowResize();
+ };
+
+ $this.data('timerScroll', window.setInterval(moveDown, 10));
+ moveDown();
+ }
+ }
+ });
+ };
+
+ oConf['stop'] = function() {
+ $(sDroppableSelector).each(function () {
+ window.clearInterval($(this).data('timerScroll'));
+ $(this).data('timerScroll', false);
+ });
+ };
+ }
+
+ oConf['helper'] = function (oEvent) {
+ return fValueAccessor()(oEvent && oEvent.target ? ko.dataFor(oEvent.target) : null);
+ };
+
+ $(oElement).draggable(oConf).on('mousedown', function () {
+ Utils.removeInFocus();
+ });
+ }
+ }
+ };
+
+ ko.bindingHandlers.droppable = {
+ 'init': function (oElement, fValueAccessor, fAllBindingsAccessor) {
+
+ var
+ Globals = require('../Common/Globals.js')
+ ;
+
+ if (!Globals.bMobileDevice)
+ {
+ var
+ fValueFunc = fValueAccessor(),
+ fAllValueFunc = fAllBindingsAccessor(),
+ fOverCallback = fAllValueFunc && fAllValueFunc['droppableOver'] ? fAllValueFunc['droppableOver'] : null,
+ fOutCallback = fAllValueFunc && fAllValueFunc['droppableOut'] ? fAllValueFunc['droppableOut'] : null,
+ oConf = {
+ 'tolerance': 'pointer',
+ 'hoverClass': 'droppableHover'
}
- if (null === mFocused && oItem.focused())
+ ;
+
+ if (fValueFunc)
+ {
+ oConf['drop'] = function (oEvent, oUi) {
+ fValueFunc(oEvent, oUi);
+ };
+
+ if (fOverCallback)
{
- mFocused = sUid;
+ oConf['over'] = function (oEvent, oUi) {
+ fOverCallback(oEvent, oUi);
+ };
}
- if (null === mSelected && oItem.selected())
+
+ if (fOutCallback)
{
- mSelected = sUid;
+ oConf['out'] = function (oEvent, oUi) {
+ fOutCallback(oEvent, oUi);
+ };
+ }
+
+ $(oElement).droppable(oConf);
+ }
+ }
+ }
+ };
+
+ ko.bindingHandlers.nano = {
+ 'init': function (oElement) {
+
+ var
+ Globals = require('../Common/Globals.js')
+ ;
+
+ if (!Globals.bDisableNanoScroll)
+ {
+ $(oElement)
+ .addClass('nano')
+ .nanoScroller({
+ 'iOSNativeScrolling': false,
+ 'preventPageScrolling': true
+ })
+ ;
+ }
+ }
+ };
+
+ ko.bindingHandlers.saveTrigger = {
+ 'init': function (oElement) {
+
+ var $oEl = $(oElement);
+
+ $oEl.data('save-trigger-type', $oEl.is('input[type=text],input[type=email],input[type=password],select,textarea') ? 'input' : 'custom');
+
+ if ('custom' === $oEl.data('save-trigger-type'))
+ {
+ $oEl.append(
+ ' '
+ ).addClass('settings-saved-trigger');
+ }
+ else
+ {
+ $oEl.addClass('settings-saved-trigger-input');
+ }
+ },
+ 'update': function (oElement, fValueAccessor) {
+ var
+ mValue = ko.utils.unwrapObservable(fValueAccessor()),
+ $oEl = $(oElement)
+ ;
+
+ if ('custom' === $oEl.data('save-trigger-type'))
+ {
+ switch (mValue.toString())
+ {
+ case '1':
+ $oEl
+ .find('.animated,.error').hide().removeClass('visible')
+ .end()
+ .find('.success').show().addClass('visible')
+ ;
+ break;
+ case '0':
+ $oEl
+ .find('.animated,.success').hide().removeClass('visible')
+ .end()
+ .find('.error').show().addClass('visible')
+ ;
+ break;
+ case '-2':
+ $oEl
+ .find('.error,.success').hide().removeClass('visible')
+ .end()
+ .find('.animated').show().addClass('visible')
+ ;
+ break;
+ default:
+ $oEl
+ .find('.animated').hide()
+ .end()
+ .find('.error,.success').removeClass('visible')
+ ;
+ break;
+ }
+ }
+ else
+ {
+ switch (mValue.toString())
+ {
+ case '1':
+ $oEl.addClass('success').removeClass('error');
+ break;
+ case '0':
+ $oEl.addClass('error').removeClass('success');
+ break;
+ case '-2':
+ // $oEl;
+ break;
+ default:
+ $oEl.removeClass('error success');
+ break;
+ }
+ }
+ }
+ };
+
+ ko.bindingHandlers.emailsTags = {
+ 'init': function(oElement, fValueAccessor, fAllBindingsAccessor) {
+
+ var
+ Utils = require('../Common/Utils.js'),
+ $oEl = $(oElement),
+ fValue = fValueAccessor(),
+ fAllBindings = fAllBindingsAccessor(),
+ fAutoCompleteSource = fAllBindings['autoCompleteSource'] || null,
+ fFocusCallback = function (bValue) {
+ if (fValue && fValue.focusTrigger)
+ {
+ fValue.focusTrigger(bValue);
}
}
+ ;
+
+ $oEl.inputosaurus({
+ 'parseOnBlur': true,
+ 'allowDragAndDrop': true,
+ 'focusCallback': fFocusCallback,
+ 'inputDelimiters': [',', ';'],
+ 'autoCompleteSource': fAutoCompleteSource,
+ 'parseHook': function (aInput) {
+ return _.map(aInput, function (sInputValue) {
+
+ var
+ sValue = Utils.trim(sInputValue),
+ oEmail = null
+ ;
+
+ if ('' !== sValue)
+ {
+ oEmail = new EmailModel();
+ oEmail.mailsoParse(sValue);
+ oEmail.clearDuplicateName();
+ return [oEmail.toLine(false), oEmail];
+ }
+
+ return [sValue, null];
+
+ });
+ },
+ 'change': _.bind(function (oEvent) {
+ $oEl.data('EmailsTagsValue', oEvent.target.value);
+ fValue(oEvent.target.value);
+ }, this)
});
+ },
+ 'update': function (oElement, fValueAccessor, fAllBindingsAccessor) {
+
+ var
+ $oEl = $(oElement),
+ fAllValueFunc = fAllBindingsAccessor(),
+ fEmailsTagsFilter = fAllValueFunc['emailsTagsFilter'] || null,
+ sValue = ko.utils.unwrapObservable(fValueAccessor())
+ ;
+
+ if ($oEl.data('EmailsTagsValue') !== sValue)
+ {
+ $oEl.val(sValue);
+ $oEl.data('EmailsTagsValue', sValue);
+ $oEl.inputosaurus('refresh');
+ }
+
+ if (fEmailsTagsFilter && ko.utils.unwrapObservable(fEmailsTagsFilter))
+ {
+ $oEl.inputosaurus('focus');
+ }
}
- }, this, 'beforeChange');
+ };
- this.list.subscribe(function (aItems) {
+ ko.bindingHandlers.contactTags = {
+ 'init': function(oElement, fValueAccessor) {
+
+ var
+ Utils = require('../Common/Utils.js'),
+ $oEl = $(oElement),
+ fValue = fValueAccessor(),
+ fAllBindings = fAllBindingsAccessor(),
+ fAutoCompleteSource = fAllBindings['autoCompleteSource'] || null,
+ fFocusCallback = function (bValue) {
+ if (fValue && fValue.focusTrigger)
+ {
+ fValue.focusTrigger(bValue);
+ }
+ }
+ ;
- var
- self = this,
- oTemp = null,
- bGetNext = false,
- aUids = [],
- mNextFocused = mFocused,
- bChecked = false,
- bSelected = false,
- iLen = 0
+ $oEl.inputosaurus({
+ 'parseOnBlur': true,
+ 'allowDragAndDrop': false,
+ 'focusCallback': fFocusCallback,
+ 'inputDelimiters': [',', ';'],
+ 'outputDelimiter': ',',
+ 'autoCompleteSource': fAutoCompleteSource,
+ 'parseHook': function (aInput) {
+ return _.map(aInput, function (sInputValue) {
+
+ var
+ sValue = Utils.trim(sInputValue),
+ oTag = null
+ ;
+
+ if ('' !== sValue)
+ {
+ oTag = new ContactTagModel();
+ oTag.name(sValue);
+ return [oTag.toLine(false), oTag];
+ }
+
+ return [sValue, null];
+
+ });
+ },
+ 'change': _.bind(function (oEvent) {
+ $oEl.data('ContactTagsValue', oEvent.target.value);
+ fValue(oEvent.target.value);
+ }, this)
+ });
+ },
+ 'update': function (oElement, fValueAccessor, fAllBindingsAccessor) {
+
+ var
+ $oEl = $(oElement),
+ fAllValueFunc = fAllBindingsAccessor(),
+ fContactTagsFilter = fAllValueFunc['contactTagsFilter'] || null,
+ sValue = ko.utils.unwrapObservable(fValueAccessor())
+ ;
+
+ if ($oEl.data('ContactTagsValue') !== sValue)
+ {
+ $oEl.val(sValue);
+ $oEl.data('ContactTagsValue', sValue);
+ $oEl.inputosaurus('refresh');
+ }
+
+ if (fContactTagsFilter && ko.utils.unwrapObservable(fContactTagsFilter))
+ {
+ $oEl.inputosaurus('focus');
+ }
+ }
+ };
+
+ ko.bindingHandlers.command = {
+ 'init': function (oElement, fValueAccessor, fAllBindingsAccessor, oViewModel) {
+ var
+ jqElement = $(oElement),
+ oCommand = fValueAccessor()
+ ;
+
+ if (!oCommand || !oCommand.enabled || !oCommand.canExecute)
+ {
+ throw new Error('You are not using command function');
+ }
+
+ jqElement.addClass('command');
+ ko.bindingHandlers[jqElement.is('form') ? 'submit' : 'click'].init.apply(oViewModel, arguments);
+ },
+
+ 'update': function (oElement, fValueAccessor) {
+
+ var
+ bResult = true,
+ jqElement = $(oElement),
+ oCommand = fValueAccessor()
+ ;
+
+ bResult = oCommand.enabled();
+ jqElement.toggleClass('command-not-enabled', !bResult);
+
+ if (bResult)
+ {
+ bResult = oCommand.canExecute();
+ jqElement.toggleClass('command-can-not-be-execute', !bResult);
+ }
+
+ jqElement.toggleClass('command-disabled disable disabled', !bResult).toggleClass('no-disabled', !!bResult);
+
+ if (jqElement.is('input') || jqElement.is('button'))
+ {
+ jqElement.prop('disabled', !bResult);
+ }
+ }
+ };
+
+ ko.extenders.trimmer = function (oTarget)
+ {
+ var
+ Utils = require('../Common/Utils.js'),
+ oResult = ko.computed({
+ 'read': oTarget,
+ 'write': function (sNewValue) {
+ oTarget(Utils.trim(sNewValue.toString()));
+ },
+ 'owner': this
+ })
;
- this.selectedItemUseCallback = false;
+ oResult(oTarget());
+ return oResult;
+ };
- this.focusedItem(null);
- this.selectedItem(null);
-
- if (Utils.isArray(aItems))
- {
- iLen = aCheckedCache.length;
-
- _.each(aItems, function (oItem) {
-
- var sUid = self.getItemUid(oItem);
- aUids.push(sUid);
-
- if (null !== mFocused && mFocused === sUid)
- {
- self.focusedItem(oItem);
- mFocused = null;
- }
-
- if (0 < iLen && -1 < Utils.inArray(sUid, aCheckedCache))
- {
- bChecked = true;
- oItem.checked(true);
- iLen--;
- }
-
- if (!bChecked && null !== mSelected && mSelected === sUid)
- {
- bSelected = true;
- self.selectedItem(oItem);
- mSelected = null;
- }
- });
-
- this.selectedItemUseCallback = true;
-
- if (!bChecked && !bSelected && this.bAutoSelect)
- {
- if (self.focusedItem())
- {
- self.selectedItem(self.focusedItem());
- }
- else if (0 < aItems.length)
- {
- if (null !== mNextFocused)
+ ko.extenders.posInterer = function (oTarget, iDefault)
+ {
+ var
+ Utils = require('../Common/Utils.js'),
+ oResult = ko.computed({
+ 'read': oTarget,
+ 'write': function (sNewValue) {
+ var iNew = Utils.pInt(sNewValue.toString(), iDefault);
+ if (0 >= iNew)
{
- bGetNext = false;
- mNextFocused = _.find(aCache, function (sUid) {
- if (bGetNext && -1 < Utils.inArray(sUid, aUids))
- {
- return sUid;
- }
- else if (mNextFocused === sUid)
- {
- bGetNext = true;
- }
- return false;
- });
+ iNew = iDefault;
+ }
- if (mNextFocused)
+ if (iNew === oTarget() && '' + iNew !== '' + sNewValue)
+ {
+ oTarget(iNew + 1);
+ }
+
+ oTarget(iNew);
+ }
+ })
+ ;
+
+ oResult(oTarget());
+ return oResult;
+ };
+
+ ko.extenders.reversible = function (oTarget)
+ {
+ var mValue = oTarget();
+
+ oTarget.commit = function ()
+ {
+ mValue = oTarget();
+ };
+
+ oTarget.reverse = function ()
+ {
+ oTarget(mValue);
+ };
+
+ oTarget.commitedValue = function ()
+ {
+ return mValue;
+ };
+
+ return oTarget;
+ };
+
+ ko.extenders.toggleSubscribe = function (oTarget, oOptions)
+ {
+ oTarget.subscribe(oOptions[1], oOptions[0], 'beforeChange');
+ oTarget.subscribe(oOptions[2], oOptions[0]);
+
+ return oTarget;
+ };
+
+ ko.extenders.falseTimeout = function (oTarget, iOption)
+ {
+ var Utils = require('../Common/Utils.js');
+
+ oTarget.iTimeout = 0;
+ oTarget.subscribe(function (bValue) {
+ if (bValue)
+ {
+ window.clearTimeout(oTarget.iTimeout);
+ oTarget.iTimeout = window.setTimeout(function () {
+ oTarget(false);
+ oTarget.iTimeout = 0;
+ }, Utils.pInt(iOption));
+ }
+ });
+
+ return oTarget;
+ };
+
+ ko.observable.fn.validateNone = function ()
+ {
+ this.hasError = ko.observable(false);
+ return this;
+ };
+
+ ko.observable.fn.validateEmail = function ()
+ {
+ var Utils = require('../Common/Utils.js');
+ this.hasError = ko.observable(false);
+
+ this.subscribe(function (sValue) {
+ sValue = Utils.trim(sValue);
+ this.hasError('' !== sValue && !(/^[^@\s]+@[^@\s]+$/.test(sValue)));
+ }, this);
+
+ this.valueHasMutated();
+ return this;
+ };
+
+ ko.observable.fn.validateSimpleEmail = function ()
+ {
+ var Utils = require('../Common/Utils.js');
+
+ this.hasError = ko.observable(false);
+
+ this.subscribe(function (sValue) {
+ sValue = Utils.trim(sValue);
+ this.hasError('' !== sValue && !(/^.+@.+$/.test(sValue)));
+ }, this);
+
+ this.valueHasMutated();
+ return this;
+ };
+
+ ko.observable.fn.validateFunc = function (fFunc)
+ {
+ var Utils = require('../Common/Utils.js');
+ this.hasFuncError = ko.observable(false);
+
+ if (Utils.isFunc(fFunc))
+ {
+ this.subscribe(function (sValue) {
+ this.hasFuncError(!fFunc(sValue));
+ }, this);
+
+ this.valueHasMutated();
+ }
+
+ return this;
+ };
+
+ module.exports = ko;
+
+}(module));
+
+},{"../Common/Globals.js":9,"../Common/Utils.js":14,"./$doc.js":16,"./$window.js":18,"./jquery.js":26,"./underscore.js":31,"./window.js":32}],29:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+'use strict';
+
+module.exports = moment;
+},{}],30:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+'use strict';
+
+module.exports = ssm;
+},{}],31:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+'use strict';
+
+module.exports = _;
+},{}],32:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+'use strict';
+
+module.exports = window;
+
+},{}],33:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ $ = require('../External/jquery.js'),
+ _ = require('../External/underscore.js'),
+ ko = require('../External/ko.js'),
+ hasher = require('../External/hasher.js'),
+ crossroads = require('../External/crossroads.js'),
+ $html = require('../External/$html.js'),
+
+ Globals = require('../Common/Globals.js'),
+ Plugins = require('../Common/Plugins.js'),
+ Utils = require('../Common/Utils.js'),
+
+ KnoinAbstractViewModel = require('../Knoin/KnoinAbstractViewModel.js')
+ ;
+
+ /**
+ * @constructor
+ */
+ function Knoin()
+ {
+ this.sDefaultScreenName = '';
+ this.oScreens = {};
+ this.oCurrentScreen = null;
+ }
+
+ Knoin.prototype.sDefaultScreenName = '';
+ Knoin.prototype.oScreens = {};
+ Knoin.prototype.oCurrentScreen = null;
+
+ Knoin.prototype.hideLoading = function ()
+ {
+ $('#rl-loading').hide();
+ };
+
+ /**
+ * @param {Object} thisObject
+ */
+ Knoin.prototype.constructorEnd = function (thisObject)
+ {
+ if (Utils.isFunc(thisObject['__constructor_end']))
+ {
+ thisObject['__constructor_end'].call(thisObject);
+ }
+ };
+
+ /**
+ * @param {string} sName
+ * @param {Function} ViewModelClass
+ * @param {Function=} AbstractViewModel = KnoinAbstractViewModel
+ */
+ Knoin.prototype.extendAsViewModel = function (sName, ViewModelClass, AbstractViewModel)
+ {
+ if (ViewModelClass)
+ {
+ if (!AbstractViewModel)
+ {
+ AbstractViewModel = KnoinAbstractViewModel;
+ }
+
+ ViewModelClass.__name = sName;
+ Plugins.regViewModelHook(sName, ViewModelClass);
+ _.extend(ViewModelClass.prototype, AbstractViewModel.prototype);
+ }
+ };
+
+ /**
+ * @param {Function} SettingsViewModelClass
+ * @param {string} sLabelName
+ * @param {string} sTemplate
+ * @param {string} sRoute
+ * @param {boolean=} bDefault
+ */
+ Knoin.prototype.addSettingsViewModel = function (SettingsViewModelClass, sTemplate, sLabelName, sRoute, bDefault)
+ {
+ SettingsViewModelClass.__rlSettingsData = {
+ 'Label': sLabelName,
+ 'Template': sTemplate,
+ 'Route': sRoute,
+ 'IsDefault': !!bDefault
+ };
+
+ Globals.aViewModels['settings'].push(SettingsViewModelClass);
+ };
+
+ /**
+ * @param {Function} SettingsViewModelClass
+ */
+ Knoin.prototype.removeSettingsViewModel = function (SettingsViewModelClass)
+ {
+ Globals.aViewModels['settings-removed'].push(SettingsViewModelClass);
+ };
+
+ /**
+ * @param {Function} SettingsViewModelClass
+ */
+ Knoin.prototype.disableSettingsViewModel = function (SettingsViewModelClass)
+ {
+ Globals.aViewModels['settings-disabled'].push(SettingsViewModelClass);
+ };
+
+ Knoin.prototype.routeOff = function ()
+ {
+ hasher.changed.active = false;
+ };
+
+ Knoin.prototype.routeOn = function ()
+ {
+ hasher.changed.active = true;
+ };
+
+ /**
+ * @param {string} sScreenName
+ * @return {?Object}
+ */
+ Knoin.prototype.screen = function (sScreenName)
+ {
+ return ('' !== sScreenName && !Utils.isUnd(this.oScreens[sScreenName])) ? this.oScreens[sScreenName] : null;
+ };
+
+ /**
+ * @param {Function} ViewModelClass
+ * @param {Object=} oScreen
+ */
+ Knoin.prototype.buildViewModel = function (ViewModelClass, oScreen)
+ {
+ if (ViewModelClass && !ViewModelClass.__builded)
+ {
+ var
+ kn = this,
+ oViewModel = new ViewModelClass(oScreen),
+ sPosition = oViewModel.viewModelPosition(),
+ oViewModelPlace = $('#rl-content #rl-' + sPosition.toLowerCase()),
+ oViewModelDom = null
+ ;
+
+ ViewModelClass.__builded = true;
+ ViewModelClass.__vm = oViewModel;
+
+ oViewModel.viewModelName = ViewModelClass.__name;
+
+ if (oViewModelPlace && 1 === oViewModelPlace.length)
+ {
+ oViewModelDom = $('').addClass('rl-view-model').addClass('RL-' + oViewModel.viewModelTemplate()).hide();
+ oViewModelDom.appendTo(oViewModelPlace);
+
+ oViewModel.viewModelDom = oViewModelDom;
+ ViewModelClass.__dom = oViewModelDom;
+
+ if ('Popups' === sPosition)
+ {
+ oViewModel.cancelCommand = oViewModel.closeCommand = Utils.createCommand(oViewModel, function () {
+ kn.hideScreenPopup(ViewModelClass);
+ });
+
+ oViewModel.modalVisibility.subscribe(function (bValue) {
+
+ var self = this;
+ if (bValue)
{
- oTemp = _.find(aItems, function (oItem) {
- return mNextFocused === self.getItemUid(oItem);
+ this.viewModelDom.show();
+ this.storeAndSetKeyScope();
+
+ Globals.popupVisibilityNames.push(this.viewModelName);
+ oViewModel.viewModelDom.css('z-index', 3000 + Globals.popupVisibilityNames().length + 10);
+
+ Utils.delegateRun(this, 'onFocus', [], 500);
+ }
+ else
+ {
+ Utils.delegateRun(this, 'onHide');
+ this.restoreKeyScope();
+
+ Globals.popupVisibilityNames.remove(this.viewModelName);
+ oViewModel.viewModelDom.css('z-index', 2000);
+
+ Globals.tooltipTrigger(!Globals.tooltipTrigger());
+
+ _.delay(function () {
+ self.viewModelDom.hide();
+ }, 300);
+ }
+
+ }, oViewModel);
+ }
+
+ Plugins.runHook('view-model-pre-build', [ViewModelClass.__name, oViewModel, oViewModelDom]);
+
+ ko.applyBindingAccessorsToNode(oViewModelDom[0], {
+ 'i18nInit': true,
+ 'template': function () { return {'name': oViewModel.viewModelTemplate()};}
+ }, oViewModel);
+
+ Utils.delegateRun(oViewModel, 'onBuild', [oViewModelDom]);
+ if (oViewModel && 'Popups' === sPosition)
+ {
+ oViewModel.registerPopupKeyDown();
+ }
+
+ Plugins.runHook('view-model-post-build', [ViewModelClass.__name, oViewModel, oViewModelDom]);
+ }
+ else
+ {
+ Utils.log('Cannot find view model position: ' + sPosition);
+ }
+ }
+
+ return ViewModelClass ? ViewModelClass.__vm : null;
+ };
+
+ /**
+ * @param {Function} ViewModelClassToHide
+ */
+ Knoin.prototype.hideScreenPopup = function (ViewModelClassToHide)
+ {
+ if (ViewModelClassToHide && ViewModelClassToHide.__vm && ViewModelClassToHide.__dom)
+ {
+ ViewModelClassToHide.__vm.modalVisibility(false);
+ Plugins.runHook('view-model-on-hide', [ViewModelClassToHide.__name, ViewModelClassToHide.__vm]);
+ }
+ };
+
+ /**
+ * @param {Function} ViewModelClassToShow
+ * @param {Array=} aParameters
+ */
+ Knoin.prototype.showScreenPopup = function (ViewModelClassToShow, aParameters)
+ {
+ if (ViewModelClassToShow)
+ {
+ this.buildViewModel(ViewModelClassToShow);
+
+ if (ViewModelClassToShow.__vm && ViewModelClassToShow.__dom)
+ {
+ ViewModelClassToShow.__vm.modalVisibility(true);
+ Utils.delegateRun(ViewModelClassToShow.__vm, 'onShow', aParameters || []);
+ Plugins.runHook('view-model-on-show', [ViewModelClassToShow.__name, ViewModelClassToShow.__vm, aParameters || []]);
+ }
+ }
+ };
+
+ /**
+ * @param {Function} ViewModelClassToShow
+ * @return {boolean}
+ */
+ Knoin.prototype.isPopupVisible = function (ViewModelClassToShow)
+ {
+ return ViewModelClassToShow && ViewModelClassToShow.__vm ? ViewModelClassToShow.__vm.modalVisibility() : false;
+ };
+
+ /**
+ * @param {string} sScreenName
+ * @param {string} sSubPart
+ */
+ Knoin.prototype.screenOnRoute = function (sScreenName, sSubPart)
+ {
+ var
+ self = this,
+ oScreen = null,
+ oCross = null
+ ;
+
+ if ('' === Utils.pString(sScreenName))
+ {
+ sScreenName = this.sDefaultScreenName;
+ }
+
+ if ('' !== sScreenName)
+ {
+ oScreen = this.screen(sScreenName);
+ if (!oScreen)
+ {
+ oScreen = this.screen(this.sDefaultScreenName);
+ if (oScreen)
+ {
+ sSubPart = sScreenName + '/' + sSubPart;
+ sScreenName = this.sDefaultScreenName;
+ }
+ }
+
+ if (oScreen && oScreen.__started)
+ {
+ if (!oScreen.__builded)
+ {
+ oScreen.__builded = true;
+
+ if (Utils.isNonEmptyArray(oScreen.viewModels()))
+ {
+ _.each(oScreen.viewModels(), function (ViewModelClass) {
+ this.buildViewModel(ViewModelClass, oScreen);
+ }, this);
+ }
+
+ Utils.delegateRun(oScreen, 'onBuild');
+ }
+
+ _.defer(function () {
+
+ // hide screen
+ if (self.oCurrentScreen)
+ {
+ Utils.delegateRun(self.oCurrentScreen, 'onHide');
+
+ if (Utils.isNonEmptyArray(self.oCurrentScreen.viewModels()))
+ {
+ _.each(self.oCurrentScreen.viewModels(), function (ViewModelClass) {
+
+ if (ViewModelClass.__vm && ViewModelClass.__dom &&
+ 'Popups' !== ViewModelClass.__vm.viewModelPosition())
+ {
+ ViewModelClass.__dom.hide();
+ ViewModelClass.__vm.viewModelVisibility(false);
+ Utils.delegateRun(ViewModelClass.__vm, 'onHide');
+ }
+
});
}
}
+ // --
- self.selectedItem(oTemp || null);
- self.focusedItem(self.selectedItem());
- }
+ self.oCurrentScreen = oScreen;
+
+ // show screen
+ if (self.oCurrentScreen)
+ {
+ Utils.delegateRun(self.oCurrentScreen, 'onShow');
+
+ Plugins.runHook('screen-on-show', [self.oCurrentScreen.screenName(), self.oCurrentScreen]);
+
+ if (Utils.isNonEmptyArray(self.oCurrentScreen.viewModels()))
+ {
+ _.each(self.oCurrentScreen.viewModels(), function (ViewModelClass) {
+
+ if (ViewModelClass.__vm && ViewModelClass.__dom &&
+ 'Popups' !== ViewModelClass.__vm.viewModelPosition())
+ {
+ ViewModelClass.__dom.show();
+ ViewModelClass.__vm.viewModelVisibility(true);
+ Utils.delegateRun(ViewModelClass.__vm, 'onShow');
+ Utils.delegateRun(ViewModelClass.__vm, 'onFocus', [], 200);
+
+ Plugins.runHook('view-model-on-show', [ViewModelClass.__name, ViewModelClass.__vm]);
+ }
+
+ }, self);
+ }
+ }
+ // --
+
+ oCross = oScreen.__cross();
+ if (oCross)
+ {
+ oCross.parse(sSubPart);
+ }
+ });
}
}
+ };
- aCache = [];
- aCheckedCache = [];
- mFocused = null;
- mSelected = null;
-
- }, this);
-}
-
-Selector.prototype.itemSelected = function (oItem)
-{
- if (this.isListChecked())
+ /**
+ * @param {Array} aScreensClasses
+ */
+ Knoin.prototype.startScreens = function (aScreensClasses)
{
- if (!oItem)
- {
- (this.oCallbacks['onItemSelect'] || this.emptyFunction)(oItem || null);
- }
- }
- else
+ $('#rl-content').css({
+ 'visibility': 'hidden'
+ });
+
+ _.each(aScreensClasses, function (CScreen) {
+
+ var
+ oScreen = new CScreen(),
+ sScreenName = oScreen ? oScreen.screenName() : ''
+ ;
+
+ if (oScreen && '' !== sScreenName)
+ {
+ if ('' === this.sDefaultScreenName)
+ {
+ this.sDefaultScreenName = sScreenName;
+ }
+
+ this.oScreens[sScreenName] = oScreen;
+ }
+
+ }, this);
+
+
+ _.each(this.oScreens, function (oScreen) {
+ if (oScreen && !oScreen.__started && oScreen.__start)
+ {
+ oScreen.__started = true;
+ oScreen.__start();
+
+ Plugins.runHook('screen-pre-start', [oScreen.screenName(), oScreen]);
+ Utils.delegateRun(oScreen, 'onStart');
+ Plugins.runHook('screen-post-start', [oScreen.screenName(), oScreen]);
+ }
+ }, this);
+
+ var oCross = crossroads.create();
+ oCross.addRoute(/^([a-zA-Z0-9\-]*)\/?(.*)$/, _.bind(this.screenOnRoute, this));
+
+ hasher.initialized.add(oCross.parse, oCross);
+ hasher.changed.add(oCross.parse, oCross);
+ hasher.init();
+
+ $('#rl-content').css({
+ 'visibility': 'visible'
+ });
+
+ _.delay(function () {
+ $html.removeClass('rl-started-trigger').addClass('rl-started');
+ }, 50);
+ };
+
+ /**
+ * @param {string} sHash
+ * @param {boolean=} bSilence = false
+ * @param {boolean=} bReplace = false
+ */
+ Knoin.prototype.setHash = function (sHash, bSilence, bReplace)
{
- if (oItem)
+ sHash = '#' === sHash.substr(0, 1) ? sHash.substr(1) : sHash;
+ sHash = '/' === sHash.substr(0, 1) ? sHash.substr(1) : sHash;
+
+ bReplace = Utils.isUnd(bReplace) ? false : !!bReplace;
+
+ if (Utils.isUnd(bSilence) ? false : !!bSilence)
{
- (this.oCallbacks['onItemSelect'] || this.emptyFunction)(oItem);
+ hasher.changed.active = false;
+ hasher[bReplace ? 'replaceHash' : 'setHash'](sHash);
+ hasher.changed.active = true;
}
+ else
+ {
+ hasher.changed.active = true;
+ hasher[bReplace ? 'replaceHash' : 'setHash'](sHash);
+ hasher.setHash(sHash);
+ }
+ };
+
+ module.exports = new Knoin();
+
+}(module));
+},{"../Common/Globals.js":9,"../Common/Plugins.js":12,"../Common/Utils.js":14,"../External/$html.js":17,"../External/crossroads.js":23,"../External/hasher.js":24,"../External/jquery.js":26,"../External/ko.js":28,"../External/underscore.js":31,"../Knoin/KnoinAbstractViewModel.js":36}],34:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ /**
+ * @constructor
+ */
+ function KnoinAbstractBoot()
+ {
+
}
-};
-Selector.prototype.goDown = function (bForceSelect)
-{
- this.newSelectPosition(Enums.EventKeyCode.Down, false, bForceSelect);
-};
+ KnoinAbstractBoot.prototype.bootstart = function ()
+ {
-Selector.prototype.goUp = function (bForceSelect)
-{
- this.newSelectPosition(Enums.EventKeyCode.Up, false, bForceSelect);
-};
+ };
-Selector.prototype.init = function (oContentVisible, oContentScrollable, sKeyScope)
-{
- this.oContentVisible = oContentVisible;
- this.oContentScrollable = oContentScrollable;
+ module.exports = KnoinAbstractBoot;
- sKeyScope = sKeyScope || 'all';
+}(module));
+},{}],35:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
- if (this.oContentVisible && this.oContentScrollable)
+(function (module) {
+
+ 'use strict';
+
+ var
+ crossroads = require('../External/crossroads.js'),
+ Utils = require('../Common/Utils.js')
+ ;
+
+ /**
+ * @param {string} sScreenName
+ * @param {?=} aViewModels = []
+ * @constructor
+ */
+ function KnoinAbstractScreen(sScreenName, aViewModels)
+ {
+ this.sScreenName = sScreenName;
+ this.aViewModels = Utils.isArray(aViewModels) ? aViewModels : [];
+ }
+
+ /**
+ * @type {Array}
+ */
+ KnoinAbstractScreen.prototype.oCross = null;
+
+ /**
+ * @type {string}
+ */
+ KnoinAbstractScreen.prototype.sScreenName = '';
+
+ /**
+ * @type {Array}
+ */
+ KnoinAbstractScreen.prototype.aViewModels = [];
+
+ /**
+ * @return {Array}
+ */
+ KnoinAbstractScreen.prototype.viewModels = function ()
+ {
+ return this.aViewModels;
+ };
+
+ /**
+ * @return {string}
+ */
+ KnoinAbstractScreen.prototype.screenName = function ()
+ {
+ return this.sScreenName;
+ };
+
+ KnoinAbstractScreen.prototype.routes = function ()
+ {
+ return null;
+ };
+
+ /**
+ * @return {?Object}
+ */
+ KnoinAbstractScreen.prototype.__cross = function ()
+ {
+ return this.oCross;
+ };
+
+ KnoinAbstractScreen.prototype.__start = function ()
{
var
- self = this
+ aRoutes = this.routes(),
+ oRoute = null,
+ fMatcher = null
;
- $(this.oContentVisible)
- .on('selectstart', function (oEvent) {
- if (oEvent && oEvent.preventDefault)
- {
- oEvent.preventDefault();
- }
- })
- .on('click', this.sItemSelector, function (oEvent) {
- self.actionClick(ko.dataFor(this), oEvent);
- })
- .on('click', this.sItemCheckedSelector, function (oEvent) {
- var oItem = ko.dataFor(this);
- if (oItem)
- {
- if (oEvent && oEvent.shiftKey)
- {
- self.actionClick(oItem, oEvent);
- }
- else
- {
- self.focusedItem(oItem);
- oItem.checked(!oItem.checked());
- }
- }
- })
- ;
+ if (Utils.isNonEmptyArray(aRoutes))
+ {
+ fMatcher = _.bind(this.onRoute || Utils.emptyFunction, this);
+ oRoute = crossroads.create();
- key('enter', sKeyScope, function () {
- if (self.focusedItem() && !self.focusedItem().selected())
+ _.each(aRoutes, function (aItem) {
+ oRoute.addRoute(aItem[0], fMatcher).rules = aItem[1];
+ });
+
+ this.oCross = oRoute;
+ }
+ };
+
+ module.exports = KnoinAbstractScreen;
+
+}(module));
+},{"../Common/Utils.js":14,"../External/crossroads.js":23}],36:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ ko = require('../External/ko.js'),
+ $window = require('../External/$window.js'),
+
+ Utils = require('../Common/Utils.js'),
+ Enums = require('../Common/Enums.js'),
+ Globals = require('../Common/Globals.js')
+ ;
+
+ /**
+ * @param {string=} sPosition = ''
+ * @param {string=} sTemplate = ''
+ * @constructor
+ */
+ function KnoinAbstractViewModel(sPosition, sTemplate)
+ {
+ this.bDisabeCloseOnEsc = false;
+ this.sPosition = Utils.pString(sPosition);
+ this.sTemplate = Utils.pString(sTemplate);
+
+ this.sDefaultKeyScope = Enums.KeyState.None;
+ this.sCurrentKeyScope = this.sDefaultKeyScope;
+
+ this.viewModelName = '';
+ this.viewModelVisibility = ko.observable(false);
+ this.modalVisibility = ko.observable(false).extend({'rateLimit': 0});
+
+ this.viewModelDom = null;
+ }
+
+ /**
+ * @type {string}
+ */
+ KnoinAbstractViewModel.prototype.sPosition = '';
+
+ /**
+ * @type {string}
+ */
+ KnoinAbstractViewModel.prototype.sTemplate = '';
+
+ /**
+ * @type {string}
+ */
+ KnoinAbstractViewModel.prototype.viewModelName = '';
+
+ /**
+ * @type {?}
+ */
+ KnoinAbstractViewModel.prototype.viewModelDom = null;
+
+ /**
+ * @return {string}
+ */
+ KnoinAbstractViewModel.prototype.viewModelTemplate = function ()
+ {
+ return this.sTemplate;
+ };
+
+ /**
+ * @return {string}
+ */
+ KnoinAbstractViewModel.prototype.viewModelPosition = function ()
+ {
+ return this.sPosition;
+ };
+
+ KnoinAbstractViewModel.prototype.cancelCommand = function () {};
+ KnoinAbstractViewModel.prototype.closeCommand = function () {};
+
+ KnoinAbstractViewModel.prototype.storeAndSetKeyScope = function ()
+ {
+ this.sCurrentKeyScope = Globals.keyScope();
+ Globals.keyScope(this.sDefaultKeyScope);
+ };
+
+ KnoinAbstractViewModel.prototype.restoreKeyScope = function ()
+ {
+ Globals.keyScope(this.sCurrentKeyScope);
+ };
+
+ KnoinAbstractViewModel.prototype.registerPopupKeyDown = function ()
+ {
+ var self = this;
+ $window.on('keydown', function (oEvent) {
+ if (oEvent && self.modalVisibility && self.modalVisibility())
{
- self.actionClick(self.focusedItem());
- return false;
+ if (!this.bDisabeCloseOnEsc && Enums.EventKeyCode.Esc === oEvent.keyCode)
+ {
+ Utils.delegateRun(self, 'cancelCommand');
+ return false;
+ }
+ else if (Enums.EventKeyCode.Backspace === oEvent.keyCode && !Utils.inFocus())
+ {
+ return false;
+ }
}
return true;
});
+ };
- key('ctrl+up, command+up, ctrl+down, command+down', sKeyScope, function () {
- return false;
- });
+ module.exports = KnoinAbstractViewModel;
- key('up, shift+up, down, shift+down, home, end, pageup, pagedown, insert, space', sKeyScope, function (event, handler) {
- if (event && handler && handler.shortcut)
- {
- // TODO
- var iKey = 0;
- switch (handler.shortcut)
- {
- case 'up':
- case 'shift+up':
- iKey = Enums.EventKeyCode.Up;
- break;
- case 'down':
- case 'shift+down':
- iKey = Enums.EventKeyCode.Down;
- break;
- case 'insert':
- iKey = Enums.EventKeyCode.Insert;
- break;
- case 'space':
- iKey = Enums.EventKeyCode.Space;
- break;
- case 'home':
- iKey = Enums.EventKeyCode.Home;
- break;
- case 'end':
- iKey = Enums.EventKeyCode.End;
- break;
- case 'pageup':
- iKey = Enums.EventKeyCode.PageUp;
- break;
- case 'pagedown':
- iKey = Enums.EventKeyCode.PageDown;
- break;
- }
+}(module));
+},{"../Common/Enums.js":7,"../Common/Globals.js":9,"../Common/Utils.js":14,"../External/$window.js":18,"../External/ko.js":28}],37:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
- if (0 < iKey)
- {
- self.newSelectPosition(iKey, key.shift);
- return false;
- }
- }
- });
- }
-};
+(function (module) {
-Selector.prototype.autoSelect = function (bValue)
-{
- this.bAutoSelect = !!bValue;
-};
-
-/**
- * @param {Object} oItem
- * @returns {string}
- */
-Selector.prototype.getItemUid = function (oItem)
-{
- var
- sUid = '',
- fGetItemUidCallback = this.oCallbacks['onItemGetUid'] || null
- ;
-
- if (fGetItemUidCallback && oItem)
- {
- sUid = fGetItemUidCallback(oItem);
- }
-
- return sUid.toString();
-};
-
-/**
- * @param {number} iEventKeyCode
- * @param {boolean} bShiftKey
- * @param {boolean=} bForceSelect = false
- */
-Selector.prototype.newSelectPosition = function (iEventKeyCode, bShiftKey, bForceSelect)
-{
- var
- iIndex = 0,
- iPageStep = 10,
- bNext = false,
- bStop = false,
- oResult = null,
- aList = this.list(),
- iListLen = aList ? aList.length : 0,
- oFocused = this.focusedItem()
- ;
-
- if (0 < iListLen)
- {
- if (!oFocused)
- {
- if (Enums.EventKeyCode.Down === iEventKeyCode || Enums.EventKeyCode.Insert === iEventKeyCode || Enums.EventKeyCode.Space === iEventKeyCode || Enums.EventKeyCode.Home === iEventKeyCode || Enums.EventKeyCode.PageUp === iEventKeyCode)
- {
- oResult = aList[0];
- }
- else if (Enums.EventKeyCode.Up === iEventKeyCode || Enums.EventKeyCode.End === iEventKeyCode || Enums.EventKeyCode.PageDown === iEventKeyCode)
- {
- oResult = aList[aList.length - 1];
- }
- }
- else if (oFocused)
- {
- if (Enums.EventKeyCode.Down === iEventKeyCode || Enums.EventKeyCode.Up === iEventKeyCode || Enums.EventKeyCode.Insert === iEventKeyCode || Enums.EventKeyCode.Space === iEventKeyCode)
- {
- _.each(aList, function (oItem) {
- if (!bStop)
- {
- switch (iEventKeyCode) {
- case Enums.EventKeyCode.Up:
- if (oFocused === oItem)
- {
- bStop = true;
- }
- else
- {
- oResult = oItem;
- }
- break;
- case Enums.EventKeyCode.Down:
- case Enums.EventKeyCode.Insert:
- if (bNext)
- {
- oResult = oItem;
- bStop = true;
- }
- else if (oFocused === oItem)
- {
- bNext = true;
- }
- break;
- }
- }
- });
- }
- else if (Enums.EventKeyCode.Home === iEventKeyCode || Enums.EventKeyCode.End === iEventKeyCode)
- {
- if (Enums.EventKeyCode.Home === iEventKeyCode)
- {
- oResult = aList[0];
- }
- else if (Enums.EventKeyCode.End === iEventKeyCode)
- {
- oResult = aList[aList.length - 1];
- }
- }
- else if (Enums.EventKeyCode.PageDown === iEventKeyCode)
- {
- for (; iIndex < iListLen; iIndex++)
- {
- if (oFocused === aList[iIndex])
- {
- iIndex += iPageStep;
- iIndex = iListLen - 1 < iIndex ? iListLen - 1 : iIndex;
- oResult = aList[iIndex];
- break;
- }
- }
- }
- else if (Enums.EventKeyCode.PageUp === iEventKeyCode)
- {
- for (iIndex = iListLen; iIndex >= 0; iIndex--)
- {
- if (oFocused === aList[iIndex])
- {
- iIndex -= iPageStep;
- iIndex = 0 > iIndex ? 0 : iIndex;
- oResult = aList[iIndex];
- break;
- }
- }
- }
- }
- }
-
- if (oResult)
- {
- this.focusedItem(oResult);
-
- if (oFocused)
- {
- if (bShiftKey)
- {
- if (Enums.EventKeyCode.Up === iEventKeyCode || Enums.EventKeyCode.Down === iEventKeyCode)
- {
- oFocused.checked(!oFocused.checked());
- }
- }
- else if (Enums.EventKeyCode.Insert === iEventKeyCode || Enums.EventKeyCode.Space === iEventKeyCode)
- {
- oFocused.checked(!oFocused.checked());
- }
- }
-
- if ((this.bAutoSelect || !!bForceSelect) &&
- !this.isListChecked() && Enums.EventKeyCode.Space !== iEventKeyCode)
- {
- this.selectedItem(oResult);
- }
-
- this.scrollToFocused();
- }
- else if (oFocused)
- {
- if (bShiftKey && (Enums.EventKeyCode.Up === iEventKeyCode || Enums.EventKeyCode.Down === iEventKeyCode))
- {
- oFocused.checked(!oFocused.checked());
- }
- else if (Enums.EventKeyCode.Insert === iEventKeyCode || Enums.EventKeyCode.Space === iEventKeyCode)
- {
- oFocused.checked(!oFocused.checked());
- }
-
- this.focusedItem(oFocused);
- }
-};
-
-/**
- * @return {boolean}
- */
-Selector.prototype.scrollToFocused = function ()
-{
- if (!this.oContentVisible || !this.oContentScrollable)
- {
- return false;
- }
+ 'use strict';
var
- iOffset = 20,
- oFocused = $(this.sItemFocusedSelector, this.oContentScrollable),
- oPos = oFocused.position(),
- iVisibleHeight = this.oContentVisible.height(),
- iFocusedHeight = oFocused.outerHeight()
+ ko = require('../External/ko.js'),
+ LinkBuilder = require('../Common/LinkBuilder.js')
;
- if (oPos && (oPos.top < 0 || oPos.top + iFocusedHeight > iVisibleHeight))
+ /**
+ * @param {string} sEmail
+ * @param {boolean=} bCanBeDelete = true
+ * @constructor
+ */
+ function AccountModel(sEmail, bCanBeDelete)
{
- if (oPos.top < 0)
+ this.email = sEmail;
+ this.deleteAccess = ko.observable(false);
+ this.canBeDalete = ko.observable(bCanBeDelete);
+ }
+
+ AccountModel.prototype.email = '';
+
+ /**
+ * @return {string}
+ */
+ AccountModel.prototype.changeAccountLink = function ()
+ {
+ return LinkBuilder.change(this.email);
+ };
+
+ module.exports = AccountModel;
+
+}(module));
+},{"../Common/LinkBuilder.js":10,"../External/ko.js":28}],38:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ window = require('../External/window.js'),
+ Globals = require('../Common/Globals.js'),
+ Utils = require('../Common/Utils.js'),
+ LinkBuilder = require('../Common/LinkBuilder.js')
+ ;
+
+ /**
+ * @constructor
+ */
+ function AttachmentModel()
+ {
+ this.mimeType = '';
+ this.fileName = '';
+ this.estimatedSize = 0;
+ this.friendlySize = '';
+ this.isInline = false;
+ this.isLinked = false;
+ this.cid = '';
+ this.cidWithOutTags = '';
+ this.contentLocation = '';
+ this.download = '';
+ this.folder = '';
+ this.uid = '';
+ this.mimeIndex = '';
+ }
+
+ /**
+ * @static
+ * @param {AjaxJsonAttachment} oJsonAttachment
+ * @return {?AttachmentModel}
+ */
+ AttachmentModel.newInstanceFromJson = function (oJsonAttachment)
+ {
+ var oAttachmentModel = new AttachmentModel();
+ return oAttachmentModel.initByJson(oJsonAttachment) ? oAttachmentModel : null;
+ };
+
+ AttachmentModel.prototype.mimeType = '';
+ AttachmentModel.prototype.fileName = '';
+ AttachmentModel.prototype.estimatedSize = 0;
+ AttachmentModel.prototype.friendlySize = '';
+ AttachmentModel.prototype.isInline = false;
+ AttachmentModel.prototype.isLinked = false;
+ AttachmentModel.prototype.cid = '';
+ AttachmentModel.prototype.cidWithOutTags = '';
+ AttachmentModel.prototype.contentLocation = '';
+ AttachmentModel.prototype.download = '';
+ AttachmentModel.prototype.folder = '';
+ AttachmentModel.prototype.uid = '';
+ AttachmentModel.prototype.mimeIndex = '';
+
+ /**
+ * @param {AjaxJsonAttachment} oJsonAttachment
+ */
+ AttachmentModel.prototype.initByJson = function (oJsonAttachment)
+ {
+ var bResult = false;
+ if (oJsonAttachment && 'Object/Attachment' === oJsonAttachment['@Object'])
{
- this.oContentScrollable.scrollTop(this.oContentScrollable.scrollTop() + oPos.top - iOffset);
+ this.mimeType = (oJsonAttachment.MimeType || '').toLowerCase();
+ this.fileName = oJsonAttachment.FileName;
+ this.estimatedSize = Utils.pInt(oJsonAttachment.EstimatedSize);
+ this.isInline = !!oJsonAttachment.IsInline;
+ this.isLinked = !!oJsonAttachment.IsLinked;
+ this.cid = oJsonAttachment.CID;
+ this.contentLocation = oJsonAttachment.ContentLocation;
+ this.download = oJsonAttachment.Download;
+
+ this.folder = oJsonAttachment.Folder;
+ this.uid = oJsonAttachment.Uid;
+ this.mimeIndex = oJsonAttachment.MimeIndex;
+
+ this.friendlySize = Utils.friendlySize(this.estimatedSize);
+ this.cidWithOutTags = this.cid.replace(/^<+/, '').replace(/>+$/, '');
+
+ bResult = true;
}
- else
+
+ return bResult;
+ };
+
+ /**
+ * @return {boolean}
+ */
+ AttachmentModel.prototype.isImage = function ()
+ {
+ return -1 < Utils.inArray(this.mimeType.toLowerCase(),
+ ['image/png', 'image/jpg', 'image/jpeg', 'image/gif']
+ );
+ };
+
+ /**
+ * @return {boolean}
+ */
+ AttachmentModel.prototype.isText = function ()
+ {
+ return 'text/' === this.mimeType.substr(0, 5) &&
+ -1 === Utils.inArray(this.mimeType, ['text/html']);
+ };
+
+ /**
+ * @return {boolean}
+ */
+ AttachmentModel.prototype.isPdf = function ()
+ {
+ return Globals.bAllowPdfPreview && 'application/pdf' === this.mimeType;
+ };
+
+ /**
+ * @return {string}
+ */
+ AttachmentModel.prototype.linkDownload = function ()
+ {
+ return LinkBuilder.attachmentDownload(this.download);
+ };
+
+ /**
+ * @return {string}
+ */
+ AttachmentModel.prototype.linkPreview = function ()
+ {
+ return LinkBuilder.attachmentPreview(this.download);
+ };
+
+ /**
+ * @return {string}
+ */
+ AttachmentModel.prototype.linkPreviewAsPlain = function ()
+ {
+ return LinkBuilder.attachmentPreviewAsPlain(this.download);
+ };
+
+ /**
+ * @return {string}
+ */
+ AttachmentModel.prototype.generateTransferDownloadUrl = function ()
+ {
+ var sLink = this.linkDownload();
+ if ('http' !== sLink.substr(0, 4))
{
- this.oContentScrollable.scrollTop(this.oContentScrollable.scrollTop() + oPos.top - iVisibleHeight + iFocusedHeight + iOffset);
+ sLink = window.location.protocol + '//' + window.location.host + window.location.pathname + sLink;
+ }
+
+ return this.mimeType + ':' + this.fileName + ':' + sLink;
+ };
+
+ /**
+ * @param {AttachmentModel} oAttachment
+ * @param {*} oEvent
+ * @return {boolean}
+ */
+ AttachmentModel.prototype.eventDragStart = function (oAttachment, oEvent)
+ {
+ var oLocalEvent = oEvent.originalEvent || oEvent;
+ if (oAttachment && oLocalEvent && oLocalEvent.dataTransfer && oLocalEvent.dataTransfer.setData)
+ {
+ oLocalEvent.dataTransfer.setData('DownloadURL', this.generateTransferDownloadUrl());
}
return true;
- }
+ };
- return false;
-};
-
-/**
- * @param {boolean=} bFast = false
- * @return {boolean}
- */
-Selector.prototype.scrollToTop = function (bFast)
-{
- if (!this.oContentVisible || !this.oContentScrollable)
- {
- return false;
- }
-
- if (bFast)
- {
- this.oContentScrollable.scrollTop(0);
- }
- else
- {
- this.oContentScrollable.stop().animate({'scrollTop': 0}, 200);
- }
-
- return true;
-};
-
-Selector.prototype.eventClickFunction = function (oItem, oEvent)
-{
- var
- sUid = this.getItemUid(oItem),
- iIndex = 0,
- iLength = 0,
- oListItem = null,
- sLineUid = '',
- bChangeRange = false,
- bIsInRange = false,
- aList = [],
- bChecked = false
- ;
-
- if (oEvent && oEvent.shiftKey)
- {
- if ('' !== sUid && '' !== this.sLastUid && sUid !== this.sLastUid)
- {
- aList = this.list();
- bChecked = oItem.checked();
-
- for (iIndex = 0, iLength = aList.length; iIndex < iLength; iIndex++)
- {
- oListItem = aList[iIndex];
- sLineUid = this.getItemUid(oListItem);
-
- bChangeRange = false;
- if (sLineUid === this.sLastUid || sLineUid === sUid)
- {
- bChangeRange = true;
- }
-
- if (bChangeRange)
- {
- bIsInRange = !bIsInRange;
- }
-
- if (bIsInRange || bChangeRange)
- {
- oListItem.checked(bChecked);
- }
- }
- }
- }
-
- this.sLastUid = '' === sUid ? '' : sUid;
-};
-
-/**
- * @param {Object} oItem
- * @param {Object=} oEvent
- */
-Selector.prototype.actionClick = function (oItem, oEvent)
-{
- if (oItem)
+ AttachmentModel.prototype.iconClass = function ()
{
var
- bClick = true,
- sUid = this.getItemUid(oItem)
+ aParts = this.mimeType.toLocaleString().split('/'),
+ sClass = 'icon-file'
;
- if (oEvent)
+ if (aParts && aParts[1])
{
- if (oEvent.shiftKey && !oEvent.ctrlKey && !oEvent.altKey)
+ if ('image' === aParts[0])
{
- bClick = false;
- if ('' === this.sLastUid)
+ sClass = 'icon-file-image';
+ }
+ else if ('text' === aParts[0])
+ {
+ sClass = 'icon-file-text';
+ }
+ else if ('audio' === aParts[0])
+ {
+ sClass = 'icon-file-music';
+ }
+ else if ('video' === aParts[0])
+ {
+ sClass = 'icon-file-movie';
+ }
+ else if (-1 < Utils.inArray(aParts[1],
+ ['zip', '7z', 'tar', 'rar', 'gzip', 'bzip', 'bzip2', 'x-zip', 'x-7z', 'x-rar', 'x-tar', 'x-gzip', 'x-bzip', 'x-bzip2', 'x-zip-compressed', 'x-7z-compressed', 'x-rar-compressed']))
+ {
+ sClass = 'icon-file-zip';
+ }
+ // else if (-1 < Utils.inArray(aParts[1],
+ // ['pdf', 'x-pdf']))
+ // {
+ // sClass = 'icon-file-pdf';
+ // }
+ // else if (-1 < Utils.inArray(aParts[1], [
+ // 'exe', 'x-exe', 'x-winexe', 'bat'
+ // ]))
+ // {
+ // sClass = 'icon-console';
+ // }
+ else if (-1 < Utils.inArray(aParts[1], [
+ 'rtf', 'msword', 'vnd.msword', 'vnd.openxmlformats-officedocument.wordprocessingml.document',
+ 'vnd.openxmlformats-officedocument.wordprocessingml.template',
+ 'vnd.ms-word.document.macroEnabled.12',
+ 'vnd.ms-word.template.macroEnabled.12'
+ ]))
+ {
+ sClass = 'icon-file-text';
+ }
+ else if (-1 < Utils.inArray(aParts[1], [
+ 'excel', 'ms-excel', 'vnd.ms-excel',
+ 'vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+ 'vnd.openxmlformats-officedocument.spreadsheetml.template',
+ 'vnd.ms-excel.sheet.macroEnabled.12',
+ 'vnd.ms-excel.template.macroEnabled.12',
+ 'vnd.ms-excel.addin.macroEnabled.12',
+ 'vnd.ms-excel.sheet.binary.macroEnabled.12'
+ ]))
+ {
+ sClass = 'icon-file-excel';
+ }
+ else if (-1 < Utils.inArray(aParts[1], [
+ 'powerpoint', 'ms-powerpoint', 'vnd.ms-powerpoint',
+ 'vnd.openxmlformats-officedocument.presentationml.presentation',
+ 'vnd.openxmlformats-officedocument.presentationml.template',
+ 'vnd.openxmlformats-officedocument.presentationml.slideshow',
+ 'vnd.ms-powerpoint.addin.macroEnabled.12',
+ 'vnd.ms-powerpoint.presentation.macroEnabled.12',
+ 'vnd.ms-powerpoint.template.macroEnabled.12',
+ 'vnd.ms-powerpoint.slideshow.macroEnabled.12'
+ ]))
+ {
+ sClass = 'icon-file-chart-graph';
+ }
+ }
+
+ return sClass;
+ };
+
+ module.exports = AttachmentModel;
+
+}(module));
+},{"../Common/Globals.js":9,"../Common/LinkBuilder.js":10,"../Common/Utils.js":14,"../External/window.js":32}],39:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ Enums = require('../Common/Enums.js'),
+ Utils = require('../Common/Utils.js')
+ ;
+
+ /**
+ * @param {string=} sEmail
+ * @param {string=} sName
+ *
+ * @constructor
+ */
+ function EmailModel(sEmail, sName)
+ {
+ this.email = sEmail || '';
+ this.name = sName || '';
+ this.privateType = null;
+
+ this.clearDuplicateName();
+ }
+
+ /**
+ * @static
+ * @param {AjaxJsonEmail} oJsonEmail
+ * @return {?EmailModel}
+ */
+ EmailModel.newInstanceFromJson = function (oJsonEmail)
+ {
+ var oEmailModel = new EmailModel();
+ return oEmailModel.initByJson(oJsonEmail) ? oEmailModel : null;
+ };
+
+ /**
+ * @type {string}
+ */
+ EmailModel.prototype.name = '';
+
+ /**
+ * @type {string}
+ */
+ EmailModel.prototype.email = '';
+
+ /**
+ * @type {(number|null)}
+ */
+ EmailModel.prototype.privateType = null;
+
+ EmailModel.prototype.clear = function ()
+ {
+ this.email = '';
+ this.name = '';
+ this.privateType = null;
+ };
+
+ /**
+ * @returns {boolean}
+ */
+ EmailModel.prototype.validate = function ()
+ {
+ return '' !== this.name || '' !== this.email;
+ };
+
+ /**
+ * @param {boolean} bWithoutName = false
+ * @return {string}
+ */
+ EmailModel.prototype.hash = function (bWithoutName)
+ {
+ return '#' + (bWithoutName ? '' : this.name) + '#' + this.email + '#';
+ };
+
+ EmailModel.prototype.clearDuplicateName = function ()
+ {
+ if (this.name === this.email)
+ {
+ this.name = '';
+ }
+ };
+
+ /**
+ * @return {number}
+ */
+ EmailModel.prototype.type = function ()
+ {
+ if (null === this.privateType)
+ {
+ if (this.email && '@facebook.com' === this.email.substr(-13))
+ {
+ this.privateType = Enums.EmailType.Facebook;
+ }
+
+ if (null === this.privateType)
+ {
+ this.privateType = Enums.EmailType.Default;
+ }
+ }
+
+ return this.privateType;
+ };
+
+ /**
+ * @param {string} sQuery
+ * @return {boolean}
+ */
+ EmailModel.prototype.search = function (sQuery)
+ {
+ return -1 < (this.name + ' ' + this.email).toLowerCase().indexOf(sQuery.toLowerCase());
+ };
+
+ /**
+ * @param {string} sString
+ */
+ EmailModel.prototype.parse = function (sString)
+ {
+ this.clear();
+
+ sString = Utils.trim(sString);
+
+ var
+ mRegex = /(?:"([^"]+)")? ?(.*?@[^>,]+)>?,? ?/g,
+ mMatch = mRegex.exec(sString)
+ ;
+
+ if (mMatch)
+ {
+ this.name = mMatch[1] || '';
+ this.email = mMatch[2] || '';
+
+ this.clearDuplicateName();
+ }
+ else if ((/^[^@]+@[^@]+$/).test(sString))
+ {
+ this.name = '';
+ this.email = sString;
+ }
+ };
+
+ /**
+ * @param {AjaxJsonEmail} oJsonEmail
+ * @return {boolean}
+ */
+ EmailModel.prototype.initByJson = function (oJsonEmail)
+ {
+ var bResult = false;
+ if (oJsonEmail && 'Object/Email' === oJsonEmail['@Object'])
+ {
+ this.name = Utils.trim(oJsonEmail.Name);
+ this.email = Utils.trim(oJsonEmail.Email);
+
+ bResult = '' !== this.email;
+ this.clearDuplicateName();
+ }
+
+ return bResult;
+ };
+
+ /**
+ * @param {boolean} bFriendlyView
+ * @param {boolean=} bWrapWithLink = false
+ * @param {boolean=} bEncodeHtml = false
+ * @return {string}
+ */
+ EmailModel.prototype.toLine = function (bFriendlyView, bWrapWithLink, bEncodeHtml)
+ {
+ var sResult = '';
+ if ('' !== this.email)
+ {
+ bWrapWithLink = Utils.isUnd(bWrapWithLink) ? false : !!bWrapWithLink;
+ bEncodeHtml = Utils.isUnd(bEncodeHtml) ? false : !!bEncodeHtml;
+
+ if (bFriendlyView && '' !== this.name)
+ {
+ sResult = bWrapWithLink ? '') +
+ '" target="_blank" tabindex="-1">' + Utils.encodeHtml(this.name) + '' :
+ (bEncodeHtml ? Utils.encodeHtml(this.name) : this.name);
+ }
+ else
+ {
+ sResult = this.email;
+ if ('' !== this.name)
{
- this.sLastUid = sUid;
+ if (bWrapWithLink)
+ {
+ sResult = Utils.encodeHtml('"' + this.name + '" <') +
+ '') + '" target="_blank" tabindex="-1">' + Utils.encodeHtml(sResult) + '' + Utils.encodeHtml('>');
+ }
+ else
+ {
+ sResult = '"' + this.name + '" <' + sResult + '>';
+ if (bEncodeHtml)
+ {
+ sResult = Utils.encodeHtml(sResult);
+ }
+ }
+ }
+ else if (bWrapWithLink)
+ {
+ sResult = '' + Utils.encodeHtml(this.email) + '';
+ }
+ }
+ }
+
+ return sResult;
+ };
+
+ /**
+ * @param {string} $sEmailAddress
+ * @return {boolean}
+ */
+ EmailModel.prototype.mailsoParse = function ($sEmailAddress)
+ {
+ $sEmailAddress = Utils.trim($sEmailAddress);
+ if ('' === $sEmailAddress)
+ {
+ return false;
+ }
+
+ var
+ substr = function (str, start, len) {
+ str += '';
+ var end = str.length;
+
+ if (start < 0) {
+ start += end;
}
- oItem.checked(!oItem.checked());
- this.eventClickFunction(oItem, oEvent);
+ end = typeof len === 'undefined' ? end : (len < 0 ? len + end : len + start);
- this.focusedItem(oItem);
- }
- else if (oEvent.ctrlKey && !oEvent.shiftKey && !oEvent.altKey)
- {
- bClick = false;
- this.focusedItem(oItem);
+ return start >= str.length || start < 0 || start > end ? false : str.slice(start, end);
+ },
- if (this.selectedItem() && oItem !== this.selectedItem())
- {
- this.selectedItem().checked(true);
+ substr_replace = function (str, replace, start, length) {
+ if (start < 0) {
+ start = start + str.length;
}
+ length = length !== undefined ? length : str.length;
+ if (length < 0) {
+ length = length + str.length - start;
+ }
+ return str.slice(0, start) + replace.substr(0, length) + replace.slice(length) + str.slice(start + length);
+ },
- oItem.checked(!oItem.checked());
- }
- }
+ $sName = '',
+ $sEmail = '',
+ $sComment = '',
- if (bClick)
+ $bInName = false,
+ $bInAddress = false,
+ $bInComment = false,
+
+ $aRegs = null,
+
+ $iStartIndex = 0,
+ $iEndIndex = 0,
+ $iCurrentIndex = 0
+ ;
+
+ while ($iCurrentIndex < $sEmailAddress.length)
{
- this.focusedItem(oItem);
- this.selectedItem(oItem);
-
- this.scrollToFocused();
- }
- }
-};
-
-Selector.prototype.on = function (sEventName, fCallback)
-{
- this.oCallbacks[sEventName] = fCallback;
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function CookieDriver()
-{
-
-}
-
-CookieDriver.supported = function ()
-{
- return true;
-};
-
-/**
- * @param {string} sKey
- * @param {*} mData
- * @returns {boolean}
- */
-CookieDriver.prototype.set = function (sKey, mData)
-{
- var
- mCokieValue = $.cookie(Consts.Values.ClientSideCookieIndexName),
- bResult = false,
- mResult = null
- ;
-
- try
- {
- mResult = null === mCokieValue ? null : JSON.parse(mCokieValue);
- if (!mResult)
- {
- mResult = {};
- }
-
- mResult[sKey] = mData;
- $.cookie(Consts.Values.ClientSideCookieIndexName, JSON.stringify(mResult), {
- 'expires': 30
- });
-
- bResult = true;
- }
- catch (oException) {}
-
- return bResult;
-};
-
-/**
- * @param {string} sKey
- * @returns {*}
- */
-CookieDriver.prototype.get = function (sKey)
-{
- var
- mCokieValue = $.cookie(Consts.Values.ClientSideCookieIndexName),
- mResult = null
- ;
-
- try
- {
- mResult = null === mCokieValue ? null : JSON.parse(mCokieValue);
- if (mResult && !Utils.isUnd(mResult[sKey]))
- {
- mResult = mResult[sKey];
- }
- else
- {
- mResult = null;
- }
- }
- catch (oException) {}
-
- return mResult;
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function LocalStorageDriver()
-{
-}
-
-LocalStorageDriver.supported = function ()
-{
- return !!window.localStorage;
-};
-
-/**
- * @param {string} sKey
- * @param {*} mData
- * @returns {boolean}
- */
-LocalStorageDriver.prototype.set = function (sKey, mData)
-{
- var
- mCookieValue = window.localStorage[Consts.Values.ClientSideCookieIndexName] || null,
- bResult = false,
- mResult = null
- ;
-
- try
- {
- mResult = null === mCookieValue ? null : JSON.parse(mCookieValue);
- if (!mResult)
- {
- mResult = {};
- }
-
- mResult[sKey] = mData;
- window.localStorage[Consts.Values.ClientSideCookieIndexName] = JSON.stringify(mResult);
-
- bResult = true;
- }
- catch (oException) {}
-
- return bResult;
-};
-
-/**
- * @param {string} sKey
- * @returns {*}
- */
-LocalStorageDriver.prototype.get = function (sKey)
-{
- var
- mCokieValue = window.localStorage[Consts.Values.ClientSideCookieIndexName] || null,
- mResult = null
- ;
-
- try
- {
- mResult = null === mCokieValue ? null : JSON.parse(mCokieValue);
- if (mResult && !Utils.isUnd(mResult[sKey]))
- {
- mResult = mResult[sKey];
- }
- else
- {
- mResult = null;
- }
- }
- catch (oException) {}
-
- return mResult;
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function LocalStorage()
-{
- var
- sStorages = [
- LocalStorageDriver,
- CookieDriver
- ],
- NextStorageDriver = _.find(sStorages, function (NextStorageDriver) {
- return NextStorageDriver.supported();
- })
- ;
-
- if (NextStorageDriver)
- {
- NextStorageDriver = /** @type {?Function} */ NextStorageDriver;
- this.oDriver = new NextStorageDriver();
- }
-}
-
-LocalStorage.prototype.oDriver = null;
-
-/**
- * @param {number} iKey
- * @param {*} mData
- * @return {boolean}
- */
-LocalStorage.prototype.set = function (iKey, mData)
-{
- return this.oDriver ? this.oDriver.set('p' + iKey, mData) : false;
-};
-
-/**
- * @param {number} iKey
- * @return {*}
- */
-LocalStorage.prototype.get = function (iKey)
-{
- return this.oDriver ? this.oDriver.get('p' + iKey) : null;
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function KnoinAbstractBoot()
-{
-
-}
-
-KnoinAbstractBoot.prototype.bootstart = function ()
-{
-
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @param {string=} sPosition = ''
- * @param {string=} sTemplate = ''
- * @constructor
- */
-function KnoinAbstractViewModel(sPosition, sTemplate)
-{
- this.bDisabeCloseOnEsc = false;
- this.sPosition = Utils.pString(sPosition);
- this.sTemplate = Utils.pString(sTemplate);
-
- this.sDefaultKeyScope = Enums.KeyState.None;
- this.sCurrentKeyScope = this.sDefaultKeyScope;
-
- this.viewModelName = '';
- this.viewModelVisibility = ko.observable(false);
- this.modalVisibility = ko.observable(false).extend({'rateLimit': 0});
-
- this.viewModelDom = null;
-}
-
-/**
- * @type {string}
- */
-KnoinAbstractViewModel.prototype.sPosition = '';
-
-/**
- * @type {string}
- */
-KnoinAbstractViewModel.prototype.sTemplate = '';
-
-/**
- * @type {string}
- */
-KnoinAbstractViewModel.prototype.viewModelName = '';
-
-/**
- * @type {?}
- */
-KnoinAbstractViewModel.prototype.viewModelDom = null;
-
-/**
- * @return {string}
- */
-KnoinAbstractViewModel.prototype.viewModelTemplate = function ()
-{
- return this.sTemplate;
-};
-
-/**
- * @return {string}
- */
-KnoinAbstractViewModel.prototype.viewModelPosition = function ()
-{
- return this.sPosition;
-};
-
-KnoinAbstractViewModel.prototype.cancelCommand = KnoinAbstractViewModel.prototype.closeCommand = function ()
-{
-};
-
-KnoinAbstractViewModel.prototype.storeAndSetKeyScope = function ()
-{
- this.sCurrentKeyScope = RL.data().keyScope();
- RL.data().keyScope(this.sDefaultKeyScope);
-};
-
-KnoinAbstractViewModel.prototype.restoreKeyScope = function ()
-{
- RL.data().keyScope(this.sCurrentKeyScope);
-};
-
-KnoinAbstractViewModel.prototype.registerPopupKeyDown = function ()
-{
- var self = this;
- $window.on('keydown', function (oEvent) {
- if (oEvent && self.modalVisibility && self.modalVisibility())
- {
- if (!this.bDisabeCloseOnEsc && Enums.EventKeyCode.Esc === oEvent.keyCode)
+ switch ($sEmailAddress.substr($iCurrentIndex, 1))
{
- Utils.delegateRun(self, 'cancelCommand');
- return false;
+ case '"':
+ if ((!$bInName) && (!$bInAddress) && (!$bInComment))
+ {
+ $bInName = true;
+ $iStartIndex = $iCurrentIndex;
+ }
+ else if ((!$bInAddress) && (!$bInComment))
+ {
+ $iEndIndex = $iCurrentIndex;
+ $sName = substr($sEmailAddress, $iStartIndex + 1, $iEndIndex - $iStartIndex - 1);
+ $sEmailAddress = substr_replace($sEmailAddress, '', $iStartIndex, $iEndIndex - $iStartIndex + 1);
+ $iEndIndex = 0;
+ $iCurrentIndex = 0;
+ $iStartIndex = 0;
+ $bInName = false;
+ }
+ break;
+ case '<':
+ if ((!$bInName) && (!$bInAddress) && (!$bInComment))
+ {
+ if ($iCurrentIndex > 0 && $sName.length === 0)
+ {
+ $sName = substr($sEmailAddress, 0, $iCurrentIndex);
+ }
+
+ $bInAddress = true;
+ $iStartIndex = $iCurrentIndex;
+ }
+ break;
+ case '>':
+ if ($bInAddress)
+ {
+ $iEndIndex = $iCurrentIndex;
+ $sEmail = substr($sEmailAddress, $iStartIndex + 1, $iEndIndex - $iStartIndex - 1);
+ $sEmailAddress = substr_replace($sEmailAddress, '', $iStartIndex, $iEndIndex - $iStartIndex + 1);
+ $iEndIndex = 0;
+ $iCurrentIndex = 0;
+ $iStartIndex = 0;
+ $bInAddress = false;
+ }
+ break;
+ case '(':
+ if ((!$bInName) && (!$bInAddress) && (!$bInComment))
+ {
+ $bInComment = true;
+ $iStartIndex = $iCurrentIndex;
+ }
+ break;
+ case ')':
+ if ($bInComment)
+ {
+ $iEndIndex = $iCurrentIndex;
+ $sComment = substr($sEmailAddress, $iStartIndex + 1, $iEndIndex - $iStartIndex - 1);
+ $sEmailAddress = substr_replace($sEmailAddress, '', $iStartIndex, $iEndIndex - $iStartIndex + 1);
+ $iEndIndex = 0;
+ $iCurrentIndex = 0;
+ $iStartIndex = 0;
+ $bInComment = false;
+ }
+ break;
+ case '\\':
+ $iCurrentIndex++;
+ break;
}
- else if (Enums.EventKeyCode.Backspace === oEvent.keyCode && !Utils.inFocus())
+
+ $iCurrentIndex++;
+ }
+
+ if ($sEmail.length === 0)
+ {
+ $aRegs = $sEmailAddress.match(/[^@\s]+@\S+/i);
+ if ($aRegs && $aRegs[0])
{
- return false;
+ $sEmail = $aRegs[0];
+ }
+ else
+ {
+ $sName = $sEmailAddress;
}
}
+ if ($sEmail.length > 0 && $sName.length === 0 && $sComment.length === 0)
+ {
+ $sName = $sEmailAddress.replace($sEmail, '');
+ }
+
+ $sEmail = Utils.trim($sEmail).replace(/^[<]+/, '').replace(/[>]+$/, '');
+ $sName = Utils.trim($sName).replace(/^["']+/, '').replace(/["']+$/, '');
+ $sComment = Utils.trim($sComment).replace(/^[(]+/, '').replace(/[)]+$/, '');
+
+ // Remove backslash
+ $sName = $sName.replace(/\\\\(.)/, '$1');
+ $sComment = $sComment.replace(/\\\\(.)/, '$1');
+
+ this.name = $sName;
+ this.email = $sEmail;
+
+ this.clearDuplicateName();
return true;
- });
-};
-
+ };
+
+ /**
+ * @return {string}
+ */
+ EmailModel.prototype.inputoTagLine = function ()
+ {
+ return 0 < this.name.length ? this.name + ' (' + this.email + ')' : this.email;
+ };
+
+ module.exports = EmailModel;
+
+}(module));
+},{"../Common/Enums.js":7,"../Common/Utils.js":14}],40:[function(require,module,exports){
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-/**
- * @param {string} sScreenName
- * @param {?=} aViewModels = []
- * @constructor
- */
-function KnoinAbstractScreen(sScreenName, aViewModels)
-{
- this.sScreenName = sScreenName;
- this.aViewModels = Utils.isArray(aViewModels) ? aViewModels : [];
-}
+(function (module) {
-/**
- * @type {Array}
- */
-KnoinAbstractScreen.prototype.oCross = null;
+ 'use strict';
-/**
- * @type {string}
- */
-KnoinAbstractScreen.prototype.sScreenName = '';
-
-/**
- * @type {Array}
- */
-KnoinAbstractScreen.prototype.aViewModels = [];
-
-/**
- * @return {Array}
- */
-KnoinAbstractScreen.prototype.viewModels = function ()
-{
- return this.aViewModels;
-};
-
-/**
- * @return {string}
- */
-KnoinAbstractScreen.prototype.screenName = function ()
-{
- return this.sScreenName;
-};
-
-KnoinAbstractScreen.prototype.routes = function ()
-{
- return null;
-};
-
-/**
- * @return {?Object}
- */
-KnoinAbstractScreen.prototype.__cross = function ()
-{
- return this.oCross;
-};
-
-KnoinAbstractScreen.prototype.__start = function ()
-{
var
- aRoutes = this.routes(),
- oRoute = null,
- fMatcher = null
+ _ = require('../External/underscore.js'),
+ ko = require('../External/ko.js'),
+ $window = require('../External/$window.js'),
+
+ Enums = require('../Common/Enums.js'),
+ Globals = require('../Common/Globals.js'),
+ Utils = require('../Common/Utils.js'),
+ Events = require('../Common/Events.js')
;
- if (Utils.isNonEmptyArray(aRoutes))
+ /**
+ * @constructor
+ */
+ function FolderModel()
{
- fMatcher = _.bind(this.onRoute || Utils.emptyFunction, this);
- oRoute = crossroads.create();
+ this.name = ko.observable('');
+ this.fullName = '';
+ this.fullNameRaw = '';
+ this.fullNameHash = '';
+ this.delimiter = '';
+ this.namespace = '';
+ this.deep = 0;
+ this.interval = 0;
- _.each(aRoutes, function (aItem) {
- oRoute.addRoute(aItem[0], fMatcher).rules = aItem[1];
+ this.selectable = false;
+ this.existen = true;
+
+ this.type = ko.observable(Enums.FolderType.User);
+
+ this.focused = ko.observable(false);
+ this.selected = ko.observable(false);
+ this.edited = ko.observable(false);
+ this.collapsed = ko.observable(true);
+ this.subScribed = ko.observable(true);
+ this.subFolders = ko.observableArray([]);
+ this.deleteAccess = ko.observable(false);
+ this.actionBlink = ko.observable(false).extend({'falseTimeout': 1000});
+
+ this.nameForEdit = ko.observable('');
+
+ this.privateMessageCountAll = ko.observable(0);
+ this.privateMessageCountUnread = ko.observable(0);
+
+ this.collapsedPrivate = ko.observable(true);
+ }
+
+ /**
+ * @static
+ * @param {AjaxJsonFolder} oJsonFolder
+ * @return {?FolderModel}
+ */
+ FolderModel.newInstanceFromJson = function (oJsonFolder)
+ {
+ var oFolderModel = new FolderModel();
+ return oFolderModel.initByJson(oJsonFolder) ? oFolderModel.initComputed() : null;
+ };
+
+ /**
+ * @return {FolderModel}
+ */
+ FolderModel.prototype.initComputed = function ()
+ {
+ this.hasSubScribedSubfolders = ko.computed(function () {
+ return !!_.find(this.subFolders(), function (oFolder) {
+ return oFolder.subScribed() && !oFolder.isSystemFolder();
+ });
+ }, this);
+
+ this.canBeEdited = ko.computed(function () {
+ return Enums.FolderType.User === this.type() && this.existen && this.selectable;
+ }, this);
+
+ this.visible = ko.computed(function () {
+ var
+ bSubScribed = this.subScribed(),
+ bSubFolders = this.hasSubScribedSubfolders()
+ ;
+
+ return (bSubScribed || (bSubFolders && (!this.existen || !this.selectable)));
+ }, this);
+
+ this.isSystemFolder = ko.computed(function () {
+ return Enums.FolderType.User !== this.type();
+ }, this);
+
+ this.hidden = ko.computed(function () {
+ var
+ bSystem = this.isSystemFolder(),
+ bSubFolders = this.hasSubScribedSubfolders()
+ ;
+
+ return (bSystem && !bSubFolders) || (!this.selectable && !bSubFolders);
+
+ }, this);
+
+ this.selectableForFolderList = ko.computed(function () {
+ return !this.isSystemFolder() && this.selectable;
+ }, this);
+
+ this.messageCountAll = ko.computed({
+ 'read': this.privateMessageCountAll,
+ 'write': function (iValue) {
+ if (Utils.isPosNumeric(iValue, true))
+ {
+ this.privateMessageCountAll(iValue);
+ }
+ else
+ {
+ this.privateMessageCountAll.valueHasMutated();
+ }
+ },
+ 'owner': this
});
- this.oCross = oRoute;
- }
-};
-
+ this.messageCountUnread = ko.computed({
+ 'read': this.privateMessageCountUnread,
+ 'write': function (iValue) {
+ if (Utils.isPosNumeric(iValue, true))
+ {
+ this.privateMessageCountUnread(iValue);
+ }
+ else
+ {
+ this.privateMessageCountUnread.valueHasMutated();
+ }
+ },
+ 'owner': this
+ });
+
+ this.printableUnreadCount = ko.computed(function () {
+ var
+ iCount = this.messageCountAll(),
+ iUnread = this.messageCountUnread(),
+ iType = this.type()
+ ;
+
+ if (0 < iCount)
+ {
+ if (Enums.FolderType.Draft === iType)
+ {
+ return '' + iCount;
+ }
+ else if (0 < iUnread && Enums.FolderType.Trash !== iType && Enums.FolderType.Archive !== iType && Enums.FolderType.SentItems !== iType)
+ {
+ return '' + iUnread;
+ }
+ }
+
+ return '';
+
+ }, this);
+
+ this.canBeDeleted = ko.computed(function () {
+ var
+ bSystem = this.isSystemFolder()
+ ;
+ return !bSystem && 0 === this.subFolders().length && 'INBOX' !== this.fullNameRaw;
+ }, this);
+
+ this.canBeSubScribed = ko.computed(function () {
+ return !this.isSystemFolder() && this.selectable && 'INBOX' !== this.fullNameRaw;
+ }, this);
+
+ this.visible.subscribe(function () {
+ Utils.timeOutAction('folder-list-folder-visibility-change', function () {
+ $window.trigger('folder-list-folder-visibility-change');
+ }, 100);
+ });
+
+ this.localName = ko.computed(function () {
+
+ Globals.langChangeTrigger();
+
+ var
+ iType = this.type(),
+ sName = this.name()
+ ;
+
+ if (this.isSystemFolder())
+ {
+ switch (iType)
+ {
+ case Enums.FolderType.Inbox:
+ sName = Utils.i18n('FOLDER_LIST/INBOX_NAME');
+ break;
+ case Enums.FolderType.SentItems:
+ sName = Utils.i18n('FOLDER_LIST/SENT_NAME');
+ break;
+ case Enums.FolderType.Draft:
+ sName = Utils.i18n('FOLDER_LIST/DRAFTS_NAME');
+ break;
+ case Enums.FolderType.Spam:
+ sName = Utils.i18n('FOLDER_LIST/SPAM_NAME');
+ break;
+ case Enums.FolderType.Trash:
+ sName = Utils.i18n('FOLDER_LIST/TRASH_NAME');
+ break;
+ case Enums.FolderType.Archive:
+ sName = Utils.i18n('FOLDER_LIST/ARCHIVE_NAME');
+ break;
+ }
+ }
+
+ return sName;
+
+ }, this);
+
+ this.manageFolderSystemName = ko.computed(function () {
+
+ Globals.langChangeTrigger();
+
+ var
+ sSuffix = '',
+ iType = this.type(),
+ sName = this.name()
+ ;
+
+ if (this.isSystemFolder())
+ {
+ switch (iType)
+ {
+ case Enums.FolderType.Inbox:
+ sSuffix = '(' + Utils.i18n('FOLDER_LIST/INBOX_NAME') + ')';
+ break;
+ case Enums.FolderType.SentItems:
+ sSuffix = '(' + Utils.i18n('FOLDER_LIST/SENT_NAME') + ')';
+ break;
+ case Enums.FolderType.Draft:
+ sSuffix = '(' + Utils.i18n('FOLDER_LIST/DRAFTS_NAME') + ')';
+ break;
+ case Enums.FolderType.Spam:
+ sSuffix = '(' + Utils.i18n('FOLDER_LIST/SPAM_NAME') + ')';
+ break;
+ case Enums.FolderType.Trash:
+ sSuffix = '(' + Utils.i18n('FOLDER_LIST/TRASH_NAME') + ')';
+ break;
+ case Enums.FolderType.Archive:
+ sSuffix = '(' + Utils.i18n('FOLDER_LIST/ARCHIVE_NAME') + ')';
+ break;
+ }
+ }
+
+ if ('' !== sSuffix && '(' + sName + ')' === sSuffix || '(inbox)' === sSuffix.toLowerCase())
+ {
+ sSuffix = '';
+ }
+
+ return sSuffix;
+
+ }, this);
+
+ this.collapsed = ko.computed({
+ 'read': function () {
+ return !this.hidden() && this.collapsedPrivate();
+ },
+ 'write': function (mValue) {
+ this.collapsedPrivate(mValue);
+ },
+ 'owner': this
+ });
+
+ this.hasUnreadMessages = ko.computed(function () {
+ return 0 < this.messageCountUnread();
+ }, this);
+
+ this.hasSubScribedUnreadMessagesSubfolders = ko.computed(function () {
+ return !!_.find(this.subFolders(), function (oFolder) {
+ return oFolder.hasUnreadMessages() || oFolder.hasSubScribedUnreadMessagesSubfolders();
+ });
+ }, this);
+
+ // subscribe
+ this.name.subscribe(function (sValue) {
+ this.nameForEdit(sValue);
+ }, this);
+
+ this.edited.subscribe(function (bValue) {
+ if (bValue)
+ {
+ this.nameForEdit(this.name());
+ }
+ }, this);
+
+ this.messageCountUnread.subscribe(function (iUnread) {
+ if (Enums.FolderType.Inbox === this.type())
+ {
+ Events.pub('mailbox.inbox-unread-count', [iUnread]);
+ }
+ }, this);
+
+ return this;
+ };
+
+ FolderModel.prototype.fullName = '';
+ FolderModel.prototype.fullNameRaw = '';
+ FolderModel.prototype.fullNameHash = '';
+ FolderModel.prototype.delimiter = '';
+ FolderModel.prototype.namespace = '';
+ FolderModel.prototype.deep = 0;
+ FolderModel.prototype.interval = 0;
+
+ /**
+ * @return {string}
+ */
+ FolderModel.prototype.collapsedCss = function ()
+ {
+ return this.hasSubScribedSubfolders() ?
+ (this.collapsed() ? 'icon-right-mini e-collapsed-sign' : 'icon-down-mini e-collapsed-sign') : 'icon-none e-collapsed-sign';
+ };
+
+ /**
+ * @param {AjaxJsonFolder} oJsonFolder
+ * @return {boolean}
+ */
+ FolderModel.prototype.initByJson = function (oJsonFolder)
+ {
+ var bResult = false;
+ if (oJsonFolder && 'Object/Folder' === oJsonFolder['@Object'])
+ {
+ this.name(oJsonFolder.Name);
+ this.delimiter = oJsonFolder.Delimiter;
+ this.fullName = oJsonFolder.FullName;
+ this.fullNameRaw = oJsonFolder.FullNameRaw;
+ this.fullNameHash = oJsonFolder.FullNameHash;
+ this.deep = oJsonFolder.FullNameRaw.split(this.delimiter).length - 1;
+ this.selectable = !!oJsonFolder.IsSelectable;
+ this.existen = !!oJsonFolder.IsExists;
+
+ this.subScribed(!!oJsonFolder.IsSubscribed);
+ this.type('INBOX' === this.fullNameRaw ? Enums.FolderType.Inbox : Enums.FolderType.User);
+
+ bResult = true;
+ }
+
+ return bResult;
+ };
+
+ /**
+ * @return {string}
+ */
+ FolderModel.prototype.printableFullName = function ()
+ {
+ return this.fullName.split(this.delimiter).join(' / ');
+ };
+
+ module.exports = FolderModel;
+
+}(module));
+},{"../Common/Enums.js":7,"../Common/Events.js":8,"../Common/Globals.js":9,"../Common/Utils.js":14,"../External/$window.js":18,"../External/ko.js":28,"../External/underscore.js":31}],41:[function(require,module,exports){
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-/**
- * @constructor
- */
-function Knoin()
-{
- this.sDefaultScreenName = '';
- this.oScreens = {};
- this.oBoot = null;
- this.oCurrentScreen = null;
-}
+(function (module) {
-/**
- * @param {Object} thisObject
- */
-Knoin.constructorEnd = function (thisObject)
-{
- if (Utils.isFunc(thisObject['__constructor_end']))
+ 'use strict';
+
+ var
+ ko = require('../External/ko.js'),
+ Utils = require('../Common/Utils.js')
+ ;
+
+ /**
+ * @param {string} sId
+ * @param {string} sEmail
+ * @param {boolean=} bCanBeDelete = true
+ * @constructor
+ */
+ function IdentityModel(sId, sEmail, bCanBeDelete)
{
- thisObject['__constructor_end'].call(thisObject);
- }
-};
+ this.id = sId;
+ this.email = ko.observable(sEmail);
+ this.name = ko.observable('');
+ this.replyTo = ko.observable('');
+ this.bcc = ko.observable('');
-Knoin.prototype.sDefaultScreenName = '';
-Knoin.prototype.oScreens = {};
-Knoin.prototype.oBoot = null;
-Knoin.prototype.oCurrentScreen = null;
-
-Knoin.prototype.hideLoading = function ()
-{
- $('#rl-loading').hide();
-};
-
-Knoin.prototype.routeOff = function ()
-{
- hasher.changed.active = false;
-};
-
-Knoin.prototype.routeOn = function ()
-{
- hasher.changed.active = true;
-};
-
-/**
- * @param {Object} oBoot
- * @return {Knoin}
- */
-Knoin.prototype.setBoot = function (oBoot)
-{
- if (Utils.isNormal(oBoot))
- {
- this.oBoot = oBoot;
+ this.deleteAccess = ko.observable(false);
+ this.canBeDalete = ko.observable(bCanBeDelete);
}
- return this;
-};
+ IdentityModel.prototype.formattedName = function ()
+ {
+ var sName = this.name();
+ return '' === sName ? this.email() : sName + ' <' + this.email() + '>';
+ };
-/**
- * @param {string} sScreenName
- * @return {?Object}
- */
-Knoin.prototype.screen = function (sScreenName)
-{
- return ('' !== sScreenName && !Utils.isUnd(this.oScreens[sScreenName])) ? this.oScreens[sScreenName] : null;
-};
+ IdentityModel.prototype.formattedNameForCompose = function ()
+ {
+ var sName = this.name();
+ return '' === sName ? this.email() : sName + ' (' + this.email() + ')';
+ };
-/**
- * @param {Function} ViewModelClass
- * @param {Object=} oScreen
- */
-Knoin.prototype.buildViewModel = function (ViewModelClass, oScreen)
-{
- if (ViewModelClass && !ViewModelClass.__builded)
+ IdentityModel.prototype.formattedNameForEmail = function ()
+ {
+ var sName = this.name();
+ return '' === sName ? this.email() : '"' + Utils.quoteName(sName) + '" <' + this.email() + '>';
+ };
+
+ module.exports = IdentityModel;
+
+}(module));
+},{"../Common/Utils.js":14,"../External/ko.js":28}],42:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ window = require('../External/window.js'),
+ $ = require('../External/jquery.js'),
+ _ = require('../External/underscore.js'),
+ ko = require('../External/ko.js'),
+ moment = require('../External/moment.js'),
+ $window = require('../External/$window.js'),
+ $div = require('../External/$div.js'),
+
+ Enums = require('../Common/Enums.js'),
+ Utils = require('../Common/Utils.js'),
+ LinkBuilder = require('../Common/LinkBuilder.js'),
+
+ EmailModel = require('./EmailModel.js'),
+ AttachmentModel = require('./AttachmentModel.js')
+ ;
+
+ /**
+ * @constructor
+ */
+ function MessageModel()
+ {
+ this.folderFullNameRaw = '';
+ this.uid = '';
+ this.hash = '';
+ this.requestHash = '';
+ this.subject = ko.observable('');
+ this.subjectPrefix = ko.observable('');
+ this.subjectSuffix = ko.observable('');
+ this.size = ko.observable(0);
+ this.dateTimeStampInUTC = ko.observable(0);
+ this.priority = ko.observable(Enums.MessagePriority.Normal);
+
+ this.proxy = false;
+
+ this.fromEmailString = ko.observable('');
+ this.fromClearEmailString = ko.observable('');
+ this.toEmailsString = ko.observable('');
+ this.toClearEmailsString = ko.observable('');
+
+ this.senderEmailsString = ko.observable('');
+ this.senderClearEmailsString = ko.observable('');
+
+ this.emails = [];
+
+ this.from = [];
+ this.to = [];
+ this.cc = [];
+ this.bcc = [];
+ this.replyTo = [];
+ this.deliveredTo = [];
+
+ this.newForAnimation = ko.observable(false);
+
+ this.deleted = ko.observable(false);
+ this.unseen = ko.observable(false);
+ this.flagged = ko.observable(false);
+ this.answered = ko.observable(false);
+ this.forwarded = ko.observable(false);
+ this.isReadReceipt = ko.observable(false);
+
+ this.focused = ko.observable(false);
+ this.selected = ko.observable(false);
+ this.checked = ko.observable(false);
+ this.hasAttachments = ko.observable(false);
+ this.attachmentsMainType = ko.observable('');
+
+ this.moment = ko.observable(moment(moment.unix(0)));
+
+ this.attachmentIconClass = ko.computed(function () {
+ var sClass = '';
+ if (this.hasAttachments())
+ {
+ sClass = 'icon-attachment';
+ switch (this.attachmentsMainType())
+ {
+ case 'image':
+ sClass = 'icon-image';
+ break;
+ case 'archive':
+ sClass = 'icon-file-zip';
+ break;
+ case 'doc':
+ sClass = 'icon-file-text';
+ break;
+ // case 'pdf':
+ // sClass = 'icon-file-pdf';
+ // break;
+ }
+ }
+ return sClass;
+ }, this);
+
+ this.fullFormatDateValue = ko.computed(function () {
+ return MessageModel.calculateFullFromatDateValue(this.dateTimeStampInUTC());
+ }, this);
+
+ this.momentDate = Utils.createMomentDate(this);
+ this.momentShortDate = Utils.createMomentShortDate(this);
+
+ this.dateTimeStampInUTC.subscribe(function (iValue) {
+ var iNow = moment().unix();
+ this.moment(moment.unix(iNow < iValue ? iNow : iValue));
+ }, this);
+
+ this.body = null;
+ this.plainRaw = '';
+ this.isHtml = ko.observable(false);
+ this.hasImages = ko.observable(false);
+ this.attachments = ko.observableArray([]);
+
+ this.isPgpSigned = ko.observable(false);
+ this.isPgpEncrypted = ko.observable(false);
+ this.pgpSignedVerifyStatus = ko.observable(Enums.SignedVerifyStatus.None);
+ this.pgpSignedVerifyUser = ko.observable('');
+
+ this.priority = ko.observable(Enums.MessagePriority.Normal);
+ this.readReceipt = ko.observable('');
+
+ this.aDraftInfo = [];
+ this.sMessageId = '';
+ this.sInReplyTo = '';
+ this.sReferences = '';
+
+ this.parentUid = ko.observable(0);
+ this.threads = ko.observableArray([]);
+ this.threadsLen = ko.observable(0);
+ this.hasUnseenSubMessage = ko.observable(false);
+ this.hasFlaggedSubMessage = ko.observable(false);
+
+ this.lastInCollapsedThread = ko.observable(false);
+ this.lastInCollapsedThreadLoading = ko.observable(false);
+
+ this.threadsLenResult = ko.computed(function () {
+ var iCount = this.threadsLen();
+ return 0 === this.parentUid() && 0 < iCount ? iCount + 1 : '';
+ }, this);
+ }
+
+ /**
+ * @static
+ * @param {AjaxJsonMessage} oJsonMessage
+ * @return {?MessageModel}
+ */
+ MessageModel.newInstanceFromJson = function (oJsonMessage)
+ {
+ var oMessageModel = new MessageModel();
+ return oMessageModel.initByJson(oJsonMessage) ? oMessageModel : null;
+ };
+
+ /**
+ * @static
+ * @param {number} iTimeStampInUTC
+ * @return {string}
+ */
+ MessageModel.calculateFullFromatDateValue = function (iTimeStampInUTC)
+ {
+ return 0 < iTimeStampInUTC ? moment.unix(iTimeStampInUTC).format('LLL') : '';
+ };
+
+ /**
+ * @static
+ * @param {Array} aEmail
+ * @param {boolean=} bFriendlyView
+ * @param {boolean=} bWrapWithLink = false
+ * @return {string}
+ */
+ MessageModel.emailsToLine = function (aEmail, bFriendlyView, bWrapWithLink)
{
var
- oViewModel = new ViewModelClass(oScreen),
- sPosition = oViewModel.viewModelPosition(),
- oViewModelPlace = $('#rl-content #rl-' + sPosition.toLowerCase()),
+ aResult = [],
+ iIndex = 0,
+ iLen = 0
+ ;
+
+ if (Utils.isNonEmptyArray(aEmail))
+ {
+ for (iIndex = 0, iLen = aEmail.length; iIndex < iLen; iIndex++)
+ {
+ aResult.push(aEmail[iIndex].toLine(bFriendlyView, bWrapWithLink));
+ }
+ }
+
+ return aResult.join(', ');
+ };
+
+ /**
+ * @static
+ * @param {Array} aEmail
+ * @return {string}
+ */
+ MessageModel.emailsToLineClear = function (aEmail)
+ {
+ var
+ aResult = [],
+ iIndex = 0,
+ iLen = 0
+ ;
+
+ if (Utils.isNonEmptyArray(aEmail))
+ {
+ for (iIndex = 0, iLen = aEmail.length; iIndex < iLen; iIndex++)
+ {
+ if (aEmail[iIndex] && aEmail[iIndex].email && '' !== aEmail[iIndex].name)
+ {
+ aResult.push(aEmail[iIndex].email);
+ }
+ }
+ }
+
+ return aResult.join(', ');
+ };
+
+ /**
+ * @static
+ * @param {?Array} aJsonEmails
+ * @return {Array.}
+ */
+ MessageModel.initEmailsFromJson = function (aJsonEmails)
+ {
+ var
+ iIndex = 0,
+ iLen = 0,
+ oEmailModel = null,
+ aResult = []
+ ;
+
+ if (Utils.isNonEmptyArray(aJsonEmails))
+ {
+ for (iIndex = 0, iLen = aJsonEmails.length; iIndex < iLen; iIndex++)
+ {
+ oEmailModel = EmailModel.newInstanceFromJson(aJsonEmails[iIndex]);
+ if (oEmailModel)
+ {
+ aResult.push(oEmailModel);
+ }
+ }
+ }
+
+ return aResult;
+ };
+
+ /**
+ * @static
+ * @param {Array.} aMessageEmails
+ * @param {Object} oLocalUnic
+ * @param {Array} aLocalEmails
+ */
+ MessageModel.replyHelper = function (aMessageEmails, oLocalUnic, aLocalEmails)
+ {
+ if (aMessageEmails && 0 < aMessageEmails.length)
+ {
+ var
+ iIndex = 0,
+ iLen = aMessageEmails.length
+ ;
+
+ for (; iIndex < iLen; iIndex++)
+ {
+ if (Utils.isUnd(oLocalUnic[aMessageEmails[iIndex].email]))
+ {
+ oLocalUnic[aMessageEmails[iIndex].email] = true;
+ aLocalEmails.push(aMessageEmails[iIndex]);
+ }
+ }
+ }
+ };
+
+ MessageModel.prototype.clear = function ()
+ {
+ this.folderFullNameRaw = '';
+ this.uid = '';
+ this.hash = '';
+ this.requestHash = '';
+ this.subject('');
+ this.subjectPrefix('');
+ this.subjectSuffix('');
+ this.size(0);
+ this.dateTimeStampInUTC(0);
+ this.priority(Enums.MessagePriority.Normal);
+
+ this.proxy = false;
+
+ this.fromEmailString('');
+ this.fromClearEmailString('');
+ this.toEmailsString('');
+ this.toClearEmailsString('');
+ this.senderEmailsString('');
+ this.senderClearEmailsString('');
+
+ this.emails = [];
+
+ this.from = [];
+ this.to = [];
+ this.cc = [];
+ this.bcc = [];
+ this.replyTo = [];
+ this.deliveredTo = [];
+
+ this.newForAnimation(false);
+
+ this.deleted(false);
+ this.unseen(false);
+ this.flagged(false);
+ this.answered(false);
+ this.forwarded(false);
+ this.isReadReceipt(false);
+
+ this.selected(false);
+ this.checked(false);
+ this.hasAttachments(false);
+ this.attachmentsMainType('');
+
+ this.body = null;
+ this.isHtml(false);
+ this.hasImages(false);
+ this.attachments([]);
+
+ this.isPgpSigned(false);
+ this.isPgpEncrypted(false);
+ this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.None);
+ this.pgpSignedVerifyUser('');
+
+ this.priority(Enums.MessagePriority.Normal);
+ this.readReceipt('');
+ this.aDraftInfo = [];
+ this.sMessageId = '';
+ this.sInReplyTo = '';
+ this.sReferences = '';
+
+ this.parentUid(0);
+ this.threads([]);
+ this.threadsLen(0);
+ this.hasUnseenSubMessage(false);
+ this.hasFlaggedSubMessage(false);
+
+ this.lastInCollapsedThread(false);
+ this.lastInCollapsedThreadLoading(false);
+ };
+
+ MessageModel.prototype.computeSenderEmail = function ()
+ {
+ var
+ Data = require('../Storages/WebMailDataStorage.js'),
+ sSent = Data.sentFolder(),
+ sDraft = Data.draftFolder()
+ ;
+
+ this.senderEmailsString(this.folderFullNameRaw === sSent || this.folderFullNameRaw === sDraft ?
+ this.toEmailsString() : this.fromEmailString());
+
+ this.senderClearEmailsString(this.folderFullNameRaw === sSent || this.folderFullNameRaw === sDraft ?
+ this.toClearEmailsString() : this.fromClearEmailString());
+ };
+
+ /**
+ * @param {AjaxJsonMessage} oJsonMessage
+ * @return {boolean}
+ */
+ MessageModel.prototype.initByJson = function (oJsonMessage)
+ {
+ var bResult = false;
+ if (oJsonMessage && 'Object/Message' === oJsonMessage['@Object'])
+ {
+ this.folderFullNameRaw = oJsonMessage.Folder;
+ this.uid = oJsonMessage.Uid;
+ this.hash = oJsonMessage.Hash;
+ this.requestHash = oJsonMessage.RequestHash;
+
+ this.proxy = !!oJsonMessage.ExternalProxy;
+
+ this.size(Utils.pInt(oJsonMessage.Size));
+
+ this.from = MessageModel.initEmailsFromJson(oJsonMessage.From);
+ this.to = MessageModel.initEmailsFromJson(oJsonMessage.To);
+ this.cc = MessageModel.initEmailsFromJson(oJsonMessage.Cc);
+ this.bcc = MessageModel.initEmailsFromJson(oJsonMessage.Bcc);
+ this.replyTo = MessageModel.initEmailsFromJson(oJsonMessage.ReplyTo);
+ this.deliveredTo = MessageModel.initEmailsFromJson(oJsonMessage.DeliveredTo);
+
+ this.subject(oJsonMessage.Subject);
+ if (Utils.isArray(oJsonMessage.SubjectParts))
+ {
+ this.subjectPrefix(oJsonMessage.SubjectParts[0]);
+ this.subjectSuffix(oJsonMessage.SubjectParts[1]);
+ }
+ else
+ {
+ this.subjectPrefix('');
+ this.subjectSuffix(this.subject());
+ }
+
+ this.dateTimeStampInUTC(Utils.pInt(oJsonMessage.DateTimeStampInUTC));
+ this.hasAttachments(!!oJsonMessage.HasAttachments);
+ this.attachmentsMainType(oJsonMessage.AttachmentsMainType);
+
+ this.fromEmailString(MessageModel.emailsToLine(this.from, true));
+ this.fromClearEmailString(MessageModel.emailsToLineClear(this.from));
+ this.toEmailsString(MessageModel.emailsToLine(this.to, true));
+ this.toClearEmailsString(MessageModel.emailsToLineClear(this.to));
+
+ this.parentUid(Utils.pInt(oJsonMessage.ParentThread));
+ this.threads(Utils.isArray(oJsonMessage.Threads) ? oJsonMessage.Threads : []);
+ this.threadsLen(Utils.pInt(oJsonMessage.ThreadsLen));
+
+ this.initFlagsByJson(oJsonMessage);
+ this.computeSenderEmail();
+
+ bResult = true;
+ }
+
+ return bResult;
+ };
+
+ /**
+ * @param {AjaxJsonMessage} oJsonMessage
+ * @return {boolean}
+ */
+ MessageModel.prototype.initUpdateByMessageJson = function (oJsonMessage)
+ {
+ var
+ Data = require('../Storages/WebMailDataStorage.js'),
+ bResult = false,
+ iPriority = Enums.MessagePriority.Normal
+ ;
+
+ if (oJsonMessage && 'Object/Message' === oJsonMessage['@Object'])
+ {
+ iPriority = Utils.pInt(oJsonMessage.Priority);
+ this.priority(-1 < Utils.inArray(iPriority, [Enums.MessagePriority.High, Enums.MessagePriority.Low]) ?
+ iPriority : Enums.MessagePriority.Normal);
+
+ this.aDraftInfo = oJsonMessage.DraftInfo;
+
+ this.sMessageId = oJsonMessage.MessageId;
+ this.sInReplyTo = oJsonMessage.InReplyTo;
+ this.sReferences = oJsonMessage.References;
+
+ this.proxy = !!oJsonMessage.ExternalProxy;
+
+ if (Data.capaOpenPGP())
+ {
+ this.isPgpSigned(!!oJsonMessage.PgpSigned);
+ this.isPgpEncrypted(!!oJsonMessage.PgpEncrypted);
+ }
+
+ this.hasAttachments(!!oJsonMessage.HasAttachments);
+ this.attachmentsMainType(oJsonMessage.AttachmentsMainType);
+
+ this.foundedCIDs = Utils.isArray(oJsonMessage.FoundedCIDs) ? oJsonMessage.FoundedCIDs : [];
+ this.attachments(this.initAttachmentsFromJson(oJsonMessage.Attachments));
+
+ this.readReceipt(oJsonMessage.ReadReceipt || '');
+
+ this.computeSenderEmail();
+
+ bResult = true;
+ }
+
+ return bResult;
+ };
+
+ /**
+ * @param {(AjaxJsonAttachment|null)} oJsonAttachments
+ * @return {Array}
+ */
+ MessageModel.prototype.initAttachmentsFromJson = function (oJsonAttachments)
+ {
+ var
+ iIndex = 0,
+ iLen = 0,
+ oAttachmentModel = null,
+ aResult = []
+ ;
+
+ if (oJsonAttachments && 'Collection/AttachmentCollection' === oJsonAttachments['@Object'] &&
+ Utils.isNonEmptyArray(oJsonAttachments['@Collection']))
+ {
+ for (iIndex = 0, iLen = oJsonAttachments['@Collection'].length; iIndex < iLen; iIndex++)
+ {
+ oAttachmentModel = AttachmentModel.newInstanceFromJson(oJsonAttachments['@Collection'][iIndex]);
+ if (oAttachmentModel)
+ {
+ if ('' !== oAttachmentModel.cidWithOutTags && 0 < this.foundedCIDs.length &&
+ 0 <= Utils.inArray(oAttachmentModel.cidWithOutTags, this.foundedCIDs))
+ {
+ oAttachmentModel.isLinked = true;
+ }
+
+ aResult.push(oAttachmentModel);
+ }
+ }
+ }
+
+ return aResult;
+ };
+
+ /**
+ * @param {AjaxJsonMessage} oJsonMessage
+ * @return {boolean}
+ */
+ MessageModel.prototype.initFlagsByJson = function (oJsonMessage)
+ {
+ var bResult = false;
+
+ if (oJsonMessage && 'Object/Message' === oJsonMessage['@Object'])
+ {
+ this.unseen(!oJsonMessage.IsSeen);
+ this.flagged(!!oJsonMessage.IsFlagged);
+ this.answered(!!oJsonMessage.IsAnswered);
+ this.forwarded(!!oJsonMessage.IsForwarded);
+ this.isReadReceipt(!!oJsonMessage.IsReadReceipt);
+
+ bResult = true;
+ }
+
+ return bResult;
+ };
+
+ /**
+ * @param {boolean} bFriendlyView
+ * @param {boolean=} bWrapWithLink = false
+ * @return {string}
+ */
+ MessageModel.prototype.fromToLine = function (bFriendlyView, bWrapWithLink)
+ {
+ return MessageModel.emailsToLine(this.from, bFriendlyView, bWrapWithLink);
+ };
+
+ /**
+ * @param {boolean} bFriendlyView
+ * @param {boolean=} bWrapWithLink = false
+ * @return {string}
+ */
+ MessageModel.prototype.toToLine = function (bFriendlyView, bWrapWithLink)
+ {
+ return MessageModel.emailsToLine(this.to, bFriendlyView, bWrapWithLink);
+ };
+
+ /**
+ * @param {boolean} bFriendlyView
+ * @param {boolean=} bWrapWithLink = false
+ * @return {string}
+ */
+ MessageModel.prototype.ccToLine = function (bFriendlyView, bWrapWithLink)
+ {
+ return MessageModel.emailsToLine(this.cc, bFriendlyView, bWrapWithLink);
+ };
+
+ /**
+ * @param {boolean} bFriendlyView
+ * @param {boolean=} bWrapWithLink = false
+ * @return {string}
+ */
+ MessageModel.prototype.bccToLine = function (bFriendlyView, bWrapWithLink)
+ {
+ return MessageModel.emailsToLine(this.bcc, bFriendlyView, bWrapWithLink);
+ };
+
+ /**
+ * @return string
+ */
+ MessageModel.prototype.lineAsCcc = function ()
+ {
+ var aResult = [];
+ if (this.deleted())
+ {
+ aResult.push('deleted');
+ }
+ if (this.selected())
+ {
+ aResult.push('selected');
+ }
+ if (this.checked())
+ {
+ aResult.push('checked');
+ }
+ if (this.flagged())
+ {
+ aResult.push('flagged');
+ }
+ if (this.unseen())
+ {
+ aResult.push('unseen');
+ }
+ if (this.answered())
+ {
+ aResult.push('answered');
+ }
+ if (this.forwarded())
+ {
+ aResult.push('forwarded');
+ }
+ if (this.focused())
+ {
+ aResult.push('focused');
+ }
+ if (this.hasAttachments())
+ {
+ aResult.push('withAttachments');
+ switch (this.attachmentsMainType())
+ {
+ case 'image':
+ aResult.push('imageOnlyAttachments');
+ break;
+ case 'archive':
+ aResult.push('archiveOnlyAttachments');
+ break;
+ }
+ }
+ if (this.newForAnimation())
+ {
+ aResult.push('new');
+ }
+ if ('' === this.subject())
+ {
+ aResult.push('emptySubject');
+ }
+ if (0 < this.parentUid())
+ {
+ aResult.push('hasParentMessage');
+ }
+ if (0 < this.threadsLen() && 0 === this.parentUid())
+ {
+ aResult.push('hasChildrenMessage');
+ }
+ if (this.hasUnseenSubMessage())
+ {
+ aResult.push('hasUnseenSubMessage');
+ }
+ if (this.hasFlaggedSubMessage())
+ {
+ aResult.push('hasFlaggedSubMessage');
+ }
+
+ return aResult.join(' ');
+ };
+
+ /**
+ * @return {boolean}
+ */
+ MessageModel.prototype.hasVisibleAttachments = function ()
+ {
+ return !!_.find(this.attachments(), function (oAttachment) {
+ return !oAttachment.isLinked;
+ });
+ };
+
+ /**
+ * @param {string} sCid
+ * @return {*}
+ */
+ MessageModel.prototype.findAttachmentByCid = function (sCid)
+ {
+ var
+ oResult = null,
+ aAttachments = this.attachments()
+ ;
+
+ if (Utils.isNonEmptyArray(aAttachments))
+ {
+ sCid = sCid.replace(/^<+/, '').replace(/>+$/, '');
+ oResult = _.find(aAttachments, function (oAttachment) {
+ return sCid === oAttachment.cidWithOutTags;
+ });
+ }
+
+ return oResult || null;
+ };
+
+ /**
+ * @param {string} sContentLocation
+ * @return {*}
+ */
+ MessageModel.prototype.findAttachmentByContentLocation = function (sContentLocation)
+ {
+ var
+ oResult = null,
+ aAttachments = this.attachments()
+ ;
+
+ if (Utils.isNonEmptyArray(aAttachments))
+ {
+ oResult = _.find(aAttachments, function (oAttachment) {
+ return sContentLocation === oAttachment.contentLocation;
+ });
+ }
+
+ return oResult || null;
+ };
+
+
+ /**
+ * @return {string}
+ */
+ MessageModel.prototype.messageId = function ()
+ {
+ return this.sMessageId;
+ };
+
+ /**
+ * @return {string}
+ */
+ MessageModel.prototype.inReplyTo = function ()
+ {
+ return this.sInReplyTo;
+ };
+
+ /**
+ * @return {string}
+ */
+ MessageModel.prototype.references = function ()
+ {
+ return this.sReferences;
+ };
+
+ /**
+ * @return {string}
+ */
+ MessageModel.prototype.fromAsSingleEmail = function ()
+ {
+ return Utils.isArray(this.from) && this.from[0] ? this.from[0].email : '';
+ };
+
+ /**
+ * @return {string}
+ */
+ MessageModel.prototype.viewLink = function ()
+ {
+ return LinkBuilder.messageViewLink(this.requestHash);
+ };
+
+ /**
+ * @return {string}
+ */
+ MessageModel.prototype.downloadLink = function ()
+ {
+ return LinkBuilder.messageDownloadLink(this.requestHash);
+ };
+
+ /**
+ * @param {Object} oExcludeEmails
+ * @return {Array}
+ */
+ MessageModel.prototype.replyEmails = function (oExcludeEmails)
+ {
+ var
+ aResult = [],
+ oUnic = Utils.isUnd(oExcludeEmails) ? {} : oExcludeEmails
+ ;
+
+ MessageModel.replyHelper(this.replyTo, oUnic, aResult);
+ if (0 === aResult.length)
+ {
+ MessageModel.replyHelper(this.from, oUnic, aResult);
+ }
+
+ return aResult;
+ };
+
+ /**
+ * @param {Object} oExcludeEmails
+ * @return {Array.}
+ */
+ MessageModel.prototype.replyAllEmails = function (oExcludeEmails)
+ {
+ var
+ aToResult = [],
+ aCcResult = [],
+ oUnic = Utils.isUnd(oExcludeEmails) ? {} : oExcludeEmails
+ ;
+
+ MessageModel.replyHelper(this.replyTo, oUnic, aToResult);
+ if (0 === aToResult.length)
+ {
+ MessageModel.replyHelper(this.from, oUnic, aToResult);
+ }
+
+ MessageModel.replyHelper(this.to, oUnic, aToResult);
+ MessageModel.replyHelper(this.cc, oUnic, aCcResult);
+
+ return [aToResult, aCcResult];
+ };
+
+ /**
+ * @return {string}
+ */
+ MessageModel.prototype.textBodyToString = function ()
+ {
+ return this.body ? this.body.html() : '';
+ };
+
+ /**
+ * @return {string}
+ */
+ MessageModel.prototype.attachmentsToStringLine = function ()
+ {
+ var aAttachLines = _.map(this.attachments(), function (oItem) {
+ return oItem.fileName + ' (' + oItem.friendlySize + ')';
+ });
+
+ return aAttachLines && 0 < aAttachLines.length ? aAttachLines.join(', ') : '';
+ };
+
+ /**
+ * @return {Object}
+ */
+ MessageModel.prototype.getDataForWindowPopup = function ()
+ {
+ return {
+ 'popupFrom': this.fromToLine(false),
+ 'popupTo': this.toToLine(false),
+ 'popupCc': this.ccToLine(false),
+ 'popupBcc': this.bccToLine(false),
+ 'popupSubject': this.subject(),
+ 'popupDate': this.fullFormatDateValue(),
+ 'popupAttachments': this.attachmentsToStringLine(),
+ 'popupBody': this.textBodyToString()
+ };
+ };
+
+ /**
+ * @param {boolean=} bPrint = false
+ */
+ MessageModel.prototype.viewPopupMessage = function (bPrint)
+ {
+ Utils.windowPopupKnockout(this.getDataForWindowPopup(), 'PopupsWindowSimpleMessage', this.subject(), function (oPopupWin) {
+ if (oPopupWin && oPopupWin.document && oPopupWin.document.body)
+ {
+ $('img.lazy', oPopupWin.document.body).each(function (iIndex, oImg) {
+
+ var
+ $oImg = $(oImg),
+ sOrig = $oImg.data('original'),
+ sSrc = $oImg.attr('src')
+ ;
+
+ if (0 <= iIndex && sOrig && !sSrc)
+ {
+ $oImg.attr('src', sOrig);
+ }
+ });
+
+ if (bPrint)
+ {
+ window.setTimeout(function () {
+ oPopupWin.print();
+ }, 100);
+ }
+ }
+ });
+ };
+
+ MessageModel.prototype.printMessage = function ()
+ {
+ this.viewPopupMessage(true);
+ };
+
+ /**
+ * @returns {string}
+ */
+ MessageModel.prototype.generateUid = function ()
+ {
+ return this.folderFullNameRaw + '/' + this.uid;
+ };
+
+ /**
+ * @param {MessageModel} oMessage
+ * @return {MessageModel}
+ */
+ MessageModel.prototype.populateByMessageListItem = function (oMessage)
+ {
+ this.folderFullNameRaw = oMessage.folderFullNameRaw;
+ this.uid = oMessage.uid;
+ this.hash = oMessage.hash;
+ this.requestHash = oMessage.requestHash;
+ this.subject(oMessage.subject());
+ this.subjectPrefix(this.subjectPrefix());
+ this.subjectSuffix(this.subjectSuffix());
+
+ this.size(oMessage.size());
+ this.dateTimeStampInUTC(oMessage.dateTimeStampInUTC());
+ this.priority(oMessage.priority());
+
+ this.proxy = oMessage.proxy;
+
+ this.fromEmailString(oMessage.fromEmailString());
+ this.fromClearEmailString(oMessage.fromClearEmailString());
+ this.toEmailsString(oMessage.toEmailsString());
+ this.toClearEmailsString(oMessage.toClearEmailsString());
+
+ this.emails = oMessage.emails;
+
+ this.from = oMessage.from;
+ this.to = oMessage.to;
+ this.cc = oMessage.cc;
+ this.bcc = oMessage.bcc;
+ this.replyTo = oMessage.replyTo;
+ this.deliveredTo = oMessage.deliveredTo;
+
+ this.unseen(oMessage.unseen());
+ this.flagged(oMessage.flagged());
+ this.answered(oMessage.answered());
+ this.forwarded(oMessage.forwarded());
+ this.isReadReceipt(oMessage.isReadReceipt());
+
+ this.selected(oMessage.selected());
+ this.checked(oMessage.checked());
+ this.hasAttachments(oMessage.hasAttachments());
+ this.attachmentsMainType(oMessage.attachmentsMainType());
+
+ this.moment(oMessage.moment());
+
+ this.body = null;
+
+ this.priority(Enums.MessagePriority.Normal);
+ this.aDraftInfo = [];
+ this.sMessageId = '';
+ this.sInReplyTo = '';
+ this.sReferences = '';
+
+ this.parentUid(oMessage.parentUid());
+ this.threads(oMessage.threads());
+ this.threadsLen(oMessage.threadsLen());
+
+ this.computeSenderEmail();
+
+ return this;
+ };
+
+ MessageModel.prototype.showExternalImages = function (bLazy)
+ {
+ if (this.body && this.body.data('rl-has-images'))
+ {
+ var sAttr = '';
+ bLazy = Utils.isUnd(bLazy) ? false : bLazy;
+
+ this.hasImages(false);
+ this.body.data('rl-has-images', false);
+
+ sAttr = this.proxy ? 'data-x-additional-src' : 'data-x-src';
+ $('[' + sAttr + ']', this.body).each(function () {
+ if (bLazy && $(this).is('img'))
+ {
+ $(this)
+ .addClass('lazy')
+ .attr('data-original', $(this).attr(sAttr))
+ .removeAttr(sAttr)
+ ;
+ }
+ else
+ {
+ $(this).attr('src', $(this).attr(sAttr)).removeAttr(sAttr);
+ }
+ });
+
+ sAttr = this.proxy ? 'data-x-additional-style-url' : 'data-x-style-url';
+ $('[' + sAttr + ']', this.body).each(function () {
+ var sStyle = Utils.trim($(this).attr('style'));
+ sStyle = '' === sStyle ? '' : (';' === sStyle.substr(-1) ? sStyle + ' ' : sStyle + '; ');
+ $(this).attr('style', sStyle + $(this).attr(sAttr)).removeAttr(sAttr);
+ });
+
+ if (bLazy)
+ {
+ $('img.lazy', this.body).addClass('lazy-inited').lazyload({
+ 'threshold' : 400,
+ 'effect' : 'fadeIn',
+ 'skip_invisible' : false,
+ 'container': $('.RL-MailMessageView .messageView .messageItem .content')[0]
+ });
+
+ $window.resize();
+ }
+
+ Utils.windowResize(500);
+ }
+ };
+
+ MessageModel.prototype.showInternalImages = function (bLazy)
+ {
+ if (this.body && !this.body.data('rl-init-internal-images'))
+ {
+ this.body.data('rl-init-internal-images', true);
+
+ bLazy = Utils.isUnd(bLazy) ? false : bLazy;
+
+ var self = this;
+
+ $('[data-x-src-cid]', this.body).each(function () {
+
+ var oAttachment = self.findAttachmentByCid($(this).attr('data-x-src-cid'));
+ if (oAttachment && oAttachment.download)
+ {
+ if (bLazy && $(this).is('img'))
+ {
+ $(this)
+ .addClass('lazy')
+ .attr('data-original', oAttachment.linkPreview());
+ }
+ else
+ {
+ $(this).attr('src', oAttachment.linkPreview());
+ }
+ }
+ });
+
+ $('[data-x-src-location]', this.body).each(function () {
+
+ var oAttachment = self.findAttachmentByContentLocation($(this).attr('data-x-src-location'));
+ if (!oAttachment)
+ {
+ oAttachment = self.findAttachmentByCid($(this).attr('data-x-src-location'));
+ }
+
+ if (oAttachment && oAttachment.download)
+ {
+ if (bLazy && $(this).is('img'))
+ {
+ $(this)
+ .addClass('lazy')
+ .attr('data-original', oAttachment.linkPreview());
+ }
+ else
+ {
+ $(this).attr('src', oAttachment.linkPreview());
+ }
+ }
+ });
+
+ $('[data-x-style-cid]', this.body).each(function () {
+
+ var
+ sStyle = '',
+ sName = '',
+ oAttachment = self.findAttachmentByCid($(this).attr('data-x-style-cid'))
+ ;
+
+ if (oAttachment && oAttachment.linkPreview)
+ {
+ sName = $(this).attr('data-x-style-cid-name');
+ if ('' !== sName)
+ {
+ sStyle = Utils.trim($(this).attr('style'));
+ sStyle = '' === sStyle ? '' : (';' === sStyle.substr(-1) ? sStyle + ' ' : sStyle + '; ');
+ $(this).attr('style', sStyle + sName + ': url(\'' + oAttachment.linkPreview() + '\')');
+ }
+ }
+ });
+
+ if (bLazy)
+ {
+ (function ($oImg, oContainer) {
+ _.delay(function () {
+ $oImg.addClass('lazy-inited').lazyload({
+ 'threshold' : 400,
+ 'effect' : 'fadeIn',
+ 'skip_invisible' : false,
+ 'container': oContainer
+ });
+ }, 300);
+ }($('img.lazy', self.body), $('.RL-MailMessageView .messageView .messageItem .content')[0]));
+ }
+
+ Utils.windowResize(500);
+ }
+ };
+
+ MessageModel.prototype.storeDataToDom = function ()
+ {
+ if (this.body)
+ {
+ this.body.data('rl-is-html', !!this.isHtml());
+ this.body.data('rl-has-images', !!this.hasImages());
+
+ this.body.data('rl-plain-raw', this.plainRaw);
+
+ if (Data.capaOpenPGP())
+ {
+ this.body.data('rl-plain-pgp-signed', !!this.isPgpSigned());
+ this.body.data('rl-plain-pgp-encrypted', !!this.isPgpEncrypted());
+ this.body.data('rl-pgp-verify-status', this.pgpSignedVerifyStatus());
+ this.body.data('rl-pgp-verify-user', this.pgpSignedVerifyUser());
+ }
+ }
+ };
+
+ MessageModel.prototype.storePgpVerifyDataToDom = function ()
+ {
+ if (this.body && Data.capaOpenPGP())
+ {
+ this.body.data('rl-pgp-verify-status', this.pgpSignedVerifyStatus());
+ this.body.data('rl-pgp-verify-user', this.pgpSignedVerifyUser());
+ }
+ };
+
+ MessageModel.prototype.fetchDataToDom = function ()
+ {
+ if (this.body)
+ {
+ this.isHtml(!!this.body.data('rl-is-html'));
+ this.hasImages(!!this.body.data('rl-has-images'));
+
+ this.plainRaw = Utils.pString(this.body.data('rl-plain-raw'));
+
+ if (Data.capaOpenPGP())
+ {
+ this.isPgpSigned(!!this.body.data('rl-plain-pgp-signed'));
+ this.isPgpEncrypted(!!this.body.data('rl-plain-pgp-encrypted'));
+ this.pgpSignedVerifyStatus(this.body.data('rl-pgp-verify-status'));
+ this.pgpSignedVerifyUser(this.body.data('rl-pgp-verify-user'));
+ }
+ else
+ {
+ this.isPgpSigned(false);
+ this.isPgpEncrypted(false);
+ this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.None);
+ this.pgpSignedVerifyUser('');
+ }
+ }
+ };
+
+ MessageModel.prototype.verifyPgpSignedClearMessage = function ()
+ {
+ if (this.isPgpSigned())
+ {
+ var
+ aRes = [],
+ mPgpMessage = null,
+ sFrom = this.from && this.from[0] && this.from[0].email ? this.from[0].email : '',
+ aPublicKeys = Data.findPublicKeysByEmail(sFrom),
+ oValidKey = null,
+ oValidSysKey = null,
+ sPlain = ''
+ ;
+
+ this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.Error);
+ this.pgpSignedVerifyUser('');
+
+ try
+ {
+ mPgpMessage = window.openpgp.cleartext.readArmored(this.plainRaw);
+ if (mPgpMessage && mPgpMessage.getText)
+ {
+ this.pgpSignedVerifyStatus(
+ aPublicKeys.length ? Enums.SignedVerifyStatus.Unverified : Enums.SignedVerifyStatus.UnknownPublicKeys);
+
+ aRes = mPgpMessage.verify(aPublicKeys);
+ if (aRes && 0 < aRes.length)
+ {
+ oValidKey = _.find(aRes, function (oItem) {
+ return oItem && oItem.keyid && oItem.valid;
+ });
+
+ if (oValidKey)
+ {
+ oValidSysKey = Data.findPublicKeyByHex(oValidKey.keyid.toHex());
+ if (oValidSysKey)
+ {
+ sPlain = mPgpMessage.getText();
+
+ this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.Success);
+ this.pgpSignedVerifyUser(oValidSysKey.user);
+
+ sPlain =
+ $div.empty().append(
+ $('').text(sPlain)
+ ).html()
+ ;
+
+ $div.empty();
+
+ this.replacePlaneTextBody(sPlain);
+ }
+ }
+ }
+ }
+ }
+ catch (oExc) {}
+
+ this.storePgpVerifyDataToDom();
+ }
+ };
+
+ MessageModel.prototype.decryptPgpEncryptedMessage = function (sPassword)
+ {
+ if (this.isPgpEncrypted())
+ {
+ var
+ aRes = [],
+ mPgpMessage = null,
+ mPgpMessageDecrypted = null,
+ sFrom = this.from && this.from[0] && this.from[0].email ? this.from[0].email : '',
+ aPublicKey = Data.findPublicKeysByEmail(sFrom),
+ oPrivateKey = Data.findSelfPrivateKey(sPassword),
+ oValidKey = null,
+ oValidSysKey = null,
+ sPlain = ''
+ ;
+
+ this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.Error);
+ this.pgpSignedVerifyUser('');
+
+ if (!oPrivateKey)
+ {
+ this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.UnknownPrivateKey);
+ }
+
+ try
+ {
+ mPgpMessage = window.openpgp.message.readArmored(this.plainRaw);
+ if (mPgpMessage && oPrivateKey && mPgpMessage.decrypt)
+ {
+ this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.Unverified);
+
+ mPgpMessageDecrypted = mPgpMessage.decrypt(oPrivateKey);
+ if (mPgpMessageDecrypted)
+ {
+ aRes = mPgpMessageDecrypted.verify(aPublicKey);
+ if (aRes && 0 < aRes.length)
+ {
+ oValidKey = _.find(aRes, function (oItem) {
+ return oItem && oItem.keyid && oItem.valid;
+ });
+
+ if (oValidKey)
+ {
+ oValidSysKey = Data.findPublicKeyByHex(oValidKey.keyid.toHex());
+ if (oValidSysKey)
+ {
+ this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.Success);
+ this.pgpSignedVerifyUser(oValidSysKey.user);
+ }
+ }
+ }
+
+ sPlain = mPgpMessageDecrypted.getText();
+
+ sPlain =
+ $div.empty().append(
+ $('').text(sPlain)
+ ).html()
+ ;
+
+ $div.empty();
+
+ this.replacePlaneTextBody(sPlain);
+ }
+ }
+ }
+ catch (oExc) {}
+
+ this.storePgpVerifyDataToDom();
+ }
+ };
+
+ MessageModel.prototype.replacePlaneTextBody = function (sPlain)
+ {
+ if (this.body)
+ {
+ this.body.html(sPlain).addClass('b-text-part plain');
+ }
+ };
+
+ /**
+ * @return {string}
+ */
+ MessageModel.prototype.flagHash = function ()
+ {
+ return [this.deleted(), this.unseen(), this.flagged(), this.answered(), this.forwarded(),
+ this.isReadReceipt()].join('');
+ };
+
+ module.exports = MessageModel;
+
+}(module));
+},{"../Common/Enums.js":7,"../Common/LinkBuilder.js":10,"../Common/Utils.js":14,"../External/$div.js":15,"../External/$window.js":18,"../External/jquery.js":26,"../External/ko.js":28,"../External/moment.js":29,"../External/underscore.js":31,"../External/window.js":32,"../Storages/WebMailDataStorage.js":67,"./AttachmentModel.js":38,"./EmailModel.js":39}],43:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ $ = require('../External/jquery.js'),
+ _ = require('../External/underscore.js'),
+ ko = require('../External/ko.js'),
+
+ Globals = require('../Common/Globals.js'),
+ Utils = require('../Common/Utils.js'),
+ LinkBuilder = require('../Common/LinkBuilder.js'),
+
+ kn = require('../Knoin/Knoin.js'),
+ KnoinAbstractScreen = require('../Knoin/KnoinAbstractScreen.js')
+ ;
+
+ /**
+ * @param {Array} aViewModels
+ * @constructor
+ * @extends KnoinAbstractScreen
+ */
+ function AbstractSettings(aViewModels)
+ {
+ KnoinAbstractScreen.call(this, 'settings', aViewModels);
+
+ this.menu = ko.observableArray([]);
+
+ this.oCurrentSubScreen = null;
+ this.oViewModelPlace = null;
+ }
+
+ _.extend(AbstractSettings.prototype, KnoinAbstractScreen.prototype);
+
+ AbstractSettings.prototype.onRoute = function (sSubName)
+ {
+ var
+ self = this,
+ oSettingsScreen = null,
+ RoutedSettingsViewModel = null,
+ oViewModelPlace = null,
oViewModelDom = null
;
- ViewModelClass.__builded = true;
- ViewModelClass.__vm = oViewModel;
- oViewModel.data = RL.data();
-
- oViewModel.viewModelName = ViewModelClass.__name;
-
- if (oViewModelPlace && 1 === oViewModelPlace.length)
- {
- oViewModelDom = $('').addClass('rl-view-model').addClass('RL-' + oViewModel.viewModelTemplate()).hide();
- oViewModelDom.appendTo(oViewModelPlace);
-
- oViewModel.viewModelDom = oViewModelDom;
- ViewModelClass.__dom = oViewModelDom;
-
- if ('Popups' === sPosition)
- {
- oViewModel.cancelCommand = oViewModel.closeCommand = Utils.createCommand(oViewModel, function () {
- kn.hideScreenPopup(ViewModelClass);
- });
-
- oViewModel.modalVisibility.subscribe(function (bValue) {
-
- var self = this;
- if (bValue)
- {
- this.viewModelDom.show();
- this.storeAndSetKeyScope();
-
- RL.popupVisibilityNames.push(this.viewModelName);
- oViewModel.viewModelDom.css('z-index', 3000 + RL.popupVisibilityNames().length + 10);
-
- Utils.delegateRun(this, 'onFocus', [], 500);
- }
- else
- {
- Utils.delegateRun(this, 'onHide');
- this.restoreKeyScope();
-
- RL.popupVisibilityNames.remove(this.viewModelName);
- oViewModel.viewModelDom.css('z-index', 2000);
-
- Globals.tooltipTrigger(!Globals.tooltipTrigger());
-
- _.delay(function () {
- self.viewModelDom.hide();
- }, 300);
- }
-
- }, oViewModel);
- }
-
- Plugins.runHook('view-model-pre-build', [ViewModelClass.__name, oViewModel, oViewModelDom]);
-
- ko.applyBindingAccessorsToNode(oViewModelDom[0], {
- 'i18nInit': true,
- 'template': function () { return {'name': oViewModel.viewModelTemplate()};}
- }, oViewModel);
-
- Utils.delegateRun(oViewModel, 'onBuild', [oViewModelDom]);
- if (oViewModel && 'Popups' === sPosition)
- {
- oViewModel.registerPopupKeyDown();
- }
-
- Plugins.runHook('view-model-post-build', [ViewModelClass.__name, oViewModel, oViewModelDom]);
- }
- else
- {
- Utils.log('Cannot find view model position: ' + sPosition);
- }
- }
-
- return ViewModelClass ? ViewModelClass.__vm : null;
-};
-
-/**
- * @param {Object} oViewModel
- * @param {Object} oViewModelDom
- */
-Knoin.prototype.applyExternal = function (oViewModel, oViewModelDom)
-{
- if (oViewModel && oViewModelDom)
- {
- ko.applyBindings(oViewModel, oViewModelDom);
- }
-};
-
-/**
- * @param {Function} ViewModelClassToHide
- */
-Knoin.prototype.hideScreenPopup = function (ViewModelClassToHide)
-{
- if (ViewModelClassToHide && ViewModelClassToHide.__vm && ViewModelClassToHide.__dom)
- {
- ViewModelClassToHide.__vm.modalVisibility(false);
- Plugins.runHook('view-model-on-hide', [ViewModelClassToHide.__name, ViewModelClassToHide.__vm]);
- }
-};
-
-/**
- * @param {Function} ViewModelClassToShow
- * @param {Array=} aParameters
- */
-Knoin.prototype.showScreenPopup = function (ViewModelClassToShow, aParameters)
-{
- if (ViewModelClassToShow)
- {
- this.buildViewModel(ViewModelClassToShow);
-
- if (ViewModelClassToShow.__vm && ViewModelClassToShow.__dom)
- {
- ViewModelClassToShow.__vm.modalVisibility(true);
- Utils.delegateRun(ViewModelClassToShow.__vm, 'onShow', aParameters || []);
- Plugins.runHook('view-model-on-show', [ViewModelClassToShow.__name, ViewModelClassToShow.__vm, aParameters || []]);
- }
- }
-};
-
-/**
- * @param {Function} ViewModelClassToShow
- * @return {boolean}
- */
-Knoin.prototype.isPopupVisible = function (ViewModelClassToShow)
-{
- return ViewModelClassToShow && ViewModelClassToShow.__vm ? ViewModelClassToShow.__vm.modalVisibility() : false;
-};
-
-/**
- * @param {string} sScreenName
- * @param {string} sSubPart
- */
-Knoin.prototype.screenOnRoute = function (sScreenName, sSubPart)
-{
- var
- self = this,
- oScreen = null,
- oCross = null
- ;
-
- if ('' === Utils.pString(sScreenName))
- {
- sScreenName = this.sDefaultScreenName;
- }
-
- if ('' !== sScreenName)
- {
- oScreen = this.screen(sScreenName);
- if (!oScreen)
- {
- oScreen = this.screen(this.sDefaultScreenName);
- if (oScreen)
- {
- sSubPart = sScreenName + '/' + sSubPart;
- sScreenName = this.sDefaultScreenName;
- }
- }
-
- if (oScreen && oScreen.__started)
- {
- if (!oScreen.__builded)
- {
- oScreen.__builded = true;
-
- if (Utils.isNonEmptyArray(oScreen.viewModels()))
- {
- _.each(oScreen.viewModels(), function (ViewModelClass) {
- this.buildViewModel(ViewModelClass, oScreen);
- }, this);
- }
-
- Utils.delegateRun(oScreen, 'onBuild');
- }
-
- _.defer(function () {
-
- // hide screen
- if (self.oCurrentScreen)
- {
- Utils.delegateRun(self.oCurrentScreen, 'onHide');
-
- if (Utils.isNonEmptyArray(self.oCurrentScreen.viewModels()))
- {
- _.each(self.oCurrentScreen.viewModels(), function (ViewModelClass) {
-
- if (ViewModelClass.__vm && ViewModelClass.__dom &&
- 'Popups' !== ViewModelClass.__vm.viewModelPosition())
- {
- ViewModelClass.__dom.hide();
- ViewModelClass.__vm.viewModelVisibility(false);
- Utils.delegateRun(ViewModelClass.__vm, 'onHide');
- }
-
- });
- }
- }
- // --
-
- self.oCurrentScreen = oScreen;
-
- // show screen
- if (self.oCurrentScreen)
- {
- Utils.delegateRun(self.oCurrentScreen, 'onShow');
-
- Plugins.runHook('screen-on-show', [self.oCurrentScreen.screenName(), self.oCurrentScreen]);
-
- if (Utils.isNonEmptyArray(self.oCurrentScreen.viewModels()))
- {
- _.each(self.oCurrentScreen.viewModels(), function (ViewModelClass) {
-
- if (ViewModelClass.__vm && ViewModelClass.__dom &&
- 'Popups' !== ViewModelClass.__vm.viewModelPosition())
- {
- ViewModelClass.__dom.show();
- ViewModelClass.__vm.viewModelVisibility(true);
- Utils.delegateRun(ViewModelClass.__vm, 'onShow');
- Utils.delegateRun(ViewModelClass.__vm, 'onFocus', [], 200);
-
- Plugins.runHook('view-model-on-show', [ViewModelClass.__name, ViewModelClass.__vm]);
- }
-
- }, self);
- }
- }
- // --
-
- oCross = oScreen.__cross();
- if (oCross)
- {
- oCross.parse(sSubPart);
- }
- });
- }
- }
-};
-
-/**
- * @param {Array} aScreensClasses
- */
-Knoin.prototype.startScreens = function (aScreensClasses)
-{
- $('#rl-content').css({
- 'visibility': 'hidden'
- });
-
- _.each(aScreensClasses, function (CScreen) {
-
- var
- oScreen = new CScreen(),
- sScreenName = oScreen ? oScreen.screenName() : ''
- ;
-
- if (oScreen && '' !== sScreenName)
- {
- if ('' === this.sDefaultScreenName)
- {
- this.sDefaultScreenName = sScreenName;
- }
-
- this.oScreens[sScreenName] = oScreen;
- }
-
- }, this);
-
-
- _.each(this.oScreens, function (oScreen) {
- if (oScreen && !oScreen.__started && oScreen.__start)
- {
- oScreen.__started = true;
- oScreen.__start();
-
- Plugins.runHook('screen-pre-start', [oScreen.screenName(), oScreen]);
- Utils.delegateRun(oScreen, 'onStart');
- Plugins.runHook('screen-post-start', [oScreen.screenName(), oScreen]);
- }
- }, this);
-
- var oCross = crossroads.create();
- oCross.addRoute(/^([a-zA-Z0-9\-]*)\/?(.*)$/, _.bind(this.screenOnRoute, this));
-
- hasher.initialized.add(oCross.parse, oCross);
- hasher.changed.add(oCross.parse, oCross);
- hasher.init();
-
- $('#rl-content').css({
- 'visibility': 'visible'
- });
-
- _.delay(function () {
- $html.removeClass('rl-started-trigger').addClass('rl-started');
- }, 50);
-};
-
-/**
- * @param {string} sHash
- * @param {boolean=} bSilence = false
- * @param {boolean=} bReplace = false
- */
-Knoin.prototype.setHash = function (sHash, bSilence, bReplace)
-{
- sHash = '#' === sHash.substr(0, 1) ? sHash.substr(1) : sHash;
- sHash = '/' === sHash.substr(0, 1) ? sHash.substr(1) : sHash;
-
- bReplace = Utils.isUnd(bReplace) ? false : !!bReplace;
-
- if (Utils.isUnd(bSilence) ? false : !!bSilence)
- {
- hasher.changed.active = false;
- hasher[bReplace ? 'replaceHash' : 'setHash'](sHash);
- hasher.changed.active = true;
- }
- else
- {
- hasher.changed.active = true;
- hasher[bReplace ? 'replaceHash' : 'setHash'](sHash);
- hasher.setHash(sHash);
- }
-};
-
-/**
- * @return {Knoin}
- */
-Knoin.prototype.bootstart = function ()
-{
- if (this.oBoot && this.oBoot.bootstart)
- {
- this.oBoot.bootstart();
- }
-
- return this;
-};
-
-kn = new Knoin();
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @param {string=} sEmail
- * @param {string=} sName
- *
- * @constructor
- */
-function EmailModel(sEmail, sName)
-{
- this.email = sEmail || '';
- this.name = sName || '';
- this.privateType = null;
-
- this.clearDuplicateName();
-}
-
-/**
- * @static
- * @param {AjaxJsonEmail} oJsonEmail
- * @return {?EmailModel}
- */
-EmailModel.newInstanceFromJson = function (oJsonEmail)
-{
- var oEmailModel = new EmailModel();
- return oEmailModel.initByJson(oJsonEmail) ? oEmailModel : null;
-};
-
-/**
- * @type {string}
- */
-EmailModel.prototype.name = '';
-
-/**
- * @type {string}
- */
-EmailModel.prototype.email = '';
-
-/**
- * @type {(number|null)}
- */
-EmailModel.prototype.privateType = null;
-
-EmailModel.prototype.clear = function ()
-{
- this.email = '';
- this.name = '';
- this.privateType = null;
-};
-
-/**
- * @returns {boolean}
- */
-EmailModel.prototype.validate = function ()
-{
- return '' !== this.name || '' !== this.email;
-};
-
-/**
- * @param {boolean} bWithoutName = false
- * @return {string}
- */
-EmailModel.prototype.hash = function (bWithoutName)
-{
- return '#' + (bWithoutName ? '' : this.name) + '#' + this.email + '#';
-};
-
-EmailModel.prototype.clearDuplicateName = function ()
-{
- if (this.name === this.email)
- {
- this.name = '';
- }
-};
-
-/**
- * @return {number}
- */
-EmailModel.prototype.type = function ()
-{
- if (null === this.privateType)
- {
- if (this.email && '@facebook.com' === this.email.substr(-13))
- {
- this.privateType = Enums.EmailType.Facebook;
- }
-
- if (null === this.privateType)
- {
- this.privateType = Enums.EmailType.Default;
- }
- }
-
- return this.privateType;
-};
-
-/**
- * @param {string} sQuery
- * @return {boolean}
- */
-EmailModel.prototype.search = function (sQuery)
-{
- return -1 < (this.name + ' ' + this.email).toLowerCase().indexOf(sQuery.toLowerCase());
-};
-
-/**
- * @param {string} sString
- */
-EmailModel.prototype.parse = function (sString)
-{
- this.clear();
-
- sString = Utils.trim(sString);
-
- var
- mRegex = /(?:"([^"]+)")? ?(.*?@[^>,]+)>?,? ?/g,
- mMatch = mRegex.exec(sString)
- ;
-
- if (mMatch)
- {
- this.name = mMatch[1] || '';
- this.email = mMatch[2] || '';
-
- this.clearDuplicateName();
- }
- else if ((/^[^@]+@[^@]+$/).test(sString))
- {
- this.name = '';
- this.email = sString;
- }
-};
-
-/**
- * @param {AjaxJsonEmail} oJsonEmail
- * @return {boolean}
- */
-EmailModel.prototype.initByJson = function (oJsonEmail)
-{
- var bResult = false;
- if (oJsonEmail && 'Object/Email' === oJsonEmail['@Object'])
- {
- this.name = Utils.trim(oJsonEmail.Name);
- this.email = Utils.trim(oJsonEmail.Email);
-
- bResult = '' !== this.email;
- this.clearDuplicateName();
- }
-
- return bResult;
-};
-
-/**
- * @param {boolean} bFriendlyView
- * @param {boolean=} bWrapWithLink = false
- * @param {boolean=} bEncodeHtml = false
- * @return {string}
- */
-EmailModel.prototype.toLine = function (bFriendlyView, bWrapWithLink, bEncodeHtml)
-{
- var sResult = '';
- if ('' !== this.email)
- {
- bWrapWithLink = Utils.isUnd(bWrapWithLink) ? false : !!bWrapWithLink;
- bEncodeHtml = Utils.isUnd(bEncodeHtml) ? false : !!bEncodeHtml;
-
- if (bFriendlyView && '' !== this.name)
- {
- sResult = bWrapWithLink ? '') +
- '" target="_blank" tabindex="-1">' + Utils.encodeHtml(this.name) + '' :
- (bEncodeHtml ? Utils.encodeHtml(this.name) : this.name);
- }
- else
- {
- sResult = this.email;
- if ('' !== this.name)
- {
- if (bWrapWithLink)
- {
- sResult = Utils.encodeHtml('"' + this.name + '" <') +
- '') + '" target="_blank" tabindex="-1">' + Utils.encodeHtml(sResult) + '' + Utils.encodeHtml('>');
- }
- else
- {
- sResult = '"' + this.name + '" <' + sResult + '>';
- if (bEncodeHtml)
- {
- sResult = Utils.encodeHtml(sResult);
- }
- }
- }
- else if (bWrapWithLink)
- {
- sResult = '' + Utils.encodeHtml(this.email) + '';
- }
- }
- }
-
- return sResult;
-};
-
-/**
- * @param {string} $sEmailAddress
- * @return {boolean}
- */
-EmailModel.prototype.mailsoParse = function ($sEmailAddress)
-{
- $sEmailAddress = Utils.trim($sEmailAddress);
- if ('' === $sEmailAddress)
- {
- return false;
- }
-
- var
- substr = function (str, start, len) {
- str += '';
- var end = str.length;
-
- if (start < 0) {
- start += end;
- }
-
- end = typeof len === 'undefined' ? end : (len < 0 ? len + end : len + start);
-
- return start >= str.length || start < 0 || start > end ? false : str.slice(start, end);
- },
-
- substr_replace = function (str, replace, start, length) {
- if (start < 0) {
- start = start + str.length;
- }
- length = length !== undefined ? length : str.length;
- if (length < 0) {
- length = length + str.length - start;
- }
- return str.slice(0, start) + replace.substr(0, length) + replace.slice(length) + str.slice(start + length);
- },
-
- $sName = '',
- $sEmail = '',
- $sComment = '',
-
- $bInName = false,
- $bInAddress = false,
- $bInComment = false,
-
- $aRegs = null,
-
- $iStartIndex = 0,
- $iEndIndex = 0,
- $iCurrentIndex = 0
- ;
-
- while ($iCurrentIndex < $sEmailAddress.length)
- {
- switch ($sEmailAddress.substr($iCurrentIndex, 1))
- {
- case '"':
- if ((!$bInName) && (!$bInAddress) && (!$bInComment))
- {
- $bInName = true;
- $iStartIndex = $iCurrentIndex;
- }
- else if ((!$bInAddress) && (!$bInComment))
- {
- $iEndIndex = $iCurrentIndex;
- $sName = substr($sEmailAddress, $iStartIndex + 1, $iEndIndex - $iStartIndex - 1);
- $sEmailAddress = substr_replace($sEmailAddress, '', $iStartIndex, $iEndIndex - $iStartIndex + 1);
- $iEndIndex = 0;
- $iCurrentIndex = 0;
- $iStartIndex = 0;
- $bInName = false;
- }
- break;
- case '<':
- if ((!$bInName) && (!$bInAddress) && (!$bInComment))
- {
- if ($iCurrentIndex > 0 && $sName.length === 0)
- {
- $sName = substr($sEmailAddress, 0, $iCurrentIndex);
- }
-
- $bInAddress = true;
- $iStartIndex = $iCurrentIndex;
- }
- break;
- case '>':
- if ($bInAddress)
- {
- $iEndIndex = $iCurrentIndex;
- $sEmail = substr($sEmailAddress, $iStartIndex + 1, $iEndIndex - $iStartIndex - 1);
- $sEmailAddress = substr_replace($sEmailAddress, '', $iStartIndex, $iEndIndex - $iStartIndex + 1);
- $iEndIndex = 0;
- $iCurrentIndex = 0;
- $iStartIndex = 0;
- $bInAddress = false;
- }
- break;
- case '(':
- if ((!$bInName) && (!$bInAddress) && (!$bInComment))
- {
- $bInComment = true;
- $iStartIndex = $iCurrentIndex;
- }
- break;
- case ')':
- if ($bInComment)
- {
- $iEndIndex = $iCurrentIndex;
- $sComment = substr($sEmailAddress, $iStartIndex + 1, $iEndIndex - $iStartIndex - 1);
- $sEmailAddress = substr_replace($sEmailAddress, '', $iStartIndex, $iEndIndex - $iStartIndex + 1);
- $iEndIndex = 0;
- $iCurrentIndex = 0;
- $iStartIndex = 0;
- $bInComment = false;
- }
- break;
- case '\\':
- $iCurrentIndex++;
- break;
- }
-
- $iCurrentIndex++;
- }
-
- if ($sEmail.length === 0)
- {
- $aRegs = $sEmailAddress.match(/[^@\s]+@\S+/i);
- if ($aRegs && $aRegs[0])
- {
- $sEmail = $aRegs[0];
- }
- else
- {
- $sName = $sEmailAddress;
- }
- }
-
- if ($sEmail.length > 0 && $sName.length === 0 && $sComment.length === 0)
- {
- $sName = $sEmailAddress.replace($sEmail, '');
- }
-
- $sEmail = Utils.trim($sEmail).replace(/^[<]+/, '').replace(/[>]+$/, '');
- $sName = Utils.trim($sName).replace(/^["']+/, '').replace(/["']+$/, '');
- $sComment = Utils.trim($sComment).replace(/^[(]+/, '').replace(/[)]+$/, '');
-
- // Remove backslash
- $sName = $sName.replace(/\\\\(.)/, '$1');
- $sComment = $sComment.replace(/\\\\(.)/, '$1');
-
- this.name = $sName;
- this.email = $sEmail;
-
- this.clearDuplicateName();
- return true;
-};
-
-/**
- * @return {string}
- */
-EmailModel.prototype.inputoTagLine = function ()
-{
- return 0 < this.name.length ? this.name + ' (' + this.email + ')' : this.email;
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function ContactModel()
-{
- this.idContact = 0;
- this.display = '';
- this.properties = [];
- this.tags = '';
- this.readOnly = false;
-
- this.focused = ko.observable(false);
- this.selected = ko.observable(false);
- this.checked = ko.observable(false);
- this.deleted = ko.observable(false);
-}
-
-/**
- * @return {Array|null}
- */
-ContactModel.prototype.getNameAndEmailHelper = function ()
-{
- var
- sName = '',
- sEmail = ''
- ;
-
- if (Utils.isNonEmptyArray(this.properties))
- {
- _.each(this.properties, function (aProperty) {
- if (aProperty)
- {
- if (Enums.ContactPropertyType.FirstName === aProperty[0])
- {
- sName = Utils.trim(aProperty[1] + ' ' + sName);
- }
- else if (Enums.ContactPropertyType.LastName === aProperty[0])
- {
- sName = Utils.trim(sName + ' ' + aProperty[1]);
- }
- else if ('' === sEmail && Enums.ContactPropertyType.Email === aProperty[0])
- {
- sEmail = aProperty[1];
- }
- }
- }, this);
- }
-
- return '' === sEmail ? null : [sEmail, sName];
-};
-
-ContactModel.prototype.parse = function (oItem)
-{
- var bResult = false;
- if (oItem && 'Object/Contact' === oItem['@Object'])
- {
- this.idContact = Utils.pInt(oItem['IdContact']);
- this.display = Utils.pString(oItem['Display']);
- this.readOnly = !!oItem['ReadOnly'];
- this.tags = '';
-
- if (Utils.isNonEmptyArray(oItem['Properties']))
- {
- _.each(oItem['Properties'], function (oProperty) {
- if (oProperty && oProperty['Type'] && Utils.isNormal(oProperty['Value']) && Utils.isNormal(oProperty['TypeStr']))
- {
- this.properties.push([Utils.pInt(oProperty['Type']), Utils.pString(oProperty['Value']), Utils.pString(oProperty['TypeStr'])]);
- }
- }, this);
- }
-
- if (Utils.isNonEmptyArray(oItem['Tags']))
- {
- this.tags = oItem['Tags'].join(',');
- }
-
- bResult = true;
- }
-
- return bResult;
-};
-
-/**
- * @return {string}
- */
-ContactModel.prototype.srcAttr = function ()
-{
- return RL.link().emptyContactPic();
-};
-
-/**
- * @return {string}
- */
-ContactModel.prototype.generateUid = function ()
-{
- return '' + this.idContact;
-};
-
-/**
- * @return string
- */
-ContactModel.prototype.lineAsCcc = function ()
-{
- var aResult = [];
- if (this.deleted())
- {
- aResult.push('deleted');
- }
- if (this.selected())
- {
- aResult.push('selected');
- }
- if (this.checked())
- {
- aResult.push('checked');
- }
- if (this.focused())
- {
- aResult.push('focused');
- }
-
- return aResult.join(' ');
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @param {number=} iType = Enums.ContactPropertyType.Unknown
- * @param {string=} sTypeStr = ''
- * @param {string=} sValue = ''
- * @param {boolean=} bFocused = false
- * @param {string=} sPlaceholder = ''
- *
- * @constructor
- */
-function ContactPropertyModel(iType, sTypeStr, sValue, bFocused, sPlaceholder)
-{
- this.type = ko.observable(Utils.isUnd(iType) ? Enums.ContactPropertyType.Unknown : iType);
- this.typeStr = ko.observable(Utils.isUnd(sTypeStr) ? '' : sTypeStr);
- this.focused = ko.observable(Utils.isUnd(bFocused) ? false : !!bFocused);
- this.value = ko.observable(Utils.pString(sValue));
-
- this.placeholder = ko.observable(sPlaceholder || '');
-
- this.placeholderValue = ko.computed(function () {
- var sPlaceholder = this.placeholder();
- return sPlaceholder ? Utils.i18n(sPlaceholder) : '';
- }, this);
-
- this.largeValue = ko.computed(function () {
- return Enums.ContactPropertyType.Note === this.type();
- }, this);
-
-}
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function ContactTagModel()
-{
- this.idContactTag = 0;
- this.name = ko.observable('');
- this.readOnly = false;
-}
-
-ContactTagModel.prototype.parse = function (oItem)
-{
- var bResult = false;
- if (oItem && 'Object/Tag' === oItem['@Object'])
- {
- this.idContact = Utils.pInt(oItem['IdContactTag']);
- this.name(Utils.pString(oItem['Name']));
- this.readOnly = !!oItem['ReadOnly'];
-
- bResult = true;
- }
-
- return bResult;
-};
-
-/**
- * @param {string} sSearch
- * @return {boolean}
- */
-ContactTagModel.prototype.filterHelper = function (sSearch)
-{
- return this.name().toLowerCase().indexOf(sSearch.toLowerCase()) !== -1;
-};
-
-/**
- * @param {boolean=} bEncodeHtml = false
- * @return {string}
- */
-ContactTagModel.prototype.toLine = function (bEncodeHtml)
-{
- return (Utils.isUnd(bEncodeHtml) ? false : !!bEncodeHtml) ?
- Utils.encodeHtml(this.name()) : this.name();
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function AttachmentModel()
-{
- this.mimeType = '';
- this.fileName = '';
- this.estimatedSize = 0;
- this.friendlySize = '';
- this.isInline = false;
- this.isLinked = false;
- this.cid = '';
- this.cidWithOutTags = '';
- this.contentLocation = '';
- this.download = '';
- this.folder = '';
- this.uid = '';
- this.mimeIndex = '';
-}
-
-/**
- * @static
- * @param {AjaxJsonAttachment} oJsonAttachment
- * @return {?AttachmentModel}
- */
-AttachmentModel.newInstanceFromJson = function (oJsonAttachment)
-{
- var oAttachmentModel = new AttachmentModel();
- return oAttachmentModel.initByJson(oJsonAttachment) ? oAttachmentModel : null;
-};
-
-AttachmentModel.prototype.mimeType = '';
-AttachmentModel.prototype.fileName = '';
-AttachmentModel.prototype.estimatedSize = 0;
-AttachmentModel.prototype.friendlySize = '';
-AttachmentModel.prototype.isInline = false;
-AttachmentModel.prototype.isLinked = false;
-AttachmentModel.prototype.cid = '';
-AttachmentModel.prototype.cidWithOutTags = '';
-AttachmentModel.prototype.contentLocation = '';
-AttachmentModel.prototype.download = '';
-AttachmentModel.prototype.folder = '';
-AttachmentModel.prototype.uid = '';
-AttachmentModel.prototype.mimeIndex = '';
-
-/**
- * @param {AjaxJsonAttachment} oJsonAttachment
- */
-AttachmentModel.prototype.initByJson = function (oJsonAttachment)
-{
- var bResult = false;
- if (oJsonAttachment && 'Object/Attachment' === oJsonAttachment['@Object'])
- {
- this.mimeType = (oJsonAttachment.MimeType || '').toLowerCase();
- this.fileName = oJsonAttachment.FileName;
- this.estimatedSize = Utils.pInt(oJsonAttachment.EstimatedSize);
- this.isInline = !!oJsonAttachment.IsInline;
- this.isLinked = !!oJsonAttachment.IsLinked;
- this.cid = oJsonAttachment.CID;
- this.contentLocation = oJsonAttachment.ContentLocation;
- this.download = oJsonAttachment.Download;
-
- this.folder = oJsonAttachment.Folder;
- this.uid = oJsonAttachment.Uid;
- this.mimeIndex = oJsonAttachment.MimeIndex;
-
- this.friendlySize = Utils.friendlySize(this.estimatedSize);
- this.cidWithOutTags = this.cid.replace(/^<+/, '').replace(/>+$/, '');
-
- bResult = true;
- }
-
- return bResult;
-};
-
-/**
- * @return {boolean}
- */
-AttachmentModel.prototype.isImage = function ()
-{
- return -1 < Utils.inArray(this.mimeType.toLowerCase(),
- ['image/png', 'image/jpg', 'image/jpeg', 'image/gif']
- );
-};
-
-/**
- * @return {boolean}
- */
-AttachmentModel.prototype.isText = function ()
-{
- return 'text/' === this.mimeType.substr(0, 5) &&
- -1 === Utils.inArray(this.mimeType, ['text/html']);
-};
-
-/**
- * @return {boolean}
- */
-AttachmentModel.prototype.isPdf = function ()
-{
- return Globals.bAllowPdfPreview && 'application/pdf' === this.mimeType;
-};
-
-/**
- * @return {string}
- */
-AttachmentModel.prototype.linkDownload = function ()
-{
- return RL.link().attachmentDownload(this.download);
-};
-
-/**
- * @return {string}
- */
-AttachmentModel.prototype.linkPreview = function ()
-{
- return RL.link().attachmentPreview(this.download);
-};
-
-/**
- * @return {string}
- */
-AttachmentModel.prototype.linkPreviewAsPlain = function ()
-{
- return RL.link().attachmentPreviewAsPlain(this.download);
-};
-
-/**
- * @return {string}
- */
-AttachmentModel.prototype.generateTransferDownloadUrl = function ()
-{
- var sLink = this.linkDownload();
- if ('http' !== sLink.substr(0, 4))
- {
- sLink = window.location.protocol + '//' + window.location.host + window.location.pathname + sLink;
- }
-
- return this.mimeType + ':' + this.fileName + ':' + sLink;
-};
-
-/**
- * @param {AttachmentModel} oAttachment
- * @param {*} oEvent
- * @return {boolean}
- */
-AttachmentModel.prototype.eventDragStart = function (oAttachment, oEvent)
-{
- var oLocalEvent = oEvent.originalEvent || oEvent;
- if (oAttachment && oLocalEvent && oLocalEvent.dataTransfer && oLocalEvent.dataTransfer.setData)
- {
- oLocalEvent.dataTransfer.setData('DownloadURL', this.generateTransferDownloadUrl());
- }
-
- return true;
-};
-
-AttachmentModel.prototype.iconClass = function ()
-{
- var
- aParts = this.mimeType.toLocaleString().split('/'),
- sClass = 'icon-file'
- ;
-
- if (aParts && aParts[1])
- {
- if ('image' === aParts[0])
- {
- sClass = 'icon-file-image';
- }
- else if ('text' === aParts[0])
- {
- sClass = 'icon-file-text';
- }
- else if ('audio' === aParts[0])
- {
- sClass = 'icon-file-music';
- }
- else if ('video' === aParts[0])
- {
- sClass = 'icon-file-movie';
- }
- else if (-1 < Utils.inArray(aParts[1],
- ['zip', '7z', 'tar', 'rar', 'gzip', 'bzip', 'bzip2', 'x-zip', 'x-7z', 'x-rar', 'x-tar', 'x-gzip', 'x-bzip', 'x-bzip2', 'x-zip-compressed', 'x-7z-compressed', 'x-rar-compressed']))
- {
- sClass = 'icon-file-zip';
- }
-// else if (-1 < Utils.inArray(aParts[1],
-// ['pdf', 'x-pdf']))
-// {
-// sClass = 'icon-file-pdf';
-// }
-// else if (-1 < Utils.inArray(aParts[1], [
-// 'exe', 'x-exe', 'x-winexe', 'bat'
-// ]))
-// {
-// sClass = 'icon-console';
-// }
- else if (-1 < Utils.inArray(aParts[1], [
- 'rtf', 'msword', 'vnd.msword', 'vnd.openxmlformats-officedocument.wordprocessingml.document',
- 'vnd.openxmlformats-officedocument.wordprocessingml.template',
- 'vnd.ms-word.document.macroEnabled.12',
- 'vnd.ms-word.template.macroEnabled.12'
- ]))
- {
- sClass = 'icon-file-text';
- }
- else if (-1 < Utils.inArray(aParts[1], [
- 'excel', 'ms-excel', 'vnd.ms-excel',
- 'vnd.openxmlformats-officedocument.spreadsheetml.sheet',
- 'vnd.openxmlformats-officedocument.spreadsheetml.template',
- 'vnd.ms-excel.sheet.macroEnabled.12',
- 'vnd.ms-excel.template.macroEnabled.12',
- 'vnd.ms-excel.addin.macroEnabled.12',
- 'vnd.ms-excel.sheet.binary.macroEnabled.12'
- ]))
- {
- sClass = 'icon-file-excel';
- }
- else if (-1 < Utils.inArray(aParts[1], [
- 'powerpoint', 'ms-powerpoint', 'vnd.ms-powerpoint',
- 'vnd.openxmlformats-officedocument.presentationml.presentation',
- 'vnd.openxmlformats-officedocument.presentationml.template',
- 'vnd.openxmlformats-officedocument.presentationml.slideshow',
- 'vnd.ms-powerpoint.addin.macroEnabled.12',
- 'vnd.ms-powerpoint.presentation.macroEnabled.12',
- 'vnd.ms-powerpoint.template.macroEnabled.12',
- 'vnd.ms-powerpoint.slideshow.macroEnabled.12'
- ]))
- {
- sClass = 'icon-file-chart-graph';
- }
- }
-
- return sClass;
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @param {string} sId
- * @param {string} sFileName
- * @param {?number=} nSize
- * @param {boolean=} bInline
- * @param {boolean=} bLinked
- * @param {string=} sCID
- * @param {string=} sContentLocation
- */
-function ComposeAttachmentModel(sId, sFileName, nSize, bInline, bLinked, sCID, sContentLocation)
-{
- this.id = sId;
- this.isInline = Utils.isUnd(bInline) ? false : !!bInline;
- this.isLinked = Utils.isUnd(bLinked) ? false : !!bLinked;
- this.CID = Utils.isUnd(sCID) ? '' : sCID;
- this.contentLocation = Utils.isUnd(sContentLocation) ? '' : sContentLocation;
- this.fromMessage = false;
-
- this.fileName = ko.observable(sFileName);
- this.size = ko.observable(Utils.isUnd(nSize) ? null : nSize);
- this.tempName = ko.observable('');
-
- this.progress = ko.observable('');
- this.error = ko.observable('');
- this.waiting = ko.observable(true);
- this.uploading = ko.observable(false);
- this.enabled = ko.observable(true);
-
- this.friendlySize = ko.computed(function () {
- var mSize = this.size();
- return null === mSize ? '' : Utils.friendlySize(this.size());
- }, this);
-}
-
-ComposeAttachmentModel.prototype.id = '';
-ComposeAttachmentModel.prototype.isInline = false;
-ComposeAttachmentModel.prototype.isLinked = false;
-ComposeAttachmentModel.prototype.CID = '';
-ComposeAttachmentModel.prototype.contentLocation = '';
-ComposeAttachmentModel.prototype.fromMessage = false;
-ComposeAttachmentModel.prototype.cancel = Utils.emptyFunction;
-
-/**
- * @param {AjaxJsonComposeAttachment} oJsonAttachment
- */
-ComposeAttachmentModel.prototype.initByUploadJson = function (oJsonAttachment)
-{
- var bResult = false;
- if (oJsonAttachment)
- {
- this.fileName(oJsonAttachment.Name);
- this.size(Utils.isUnd(oJsonAttachment.Size) ? 0 : Utils.pInt(oJsonAttachment.Size));
- this.tempName(Utils.isUnd(oJsonAttachment.TempName) ? '' : oJsonAttachment.TempName);
- this.isInline = false;
-
- bResult = true;
- }
-
- return bResult;
-};
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function MessageModel()
-{
- this.folderFullNameRaw = '';
- this.uid = '';
- this.hash = '';
- this.requestHash = '';
- this.subject = ko.observable('');
- this.subjectPrefix = ko.observable('');
- this.subjectSuffix = ko.observable('');
- this.size = ko.observable(0);
- this.dateTimeStampInUTC = ko.observable(0);
- this.priority = ko.observable(Enums.MessagePriority.Normal);
-
- this.proxy = false;
-
- this.fromEmailString = ko.observable('');
- this.fromClearEmailString = ko.observable('');
- this.toEmailsString = ko.observable('');
- this.toClearEmailsString = ko.observable('');
-
- this.senderEmailsString = ko.observable('');
- this.senderClearEmailsString = ko.observable('');
-
- this.emails = [];
-
- this.from = [];
- this.to = [];
- this.cc = [];
- this.bcc = [];
- this.replyTo = [];
- this.deliveredTo = [];
-
- this.newForAnimation = ko.observable(false);
-
- this.deleted = ko.observable(false);
- this.unseen = ko.observable(false);
- this.flagged = ko.observable(false);
- this.answered = ko.observable(false);
- this.forwarded = ko.observable(false);
- this.isReadReceipt = ko.observable(false);
-
- this.focused = ko.observable(false);
- this.selected = ko.observable(false);
- this.checked = ko.observable(false);
- this.hasAttachments = ko.observable(false);
- this.attachmentsMainType = ko.observable('');
-
- this.moment = ko.observable(moment(moment.unix(0)));
-
- this.attachmentIconClass = ko.computed(function () {
- var sClass = '';
- if (this.hasAttachments())
- {
- sClass = 'icon-attachment';
- switch (this.attachmentsMainType())
- {
- case 'image':
- sClass = 'icon-image';
- break;
- case 'archive':
- sClass = 'icon-file-zip';
- break;
- case 'doc':
- sClass = 'icon-file-text';
- break;
-// case 'pdf':
-// sClass = 'icon-file-pdf';
-// break;
- }
- }
- return sClass;
- }, this);
-
- this.fullFormatDateValue = ko.computed(function () {
- return MessageModel.calculateFullFromatDateValue(this.dateTimeStampInUTC());
- }, this);
-
- this.momentDate = Utils.createMomentDate(this);
- this.momentShortDate = Utils.createMomentShortDate(this);
-
- this.dateTimeStampInUTC.subscribe(function (iValue) {
- var iNow = moment().unix();
- this.moment(moment.unix(iNow < iValue ? iNow : iValue));
- }, this);
-
- this.body = null;
- this.plainRaw = '';
- this.isHtml = ko.observable(false);
- this.hasImages = ko.observable(false);
- this.attachments = ko.observableArray([]);
-
- this.isPgpSigned = ko.observable(false);
- this.isPgpEncrypted = ko.observable(false);
- this.pgpSignedVerifyStatus = ko.observable(Enums.SignedVerifyStatus.None);
- this.pgpSignedVerifyUser = ko.observable('');
-
- this.priority = ko.observable(Enums.MessagePriority.Normal);
- this.readReceipt = ko.observable('');
-
- this.aDraftInfo = [];
- this.sMessageId = '';
- this.sInReplyTo = '';
- this.sReferences = '';
-
- this.parentUid = ko.observable(0);
- this.threads = ko.observableArray([]);
- this.threadsLen = ko.observable(0);
- this.hasUnseenSubMessage = ko.observable(false);
- this.hasFlaggedSubMessage = ko.observable(false);
-
- this.lastInCollapsedThread = ko.observable(false);
- this.lastInCollapsedThreadLoading = ko.observable(false);
-
- this.threadsLenResult = ko.computed(function () {
- var iCount = this.threadsLen();
- return 0 === this.parentUid() && 0 < iCount ? iCount + 1 : '';
- }, this);
-}
-
-/**
- * @static
- * @param {AjaxJsonMessage} oJsonMessage
- * @return {?MessageModel}
- */
-MessageModel.newInstanceFromJson = function (oJsonMessage)
-{
- var oMessageModel = new MessageModel();
- return oMessageModel.initByJson(oJsonMessage) ? oMessageModel : null;
-};
-
-/**
- * @static
- * @param {number} iTimeStampInUTC
- * @return {string}
- */
-MessageModel.calculateFullFromatDateValue = function (iTimeStampInUTC)
-{
- return 0 < iTimeStampInUTC ? moment.unix(iTimeStampInUTC).format('LLL') : '';
-};
-
-/**
- * @static
- * @param {Array} aEmail
- * @param {boolean=} bFriendlyView
- * @param {boolean=} bWrapWithLink = false
- * @return {string}
- */
-MessageModel.emailsToLine = function (aEmail, bFriendlyView, bWrapWithLink)
-{
- var
- aResult = [],
- iIndex = 0,
- iLen = 0
- ;
-
- if (Utils.isNonEmptyArray(aEmail))
- {
- for (iIndex = 0, iLen = aEmail.length; iIndex < iLen; iIndex++)
- {
- aResult.push(aEmail[iIndex].toLine(bFriendlyView, bWrapWithLink));
- }
- }
-
- return aResult.join(', ');
-};
-
-/**
- * @static
- * @param {Array} aEmail
- * @return {string}
- */
-MessageModel.emailsToLineClear = function (aEmail)
-{
- var
- aResult = [],
- iIndex = 0,
- iLen = 0
- ;
-
- if (Utils.isNonEmptyArray(aEmail))
- {
- for (iIndex = 0, iLen = aEmail.length; iIndex < iLen; iIndex++)
- {
- if (aEmail[iIndex] && aEmail[iIndex].email && '' !== aEmail[iIndex].name)
- {
- aResult.push(aEmail[iIndex].email);
- }
- }
- }
-
- return aResult.join(', ');
-};
-
-/**
- * @static
- * @param {?Array} aJsonEmails
- * @return {Array.}
- */
-MessageModel.initEmailsFromJson = function (aJsonEmails)
-{
- var
- iIndex = 0,
- iLen = 0,
- oEmailModel = null,
- aResult = []
- ;
-
- if (Utils.isNonEmptyArray(aJsonEmails))
- {
- for (iIndex = 0, iLen = aJsonEmails.length; iIndex < iLen; iIndex++)
- {
- oEmailModel = EmailModel.newInstanceFromJson(aJsonEmails[iIndex]);
- if (oEmailModel)
- {
- aResult.push(oEmailModel);
- }
- }
- }
-
- return aResult;
-};
-
-/**
- * @static
- * @param {Array.} aMessageEmails
- * @param {Object} oLocalUnic
- * @param {Array} aLocalEmails
- */
-MessageModel.replyHelper = function (aMessageEmails, oLocalUnic, aLocalEmails)
-{
- if (aMessageEmails && 0 < aMessageEmails.length)
- {
- var
- iIndex = 0,
- iLen = aMessageEmails.length
- ;
-
- for (; iIndex < iLen; iIndex++)
- {
- if (Utils.isUnd(oLocalUnic[aMessageEmails[iIndex].email]))
- {
- oLocalUnic[aMessageEmails[iIndex].email] = true;
- aLocalEmails.push(aMessageEmails[iIndex]);
- }
- }
- }
-};
-
-MessageModel.prototype.clear = function ()
-{
- this.folderFullNameRaw = '';
- this.uid = '';
- this.hash = '';
- this.requestHash = '';
- this.subject('');
- this.subjectPrefix('');
- this.subjectSuffix('');
- this.size(0);
- this.dateTimeStampInUTC(0);
- this.priority(Enums.MessagePriority.Normal);
-
- this.proxy = false;
-
- this.fromEmailString('');
- this.fromClearEmailString('');
- this.toEmailsString('');
- this.toClearEmailsString('');
- this.senderEmailsString('');
- this.senderClearEmailsString('');
-
- this.emails = [];
-
- this.from = [];
- this.to = [];
- this.cc = [];
- this.bcc = [];
- this.replyTo = [];
- this.deliveredTo = [];
-
- this.newForAnimation(false);
-
- this.deleted(false);
- this.unseen(false);
- this.flagged(false);
- this.answered(false);
- this.forwarded(false);
- this.isReadReceipt(false);
-
- this.selected(false);
- this.checked(false);
- this.hasAttachments(false);
- this.attachmentsMainType('');
-
- this.body = null;
- this.isHtml(false);
- this.hasImages(false);
- this.attachments([]);
-
- this.isPgpSigned(false);
- this.isPgpEncrypted(false);
- this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.None);
- this.pgpSignedVerifyUser('');
-
- this.priority(Enums.MessagePriority.Normal);
- this.readReceipt('');
- this.aDraftInfo = [];
- this.sMessageId = '';
- this.sInReplyTo = '';
- this.sReferences = '';
-
- this.parentUid(0);
- this.threads([]);
- this.threadsLen(0);
- this.hasUnseenSubMessage(false);
- this.hasFlaggedSubMessage(false);
-
- this.lastInCollapsedThread(false);
- this.lastInCollapsedThreadLoading(false);
-};
-
-MessageModel.prototype.computeSenderEmail = function ()
-{
- var
- sSent = RL.data().sentFolder(),
- sDraft = RL.data().draftFolder()
- ;
-
- this.senderEmailsString(this.folderFullNameRaw === sSent || this.folderFullNameRaw === sDraft ?
- this.toEmailsString() : this.fromEmailString());
-
- this.senderClearEmailsString(this.folderFullNameRaw === sSent || this.folderFullNameRaw === sDraft ?
- this.toClearEmailsString() : this.fromClearEmailString());
-};
-
-/**
- * @param {AjaxJsonMessage} oJsonMessage
- * @return {boolean}
- */
-MessageModel.prototype.initByJson = function (oJsonMessage)
-{
- var bResult = false;
- if (oJsonMessage && 'Object/Message' === oJsonMessage['@Object'])
- {
- this.folderFullNameRaw = oJsonMessage.Folder;
- this.uid = oJsonMessage.Uid;
- this.hash = oJsonMessage.Hash;
- this.requestHash = oJsonMessage.RequestHash;
-
- this.proxy = !!oJsonMessage.ExternalProxy;
-
- this.size(Utils.pInt(oJsonMessage.Size));
-
- this.from = MessageModel.initEmailsFromJson(oJsonMessage.From);
- this.to = MessageModel.initEmailsFromJson(oJsonMessage.To);
- this.cc = MessageModel.initEmailsFromJson(oJsonMessage.Cc);
- this.bcc = MessageModel.initEmailsFromJson(oJsonMessage.Bcc);
- this.replyTo = MessageModel.initEmailsFromJson(oJsonMessage.ReplyTo);
- this.deliveredTo = MessageModel.initEmailsFromJson(oJsonMessage.DeliveredTo);
-
- this.subject(oJsonMessage.Subject);
- if (Utils.isArray(oJsonMessage.SubjectParts))
- {
- this.subjectPrefix(oJsonMessage.SubjectParts[0]);
- this.subjectSuffix(oJsonMessage.SubjectParts[1]);
- }
- else
- {
- this.subjectPrefix('');
- this.subjectSuffix(this.subject());
- }
-
- this.dateTimeStampInUTC(Utils.pInt(oJsonMessage.DateTimeStampInUTC));
- this.hasAttachments(!!oJsonMessage.HasAttachments);
- this.attachmentsMainType(oJsonMessage.AttachmentsMainType);
-
- this.fromEmailString(MessageModel.emailsToLine(this.from, true));
- this.fromClearEmailString(MessageModel.emailsToLineClear(this.from));
- this.toEmailsString(MessageModel.emailsToLine(this.to, true));
- this.toClearEmailsString(MessageModel.emailsToLineClear(this.to));
-
- this.parentUid(Utils.pInt(oJsonMessage.ParentThread));
- this.threads(Utils.isArray(oJsonMessage.Threads) ? oJsonMessage.Threads : []);
- this.threadsLen(Utils.pInt(oJsonMessage.ThreadsLen));
-
- this.initFlagsByJson(oJsonMessage);
- this.computeSenderEmail();
-
- bResult = true;
- }
-
- return bResult;
-};
-
-/**
- * @param {AjaxJsonMessage} oJsonMessage
- * @return {boolean}
- */
-MessageModel.prototype.initUpdateByMessageJson = function (oJsonMessage)
-{
- var
- bResult = false,
- iPriority = Enums.MessagePriority.Normal
- ;
-
- if (oJsonMessage && 'Object/Message' === oJsonMessage['@Object'])
- {
- iPriority = Utils.pInt(oJsonMessage.Priority);
- this.priority(-1 < Utils.inArray(iPriority, [Enums.MessagePriority.High, Enums.MessagePriority.Low]) ?
- iPriority : Enums.MessagePriority.Normal);
-
- this.aDraftInfo = oJsonMessage.DraftInfo;
-
- this.sMessageId = oJsonMessage.MessageId;
- this.sInReplyTo = oJsonMessage.InReplyTo;
- this.sReferences = oJsonMessage.References;
-
- this.proxy = !!oJsonMessage.ExternalProxy;
-
- if (RL.data().capaOpenPGP())
- {
- this.isPgpSigned(!!oJsonMessage.PgpSigned);
- this.isPgpEncrypted(!!oJsonMessage.PgpEncrypted);
- }
-
- this.hasAttachments(!!oJsonMessage.HasAttachments);
- this.attachmentsMainType(oJsonMessage.AttachmentsMainType);
-
- this.foundedCIDs = Utils.isArray(oJsonMessage.FoundedCIDs) ? oJsonMessage.FoundedCIDs : [];
- this.attachments(this.initAttachmentsFromJson(oJsonMessage.Attachments));
-
- this.readReceipt(oJsonMessage.ReadReceipt || '');
-
- this.computeSenderEmail();
-
- bResult = true;
- }
-
- return bResult;
-};
-
-/**
- * @param {(AjaxJsonAttachment|null)} oJsonAttachments
- * @return {Array}
- */
-MessageModel.prototype.initAttachmentsFromJson = function (oJsonAttachments)
-{
- var
- iIndex = 0,
- iLen = 0,
- oAttachmentModel = null,
- aResult = []
- ;
-
- if (oJsonAttachments && 'Collection/AttachmentCollection' === oJsonAttachments['@Object'] &&
- Utils.isNonEmptyArray(oJsonAttachments['@Collection']))
- {
- for (iIndex = 0, iLen = oJsonAttachments['@Collection'].length; iIndex < iLen; iIndex++)
- {
- oAttachmentModel = AttachmentModel.newInstanceFromJson(oJsonAttachments['@Collection'][iIndex]);
- if (oAttachmentModel)
- {
- if ('' !== oAttachmentModel.cidWithOutTags && 0 < this.foundedCIDs.length &&
- 0 <= Utils.inArray(oAttachmentModel.cidWithOutTags, this.foundedCIDs))
- {
- oAttachmentModel.isLinked = true;
- }
-
- aResult.push(oAttachmentModel);
- }
- }
- }
-
- return aResult;
-};
-
-/**
- * @param {AjaxJsonMessage} oJsonMessage
- * @return {boolean}
- */
-MessageModel.prototype.initFlagsByJson = function (oJsonMessage)
-{
- var bResult = false;
-
- if (oJsonMessage && 'Object/Message' === oJsonMessage['@Object'])
- {
- this.unseen(!oJsonMessage.IsSeen);
- this.flagged(!!oJsonMessage.IsFlagged);
- this.answered(!!oJsonMessage.IsAnswered);
- this.forwarded(!!oJsonMessage.IsForwarded);
- this.isReadReceipt(!!oJsonMessage.IsReadReceipt);
-
- bResult = true;
- }
-
- return bResult;
-};
-
-/**
- * @param {boolean} bFriendlyView
- * @param {boolean=} bWrapWithLink = false
- * @return {string}
- */
-MessageModel.prototype.fromToLine = function (bFriendlyView, bWrapWithLink)
-{
- return MessageModel.emailsToLine(this.from, bFriendlyView, bWrapWithLink);
-};
-
-/**
- * @param {boolean} bFriendlyView
- * @param {boolean=} bWrapWithLink = false
- * @return {string}
- */
-MessageModel.prototype.toToLine = function (bFriendlyView, bWrapWithLink)
-{
- return MessageModel.emailsToLine(this.to, bFriendlyView, bWrapWithLink);
-};
-
-/**
- * @param {boolean} bFriendlyView
- * @param {boolean=} bWrapWithLink = false
- * @return {string}
- */
-MessageModel.prototype.ccToLine = function (bFriendlyView, bWrapWithLink)
-{
- return MessageModel.emailsToLine(this.cc, bFriendlyView, bWrapWithLink);
-};
-
-/**
- * @param {boolean} bFriendlyView
- * @param {boolean=} bWrapWithLink = false
- * @return {string}
- */
-MessageModel.prototype.bccToLine = function (bFriendlyView, bWrapWithLink)
-{
- return MessageModel.emailsToLine(this.bcc, bFriendlyView, bWrapWithLink);
-};
-
-/**
- * @return string
- */
-MessageModel.prototype.lineAsCcc = function ()
-{
- var aResult = [];
- if (this.deleted())
- {
- aResult.push('deleted');
- }
- if (this.selected())
- {
- aResult.push('selected');
- }
- if (this.checked())
- {
- aResult.push('checked');
- }
- if (this.flagged())
- {
- aResult.push('flagged');
- }
- if (this.unseen())
- {
- aResult.push('unseen');
- }
- if (this.answered())
- {
- aResult.push('answered');
- }
- if (this.forwarded())
- {
- aResult.push('forwarded');
- }
- if (this.focused())
- {
- aResult.push('focused');
- }
- if (this.hasAttachments())
- {
- aResult.push('withAttachments');
- switch (this.attachmentsMainType())
- {
- case 'image':
- aResult.push('imageOnlyAttachments');
- break;
- case 'archive':
- aResult.push('archiveOnlyAttachments');
- break;
- }
- }
- if (this.newForAnimation())
- {
- aResult.push('new');
- }
- if ('' === this.subject())
- {
- aResult.push('emptySubject');
- }
- if (0 < this.parentUid())
- {
- aResult.push('hasParentMessage');
- }
- if (0 < this.threadsLen() && 0 === this.parentUid())
- {
- aResult.push('hasChildrenMessage');
- }
- if (this.hasUnseenSubMessage())
- {
- aResult.push('hasUnseenSubMessage');
- }
- if (this.hasFlaggedSubMessage())
- {
- aResult.push('hasFlaggedSubMessage');
- }
-
- return aResult.join(' ');
-};
-
-/**
- * @return {boolean}
- */
-MessageModel.prototype.hasVisibleAttachments = function ()
-{
- return !!_.find(this.attachments(), function (oAttachment) {
- return !oAttachment.isLinked;
- });
-// return 0 < this.attachments().length;
-};
-
-/**
- * @param {string} sCid
- * @return {*}
- */
-MessageModel.prototype.findAttachmentByCid = function (sCid)
-{
- var
- oResult = null,
- aAttachments = this.attachments()
- ;
-
- if (Utils.isNonEmptyArray(aAttachments))
- {
- sCid = sCid.replace(/^<+/, '').replace(/>+$/, '');
- oResult = _.find(aAttachments, function (oAttachment) {
- return sCid === oAttachment.cidWithOutTags;
+ RoutedSettingsViewModel = _.find(Globals.aViewModels['settings'], function (SettingsViewModel) {
+ return SettingsViewModel && SettingsViewModel.__rlSettingsData &&
+ sSubName === SettingsViewModel.__rlSettingsData.Route;
});
- }
- return oResult || null;
-};
-
-/**
- * @param {string} sContentLocation
- * @return {*}
- */
-MessageModel.prototype.findAttachmentByContentLocation = function (sContentLocation)
-{
- var
- oResult = null,
- aAttachments = this.attachments()
- ;
-
- if (Utils.isNonEmptyArray(aAttachments))
- {
- oResult = _.find(aAttachments, function (oAttachment) {
- return sContentLocation === oAttachment.contentLocation;
- });
- }
-
- return oResult || null;
-};
-
-
-/**
- * @return {string}
- */
-MessageModel.prototype.messageId = function ()
-{
- return this.sMessageId;
-};
-
-/**
- * @return {string}
- */
-MessageModel.prototype.inReplyTo = function ()
-{
- return this.sInReplyTo;
-};
-
-/**
- * @return {string}
- */
-MessageModel.prototype.references = function ()
-{
- return this.sReferences;
-};
-
-/**
- * @return {string}
- */
-MessageModel.prototype.fromAsSingleEmail = function ()
-{
- return Utils.isArray(this.from) && this.from[0] ? this.from[0].email : '';
-};
-
-/**
- * @return {string}
- */
-MessageModel.prototype.viewLink = function ()
-{
- return RL.link().messageViewLink(this.requestHash);
-};
-
-/**
- * @return {string}
- */
-MessageModel.prototype.downloadLink = function ()
-{
- return RL.link().messageDownloadLink(this.requestHash);
-};
-
-/**
- * @param {Object} oExcludeEmails
- * @return {Array}
- */
-MessageModel.prototype.replyEmails = function (oExcludeEmails)
-{
- var
- aResult = [],
- oUnic = Utils.isUnd(oExcludeEmails) ? {} : oExcludeEmails
- ;
-
- MessageModel.replyHelper(this.replyTo, oUnic, aResult);
- if (0 === aResult.length)
- {
- MessageModel.replyHelper(this.from, oUnic, aResult);
- }
-
- return aResult;
-};
-
-/**
- * @param {Object} oExcludeEmails
- * @return {Array.}
- */
-MessageModel.prototype.replyAllEmails = function (oExcludeEmails)
-{
- var
- aToResult = [],
- aCcResult = [],
- oUnic = Utils.isUnd(oExcludeEmails) ? {} : oExcludeEmails
- ;
-
- MessageModel.replyHelper(this.replyTo, oUnic, aToResult);
- if (0 === aToResult.length)
- {
- MessageModel.replyHelper(this.from, oUnic, aToResult);
- }
-
- MessageModel.replyHelper(this.to, oUnic, aToResult);
- MessageModel.replyHelper(this.cc, oUnic, aCcResult);
-
- return [aToResult, aCcResult];
-};
-
-/**
- * @return {string}
- */
-MessageModel.prototype.textBodyToString = function ()
-{
- return this.body ? this.body.html() : '';
-};
-
-/**
- * @return {string}
- */
-MessageModel.prototype.attachmentsToStringLine = function ()
-{
- var aAttachLines = _.map(this.attachments(), function (oItem) {
- return oItem.fileName + ' (' + oItem.friendlySize + ')';
- });
-
- return aAttachLines && 0 < aAttachLines.length ? aAttachLines.join(', ') : '';
-};
-
-/**
- * @return {Object}
- */
-MessageModel.prototype.getDataForWindowPopup = function ()
-{
- return {
- 'popupFrom': this.fromToLine(false),
- 'popupTo': this.toToLine(false),
- 'popupCc': this.ccToLine(false),
- 'popupBcc': this.bccToLine(false),
- 'popupSubject': this.subject(),
- 'popupDate': this.fullFormatDateValue(),
- 'popupAttachments': this.attachmentsToStringLine(),
- 'popupBody': this.textBodyToString()
- };
-};
-
-/**
- * @param {boolean=} bPrint = false
- */
-MessageModel.prototype.viewPopupMessage = function (bPrint)
-{
- Utils.windowPopupKnockout(this.getDataForWindowPopup(), 'PopupsWindowSimpleMessage', this.subject(), function (oPopupWin) {
- if (oPopupWin && oPopupWin.document && oPopupWin.document.body)
+ if (RoutedSettingsViewModel)
{
- $('img.lazy', oPopupWin.document.body).each(function (iIndex, oImg) {
-
- var
- $oImg = $(oImg),
- sOrig = $oImg.data('original'),
- sSrc = $oImg.attr('src')
- ;
-
- if (0 <= iIndex && sOrig && !sSrc)
- {
- $oImg.attr('src', sOrig);
- }
- });
-
- if (bPrint)
+ if (_.find(Globals.aViewModels['settings-removed'], function (DisabledSettingsViewModel) {
+ return DisabledSettingsViewModel && DisabledSettingsViewModel === RoutedSettingsViewModel;
+ }))
{
- window.setTimeout(function () {
- oPopupWin.print();
- }, 100);
+ RoutedSettingsViewModel = null;
+ }
+
+ if (RoutedSettingsViewModel && _.find(Globals.aViewModels['settings-disabled'], function (DisabledSettingsViewModel) {
+ return DisabledSettingsViewModel && DisabledSettingsViewModel === RoutedSettingsViewModel;
+ }))
+ {
+ RoutedSettingsViewModel = null;
}
}
- });
-};
-MessageModel.prototype.printMessage = function ()
-{
- this.viewPopupMessage(true);
-};
-
-/**
- * @returns {string}
- */
-MessageModel.prototype.generateUid = function ()
-{
- return this.folderFullNameRaw + '/' + this.uid;
-};
-
-/**
- * @param {MessageModel} oMessage
- * @return {MessageModel}
- */
-MessageModel.prototype.populateByMessageListItem = function (oMessage)
-{
- this.folderFullNameRaw = oMessage.folderFullNameRaw;
- this.uid = oMessage.uid;
- this.hash = oMessage.hash;
- this.requestHash = oMessage.requestHash;
- this.subject(oMessage.subject());
- this.subjectPrefix(this.subjectPrefix());
- this.subjectSuffix(this.subjectSuffix());
-
- this.size(oMessage.size());
- this.dateTimeStampInUTC(oMessage.dateTimeStampInUTC());
- this.priority(oMessage.priority());
-
- this.proxy = oMessage.proxy;
-
- this.fromEmailString(oMessage.fromEmailString());
- this.fromClearEmailString(oMessage.fromClearEmailString());
- this.toEmailsString(oMessage.toEmailsString());
- this.toClearEmailsString(oMessage.toClearEmailsString());
-
- this.emails = oMessage.emails;
-
- this.from = oMessage.from;
- this.to = oMessage.to;
- this.cc = oMessage.cc;
- this.bcc = oMessage.bcc;
- this.replyTo = oMessage.replyTo;
- this.deliveredTo = oMessage.deliveredTo;
-
- this.unseen(oMessage.unseen());
- this.flagged(oMessage.flagged());
- this.answered(oMessage.answered());
- this.forwarded(oMessage.forwarded());
- this.isReadReceipt(oMessage.isReadReceipt());
-
- this.selected(oMessage.selected());
- this.checked(oMessage.checked());
- this.hasAttachments(oMessage.hasAttachments());
- this.attachmentsMainType(oMessage.attachmentsMainType());
-
- this.moment(oMessage.moment());
-
- this.body = null;
-// this.isHtml(false);
-// this.hasImages(false);
-// this.attachments([]);
-
-// this.isPgpSigned(false);
-// this.isPgpEncrypted(false);
-
- this.priority(Enums.MessagePriority.Normal);
- this.aDraftInfo = [];
- this.sMessageId = '';
- this.sInReplyTo = '';
- this.sReferences = '';
-
- this.parentUid(oMessage.parentUid());
- this.threads(oMessage.threads());
- this.threadsLen(oMessage.threadsLen());
-
- this.computeSenderEmail();
-
- return this;
-};
-
-MessageModel.prototype.showExternalImages = function (bLazy)
-{
- if (this.body && this.body.data('rl-has-images'))
- {
- var sAttr = '';
- bLazy = Utils.isUnd(bLazy) ? false : bLazy;
-
- this.hasImages(false);
- this.body.data('rl-has-images', false);
-
- sAttr = this.proxy ? 'data-x-additional-src' : 'data-x-src';
- $('[' + sAttr + ']', this.body).each(function () {
- if (bLazy && $(this).is('img'))
+ if (RoutedSettingsViewModel)
+ {
+ if (RoutedSettingsViewModel.__builded && RoutedSettingsViewModel.__vm)
{
- $(this)
- .addClass('lazy')
- .attr('data-original', $(this).attr(sAttr))
- .removeAttr(sAttr)
- ;
+ oSettingsScreen = RoutedSettingsViewModel.__vm;
}
else
{
- $(this).attr('src', $(this).attr(sAttr)).removeAttr(sAttr);
- }
- });
-
- sAttr = this.proxy ? 'data-x-additional-style-url' : 'data-x-style-url';
- $('[' + sAttr + ']', this.body).each(function () {
- var sStyle = Utils.trim($(this).attr('style'));
- sStyle = '' === sStyle ? '' : (';' === sStyle.substr(-1) ? sStyle + ' ' : sStyle + '; ');
- $(this).attr('style', sStyle + $(this).attr(sAttr)).removeAttr(sAttr);
- });
-
- if (bLazy)
- {
- $('img.lazy', this.body).addClass('lazy-inited').lazyload({
- 'threshold' : 400,
- 'effect' : 'fadeIn',
- 'skip_invisible' : false,
- 'container': $('.RL-MailMessageView .messageView .messageItem .content')[0]
- });
-
- $window.resize();
- }
-
- Utils.windowResize(500);
- }
-};
-
-MessageModel.prototype.showInternalImages = function (bLazy)
-{
- if (this.body && !this.body.data('rl-init-internal-images'))
- {
- this.body.data('rl-init-internal-images', true);
-
- bLazy = Utils.isUnd(bLazy) ? false : bLazy;
-
- var self = this;
-
- $('[data-x-src-cid]', this.body).each(function () {
-
- var oAttachment = self.findAttachmentByCid($(this).attr('data-x-src-cid'));
- if (oAttachment && oAttachment.download)
- {
- if (bLazy && $(this).is('img'))
+ oViewModelPlace = this.oViewModelPlace;
+ if (oViewModelPlace && 1 === oViewModelPlace.length)
{
- $(this)
- .addClass('lazy')
- .attr('data-original', oAttachment.linkPreview());
+ RoutedSettingsViewModel = /** @type {?Function} */ RoutedSettingsViewModel;
+ oSettingsScreen = new RoutedSettingsViewModel();
+
+ oViewModelDom = $('').addClass('rl-settings-view-model').hide();
+ oViewModelDom.appendTo(oViewModelPlace);
+
+ oSettingsScreen.viewModelDom = oViewModelDom;
+
+ oSettingsScreen.__rlSettingsData = RoutedSettingsViewModel.__rlSettingsData;
+
+ RoutedSettingsViewModel.__dom = oViewModelDom;
+ RoutedSettingsViewModel.__builded = true;
+ RoutedSettingsViewModel.__vm = oSettingsScreen;
+
+ ko.applyBindingAccessorsToNode(oViewModelDom[0], {
+ 'i18nInit': true,
+ 'template': function () { return {'name': RoutedSettingsViewModel.__rlSettingsData.Template}; }
+ }, oSettingsScreen);
+
+ Utils.delegateRun(oSettingsScreen, 'onBuild', [oViewModelDom]);
}
else
{
- $(this).attr('src', oAttachment.linkPreview());
+ Utils.log('Cannot find sub settings view model position: SettingsSubScreen');
}
}
- });
- $('[data-x-src-location]', this.body).each(function () {
-
- var oAttachment = self.findAttachmentByContentLocation($(this).attr('data-x-src-location'));
- if (!oAttachment)
+ if (oSettingsScreen)
{
- oAttachment = self.findAttachmentByCid($(this).attr('data-x-src-location'));
- }
-
- if (oAttachment && oAttachment.download)
- {
- if (bLazy && $(this).is('img'))
- {
- $(this)
- .addClass('lazy')
- .attr('data-original', oAttachment.linkPreview());
- }
- else
- {
- $(this).attr('src', oAttachment.linkPreview());
- }
- }
- });
-
- $('[data-x-style-cid]', this.body).each(function () {
-
- var
- sStyle = '',
- sName = '',
- oAttachment = self.findAttachmentByCid($(this).attr('data-x-style-cid'))
- ;
-
- if (oAttachment && oAttachment.linkPreview)
- {
- sName = $(this).attr('data-x-style-cid-name');
- if ('' !== sName)
- {
- sStyle = Utils.trim($(this).attr('style'));
- sStyle = '' === sStyle ? '' : (';' === sStyle.substr(-1) ? sStyle + ' ' : sStyle + '; ');
- $(this).attr('style', sStyle + sName + ': url(\'' + oAttachment.linkPreview() + '\')');
- }
- }
- });
-
- if (bLazy)
- {
- (function ($oImg, oContainer) {
- _.delay(function () {
- $oImg.addClass('lazy-inited').lazyload({
- 'threshold' : 400,
- 'effect' : 'fadeIn',
- 'skip_invisible' : false,
- 'container': oContainer
- });
- }, 300);
- }($('img.lazy', self.body), $('.RL-MailMessageView .messageView .messageItem .content')[0]));
- }
-
- Utils.windowResize(500);
- }
-};
-
-MessageModel.prototype.storeDataToDom = function ()
-{
- if (this.body)
- {
- this.body.data('rl-is-html', !!this.isHtml());
- this.body.data('rl-has-images', !!this.hasImages());
-
- this.body.data('rl-plain-raw', this.plainRaw);
-
- if (RL.data().capaOpenPGP())
- {
- this.body.data('rl-plain-pgp-signed', !!this.isPgpSigned());
- this.body.data('rl-plain-pgp-encrypted', !!this.isPgpEncrypted());
- this.body.data('rl-pgp-verify-status', this.pgpSignedVerifyStatus());
- this.body.data('rl-pgp-verify-user', this.pgpSignedVerifyUser());
- }
- }
-};
-
-MessageModel.prototype.storePgpVerifyDataToDom = function ()
-{
- if (this.body && RL.data().capaOpenPGP())
- {
- this.body.data('rl-pgp-verify-status', this.pgpSignedVerifyStatus());
- this.body.data('rl-pgp-verify-user', this.pgpSignedVerifyUser());
- }
-};
-
-MessageModel.prototype.fetchDataToDom = function ()
-{
- if (this.body)
- {
- this.isHtml(!!this.body.data('rl-is-html'));
- this.hasImages(!!this.body.data('rl-has-images'));
-
- this.plainRaw = Utils.pString(this.body.data('rl-plain-raw'));
-
- if (RL.data().capaOpenPGP())
- {
- this.isPgpSigned(!!this.body.data('rl-plain-pgp-signed'));
- this.isPgpEncrypted(!!this.body.data('rl-plain-pgp-encrypted'));
- this.pgpSignedVerifyStatus(this.body.data('rl-pgp-verify-status'));
- this.pgpSignedVerifyUser(this.body.data('rl-pgp-verify-user'));
- }
- else
- {
- this.isPgpSigned(false);
- this.isPgpEncrypted(false);
- this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.None);
- this.pgpSignedVerifyUser('');
- }
- }
-};
-
-MessageModel.prototype.verifyPgpSignedClearMessage = function ()
-{
- if (this.isPgpSigned())
- {
- var
- aRes = [],
- mPgpMessage = null,
- sFrom = this.from && this.from[0] && this.from[0].email ? this.from[0].email : '',
- aPublicKeys = RL.data().findPublicKeysByEmail(sFrom),
- oValidKey = null,
- oValidSysKey = null,
- sPlain = ''
- ;
-
- this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.Error);
- this.pgpSignedVerifyUser('');
-
- try
- {
- mPgpMessage = window.openpgp.cleartext.readArmored(this.plainRaw);
- if (mPgpMessage && mPgpMessage.getText)
- {
- this.pgpSignedVerifyStatus(
- aPublicKeys.length ? Enums.SignedVerifyStatus.Unverified : Enums.SignedVerifyStatus.UnknownPublicKeys);
-
- aRes = mPgpMessage.verify(aPublicKeys);
- if (aRes && 0 < aRes.length)
- {
- oValidKey = _.find(aRes, function (oItem) {
- return oItem && oItem.keyid && oItem.valid;
- });
-
- if (oValidKey)
+ _.defer(function () {
+ // hide
+ if (self.oCurrentSubScreen)
{
- oValidSysKey = RL.data().findPublicKeyByHex(oValidKey.keyid.toHex());
- if (oValidSysKey)
- {
- sPlain = mPgpMessage.getText();
-
- this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.Success);
- this.pgpSignedVerifyUser(oValidSysKey.user);
-
- sPlain =
- $proxyDiv.empty().append(
- $('').text(sPlain)
- ).html()
- ;
-
- $proxyDiv.empty();
-
- this.replacePlaneTextBody(sPlain);
- }
+ Utils.delegateRun(self.oCurrentSubScreen, 'onHide');
+ self.oCurrentSubScreen.viewModelDom.hide();
}
- }
- }
- }
- catch (oExc) {}
+ // --
- this.storePgpVerifyDataToDom();
- }
-};
+ self.oCurrentSubScreen = oSettingsScreen;
-MessageModel.prototype.decryptPgpEncryptedMessage = function (sPassword)
-{
- if (this.isPgpEncrypted())
- {
- var
- aRes = [],
- mPgpMessage = null,
- mPgpMessageDecrypted = null,
- sFrom = this.from && this.from[0] && this.from[0].email ? this.from[0].email : '',
- aPublicKey = RL.data().findPublicKeysByEmail(sFrom),
- oPrivateKey = RL.data().findSelfPrivateKey(sPassword),
- oValidKey = null,
- oValidSysKey = null,
- sPlain = ''
- ;
-
- this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.Error);
- this.pgpSignedVerifyUser('');
-
- if (!oPrivateKey)
- {
- this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.UnknownPrivateKey);
- }
-
- try
- {
- mPgpMessage = window.openpgp.message.readArmored(this.plainRaw);
- if (mPgpMessage && oPrivateKey && mPgpMessage.decrypt)
- {
- this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.Unverified);
-
- mPgpMessageDecrypted = mPgpMessage.decrypt(oPrivateKey);
- if (mPgpMessageDecrypted)
- {
- aRes = mPgpMessageDecrypted.verify(aPublicKey);
- if (aRes && 0 < aRes.length)
+ // show
+ if (self.oCurrentSubScreen)
{
- oValidKey = _.find(aRes, function (oItem) {
- return oItem && oItem.keyid && oItem.valid;
+ self.oCurrentSubScreen.viewModelDom.show();
+ Utils.delegateRun(self.oCurrentSubScreen, 'onShow');
+ Utils.delegateRun(self.oCurrentSubScreen, 'onFocus', [], 200);
+
+ _.each(self.menu(), function (oItem) {
+ oItem.selected(oSettingsScreen && oSettingsScreen.__rlSettingsData && oItem.route === oSettingsScreen.__rlSettingsData.Route);
});
- if (oValidKey)
- {
- oValidSysKey = RL.data().findPublicKeyByHex(oValidKey.keyid.toHex());
- if (oValidSysKey)
- {
- this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.Success);
- this.pgpSignedVerifyUser(oValidSysKey.user);
- }
- }
+ $('#rl-content .b-settings .b-content .content').scrollTop(0);
}
+ // --
- sPlain = mPgpMessageDecrypted.getText();
-
- sPlain =
- $proxyDiv.empty().append(
- $('').text(sPlain)
- ).html()
- ;
-
- $proxyDiv.empty();
-
- this.replacePlaneTextBody(sPlain);
- }
+ Utils.windowResize();
+ });
}
}
- catch (oExc) {}
-
- this.storePgpVerifyDataToDom();
- }
-};
-
-MessageModel.prototype.replacePlaneTextBody = function (sPlain)
-{
- if (this.body)
- {
- this.body.html(sPlain).addClass('b-text-part plain');
- }
-};
-
-/**
- * @return {string}
- */
-MessageModel.prototype.flagHash = function ()
-{
- return [this.deleted(), this.unseen(), this.flagged(), this.answered(), this.forwarded(),
- this.isReadReceipt()].join('');
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function FolderModel()
-{
- this.name = ko.observable('');
- this.fullName = '';
- this.fullNameRaw = '';
- this.fullNameHash = '';
- this.delimiter = '';
- this.namespace = '';
- this.deep = 0;
- this.interval = 0;
-
- this.selectable = false;
- this.existen = true;
-
- this.type = ko.observable(Enums.FolderType.User);
-
- this.focused = ko.observable(false);
- this.selected = ko.observable(false);
- this.edited = ko.observable(false);
- this.collapsed = ko.observable(true);
- this.subScribed = ko.observable(true);
- this.subFolders = ko.observableArray([]);
- this.deleteAccess = ko.observable(false);
- this.actionBlink = ko.observable(false).extend({'falseTimeout': 1000});
-
- this.nameForEdit = ko.observable('');
-
- this.name.subscribe(function (sValue) {
- this.nameForEdit(sValue);
- }, this);
-
- this.edited.subscribe(function (bValue) {
- if (bValue)
+ else
{
- this.nameForEdit(this.name());
+ kn.setHash(LinkBuilder.settings(), false, true);
}
- }, this);
-
- this.privateMessageCountAll = ko.observable(0);
- this.privateMessageCountUnread = ko.observable(0);
-
- this.collapsedPrivate = ko.observable(true);
-}
-
-/**
- * @static
- * @param {AjaxJsonFolder} oJsonFolder
- * @return {?FolderModel}
- */
-FolderModel.newInstanceFromJson = function (oJsonFolder)
-{
- var oFolderModel = new FolderModel();
- return oFolderModel.initByJson(oJsonFolder) ? oFolderModel.initComputed() : null;
-};
-
-/**
- * @return {FolderModel}
- */
-FolderModel.prototype.initComputed = function ()
-{
- this.hasSubScribedSubfolders = ko.computed(function () {
- return !!_.find(this.subFolders(), function (oFolder) {
- return oFolder.subScribed() && !oFolder.isSystemFolder();
- });
- }, this);
-
- this.canBeEdited = ko.computed(function () {
- return Enums.FolderType.User === this.type() && this.existen && this.selectable;
- }, this);
-
- this.visible = ko.computed(function () {
- var
- bSubScribed = this.subScribed(),
- bSubFolders = this.hasSubScribedSubfolders()
- ;
-
- return (bSubScribed || (bSubFolders && (!this.existen || !this.selectable)));
- }, this);
-
- this.isSystemFolder = ko.computed(function () {
- return Enums.FolderType.User !== this.type();
- }, this);
-
- this.hidden = ko.computed(function () {
- var
- bSystem = this.isSystemFolder(),
- bSubFolders = this.hasSubScribedSubfolders()
- ;
-
- return (bSystem && !bSubFolders) || (!this.selectable && !bSubFolders);
-
- }, this);
-
- this.selectableForFolderList = ko.computed(function () {
- return !this.isSystemFolder() && this.selectable;
- }, this);
-
- this.messageCountAll = ko.computed({
- 'read': this.privateMessageCountAll,
- 'write': function (iValue) {
- if (Utils.isPosNumeric(iValue, true))
- {
- this.privateMessageCountAll(iValue);
- }
- else
- {
- this.privateMessageCountAll.valueHasMutated();
- }
- },
- 'owner': this
- });
-
- this.messageCountUnread = ko.computed({
- 'read': this.privateMessageCountUnread,
- 'write': function (iValue) {
- if (Utils.isPosNumeric(iValue, true))
- {
- this.privateMessageCountUnread(iValue);
- }
- else
- {
- this.privateMessageCountUnread.valueHasMutated();
- }
- },
- 'owner': this
- });
-
- this.printableUnreadCount = ko.computed(function () {
- var
- iCount = this.messageCountAll(),
- iUnread = this.messageCountUnread(),
- iType = this.type()
- ;
-
- if (Enums.FolderType.Inbox === iType)
- {
- RL.data().foldersInboxUnreadCount(iUnread);
- }
-
- if (0 < iCount)
- {
- if (Enums.FolderType.Draft === iType)
- {
- return '' + iCount;
- }
- else if (0 < iUnread && Enums.FolderType.Trash !== iType && Enums.FolderType.Archive !== iType && Enums.FolderType.SentItems !== iType)
- {
- return '' + iUnread;
- }
- }
-
- return '';
-
- }, this);
-
- this.canBeDeleted = ko.computed(function () {
- var
- bSystem = this.isSystemFolder()
- ;
- return !bSystem && 0 === this.subFolders().length && 'INBOX' !== this.fullNameRaw;
- }, this);
-
- this.canBeSubScribed = ko.computed(function () {
- return !this.isSystemFolder() && this.selectable && 'INBOX' !== this.fullNameRaw;
- }, this);
-
- this.visible.subscribe(function () {
- Utils.timeOutAction('folder-list-folder-visibility-change', function () {
- $window.trigger('folder-list-folder-visibility-change');
- }, 100);
- });
-
- this.localName = ko.computed(function () {
-
- Globals.langChangeTrigger();
-
- var
- iType = this.type(),
- sName = this.name()
- ;
-
- if (this.isSystemFolder())
- {
- switch (iType)
- {
- case Enums.FolderType.Inbox:
- sName = Utils.i18n('FOLDER_LIST/INBOX_NAME');
- break;
- case Enums.FolderType.SentItems:
- sName = Utils.i18n('FOLDER_LIST/SENT_NAME');
- break;
- case Enums.FolderType.Draft:
- sName = Utils.i18n('FOLDER_LIST/DRAFTS_NAME');
- break;
- case Enums.FolderType.Spam:
- sName = Utils.i18n('FOLDER_LIST/SPAM_NAME');
- break;
- case Enums.FolderType.Trash:
- sName = Utils.i18n('FOLDER_LIST/TRASH_NAME');
- break;
- case Enums.FolderType.Archive:
- sName = Utils.i18n('FOLDER_LIST/ARCHIVE_NAME');
- break;
- }
- }
-
- return sName;
-
- }, this);
-
- this.manageFolderSystemName = ko.computed(function () {
-
- Globals.langChangeTrigger();
-
- var
- sSuffix = '',
- iType = this.type(),
- sName = this.name()
- ;
-
- if (this.isSystemFolder())
- {
- switch (iType)
- {
- case Enums.FolderType.Inbox:
- sSuffix = '(' + Utils.i18n('FOLDER_LIST/INBOX_NAME') + ')';
- break;
- case Enums.FolderType.SentItems:
- sSuffix = '(' + Utils.i18n('FOLDER_LIST/SENT_NAME') + ')';
- break;
- case Enums.FolderType.Draft:
- sSuffix = '(' + Utils.i18n('FOLDER_LIST/DRAFTS_NAME') + ')';
- break;
- case Enums.FolderType.Spam:
- sSuffix = '(' + Utils.i18n('FOLDER_LIST/SPAM_NAME') + ')';
- break;
- case Enums.FolderType.Trash:
- sSuffix = '(' + Utils.i18n('FOLDER_LIST/TRASH_NAME') + ')';
- break;
- case Enums.FolderType.Archive:
- sSuffix = '(' + Utils.i18n('FOLDER_LIST/ARCHIVE_NAME') + ')';
- break;
- }
- }
-
- if ('' !== sSuffix && '(' + sName + ')' === sSuffix || '(inbox)' === sSuffix.toLowerCase())
- {
- sSuffix = '';
- }
-
- return sSuffix;
-
- }, this);
-
- this.collapsed = ko.computed({
- 'read': function () {
- return !this.hidden() && this.collapsedPrivate();
- },
- 'write': function (mValue) {
- this.collapsedPrivate(mValue);
- },
- 'owner': this
- });
-
- this.hasUnreadMessages = ko.computed(function () {
- return 0 < this.messageCountUnread();
- }, this);
-
- this.hasSubScribedUnreadMessagesSubfolders = ko.computed(function () {
- return !!_.find(this.subFolders(), function (oFolder) {
- return oFolder.hasUnreadMessages() || oFolder.hasSubScribedUnreadMessagesSubfolders();
- });
- }, this);
-
- return this;
-};
-
-FolderModel.prototype.fullName = '';
-FolderModel.prototype.fullNameRaw = '';
-FolderModel.prototype.fullNameHash = '';
-FolderModel.prototype.delimiter = '';
-FolderModel.prototype.namespace = '';
-FolderModel.prototype.deep = 0;
-FolderModel.prototype.interval = 0;
-
-/**
- * @return {string}
- */
-FolderModel.prototype.collapsedCss = function ()
-{
- return this.hasSubScribedSubfolders() ?
- (this.collapsed() ? 'icon-right-mini e-collapsed-sign' : 'icon-down-mini e-collapsed-sign') : 'icon-none e-collapsed-sign';
-};
-
-/**
- * @param {AjaxJsonFolder} oJsonFolder
- * @return {boolean}
- */
-FolderModel.prototype.initByJson = function (oJsonFolder)
-{
- var bResult = false;
- if (oJsonFolder && 'Object/Folder' === oJsonFolder['@Object'])
- {
- this.name(oJsonFolder.Name);
- this.delimiter = oJsonFolder.Delimiter;
- this.fullName = oJsonFolder.FullName;
- this.fullNameRaw = oJsonFolder.FullNameRaw;
- this.fullNameHash = oJsonFolder.FullNameHash;
- this.deep = oJsonFolder.FullNameRaw.split(this.delimiter).length - 1;
- this.selectable = !!oJsonFolder.IsSelectable;
- this.existen = !!oJsonFolder.IsExists;
-
- this.subScribed(!!oJsonFolder.IsSubscribed);
- this.type('INBOX' === this.fullNameRaw ? Enums.FolderType.Inbox : Enums.FolderType.User);
-
- bResult = true;
- }
-
- return bResult;
-};
-
-/**
- * @return {string}
- */
-FolderModel.prototype.printableFullName = function ()
-{
- return this.fullName.split(this.delimiter).join(' / ');
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @param {string} sEmail
- * @param {boolean=} bCanBeDelete = true
- * @constructor
- */
-function AccountModel(sEmail, bCanBeDelete)
-{
- this.email = sEmail;
- this.deleteAccess = ko.observable(false);
- this.canBeDalete = ko.observable(bCanBeDelete);
-}
-
-AccountModel.prototype.email = '';
-
-/**
- * @return {string}
- */
-AccountModel.prototype.changeAccountLink = function ()
-{
- return RL.link().change(this.email);
-};
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @param {string} sId
- * @param {string} sEmail
- * @param {boolean=} bCanBeDelete = true
- * @constructor
- */
-function IdentityModel(sId, sEmail, bCanBeDelete)
-{
- this.id = sId;
- this.email = ko.observable(sEmail);
- this.name = ko.observable('');
- this.replyTo = ko.observable('');
- this.bcc = ko.observable('');
-
- this.deleteAccess = ko.observable(false);
- this.canBeDalete = ko.observable(bCanBeDelete);
-}
-
-IdentityModel.prototype.formattedName = function ()
-{
- var sName = this.name();
- return '' === sName ? this.email() : sName + ' <' + this.email() + '>';
-};
-
-IdentityModel.prototype.formattedNameForCompose = function ()
-{
- var sName = this.name();
- return '' === sName ? this.email() : sName + ' (' + this.email() + ')';
-};
-
-IdentityModel.prototype.formattedNameForEmail = function ()
-{
- var sName = this.name();
- return '' === sName ? this.email() : '"' + Utils.quoteName(sName) + '" <' + this.email() + '>';
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function FilterConditionModel(oKoList)
-{
- this.parentList = oKoList;
-
- this.field = ko.observable(Enums.FilterConditionField.From);
-
- this.fieldOptions = [ // TODO i18n
- {'id': Enums.FilterConditionField.From, 'name': 'From'},
- {'id': Enums.FilterConditionField.Recipient, 'name': 'Recipient (To or CC)'},
- {'id': Enums.FilterConditionField.To, 'name': 'To'},
- {'id': Enums.FilterConditionField.Subject, 'name': 'Subject'}
- ];
-
- this.type = ko.observable(Enums.FilterConditionType.EqualTo);
-
- this.typeOptions = [ // TODO i18n
- {'id': Enums.FilterConditionType.EqualTo, 'name': 'Equal To'},
- {'id': Enums.FilterConditionType.NotEqualTo, 'name': 'Not Equal To'},
- {'id': Enums.FilterConditionType.Contains, 'name': 'Contains'},
- {'id': Enums.FilterConditionType.NotContains, 'name': 'Not Contains'}
- ];
-
- this.value = ko.observable('');
-
- this.template = ko.computed(function () {
-
- var sTemplate = '';
- switch (this.type())
- {
- default:
- sTemplate = 'SettingsFiltersConditionDefault';
- break;
- }
-
- return sTemplate;
-
- }, this);
-}
-
-FilterConditionModel.prototype.removeSelf = function ()
-{
- this.parentList.remove(this);
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function FilterModel()
-{
- this.new = ko.observable(true);
- this.enabled = ko.observable(true);
-
- this.name = ko.observable('');
-
- this.conditionsType = ko.observable(Enums.FilterRulesType.And);
-
- this.conditions = ko.observableArray([]);
-
- this.conditions.subscribe(function () {
- Utils.windowResize();
- });
-
- // Actions
- this.actionMarkAsRead = ko.observable(false);
- this.actionSkipOtherFilters = ko.observable(true);
- this.actionValue = ko.observable('');
-
- this.actionType = ko.observable(Enums.FiltersAction.Move);
- this.actionTypeOptions = [ // TODO i18n
- {'id': Enums.FiltersAction.None, 'name': 'Action - None'},
- {'id': Enums.FiltersAction.Move, 'name': 'Action - Move to'},
-// {'id': Enums.FiltersAction.Forward, 'name': 'Action - Forward to'},
- {'id': Enums.FiltersAction.Discard, 'name': 'Action - Discard'}
- ];
-
- this.actionMarkAsReadVisiblity = ko.computed(function () {
- return -1 < Utils.inArray(this.actionType(), [
- Enums.FiltersAction.None, Enums.FiltersAction.Forward, Enums.FiltersAction.Move
- ]);
- }, this);
-
- this.actionTemplate = ko.computed(function () {
-
- var sTemplate = '';
- switch (this.actionType())
- {
- default:
- case Enums.FiltersAction.Move:
- sTemplate = 'SettingsFiltersActionValueAsFolders';
- break;
- case Enums.FiltersAction.Forward:
- sTemplate = 'SettingsFiltersActionWithValue';
- break;
- case Enums.FiltersAction.None:
- case Enums.FiltersAction.Discard:
- sTemplate = 'SettingsFiltersActionNoValue';
- break;
- }
-
- return sTemplate;
-
- }, this);
-}
-
-FilterModel.prototype.addCondition = function ()
-{
- this.conditions.push(new FilterConditionModel(this.conditions));
-};
-
-FilterModel.prototype.parse = function (oItem)
-{
- var bResult = false;
- if (oItem && 'Object/Filter' === oItem['@Object'])
- {
- this.name(Utils.pString(oItem['Name']));
-
- bResult = true;
- }
-
- return bResult;
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @param {string} iIndex
- * @param {string} sGuID
- * @param {string} sID
- * @param {string} sUserID
- * @param {string} sEmail
- * @param {boolean} bIsPrivate
- * @param {string} sArmor
- * @constructor
- */
-function OpenPgpKeyModel(iIndex, sGuID, sID, sUserID, sEmail, bIsPrivate, sArmor)
-{
- this.index = iIndex;
- this.id = sID;
- this.guid = sGuID;
- this.user = sUserID;
- this.email = sEmail;
- this.armor = sArmor;
- this.isPrivate = !!bIsPrivate;
-
- this.deleteAccess = ko.observable(false);
-}
-
-OpenPgpKeyModel.prototype.index = 0;
-OpenPgpKeyModel.prototype.id = '';
-OpenPgpKeyModel.prototype.guid = '';
-OpenPgpKeyModel.prototype.user = '';
-OpenPgpKeyModel.prototype.email = '';
-OpenPgpKeyModel.prototype.armor = '';
-OpenPgpKeyModel.prototype.isPrivate = false;
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends KnoinAbstractViewModel
- */
-function PopupsFolderClearViewModel()
-{
- KnoinAbstractViewModel.call(this, 'Popups', 'PopupsFolderClear');
-
- this.selectedFolder = ko.observable(null);
- this.clearingProcess = ko.observable(false);
- this.clearingError = ko.observable('');
-
- this.folderFullNameForClear = ko.computed(function () {
- var oFolder = this.selectedFolder();
- return oFolder ? oFolder.printableFullName() : '';
- }, this);
-
- this.folderNameForClear = ko.computed(function () {
- var oFolder = this.selectedFolder();
- return oFolder ? oFolder.localName() : '';
- }, this);
-
- this.dangerDescHtml = ko.computed(function () {
- return Utils.i18n('POPUPS_CLEAR_FOLDER/DANGER_DESC_HTML_1', {
- 'FOLDER': this.folderNameForClear()
- });
- }, this);
-
- this.clearCommand = Utils.createCommand(this, function () {
-
- var
- self = this,
- oFolderToClear = this.selectedFolder()
- ;
-
- if (oFolderToClear)
- {
- RL.data().message(null);
- RL.data().messageList([]);
-
- this.clearingProcess(true);
-
- RL.cache().setFolderHash(oFolderToClear.fullNameRaw, '');
- RL.remote().folderClear(function (sResult, oData) {
-
- self.clearingProcess(false);
- if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
- {
- RL.reloadMessageList(true);
- self.cancelCommand();
- }
- else
- {
- if (oData && oData.ErrorCode)
- {
- self.clearingError(Utils.getNotification(oData.ErrorCode));
- }
- else
- {
- self.clearingError(Utils.getNotification(Enums.Notification.MailServerError));
- }
- }
- }, oFolderToClear.fullNameRaw);
- }
-
- }, function () {
-
- var
- oFolder = this.selectedFolder(),
- bIsClearing = this.clearingProcess()
- ;
-
- return !bIsClearing && null !== oFolder;
-
- });
-
- Knoin.constructorEnd(this);
-}
-
-Utils.extendAsViewModel('PopupsFolderClearViewModel', PopupsFolderClearViewModel);
-
-PopupsFolderClearViewModel.prototype.clearPopup = function ()
-{
- this.clearingProcess(false);
- this.selectedFolder(null);
-};
-
-PopupsFolderClearViewModel.prototype.onShow = function (oFolder)
-{
- this.clearPopup();
- if (oFolder)
- {
- this.selectedFolder(oFolder);
- }
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends KnoinAbstractViewModel
- */
-function PopupsFolderCreateViewModel()
-{
- KnoinAbstractViewModel.call(this, 'Popups', 'PopupsFolderCreate');
-
- Utils.initOnStartOrLangChange(function () {
- this.sNoParentText = Utils.i18n('POPUPS_CREATE_FOLDER/SELECT_NO_PARENT');
- }, this);
-
- this.folderName = ko.observable('');
- this.folderName.focused = ko.observable(false);
-
- this.selectedParentValue = ko.observable(Consts.Values.UnuseOptionValue);
-
- this.parentFolderSelectList = ko.computed(function () {
-
- var
- oData = RL.data(),
- aTop = [],
- fDisableCallback = null,
- fVisibleCallback = null,
- aList = oData.folderList(),
- fRenameCallback = function (oItem) {
- return oItem ? (oItem.isSystemFolder() ? oItem.name() + ' ' + oItem.manageFolderSystemName() : oItem.name()) : '';
- }
- ;
-
- aTop.push(['', this.sNoParentText]);
-
- if ('' !== oData.namespace)
- {
- fDisableCallback = function (oItem)
- {
- return oData.namespace !== oItem.fullNameRaw.substr(0, oData.namespace.length);
- };
- }
-
- return RL.folderListOptionsBuilder([], aList, [], aTop, null, fDisableCallback, fVisibleCallback, fRenameCallback);
-
- }, this);
-
- // commands
- this.createFolder = Utils.createCommand(this, function () {
-
- var
- oData = RL.data(),
- sParentFolderName = this.selectedParentValue()
- ;
-
- if ('' === sParentFolderName && 1 < oData.namespace.length)
- {
- sParentFolderName = oData.namespace.substr(0, oData.namespace.length - 1);
- }
-
- oData.foldersCreating(true);
- RL.remote().folderCreate(function (sResult, oData) {
-
- RL.data().foldersCreating(false);
- if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
- {
- RL.folders();
- }
- else
- {
- RL.data().foldersListError(
- oData && oData.ErrorCode ? Utils.getNotification(oData.ErrorCode) : Utils.i18n('NOTIFICATIONS/CANT_CREATE_FOLDER'));
- }
-
- }, this.folderName(), sParentFolderName);
-
- this.cancelCommand();
-
- }, function () {
- return this.simpleFolderNameValidation(this.folderName());
- });
-
- this.defautOptionsAfterRender = Utils.defautOptionsAfterRender;
-
- Knoin.constructorEnd(this);
-}
-
-Utils.extendAsViewModel('PopupsFolderCreateViewModel', PopupsFolderCreateViewModel);
-
-PopupsFolderCreateViewModel.prototype.sNoParentText = '';
-
-PopupsFolderCreateViewModel.prototype.simpleFolderNameValidation = function (sName)
-{
- return (/^[^\\\/]+$/g).test(Utils.trim(sName));
-};
-
-PopupsFolderCreateViewModel.prototype.clearPopup = function ()
-{
- this.folderName('');
- this.selectedParentValue('');
- this.folderName.focused(false);
-};
-
-PopupsFolderCreateViewModel.prototype.onShow = function ()
-{
- this.clearPopup();
-};
-
-PopupsFolderCreateViewModel.prototype.onFocus = function ()
-{
- this.folderName.focused(true);
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends KnoinAbstractViewModel
- */
-function PopupsFolderSystemViewModel()
-{
- KnoinAbstractViewModel.call(this, 'Popups', 'PopupsFolderSystem');
-
- Utils.initOnStartOrLangChange(function () {
- this.sChooseOnText = Utils.i18n('POPUPS_SYSTEM_FOLDERS/SELECT_CHOOSE_ONE');
- this.sUnuseText = Utils.i18n('POPUPS_SYSTEM_FOLDERS/SELECT_UNUSE_NAME');
- }, this);
-
- this.notification = ko.observable('');
-
- this.folderSelectList = ko.computed(function () {
- return RL.folderListOptionsBuilder([], RL.data().folderList(), RL.data().folderListSystemNames(), [
- ['', this.sChooseOnText],
- [Consts.Values.UnuseOptionValue, this.sUnuseText]
- ]);
- }, this);
-
- var
- oData = RL.data(),
- self = this,
- fSaveSystemFolders = null,
- fCallback = null
- ;
-
- this.sentFolder = oData.sentFolder;
- this.draftFolder = oData.draftFolder;
- this.spamFolder = oData.spamFolder;
- this.trashFolder = oData.trashFolder;
- this.archiveFolder = oData.archiveFolder;
-
- fSaveSystemFolders = _.debounce(function () {
-
- RL.settingsSet('SentFolder', self.sentFolder());
- RL.settingsSet('DraftFolder', self.draftFolder());
- RL.settingsSet('SpamFolder', self.spamFolder());
- RL.settingsSet('TrashFolder', self.trashFolder());
- RL.settingsSet('ArchiveFolder', self.archiveFolder());
-
- RL.remote().saveSystemFolders(Utils.emptyFunction, {
- 'SentFolder': self.sentFolder(),
- 'DraftFolder': self.draftFolder(),
- 'SpamFolder': self.spamFolder(),
- 'TrashFolder': self.trashFolder(),
- 'ArchiveFolder': self.archiveFolder(),
- 'NullFolder': 'NullFolder'
- });
-
- }, 1000);
-
- fCallback = function () {
-
- RL.settingsSet('SentFolder', self.sentFolder());
- RL.settingsSet('DraftFolder', self.draftFolder());
- RL.settingsSet('SpamFolder', self.spamFolder());
- RL.settingsSet('TrashFolder', self.trashFolder());
- RL.settingsSet('ArchiveFolder', self.archiveFolder());
-
- fSaveSystemFolders();
};
- this.sentFolder.subscribe(fCallback);
- this.draftFolder.subscribe(fCallback);
- this.spamFolder.subscribe(fCallback);
- this.trashFolder.subscribe(fCallback);
- this.archiveFolder.subscribe(fCallback);
-
- this.defautOptionsAfterRender = Utils.defautOptionsAfterRender;
-
- Knoin.constructorEnd(this);
-}
-
-Utils.extendAsViewModel('PopupsFolderSystemViewModel', PopupsFolderSystemViewModel);
-
-PopupsFolderSystemViewModel.prototype.sChooseOnText = '';
-PopupsFolderSystemViewModel.prototype.sUnuseText = '';
-
-/**
- * @param {number=} iNotificationType = Enums.SetSystemFoldersNotification.None
- */
-PopupsFolderSystemViewModel.prototype.onShow = function (iNotificationType)
-{
- var sNotification = '';
-
- iNotificationType = Utils.isUnd(iNotificationType) ? Enums.SetSystemFoldersNotification.None : iNotificationType;
-
- switch (iNotificationType)
+ AbstractSettings.prototype.onHide = function ()
{
- case Enums.SetSystemFoldersNotification.Sent:
- sNotification = Utils.i18n('POPUPS_SYSTEM_FOLDERS/NOTIFICATION_SENT');
- break;
- case Enums.SetSystemFoldersNotification.Draft:
- sNotification = Utils.i18n('POPUPS_SYSTEM_FOLDERS/NOTIFICATION_DRAFTS');
- break;
- case Enums.SetSystemFoldersNotification.Spam:
- sNotification = Utils.i18n('POPUPS_SYSTEM_FOLDERS/NOTIFICATION_SPAM');
- break;
- case Enums.SetSystemFoldersNotification.Trash:
- sNotification = Utils.i18n('POPUPS_SYSTEM_FOLDERS/NOTIFICATION_TRASH');
- break;
- case Enums.SetSystemFoldersNotification.Archive:
- sNotification = Utils.i18n('POPUPS_SYSTEM_FOLDERS/NOTIFICATION_ARCHIVE');
- break;
- }
+ if (this.oCurrentSubScreen && this.oCurrentSubScreen.viewModelDom)
+ {
+ Utils.delegateRun(this.oCurrentSubScreen, 'onHide');
+ this.oCurrentSubScreen.viewModelDom.hide();
+ }
+ };
- this.notification(sNotification);
-};
+ AbstractSettings.prototype.onBuild = function ()
+ {
+ _.each(Globals.aViewModels['settings'], function (SettingsViewModel) {
+ if (SettingsViewModel && SettingsViewModel.__rlSettingsData &&
+ !_.find(Globals.aViewModels['settings-removed'], function (RemoveSettingsViewModel) {
+ return RemoveSettingsViewModel && RemoveSettingsViewModel === SettingsViewModel;
+ }))
+ {
+ this.menu.push({
+ 'route': SettingsViewModel.__rlSettingsData.Route,
+ 'label': SettingsViewModel.__rlSettingsData.Label,
+ 'selected': ko.observable(false),
+ 'disabled': !!_.find(Globals.aViewModels['settings-disabled'], function (DisabledSettingsViewModel) {
+ return DisabledSettingsViewModel && DisabledSettingsViewModel === SettingsViewModel;
+ })
+ });
+ }
+ }, this);
-
+ this.oViewModelPlace = $('#rl-content #rl-settings-subscreen');
+ };
+
+ AbstractSettings.prototype.routes = function ()
+ {
+ var
+ DefaultViewModel = _.find(Globals.aViewModels['settings'], function (SettingsViewModel) {
+ return SettingsViewModel && SettingsViewModel.__rlSettingsData && SettingsViewModel.__rlSettingsData['IsDefault'];
+ }),
+ sDefaultRoute = DefaultViewModel ? DefaultViewModel.__rlSettingsData['Route'] : 'general',
+ oRules = {
+ 'subname': /^(.*)$/,
+ 'normalize_': function (oRequest, oVals) {
+ oVals.subname = Utils.isUnd(oVals.subname) ? sDefaultRoute : Utils.pString(oVals.subname);
+ return [oVals.subname];
+ }
+ }
+ ;
+
+ return [
+ ['{subname}/', oRules],
+ ['{subname}', oRules],
+ ['', oRules]
+ ];
+ };
+
+ module.exports = AbstractSettings;
+
+}(module));
+},{"../Common/Globals.js":9,"../Common/LinkBuilder.js":10,"../Common/Utils.js":14,"../External/jquery.js":26,"../External/ko.js":28,"../External/underscore.js":31,"../Knoin/Knoin.js":33,"../Knoin/KnoinAbstractScreen.js":35}],44:[function(require,module,exports){
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-/**
- * @constructor
- * @extends KnoinAbstractViewModel
- */
-function PopupsComposeViewModel()
-{
- KnoinAbstractViewModel.call(this, 'Popups', 'PopupsCompose');
+(function (module) {
- this.oEditor = null;
- this.aDraftInfo = null;
- this.sInReplyTo = '';
- this.bFromDraft = false;
- this.bSkipNext = false;
- this.sReferences = '';
-
- this.bCapaAdditionalIdentities = RL.capa(Enums.Capa.AdditionalIdentities);
+ 'use strict';
var
- self = this,
- oRainLoopData = RL.data(),
- fCcAndBccCheckHelper = function (aValue) {
- if (false === self.showCcAndBcc() && 0 < aValue.length)
- {
- self.showCcAndBcc(true);
- }
- }
+ _ = require('../External/underscore.js'),
+ KnoinAbstractScreen = require('../Knoin/KnoinAbstractScreen.js')
;
- this.capaOpenPGP = oRainLoopData.capaOpenPGP;
+ /**
+ * @constructor
+ * @extends KnoinAbstractScreen
+ */
+ function LoginScreen()
+ {
+ var LoginViewModel = require('../ViewModels/LoginViewModel.js');
+ KnoinAbstractScreen.call(this, 'login', [LoginViewModel]);
+ }
- this.resizer = ko.observable(false).extend({'throttle': 50});
+ _.extend(LoginScreen.prototype, KnoinAbstractScreen.prototype);
- this.identitiesDropdownTrigger = ko.observable(false);
+ LoginScreen.prototype.onShow = function ()
+ {
+ var RL = require('../Boots/RainLoopApp.js');
+ RL.setTitle('');
+ };
- this.to = ko.observable('');
- this.to.focusTrigger = ko.observable(false);
- this.cc = ko.observable('');
- this.bcc = ko.observable('');
+ module.exports = LoginScreen;
- this.replyTo = ko.observable('');
- this.subject = ko.observable('');
- this.isHtml = ko.observable(false);
+}(module));
+},{"../Boots/RainLoopApp.js":4,"../External/underscore.js":31,"../Knoin/KnoinAbstractScreen.js":35,"../ViewModels/LoginViewModel.js":69}],45:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
- this.requestReadReceipt = ko.observable(false);
+(function (module) {
- this.sendError = ko.observable(false);
- this.sendSuccessButSaveError = ko.observable(false);
- this.savedError = ko.observable(false);
+ 'use strict';
- this.savedTime = ko.observable(0);
- this.savedOrSendingText = ko.observable('');
+ var
+ _ = require('../External/underscore.js'),
+ $html = require('../External/$html.js'),
+
+ Enums = require('../Common/Enums.js'),
+ Globals = require('../Common/Globals.js'),
+ Utils = require('../Common/Utils.js'),
+ Events = require('../Common/Events.js'),
- this.emptyToError = ko.observable(false);
- this.attachmentsInProcessError = ko.observable(false);
- this.showCcAndBcc = ko.observable(false);
+ KnoinAbstractScreen = require('../Knoin/KnoinAbstractScreen.js'),
- this.cc.subscribe(fCcAndBccCheckHelper, this);
- this.bcc.subscribe(fCcAndBccCheckHelper, this);
+ AppSettings = require('../Storages/AppSettings.js'),
+ Data = require('../Storages/WebMailDataStorage.js'),
+ Cache = require('../Storages/WebMailCacheStorage.js'),
+ Remote = require('../Storages/WebMailAjaxRemoteStorage.js')
+ ;
- this.draftFolder = ko.observable('');
- this.draftUid = ko.observable('');
- this.sending = ko.observable(false);
- this.saving = ko.observable(false);
- this.attachments = ko.observableArray([]);
+ /**
+ * @constructor
+ * @extends KnoinAbstractScreen
+ */
+ function MailBoxScreen()
+ {
+ var
+ MailBoxSystemDropDownViewModel = require('../ViewModels/MailBoxSystemDropDownViewModel.js'),
+ MailBoxFolderListViewModel = require('../ViewModels/MailBoxFolderListViewModel.js'),
+ MailBoxMessageListViewModel = require('../ViewModels/MailBoxMessageListViewModel.js'),
+ MailBoxMessageViewViewModel = require('../ViewModels/MailBoxMessageViewViewModel.js')
+ ;
- this.attachmentsInProcess = this.attachments.filter(function (oItem) {
- return oItem && '' === oItem.tempName();
- });
+ KnoinAbstractScreen.call(this, 'mailbox', [
+ MailBoxSystemDropDownViewModel,
+ MailBoxFolderListViewModel,
+ MailBoxMessageListViewModel,
+ MailBoxMessageViewViewModel
+ ]);
- this.attachmentsInReady = this.attachments.filter(function (oItem) {
- return oItem && '' !== oItem.tempName();
- });
+ this.oLastRoute = {};
+ }
- this.attachments.subscribe(function () {
- this.triggerForResize();
- }, this);
+ _.extend(MailBoxScreen.prototype, KnoinAbstractScreen.prototype);
- this.isDraftFolderMessage = ko.computed(function () {
- return '' !== this.draftFolder() && '' !== this.draftUid();
- }, this);
+ /**
+ * @type {Object}
+ */
+ MailBoxScreen.prototype.oLastRoute = {};
- this.composeUploaderButton = ko.observable(null);
- this.composeUploaderDropPlace = ko.observable(null);
- this.dragAndDropEnabled = ko.observable(false);
- this.dragAndDropOver = ko.observable(false).extend({'throttle': 1});
- this.dragAndDropVisible = ko.observable(false).extend({'throttle': 1});
- this.attacheMultipleAllowed = ko.observable(false);
- this.addAttachmentEnabled = ko.observable(false);
+ MailBoxScreen.prototype.setNewTitle = function ()
+ {
+ var
+ RL = require('../Boots/RainLoopApp.js'),
+ sEmail = Data.accountEmail(),
+ nFoldersInboxUnreadCount = Data.foldersInboxUnreadCount()
+ ;
+
+ RL.setTitle(('' === sEmail ? '' :
+ (0 < nFoldersInboxUnreadCount ? '(' + nFoldersInboxUnreadCount + ') ' : ' ') + sEmail + ' - ') + Utils.i18n('TITLES/MAILBOX'));
+ };
- this.composeEditorArea = ko.observable(null);
+ MailBoxScreen.prototype.onShow = function ()
+ {
+ this.setNewTitle();
+ Globals.keyScope(Enums.KeyState.MessageList);
+ };
- this.identities = RL.data().identities;
- this.defaultIdentityID = RL.data().defaultIdentityID;
- this.currentIdentityID = ko.observable('');
+ /**
+ * @param {string} sFolderHash
+ * @param {number} iPage
+ * @param {string} sSearch
+ * @param {boolean=} bPreview = false
+ */
+ MailBoxScreen.prototype.onRoute = function (sFolderHash, iPage, sSearch, bPreview)
+ {
+ var RL = require('../Boots/RainLoopApp.js');
+ if (Utils.isUnd(bPreview) ? false : !!bPreview)
+ {
+ if (Enums.Layout.NoPreview === Data.layout() && !Data.message())
+ {
+ RL.historyBack();
+ }
+ }
+ else
+ {
+ var
+ sFolderFullNameRaw = Cache.getFolderFullNameRaw(sFolderHash),
+ oFolder = Cache.getFolderFromCacheList(sFolderFullNameRaw)
+ ;
- this.currentIdentityString = ko.observable('');
- this.currentIdentityResultEmail = ko.observable('');
+ if (oFolder)
+ {
+ Data
+ .currentFolder(oFolder)
+ .messageListPage(iPage)
+ .messageListSearch(sSearch)
+ ;
- this.identitiesOptions = ko.computed(function () {
+ if (Enums.Layout.NoPreview === Data.layout() && Data.message())
+ {
+ Data.message(null);
+ }
- var aList = [{
- 'optValue': oRainLoopData.accountEmail(),
- 'optText': this.formattedFrom(false)
- }];
+ RL.reloadMessageList();
+ }
+ }
+ };
- _.each(oRainLoopData.identities(), function (oItem) {
- aList.push({
- 'optValue': oItem.id,
- 'optText': oItem.formattedNameForCompose()
- });
+ MailBoxScreen.prototype.onStart = function ()
+ {
+ var
+ RL = require('../Boots/RainLoopApp.js'),
+ fResizeFunction = function () {
+ Utils.windowResize();
+ }
+ ;
+
+ if (AppSettings.capa(Enums.Capa.AdditionalAccounts) || AppSettings.capa(Enums.Capa.AdditionalIdentities))
+ {
+ RL.accountsAndIdentities();
+ }
+
+ _.delay(function () {
+ if ('INBOX' !== Data.currentFolderFullNameRaw())
+ {
+ RL.folderInformation('INBOX');
+ }
+ }, 1000);
+
+ _.delay(function () {
+ RL.quota();
+ }, 5000);
+
+ _.delay(function () {
+ Remote.appDelayStart(Utils.emptyFunction);
+ }, 35000);
+
+ $html.toggleClass('rl-no-preview-pane', Enums.Layout.NoPreview === Data.layout());
+
+ Data.folderList.subscribe(fResizeFunction);
+ Data.messageList.subscribe(fResizeFunction);
+ Data.message.subscribe(fResizeFunction);
+
+ Data.layout.subscribe(function (nValue) {
+ $html.toggleClass('rl-no-preview-pane', Enums.Layout.NoPreview === nValue);
});
- return aList;
+ Events.sub('mailbox.inbox-unread-count', function (nCount) {
+ Data.foldersInboxUnreadCount(nCount)
+ });
- }, this);
+ Data.foldersInboxUnreadCount.subscribe(function () {
+ this.setNewTitle();
+ }, this);
+ };
- ko.computed(function () {
-
- var
- sResult = '',
- sResultEmail = '',
- oItem = null,
- aList = this.identities(),
- sID = this.currentIdentityID()
- ;
-
- if (this.bCapaAdditionalIdentities && sID && sID !== RL.data().accountEmail())
- {
- oItem = _.find(aList, function (oItem) {
- return oItem && sID === oItem['id'];
- });
-
- sResult = oItem ? oItem.formattedNameForCompose() : '';
- sResultEmail = oItem ? oItem.formattedNameForEmail() : '';
-
- if ('' === sResult && aList[0])
- {
- this.currentIdentityID(aList[0]['id']);
- return '';
- }
- }
-
- if ('' === sResult)
- {
- sResult = this.formattedFrom(false);
- sResultEmail = this.formattedFrom(true);
- }
-
- this.currentIdentityString(sResult);
- this.currentIdentityResultEmail(sResultEmail);
-
- return sResult;
-
- }, this);
-
- this.to.subscribe(function (sValue) {
- if (this.emptyToError() && 0 < sValue.length)
- {
- this.emptyToError(false);
- }
- }, this);
-
- this.attachmentsInProcess.subscribe(function (aValue) {
- if (this.attachmentsInProcessError() && Utils.isArray(aValue) && 0 === aValue.length)
- {
- this.attachmentsInProcessError(false);
- }
- }, this);
-
- this.editorResizeThrottle = _.throttle(_.bind(this.editorResize, this), 100);
-
- this.resizer.subscribe(function () {
- this.editorResizeThrottle();
- }, this);
-
- this.canBeSendedOrSaved = ko.computed(function () {
- return !this.sending() && !this.saving();
- }, this);
-
- this.deleteCommand = Utils.createCommand(this, function () {
-
- RL.deleteMessagesFromFolderWithoutCheck(this.draftFolder(), [this.draftUid()]);
- kn.hideScreenPopup(PopupsComposeViewModel);
-
- }, function () {
- return this.isDraftFolderMessage();
- });
-
- this.sendMessageResponse = _.bind(this.sendMessageResponse, this);
- this.saveMessageResponse = _.bind(this.saveMessageResponse, this);
-
- this.sendCommand = Utils.createCommand(this, function () {
- var
- sTo = Utils.trim(this.to()),
- sSentFolder = RL.data().sentFolder(),
- aFlagsCache = []
- ;
-
- if (0 < this.attachmentsInProcess().length)
- {
- this.attachmentsInProcessError(true);
- }
- else if (0 === sTo.length)
- {
- this.emptyToError(true);
- }
- else
- {
- if (RL.data().replySameFolder())
- {
- if (Utils.isArray(this.aDraftInfo) && 3 === this.aDraftInfo.length && Utils.isNormal(this.aDraftInfo[2]) && 0 < this.aDraftInfo[2].length)
- {
- sSentFolder = this.aDraftInfo[2];
- }
- }
-
- if ('' === sSentFolder)
- {
- kn.showScreenPopup(PopupsFolderSystemViewModel, [Enums.SetSystemFoldersNotification.Sent]);
- }
- else
- {
- this.sendError(false);
- this.sending(true);
-
- if (Utils.isArray(this.aDraftInfo) && 3 === this.aDraftInfo.length)
- {
- aFlagsCache = RL.cache().getMessageFlagsFromCache(this.aDraftInfo[2], this.aDraftInfo[1]);
- if (aFlagsCache)
- {
- if ('forward' === this.aDraftInfo[0])
- {
- aFlagsCache[3] = true;
- }
- else
- {
- aFlagsCache[2] = true;
- }
-
- RL.cache().setMessageFlagsToCache(this.aDraftInfo[2], this.aDraftInfo[1], aFlagsCache);
- RL.reloadFlagsCurrentMessageListAndMessageFromCache();
- RL.cache().setFolderHash(this.aDraftInfo[2], '');
- }
- }
-
- sSentFolder = Consts.Values.UnuseOptionValue === sSentFolder ? '' : sSentFolder;
-
- RL.cache().setFolderHash(this.draftFolder(), '');
- RL.cache().setFolderHash(sSentFolder, '');
-
- RL.remote().sendMessage(
- this.sendMessageResponse,
- this.draftFolder(),
- this.draftUid(),
- sSentFolder,
- this.currentIdentityResultEmail(),
- sTo,
- this.cc(),
- this.bcc(),
- this.subject(),
- this.oEditor ? this.oEditor.isHtml() : false,
- this.oEditor ? this.oEditor.getData(true) : '',
- this.prepearAttachmentsForSendOrSave(),
- this.aDraftInfo,
- this.sInReplyTo,
- this.sReferences,
- this.requestReadReceipt()
- );
- }
- }
- }, this.canBeSendedOrSaved);
-
- this.saveCommand = Utils.createCommand(this, function () {
-
- if (RL.data().draftFolderNotEnabled())
- {
- kn.showScreenPopup(PopupsFolderSystemViewModel, [Enums.SetSystemFoldersNotification.Draft]);
- }
- else
- {
- this.savedError(false);
- this.saving(true);
-
- this.bSkipNext = true;
-
- RL.cache().setFolderHash(RL.data().draftFolder(), '');
-
- RL.remote().saveMessage(
- this.saveMessageResponse,
- this.draftFolder(),
- this.draftUid(),
- RL.data().draftFolder(),
- this.currentIdentityResultEmail(),
- this.to(),
- this.cc(),
- this.bcc(),
- this.subject(),
- this.oEditor ? this.oEditor.isHtml() : false,
- this.oEditor ? this.oEditor.getData(true) : '',
- this.prepearAttachmentsForSendOrSave(),
- this.aDraftInfo,
- this.sInReplyTo,
- this.sReferences
- );
- }
-
- }, this.canBeSendedOrSaved);
-
- RL.sub('interval.1m', function () {
- if (this.modalVisibility() && !RL.data().draftFolderNotEnabled() && !this.isEmptyForm(false) &&
- !this.bSkipNext && !this.saving() && !this.sending() && !this.savedError())
- {
- this.bSkipNext = false;
- this.saveCommand();
- }
- }, this);
-
- this.showCcAndBcc.subscribe(function () {
- this.triggerForResize();
- }, this);
-
- this.dropboxEnabled = ko.observable(!!RL.settingsGet('DropboxApiKey'));
-
- this.dropboxCommand = Utils.createCommand(this, function () {
-
- if (window.Dropbox)
- {
- window.Dropbox.choose({
- //'iframe': true,
- 'success': function(aFiles) {
-
- if (aFiles && aFiles[0] && aFiles[0]['link'])
- {
- self.addDropboxAttachment(aFiles[0]);
- }
- },
- 'linkType': "direct",
- 'multiselect': false
- });
- }
-
- return true;
-
- }, function () {
- return this.dropboxEnabled();
- });
-
- this.driveEnabled = ko.observable(Globals.bXMLHttpRequestSupported &&
- !!RL.settingsGet('GoogleClientID') && !!RL.settingsGet('GoogleApiKey'));
-
- this.driveVisible = ko.observable(false);
-
- this.driveCommand = Utils.createCommand(this, function () {
-
- this.driveOpenPopup();
- return true;
-
- }, function () {
- return this.driveEnabled();
- });
-
- this.driveCallback = _.bind(this.driveCallback, this);
-
- this.bDisabeCloseOnEsc = true;
- this.sDefaultKeyScope = Enums.KeyState.Compose;
-
- this.tryToClosePopup = _.debounce(_.bind(this.tryToClosePopup, this), 200);
-
- Knoin.constructorEnd(this);
-}
-
-Utils.extendAsViewModel('PopupsComposeViewModel', PopupsComposeViewModel);
-
-PopupsComposeViewModel.prototype.openOpenPgpPopup = function ()
-{
- if (this.capaOpenPGP() && this.oEditor && !this.oEditor.isHtml())
+ /**
+ * @return {Array}
+ */
+ MailBoxScreen.prototype.routes = function ()
{
- var self = this;
- kn.showScreenPopup(PopupsComposeOpenPgpViewModel, [
- function (sResult) {
- self.editor(function (oEditor) {
- oEditor.setPlain(sResult);
- });
+ var
+ fNormP = function () {
+ return ['Inbox', 1, '', true];
},
- this.oEditor.getData(),
- this.currentIdentityResultEmail(),
- this.to(),
- this.cc(),
- this.bcc()
- ]);
- }
-};
+ fNormS = function (oRequest, oVals) {
+ oVals[0] = Utils.pString(oVals[0]);
+ oVals[1] = Utils.pInt(oVals[1]);
+ oVals[1] = 0 >= oVals[1] ? 1 : oVals[1];
+ oVals[2] = Utils.pString(oVals[2]);
-PopupsComposeViewModel.prototype.reloadDraftFolder = function ()
-{
- var sDraftFolder = RL.data().draftFolder();
- if ('' !== sDraftFolder)
- {
- RL.cache().setFolderHash(sDraftFolder, '');
- if (RL.data().currentFolderFullNameRaw() === sDraftFolder)
- {
- RL.reloadMessageList(true);
- }
- else
- {
- RL.folderInformation(sDraftFolder);
- }
- }
-};
+ if ('' === oRequest)
+ {
+ oVals[0] = 'Inbox';
+ oVals[1] = 1;
+ }
-PopupsComposeViewModel.prototype.findIdentityIdByMessage = function (sComposeType, oMessage)
-{
- var
- oIDs = {},
- sResult = '',
- fFindHelper = function (oItem) {
- if (oItem && oItem.email && oIDs[oItem.email])
- {
- sResult = oIDs[oItem.email];
- return true;
+ return [decodeURI(oVals[0]), oVals[1], decodeURI(oVals[2]), false];
+ },
+ fNormD = function (oRequest, oVals) {
+ oVals[0] = Utils.pString(oVals[0]);
+ oVals[1] = Utils.pString(oVals[1]);
+
+ if ('' === oRequest)
+ {
+ oVals[0] = 'Inbox';
+ }
+
+ return [decodeURI(oVals[0]), 1, decodeURI(oVals[1]), false];
}
+ ;
- return false;
- }
+ return [
+ [/^([a-zA-Z0-9]+)\/p([1-9][0-9]*)\/(.+)\/?$/, {'normalize_': fNormS}],
+ [/^([a-zA-Z0-9]+)\/p([1-9][0-9]*)$/, {'normalize_': fNormS}],
+ [/^([a-zA-Z0-9]+)\/(.+)\/?$/, {'normalize_': fNormD}],
+ [/^message-preview$/, {'normalize_': fNormP}],
+ [/^([^\/]*)$/, {'normalize_': fNormS}]
+ ];
+ };
+
+ module.exports = MailBoxScreen;
+
+}(module));
+},{"../Boots/RainLoopApp.js":4,"../Common/Enums.js":7,"../Common/Events.js":8,"../Common/Globals.js":9,"../Common/Utils.js":14,"../External/$html.js":17,"../External/underscore.js":31,"../Knoin/KnoinAbstractScreen.js":35,"../Storages/AppSettings.js":61,"../Storages/WebMailAjaxRemoteStorage.js":65,"../Storages/WebMailCacheStorage.js":66,"../Storages/WebMailDataStorage.js":67,"../ViewModels/MailBoxFolderListViewModel.js":70,"../ViewModels/MailBoxMessageListViewModel.js":71,"../ViewModels/MailBoxMessageViewViewModel.js":72,"../ViewModels/MailBoxSystemDropDownViewModel.js":73}],46:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ _ = require('../External/underscore.js'),
+
+ Enums = require('../Common/Enums.js'),
+ Utils = require('../Common/Utils.js'),
+ Globals = require('../Common/Globals.js'),
+
+ AbstractSettings = require('./AbstractSettings.js')
;
- if (this.bCapaAdditionalIdentities)
+ /**
+ * @constructor
+ * @extends AbstractSettings
+ */
+ function SettingsScreen()
{
- _.each(this.identities(), function (oItem) {
- oIDs[oItem.email()] = oItem['id'];
+ var
+ RL = require('../Boots/RainLoopApp.js'),
+
+ SettingsSystemDropDownViewModel = require('../ViewModels/SettingsSystemDropDownViewModel.js'),
+ SettingsMenuViewModel = require('../ViewModels/SettingsMenuViewModel.js'),
+ SettingsPaneViewModel = require('../ViewModels/SettingsPaneViewModel.js')
+ ;
+
+ AbstractSettings.call(this, [
+ SettingsSystemDropDownViewModel,
+ SettingsMenuViewModel,
+ SettingsPaneViewModel
+ ]);
+
+ Utils.initOnStartOrLangChange(function () {
+ this.sSettingsTitle = Utils.i18n('TITLES/SETTINGS');
+ }, this, function () {
+ RL.setTitle(this.sSettingsTitle);
});
}
- oIDs[RL.data().accountEmail()] = RL.data().accountEmail();
+ _.extend(SettingsScreen.prototype, AbstractSettings.prototype);
- if (oMessage)
+ SettingsScreen.prototype.onShow = function ()
{
- switch (sComposeType)
- {
- case Enums.ComposeType.Empty:
- break;
- case Enums.ComposeType.Reply:
- case Enums.ComposeType.ReplyAll:
- case Enums.ComposeType.Forward:
- case Enums.ComposeType.ForwardAsAttachment:
- _.find(_.union(oMessage.to, oMessage.cc, oMessage.bcc, oMessage.deliveredTo), fFindHelper);
- break;
- case Enums.ComposeType.Draft:
- _.find(_.union(oMessage.from, oMessage.replyTo), fFindHelper);
- break;
- }
- }
+ var RL = require('../Boots/RainLoopApp.js');
+
+ RL.setTitle(this.sSettingsTitle);
+ Globals.keyScope(Enums.KeyState.Settings);
+ };
- if ('' === sResult)
- {
- sResult = this.defaultIdentityID();
- }
+ module.exports = SettingsScreen;
- if ('' === sResult)
- {
- sResult = RL.data().accountEmail();
- }
+}(module));
+},{"../Boots/RainLoopApp.js":4,"../Common/Enums.js":7,"../Common/Globals.js":9,"../Common/Utils.js":14,"../External/underscore.js":31,"../ViewModels/SettingsMenuViewModel.js":89,"../ViewModels/SettingsPaneViewModel.js":90,"../ViewModels/SettingsSystemDropDownViewModel.js":91,"./AbstractSettings.js":43}],47:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
- return sResult;
-};
+(function (module) {
-PopupsComposeViewModel.prototype.selectIdentity = function (oIdentity)
-{
- if (oIdentity)
- {
- this.currentIdentityID(oIdentity.optValue);
- }
-};
+ 'use strict';
-/**
- *
- * @param {boolean=} bHeaderResult = false
- * @returns {string}
- */
-PopupsComposeViewModel.prototype.formattedFrom = function (bHeaderResult)
-{
var
- sDisplayName = RL.data().displayName(),
- sEmail = RL.data().accountEmail()
+ window = require('../External/window.js'),
+ _ = require('../External/underscore.js'),
+ ko = require('../External/ko.js'),
+
+ Enums = require('../Common/Enums.js'),
+ Utils = require('../Common/Utils.js'),
+ LinkBuilder = require('../Common/LinkBuilder.js'),
+
+ Data = require('../Storages/WebMailDataStorage.js'),
+ Remote = require('../Storages/WebMailAjaxRemoteStorage.js'),
+
+ kn = require('../Knoin/Knoin.js'),
+ PopupsAddAccountViewModel = require('../ViewModels/Popups/PopupsAddAccountViewModel.js')
;
- return '' === sDisplayName ? sEmail :
- ((Utils.isUnd(bHeaderResult) ? false : !!bHeaderResult) ?
- '"' + Utils.quoteName(sDisplayName) + '" <' + sEmail + '>' :
- sDisplayName + ' (' + sEmail + ')')
- ;
-};
-
-PopupsComposeViewModel.prototype.sendMessageResponse = function (sResult, oData)
-{
- var
- bResult = false,
- sMessage = ''
- ;
-
- this.sending(false);
-
- if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ /**
+ * @constructor
+ */
+ function SettingsAccounts()
{
- bResult = true;
- if (this.modalVisibility())
- {
- Utils.delegateRun(this, 'closeCommand');
- }
+ this.accounts = Data.accounts;
+
+ this.processText = ko.computed(function () {
+ return Data.accountsLoading() ? Utils.i18n('SETTINGS_ACCOUNTS/LOADING_PROCESS') : '';
+ }, this);
+
+ this.visibility = ko.computed(function () {
+ return '' === this.processText() ? 'hidden' : 'visible';
+ }, this);
+
+ this.accountForDeletion = ko.observable(null).extend({'falseTimeout': 3000}).extend({'toggleSubscribe': [this,
+ function (oPrev) {
+ if (oPrev)
+ {
+ oPrev.deleteAccess(false);
+ }
+ }, function (oNext) {
+ if (oNext)
+ {
+ oNext.deleteAccess(true);
+ }
+ }
+ ]});
}
- if (this.modalVisibility() && !bResult)
+ SettingsAccounts.prototype.addNewAccount = function ()
{
- if (oData && Enums.Notification.CantSaveMessage === oData.ErrorCode)
+ kn.showScreenPopup(PopupsAddAccountViewModel);
+ };
+
+ /**
+ * @param {AccountModel} oAccountToRemove
+ */
+ SettingsAccounts.prototype.deleteAccount = function (oAccountToRemove)
+ {
+ if (oAccountToRemove && oAccountToRemove.deleteAccess())
{
- this.sendSuccessButSaveError(true);
- window.alert(Utils.trim(Utils.i18n('COMPOSE/SAVED_ERROR_ON_SEND')));
+ this.accountForDeletion(null);
+
+ var
+ RL = require('../Boots/RainLoopApp.js'),
+ fRemoveAccount = function (oAccount) {
+ return oAccountToRemove === oAccount;
+ }
+ ;
+
+ if (oAccountToRemove)
+ {
+ this.accounts.remove(fRemoveAccount);
+
+ Remote.accountDelete(function (sResult, oData) {
+
+ if (Enums.StorageResultType.Success === sResult && oData &&
+ oData.Result && oData.Reload)
+ {
+ kn.routeOff();
+ kn.setHash(LinkBuilder.root(), true);
+ kn.routeOff();
+
+ _.defer(function () {
+ window.location.reload();
+ });
+ }
+ else
+ {
+ RL.accountsAndIdentities();
+ }
+
+ }, oAccountToRemove.email);
+ }
+ }
+ };
+
+ module.exports = SettingsAccounts;
+
+}(module));
+},{"../Boots/RainLoopApp.js":4,"../Common/Enums.js":7,"../Common/LinkBuilder.js":10,"../Common/Utils.js":14,"../External/ko.js":28,"../External/underscore.js":31,"../External/window.js":32,"../Knoin/Knoin.js":33,"../Storages/WebMailAjaxRemoteStorage.js":65,"../Storages/WebMailDataStorage.js":67,"../ViewModels/Popups/PopupsAddAccountViewModel.js":74}],48:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ _ = require('../External/underscore.js'),
+ ko = require('../External/ko.js'),
+
+ Enums = require('../Common/Enums.js'),
+ Utils = require('../Common/Utils.js'),
+
+ Remote = require('../Storages/WebMailAjaxRemoteStorage.js')
+ ;
+
+ /**
+ * @constructor
+ */
+ function SettingsChangePassword()
+ {
+ this.changeProcess = ko.observable(false);
+
+ this.errorDescription = ko.observable('');
+ this.passwordMismatch = ko.observable(false);
+ this.passwordUpdateError = ko.observable(false);
+ this.passwordUpdateSuccess = ko.observable(false);
+
+ this.currentPassword = ko.observable('');
+ this.currentPassword.error = ko.observable(false);
+ this.newPassword = ko.observable('');
+ this.newPassword2 = ko.observable('');
+
+ this.currentPassword.subscribe(function () {
+ this.passwordUpdateError(false);
+ this.passwordUpdateSuccess(false);
+ this.currentPassword.error(false);
+ }, this);
+
+ this.newPassword.subscribe(function () {
+ this.passwordUpdateError(false);
+ this.passwordUpdateSuccess(false);
+ this.passwordMismatch(false);
+ }, this);
+
+ this.newPassword2.subscribe(function () {
+ this.passwordUpdateError(false);
+ this.passwordUpdateSuccess(false);
+ this.passwordMismatch(false);
+ }, this);
+
+ this.saveNewPasswordCommand = Utils.createCommand(this, function () {
+
+ if (this.newPassword() !== this.newPassword2())
+ {
+ this.passwordMismatch(true);
+ this.errorDescription(Utils.i18n('SETTINGS_CHANGE_PASSWORD/ERROR_PASSWORD_MISMATCH'));
+ }
+ else
+ {
+ this.changeProcess(true);
+
+ this.passwordUpdateError(false);
+ this.passwordUpdateSuccess(false);
+ this.currentPassword.error(false);
+ this.passwordMismatch(false);
+ this.errorDescription('');
+
+ Remote.changePassword(this.onChangePasswordResponse, this.currentPassword(), this.newPassword());
+ }
+
+ }, function () {
+ return !this.changeProcess() && '' !== this.currentPassword() &&
+ '' !== this.newPassword() && '' !== this.newPassword2();
+ });
+
+ this.onChangePasswordResponse = _.bind(this.onChangePasswordResponse, this);
+ }
+
+ SettingsChangePassword.prototype.onHide = function ()
+ {
+ this.changeProcess(false);
+ this.currentPassword('');
+ this.newPassword('');
+ this.newPassword2('');
+ this.errorDescription('');
+ this.passwordMismatch(false);
+ this.currentPassword.error(false);
+ };
+
+ SettingsChangePassword.prototype.onChangePasswordResponse = function (sResult, oData)
+ {
+ this.changeProcess(false);
+ this.passwordMismatch(false);
+ this.errorDescription('');
+ this.currentPassword.error(false);
+
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ {
+ this.currentPassword('');
+ this.newPassword('');
+ this.newPassword2('');
+
+ this.passwordUpdateSuccess(true);
+ this.currentPassword.error(false);
}
else
{
- sMessage = Utils.getNotification(oData && oData.ErrorCode ? oData.ErrorCode : Enums.Notification.CantSendMessage,
- oData && oData.ErrorMessage ? oData.ErrorMessage : '');
+ if (oData && Enums.Notification.CurrentPasswordIncorrect === oData.ErrorCode)
+ {
+ this.currentPassword.error(true);
+ }
- this.sendError(true);
- window.alert(sMessage || Utils.getNotification(Enums.Notification.CantSendMessage));
+ this.passwordUpdateError(true);
+ this.errorDescription(oData && oData.ErrorCode ? Utils.getNotification(oData.ErrorCode) :
+ Utils.getNotification(Enums.Notification.CouldNotSaveNewPassword));
}
- }
+ };
- this.reloadDraftFolder();
-};
+ module.exports = SettingsChangePassword;
+
+}(module));
+},{"../Common/Enums.js":7,"../Common/Utils.js":14,"../External/ko.js":28,"../External/underscore.js":31,"../Storages/WebMailAjaxRemoteStorage.js":65}],49:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
-PopupsComposeViewModel.prototype.saveMessageResponse = function (sResult, oData)
-{
var
- bResult = false,
- oMessage = null
+ ko = require('../External/ko.js'),
+
+ Utils = require('../Common/Utils.js'),
+
+ Remote = require('../Storages/WebMailAjaxRemoteStorage.js'),
+
+ Data = require('../Storages/WebMailDataStorage.js')
;
- this.saving(false);
-
- if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ /**
+ * @constructor
+ */
+ function SettingsContacts()
{
- if (oData.Result.NewFolder && oData.Result.NewUid)
- {
- if (this.bFromDraft)
- {
- oMessage = RL.data().message();
- if (oMessage && this.draftFolder() === oMessage.folderFullNameRaw && this.draftUid() === oMessage.uid)
- {
- RL.data().message(null);
- }
- }
+ this.contactsAutosave = Data.contactsAutosave;
- this.draftFolder(oData.Result.NewFolder);
- this.draftUid(oData.Result.NewUid);
+ this.allowContactsSync = Data.allowContactsSync;
+ this.enableContactsSync = Data.enableContactsSync;
+ this.contactsSyncUrl = Data.contactsSyncUrl;
+ this.contactsSyncUser = Data.contactsSyncUser;
+ this.contactsSyncPass = Data.contactsSyncPass;
- if (this.modalVisibility())
- {
- this.savedTime(Math.round((new window.Date()).getTime() / 1000));
+ this.saveTrigger = ko.computed(function () {
+ return [
+ this.enableContactsSync() ? '1' : '0',
+ this.contactsSyncUrl(),
+ this.contactsSyncUser(),
+ this.contactsSyncPass()
+ ].join('|');
+ }, this).extend({'throttle': 500});
- this.savedOrSendingText(
- 0 < this.savedTime() ? Utils.i18n('COMPOSE/SAVED_TIME', {
- 'TIME': moment.unix(this.savedTime() - 1).format('LT')
- }) : ''
- );
-
- bResult = true;
-
- if (this.bFromDraft)
- {
- RL.cache().setFolderHash(this.draftFolder(), '');
- }
- }
- }
+ this.saveTrigger.subscribe(function () {
+ Remote.saveContactsSyncData(null,
+ this.enableContactsSync(),
+ this.contactsSyncUrl(),
+ this.contactsSyncUser(),
+ this.contactsSyncPass()
+ );
+ }, this);
}
- if (!this.modalVisibility() && !bResult)
+ SettingsContacts.prototype.onBuild = function ()
{
- this.savedError(true);
- this.savedOrSendingText(Utils.getNotification(Enums.Notification.CantSaveMessage));
- }
+ Data.contactsAutosave.subscribe(function (bValue) {
+ Remote.saveSettings(Utils.emptyFunction, {
+ 'ContactsAutosave': bValue ? '1' : '0'
+ });
+ });
+ };
- this.reloadDraftFolder();
-};
+ module.exports = SettingsContacts;
-PopupsComposeViewModel.prototype.onHide = function ()
-{
- this.reset();
- kn.routeOn();
-};
+}(module));
+},{"../Common/Utils.js":14,"../External/ko.js":28,"../Storages/WebMailAjaxRemoteStorage.js":65,"../Storages/WebMailDataStorage.js":67}],50:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-/**
- * @param {string} sSignature
- * @param {string=} sFrom
- * @param {string=} sData
- * @param {string=} sComposeType
- * @return {string}
- */
-PopupsComposeViewModel.prototype.convertSignature = function (sSignature, sFrom, sData, sComposeType)
-{
- var bHtml = false, bData = false;
- if ('' !== sSignature)
- {
- if (':HTML:' === sSignature.substr(0, 6))
- {
- bHtml = true;
- sSignature = sSignature.substr(6);
- }
+(function (module) {
- sSignature = sSignature.replace(/[\r]/, '');
-
- sFrom = Utils.pString(sFrom);
- if ('' !== sFrom)
- {
- sSignature = sSignature.replace(/{{FROM}}/, sFrom);
- }
-
- sSignature = sSignature.replace(/[\s]{1,2}{{FROM}}/, '{{FROM}}');
-
- sSignature = sSignature.replace(/{{FROM}}/, '');
- sSignature = sSignature.replace(/{{DATE}}/, moment().format('llll'));
-
- if (sData && Enums.ComposeType.Empty === sComposeType &&
- -1 < sSignature.indexOf('{{DATA}}'))
- {
- bData = true;
- sSignature = sSignature.replace('{{DATA}}', sData);
- }
-
- sSignature = sSignature.replace(/{{DATA}}/, '');
-
- if (!bHtml)
- {
- sSignature = Utils.convertPlainTextToHtml(sSignature);
- }
- }
-
- if (sData && !bData)
- {
- switch (sComposeType)
- {
- case Enums.ComposeType.Empty:
- sSignature = sData + '
' + sSignature;
- break;
- default:
- sSignature = sSignature + '
' + sData;
- break;
- }
- }
-
- return sSignature;
-};
-
-PopupsComposeViewModel.prototype.editor = function (fOnInit)
-{
- if (fOnInit)
- {
- var self = this;
- if (!this.oEditor && this.composeEditorArea())
- {
- _.delay(function () {
- self.oEditor = new NewHtmlEditorWrapper(self.composeEditorArea(), null, function () {
- fOnInit(self.oEditor);
- }, function (bHtml) {
- self.isHtml(!!bHtml);
- });
- }, 300);
- }
- else if (this.oEditor)
- {
- fOnInit(this.oEditor);
- }
- }
-};
-
-/**
- * @param {string=} sType = Enums.ComposeType.Empty
- * @param {?MessageModel|Array=} oMessageOrArray = null
- * @param {Array=} aToEmails = null
- * @param {string=} sCustomSubject = null
- * @param {string=} sCustomPlainText = null
- */
-PopupsComposeViewModel.prototype.onShow = function (sType, oMessageOrArray, aToEmails, sCustomSubject, sCustomPlainText)
-{
- kn.routeOff();
+ 'use strict';
var
- self = this,
- sFrom = '',
- sTo = '',
- sCc = '',
- sDate = '',
- sSubject = '',
- oText = null,
- oSubText = null,
- sText = '',
- sReplyTitle = '',
- aResplyAllParts = [],
- oExcludeEmail = {},
- mEmail = RL.data().accountEmail(),
- sSignature = RL.data().signature(),
- bSignatureToAll = RL.data().signatureToAll(),
- aDownloads = [],
- aDraftInfo = null,
- oMessage = null,
- sComposeType = sType || Enums.ComposeType.Empty,
- fEmailArrayToStringLineHelper = function (aList, bFriendly) {
+ ko = require('../External/ko.js'),
+ Utils = require('../Common/Utils.js'),
+ kn = require('../Knoin/Knoin.js'),
+ PopupsFilterViewModel = require('../ViewModels/Popups/PopupsFilterViewModel.js')
+ ;
+
+ /**
+ * @constructor
+ */
+ function SettingsFilters()
+ {
+ this.filters = ko.observableArray([]);
+ this.filters.loading = ko.observable(false);
+
+ this.filters.subscribe(function () {
+ Utils.windowResize();
+ });
+ }
+
+ SettingsFilters.prototype.deleteFilter = function (oFilter)
+ {
+ this.filters.remove(oFilter);
+ };
+
+ SettingsFilters.prototype.addFilter = function ()
+ {
+ kn.showScreenPopup(PopupsFilterViewModel, [new FilterModel()]);
+ };
+
+ module.exports = SettingsFilters;
+
+}(module));
+},{"../Common/Utils.js":14,"../External/ko.js":28,"../Knoin/Knoin.js":33,"../ViewModels/Popups/PopupsFilterViewModel.js":80}],51:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ ko = require('../External/ko.js'),
+ Enums = require('../Common/Enums.js'),
+ Utils = require('../Common/Utils.js'),
+
+ kn = require('../Knoin/Knoin.js'),
+
+ AppSettings = require('../Storages/AppSettings.js'),
+ LocalStorage = require('../Storages/LocalStorage.js'),
+ Data = require('../Storages/WebMailDataStorage.js'),
+ Cache = require('../Storages/WebMailCacheStorage.js'),
+ Remote = require('../Storages/WebMailAjaxRemoteStorage.js'),
+
+ RL = require('../Boots/RainLoopApp.js'),
+
+ PopupsFolderCreateViewModel = require('../ViewModels/Popups/PopupsFolderCreateViewModel.js'),
+ PopupsFolderSystemViewModel = require('../ViewModels/Popups/PopupsFolderSystemViewModel.js')
+ ;
+
+ /**
+ * @constructor
+ */
+ function SettingsFolders()
+ {
+ this.foldersListError = Data.foldersListError;
+ this.folderList = Data.folderList;
+
+ this.processText = ko.computed(function () {
var
- iIndex = 0,
- iLen = aList.length,
+ bLoading = Data.foldersLoading(),
+ bCreating = Data.foldersCreating(),
+ bDeleting = Data.foldersDeleting(),
+ bRenaming = Data.foldersRenaming()
+ ;
+
+ if (bCreating)
+ {
+ return Utils.i18n('SETTINGS_FOLDERS/CREATING_PROCESS');
+ }
+ else if (bDeleting)
+ {
+ return Utils.i18n('SETTINGS_FOLDERS/DELETING_PROCESS');
+ }
+ else if (bRenaming)
+ {
+ return Utils.i18n('SETTINGS_FOLDERS/RENAMING_PROCESS');
+ }
+ else if (bLoading)
+ {
+ return Utils.i18n('SETTINGS_FOLDERS/LOADING_PROCESS');
+ }
+
+ return '';
+
+ }, this);
+
+ this.visibility = ko.computed(function () {
+ return '' === this.processText() ? 'hidden' : 'visible';
+ }, this);
+
+ this.folderForDeletion = ko.observable(null).extend({'falseTimeout': 3000}).extend({'toggleSubscribe': [this,
+ function (oPrev) {
+ if (oPrev)
+ {
+ oPrev.deleteAccess(false);
+ }
+ }, function (oNext) {
+ if (oNext)
+ {
+ oNext.deleteAccess(true);
+ }
+ }
+ ]});
+
+ this.folderForEdit = ko.observable(null).extend({'toggleSubscribe': [this,
+ function (oPrev) {
+ if (oPrev)
+ {
+ oPrev.edited(false);
+ }
+ }, function (oNext) {
+ if (oNext && oNext.canBeEdited())
+ {
+ oNext.edited(true);
+ }
+ }
+ ]});
+
+ this.useImapSubscribe = !!AppSettings.settingsGet('UseImapSubscribe');
+ }
+
+ SettingsFolders.prototype.folderEditOnEnter = function (oFolder)
+ {
+ var sEditName = oFolder ? Utils.trim(oFolder.nameForEdit()) : '';
+ if ('' !== sEditName && oFolder.name() !== sEditName)
+ {
+ LocalStorage.set(Enums.ClientSideKeyName.FoldersLashHash, '');
+
+ Data.foldersRenaming(true);
+ Remote.folderRename(function (sResult, oData) {
+
+ Data.foldersRenaming(false);
+ if (Enums.StorageResultType.Success !== sResult || !oData || !oData.Result)
+ {
+ Data.foldersListError(
+ oData && oData.ErrorCode ? Utils.getNotification(oData.ErrorCode) : Utils.i18n('NOTIFICATIONS/CANT_RENAME_FOLDER'));
+ }
+
+ RL.folders();
+
+ }, oFolder.fullNameRaw, sEditName);
+
+ Cache.removeFolderFromCacheList(oFolder.fullNameRaw);
+
+ oFolder.name(sEditName);
+ }
+
+ oFolder.edited(false);
+ };
+
+ SettingsFolders.prototype.folderEditOnEsc = function (oFolder)
+ {
+ if (oFolder)
+ {
+ oFolder.edited(false);
+ }
+ };
+
+ SettingsFolders.prototype.onShow = function ()
+ {
+ Data.foldersListError('');
+ };
+
+ SettingsFolders.prototype.createFolder = function ()
+ {
+ kn.showScreenPopup(PopupsFolderCreateViewModel);
+ };
+
+ SettingsFolders.prototype.systemFolder = function ()
+ {
+ kn.showScreenPopup(PopupsFolderSystemViewModel);
+ };
+
+ SettingsFolders.prototype.deleteFolder = function (oFolderToRemove)
+ {
+ if (oFolderToRemove && oFolderToRemove.canBeDeleted() && oFolderToRemove.deleteAccess() &&
+ 0 === oFolderToRemove.privateMessageCountAll())
+ {
+ this.folderForDeletion(null);
+
+ var
+ fRemoveFolder = function (oFolder) {
+
+ if (oFolderToRemove === oFolder)
+ {
+ return true;
+ }
+
+ oFolder.subFolders.remove(fRemoveFolder);
+ return false;
+ }
+ ;
+
+ if (oFolderToRemove)
+ {
+ LocalStorage.set(Enums.ClientSideKeyName.FoldersLashHash, '');
+
+ Data.folderList.remove(fRemoveFolder);
+
+ Data.foldersDeleting(true);
+ Remote.folderDelete(function (sResult, oData) {
+
+ Data.foldersDeleting(false);
+ if (Enums.StorageResultType.Success !== sResult || !oData || !oData.Result)
+ {
+ Data.foldersListError(
+ oData && oData.ErrorCode ? Utils.getNotification(oData.ErrorCode) : Utils.i18n('NOTIFICATIONS/CANT_DELETE_FOLDER'));
+ }
+
+ RL.folders();
+
+ }, oFolderToRemove.fullNameRaw);
+
+ Cache.removeFolderFromCacheList(oFolderToRemove.fullNameRaw);
+ }
+ }
+ else if (0 < oFolderToRemove.privateMessageCountAll())
+ {
+ Data.foldersListError(Utils.getNotification(Enums.Notification.CantDeleteNonEmptyFolder));
+ }
+ };
+
+ SettingsFolders.prototype.subscribeFolder = function (oFolder)
+ {
+ LocalStorage.set(Enums.ClientSideKeyName.FoldersLashHash, '');
+ Remote.folderSetSubscribe(Utils.emptyFunction, oFolder.fullNameRaw, true);
+
+ oFolder.subScribed(true);
+ };
+
+ SettingsFolders.prototype.unSubscribeFolder = function (oFolder)
+ {
+ LocalStorage.set(Enums.ClientSideKeyName.FoldersLashHash, '');
+ Remote.folderSetSubscribe(Utils.emptyFunction, oFolder.fullNameRaw, false);
+
+ oFolder.subScribed(false);
+ };
+
+ module.exports = SettingsFolders;
+
+}(module));
+},{"../Boots/RainLoopApp.js":4,"../Common/Enums.js":7,"../Common/Utils.js":14,"../External/ko.js":28,"../Knoin/Knoin.js":33,"../Storages/AppSettings.js":61,"../Storages/LocalStorage.js":62,"../Storages/WebMailAjaxRemoteStorage.js":65,"../Storages/WebMailCacheStorage.js":66,"../Storages/WebMailDataStorage.js":67,"../ViewModels/Popups/PopupsFolderCreateViewModel.js":81,"../ViewModels/Popups/PopupsFolderSystemViewModel.js":82}],52:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ $ = require('../External/jquery.js'),
+ ko = require('../External/ko.js'),
+
+ Enums = require('../Common/Enums.js'),
+ Consts = require('../Common/Consts.js'),
+ Globals = require('../Common/Globals.js'),
+ Utils = require('../Common/Utils.js'),
+ LinkBuilder = require('../Common/LinkBuilder.js'),
+
+ Data = require('../Storages/WebMailDataStorage.js'),
+ Remote = require('../Storages/WebMailAjaxRemoteStorage.js'),
+
+ kn = require('../Knoin/Knoin.js'),
+ PopupsLanguagesViewModel = require('../ViewModels/Popups/PopupsLanguagesViewModel.js')
+ ;
+
+ /**
+ * @constructor
+ */
+ function SettingsGeneral()
+ {
+ this.mainLanguage = Data.mainLanguage;
+ this.mainMessagesPerPage = Data.mainMessagesPerPage;
+ this.mainMessagesPerPageArray = Consts.Defaults.MessagesPerPageArray;
+ this.editorDefaultType = Data.editorDefaultType;
+ this.showImages = Data.showImages;
+ this.interfaceAnimation = Data.interfaceAnimation;
+ this.useDesktopNotifications = Data.useDesktopNotifications;
+ this.threading = Data.threading;
+ this.useThreads = Data.useThreads;
+ this.replySameFolder = Data.replySameFolder;
+ this.layout = Data.layout;
+ this.usePreviewPane = Data.usePreviewPane;
+ this.useCheckboxesInList = Data.useCheckboxesInList;
+ this.allowLanguagesOnSettings = Data.allowLanguagesOnSettings;
+
+ this.isDesktopNotificationsSupported = ko.computed(function () {
+ return Enums.DesktopNotifications.NotSupported !== Data.desktopNotificationsPermisions();
+ });
+
+ this.isDesktopNotificationsDenied = ko.computed(function () {
+ return Enums.DesktopNotifications.NotSupported === Data.desktopNotificationsPermisions() ||
+ Enums.DesktopNotifications.Denied === Data.desktopNotificationsPermisions();
+ });
+
+ this.mainLanguageFullName = ko.computed(function () {
+ return Utils.convertLangName(this.mainLanguage());
+ }, this);
+
+ this.languageTrigger = ko.observable(Enums.SaveSettingsStep.Idle).extend({'throttle': 100});
+ this.mppTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
+
+ this.isAnimationSupported = Globals.bAnimationSupported;
+ }
+
+ SettingsGeneral.prototype.toggleLayout = function ()
+ {
+ this.layout(Enums.Layout.NoPreview === this.layout() ? Enums.Layout.SidePreview : Enums.Layout.NoPreview);
+ };
+
+ SettingsGeneral.prototype.onBuild = function ()
+ {
+ var self = this;
+
+ _.delay(function () {
+
+ var
+ f1 = Utils.settingsSaveHelperSimpleFunction(self.mppTrigger, self)
+ ;
+
+ Data.language.subscribe(function (sValue) {
+
+ self.languageTrigger(Enums.SaveSettingsStep.Animate);
+
+ $.ajax({
+ 'url': LinkBuilder.langLink(sValue),
+ 'dataType': 'script',
+ 'cache': true
+ }).done(function() {
+ Utils.i18nReload();
+ self.languageTrigger(Enums.SaveSettingsStep.TrueResult);
+ }).fail(function() {
+ self.languageTrigger(Enums.SaveSettingsStep.FalseResult);
+ }).always(function() {
+ _.delay(function () {
+ self.languageTrigger(Enums.SaveSettingsStep.Idle);
+ }, 1000);
+ });
+
+ Remote.saveSettings(Utils.emptyFunction, {
+ 'Language': sValue
+ });
+ });
+
+ Data.editorDefaultType.subscribe(function (sValue) {
+ Remote.saveSettings(Utils.emptyFunction, {
+ 'EditorDefaultType': sValue
+ });
+ });
+
+ Data.messagesPerPage.subscribe(function (iValue) {
+ Remote.saveSettings(f1, {
+ 'MPP': iValue
+ });
+ });
+
+ Data.showImages.subscribe(function (bValue) {
+ Remote.saveSettings(Utils.emptyFunction, {
+ 'ShowImages': bValue ? '1' : '0'
+ });
+ });
+
+ Data.interfaceAnimation.subscribe(function (sValue) {
+ Remote.saveSettings(Utils.emptyFunction, {
+ 'InterfaceAnimation': sValue
+ });
+ });
+
+ Data.useDesktopNotifications.subscribe(function (bValue) {
+ Utils.timeOutAction('SaveDesktopNotifications', function () {
+ Remote.saveSettings(Utils.emptyFunction, {
+ 'DesktopNotifications': bValue ? '1' : '0'
+ });
+ }, 3000);
+ });
+
+ Data.replySameFolder.subscribe(function (bValue) {
+ Utils.timeOutAction('SaveReplySameFolder', function () {
+ Remote.saveSettings(Utils.emptyFunction, {
+ 'ReplySameFolder': bValue ? '1' : '0'
+ });
+ }, 3000);
+ });
+
+ Data.useThreads.subscribe(function (bValue) {
+
+ Data.messageList([]);
+
+ Remote.saveSettings(Utils.emptyFunction, {
+ 'UseThreads': bValue ? '1' : '0'
+ });
+ });
+
+ Data.layout.subscribe(function (nValue) {
+
+ Data.messageList([]);
+
+ Remote.saveSettings(Utils.emptyFunction, {
+ 'Layout': nValue
+ });
+ });
+
+ Data.useCheckboxesInList.subscribe(function (bValue) {
+ Remote.saveSettings(Utils.emptyFunction, {
+ 'UseCheckboxesInList': bValue ? '1' : '0'
+ });
+ });
+
+ }, 50);
+ };
+
+ SettingsGeneral.prototype.onShow = function ()
+ {
+ Data.desktopNotifications.valueHasMutated();
+ };
+
+ SettingsGeneral.prototype.selectLanguage = function ()
+ {
+ kn.showScreenPopup(PopupsLanguagesViewModel);
+ };
+
+ module.exports = SettingsGeneral;
+
+}(module));
+},{"../Common/Consts.js":6,"../Common/Enums.js":7,"../Common/Globals.js":9,"../Common/LinkBuilder.js":10,"../Common/Utils.js":14,"../External/jquery.js":26,"../External/ko.js":28,"../Knoin/Knoin.js":33,"../Storages/WebMailAjaxRemoteStorage.js":65,"../Storages/WebMailDataStorage.js":67,"../ViewModels/Popups/PopupsLanguagesViewModel.js":86}],53:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ ko = require('../External/ko.js'),
+
+ Enums = require('../Common/Enums.js'),
+ Utils = require('../Common/Utils.js'),
+ NewHtmlEditorWrapper = require('../Common/NewHtmlEditorWrapper.js'),
+
+ Data = require('../Storages/WebMailDataStorage.js'),
+ Remote = require('../Storages/WebMailAjaxRemoteStorage.js'),
+
+ RL = require('../Boots/RainLoopApp.js'),
+
+ kn = require('../Knoin/Knoin.js'),
+ PopupsIdentityViewModel = require('../ViewModels/Popups/PopupsIdentityViewModel.js')
+ ;
+
+ /**
+ * @constructor
+ */
+ function SettingsIdentities()
+ {
+ this.editor = null;
+ this.defautOptionsAfterRender = Utils.defautOptionsAfterRender;
+
+ this.accountEmail = Data.accountEmail;
+ this.displayName = Data.displayName;
+ this.signature = Data.signature;
+ this.signatureToAll = Data.signatureToAll;
+ this.replyTo = Data.replyTo;
+
+ this.signatureDom = ko.observable(null);
+
+ this.defaultIdentityIDTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
+ this.displayNameTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
+ this.replyTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
+ this.signatureTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
+
+ this.identities = Data.identities;
+ this.defaultIdentityID = Data.defaultIdentityID;
+
+ this.identitiesOptions = ko.computed(function () {
+
+ var
+ aList = this.identities(),
aResult = []
;
- for (; iIndex < iLen; iIndex++)
+ if (0 < aList.length)
{
- aResult.push(aList[iIndex].toLine(!!bFriendly));
- }
-
- return aResult.join(', ');
- }
- ;
-
- oMessageOrArray = oMessageOrArray || null;
- if (oMessageOrArray && Utils.isNormal(oMessageOrArray))
- {
- oMessage = Utils.isArray(oMessageOrArray) && 1 === oMessageOrArray.length ? oMessageOrArray[0] :
- (!Utils.isArray(oMessageOrArray) ? oMessageOrArray : null);
- }
-
- if (null !== mEmail)
- {
- oExcludeEmail[mEmail] = true;
- }
-
- this.currentIdentityID(this.findIdentityIdByMessage(sComposeType, oMessage));
- this.reset();
-
- if (Utils.isNonEmptyArray(aToEmails))
- {
- this.to(fEmailArrayToStringLineHelper(aToEmails));
- }
-
- if ('' !== sComposeType && oMessage)
- {
- sDate = oMessage.fullFormatDateValue();
- sSubject = oMessage.subject();
- aDraftInfo = oMessage.aDraftInfo;
-
- oText = $(oMessage.body).clone();
- Utils.removeBlockquoteSwitcher(oText);
-
- oSubText = oText.find('[data-html-editor-font-wrapper=true]');
- sText = oSubText && oSubText[0] ? oSubText.html() : oText.html();
-
- switch (sComposeType)
- {
- case Enums.ComposeType.Empty:
- break;
-
- case Enums.ComposeType.Reply:
- this.to(fEmailArrayToStringLineHelper(oMessage.replyEmails(oExcludeEmail)));
- this.subject(Utils.replySubjectAdd('Re', sSubject));
- this.prepearMessageAttachments(oMessage, sComposeType);
- this.aDraftInfo = ['reply', oMessage.uid, oMessage.folderFullNameRaw];
- this.sInReplyTo = oMessage.sMessageId;
- this.sReferences = Utils.trim(this.sInReplyTo + ' ' + oMessage.sReferences);
- break;
-
- case Enums.ComposeType.ReplyAll:
- aResplyAllParts = oMessage.replyAllEmails(oExcludeEmail);
- this.to(fEmailArrayToStringLineHelper(aResplyAllParts[0]));
- this.cc(fEmailArrayToStringLineHelper(aResplyAllParts[1]));
- this.subject(Utils.replySubjectAdd('Re', sSubject));
- this.prepearMessageAttachments(oMessage, sComposeType);
- this.aDraftInfo = ['reply', oMessage.uid, oMessage.folderFullNameRaw];
- this.sInReplyTo = oMessage.sMessageId;
- this.sReferences = Utils.trim(this.sInReplyTo + ' ' + oMessage.references());
- break;
-
- case Enums.ComposeType.Forward:
- this.subject(Utils.replySubjectAdd('Fwd', sSubject));
- this.prepearMessageAttachments(oMessage, sComposeType);
- this.aDraftInfo = ['forward', oMessage.uid, oMessage.folderFullNameRaw];
- this.sInReplyTo = oMessage.sMessageId;
- this.sReferences = Utils.trim(this.sInReplyTo + ' ' + oMessage.sReferences);
- break;
-
- case Enums.ComposeType.ForwardAsAttachment:
- this.subject(Utils.replySubjectAdd('Fwd', sSubject));
- this.prepearMessageAttachments(oMessage, sComposeType);
- this.aDraftInfo = ['forward', oMessage.uid, oMessage.folderFullNameRaw];
- this.sInReplyTo = oMessage.sMessageId;
- this.sReferences = Utils.trim(this.sInReplyTo + ' ' + oMessage.sReferences);
- break;
-
- case Enums.ComposeType.Draft:
- this.to(fEmailArrayToStringLineHelper(oMessage.to));
- this.cc(fEmailArrayToStringLineHelper(oMessage.cc));
- this.bcc(fEmailArrayToStringLineHelper(oMessage.bcc));
-
- this.bFromDraft = true;
-
- this.draftFolder(oMessage.folderFullNameRaw);
- this.draftUid(oMessage.uid);
-
- this.subject(sSubject);
- this.prepearMessageAttachments(oMessage, sComposeType);
-
- this.aDraftInfo = Utils.isNonEmptyArray(aDraftInfo) && 3 === aDraftInfo.length ? aDraftInfo : null;
- this.sInReplyTo = oMessage.sInReplyTo;
- this.sReferences = oMessage.sReferences;
- break;
-
- case Enums.ComposeType.EditAsNew:
- this.to(fEmailArrayToStringLineHelper(oMessage.to));
- this.cc(fEmailArrayToStringLineHelper(oMessage.cc));
- this.bcc(fEmailArrayToStringLineHelper(oMessage.bcc));
-
- this.subject(sSubject);
- this.prepearMessageAttachments(oMessage, sComposeType);
-
- this.aDraftInfo = Utils.isNonEmptyArray(aDraftInfo) && 3 === aDraftInfo.length ? aDraftInfo : null;
- this.sInReplyTo = oMessage.sInReplyTo;
- this.sReferences = oMessage.sReferences;
- break;
- }
-
- switch (sComposeType)
- {
- case Enums.ComposeType.Reply:
- case Enums.ComposeType.ReplyAll:
- sFrom = oMessage.fromToLine(false, true);
- sReplyTitle = Utils.i18n('COMPOSE/REPLY_MESSAGE_TITLE', {
- 'DATETIME': sDate,
- 'EMAIL': sFrom
+ aResult.push({
+ 'id': this.accountEmail.peek(),
+ 'name': this.formattedAccountIdentity(),
+ 'seporator': false
});
- sText = '
' + sReplyTitle + ':' +
- '' + sText + '
';
-
- break;
-
- case Enums.ComposeType.Forward:
- sFrom = oMessage.fromToLine(false, true);
- sTo = oMessage.toToLine(false, true);
- sCc = oMessage.ccToLine(false, true);
- sText = '
' + Utils.i18n('COMPOSE/FORWARD_MESSAGE_TOP_TITLE') +
- '
' + Utils.i18n('COMPOSE/FORWARD_MESSAGE_TOP_FROM') + ': ' + sFrom +
- '
' + Utils.i18n('COMPOSE/FORWARD_MESSAGE_TOP_TO') + ': ' + sTo +
- (0 < sCc.length ? '
' + Utils.i18n('COMPOSE/FORWARD_MESSAGE_TOP_CC') + ': ' + sCc : '') +
- '
' + Utils.i18n('COMPOSE/FORWARD_MESSAGE_TOP_SENT') + ': ' + Utils.encodeHtml(sDate) +
- '
' + Utils.i18n('COMPOSE/FORWARD_MESSAGE_TOP_SUBJECT') + ': ' + Utils.encodeHtml(sSubject) +
- '
' + sText;
- break;
- case Enums.ComposeType.ForwardAsAttachment:
- sText = '';
- break;
- }
-
- if (bSignatureToAll && '' !== sSignature &&
- Enums.ComposeType.EditAsNew !== sComposeType && Enums.ComposeType.Draft !== sComposeType)
- {
- sText = this.convertSignature(sSignature, fEmailArrayToStringLineHelper(oMessage.from, true), sText, sComposeType);
- }
-
- this.editor(function (oEditor) {
- oEditor.setHtml(sText, false);
- if (!oMessage.isHtml())
- {
- oEditor.modeToggle(false);
- }
- });
- }
- else if (Enums.ComposeType.Empty === sComposeType)
- {
- this.subject(Utils.isNormal(sCustomSubject) ? '' + sCustomSubject : '');
-
- sText = Utils.isNormal(sCustomPlainText) ? '' + sCustomPlainText : '';
- if (bSignatureToAll && '' !== sSignature)
- {
- sText = this.convertSignature(sSignature, '',
- Utils.convertPlainTextToHtml(sText), sComposeType);
- }
-
- this.editor(function (oEditor) {
- oEditor.setHtml(sText, false);
- if (Enums.EditorDefaultType.Html !== RL.data().editorDefaultType())
- {
- oEditor.modeToggle(false);
- }
- });
- }
- else if (Utils.isNonEmptyArray(oMessageOrArray))
- {
- _.each(oMessageOrArray, function (oMessage) {
- self.addMessageAsAttachment(oMessage);
- });
- }
-
- aDownloads = this.getAttachmentsDownloadsForUpload();
- if (Utils.isNonEmptyArray(aDownloads))
- {
- RL.remote().messageUploadAttachments(function (sResult, oData) {
-
- if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
- {
- var
- oAttachment = null,
- sTempName = ''
- ;
-
- if (!self.viewModelVisibility())
- {
- for (sTempName in oData.Result)
- {
- if (oData.Result.hasOwnProperty(sTempName))
- {
- oAttachment = self.getAttachmentById(oData.Result[sTempName]);
- if (oAttachment)
- {
- oAttachment.tempName(sTempName);
- }
- }
- }
- }
- }
- else
- {
- self.setMessageAttachmentFailedDowbloadText();
- }
-
- }, aDownloads);
- }
-
- this.triggerForResize();
-};
-
-PopupsComposeViewModel.prototype.onFocus = function ()
-{
- if ('' === this.to())
- {
- this.to.focusTrigger(!this.to.focusTrigger());
- }
- else if (this.oEditor)
- {
- this.oEditor.focus();
- }
-
- this.triggerForResize();
-};
-
-PopupsComposeViewModel.prototype.editorResize = function ()
-{
- if (this.oEditor)
- {
- this.oEditor.resize();
- }
-};
-
-PopupsComposeViewModel.prototype.tryToClosePopup = function ()
-{
- var self = this;
- if (!kn.isPopupVisible(PopupsAskViewModel))
- {
- kn.showScreenPopup(PopupsAskViewModel, [Utils.i18n('POPUPS_ASK/DESC_WANT_CLOSE_THIS_WINDOW'), function () {
- if (self.modalVisibility())
- {
- Utils.delegateRun(self, 'closeCommand');
- }
- }]);
- }
-};
-
-PopupsComposeViewModel.prototype.onBuild = function ()
-{
- this.initUploader();
-
- var
- self = this,
- oScript = null
- ;
-
- key('ctrl+q, command+q', Enums.KeyState.Compose, function () {
- self.identitiesDropdownTrigger(true);
- return false;
- });
-
- key('ctrl+s, command+s', Enums.KeyState.Compose, function () {
- self.saveCommand();
- return false;
- });
-
- key('ctrl+enter, command+enter', Enums.KeyState.Compose, function () {
- self.sendCommand();
- return false;
- });
-
- key('esc', Enums.KeyState.Compose, function () {
- if (self.modalVisibility())
- {
- self.tryToClosePopup();
- }
- return false;
- });
-
- $window.on('resize', function () {
- self.triggerForResize();
- });
-
- if (this.dropboxEnabled())
- {
- oScript = document.createElement('script');
- oScript.type = 'text/javascript';
- oScript.src = 'https://www.dropbox.com/static/api/1/dropins.js';
- $(oScript).attr('id', 'dropboxjs').attr('data-app-key', RL.settingsGet('DropboxApiKey'));
-
- document.body.appendChild(oScript);
- }
-
- if (this.driveEnabled())
- {
- $.getScript('https://apis.google.com/js/api.js', function () {
- if (window.gapi)
- {
- self.driveVisible(true);
- }
- });
- }
-};
-
-PopupsComposeViewModel.prototype.driveCallback = function (sAccessToken, oData)
-{
- if (oData && window.XMLHttpRequest && window.google &&
- oData[window.google.picker.Response.ACTION] === window.google.picker.Action.PICKED &&
- oData[window.google.picker.Response.DOCUMENTS] && oData[window.google.picker.Response.DOCUMENTS][0] &&
- oData[window.google.picker.Response.DOCUMENTS][0]['id'])
- {
- var
- self = this,
- oRequest = new window.XMLHttpRequest()
- ;
-
- oRequest.open('GET', 'https://www.googleapis.com/drive/v2/files/' + oData[window.google.picker.Response.DOCUMENTS][0]['id']);
- oRequest.setRequestHeader('Authorization', 'Bearer ' + sAccessToken);
- oRequest.addEventListener('load', function() {
- if (oRequest && oRequest.responseText)
- {
- var oItem = JSON.parse(oRequest.responseText), fExport = function (oItem, sMimeType, sExt) {
- if (oItem && oItem['exportLinks'])
- {
- if (oItem['exportLinks'][sMimeType])
- {
- oItem['downloadUrl'] = oItem['exportLinks'][sMimeType];
- oItem['title'] = oItem['title'] + '.' + sExt;
- oItem['mimeType'] = sMimeType;
- }
- else if (oItem['exportLinks']['application/pdf'])
- {
- oItem['downloadUrl'] = oItem['exportLinks']['application/pdf'];
- oItem['title'] = oItem['title'] + '.pdf';
- oItem['mimeType'] = 'application/pdf';
- }
- }
- };
-
- if (oItem && !oItem['downloadUrl'] && oItem['mimeType'] && oItem['exportLinks'])
- {
- switch (oItem['mimeType'].toString().toLowerCase())
- {
- case 'application/vnd.google-apps.document':
- fExport(oItem, 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'docx');
- break;
- case 'application/vnd.google-apps.spreadsheet':
- fExport(oItem, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'xlsx');
- break;
- case 'application/vnd.google-apps.drawing':
- fExport(oItem, 'image/png', 'png');
- break;
- case 'application/vnd.google-apps.presentation':
- fExport(oItem, 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'pptx');
- break;
- default:
- fExport(oItem, 'application/pdf', 'pdf');
- break;
- }
- }
-
- if (oItem && oItem['downloadUrl'])
- {
- self.addDriveAttachment(oItem, sAccessToken);
- }
- }
- });
-
- oRequest.send();
- }
-};
-
-PopupsComposeViewModel.prototype.driveCreatePiker = function (oOauthToken)
-{
- if (window.gapi && oOauthToken && oOauthToken.access_token)
- {
- var self = this;
-
- window.gapi.load('picker', {'callback': function () {
-
- if (window.google && window.google.picker)
- {
- var drivePicker = new window.google.picker.PickerBuilder()
- .addView(
- new window.google.picker.DocsView()
- .setIncludeFolders(true)
- )
- .setAppId(RL.settingsGet('GoogleClientID'))
- .setOAuthToken(oOauthToken.access_token)
- .setCallback(_.bind(self.driveCallback, self, oOauthToken.access_token))
- .enableFeature(window.google.picker.Feature.NAV_HIDDEN)
- .build()
- ;
-
- drivePicker.setVisible(true);
- }
- }});
- }
-};
-
-PopupsComposeViewModel.prototype.driveOpenPopup = function ()
-{
- if (window.gapi)
- {
- var self = this;
-
- window.gapi.load('auth', {'callback': function () {
-
- var oAuthToken = window.gapi.auth.getToken();
- if (!oAuthToken)
- {
- window.gapi.auth.authorize({
- 'client_id': RL.settingsGet('GoogleClientID'),
- 'scope': 'https://www.googleapis.com/auth/drive.readonly',
- 'immediate': true
- }, function (oAuthResult) {
- if (oAuthResult && !oAuthResult.error)
- {
- var oAuthToken = window.gapi.auth.getToken();
- if (oAuthToken)
- {
- self.driveCreatePiker(oAuthToken);
- }
- }
- else
- {
- window.gapi.auth.authorize({
- 'client_id': RL.settingsGet('GoogleClientID'),
- 'scope': 'https://www.googleapis.com/auth/drive.readonly',
- 'immediate': false
- }, function (oAuthResult) {
- if (oAuthResult && !oAuthResult.error)
- {
- var oAuthToken = window.gapi.auth.getToken();
- if (oAuthToken)
- {
- self.driveCreatePiker(oAuthToken);
- }
- }
- });
- }
+ aResult.push({
+ 'id': '---',
+ 'name': '---',
+ 'seporator': true,
+ 'disabled': true
});
- }
- else
- {
- self.driveCreatePiker(oAuthToken);
- }
- }});
- }
-};
-/**
- * @param {string} sId
- * @return {?Object}
- */
-PopupsComposeViewModel.prototype.getAttachmentById = function (sId)
-{
- var
- aAttachments = this.attachments(),
- iIndex = 0,
- iLen = aAttachments.length
- ;
-
- for (; iIndex < iLen; iIndex++)
- {
- if (aAttachments[iIndex] && sId === aAttachments[iIndex].id)
- {
- return aAttachments[iIndex];
- }
- }
-
- return null;
-};
-
-PopupsComposeViewModel.prototype.initUploader = function ()
-{
- if (this.composeUploaderButton())
- {
- var
- oUploadCache = {},
- iAttachmentSizeLimit = Utils.pInt(RL.settingsGet('AttachmentLimit')),
- oJua = new Jua({
- 'action': RL.link().upload(),
- 'name': 'uploader',
- 'queueSize': 2,
- 'multipleSizeLimit': 50,
- 'disableFolderDragAndDrop': false,
- 'clickElement': this.composeUploaderButton(),
- 'dragAndDropElement': this.composeUploaderDropPlace()
- })
- ;
-
- if (oJua)
- {
- oJua
-// .on('onLimitReached', function (iLimit) {
-// alert(iLimit);
-// })
- .on('onDragEnter', _.bind(function () {
- this.dragAndDropOver(true);
- }, this))
- .on('onDragLeave', _.bind(function () {
- this.dragAndDropOver(false);
- }, this))
- .on('onBodyDragEnter', _.bind(function () {
- this.dragAndDropVisible(true);
- }, this))
- .on('onBodyDragLeave', _.bind(function () {
- this.dragAndDropVisible(false);
- }, this))
- .on('onProgress', _.bind(function (sId, iLoaded, iTotal) {
- var oItem = null;
- if (Utils.isUnd(oUploadCache[sId]))
- {
- oItem = this.getAttachmentById(sId);
- if (oItem)
- {
- oUploadCache[sId] = oItem;
- }
- }
- else
- {
- oItem = oUploadCache[sId];
- }
-
- if (oItem)
- {
- oItem.progress(' - ' + Math.floor(iLoaded / iTotal * 100) + '%');
- }
-
- }, this))
- .on('onSelect', _.bind(function (sId, oData) {
-
- this.dragAndDropOver(false);
-
- var
- that = this,
- sFileName = Utils.isUnd(oData.FileName) ? '' : oData.FileName.toString(),
- mSize = Utils.isNormal(oData.Size) ? Utils.pInt(oData.Size) : null,
- oAttachment = new ComposeAttachmentModel(sId, sFileName, mSize)
- ;
-
- oAttachment.cancel = (function (sId) {
-
- return function () {
- that.attachments.remove(function (oItem) {
- return oItem && oItem.id === sId;
- });
-
- if (oJua)
- {
- oJua.cancel(sId);
- }
- };
-
- }(sId));
-
- this.attachments.push(oAttachment);
-
- if (0 < mSize && 0 < iAttachmentSizeLimit && iAttachmentSizeLimit < mSize)
- {
- oAttachment.error(Utils.i18n('UPLOAD/ERROR_FILE_IS_TOO_BIG'));
- return false;
- }
-
- return true;
-
- }, this))
- .on('onStart', _.bind(function (sId) {
-
- var
- oItem = null
- ;
-
- if (Utils.isUnd(oUploadCache[sId]))
- {
- oItem = this.getAttachmentById(sId);
- if (oItem)
- {
- oUploadCache[sId] = oItem;
- }
- }
- else
- {
- oItem = oUploadCache[sId];
- }
-
- if (oItem)
- {
- oItem.waiting(false);
- oItem.uploading(true);
- }
-
- }, this))
- .on('onComplete', _.bind(function (sId, bResult, oData) {
-
- var
- sError = '',
- mErrorCode = null,
- oAttachmentJson = null,
- oAttachment = this.getAttachmentById(sId)
- ;
-
- oAttachmentJson = bResult && oData && oData.Result && oData.Result.Attachment ? oData.Result.Attachment : null;
- mErrorCode = oData && oData.Result && oData.Result.ErrorCode ? oData.Result.ErrorCode : null;
-
- if (null !== mErrorCode)
- {
- sError = Utils.getUploadErrorDescByCode(mErrorCode);
- }
- else if (!oAttachmentJson)
- {
- sError = Utils.i18n('UPLOAD/ERROR_UNKNOWN');
- }
-
- if (oAttachment)
- {
- if ('' !== sError && 0 < sError.length)
- {
- oAttachment
- .waiting(false)
- .uploading(false)
- .error(sError)
- ;
- }
- else if (oAttachmentJson)
- {
- oAttachment
- .waiting(false)
- .uploading(false)
- ;
-
- oAttachment.initByUploadJson(oAttachmentJson);
- }
-
- if (Utils.isUnd(oUploadCache[sId]))
- {
- delete (oUploadCache[sId]);
- }
- }
-
- }, this))
- ;
-
- this
- .addAttachmentEnabled(true)
- .dragAndDropEnabled(oJua.isDragAndDropSupported())
- ;
- }
- else
- {
- this
- .addAttachmentEnabled(false)
- .dragAndDropEnabled(false)
- ;
- }
- }
-};
-
-/**
- * @return {Object}
- */
-PopupsComposeViewModel.prototype.prepearAttachmentsForSendOrSave = function ()
-{
- var oResult = {};
- _.each(this.attachmentsInReady(), function (oItem) {
- if (oItem && '' !== oItem.tempName() && oItem.enabled())
- {
- oResult[oItem.tempName()] = [
- oItem.fileName(),
- oItem.isInline ? '1' : '0',
- oItem.CID,
- oItem.contentLocation
- ];
- }
- });
-
- return oResult;
-};
-
-/**
- * @param {MessageModel} oMessage
- */
-PopupsComposeViewModel.prototype.addMessageAsAttachment = function (oMessage)
-{
- if (oMessage)
- {
- var
- self = this,
- oAttachment = null,
- sTemp = oMessage.subject(),
- fCancelFunc = function (sId) {
- return function () {
- self.attachments.remove(function (oItem) {
- return oItem && oItem.id === sId;
+ _.each(aList, function (oItem) {
+ aResult.push({
+ 'id': oItem.id,
+ 'name': oItem.formattedNameForEmail(),
+ 'seporator': false
});
- };
- }
- ;
-
- sTemp = '.eml' === sTemp.substr(-4).toLowerCase() ? sTemp : sTemp + '.eml';
- oAttachment = new ComposeAttachmentModel(
- oMessage.requestHash, sTemp, oMessage.size()
- );
-
- oAttachment.fromMessage = true;
- oAttachment.cancel = fCancelFunc(oMessage.requestHash);
- oAttachment.waiting(false).uploading(true);
-
- this.attachments.push(oAttachment);
- }
-};
-
-/**
- * @param {Object} oDropboxFile
- * @return {boolean}
- */
-PopupsComposeViewModel.prototype.addDropboxAttachment = function (oDropboxFile)
-{
- var
- self = this,
- oAttachment = null,
- fCancelFunc = function (sId) {
- return function () {
- self.attachments.remove(function (oItem) {
- return oItem && oItem.id === sId;
});
- };
- },
- iAttachmentSizeLimit = Utils.pInt(RL.settingsGet('AttachmentLimit')),
- mSize = oDropboxFile['bytes']
- ;
+ }
- oAttachment = new ComposeAttachmentModel(
- oDropboxFile['link'], oDropboxFile['name'], mSize
- );
+ return aResult;
+ }, this);
- oAttachment.fromMessage = false;
- oAttachment.cancel = fCancelFunc(oDropboxFile['link']);
- oAttachment.waiting(false).uploading(true);
+ this.processText = ko.computed(function () {
+ return Data.identitiesLoading() ? Utils.i18n('SETTINGS_IDENTITIES/LOADING_PROCESS') : '';
+ }, this);
- this.attachments.push(oAttachment);
+ this.visibility = ko.computed(function () {
+ return '' === this.processText() ? 'hidden' : 'visible';
+ }, this);
- if (0 < mSize && 0 < iAttachmentSizeLimit && iAttachmentSizeLimit < mSize)
- {
- oAttachment.uploading(false);
- oAttachment.error(Utils.i18n('UPLOAD/ERROR_FILE_IS_TOO_BIG'));
- return false;
+ this.identityForDeletion = ko.observable(null).extend({'falseTimeout': 3000}).extend({'toggleSubscribe': [this,
+ function (oPrev) {
+ if (oPrev)
+ {
+ oPrev.deleteAccess(false);
+ }
+ }, function (oNext) {
+ if (oNext)
+ {
+ oNext.deleteAccess(true);
+ }
+ }
+ ]});
}
- RL.remote().composeUploadExternals(function (sResult, oData) {
-
- var bResult = false;
- oAttachment.uploading(false);
-
- if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
- {
- if (oData.Result[oAttachment.id])
- {
- bResult = true;
- oAttachment.tempName(oData.Result[oAttachment.id]);
- }
- }
-
- if (!bResult)
- {
- oAttachment.error(Utils.getUploadErrorDescByCode(Enums.UploadErrorCode.FileNoUploaded));
- }
-
- }, [oDropboxFile['link']]);
-
- return true;
-};
-
-/**
- * @param {Object} oDriveFile
- * @param {string} sAccessToken
- * @return {boolean}
- */
-PopupsComposeViewModel.prototype.addDriveAttachment = function (oDriveFile, sAccessToken)
-{
- var
- self = this,
- fCancelFunc = function (sId) {
- return function () {
- self.attachments.remove(function (oItem) {
- return oItem && oItem.id === sId;
- });
- };
- },
- iAttachmentSizeLimit = Utils.pInt(RL.settingsGet('AttachmentLimit')),
- oAttachment = null,
- mSize = oDriveFile['fileSize'] ? Utils.pInt(oDriveFile['fileSize']) : 0
- ;
-
- oAttachment = new ComposeAttachmentModel(
- oDriveFile['downloadUrl'], oDriveFile['title'], mSize
- );
-
- oAttachment.fromMessage = false;
- oAttachment.cancel = fCancelFunc(oDriveFile['downloadUrl']);
- oAttachment.waiting(false).uploading(true);
-
- this.attachments.push(oAttachment);
-
- if (0 < mSize && 0 < iAttachmentSizeLimit && iAttachmentSizeLimit < mSize)
- {
- oAttachment.uploading(false);
- oAttachment.error(Utils.i18n('UPLOAD/ERROR_FILE_IS_TOO_BIG'));
- return false;
- }
-
- RL.remote().composeUploadDrive(function (sResult, oData) {
-
- var bResult = false;
- oAttachment.uploading(false);
-
- if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
- {
- if (oData.Result[oAttachment.id])
- {
- bResult = true;
- oAttachment.tempName(oData.Result[oAttachment.id][0]);
- oAttachment.size(Utils.pInt(oData.Result[oAttachment.id][1]));
- }
- }
-
- if (!bResult)
- {
- oAttachment.error(Utils.getUploadErrorDescByCode(Enums.UploadErrorCode.FileNoUploaded));
- }
-
- }, oDriveFile['downloadUrl'], sAccessToken);
-
- return true;
-};
-
-/**
- * @param {MessageModel} oMessage
- * @param {string} sType
- */
-PopupsComposeViewModel.prototype.prepearMessageAttachments = function (oMessage, sType)
-{
- if (oMessage)
+ /**
+ *
+ * @return {string}
+ */
+ SettingsIdentities.prototype.formattedAccountIdentity = function ()
{
var
- self = this,
- aAttachments = Utils.isNonEmptyArray(oMessage.attachments()) ? oMessage.attachments() : [],
- iIndex = 0,
- iLen = aAttachments.length,
- oAttachment = null,
- oItem = null,
- bAdd = false,
- fCancelFunc = function (sId) {
- return function () {
- self.attachments.remove(function (oItem) {
- return oItem && oItem.id === sId;
- });
- };
- }
+ sDisplayName = this.displayName.peek(),
+ sEmail = this.accountEmail.peek()
;
- if (Enums.ComposeType.ForwardAsAttachment === sType)
- {
- this.addMessageAsAttachment(oMessage);
- }
- else
- {
- for (; iIndex < iLen; iIndex++)
- {
- oItem = aAttachments[iIndex];
+ return '' === sDisplayName ? sEmail : '"' + Utils.quoteName(sDisplayName) + '" <' + sEmail + '>';
+ };
- bAdd = false;
- switch (sType) {
- case Enums.ComposeType.Reply:
- case Enums.ComposeType.ReplyAll:
- bAdd = oItem.isLinked;
- break;
+ SettingsIdentities.prototype.addNewIdentity = function ()
+ {
+ kn.showScreenPopup(PopupsIdentityViewModel);
+ };
- case Enums.ComposeType.Forward:
- case Enums.ComposeType.Draft:
- case Enums.ComposeType.EditAsNew:
- bAdd = true;
- break;
+ SettingsIdentities.prototype.editIdentity = function (oIdentity)
+ {
+ kn.showScreenPopup(PopupsIdentityViewModel, [oIdentity]);
+ };
+
+ /**
+ * @param {IdentityModel} oIdentityToRemove
+ */
+ SettingsIdentities.prototype.deleteIdentity = function (oIdentityToRemove)
+ {
+ if (oIdentityToRemove && oIdentityToRemove.deleteAccess())
+ {
+ this.identityForDeletion(null);
+
+ var
+ fRemoveFolder = function (oIdentity) {
+ return oIdentityToRemove === oIdentity;
}
-
- if (bAdd)
- {
- oAttachment = new ComposeAttachmentModel(
- oItem.download, oItem.fileName, oItem.estimatedSize,
- oItem.isInline, oItem.isLinked, oItem.cid, oItem.contentLocation
- );
-
- oAttachment.fromMessage = true;
- oAttachment.cancel = fCancelFunc(oItem.download);
- oAttachment.waiting(false).uploading(true);
-
- this.attachments.push(oAttachment);
- }
- }
- }
- }
-};
-
-PopupsComposeViewModel.prototype.removeLinkedAttachments = function ()
-{
- this.attachments.remove(function (oItem) {
- return oItem && oItem.isLinked;
- });
-};
-
-PopupsComposeViewModel.prototype.setMessageAttachmentFailedDowbloadText = function ()
-{
- _.each(this.attachments(), function(oAttachment) {
- if (oAttachment && oAttachment.fromMessage)
- {
- oAttachment
- .waiting(false)
- .uploading(false)
- .error(Utils.getUploadErrorDescByCode(Enums.UploadErrorCode.FileNoUploaded))
;
- }
- }, this);
-};
-/**
- * @param {boolean=} bIncludeAttachmentInProgress = true
- * @return {boolean}
- */
-PopupsComposeViewModel.prototype.isEmptyForm = function (bIncludeAttachmentInProgress)
-{
- bIncludeAttachmentInProgress = Utils.isUnd(bIncludeAttachmentInProgress) ? true : !!bIncludeAttachmentInProgress;
- var bAttach = bIncludeAttachmentInProgress ?
- 0 === this.attachments().length : 0 === this.attachmentsInReady().length;
-
- return 0 === this.to().length &&
- 0 === this.cc().length &&
- 0 === this.bcc().length &&
- 0 === this.subject().length &&
- bAttach &&
- (!this.oEditor || '' === this.oEditor.getData())
- ;
-};
-
-PopupsComposeViewModel.prototype.reset = function ()
-{
- this.to('');
- this.cc('');
- this.bcc('');
- this.replyTo('');
- this.subject('');
-
- this.requestReadReceipt(false);
-
- this.aDraftInfo = null;
- this.sInReplyTo = '';
- this.bFromDraft = false;
- this.sReferences = '';
-
- this.sendError(false);
- this.sendSuccessButSaveError(false);
- this.savedError(false);
- this.savedTime(0);
- this.savedOrSendingText('');
- this.emptyToError(false);
- this.attachmentsInProcessError(false);
- this.showCcAndBcc(false);
-
- this.attachments([]);
- this.dragAndDropOver(false);
- this.dragAndDropVisible(false);
-
- this.draftFolder('');
- this.draftUid('');
-
- this.sending(false);
- this.saving(false);
-
- if (this.oEditor)
- {
- this.oEditor.clear(false);
- }
-};
-
-/**
- * @return {Array}
- */
-PopupsComposeViewModel.prototype.getAttachmentsDownloadsForUpload = function ()
-{
- return _.map(_.filter(this.attachments(), function (oItem) {
- return oItem && '' === oItem.tempName();
- }), function (oItem) {
- return oItem.id;
- });
-};
-
-PopupsComposeViewModel.prototype.triggerForResize = function ()
-{
- this.resizer(!this.resizer());
- this.editorResizeThrottle();
-};
-
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends KnoinAbstractViewModel
- */
-function PopupsContactsViewModel()
-{
- KnoinAbstractViewModel.call(this, 'Popups', 'PopupsContacts');
-
- var
- self = this,
- fFastClearEmptyListHelper = function (aList) {
- if (aList && 0 < aList.length) {
- self.viewProperties.removeAll(aList);
- }
- }
- ;
-
- this.allowContactsSync = RL.data().allowContactsSync;
- this.enableContactsSync = RL.data().enableContactsSync;
- this.allowExport = !Globals.bMobileDevice;
-
- this.search = ko.observable('');
- this.contactsCount = ko.observable(0);
- this.contacts = RL.data().contacts;
- this.contactTags = RL.data().contactTags;
-
- this.currentContact = ko.observable(null);
-
- this.importUploaderButton = ko.observable(null);
-
- this.contactsPage = ko.observable(1);
- this.contactsPageCount = ko.computed(function () {
- var iPage = Math.ceil(this.contactsCount() / Consts.Defaults.ContactsPerPage);
- return 0 >= iPage ? 1 : iPage;
- }, this);
-
- this.contactsPagenator = ko.computed(Utils.computedPagenatorHelper(this.contactsPage, this.contactsPageCount));
-
- this.emptySelection = ko.observable(true);
- this.viewClearSearch = ko.observable(false);
-
- this.viewID = ko.observable('');
- this.viewReadOnly = ko.observable(false);
- this.viewProperties = ko.observableArray([]);
-
- this.viewTags = ko.observable('');
- this.viewTags.visibility = ko.observable(false);
- this.viewTags.focusTrigger = ko.observable(false);
-
- this.viewTags.focusTrigger.subscribe(function (bValue) {
- if (!bValue && '' === this.viewTags())
- {
- this.viewTags.visibility(false);
- }
- else if (bValue)
- {
- this.viewTags.visibility(true);
- }
- }, this);
-
- this.viewSaveTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
-
- this.viewPropertiesNames = this.viewProperties.filter(function(oProperty) {
- return -1 < Utils.inArray(oProperty.type(), [
- Enums.ContactPropertyType.FirstName, Enums.ContactPropertyType.LastName
- ]);
- });
-
- this.viewPropertiesOther = this.viewProperties.filter(function(oProperty) {
- return -1 < Utils.inArray(oProperty.type(), [
- Enums.ContactPropertyType.Note
- ]);
- });
-
- this.viewPropertiesOther = ko.computed(function () {
-
- var aList = _.filter(this.viewProperties(), function (oProperty) {
- return -1 < Utils.inArray(oProperty.type(), [
- Enums.ContactPropertyType.Nick
- ]);
- });
-
- return _.sortBy(aList, function (oProperty) {
- return oProperty.type();
- });
-
- }, this);
-
- this.viewPropertiesEmails = this.viewProperties.filter(function(oProperty) {
- return Enums.ContactPropertyType.Email === oProperty.type();
- });
-
- this.viewPropertiesWeb = this.viewProperties.filter(function(oProperty) {
- return Enums.ContactPropertyType.Web === oProperty.type();
- });
-
- this.viewHasNonEmptyRequaredProperties = ko.computed(function() {
-
- var
- aNames = this.viewPropertiesNames(),
- aEmail = this.viewPropertiesEmails(),
- fHelper = function (oProperty) {
- return '' !== Utils.trim(oProperty.value());
- }
- ;
-
- return !!(_.find(aNames, fHelper) || _.find(aEmail, fHelper));
- }, this);
-
- this.viewPropertiesPhones = this.viewProperties.filter(function(oProperty) {
- return Enums.ContactPropertyType.Phone === oProperty.type();
- });
-
- this.viewPropertiesEmailsNonEmpty = this.viewPropertiesNames.filter(function(oProperty) {
- return '' !== Utils.trim(oProperty.value());
- });
-
- this.viewPropertiesEmailsEmptyAndOnFocused = this.viewPropertiesEmails.filter(function(oProperty) {
- var bF = oProperty.focused();
- return '' === Utils.trim(oProperty.value()) && !bF;
- });
-
- this.viewPropertiesPhonesEmptyAndOnFocused = this.viewPropertiesPhones.filter(function(oProperty) {
- var bF = oProperty.focused();
- return '' === Utils.trim(oProperty.value()) && !bF;
- });
-
- this.viewPropertiesWebEmptyAndOnFocused = this.viewPropertiesWeb.filter(function(oProperty) {
- var bF = oProperty.focused();
- return '' === Utils.trim(oProperty.value()) && !bF;
- });
-
- this.viewPropertiesOtherEmptyAndOnFocused = ko.computed(function () {
- return _.filter(this.viewPropertiesOther(), function (oProperty) {
- var bF = oProperty.focused();
- return '' === Utils.trim(oProperty.value()) && !bF;
- });
- }, this);
-
- this.viewPropertiesEmailsEmptyAndOnFocused.subscribe(function(aList) {
- fFastClearEmptyListHelper(aList);
- });
-
- this.viewPropertiesPhonesEmptyAndOnFocused.subscribe(function(aList) {
- fFastClearEmptyListHelper(aList);
- });
-
- this.viewPropertiesWebEmptyAndOnFocused.subscribe(function(aList) {
- fFastClearEmptyListHelper(aList);
- });
-
- this.viewPropertiesOtherEmptyAndOnFocused.subscribe(function(aList) {
- fFastClearEmptyListHelper(aList);
- });
-
- this.viewSaving = ko.observable(false);
-
- this.useCheckboxesInList = RL.data().useCheckboxesInList;
-
- this.search.subscribe(function () {
- this.reloadContactList();
- }, this);
-
- this.contacts.subscribe(function () {
- Utils.windowResize();
- }, this);
-
- this.viewProperties.subscribe(function () {
- Utils.windowResize();
- }, this);
-
- this.contactsChecked = ko.computed(function () {
- return _.filter(this.contacts(), function (oItem) {
- return oItem.checked();
- });
- }, this);
-
- this.contactsCheckedOrSelected = ko.computed(function () {
-
- var
- aChecked = this.contactsChecked(),
- oSelected = this.currentContact()
- ;
-
- return _.union(aChecked, oSelected ? [oSelected] : []);
-
- }, this);
-
- this.contactsCheckedOrSelectedUids = ko.computed(function () {
- return _.map(this.contactsCheckedOrSelected(), function (oContact) {
- return oContact.idContact;
- });
- }, this);
-
- this.selector = new Selector(this.contacts, this.currentContact,
- '.e-contact-item .actionHandle', '.e-contact-item.selected', '.e-contact-item .checkboxItem',
- '.e-contact-item.focused');
-
- this.selector.on('onItemSelect', _.bind(function (oContact) {
- this.populateViewContact(oContact ? oContact : null);
- if (!oContact)
- {
- this.emptySelection(true);
- }
- }, this));
-
- this.selector.on('onItemGetUid', function (oContact) {
- return oContact ? oContact.generateUid() : '';
- });
-
- this.newCommand = Utils.createCommand(this, function () {
- this.populateViewContact(null);
- this.currentContact(null);
- });
-
- this.deleteCommand = Utils.createCommand(this, function () {
- this.deleteSelectedContacts();
- this.emptySelection(true);
- }, function () {
- return 0 < this.contactsCheckedOrSelected().length;
- });
-
- this.newMessageCommand = Utils.createCommand(this, function () {
- var aC = this.contactsCheckedOrSelected(), aE = [];
- if (Utils.isNonEmptyArray(aC))
- {
- aE = _.map(aC, function (oItem) {
- if (oItem)
- {
- var
- aData = oItem.getNameAndEmailHelper(),
- oEmail = aData ? new EmailModel(aData[0], aData[1]) : null
- ;
-
- if (oEmail && oEmail.validate())
- {
- return oEmail;
- }
- }
-
- return null;
- });
-
- aE = _.compact(aE);
- }
-
- if (Utils.isNonEmptyArray(aE))
- {
- kn.hideScreenPopup(PopupsContactsViewModel);
- kn.showScreenPopup(PopupsComposeViewModel, [Enums.ComposeType.Empty, null, aE]);
- }
-
- }, function () {
- return 0 < this.contactsCheckedOrSelected().length;
- });
-
- this.clearCommand = Utils.createCommand(this, function () {
- this.search('');
- });
-
- this.saveCommand = Utils.createCommand(this, function () {
-
- this.viewSaving(true);
- this.viewSaveTrigger(Enums.SaveSettingsStep.Animate);
-
- var
- sRequestUid = Utils.fakeMd5(),
- aProperties = []
- ;
-
- _.each(this.viewProperties(), function (oItem) {
- if (oItem.type() && '' !== Utils.trim(oItem.value()))
+ if (oIdentityToRemove)
{
- aProperties.push([oItem.type(), oItem.value(), oItem.typeStr()]);
- }
- });
+ this.identities.remove(fRemoveFolder);
- RL.remote().contactSave(function (sResult, oData) {
-
- var bRes = false;
- self.viewSaving(false);
-
- if (Enums.StorageResultType.Success === sResult && oData && oData.Result &&
- oData.Result.RequestUid === sRequestUid && 0 < Utils.pInt(oData.Result.ResultID))
- {
- if ('' === self.viewID())
- {
- self.viewID(Utils.pInt(oData.Result.ResultID));
- }
-
- self.reloadContactList();
- bRes = true;
- }
-
- _.delay(function () {
- self.viewSaveTrigger(bRes ? Enums.SaveSettingsStep.TrueResult : Enums.SaveSettingsStep.FalseResult);
- }, 300);
-
- if (bRes)
- {
- self.watchDirty(false);
-
- _.delay(function () {
- self.viewSaveTrigger(Enums.SaveSettingsStep.Idle);
- }, 1000);
- }
-
- }, sRequestUid, this.viewID(), this.viewTags(), aProperties);
-
- }, function () {
- var
- bV = this.viewHasNonEmptyRequaredProperties(),
- bReadOnly = this.viewReadOnly()
- ;
- return !this.viewSaving() && bV && !bReadOnly;
- });
-
- this.syncCommand = Utils.createCommand(this, function () {
-
- var self = this;
- RL.contactsSync(function (sResult, oData) {
- if (Enums.StorageResultType.Success !== sResult || !oData || !oData.Result)
- {
- window.alert(Utils.getNotification(
- oData && oData.ErrorCode ? oData.ErrorCode : Enums.Notification.ContactsSyncError));
- }
-
- self.reloadContactList(true);
- });
-
- }, function () {
- return !this.contacts.syncing() && !this.contacts.importing();
- });
-
- this.bDropPageAfterDelete = false;
-
- this.watchDirty = ko.observable(false);
- this.watchHash = ko.observable(false);
-
- this.viewHash = ko.computed(function () {
- return '' + self.viewTags() + '|' + _.map(self.viewProperties(), function (oItem) {
- return oItem.value();
- }).join('');
- });
-
-// this.saveCommandDebounce = _.debounce(_.bind(this.saveCommand, this), 1000);
-
- this.viewHash.subscribe(function () {
- if (this.watchHash() && !this.viewReadOnly() && !this.watchDirty())
- {
- this.watchDirty(true);
- }
- }, this);
-
- this.sDefaultKeyScope = Enums.KeyState.ContactList;
-
- Knoin.constructorEnd(this);
-}
-
-Utils.extendAsViewModel('PopupsContactsViewModel', PopupsContactsViewModel);
-
-PopupsContactsViewModel.prototype.getPropertyPlceholder = function (sType)
-{
- var sResult = '';
- switch (sType)
- {
- case Enums.ContactPropertyType.LastName:
- sResult = 'CONTACTS/PLACEHOLDER_ENTER_LAST_NAME';
- break;
- case Enums.ContactPropertyType.FirstName:
- sResult = 'CONTACTS/PLACEHOLDER_ENTER_FIRST_NAME';
- break;
- case Enums.ContactPropertyType.Nick:
- sResult = 'CONTACTS/PLACEHOLDER_ENTER_NICK_NAME';
- break;
- }
-
- return sResult;
-};
-
-PopupsContactsViewModel.prototype.addNewProperty = function (sType, sTypeStr)
-{
- this.viewProperties.push(new ContactPropertyModel(sType, sTypeStr || '', '', true, this.getPropertyPlceholder(sType)));
-};
-
-PopupsContactsViewModel.prototype.addNewOrFocusProperty = function (sType, sTypeStr)
-{
- var oItem = _.find(this.viewProperties(), function (oItem) {
- return sType === oItem.type();
- });
-
- if (oItem)
- {
- oItem.focused(true);
- }
- else
- {
- this.addNewProperty(sType, sTypeStr);
- }
-};
-
-PopupsContactsViewModel.prototype.addNewTag = function ()
-{
- this.viewTags.visibility(true);
- this.viewTags.focusTrigger(true);
-};
-
-PopupsContactsViewModel.prototype.addNewEmail = function ()
-{
- this.addNewProperty(Enums.ContactPropertyType.Email, 'Home');
-};
-
-PopupsContactsViewModel.prototype.addNewPhone = function ()
-{
- this.addNewProperty(Enums.ContactPropertyType.Phone, 'Mobile');
-};
-
-PopupsContactsViewModel.prototype.addNewWeb = function ()
-{
- this.addNewProperty(Enums.ContactPropertyType.Web);
-};
-
-PopupsContactsViewModel.prototype.addNewNickname = function ()
-{
- this.addNewOrFocusProperty(Enums.ContactPropertyType.Nick);
-};
-
-PopupsContactsViewModel.prototype.addNewNotes = function ()
-{
- this.addNewOrFocusProperty(Enums.ContactPropertyType.Note);
-};
-
-PopupsContactsViewModel.prototype.addNewBirthday = function ()
-{
- this.addNewOrFocusProperty(Enums.ContactPropertyType.Birthday);
-};
-
-//PopupsContactsViewModel.prototype.addNewAddress = function ()
-//{
-//};
-
-PopupsContactsViewModel.prototype.exportVcf = function ()
-{
- RL.download(RL.link().exportContactsVcf());
-};
-
-PopupsContactsViewModel.prototype.exportCsv = function ()
-{
- RL.download(RL.link().exportContactsCsv());
-};
-
-PopupsContactsViewModel.prototype.initUploader = function ()
-{
- if (this.importUploaderButton())
- {
- var
- oJua = new Jua({
- 'action': RL.link().uploadContacts(),
- 'name': 'uploader',
- 'queueSize': 1,
- 'multipleSizeLimit': 1,
- 'disableFolderDragAndDrop': true,
- 'disableDragAndDrop': true,
- 'disableMultiple': true,
- 'disableDocumentDropPrevent': true,
- 'clickElement': this.importUploaderButton()
- })
- ;
-
- if (oJua)
- {
- oJua
- .on('onStart', _.bind(function () {
- this.contacts.importing(true);
- }, this))
- .on('onComplete', _.bind(function (sId, bResult, oData) {
-
- this.contacts.importing(false);
- this.reloadContactList();
-
- if (!sId || !bResult || !oData || !oData.Result)
- {
- window.alert(Utils.i18n('CONTACTS/ERROR_IMPORT_FILE'));
- }
-
- }, this))
- ;
- }
- }
-};
-
-PopupsContactsViewModel.prototype.removeCheckedOrSelectedContactsFromList = function ()
-{
- var
- self = this,
- oKoContacts = this.contacts,
- oCurrentContact = this.currentContact(),
- iCount = this.contacts().length,
- aContacts = this.contactsCheckedOrSelected()
- ;
-
- if (0 < aContacts.length)
- {
- _.each(aContacts, function (oContact) {
-
- if (oCurrentContact && oCurrentContact.idContact === oContact.idContact)
- {
- oCurrentContact = null;
- self.currentContact(null);
- }
-
- oContact.deleted(true);
- iCount--;
- });
-
- if (iCount <= 0)
- {
- this.bDropPageAfterDelete = true;
- }
-
- _.delay(function () {
-
- _.each(aContacts, function (oContact) {
- oKoContacts.remove(oContact);
- });
-
- }, 500);
- }
-};
-
-PopupsContactsViewModel.prototype.deleteSelectedContacts = function ()
-{
- if (0 < this.contactsCheckedOrSelected().length)
- {
- RL.remote().contactsDelete(
- _.bind(this.deleteResponse, this),
- this.contactsCheckedOrSelectedUids()
- );
-
- this.removeCheckedOrSelectedContactsFromList();
- }
-};
-
-/**
- * @param {string} sResult
- * @param {AjaxJsonDefaultResponse} oData
- */
-PopupsContactsViewModel.prototype.deleteResponse = function (sResult, oData)
-{
- if (500 < (Enums.StorageResultType.Success === sResult && oData && oData.Time ? Utils.pInt(oData.Time) : 0))
- {
- this.reloadContactList(this.bDropPageAfterDelete);
- }
- else
- {
- _.delay((function (self) {
- return function () {
- self.reloadContactList(self.bDropPageAfterDelete);
- };
- }(this)), 500);
- }
-};
-
-PopupsContactsViewModel.prototype.removeProperty = function (oProp)
-{
- this.viewProperties.remove(oProp);
-};
-
-/**
- * @param {?ContactModel} oContact
- */
-PopupsContactsViewModel.prototype.populateViewContact = function (oContact)
-{
- var
- sId = '',
- sLastName = '',
- sFirstName = '',
- aList = []
- ;
-
- this.watchHash(false);
-
- this.emptySelection(false);
- this.viewReadOnly(false);
- this.viewTags('');
-
- if (oContact)
- {
- sId = oContact.idContact;
- if (Utils.isNonEmptyArray(oContact.properties))
- {
- _.each(oContact.properties, function (aProperty) {
- if (aProperty && aProperty[0])
- {
- if (Enums.ContactPropertyType.LastName === aProperty[0])
- {
- sLastName = aProperty[1];
- }
- else if (Enums.ContactPropertyType.FirstName === aProperty[0])
- {
- sFirstName = aProperty[1];
- }
- else
- {
- aList.push(new ContactPropertyModel(aProperty[0], aProperty[2] || '', aProperty[1]));
- }
- }
- });
- }
-
- this.viewTags(oContact.tags);
-
- this.viewReadOnly(!!oContact.readOnly);
- }
-
- this.viewTags.focusTrigger.valueHasMutated();
- this.viewTags.visibility('' !== this.viewTags());
-
- aList.unshift(new ContactPropertyModel(Enums.ContactPropertyType.LastName, '', sLastName, false,
- this.getPropertyPlceholder(Enums.ContactPropertyType.LastName)));
-
- aList.unshift(new ContactPropertyModel(Enums.ContactPropertyType.FirstName, '', sFirstName, !oContact,
- this.getPropertyPlceholder(Enums.ContactPropertyType.FirstName)));
-
- this.viewID(sId);
- this.viewProperties([]);
- this.viewProperties(aList);
-
- this.watchDirty(false);
- this.watchHash(true);
-};
-
-/**
- * @param {boolean=} bDropPagePosition = false
- */
-PopupsContactsViewModel.prototype.reloadContactList = function (bDropPagePosition)
-{
- var
- self = this,
- iOffset = (this.contactsPage() - 1) * Consts.Defaults.ContactsPerPage
- ;
-
- this.bDropPageAfterDelete = false;
-
- if (Utils.isUnd(bDropPagePosition) ? false : !!bDropPagePosition)
- {
- this.contactsPage(1);
- iOffset = 0;
- }
-
- this.contacts.loading(true);
- RL.remote().contacts(function (sResult, oData) {
- var
- iCount = 0,
- aList = [],
- aTagsList = []
- ;
-
- if (Enums.StorageResultType.Success === sResult && oData && oData.Result && oData.Result.List)
- {
- if (Utils.isNonEmptyArray(oData.Result.List))
- {
- aList = _.map(oData.Result.List, function (oItem) {
- var oContact = new ContactModel();
- return oContact.parse(oItem) ? oContact : null;
- });
-
- aList = _.compact(aList);
-
- iCount = Utils.pInt(oData.Result.Count);
- iCount = 0 < iCount ? iCount : 0;
- }
-
- if (Utils.isNonEmptyArray(oData.Result.Tags))
- {
- aTagsList = _.map(oData.Result.Tags, function (oItem) {
- var oContactTag = new ContactTagModel();
- return oContactTag.parse(oItem) ? oContactTag : null;
- });
-
- aTagsList = _.compact(aTagsList);
- }
- }
-
- self.contactsCount(iCount);
-
- self.contacts(aList);
- self.contacts.loading(false);
- self.contactTags(aTagsList);
-
- self.viewClearSearch('' !== self.search());
-
- }, iOffset, Consts.Defaults.ContactsPerPage, this.search());
-};
-
-PopupsContactsViewModel.prototype.onBuild = function (oDom)
-{
- this.oContentVisible = $('.b-list-content', oDom);
- this.oContentScrollable = $('.content', this.oContentVisible);
-
- this.selector.init(this.oContentVisible, this.oContentScrollable, Enums.KeyState.ContactList);
-
- var self = this;
-
- key('delete', Enums.KeyState.ContactList, function () {
- self.deleteCommand();
- return false;
- });
-
- oDom
- .on('click', '.e-pagenator .e-page', function () {
- var oPage = ko.dataFor(this);
- if (oPage)
- {
- self.contactsPage(Utils.pInt(oPage.value));
- self.reloadContactList();
- }
- })
- ;
-
- this.initUploader();
-};
-
-PopupsContactsViewModel.prototype.onShow = function ()
-{
- kn.routeOff();
- this.reloadContactList(true);
-};
-
-PopupsContactsViewModel.prototype.onHide = function ()
-{
- kn.routeOn();
- this.currentContact(null);
- this.emptySelection(true);
- this.search('');
- this.contactsCount(0);
- this.contacts([]);
-// _.each(this.contacts(), function (oItem) {
-// oItem.checked(false);
-// });
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends KnoinAbstractViewModel
- */
-function PopupsAdvancedSearchViewModel()
-{
- KnoinAbstractViewModel.call(this, 'Popups', 'PopupsAdvancedSearch');
-
- this.fromFocus = ko.observable(false);
-
- this.from = ko.observable('');
- this.to = ko.observable('');
- this.subject = ko.observable('');
- this.text = ko.observable('');
- this.selectedDateValue = ko.observable(-1);
-
- this.hasAttachment = ko.observable(false);
- this.starred = ko.observable(false);
- this.unseen = ko.observable(false);
-
- this.searchCommand = Utils.createCommand(this, function () {
-
- var sSearch = this.buildSearchString();
- if ('' !== sSearch)
- {
- RL.data().mainMessageListSearch(sSearch);
- }
-
- this.cancelCommand();
- });
-
- Knoin.constructorEnd(this);
-}
-
-Utils.extendAsViewModel('PopupsAdvancedSearchViewModel', PopupsAdvancedSearchViewModel);
-
-PopupsAdvancedSearchViewModel.prototype.buildSearchStringValue = function (sValue)
-{
- if (-1 < sValue.indexOf(' '))
- {
- sValue = '"' + sValue + '"';
- }
-
- return sValue;
-};
-
-PopupsAdvancedSearchViewModel.prototype.buildSearchString = function ()
-{
- var
- aResult = [],
- sFrom = Utils.trim(this.from()),
- sTo = Utils.trim(this.to()),
- sSubject = Utils.trim(this.subject()),
- sText = Utils.trim(this.text()),
- aIs = [],
- aHas = []
- ;
-
- if (sFrom && '' !== sFrom)
- {
- aResult.push('from:' + this.buildSearchStringValue(sFrom));
- }
-
- if (sTo && '' !== sTo)
- {
- aResult.push('to:' + this.buildSearchStringValue(sTo));
- }
-
- if (sSubject && '' !== sSubject)
- {
- aResult.push('subject:' + this.buildSearchStringValue(sSubject));
- }
-
- if (this.hasAttachment())
- {
- aHas.push('attachment');
- }
-
- if (this.unseen())
- {
- aIs.push('unseen');
- }
-
- if (this.starred())
- {
- aIs.push('flagged');
- }
-
- if (0 < aHas.length)
- {
- aResult.push('has:' + aHas.join(','));
- }
-
- if (0 < aIs.length)
- {
- aResult.push('is:' + aIs.join(','));
- }
-
- if (-1 < this.selectedDateValue())
- {
- aResult.push('date:' + moment().subtract('days', this.selectedDateValue()).format('YYYY.MM.DD') + '/');
- }
-
- if (sText && '' !== sText)
- {
- aResult.push('text:' + this.buildSearchStringValue(sText));
- }
-
- return Utils.trim(aResult.join(' '));
-};
-
-PopupsAdvancedSearchViewModel.prototype.clearPopup = function ()
-{
- this.from('');
- this.to('');
- this.subject('');
- this.text('');
-
- this.selectedDateValue(-1);
- this.hasAttachment(false);
- this.starred(false);
- this.unseen(false);
-
- this.fromFocus(true);
-};
-
-PopupsAdvancedSearchViewModel.prototype.onShow = function ()
-{
- this.clearPopup();
-};
-
-PopupsAdvancedSearchViewModel.prototype.onFocus = function ()
-{
- this.fromFocus(true);
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends KnoinAbstractViewModel
- */
-function PopupsAddAccountViewModel()
-{
- KnoinAbstractViewModel.call(this, 'Popups', 'PopupsAddAccount');
-
- this.email = ko.observable('');
- this.password = ko.observable('');
-
- this.emailError = ko.observable(false);
- this.passwordError = ko.observable(false);
-
- this.email.subscribe(function () {
- this.emailError(false);
- }, this);
-
- this.password.subscribe(function () {
- this.passwordError(false);
- }, this);
-
- this.submitRequest = ko.observable(false);
- this.submitError = ko.observable('');
-
- this.emailFocus = ko.observable(false);
-
- this.addAccountCommand = Utils.createCommand(this, function () {
-
- this.emailError('' === Utils.trim(this.email()));
- this.passwordError('' === Utils.trim(this.password()));
-
- if (this.emailError() || this.passwordError())
- {
- return false;
- }
-
- this.submitRequest(true);
-
- RL.remote().accountAdd(_.bind(function (sResult, oData) {
-
- this.submitRequest(false);
- if (Enums.StorageResultType.Success === sResult && oData && 'AccountAdd' === oData.Action)
- {
- if (oData.Result)
- {
+ Remote.identityDelete(function () {
RL.accountsAndIdentities();
- this.cancelCommand();
- }
- else if (oData.ErrorCode)
- {
- this.submitError(Utils.getNotification(oData.ErrorCode));
- }
- }
- else
- {
- this.submitError(Utils.getNotification(Enums.Notification.UnknownError));
- }
-
- }, this), this.email(), '', this.password());
-
- return true;
-
- }, function () {
- return !this.submitRequest();
- });
-
- Knoin.constructorEnd(this);
-}
-
-Utils.extendAsViewModel('PopupsAddAccountViewModel', PopupsAddAccountViewModel);
-
-PopupsAddAccountViewModel.prototype.clearPopup = function ()
-{
- this.email('');
- this.password('');
-
- this.emailError(false);
- this.passwordError(false);
-
- this.submitRequest(false);
- this.submitError('');
-};
-
-PopupsAddAccountViewModel.prototype.onShow = function ()
-{
- this.clearPopup();
-};
-
-PopupsAddAccountViewModel.prototype.onFocus = function ()
-{
- this.emailFocus(true);
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends KnoinAbstractViewModel
- */
-function PopupsAddOpenPgpKeyViewModel()
-{
- KnoinAbstractViewModel.call(this, 'Popups', 'PopupsAddOpenPgpKey');
-
- this.key = ko.observable('');
- this.key.error = ko.observable(false);
- this.key.focus = ko.observable(false);
-
- this.key.subscribe(function () {
- this.key.error(false);
- }, this);
-
- this.addOpenPgpKeyCommand = Utils.createCommand(this, function () {
-
- var
- iCount = 30,
- aMatch = null,
- sKey = Utils.trim(this.key()),
- oReg = /[\-]{3,6}BEGIN[\s]PGP[\s](PRIVATE|PUBLIC)[\s]KEY[\s]BLOCK[\-]{3,6}[\s\S]+?[\-]{3,6}END[\s]PGP[\s](PRIVATE|PUBLIC)[\s]KEY[\s]BLOCK[\-]{3,6}/gi,
- oOpenpgpKeyring = RL.data().openpgpKeyring
- ;
-
- sKey = sKey.replace(/[\r\n]([a-zA-Z0-9]{2,}:[^\r\n]+)[\r\n]+([a-zA-Z0-9\/\\+=]{10,})/g, '\n$1!-!N!-!$2')
- .replace(/[\n\r]+/g, '\n').replace(/!-!N!-!/g, '\n\n');
-
- this.key.error('' === sKey);
-
- if (!oOpenpgpKeyring || this.key.error())
- {
- return false;
- }
-
- do
- {
- aMatch = oReg.exec(sKey);
- if (!aMatch || 0 > iCount)
- {
- break;
- }
-
- if (aMatch[0] && aMatch[1] && aMatch[2] && aMatch[1] === aMatch[2])
- {
- if ('PRIVATE' === aMatch[1])
- {
- oOpenpgpKeyring.privateKeys.importKey(aMatch[0]);
- }
- else if ('PUBLIC' === aMatch[1])
- {
- oOpenpgpKeyring.publicKeys.importKey(aMatch[0]);
- }
- }
-
- iCount--;
- }
- while (true);
-
- oOpenpgpKeyring.store();
-
- RL.reloadOpenPgpKeys();
- Utils.delegateRun(this, 'cancelCommand');
-
- return true;
- });
-
- Knoin.constructorEnd(this);
-}
-
-Utils.extendAsViewModel('PopupsAddOpenPgpKeyViewModel', PopupsAddOpenPgpKeyViewModel);
-
-PopupsAddOpenPgpKeyViewModel.prototype.clearPopup = function ()
-{
- this.key('');
- this.key.error(false);
-};
-
-PopupsAddOpenPgpKeyViewModel.prototype.onShow = function ()
-{
- this.clearPopup();
-};
-
-PopupsAddOpenPgpKeyViewModel.prototype.onFocus = function ()
-{
- this.key.focus(true);
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends KnoinAbstractViewModel
- */
-function PopupsViewOpenPgpKeyViewModel()
-{
- KnoinAbstractViewModel.call(this, 'Popups', 'PopupsViewOpenPgpKey');
-
- this.key = ko.observable('');
- this.keyDom = ko.observable(null);
-
- Knoin.constructorEnd(this);
-}
-
-Utils.extendAsViewModel('PopupsViewOpenPgpKeyViewModel', PopupsViewOpenPgpKeyViewModel);
-
-PopupsViewOpenPgpKeyViewModel.prototype.clearPopup = function ()
-{
- this.key('');
-};
-
-PopupsViewOpenPgpKeyViewModel.prototype.selectKey = function ()
-{
- var oEl = this.keyDom();
- if (oEl)
- {
- Utils.selectElement(oEl);
- }
-};
-
-PopupsViewOpenPgpKeyViewModel.prototype.onShow = function (oOpenPgpKey)
-{
- this.clearPopup();
-
- if (oOpenPgpKey)
- {
- this.key(oOpenPgpKey.armor);
- }
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends KnoinAbstractViewModel
- */
-function PopupsGenerateNewOpenPgpKeyViewModel()
-{
- KnoinAbstractViewModel.call(this, 'Popups', 'PopupsGenerateNewOpenPgpKey');
-
- this.email = ko.observable('');
- this.email.focus = ko.observable('');
- this.email.error = ko.observable(false);
-
- this.name = ko.observable('');
- this.password = ko.observable('');
- this.keyBitLength = ko.observable(2048);
-
- this.submitRequest = ko.observable(false);
-
- this.email.subscribe(function () {
- this.email.error(false);
- }, this);
-
- this.generateOpenPgpKeyCommand = Utils.createCommand(this, function () {
-
- var
- self = this,
- sUserID = '',
- mKeyPair = null,
- oOpenpgpKeyring = RL.data().openpgpKeyring
- ;
-
- this.email.error('' === Utils.trim(this.email()));
- if (!oOpenpgpKeyring || this.email.error())
- {
- return false;
- }
-
- sUserID = this.email();
- if ('' !== this.name())
- {
- sUserID = this.name() + ' <' + sUserID + '>';
- }
-
- this.submitRequest(true);
-
- _.delay(function () {
-// mKeyPair = window.openpgp.generateKeyPair(1, Utils.pInt(self.keyBitLength()), sUserID, Utils.trim(self.password()));
- mKeyPair = window.openpgp.generateKeyPair({
- 'userId': sUserID,
- 'numBits': Utils.pInt(self.keyBitLength()),
- 'passphrase': Utils.trim(self.password())
- });
-
- if (mKeyPair && mKeyPair.privateKeyArmored)
- {
- oOpenpgpKeyring.privateKeys.importKey(mKeyPair.privateKeyArmored);
- oOpenpgpKeyring.publicKeys.importKey(mKeyPair.publicKeyArmored);
- oOpenpgpKeyring.store();
-
- RL.reloadOpenPgpKeys();
- Utils.delegateRun(self, 'cancelCommand');
- }
-
- self.submitRequest(false);
- }, 100);
-
- return true;
- });
-
- Knoin.constructorEnd(this);
-}
-
-Utils.extendAsViewModel('PopupsGenerateNewOpenPgpKeyViewModel', PopupsGenerateNewOpenPgpKeyViewModel);
-
-PopupsGenerateNewOpenPgpKeyViewModel.prototype.clearPopup = function ()
-{
- this.name('');
- this.password('');
-
- this.email('');
- this.email.error(false);
- this.keyBitLength(2048);
-};
-
-PopupsGenerateNewOpenPgpKeyViewModel.prototype.onShow = function ()
-{
- this.clearPopup();
-};
-
-PopupsGenerateNewOpenPgpKeyViewModel.prototype.onFocus = function ()
-{
- this.email.focus(true);
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends KnoinAbstractViewModel
- */
-function PopupsComposeOpenPgpViewModel()
-{
- KnoinAbstractViewModel.call(this, 'Popups', 'PopupsComposeOpenPgp');
-
- this.notification = ko.observable('');
-
- this.sign = ko.observable(true);
- this.encrypt = ko.observable(true);
-
- this.password = ko.observable('');
- this.password.focus = ko.observable(false);
- this.buttonFocus = ko.observable(false);
-
- this.from = ko.observable('');
- this.to = ko.observableArray([]);
- this.text = ko.observable('');
-
- this.resultCallback = null;
-
- this.submitRequest = ko.observable(false);
-
- // commands
- this.doCommand = Utils.createCommand(this, function () {
-
- var
- self = this,
- bResult = true,
- oData = RL.data(),
- oPrivateKey = null,
- aPublicKeys = []
- ;
-
- this.submitRequest(true);
-
- if (bResult && this.sign() && '' === this.from())
- {
- this.notification(Utils.i18n('PGP_NOTIFICATIONS/SPECIFY_FROM_EMAIL'));
- bResult = false;
- }
-
- if (bResult && this.sign())
- {
- oPrivateKey = oData.findPrivateKeyByEmail(this.from(), this.password());
- if (!oPrivateKey)
- {
- this.notification(Utils.i18n('PGP_NOTIFICATIONS/NO_PRIVATE_KEY_FOUND_FOR', {
- 'EMAIL': this.from()
- }));
-
- bResult = false;
+ }, oIdentityToRemove.id);
}
}
+ };
- if (bResult && this.encrypt() && 0 === this.to().length)
- {
- this.notification(Utils.i18n('PGP_NOTIFICATIONS/SPECIFY_AT_LEAST_ONE_RECIPIENT'));
- bResult = false;
- }
-
- if (bResult && this.encrypt())
- {
- aPublicKeys = [];
- _.each(this.to(), function (sEmail) {
- var aKeys = oData.findPublicKeysByEmail(sEmail);
- if (0 === aKeys.length && bResult)
- {
- self.notification(Utils.i18n('PGP_NOTIFICATIONS/NO_PUBLIC_KEYS_FOUND_FOR', {
- 'EMAIL': sEmail
- }));
-
- bResult = false;
- }
-
- aPublicKeys = aPublicKeys.concat(aKeys);
- });
-
- if (bResult && (0 === aPublicKeys.length || this.to().length !== aPublicKeys.length))
- {
- bResult = false;
- }
- }
-
- _.delay(function () {
-
- if (self.resultCallback && bResult)
- {
- try {
-
- if (oPrivateKey && 0 === aPublicKeys.length)
- {
- self.resultCallback(
- window.openpgp.signClearMessage([oPrivateKey], self.text())
- );
- }
- else if (oPrivateKey && 0 < aPublicKeys.length)
- {
- self.resultCallback(
- window.openpgp.signAndEncryptMessage(aPublicKeys, oPrivateKey, self.text())
- );
- }
- else if (!oPrivateKey && 0 < aPublicKeys.length)
- {
- self.resultCallback(
- window.openpgp.encryptMessage(aPublicKeys, self.text())
- );
- }
- }
- catch (e)
- {
- self.notification(Utils.i18n('PGP_NOTIFICATIONS/PGP_ERROR', {
- 'ERROR': '' + e
- }));
-
- bResult = false;
- }
- }
-
- if (bResult)
- {
- self.cancelCommand();
- }
-
- self.submitRequest(false);
-
- }, 10);
-
- }, function () {
- return !this.submitRequest() && (this.sign() || this.encrypt());
- });
-
- this.sDefaultKeyScope = Enums.KeyState.PopupComposeOpenPGP;
-
- Knoin.constructorEnd(this);
-}
-
-Utils.extendAsViewModel('PopupsComposeOpenPgpViewModel', PopupsComposeOpenPgpViewModel);
-
-PopupsComposeOpenPgpViewModel.prototype.clearPopup = function ()
-{
- this.notification('');
-
- this.password('');
- this.password.focus(false);
- this.buttonFocus(false);
-
- this.from('');
- this.to([]);
- this.text('');
-
- this.submitRequest(false);
-
- this.resultCallback = null;
-};
-
-PopupsComposeOpenPgpViewModel.prototype.onBuild = function ()
-{
- key('tab,shift+tab', Enums.KeyState.PopupComposeOpenPGP, _.bind(function () {
-
- switch (true)
- {
- case this.password.focus():
- this.buttonFocus(true);
- break;
- case this.buttonFocus():
- this.password.focus(true);
- break;
- }
-
- return false;
-
- }, this));
-};
-
-PopupsComposeOpenPgpViewModel.prototype.onHide = function ()
-{
- this.clearPopup();
-};
-
-PopupsComposeOpenPgpViewModel.prototype.onFocus = function ()
-{
- if (this.sign())
+ SettingsIdentities.prototype.onFocus = function ()
{
- this.password.focus(true);
- }
- else
- {
- this.buttonFocus(true);
- }
-};
-
-PopupsComposeOpenPgpViewModel.prototype.onShow = function (fCallback, sText, sFromEmail, sTo, sCc, sBcc)
-{
- this.clearPopup();
-
- var
- oEmail = new EmailModel(),
- sResultFromEmail = '',
- aRec = []
- ;
-
- this.resultCallback = fCallback;
-
- oEmail.clear();
- oEmail.mailsoParse(sFromEmail);
- if ('' !== oEmail.email)
- {
- sResultFromEmail = oEmail.email;
- }
-
- if ('' !== sTo)
- {
- aRec.push(sTo);
- }
-
- if ('' !== sCc)
- {
- aRec.push(sCc);
- }
-
- if ('' !== sBcc)
- {
- aRec.push(sBcc);
- }
-
- aRec = aRec.join(', ').split(',');
- aRec = _.compact(_.map(aRec, function (sValue) {
- oEmail.clear();
- oEmail.mailsoParse(Utils.trim(sValue));
- return '' === oEmail.email ? false : oEmail.email;
- }));
-
- this.from(sResultFromEmail);
- this.to(aRec);
- this.text(sText);
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends KnoinAbstractViewModel
- */
-function PopupsIdentityViewModel()
-{
- KnoinAbstractViewModel.call(this, 'Popups', 'PopupsIdentity');
-
- this.id = '';
- this.edit = ko.observable(false);
- this.owner = ko.observable(false);
-
- this.email = ko.observable('').validateEmail();
- this.email.focused = ko.observable(false);
- this.name = ko.observable('');
- this.name.focused = ko.observable(false);
- this.replyTo = ko.observable('').validateSimpleEmail();
- this.replyTo.focused = ko.observable(false);
- this.bcc = ko.observable('').validateSimpleEmail();
- this.bcc.focused = ko.observable(false);
-
-// this.email.subscribe(function () {
-// this.email.hasError(false);
-// }, this);
-
- this.submitRequest = ko.observable(false);
- this.submitError = ko.observable('');
-
- this.addOrEditIdentityCommand = Utils.createCommand(this, function () {
-
- if (!this.email.hasError())
- {
- this.email.hasError('' === Utils.trim(this.email()));
- }
-
- if (this.email.hasError())
- {
- if (!this.owner())
- {
- this.email.focused(true);
- }
-
- return false;
- }
-
- if (this.replyTo.hasError())
- {
- this.replyTo.focused(true);
- return false;
- }
-
- if (this.bcc.hasError())
- {
- this.bcc.focused(true);
- return false;
- }
-
- this.submitRequest(true);
-
- RL.remote().identityUpdate(_.bind(function (sResult, oData) {
-
- this.submitRequest(false);
- if (Enums.StorageResultType.Success === sResult && oData)
- {
- if (oData.Result)
- {
- RL.accountsAndIdentities();
- this.cancelCommand();
- }
- else if (oData.ErrorCode)
- {
- this.submitError(Utils.getNotification(oData.ErrorCode));
- }
- }
- else
- {
- this.submitError(Utils.getNotification(Enums.Notification.UnknownError));
- }
-
- }, this), this.id, this.email(), this.name(), this.replyTo(), this.bcc());
-
- return true;
-
- }, function () {
- return !this.submitRequest();
- });
-
- this.label = ko.computed(function () {
- return Utils.i18n('POPUPS_IDENTITIES/' + (this.edit() ? 'TITLE_UPDATE_IDENTITY': 'TITLE_ADD_IDENTITY'));
- }, this);
-
- this.button = ko.computed(function () {
- return Utils.i18n('POPUPS_IDENTITIES/' + (this.edit() ? 'BUTTON_UPDATE_IDENTITY': 'BUTTON_ADD_IDENTITY'));
- }, this);
-
- Knoin.constructorEnd(this);
-}
-
-Utils.extendAsViewModel('PopupsIdentityViewModel', PopupsIdentityViewModel);
-
-PopupsIdentityViewModel.prototype.clearPopup = function ()
-{
- this.id = '';
- this.edit(false);
- this.owner(false);
-
- this.name('');
- this.email('');
- this.replyTo('');
- this.bcc('');
-
- this.email.hasError(false);
- this.replyTo.hasError(false);
- this.bcc.hasError(false);
-
- this.submitRequest(false);
- this.submitError('');
-};
-
-/**
- * @param {?IdentityModel} oIdentity
- */
-PopupsIdentityViewModel.prototype.onShow = function (oIdentity)
-{
- this.clearPopup();
-
- if (oIdentity)
- {
- this.edit(true);
-
- this.id = oIdentity.id;
- this.name(oIdentity.name());
- this.email(oIdentity.email());
- this.replyTo(oIdentity.replyTo());
- this.bcc(oIdentity.bcc());
-
- this.owner(this.id === RL.data().accountEmail());
- }
-};
-
-PopupsIdentityViewModel.prototype.onFocus = function ()
-{
- if (!this.owner())
- {
- this.email.focused(true);
- }
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends KnoinAbstractViewModel
- */
-function PopupsLanguagesViewModel()
-{
- KnoinAbstractViewModel.call(this, 'Popups', 'PopupsLanguages');
-
- this.exp = ko.observable(false);
-
- this.languages = ko.computed(function () {
- return _.map(RL.data().languages(), function (sLanguage) {
- return {
- 'key': sLanguage,
- 'selected': ko.observable(false),
- 'fullName': Utils.convertLangName(sLanguage)
- };
- });
- });
-
- RL.data().mainLanguage.subscribe(function () {
- this.resetMainLanguage();
- }, this);
-
- Knoin.constructorEnd(this);
-}
-
-Utils.extendAsViewModel('PopupsLanguagesViewModel', PopupsLanguagesViewModel);
-
-PopupsLanguagesViewModel.prototype.languageEnName = function (sLanguage)
-{
- return Utils.convertLangName(sLanguage, true);
-};
-
-PopupsLanguagesViewModel.prototype.resetMainLanguage = function ()
-{
- var sCurrent = RL.data().mainLanguage();
- _.each(this.languages(), function (oItem) {
- oItem['selected'](oItem['key'] === sCurrent);
- });
-};
-
-PopupsLanguagesViewModel.prototype.onShow = function ()
-{
- this.exp(true);
-
- this.resetMainLanguage();
-};
-
-PopupsLanguagesViewModel.prototype.onHide = function ()
-{
- this.exp(false);
-};
-
-PopupsLanguagesViewModel.prototype.changeLanguage = function (sLang)
-{
- RL.data().mainLanguage(sLang);
- this.cancelCommand();
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends KnoinAbstractViewModel
- */
-function PopupsTwoFactorTestViewModel()
-{
- KnoinAbstractViewModel.call(this, 'Popups', 'PopupsTwoFactorTest');
-
- var self = this;
-
- this.code = ko.observable('');
- this.code.focused = ko.observable(false);
- this.code.status = ko.observable(null);
-
- this.testing = ko.observable(false);
-
- // commands
- this.testCode = Utils.createCommand(this, function () {
-
- this.testing(true);
- RL.remote().testTwoFactor(function (sResult, oData) {
-
- self.testing(false);
- self.code.status(Enums.StorageResultType.Success === sResult && oData && oData.Result ? true : false);
-
- }, this.code());
-
- }, function () {
- return '' !== this.code() && !this.testing();
- });
-
- Knoin.constructorEnd(this);
-}
-
-Utils.extendAsViewModel('PopupsTwoFactorTestViewModel', PopupsTwoFactorTestViewModel);
-
-PopupsTwoFactorTestViewModel.prototype.clearPopup = function ()
-{
- this.code('');
- this.code.focused(false);
- this.code.status(null);
- this.testing(false);
-};
-
-PopupsTwoFactorTestViewModel.prototype.onShow = function ()
-{
- this.clearPopup();
-};
-
-PopupsTwoFactorTestViewModel.prototype.onFocus = function ()
-{
- this.code.focused(true);
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends KnoinAbstractViewModel
- */
-function PopupsAskViewModel()
-{
- KnoinAbstractViewModel.call(this, 'Popups', 'PopupsAsk');
-
- this.askDesc = ko.observable('');
- this.yesButton = ko.observable('');
- this.noButton = ko.observable('');
-
- this.yesFocus = ko.observable(false);
- this.noFocus = ko.observable(false);
-
- this.fYesAction = null;
- this.fNoAction = null;
-
- this.bDisabeCloseOnEsc = true;
- this.sDefaultKeyScope = Enums.KeyState.PopupAsk;
-
- Knoin.constructorEnd(this);
-}
-
-Utils.extendAsViewModel('PopupsAskViewModel', PopupsAskViewModel);
-
-PopupsAskViewModel.prototype.clearPopup = function ()
-{
- this.askDesc('');
- this.yesButton(Utils.i18n('POPUPS_ASK/BUTTON_YES'));
- this.noButton(Utils.i18n('POPUPS_ASK/BUTTON_NO'));
-
- this.yesFocus(false);
- this.noFocus(false);
-
- this.fYesAction = null;
- this.fNoAction = null;
-};
-
-PopupsAskViewModel.prototype.yesClick = function ()
-{
- this.cancelCommand();
-
- if (Utils.isFunc(this.fYesAction))
- {
- this.fYesAction.call(null);
- }
-};
-
-PopupsAskViewModel.prototype.noClick = function ()
-{
- this.cancelCommand();
-
- if (Utils.isFunc(this.fNoAction))
- {
- this.fNoAction.call(null);
- }
-};
-
-/**
- * @param {string} sAskDesc
- * @param {Function=} fYesFunc
- * @param {Function=} fNoFunc
- * @param {string=} sYesButton
- * @param {string=} sNoButton
- */
-PopupsAskViewModel.prototype.onShow = function (sAskDesc, fYesFunc, fNoFunc, sYesButton, sNoButton)
-{
- this.clearPopup();
-
- this.fYesAction = fYesFunc || null;
- this.fNoAction = fNoFunc || null;
-
- this.askDesc(sAskDesc || '');
- if (sYesButton)
- {
- this.yesButton(sYesButton);
- }
-
- if (sYesButton)
- {
- this.yesButton(sNoButton);
- }
-};
-
-PopupsAskViewModel.prototype.onFocus = function ()
-{
- this.yesFocus(true);
-};
-
-PopupsAskViewModel.prototype.onBuild = function ()
-{
- key('tab, shift+tab, right, left', Enums.KeyState.PopupAsk, _.bind(function () {
- if (this.yesFocus())
- {
- this.noFocus(true);
- }
- else
- {
- this.yesFocus(true);
- }
- return false;
- }, this));
-
- key('esc', Enums.KeyState.PopupAsk, _.bind(function () {
- this.noClick();
- return false;
- }, this));
-};
-
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends KnoinAbstractViewModel
- */
-function PopupsKeyboardShortcutsHelpViewModel()
-{
- KnoinAbstractViewModel.call(this, 'Popups', 'PopupsKeyboardShortcutsHelp');
-
- this.sDefaultKeyScope = Enums.KeyState.PopupKeyboardShortcutsHelp;
-
- Knoin.constructorEnd(this);
-}
-
-Utils.extendAsViewModel('PopupsKeyboardShortcutsHelpViewModel', PopupsKeyboardShortcutsHelpViewModel);
-
-PopupsKeyboardShortcutsHelpViewModel.prototype.onBuild = function (oDom)
-{
- key('tab, shift+tab, left, right', Enums.KeyState.PopupKeyboardShortcutsHelp, _.bind(function (event, handler) {
- if (event && handler)
+ if (!this.editor && this.signatureDom())
{
var
- $tabs = oDom.find('.nav.nav-tabs > li'),
- bNext = handler && ('tab' === handler.shortcut || 'right' === handler.shortcut),
- iIndex = $tabs.index($tabs.filter('.active'))
+ self = this,
+ sSignature = Data.signature()
;
- if (!bNext && iIndex > 0)
- {
- iIndex--;
- }
- else if (bNext && iIndex < $tabs.length - 1)
- {
- iIndex++;
- }
- else
- {
- iIndex = bNext ? 0 : $tabs.length - 1;
- }
-
- $tabs.eq(iIndex).find('a[data-toggle="tab"]').tab('show');
- return false;
+ this.editor = new NewHtmlEditorWrapper(self.signatureDom(), function () {
+ Data.signature(
+ (self.editor.isHtml() ? ':HTML:' : '') + self.editor.getData()
+ );
+ }, function () {
+ if (':HTML:' === sSignature.substr(0, 6))
+ {
+ self.editor.setHtml(sSignature.substr(6), false);
+ }
+ else
+ {
+ self.editor.setPlain(sSignature, false);
+ }
+ });
}
- }, this));
-};
-
+ };
+
+ SettingsIdentities.prototype.onBuild = function (oDom)
+ {
+ var self = this;
+
+ oDom
+ .on('click', '.identity-item .e-action', function () {
+ var oIdentityItem = ko.dataFor(this);
+ if (oIdentityItem)
+ {
+ self.editIdentity(oIdentityItem);
+ }
+ })
+ ;
+
+ _.delay(function () {
+
+ var
+ f1 = Utils.settingsSaveHelperSimpleFunction(self.displayNameTrigger, self),
+ f2 = Utils.settingsSaveHelperSimpleFunction(self.replyTrigger, self),
+ f3 = Utils.settingsSaveHelperSimpleFunction(self.signatureTrigger, self),
+ f4 = Utils.settingsSaveHelperSimpleFunction(self.defaultIdentityIDTrigger, self)
+ ;
+
+ Data.defaultIdentityID.subscribe(function (sValue) {
+ Remote.saveSettings(f4, {
+ 'DefaultIdentityID': sValue
+ });
+ });
+
+ Data.displayName.subscribe(function (sValue) {
+ Remote.saveSettings(f1, {
+ 'DisplayName': sValue
+ });
+ });
+
+ Data.replyTo.subscribe(function (sValue) {
+ Remote.saveSettings(f2, {
+ 'ReplyTo': sValue
+ });
+ });
+
+ Data.signature.subscribe(function (sValue) {
+ Remote.saveSettings(f3, {
+ 'Signature': sValue
+ });
+ });
+
+ Data.signatureToAll.subscribe(function (bValue) {
+ Remote.saveSettings(null, {
+ 'SignatureToAll': bValue ? '1' : '0'
+ });
+ });
+
+ }, 50);
+ };
+
+ module.exports = SettingsIdentities;
+
+}(module));
+},{"../Boots/RainLoopApp.js":4,"../Common/Enums.js":7,"../Common/NewHtmlEditorWrapper.js":11,"../Common/Utils.js":14,"../External/ko.js":28,"../Knoin/Knoin.js":33,"../Storages/WebMailAjaxRemoteStorage.js":65,"../Storages/WebMailDataStorage.js":67,"../ViewModels/Popups/PopupsIdentityViewModel.js":84}],54:[function(require,module,exports){
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-/**
- * @constructor
- * @extends KnoinAbstractViewModel
- */
-function PopupsFilterViewModel()
-{
- KnoinAbstractViewModel.call(this, 'Popups', 'PopupsFilter');
+(function (module) {
- this.filter = ko.observable(null);
+ 'use strict';
- this.selectedFolderValue = ko.observable(Consts.Values.UnuseOptionValue);
- this.folderSelectList = RL.data().folderMenuForMove;
- this.defautOptionsAfterRender = Utils.defautOptionsAfterRender;
+ var
+ ko = require('../External/ko.js'),
+
+ Enums = require('../Common/Enums.js'),
+ Utils = require('../Common/Utils.js'),
+ NewHtmlEditorWrapper = require('../Common/NewHtmlEditorWrapper.js'),
- Knoin.constructorEnd(this);
-}
+ Data = require('../Storages/WebMailDataStorage.js'),
+ Remote = require('../Storages/WebMailAjaxRemoteStorage.js')
+ ;
-Utils.extendAsViewModel('PopupsFilterViewModel', PopupsFilterViewModel);
+ /**
+ * @constructor
+ */
+ function SettingsIdentity()
+ {
+ this.editor = null;
-PopupsFilterViewModel.prototype.clearPopup = function ()
-{
+ this.displayName = Data.displayName;
+ this.signature = Data.signature;
+ this.signatureToAll = Data.signatureToAll;
+ this.replyTo = Data.replyTo;
-};
+ this.signatureDom = ko.observable(null);
-PopupsFilterViewModel.prototype.onShow = function (oFilter)
-{
- this.clearPopup();
+ this.displayNameTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
+ this.replyTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
+ this.signatureTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
+ }
- this.filter(oFilter);
-};
+ SettingsIdentity.prototype.onFocus = function ()
+ {
+ if (!this.editor && this.signatureDom())
+ {
+ var
+ self = this,
+ sSignature = Data.signature()
+ ;
-PopupsFilterViewModel.prototype.onFocus = function ()
-{
+ this.editor = new NewHtmlEditorWrapper(self.signatureDom(), function () {
+ Data.signature(
+ (self.editor.isHtml() ? ':HTML:' : '') + self.editor.getData()
+ );
+ }, function () {
+ if (':HTML:' === sSignature.substr(0, 6))
+ {
+ self.editor.setHtml(sSignature.substr(6), false);
+ }
+ else
+ {
+ self.editor.setPlain(sSignature, false);
+ }
+ });
+ }
+ };
-};
-
+ SettingsIdentity.prototype.onBuild = function ()
+ {
+ var self = this;
+ _.delay(function () {
+
+ var
+ f1 = Utils.settingsSaveHelperSimpleFunction(self.displayNameTrigger, self),
+ f2 = Utils.settingsSaveHelperSimpleFunction(self.replyTrigger, self),
+ f3 = Utils.settingsSaveHelperSimpleFunction(self.signatureTrigger, self)
+ ;
+
+ Data.displayName.subscribe(function (sValue) {
+ Remote.saveSettings(f1, {
+ 'DisplayName': sValue
+ });
+ });
+
+ Data.replyTo.subscribe(function (sValue) {
+ Remote.saveSettings(f2, {
+ 'ReplyTo': sValue
+ });
+ });
+
+ Data.signature.subscribe(function (sValue) {
+ Remote.saveSettings(f3, {
+ 'Signature': sValue
+ });
+ });
+
+ Data.signatureToAll.subscribe(function (bValue) {
+ Remote.saveSettings(null, {
+ 'SignatureToAll': bValue ? '1' : '0'
+ });
+ });
+
+ }, 50);
+ };
+
+ module.exports = SettingsIdentity;
+
+}(module));
+},{"../Common/Enums.js":7,"../Common/NewHtmlEditorWrapper.js":11,"../Common/Utils.js":14,"../External/ko.js":28,"../Storages/WebMailAjaxRemoteStorage.js":65,"../Storages/WebMailDataStorage.js":67}],55:[function(require,module,exports){
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-/**
- * @constructor
- * @extends KnoinAbstractViewModel
- */
-function LoginViewModel()
-{
- KnoinAbstractViewModel.call(this, 'Center', 'Login');
+(function (module) {
- var oData = RL.data();
+ 'use strict';
- this.email = ko.observable('');
- this.password = ko.observable('');
- this.signMe = ko.observable(false);
+ var
+ ko = require('../External/ko.js'),
+
+ kn = require('../Knoin/Knoin.js'),
- this.additionalCode = ko.observable('');
- this.additionalCode.error = ko.observable(false);
- this.additionalCode.focused = ko.observable(false);
- this.additionalCode.visibility = ko.observable(false);
- this.additionalCodeSignMe = ko.observable(false);
+ Data = require('../Storages/WebMailDataStorage.js'),
- this.logoImg = Utils.trim(RL.settingsGet('LoginLogo'));
- this.loginDescription = Utils.trim(RL.settingsGet('LoginDescription'));
- this.logoCss = Utils.trim(RL.settingsGet('LoginCss'));
+ RL = require('../Boots/RainLoopApp.js'),
+
+ PopupsAddOpenPgpKeyViewModel = require('../ViewModels/Popups/PopupsAddOpenPgpKeyViewModel.js'),
+ PopupsGenerateNewOpenPgpKeyViewModel = require('../ViewModels/Popups/PopupsGenerateNewOpenPgpKeyViewModel.js'),
+ PopupsViewOpenPgpKeyViewModel = require('../ViewModels/Popups/PopupsViewOpenPgpKeyViewModel.js')
+ ;
- this.emailError = ko.observable(false);
- this.passwordError = ko.observable(false);
+ /**
+ * @constructor
+ */
+ function SettingsOpenPGP()
+ {
+ this.openpgpkeys = Data.openpgpkeys;
+ this.openpgpkeysPublic = Data.openpgpkeysPublic;
+ this.openpgpkeysPrivate = Data.openpgpkeysPrivate;
- this.emailFocus = ko.observable(false);
- this.submitFocus = ko.observable(false);
+ this.openPgpKeyForDeletion = ko.observable(null).extend({'falseTimeout': 3000}).extend({'toggleSubscribe': [this,
+ function (oPrev) {
+ if (oPrev)
+ {
+ oPrev.deleteAccess(false);
+ }
+ }, function (oNext) {
+ if (oNext)
+ {
+ oNext.deleteAccess(true);
+ }
+ }
+ ]});
+ }
- this.email.subscribe(function () {
- this.emailError(false);
- this.additionalCode('');
- this.additionalCode.visibility(false);
- }, this);
+ SettingsOpenPGP.prototype.addOpenPgpKey = function ()
+ {
+ kn.showScreenPopup(PopupsAddOpenPgpKeyViewModel);
+ };
- this.password.subscribe(function () {
- this.passwordError(false);
- }, this);
+ SettingsOpenPGP.prototype.generateOpenPgpKey = function ()
+ {
+ kn.showScreenPopup(PopupsGenerateNewOpenPgpKeyViewModel);
+ };
- this.additionalCode.subscribe(function () {
- this.additionalCode.error(false);
- }, this);
-
- this.additionalCode.visibility.subscribe(function () {
- this.additionalCode.error(false);
- }, this);
-
- this.submitRequest = ko.observable(false);
- this.submitError = ko.observable('');
-
- this.allowLanguagesOnLogin = oData.allowLanguagesOnLogin;
-
- this.langRequest = ko.observable(false);
- this.mainLanguage = oData.mainLanguage;
- this.bSendLanguage = false;
-
- this.mainLanguageFullName = ko.computed(function () {
- return Utils.convertLangName(this.mainLanguage());
- }, this);
-
- this.signMeType = ko.observable(Enums.LoginSignMeType.Unused);
-
- this.signMeType.subscribe(function (iValue) {
- this.signMe(Enums.LoginSignMeType.DefaultOn === iValue);
- }, this);
-
- this.signMeVisibility = ko.computed(function () {
- return Enums.LoginSignMeType.Unused !== this.signMeType();
- }, this);
-
- this.submitCommand = Utils.createCommand(this, function () {
-
- Utils.triggerAutocompleteInputChange();
-
- this.emailError('' === Utils.trim(this.email()));
- this.passwordError('' === Utils.trim(this.password()));
-
- if (this.additionalCode.visibility())
+ SettingsOpenPGP.prototype.viewOpenPgpKey = function (oOpenPgpKey)
+ {
+ if (oOpenPgpKey)
{
- this.additionalCode.error('' === Utils.trim(this.additionalCode()));
+ kn.showScreenPopup(PopupsViewOpenPgpKeyViewModel, [oOpenPgpKey]);
+ }
+ };
+
+ /**
+ * @param {OpenPgpKeyModel} oOpenPgpKeyToRemove
+ */
+ SettingsOpenPGP.prototype.deleteOpenPgpKey = function (oOpenPgpKeyToRemove)
+ {
+ if (oOpenPgpKeyToRemove && oOpenPgpKeyToRemove.deleteAccess())
+ {
+ this.openPgpKeyForDeletion(null);
+
+ if (oOpenPgpKeyToRemove && Data.openpgpKeyring)
+ {
+ this.openpgpkeys.remove(function (oOpenPgpKey) {
+ return oOpenPgpKeyToRemove === oOpenPgpKey;
+ });
+
+ Data.openpgpKeyring[oOpenPgpKeyToRemove.isPrivate ? 'privateKeys' : 'publicKeys']
+ .removeForId(oOpenPgpKeyToRemove.guid);
+
+ Data.openpgpKeyring.store();
+
+ RL.reloadOpenPgpKeys();
+ }
+ }
+ };
+
+ module.exports = SettingsOpenPGP;
+
+}(module));
+},{"../Boots/RainLoopApp.js":4,"../External/ko.js":28,"../Knoin/Knoin.js":33,"../Storages/WebMailDataStorage.js":67,"../ViewModels/Popups/PopupsAddOpenPgpKeyViewModel.js":75,"../ViewModels/Popups/PopupsGenerateNewOpenPgpKeyViewModel.js":83,"../ViewModels/Popups/PopupsViewOpenPgpKeyViewModel.js":88}],56:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ ko = require('../External/ko.js'),
+
+ Enums = require('../Common/Enums.js'),
+ Globals = require('../Common/Globals.js'),
+ Utils = require('../Common/Utils.js'),
+
+ Remote = require('../Storages/WebMailAjaxRemoteStorage.js'),
+
+ kn = require('../Knoin/Knoin.js'),
+ PopupsTwoFactorTestViewModel = require('../ViewModels/Popups/PopupsTwoFactorTestViewModel.js')
+ ;
+
+ /**
+ * @constructor
+ */
+ function SettingsSecurity()
+ {
+ this.processing = ko.observable(false);
+ this.clearing = ko.observable(false);
+ this.secreting = ko.observable(false);
+
+ this.viewUser = ko.observable('');
+ this.viewEnable = ko.observable(false);
+ this.viewEnable.subs = true;
+ this.twoFactorStatus = ko.observable(false);
+
+ this.viewSecret = ko.observable('');
+ this.viewBackupCodes = ko.observable('');
+ this.viewUrl = ko.observable('');
+
+ this.bFirst = true;
+
+ this.viewTwoFactorStatus = ko.computed(function () {
+ Globals.langChangeTrigger();
+ return Utils.i18n(
+ this.twoFactorStatus() ?
+ 'SETTINGS_SECURITY/TWO_FACTOR_SECRET_CONFIGURED_DESC' :
+ 'SETTINGS_SECURITY/TWO_FACTOR_SECRET_NOT_CONFIGURED_DESC'
+ );
+ }, this);
+
+ this.onResult = _.bind(this.onResult, this);
+ this.onSecretResult = _.bind(this.onSecretResult, this);
+ }
+
+ SettingsSecurity.prototype.showSecret = function ()
+ {
+ this.secreting(true);
+ Remote.showTwoFactorSecret(this.onSecretResult);
+ };
+
+ SettingsSecurity.prototype.hideSecret = function ()
+ {
+ this.viewSecret('');
+ this.viewBackupCodes('');
+ this.viewUrl('');
+ };
+
+ SettingsSecurity.prototype.createTwoFactor = function ()
+ {
+ this.processing(true);
+ Remote.createTwoFactor(this.onResult);
+ };
+
+ SettingsSecurity.prototype.enableTwoFactor = function ()
+ {
+ this.processing(true);
+ Remote.enableTwoFactor(this.onResult, this.viewEnable());
+ };
+
+ SettingsSecurity.prototype.testTwoFactor = function ()
+ {
+ kn.showScreenPopup(PopupsTwoFactorTestViewModel);
+ };
+
+ SettingsSecurity.prototype.clearTwoFactor = function ()
+ {
+ this.viewSecret('');
+ this.viewBackupCodes('');
+ this.viewUrl('');
+
+ this.clearing(true);
+ Remote.clearTwoFactor(this.onResult);
+ };
+
+ SettingsSecurity.prototype.onShow = function ()
+ {
+ this.viewSecret('');
+ this.viewBackupCodes('');
+ this.viewUrl('');
+ };
+
+ SettingsSecurity.prototype.onResult = function (sResult, oData)
+ {
+ this.processing(false);
+ this.clearing(false);
+
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ {
+ this.viewUser(Utils.pString(oData.Result.User));
+ this.viewEnable(!!oData.Result.Enable);
+ this.twoFactorStatus(!!oData.Result.IsSet);
+
+ this.viewSecret(Utils.pString(oData.Result.Secret));
+ this.viewBackupCodes(Utils.pString(oData.Result.BackupCodes).replace(/[\s]+/g, ' '));
+ this.viewUrl(Utils.pString(oData.Result.Url));
+ }
+ else
+ {
+ this.viewUser('');
+ this.viewEnable(false);
+ this.twoFactorStatus(false);
+
+ this.viewSecret('');
+ this.viewBackupCodes('');
+ this.viewUrl('');
}
- if (this.emailError() || this.passwordError() || this.additionalCode.error())
+ if (this.bFirst)
{
- return false;
- }
-
- this.submitRequest(true);
-
- var
- sPassword = this.password(),
-
- fLoginRequest = _.bind(function (sPassword) {
-
- RL.remote().login(_.bind(function (sResult, oData) {
-
- if (Enums.StorageResultType.Success === sResult && oData && 'Login' === oData.Action)
- {
- if (oData.Result)
+ this.bFirst = false;
+ var self = this;
+ this.viewEnable.subscribe(function (bValue) {
+ if (this.viewEnable.subs)
+ {
+ Remote.enableTwoFactor(function (sResult, oData) {
+ if (Enums.StorageResultType.Success !== sResult || !oData || !oData.Result)
{
- if (oData.TwoFactorAuth)
- {
- this.additionalCode('');
- this.additionalCode.visibility(true);
- this.additionalCode.focused(true);
+ self.viewEnable.subs = false;
+ self.viewEnable(false);
+ self.viewEnable.subs = true;
+ }
+ }, bValue);
+ }
+ }, this);
+ }
+ };
- this.submitRequest(false);
+ SettingsSecurity.prototype.onSecretResult = function (sResult, oData)
+ {
+ this.secreting(false);
+
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ {
+ this.viewSecret(Utils.pString(oData.Result.Secret));
+ this.viewUrl(Utils.pString(oData.Result.Url));
+ }
+ else
+ {
+ this.viewSecret('');
+ this.viewUrl('');
+ }
+ };
+
+ SettingsSecurity.prototype.onBuild = function ()
+ {
+ this.processing(true);
+ Remote.getTwoFactor(this.onResult);
+ };
+
+ module.exports = SettingsSecurity;
+
+}(module));
+},{"../Common/Enums.js":7,"../Common/Globals.js":9,"../Common/Utils.js":14,"../External/ko.js":28,"../Knoin/Knoin.js":33,"../Storages/WebMailAjaxRemoteStorage.js":65,"../ViewModels/Popups/PopupsTwoFactorTestViewModel.js":87}],57:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ Utils = require('../Common/Utils.js'),
+
+ Data = require('../Storages/WebMailDataStorage.js'),
+
+ RL = require('../Boots/RainLoopApp.js')
+ ;
+
+ /**
+ * @constructor
+ */
+ function SettingsSocial()
+ {
+ this.googleEnable = Data.googleEnable;
+
+ this.googleActions = Data.googleActions;
+ this.googleLoggined = Data.googleLoggined;
+ this.googleUserName = Data.googleUserName;
+
+ this.facebookEnable = Data.facebookEnable;
+
+ this.facebookActions = Data.facebookActions;
+ this.facebookLoggined = Data.facebookLoggined;
+ this.facebookUserName = Data.facebookUserName;
+
+ this.twitterEnable = Data.twitterEnable;
+
+ this.twitterActions = Data.twitterActions;
+ this.twitterLoggined = Data.twitterLoggined;
+ this.twitterUserName = Data.twitterUserName;
+
+ this.connectGoogle = Utils.createCommand(this, function () {
+ if (!this.googleLoggined())
+ {
+ RL.googleConnect();
+ }
+ }, function () {
+ return !this.googleLoggined() && !this.googleActions();
+ });
+
+ this.disconnectGoogle = Utils.createCommand(this, function () {
+ RL.googleDisconnect();
+ });
+
+ this.connectFacebook = Utils.createCommand(this, function () {
+ if (!this.facebookLoggined())
+ {
+ RL.facebookConnect();
+ }
+ }, function () {
+ return !this.facebookLoggined() && !this.facebookActions();
+ });
+
+ this.disconnectFacebook = Utils.createCommand(this, function () {
+ RL.facebookDisconnect();
+ });
+
+ this.connectTwitter = Utils.createCommand(this, function () {
+ if (!this.twitterLoggined())
+ {
+ RL.twitterConnect();
+ }
+ }, function () {
+ return !this.twitterLoggined() && !this.twitterActions();
+ });
+
+ this.disconnectTwitter = Utils.createCommand(this, function () {
+ RL.twitterDisconnect();
+ });
+ }
+
+ module.exports = SettingsSocial;
+
+}(module));
+},{"../Boots/RainLoopApp.js":4,"../Common/Utils.js":14,"../Storages/WebMailDataStorage.js":67}],58:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ window = require('../External/window.js'),
+ $ = require('../External/jquery.js'),
+ ko = require('../External/ko.js'),
+
+ Enums = require('../Common/Enums.js'),
+ Utils = require('../Common/Utils.js'),
+ LinkBuilder = require('../Common/LinkBuilder.js'),
+
+ Data = require('../Storages/WebMailDataStorage.js'),
+ Remote = require('../Storages/WebMailAjaxRemoteStorage.js')
+ ;
+
+ /**
+ * @constructor
+ */
+ function SettingsThemes()
+ {
+ var self = this;
+
+ this.mainTheme = Data.mainTheme;
+ this.themesObjects = ko.observableArray([]);
+
+ this.themeTrigger = ko.observable(Enums.SaveSettingsStep.Idle).extend({'throttle': 100});
+
+ this.oLastAjax = null;
+ this.iTimer = 0;
+
+ Data.theme.subscribe(function (sValue) {
+
+ _.each(this.themesObjects(), function (oTheme) {
+ oTheme.selected(sValue === oTheme.name);
+ });
+
+ var
+ oThemeLink = $('#rlThemeLink'),
+ oThemeStyle = $('#rlThemeStyle'),
+ sUrl = oThemeLink.attr('href')
+ ;
+
+ if (!sUrl)
+ {
+ sUrl = oThemeStyle.attr('data-href');
+ }
+
+ if (sUrl)
+ {
+ sUrl = sUrl.toString().replace(/\/-\/[^\/]+\/\-\//, '/-/' + sValue + '/-/');
+ sUrl = sUrl.toString().replace(/\/Css\/[^\/]+\/User\//, '/Css/0/User/');
+
+ if ('Json/' !== sUrl.substring(sUrl.length - 5, sUrl.length))
+ {
+ sUrl += 'Json/';
+ }
+
+ window.clearTimeout(self.iTimer);
+ self.themeTrigger(Enums.SaveSettingsStep.Animate);
+
+ if (this.oLastAjax && this.oLastAjax.abort)
+ {
+ this.oLastAjax.abort();
+ }
+
+ this.oLastAjax = $.ajax({
+ 'url': sUrl,
+ 'dataType': 'json'
+ }).done(function(aData) {
+
+ if (aData && Utils.isArray(aData) && 2 === aData.length)
+ {
+ if (oThemeLink && oThemeLink[0] && (!oThemeStyle || !oThemeStyle[0]))
+ {
+ oThemeStyle = $('');
+ oThemeLink.after(oThemeStyle);
+ oThemeLink.remove();
+ }
+
+ if (oThemeStyle && oThemeStyle[0])
+ {
+ oThemeStyle.attr('data-href', sUrl).attr('data-theme', aData[0]);
+ if (oThemeStyle && oThemeStyle[0] && oThemeStyle[0].styleSheet && !Utils.isUnd(oThemeStyle[0].styleSheet.cssText))
+ {
+ oThemeStyle[0].styleSheet.cssText = aData[1];
}
else
{
- RL.loginAndLogoutReload();
+ oThemeStyle.text(aData[1]);
}
}
- else if (oData.ErrorCode)
- {
- this.submitRequest(false);
- this.submitError(Utils.getNotification(oData.ErrorCode));
- if ('' === this.submitError())
+ self.themeTrigger(Enums.SaveSettingsStep.TrueResult);
+ }
+
+ }).always(function() {
+
+ self.iTimer = window.setTimeout(function () {
+ self.themeTrigger(Enums.SaveSettingsStep.Idle);
+ }, 1000);
+
+ self.oLastAjax = null;
+ });
+ }
+
+ Remote.saveSettings(null, {
+ 'Theme': sValue
+ });
+
+ }, this);
+ }
+
+ SettingsThemes.prototype.onBuild = function ()
+ {
+ var sCurrentTheme = Data.theme();
+ this.themesObjects(_.map(Data.themes(), function (sTheme) {
+ return {
+ 'name': sTheme,
+ 'nameDisplay': Utils.convertThemeName(sTheme),
+ 'selected': ko.observable(sTheme === sCurrentTheme),
+ 'themePreviewSrc': LinkBuilder.themePreviewLink(sTheme)
+ };
+ }));
+ };
+
+ module.exports = SettingsThemes;
+
+}(module));
+},{"../Common/Enums.js":7,"../Common/LinkBuilder.js":10,"../Common/Utils.js":14,"../External/jquery.js":26,"../External/ko.js":28,"../External/window.js":32,"../Storages/WebMailAjaxRemoteStorage.js":65,"../Storages/WebMailDataStorage.js":67}],59:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ window = require('../External/window.js'),
+ $ = require('../External/jquery.js'),
+
+ Consts = require('../Common/Consts.js'),
+ Enums = require('../Common/Enums.js'),
+ Globals = require('../Common/Globals.js'),
+ Utils = require('../Common/Utils.js'),
+ Plugins = require('../Common/Plugins.js'),
+ LinkBuilder = require('../Common/LinkBuilder.js'),
+
+ AppSettings = require('./AppSettings.js')
+ ;
+
+ /**
+ * @constructor
+ */
+ function AbstractAjaxRemoteStorage()
+ {
+ this.oRequests = {};
+ }
+
+ AbstractAjaxRemoteStorage.prototype.oRequests = {};
+
+ /**
+ * @param {?Function} fCallback
+ * @param {string} sRequestAction
+ * @param {string} sType
+ * @param {?AjaxJsonDefaultResponse} oData
+ * @param {boolean} bCached
+ * @param {*=} oRequestParameters
+ */
+ AbstractAjaxRemoteStorage.prototype.defaultResponse = function (fCallback, sRequestAction, sType, oData, bCached, oRequestParameters)
+ {
+ var
+ fCall = function () {
+ if (Enums.StorageResultType.Success !== sType && Globals.bUnload)
+ {
+ sType = Enums.StorageResultType.Unload;
+ }
+
+ if (Enums.StorageResultType.Success === sType && oData && !oData.Result)
+ {
+ if (oData && -1 < Utils.inArray(oData.ErrorCode, [
+ Enums.Notification.AuthError, Enums.Notification.AccessError,
+ Enums.Notification.ConnectionError, Enums.Notification.DomainNotAllowed, Enums.Notification.AccountNotAllowed,
+ Enums.Notification.MailServerError, Enums.Notification.UnknownNotification, Enums.Notification.UnknownError
+ ]))
+ {
+ Globals.iAjaxErrorCount++;
+ }
+
+ if (oData && Enums.Notification.InvalidToken === oData.ErrorCode)
+ {
+ Globals.iTokenErrorCount++;
+ }
+
+ if (Consts.Values.TokenErrorLimit < Globals.iTokenErrorCount)
+ {
+ if (Globals.__RL)
+ {
+ Globals.__RL.loginAndLogoutReload(true);
+ }
+ }
+
+ if (oData.Logout || Consts.Values.AjaxErrorLimit < Globals.iAjaxErrorCount)
+ {
+ if (window.__rlah_clear)
+ {
+ window.__rlah_clear();
+ }
+
+ if (Globals.__RL)
+ {
+ Globals.__RL.loginAndLogoutReload(true);
+ }
+ }
+ }
+ else if (Enums.StorageResultType.Success === sType && oData && oData.Result)
+ {
+ Globals.iAjaxErrorCount = 0;
+ Globals.iTokenErrorCount = 0;
+ }
+
+ if (fCallback)
+ {
+ Plugins.runHook('ajax-default-response', [sRequestAction, Enums.StorageResultType.Success === sType ? oData : null, sType, bCached, oRequestParameters]);
+
+ fCallback(
+ sType,
+ Enums.StorageResultType.Success === sType ? oData : null,
+ bCached,
+ sRequestAction,
+ oRequestParameters
+ );
+ }
+ }
+ ;
+
+ switch (sType)
+ {
+ case 'success':
+ sType = Enums.StorageResultType.Success;
+ break;
+ case 'abort':
+ sType = Enums.StorageResultType.Abort;
+ break;
+ default:
+ sType = Enums.StorageResultType.Error;
+ break;
+ }
+
+ if (Enums.StorageResultType.Error === sType)
+ {
+ _.delay(fCall, 300);
+ }
+ else
+ {
+ fCall();
+ }
+ };
+
+ /**
+ * @param {?Function} fResultCallback
+ * @param {Object} oParameters
+ * @param {?number=} iTimeOut = 20000
+ * @param {string=} sGetAdd = ''
+ * @param {Array=} aAbortActions = []
+ * @return {jQuery.jqXHR}
+ */
+ AbstractAjaxRemoteStorage.prototype.ajaxRequest = function (fResultCallback, oParameters, iTimeOut, sGetAdd, aAbortActions)
+ {
+ var
+ self = this,
+ bPost = '' === sGetAdd,
+ oHeaders = {},
+ iStart = (new window.Date()).getTime(),
+ oDefAjax = null,
+ sAction = ''
+ ;
+
+ oParameters = oParameters || {};
+ iTimeOut = Utils.isNormal(iTimeOut) ? iTimeOut : 20000;
+ sGetAdd = Utils.isUnd(sGetAdd) ? '' : Utils.pString(sGetAdd);
+ aAbortActions = Utils.isArray(aAbortActions) ? aAbortActions : [];
+
+ sAction = oParameters.Action || '';
+
+ if (sAction && 0 < aAbortActions.length)
+ {
+ _.each(aAbortActions, function (sActionToAbort) {
+ if (self.oRequests[sActionToAbort])
+ {
+ self.oRequests[sActionToAbort].__aborted = true;
+ if (self.oRequests[sActionToAbort].abort)
+ {
+ self.oRequests[sActionToAbort].abort();
+ }
+ self.oRequests[sActionToAbort] = null;
+ }
+ });
+ }
+
+ if (bPost)
+ {
+ oParameters['XToken'] = AppSettings.settingsGet('Token');
+ }
+
+ oDefAjax = $.ajax({
+ 'type': bPost ? 'POST' : 'GET',
+ 'url': LinkBuilder.ajax(sGetAdd),
+ 'async': true,
+ 'dataType': 'json',
+ 'data': bPost ? oParameters : {},
+ 'headers': oHeaders,
+ 'timeout': iTimeOut,
+ 'global': true
+ });
+
+ oDefAjax.always(function (oData, sType) {
+
+ var bCached = false;
+ if (oData && oData['Time'])
+ {
+ bCached = Utils.pInt(oData['Time']) > (new window.Date()).getTime() - iStart;
+ }
+
+ if (sAction && self.oRequests[sAction])
+ {
+ if (self.oRequests[sAction].__aborted)
+ {
+ sType = 'abort';
+ }
+
+ self.oRequests[sAction] = null;
+ }
+
+ self.defaultResponse(fResultCallback, sAction, sType, oData, bCached, oParameters);
+ });
+
+ if (sAction && 0 < aAbortActions.length && -1 < Utils.inArray(sAction, aAbortActions))
+ {
+ if (this.oRequests[sAction])
+ {
+ this.oRequests[sAction].__aborted = true;
+ if (this.oRequests[sAction].abort)
+ {
+ this.oRequests[sAction].abort();
+ }
+ this.oRequests[sAction] = null;
+ }
+
+ this.oRequests[sAction] = oDefAjax;
+ }
+
+ return oDefAjax;
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {string} sAction
+ * @param {Object=} oParameters
+ * @param {?number=} iTimeout
+ * @param {string=} sGetAdd = ''
+ * @param {Array=} aAbortActions = []
+ */
+ AbstractAjaxRemoteStorage.prototype.defaultRequest = function (fCallback, sAction, oParameters, iTimeout, sGetAdd, aAbortActions)
+ {
+ oParameters = oParameters || {};
+ oParameters.Action = sAction;
+
+ sGetAdd = Utils.pString(sGetAdd);
+
+ Plugins.runHook('ajax-default-request', [sAction, oParameters, sGetAdd]);
+
+ this.ajaxRequest(fCallback, oParameters,
+ Utils.isUnd(iTimeout) ? Consts.Defaults.DefaultAjaxTimeout : Utils.pInt(iTimeout), sGetAdd, aAbortActions);
+ };
+
+ /**
+ * @param {?Function} fCallback
+ */
+ AbstractAjaxRemoteStorage.prototype.noop = function (fCallback)
+ {
+ this.defaultRequest(fCallback, 'Noop');
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {string} sMessage
+ * @param {string} sFileName
+ * @param {number} iLineNo
+ * @param {string} sLocation
+ * @param {string} sHtmlCapa
+ * @param {number} iTime
+ */
+ AbstractAjaxRemoteStorage.prototype.jsError = function (fCallback, sMessage, sFileName, iLineNo, sLocation, sHtmlCapa, iTime)
+ {
+ this.defaultRequest(fCallback, 'JsError', {
+ 'Message': sMessage,
+ 'FileName': sFileName,
+ 'LineNo': iLineNo,
+ 'Location': sLocation,
+ 'HtmlCapa': sHtmlCapa,
+ 'TimeOnPage': iTime
+ });
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {string} sType
+ * @param {Array=} mData = null
+ * @param {boolean=} bIsError = false
+ */
+ AbstractAjaxRemoteStorage.prototype.jsInfo = function (fCallback, sType, mData, bIsError)
+ {
+ this.defaultRequest(fCallback, 'JsInfo', {
+ 'Type': sType,
+ 'Data': mData,
+ 'IsError': (Utils.isUnd(bIsError) ? false : !!bIsError) ? '1' : '0'
+ });
+ };
+
+ /**
+ * @param {?Function} fCallback
+ */
+ AbstractAjaxRemoteStorage.prototype.getPublicKey = function (fCallback)
+ {
+ this.defaultRequest(fCallback, 'GetPublicKey');
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {string} sVersion
+ */
+ AbstractAjaxRemoteStorage.prototype.jsVersion = function (fCallback, sVersion)
+ {
+ this.defaultRequest(fCallback, 'Version', {
+ 'Version': sVersion
+ });
+ };
+
+ module.exports = AbstractAjaxRemoteStorage;
+
+}(module));
+},{"../Common/Consts.js":6,"../Common/Enums.js":7,"../Common/Globals.js":9,"../Common/LinkBuilder.js":10,"../Common/Plugins.js":12,"../Common/Utils.js":14,"../External/jquery.js":26,"../External/window.js":32,"./AppSettings.js":61}],60:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ Enums = require('../Common/Enums.js'),
+ Utils = require('../Common/Utils.js'),
+
+ AppSettings = require('./AppSettings.js')
+ ;
+
+ /**
+ * @constructor
+ */
+ function AbstractData()
+ {
+ Utils.initDataConstructorBySettings(this);
+ }
+
+ AbstractData.prototype.populateDataOnStart = function()
+ {
+ var
+ mLayout = Utils.pInt(AppSettings.settingsGet('Layout')),
+ aLanguages = AppSettings.settingsGet('Languages'),
+ aThemes = AppSettings.settingsGet('Themes')
+ ;
+
+ if (Utils.isArray(aLanguages))
+ {
+ this.languages(aLanguages);
+ }
+
+ if (Utils.isArray(aThemes))
+ {
+ this.themes(aThemes);
+ }
+
+ this.mainLanguage(AppSettings.settingsGet('Language'));
+ this.mainTheme(AppSettings.settingsGet('Theme'));
+
+ this.capaAdditionalAccounts(AppSettings.capa(Enums.Capa.AdditionalAccounts));
+ this.capaAdditionalIdentities(AppSettings.capa(Enums.Capa.AdditionalIdentities));
+ this.capaGravatar(AppSettings.capa(Enums.Capa.Gravatar));
+ this.determineUserLanguage(!!AppSettings.settingsGet('DetermineUserLanguage'));
+ this.determineUserDomain(!!AppSettings.settingsGet('DetermineUserDomain'));
+
+ this.capaThemes(AppSettings.capa(Enums.Capa.Themes));
+ this.allowLanguagesOnLogin(!!AppSettings.settingsGet('AllowLanguagesOnLogin'));
+ this.allowLanguagesOnSettings(!!AppSettings.settingsGet('AllowLanguagesOnSettings'));
+ this.useLocalProxyForExternalImages(!!AppSettings.settingsGet('UseLocalProxyForExternalImages'));
+
+ this.editorDefaultType(AppSettings.settingsGet('EditorDefaultType'));
+ this.showImages(!!AppSettings.settingsGet('ShowImages'));
+ this.contactsAutosave(!!AppSettings.settingsGet('ContactsAutosave'));
+ this.interfaceAnimation(AppSettings.settingsGet('InterfaceAnimation'));
+
+ this.mainMessagesPerPage(AppSettings.settingsGet('MPP'));
+
+ this.desktopNotifications(!!AppSettings.settingsGet('DesktopNotifications'));
+ this.useThreads(!!AppSettings.settingsGet('UseThreads'));
+ this.replySameFolder(!!AppSettings.settingsGet('ReplySameFolder'));
+ this.useCheckboxesInList(!!AppSettings.settingsGet('UseCheckboxesInList'));
+
+ this.layout(Enums.Layout.SidePreview);
+ if (-1 < Utils.inArray(mLayout, [Enums.Layout.NoPreview, Enums.Layout.SidePreview, Enums.Layout.BottomPreview]))
+ {
+ this.layout(mLayout);
+ }
+ this.facebookSupported(!!AppSettings.settingsGet('SupportedFacebookSocial'));
+ this.facebookEnable(!!AppSettings.settingsGet('AllowFacebookSocial'));
+ this.facebookAppID(AppSettings.settingsGet('FacebookAppID'));
+ this.facebookAppSecret(AppSettings.settingsGet('FacebookAppSecret'));
+
+ this.twitterEnable(!!AppSettings.settingsGet('AllowTwitterSocial'));
+ this.twitterConsumerKey(AppSettings.settingsGet('TwitterConsumerKey'));
+ this.twitterConsumerSecret(AppSettings.settingsGet('TwitterConsumerSecret'));
+
+ this.googleEnable(!!AppSettings.settingsGet('AllowGoogleSocial'));
+ this.googleClientID(AppSettings.settingsGet('GoogleClientID'));
+ this.googleClientSecret(AppSettings.settingsGet('GoogleClientSecret'));
+ this.googleApiKey(AppSettings.settingsGet('GoogleApiKey'));
+
+ this.dropboxEnable(!!AppSettings.settingsGet('AllowDropboxSocial'));
+ this.dropboxApiKey(AppSettings.settingsGet('DropboxApiKey'));
+
+ this.contactsIsAllowed(!!AppSettings.settingsGet('ContactsIsAllowed'));
+ };
+
+ module.exports = AbstractData;
+
+}(module));
+},{"../Common/Enums.js":7,"../Common/Utils.js":14,"./AppSettings.js":61}],61:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ AppData = require('../External/AppData.js'),
+
+ Utils = require('../Common/Utils.js')
+ ;
+
+ /**
+ * @constructor
+ */
+ function AppSettings()
+ {
+ this.oSettings = null;
+ }
+
+ AppSettings.prototype.oSettings = null;
+
+ /**
+ * @param {string} sName
+ * @return {?}
+ */
+ AppSettings.prototype.settingsGet = function (sName)
+ {
+ if (null === this.oSettings)
+ {
+ this.oSettings = Utils.isNormal(AppData) ? AppData : {};
+ }
+
+ return Utils.isUnd(this.oSettings[sName]) ? null : this.oSettings[sName];
+ };
+
+ /**
+ * @param {string} sName
+ * @param {?} mValue
+ */
+ AppSettings.prototype.settingsSet = function (sName, mValue)
+ {
+ if (null === this.oSettings)
+ {
+ this.oSettings = Utils.isNormal(AppData) ? AppData : {};
+ }
+
+ this.oSettings[sName] = mValue;
+ };
+
+ /**
+ * @param {string} sName
+ * @return {boolean}
+ */
+ AppSettings.prototype.capa = function (sName)
+ {
+ var mCapa = this.settingsGet('Capa');
+ return Utils.isArray(mCapa) && Utils.isNormal(sName) && -1 < Utils.inArray(sName, mCapa);
+ };
+
+
+ module.exports = new AppSettings();
+
+}(module));
+},{"../Common/Utils.js":14,"../External/AppData.js":19}],62:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ _ = require('../External/underscore.js'),
+
+ CookieDriver = require('./LocalStorages/CookieDriver.js'),
+ LocalStorageDriver = require('./LocalStorages/LocalStorageDriver.js')
+ ;
+
+ /**
+ * @constructor
+ */
+ function LocalStorage()
+ {
+ var
+ NextStorageDriver = _.find([LocalStorageDriver, CookieDriver], function (NextStorageDriver) {
+ return NextStorageDriver.supported();
+ })
+ ;
+
+ if (NextStorageDriver)
+ {
+ NextStorageDriver = /** @type {?Function} */ NextStorageDriver;
+ this.oDriver = new NextStorageDriver();
+ }
+ }
+
+ LocalStorage.prototype.oDriver = null;
+
+ /**
+ * @param {number} iKey
+ * @param {*} mData
+ * @return {boolean}
+ */
+ LocalStorage.prototype.set = function (iKey, mData)
+ {
+ return this.oDriver ? this.oDriver.set('p' + iKey, mData) : false;
+ };
+
+ /**
+ * @param {number} iKey
+ * @return {*}
+ */
+ LocalStorage.prototype.get = function (iKey)
+ {
+ return this.oDriver ? this.oDriver.get('p' + iKey) : null;
+ };
+
+ module.exports = new LocalStorage();
+
+}(module));
+},{"../External/underscore.js":31,"./LocalStorages/CookieDriver.js":63,"./LocalStorages/LocalStorageDriver.js":64}],63:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ $ = require('../../External/jquery.js'),
+ JSON = require('../../External/JSON.js'),
+ Consts = require('../../Common/Consts.js'),
+ Utils = require('../../Common/Utils.js')
+ ;
+
+ /**
+ * @constructor
+ */
+ function CookieDriver()
+ {
+
+ }
+
+ CookieDriver.supported = function ()
+ {
+ return true;
+ };
+
+ /**
+ * @param {string} sKey
+ * @param {*} mData
+ * @returns {boolean}
+ */
+ CookieDriver.prototype.set = function (sKey, mData)
+ {
+ var
+ mCokieValue = $.cookie(Consts.Values.ClientSideCookieIndexName),
+ bResult = false,
+ mResult = null
+ ;
+
+ try
+ {
+ mResult = null === mCokieValue ? null : JSON.parse(mCokieValue);
+ if (!mResult)
+ {
+ mResult = {};
+ }
+
+ mResult[sKey] = mData;
+ $.cookie(Consts.Values.ClientSideCookieIndexName, JSON.stringify(mResult), {
+ 'expires': 30
+ });
+
+ bResult = true;
+ }
+ catch (oException) {}
+
+ return bResult;
+ };
+
+ /**
+ * @param {string} sKey
+ * @returns {*}
+ */
+ CookieDriver.prototype.get = function (sKey)
+ {
+ var
+ mCokieValue = $.cookie(Consts.Values.ClientSideCookieIndexName),
+ mResult = null
+ ;
+
+ try
+ {
+ mResult = null === mCokieValue ? null : JSON.parse(mCokieValue);
+ if (mResult && !Utils.isUnd(mResult[sKey]))
+ {
+ mResult = mResult[sKey];
+ }
+ else
+ {
+ mResult = null;
+ }
+ }
+ catch (oException) {}
+
+ return mResult;
+ };
+
+ module.exports = CookieDriver;
+
+}(module));
+},{"../../Common/Consts.js":6,"../../Common/Utils.js":14,"../../External/JSON.js":20,"../../External/jquery.js":26}],64:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ window = require('../../External/window.js'),
+ JSON = require('../../External/JSON.js'),
+ Consts = require('../../Common/Consts.js'),
+ Utils = require('../../Common/Utils.js')
+ ;
+
+ /**
+ * @constructor
+ */
+ function LocalStorageDriver()
+ {
+ }
+
+ LocalStorageDriver.supported = function ()
+ {
+ return !!window.localStorage;
+ };
+
+ /**
+ * @param {string} sKey
+ * @param {*} mData
+ * @returns {boolean}
+ */
+ LocalStorageDriver.prototype.set = function (sKey, mData)
+ {
+ var
+ mCookieValue = window.localStorage[Consts.Values.ClientSideCookieIndexName] || null,
+ bResult = false,
+ mResult = null
+ ;
+
+ try
+ {
+ mResult = null === mCookieValue ? null : JSON.parse(mCookieValue);
+ if (!mResult)
+ {
+ mResult = {};
+ }
+
+ mResult[sKey] = mData;
+ window.localStorage[Consts.Values.ClientSideCookieIndexName] = JSON.stringify(mResult);
+
+ bResult = true;
+ }
+ catch (oException) {}
+
+ return bResult;
+ };
+
+ /**
+ * @param {string} sKey
+ * @returns {*}
+ */
+ LocalStorageDriver.prototype.get = function (sKey)
+ {
+ var
+ mCokieValue = window.localStorage[Consts.Values.ClientSideCookieIndexName] || null,
+ mResult = null
+ ;
+
+ try
+ {
+ mResult = null === mCokieValue ? null : JSON.parse(mCokieValue);
+ if (mResult && !Utils.isUnd(mResult[sKey]))
+ {
+ mResult = mResult[sKey];
+ }
+ else
+ {
+ mResult = null;
+ }
+ }
+ catch (oException) {}
+
+ return mResult;
+ };
+
+ module.exports = LocalStorageDriver;
+
+}(module));
+},{"../../Common/Consts.js":6,"../../Common/Utils.js":14,"../../External/JSON.js":20,"../../External/window.js":32}],65:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ _ = require('../External/underscore.js'),
+
+ Utils = require('../Common/Utils.js'),
+ Consts = require('../Common/Consts.js'),
+ Globals = require('../Common/Globals.js'),
+ Base64 = require('../Common/Base64.js'),
+
+ AppSettings = require('./AppSettings.js'),
+ Cache = require('./WebMailCacheStorage.js'),
+ Data = require('./WebMailDataStorage.js'),
+
+ AbstractAjaxRemoteStorage = require('./AbstractAjaxRemoteStorage.js')
+ ;
+
+ /**
+ * @constructor
+ * @extends AbstractAjaxRemoteStorage
+ */
+ function WebMailAjaxRemoteStorage()
+ {
+ AbstractAjaxRemoteStorage.call(this);
+
+ this.oRequests = {};
+ }
+
+ _.extend(WebMailAjaxRemoteStorage.prototype, AbstractAjaxRemoteStorage.prototype);
+
+ /**
+ * @param {?Function} fCallback
+ */
+ WebMailAjaxRemoteStorage.prototype.folders = function (fCallback)
+ {
+ this.defaultRequest(fCallback, 'Folders', {
+ 'SentFolder': AppSettings.settingsGet('SentFolder'),
+ 'DraftFolder': AppSettings.settingsGet('DraftFolder'),
+ 'SpamFolder': AppSettings.settingsGet('SpamFolder'),
+ 'TrashFolder': AppSettings.settingsGet('TrashFolder'),
+ 'ArchiveFolder': AppSettings.settingsGet('ArchiveFolder')
+ }, null, '', ['Folders']);
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {string} sEmail
+ * @param {string} sLogin
+ * @param {string} sPassword
+ * @param {boolean} bSignMe
+ * @param {string=} sLanguage
+ * @param {string=} sAdditionalCode
+ * @param {boolean=} bAdditionalCodeSignMe
+ */
+ WebMailAjaxRemoteStorage.prototype.login = function (fCallback, sEmail, sLogin, sPassword, bSignMe, sLanguage, sAdditionalCode, bAdditionalCodeSignMe)
+ {
+ this.defaultRequest(fCallback, 'Login', {
+ 'Email': sEmail,
+ 'Login': sLogin,
+ 'Password': sPassword,
+ 'Language': sLanguage || '',
+ 'AdditionalCode': sAdditionalCode || '',
+ 'AdditionalCodeSignMe': bAdditionalCodeSignMe ? '1' : '0',
+ 'SignMe': bSignMe ? '1' : '0'
+ });
+ };
+
+ /**
+ * @param {?Function} fCallback
+ */
+ WebMailAjaxRemoteStorage.prototype.getTwoFactor = function (fCallback)
+ {
+ this.defaultRequest(fCallback, 'GetTwoFactorInfo');
+ };
+
+ /**
+ * @param {?Function} fCallback
+ */
+ WebMailAjaxRemoteStorage.prototype.createTwoFactor = function (fCallback)
+ {
+ this.defaultRequest(fCallback, 'CreateTwoFactorSecret');
+ };
+
+ /**
+ * @param {?Function} fCallback
+ */
+ WebMailAjaxRemoteStorage.prototype.clearTwoFactor = function (fCallback)
+ {
+ this.defaultRequest(fCallback, 'ClearTwoFactorInfo');
+ };
+
+ /**
+ * @param {?Function} fCallback
+ */
+ WebMailAjaxRemoteStorage.prototype.showTwoFactorSecret = function (fCallback)
+ {
+ this.defaultRequest(fCallback, 'ShowTwoFactorSecret');
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {string} sCode
+ */
+ WebMailAjaxRemoteStorage.prototype.testTwoFactor = function (fCallback, sCode)
+ {
+ this.defaultRequest(fCallback, 'TestTwoFactorInfo', {
+ 'Code': sCode
+ });
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {boolean} bEnable
+ */
+ WebMailAjaxRemoteStorage.prototype.enableTwoFactor = function (fCallback, bEnable)
+ {
+ this.defaultRequest(fCallback, 'EnableTwoFactor', {
+ 'Enable': bEnable ? '1' : '0'
+ });
+ };
+
+ /**
+ * @param {?Function} fCallback
+ */
+ WebMailAjaxRemoteStorage.prototype.clearTwoFactorInfo = function (fCallback)
+ {
+ this.defaultRequest(fCallback, 'ClearTwoFactorInfo');
+ };
+
+ /**
+ * @param {?Function} fCallback
+ */
+ WebMailAjaxRemoteStorage.prototype.contactsSync = function (fCallback)
+ {
+ this.defaultRequest(fCallback, 'ContactsSync', null, Consts.Defaults.ContactsSyncAjaxTimeout);
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {boolean} bEnable
+ * @param {string} sUrl
+ * @param {string} sUser
+ * @param {string} sPassword
+ */
+ WebMailAjaxRemoteStorage.prototype.saveContactsSyncData = function (fCallback, bEnable, sUrl, sUser, sPassword)
+ {
+ this.defaultRequest(fCallback, 'SaveContactsSyncData', {
+ 'Enable': bEnable ? '1' : '0',
+ 'Url': sUrl,
+ 'User': sUser,
+ 'Password': sPassword
+ });
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {string} sEmail
+ * @param {string} sLogin
+ * @param {string} sPassword
+ */
+ WebMailAjaxRemoteStorage.prototype.accountAdd = function (fCallback, sEmail, sLogin, sPassword)
+ {
+ this.defaultRequest(fCallback, 'AccountAdd', {
+ 'Email': sEmail,
+ 'Login': sLogin,
+ 'Password': sPassword
+ });
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {string} sEmailToDelete
+ */
+ WebMailAjaxRemoteStorage.prototype.accountDelete = function (fCallback, sEmailToDelete)
+ {
+ this.defaultRequest(fCallback, 'AccountDelete', {
+ 'EmailToDelete': sEmailToDelete
+ });
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {string} sId
+ * @param {string} sEmail
+ * @param {string} sName
+ * @param {string} sReplyTo
+ * @param {string} sBcc
+ */
+ WebMailAjaxRemoteStorage.prototype.identityUpdate = function (fCallback, sId, sEmail, sName, sReplyTo, sBcc)
+ {
+ this.defaultRequest(fCallback, 'IdentityUpdate', {
+ 'Id': sId,
+ 'Email': sEmail,
+ 'Name': sName,
+ 'ReplyTo': sReplyTo,
+ 'Bcc': sBcc
+ });
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {string} sIdToDelete
+ */
+ WebMailAjaxRemoteStorage.prototype.identityDelete = function (fCallback, sIdToDelete)
+ {
+ this.defaultRequest(fCallback, 'IdentityDelete', {
+ 'IdToDelete': sIdToDelete
+ });
+ };
+
+ /**
+ * @param {?Function} fCallback
+ */
+ WebMailAjaxRemoteStorage.prototype.accountsAndIdentities = function (fCallback)
+ {
+ this.defaultRequest(fCallback, 'AccountsAndIdentities');
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {string} sFolderFullNameRaw
+ * @param {number=} iOffset = 0
+ * @param {number=} iLimit = 20
+ * @param {string=} sSearch = ''
+ * @param {boolean=} bSilent = false
+ */
+ WebMailAjaxRemoteStorage.prototype.messageList = function (fCallback, sFolderFullNameRaw, iOffset, iLimit, sSearch, bSilent)
+ {
+ sFolderFullNameRaw = Utils.pString(sFolderFullNameRaw);
+
+ var
+ sFolderHash = Cache.getFolderHash(sFolderFullNameRaw)
+ ;
+
+ bSilent = Utils.isUnd(bSilent) ? false : !!bSilent;
+ iOffset = Utils.isUnd(iOffset) ? 0 : Utils.pInt(iOffset);
+ iLimit = Utils.isUnd(iOffset) ? 20 : Utils.pInt(iLimit);
+ sSearch = Utils.pString(sSearch);
+
+ if ('' !== sFolderHash && ('' === sSearch || -1 === sSearch.indexOf('is:')))
+ {
+ this.defaultRequest(fCallback, 'MessageList', {},
+ '' === sSearch ? Consts.Defaults.DefaultAjaxTimeout : Consts.Defaults.SearchAjaxTimeout,
+ 'MessageList/' + Base64.urlsafe_encode([
+ sFolderFullNameRaw,
+ iOffset,
+ iLimit,
+ sSearch,
+ Data.projectHash(),
+ sFolderHash,
+ 'INBOX' === sFolderFullNameRaw ? Cache.getFolderUidNext(sFolderFullNameRaw) : '',
+ Data.threading() && Data.useThreads() ? '1' : '0',
+ Data.threading() && sFolderFullNameRaw === Data.messageListThreadFolder() ? Data.messageListThreadUids().join(',') : ''
+ ].join(String.fromCharCode(0))), bSilent ? [] : ['MessageList']);
+ }
+ else
+ {
+ this.defaultRequest(fCallback, 'MessageList', {
+ 'Folder': sFolderFullNameRaw,
+ 'Offset': iOffset,
+ 'Limit': iLimit,
+ 'Search': sSearch,
+ 'UidNext': 'INBOX' === sFolderFullNameRaw ? Cache.getFolderUidNext(sFolderFullNameRaw) : '',
+ 'UseThreads': Data.threading() && Data.useThreads() ? '1' : '0',
+ 'ExpandedThreadUid': Data.threading() && sFolderFullNameRaw === Data.messageListThreadFolder() ? Data.messageListThreadUids().join(',') : ''
+ }, '' === sSearch ? Consts.Defaults.DefaultAjaxTimeout : Consts.Defaults.SearchAjaxTimeout, '', bSilent ? [] : ['MessageList']);
+ }
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {Array} aDownloads
+ */
+ WebMailAjaxRemoteStorage.prototype.messageUploadAttachments = function (fCallback, aDownloads)
+ {
+ this.defaultRequest(fCallback, 'MessageUploadAttachments', {
+ 'Attachments': aDownloads
+ }, 999000);
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {string} sFolderFullNameRaw
+ * @param {number} iUid
+ * @return {boolean}
+ */
+ WebMailAjaxRemoteStorage.prototype.message = function (fCallback, sFolderFullNameRaw, iUid)
+ {
+ sFolderFullNameRaw = Utils.pString(sFolderFullNameRaw);
+ iUid = Utils.pInt(iUid);
+
+ if (Cache.getFolderFromCacheList(sFolderFullNameRaw) && 0 < iUid)
+ {
+ this.defaultRequest(fCallback, 'Message', {}, null,
+ 'Message/' + Base64.urlsafe_encode([
+ sFolderFullNameRaw,
+ iUid,
+ Data.projectHash(),
+ Data.threading() && Data.useThreads() ? '1' : '0'
+ ].join(String.fromCharCode(0))), ['Message']);
+
+ return true;
+ }
+
+ return false;
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {Array} aExternals
+ */
+ WebMailAjaxRemoteStorage.prototype.composeUploadExternals = function (fCallback, aExternals)
+ {
+ this.defaultRequest(fCallback, 'ComposeUploadExternals', {
+ 'Externals': aExternals
+ }, 999000);
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {string} sUrl
+ * @param {string} sAccessToken
+ */
+ WebMailAjaxRemoteStorage.prototype.composeUploadDrive = function (fCallback, sUrl, sAccessToken)
+ {
+ this.defaultRequest(fCallback, 'ComposeUploadDrive', {
+ 'AccessToken': sAccessToken,
+ 'Url': sUrl
+ }, 999000);
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {string} sFolder
+ * @param {Array=} aList = []
+ */
+ WebMailAjaxRemoteStorage.prototype.folderInformation = function (fCallback, sFolder, aList)
+ {
+ var
+ bRequest = true,
+ aUids = []
+ ;
+
+ if (Utils.isArray(aList) && 0 < aList.length)
+ {
+ bRequest = false;
+ _.each(aList, function (oMessageListItem) {
+ if (!Cache.getMessageFlagsFromCache(oMessageListItem.folderFullNameRaw, oMessageListItem.uid))
+ {
+ aUids.push(oMessageListItem.uid);
+ }
+
+ if (0 < oMessageListItem.threads().length)
+ {
+ _.each(oMessageListItem.threads(), function (sUid) {
+ if (!Cache.getMessageFlagsFromCache(oMessageListItem.folderFullNameRaw, sUid))
+ {
+ aUids.push(sUid);
+ }
+ });
+ }
+ });
+
+ if (0 < aUids.length)
+ {
+ bRequest = true;
+ }
+ }
+
+ if (bRequest)
+ {
+ this.defaultRequest(fCallback, 'FolderInformation', {
+ 'Folder': sFolder,
+ 'FlagsUids': Utils.isArray(aUids) ? aUids.join(',') : '',
+ 'UidNext': 'INBOX' === sFolder ? Cache.getFolderUidNext(sFolder) : ''
+ });
+ }
+ else if (Data.useThreads())
+ {
+ if (Globals.__RL)
+ {
+ Globals.__RL.reloadFlagsCurrentMessageListAndMessageFromCache();
+ }
+ }
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {Array} aFolders
+ */
+ WebMailAjaxRemoteStorage.prototype.folderInformationMultiply = function (fCallback, aFolders)
+ {
+ this.defaultRequest(fCallback, 'FolderInformationMultiply', {
+ 'Folders': aFolders
+ });
+ };
+
+ /**
+ * @param {?Function} fCallback
+ */
+ WebMailAjaxRemoteStorage.prototype.logout = function (fCallback)
+ {
+ this.defaultRequest(fCallback, 'Logout');
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {string} sFolderFullNameRaw
+ * @param {Array} aUids
+ * @param {boolean} bSetFlagged
+ */
+ WebMailAjaxRemoteStorage.prototype.messageSetFlagged = function (fCallback, sFolderFullNameRaw, aUids, bSetFlagged)
+ {
+ this.defaultRequest(fCallback, 'MessageSetFlagged', {
+ 'Folder': sFolderFullNameRaw,
+ 'Uids': aUids.join(','),
+ 'SetAction': bSetFlagged ? '1' : '0'
+ });
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {string} sFolderFullNameRaw
+ * @param {Array} aUids
+ * @param {boolean} bSetSeen
+ */
+ WebMailAjaxRemoteStorage.prototype.messageSetSeen = function (fCallback, sFolderFullNameRaw, aUids, bSetSeen)
+ {
+ this.defaultRequest(fCallback, 'MessageSetSeen', {
+ 'Folder': sFolderFullNameRaw,
+ 'Uids': aUids.join(','),
+ 'SetAction': bSetSeen ? '1' : '0'
+ });
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {string} sFolderFullNameRaw
+ * @param {boolean} bSetSeen
+ */
+ WebMailAjaxRemoteStorage.prototype.messageSetSeenToAll = function (fCallback, sFolderFullNameRaw, bSetSeen)
+ {
+ this.defaultRequest(fCallback, 'MessageSetSeenToAll', {
+ 'Folder': sFolderFullNameRaw,
+ 'SetAction': bSetSeen ? '1' : '0'
+ });
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {string} sMessageFolder
+ * @param {string} sMessageUid
+ * @param {string} sDraftFolder
+ * @param {string} sFrom
+ * @param {string} sTo
+ * @param {string} sCc
+ * @param {string} sBcc
+ * @param {string} sSubject
+ * @param {boolean} bTextIsHtml
+ * @param {string} sText
+ * @param {Array} aAttachments
+ * @param {(Array|null)} aDraftInfo
+ * @param {string} sInReplyTo
+ * @param {string} sReferences
+ */
+ WebMailAjaxRemoteStorage.prototype.saveMessage = function (fCallback, sMessageFolder, sMessageUid, sDraftFolder,
+ sFrom, sTo, sCc, sBcc, sSubject, bTextIsHtml, sText, aAttachments, aDraftInfo, sInReplyTo, sReferences)
+ {
+ this.defaultRequest(fCallback, 'SaveMessage', {
+ 'MessageFolder': sMessageFolder,
+ 'MessageUid': sMessageUid,
+ 'DraftFolder': sDraftFolder,
+ 'From': sFrom,
+ 'To': sTo,
+ 'Cc': sCc,
+ 'Bcc': sBcc,
+ 'Subject': sSubject,
+ 'TextIsHtml': bTextIsHtml ? '1' : '0',
+ 'Text': sText,
+ 'DraftInfo': aDraftInfo,
+ 'InReplyTo': sInReplyTo,
+ 'References': sReferences,
+ 'Attachments': aAttachments
+ }, Consts.Defaults.SaveMessageAjaxTimeout);
+ };
+
+
+ /**
+ * @param {?Function} fCallback
+ * @param {string} sMessageFolder
+ * @param {string} sMessageUid
+ * @param {string} sReadReceipt
+ * @param {string} sSubject
+ * @param {string} sText
+ */
+ WebMailAjaxRemoteStorage.prototype.sendReadReceiptMessage = function (fCallback, sMessageFolder, sMessageUid, sReadReceipt, sSubject, sText)
+ {
+ this.defaultRequest(fCallback, 'SendReadReceiptMessage', {
+ 'MessageFolder': sMessageFolder,
+ 'MessageUid': sMessageUid,
+ 'ReadReceipt': sReadReceipt,
+ 'Subject': sSubject,
+ 'Text': sText
+ });
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {string} sMessageFolder
+ * @param {string} sMessageUid
+ * @param {string} sSentFolder
+ * @param {string} sFrom
+ * @param {string} sTo
+ * @param {string} sCc
+ * @param {string} sBcc
+ * @param {string} sSubject
+ * @param {boolean} bTextIsHtml
+ * @param {string} sText
+ * @param {Array} aAttachments
+ * @param {(Array|null)} aDraftInfo
+ * @param {string} sInReplyTo
+ * @param {string} sReferences
+ * @param {boolean} bRequestReadReceipt
+ */
+ WebMailAjaxRemoteStorage.prototype.sendMessage = function (fCallback, sMessageFolder, sMessageUid, sSentFolder,
+ sFrom, sTo, sCc, sBcc, sSubject, bTextIsHtml, sText, aAttachments, aDraftInfo, sInReplyTo, sReferences, bRequestReadReceipt)
+ {
+ this.defaultRequest(fCallback, 'SendMessage', {
+ 'MessageFolder': sMessageFolder,
+ 'MessageUid': sMessageUid,
+ 'SentFolder': sSentFolder,
+ 'From': sFrom,
+ 'To': sTo,
+ 'Cc': sCc,
+ 'Bcc': sBcc,
+ 'Subject': sSubject,
+ 'TextIsHtml': bTextIsHtml ? '1' : '0',
+ 'Text': sText,
+ 'DraftInfo': aDraftInfo,
+ 'InReplyTo': sInReplyTo,
+ 'References': sReferences,
+ 'ReadReceiptRequest': bRequestReadReceipt ? '1' : '0',
+ 'Attachments': aAttachments
+ }, Consts.Defaults.SendMessageAjaxTimeout);
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {Object} oData
+ */
+ WebMailAjaxRemoteStorage.prototype.saveSystemFolders = function (fCallback, oData)
+ {
+ this.defaultRequest(fCallback, 'SystemFoldersUpdate', oData);
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {Object} oData
+ */
+ WebMailAjaxRemoteStorage.prototype.saveSettings = function (fCallback, oData)
+ {
+ this.defaultRequest(fCallback, 'SettingsUpdate', oData);
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {string} sPrevPassword
+ * @param {string} sNewPassword
+ */
+ WebMailAjaxRemoteStorage.prototype.changePassword = function (fCallback, sPrevPassword, sNewPassword)
+ {
+ this.defaultRequest(fCallback, 'ChangePassword', {
+ 'PrevPassword': sPrevPassword,
+ 'NewPassword': sNewPassword
+ });
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {string} sNewFolderName
+ * @param {string} sParentName
+ */
+ WebMailAjaxRemoteStorage.prototype.folderCreate = function (fCallback, sNewFolderName, sParentName)
+ {
+ this.defaultRequest(fCallback, 'FolderCreate', {
+ 'Folder': sNewFolderName,
+ 'Parent': sParentName
+ }, null, '', ['Folders']);
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {string} sFolderFullNameRaw
+ */
+ WebMailAjaxRemoteStorage.prototype.folderDelete = function (fCallback, sFolderFullNameRaw)
+ {
+ this.defaultRequest(fCallback, 'FolderDelete', {
+ 'Folder': sFolderFullNameRaw
+ }, null, '', ['Folders']);
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {string} sPrevFolderFullNameRaw
+ * @param {string} sNewFolderName
+ */
+ WebMailAjaxRemoteStorage.prototype.folderRename = function (fCallback, sPrevFolderFullNameRaw, sNewFolderName)
+ {
+ this.defaultRequest(fCallback, 'FolderRename', {
+ 'Folder': sPrevFolderFullNameRaw,
+ 'NewFolderName': sNewFolderName
+ }, null, '', ['Folders']);
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {string} sFolderFullNameRaw
+ */
+ WebMailAjaxRemoteStorage.prototype.folderClear = function (fCallback, sFolderFullNameRaw)
+ {
+ this.defaultRequest(fCallback, 'FolderClear', {
+ 'Folder': sFolderFullNameRaw
+ });
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {string} sFolderFullNameRaw
+ * @param {boolean} bSubscribe
+ */
+ WebMailAjaxRemoteStorage.prototype.folderSetSubscribe = function (fCallback, sFolderFullNameRaw, bSubscribe)
+ {
+ this.defaultRequest(fCallback, 'FolderSubscribe', {
+ 'Folder': sFolderFullNameRaw,
+ 'Subscribe': bSubscribe ? '1' : '0'
+ });
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {string} sFolder
+ * @param {string} sToFolder
+ * @param {Array} aUids
+ * @param {string=} sLearning
+ */
+ WebMailAjaxRemoteStorage.prototype.messagesMove = function (fCallback, sFolder, sToFolder, aUids, sLearning)
+ {
+ this.defaultRequest(fCallback, 'MessageMove', {
+ 'FromFolder': sFolder,
+ 'ToFolder': sToFolder,
+ 'Uids': aUids.join(','),
+ 'Learning': sLearning || ''
+ }, null, '', ['MessageList']);
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {string} sFolder
+ * @param {string} sToFolder
+ * @param {Array} aUids
+ */
+ WebMailAjaxRemoteStorage.prototype.messagesCopy = function (fCallback, sFolder, sToFolder, aUids)
+ {
+ this.defaultRequest(fCallback, 'MessageCopy', {
+ 'FromFolder': sFolder,
+ 'ToFolder': sToFolder,
+ 'Uids': aUids.join(',')
+ });
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {string} sFolder
+ * @param {Array} aUids
+ */
+ WebMailAjaxRemoteStorage.prototype.messagesDelete = function (fCallback, sFolder, aUids)
+ {
+ this.defaultRequest(fCallback, 'MessageDelete', {
+ 'Folder': sFolder,
+ 'Uids': aUids.join(',')
+ }, null, '', ['MessageList']);
+ };
+
+ /**
+ * @param {?Function} fCallback
+ */
+ WebMailAjaxRemoteStorage.prototype.appDelayStart = function (fCallback)
+ {
+ this.defaultRequest(fCallback, 'AppDelayStart');
+ };
+
+ /**
+ * @param {?Function} fCallback
+ */
+ WebMailAjaxRemoteStorage.prototype.quota = function (fCallback)
+ {
+ this.defaultRequest(fCallback, 'Quota');
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {number} iOffset
+ * @param {number} iLimit
+ * @param {string} sSearch
+ */
+ WebMailAjaxRemoteStorage.prototype.contacts = function (fCallback, iOffset, iLimit, sSearch)
+ {
+ this.defaultRequest(fCallback, 'Contacts', {
+ 'Offset': iOffset,
+ 'Limit': iLimit,
+ 'Search': sSearch
+ }, null, '', ['Contacts']);
+ };
+
+ /**
+ * @param {?Function} fCallback
+ */
+ WebMailAjaxRemoteStorage.prototype.contactSave = function (fCallback, sRequestUid, sUid, sTags, aProperties)
+ {
+ this.defaultRequest(fCallback, 'ContactSave', {
+ 'RequestUid': sRequestUid,
+ 'Uid': Utils.trim(sUid),
+ 'Tags': Utils.trim(sTags),
+ 'Properties': aProperties
+ });
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {Array} aUids
+ */
+ WebMailAjaxRemoteStorage.prototype.contactsDelete = function (fCallback, aUids)
+ {
+ this.defaultRequest(fCallback, 'ContactsDelete', {
+ 'Uids': aUids.join(',')
+ });
+ };
+
+ /**
+ * @param {?Function} fCallback
+ * @param {string} sQuery
+ * @param {number} iPage
+ */
+ WebMailAjaxRemoteStorage.prototype.suggestions = function (fCallback, sQuery, iPage)
+ {
+ this.defaultRequest(fCallback, 'Suggestions', {
+ 'Query': sQuery,
+ 'Page': iPage
+ }, null, '', ['Suggestions']);
+ };
+
+ /**
+ * @param {?Function} fCallback
+ */
+ WebMailAjaxRemoteStorage.prototype.facebookUser = function (fCallback)
+ {
+ this.defaultRequest(fCallback, 'SocialFacebookUserInformation');
+ };
+
+ /**
+ * @param {?Function} fCallback
+ */
+ WebMailAjaxRemoteStorage.prototype.facebookDisconnect = function (fCallback)
+ {
+ this.defaultRequest(fCallback, 'SocialFacebookDisconnect');
+ };
+
+ /**
+ * @param {?Function} fCallback
+ */
+ WebMailAjaxRemoteStorage.prototype.twitterUser = function (fCallback)
+ {
+ this.defaultRequest(fCallback, 'SocialTwitterUserInformation');
+ };
+
+ /**
+ * @param {?Function} fCallback
+ */
+ WebMailAjaxRemoteStorage.prototype.twitterDisconnect = function (fCallback)
+ {
+ this.defaultRequest(fCallback, 'SocialTwitterDisconnect');
+ };
+
+ /**
+ * @param {?Function} fCallback
+ */
+ WebMailAjaxRemoteStorage.prototype.googleUser = function (fCallback)
+ {
+ this.defaultRequest(fCallback, 'SocialGoogleUserInformation');
+ };
+
+ /**
+ * @param {?Function} fCallback
+ */
+ WebMailAjaxRemoteStorage.prototype.googleDisconnect = function (fCallback)
+ {
+ this.defaultRequest(fCallback, 'SocialGoogleDisconnect');
+ };
+
+ /**
+ * @param {?Function} fCallback
+ */
+ WebMailAjaxRemoteStorage.prototype.socialUsers = function (fCallback)
+ {
+ this.defaultRequest(fCallback, 'SocialUsers');
+ };
+
+ module.exports = new WebMailAjaxRemoteStorage();
+
+}(module));
+},{"../Common/Base64.js":5,"../Common/Consts.js":6,"../Common/Globals.js":9,"../Common/Utils.js":14,"../External/underscore.js":31,"./AbstractAjaxRemoteStorage.js":59,"./AppSettings.js":61,"./WebMailCacheStorage.js":66,"./WebMailDataStorage.js":67}],66:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ _ = require('../External/underscore.js'),
+
+ Enums = require('../Common/Enums.js'),
+ Utils = require('../Common/Utils.js'),
+ LinkBuilder = require('../Common/LinkBuilder.js'),
+
+ AppSettings = require('./AppSettings.js')
+ ;
+
+ /**
+ * @constructor
+ */
+ function WebMailCacheStorage()
+ {
+ this.oFoldersCache = {};
+ this.oFoldersNamesCache = {};
+ this.oFolderHashCache = {};
+ this.oFolderUidNextCache = {};
+ this.oMessageListHashCache = {};
+ this.oMessageFlagsCache = {};
+ this.oNewMessage = {};
+ this.oRequestedMessage = {};
+
+ this.bCapaGravatar = AppSettings.capa(Enums.Capa.Gravatar);
+ }
+
+ /**
+ * @type {boolean}
+ */
+ WebMailCacheStorage.prototype.bCapaGravatar = false;
+
+ /**
+ * @type {Object}
+ */
+ WebMailCacheStorage.prototype.oFoldersCache = {};
+
+ /**
+ * @type {Object}
+ */
+ WebMailCacheStorage.prototype.oFoldersNamesCache = {};
+
+ /**
+ * @type {Object}
+ */
+ WebMailCacheStorage.prototype.oFolderHashCache = {};
+
+ /**
+ * @type {Object}
+ */
+ WebMailCacheStorage.prototype.oFolderUidNextCache = {};
+
+ /**
+ * @type {Object}
+ */
+ WebMailCacheStorage.prototype.oMessageListHashCache = {};
+
+ /**
+ * @type {Object}
+ */
+ WebMailCacheStorage.prototype.oMessageFlagsCache = {};
+
+ /**
+ * @type {Object}
+ */
+ WebMailCacheStorage.prototype.oBodies = {};
+
+ /**
+ * @type {Object}
+ */
+ WebMailCacheStorage.prototype.oNewMessage = {};
+
+ /**
+ * @type {Object}
+ */
+ WebMailCacheStorage.prototype.oRequestedMessage = {};
+
+ WebMailCacheStorage.prototype.clear = function ()
+ {
+ this.oFoldersCache = {};
+ this.oFoldersNamesCache = {};
+ this.oFolderHashCache = {};
+ this.oFolderUidNextCache = {};
+ this.oMessageListHashCache = {};
+ this.oMessageFlagsCache = {};
+ this.oBodies = {};
+ };
+
+
+ /**
+ * @param {string} sEmail
+ * @param {Function} fCallback
+ * @return {string}
+ */
+ WebMailCacheStorage.prototype.getUserPic = function (sEmail, fCallback)
+ {
+ sEmail = Utils.trim(sEmail);
+ fCallback(this.bCapaGravatar && '' !== sEmail ? LinkBuilder.avatarLink(sEmail) : '', sEmail);
+ };
+
+ /**
+ * @param {string} sFolderFullNameRaw
+ * @param {string} sUid
+ * @return {string}
+ */
+ WebMailCacheStorage.prototype.getMessageKey = function (sFolderFullNameRaw, sUid)
+ {
+ return sFolderFullNameRaw + '#' + sUid;
+ };
+
+ /**
+ * @param {string} sFolder
+ * @param {string} sUid
+ */
+ WebMailCacheStorage.prototype.addRequestedMessage = function (sFolder, sUid)
+ {
+ this.oRequestedMessage[this.getMessageKey(sFolder, sUid)] = true;
+ };
+
+ /**
+ * @param {string} sFolder
+ * @param {string} sUid
+ * @return {boolean}
+ */
+ WebMailCacheStorage.prototype.hasRequestedMessage = function (sFolder, sUid)
+ {
+ return true === this.oRequestedMessage[this.getMessageKey(sFolder, sUid)];
+ };
+
+ /**
+ * @param {string} sFolderFullNameRaw
+ * @param {string} sUid
+ */
+ WebMailCacheStorage.prototype.addNewMessageCache = function (sFolderFullNameRaw, sUid)
+ {
+ this.oNewMessage[this.getMessageKey(sFolderFullNameRaw, sUid)] = true;
+ };
+
+ /**
+ * @param {string} sFolderFullNameRaw
+ * @param {string} sUid
+ */
+ WebMailCacheStorage.prototype.hasNewMessageAndRemoveFromCache = function (sFolderFullNameRaw, sUid)
+ {
+ if (this.oNewMessage[this.getMessageKey(sFolderFullNameRaw, sUid)])
+ {
+ this.oNewMessage[this.getMessageKey(sFolderFullNameRaw, sUid)] = null;
+ return true;
+ }
+
+ return false;
+ };
+
+ WebMailCacheStorage.prototype.clearNewMessageCache = function ()
+ {
+ this.oNewMessage = {};
+ };
+
+ /**
+ * @param {string} sFolderHash
+ * @return {string}
+ */
+ WebMailCacheStorage.prototype.getFolderFullNameRaw = function (sFolderHash)
+ {
+ return '' !== sFolderHash && this.oFoldersNamesCache[sFolderHash] ? this.oFoldersNamesCache[sFolderHash] : '';
+ };
+
+ /**
+ * @param {string} sFolderHash
+ * @param {string} sFolderFullNameRaw
+ */
+ WebMailCacheStorage.prototype.setFolderFullNameRaw = function (sFolderHash, sFolderFullNameRaw)
+ {
+ this.oFoldersNamesCache[sFolderHash] = sFolderFullNameRaw;
+ };
+
+ /**
+ * @param {string} sFolderFullNameRaw
+ * @return {string}
+ */
+ WebMailCacheStorage.prototype.getFolderHash = function (sFolderFullNameRaw)
+ {
+ return '' !== sFolderFullNameRaw && this.oFolderHashCache[sFolderFullNameRaw] ? this.oFolderHashCache[sFolderFullNameRaw] : '';
+ };
+
+ /**
+ * @param {string} sFolderFullNameRaw
+ * @param {string} sFolderHash
+ */
+ WebMailCacheStorage.prototype.setFolderHash = function (sFolderFullNameRaw, sFolderHash)
+ {
+ this.oFolderHashCache[sFolderFullNameRaw] = sFolderHash;
+ };
+
+ /**
+ * @param {string} sFolderFullNameRaw
+ * @return {string}
+ */
+ WebMailCacheStorage.prototype.getFolderUidNext = function (sFolderFullNameRaw)
+ {
+ return '' !== sFolderFullNameRaw && this.oFolderUidNextCache[sFolderFullNameRaw] ? this.oFolderUidNextCache[sFolderFullNameRaw] : '';
+ };
+
+ /**
+ * @param {string} sFolderFullNameRaw
+ * @param {string} sUidNext
+ */
+ WebMailCacheStorage.prototype.setFolderUidNext = function (sFolderFullNameRaw, sUidNext)
+ {
+ this.oFolderUidNextCache[sFolderFullNameRaw] = sUidNext;
+ };
+
+ /**
+ * @param {string} sFolderFullNameRaw
+ * @return {?FolderModel}
+ */
+ WebMailCacheStorage.prototype.getFolderFromCacheList = function (sFolderFullNameRaw)
+ {
+ return '' !== sFolderFullNameRaw && this.oFoldersCache[sFolderFullNameRaw] ? this.oFoldersCache[sFolderFullNameRaw] : null;
+ };
+
+ /**
+ * @param {string} sFolderFullNameRaw
+ * @param {?FolderModel} oFolder
+ */
+ WebMailCacheStorage.prototype.setFolderToCacheList = function (sFolderFullNameRaw, oFolder)
+ {
+ this.oFoldersCache[sFolderFullNameRaw] = oFolder;
+ };
+
+ /**
+ * @param {string} sFolderFullNameRaw
+ */
+ WebMailCacheStorage.prototype.removeFolderFromCacheList = function (sFolderFullNameRaw)
+ {
+ this.setFolderToCacheList(sFolderFullNameRaw, null);
+ };
+
+ /**
+ * @param {string} sFolderFullName
+ * @param {string} sUid
+ * @return {?Array}
+ */
+ WebMailCacheStorage.prototype.getMessageFlagsFromCache = function (sFolderFullName, sUid)
+ {
+ return this.oMessageFlagsCache[sFolderFullName] && this.oMessageFlagsCache[sFolderFullName][sUid] ?
+ this.oMessageFlagsCache[sFolderFullName][sUid] : null;
+ };
+
+ /**
+ * @param {string} sFolderFullName
+ * @param {string} sUid
+ * @param {Array} aFlagsCache
+ */
+ WebMailCacheStorage.prototype.setMessageFlagsToCache = function (sFolderFullName, sUid, aFlagsCache)
+ {
+ if (!this.oMessageFlagsCache[sFolderFullName])
+ {
+ this.oMessageFlagsCache[sFolderFullName] = {};
+ }
+
+ this.oMessageFlagsCache[sFolderFullName][sUid] = aFlagsCache;
+ };
+
+ /**
+ * @param {string} sFolderFullName
+ */
+ WebMailCacheStorage.prototype.clearMessageFlagsFromCacheByFolder = function (sFolderFullName)
+ {
+ this.oMessageFlagsCache[sFolderFullName] = {};
+ };
+
+ /**
+ * @param {(MessageModel|null)} oMessage
+ */
+ WebMailCacheStorage.prototype.initMessageFlagsFromCache = function (oMessage)
+ {
+ if (oMessage)
+ {
+ var
+ self = this,
+ aFlags = this.getMessageFlagsFromCache(oMessage.folderFullNameRaw, oMessage.uid),
+ mUnseenSubUid = null,
+ mFlaggedSubUid = null
+ ;
+
+ if (aFlags && 0 < aFlags.length)
+ {
+ oMessage.unseen(!!aFlags[0]);
+ oMessage.flagged(!!aFlags[1]);
+ oMessage.answered(!!aFlags[2]);
+ oMessage.forwarded(!!aFlags[3]);
+ oMessage.isReadReceipt(!!aFlags[4]);
+ }
+
+ if (0 < oMessage.threads().length)
+ {
+ mUnseenSubUid = _.find(oMessage.threads(), function (iSubUid) {
+ var aFlags = self.getMessageFlagsFromCache(oMessage.folderFullNameRaw, iSubUid);
+ return aFlags && 0 < aFlags.length && !!aFlags[0];
+ });
+
+ mFlaggedSubUid = _.find(oMessage.threads(), function (iSubUid) {
+ var aFlags = self.getMessageFlagsFromCache(oMessage.folderFullNameRaw, iSubUid);
+ return aFlags && 0 < aFlags.length && !!aFlags[1];
+ });
+
+ oMessage.hasUnseenSubMessage(mUnseenSubUid && 0 < Utils.pInt(mUnseenSubUid));
+ oMessage.hasFlaggedSubMessage(mFlaggedSubUid && 0 < Utils.pInt(mFlaggedSubUid));
+ }
+ }
+ };
+
+ /**
+ * @param {(MessageModel|null)} oMessage
+ */
+ WebMailCacheStorage.prototype.storeMessageFlagsToCache = function (oMessage)
+ {
+ if (oMessage)
+ {
+ this.setMessageFlagsToCache(
+ oMessage.folderFullNameRaw,
+ oMessage.uid,
+ [oMessage.unseen(), oMessage.flagged(), oMessage.answered(), oMessage.forwarded(), oMessage.isReadReceipt()]
+ );
+ }
+ };
+ /**
+ * @param {string} sFolder
+ * @param {string} sUid
+ * @param {Array} aFlags
+ */
+ WebMailCacheStorage.prototype.storeMessageFlagsToCacheByFolderAndUid = function (sFolder, sUid, aFlags)
+ {
+ if (Utils.isArray(aFlags) && 0 < aFlags.length)
+ {
+ this.setMessageFlagsToCache(sFolder, sUid, aFlags);
+ }
+ };
+
+ module.exports = new WebMailCacheStorage();
+
+}(module));
+},{"../Common/Enums.js":7,"../Common/LinkBuilder.js":10,"../Common/Utils.js":14,"../External/underscore.js":31,"./AppSettings.js":61}],67:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ window = require('../External/window.js'),
+ $ = require('../External/jquery.js'),
+ _ = require('../External/underscore.js'),
+ ko = require('../External/ko.js'),
+ moment = require('../External/moment.js'),
+ $div = require('../External/$div.js'),
+ NotificationClass = require('../External/NotificationClass.js'),
+
+ Consts = require('../Common/Consts.js'),
+ Enums = require('../Common/Enums.js'),
+ Globals = require('../Common/Globals.js'),
+ Utils = require('../Common/Utils.js'),
+ LinkBuilder = require('../Common/LinkBuilder.js'),
+
+ AppSettings = require('./AppSettings.js'),
+ Cache = require('./WebMailCacheStorage.js'),
+
+ kn = require('../Knoin/Knoin.js'),
+
+ MessageModel = require('../Models/MessageModel.js'),
+
+ LocalStorage = require('./LocalStorage.js'),
+ AbstractData = require('./AbstractData.js')
+ ;
+
+ /**
+ * @constructor
+ * @extends AbstractData
+ */
+ function WebMailDataStorage()
+ {
+ AbstractData.call(this);
+
+ var
+ fRemoveSystemFolderType = function (observable) {
+ return function () {
+ var oFolder = Cache.getFolderFromCacheList(observable());
+ if (oFolder)
+ {
+ oFolder.type(Enums.FolderType.User);
+ }
+ };
+ },
+ fSetSystemFolderType = function (iType) {
+ return function (sValue) {
+ var oFolder = Cache.getFolderFromCacheList(sValue);
+ if (oFolder)
+ {
+ oFolder.type(iType);
+ }
+ };
+ }
+ ;
+
+ this.devEmail = '';
+ this.devPassword = '';
+
+ this.accountEmail = ko.observable('');
+ this.accountIncLogin = ko.observable('');
+ this.accountOutLogin = ko.observable('');
+ this.projectHash = ko.observable('');
+ this.threading = ko.observable(false);
+
+ this.lastFoldersHash = '';
+ this.remoteSuggestions = false;
+
+ // system folders
+ this.sentFolder = ko.observable('');
+ this.draftFolder = ko.observable('');
+ this.spamFolder = ko.observable('');
+ this.trashFolder = ko.observable('');
+ this.archiveFolder = ko.observable('');
+
+ this.sentFolder.subscribe(fRemoveSystemFolderType(this.sentFolder), this, 'beforeChange');
+ this.draftFolder.subscribe(fRemoveSystemFolderType(this.draftFolder), this, 'beforeChange');
+ this.spamFolder.subscribe(fRemoveSystemFolderType(this.spamFolder), this, 'beforeChange');
+ this.trashFolder.subscribe(fRemoveSystemFolderType(this.trashFolder), this, 'beforeChange');
+ this.archiveFolder.subscribe(fRemoveSystemFolderType(this.archiveFolder), this, 'beforeChange');
+
+ this.sentFolder.subscribe(fSetSystemFolderType(Enums.FolderType.SentItems), this);
+ this.draftFolder.subscribe(fSetSystemFolderType(Enums.FolderType.Draft), this);
+ this.spamFolder.subscribe(fSetSystemFolderType(Enums.FolderType.Spam), this);
+ this.trashFolder.subscribe(fSetSystemFolderType(Enums.FolderType.Trash), this);
+ this.archiveFolder.subscribe(fSetSystemFolderType(Enums.FolderType.Archive), this);
+
+ this.draftFolderNotEnabled = ko.computed(function () {
+ return '' === this.draftFolder() || Consts.Values.UnuseOptionValue === this.draftFolder();
+ }, this);
+
+ // personal
+ this.displayName = ko.observable('');
+ this.signature = ko.observable('');
+ this.signatureToAll = ko.observable(false);
+ this.replyTo = ko.observable('');
+
+ // security
+ this.enableTwoFactor = ko.observable(false);
+
+ // accounts
+ this.accounts = ko.observableArray([]);
+ this.accountsLoading = ko.observable(false).extend({'throttle': 100});
+
+ // identities
+ this.defaultIdentityID = ko.observable('');
+ this.identities = ko.observableArray([]);
+ this.identitiesLoading = ko.observable(false).extend({'throttle': 100});
+
+ // contacts
+ this.contactTags = ko.observableArray([]);
+ this.contacts = ko.observableArray([]);
+ this.contacts.loading = ko.observable(false).extend({'throttle': 200});
+ this.contacts.importing = ko.observable(false).extend({'throttle': 200});
+ this.contacts.syncing = ko.observable(false).extend({'throttle': 200});
+ this.contacts.exportingVcf = ko.observable(false).extend({'throttle': 200});
+ this.contacts.exportingCsv = ko.observable(false).extend({'throttle': 200});
+
+ this.allowContactsSync = ko.observable(false);
+ this.enableContactsSync = ko.observable(false);
+ this.contactsSyncUrl = ko.observable('');
+ this.contactsSyncUser = ko.observable('');
+ this.contactsSyncPass = ko.observable('');
+
+ this.allowContactsSync = ko.observable(!!AppSettings.settingsGet('ContactsSyncIsAllowed'));
+ this.enableContactsSync = ko.observable(!!AppSettings.settingsGet('EnableContactsSync'));
+ this.contactsSyncUrl = ko.observable(AppSettings.settingsGet('ContactsSyncUrl'));
+ this.contactsSyncUser = ko.observable(AppSettings.settingsGet('ContactsSyncUser'));
+ this.contactsSyncPass = ko.observable(AppSettings.settingsGet('ContactsSyncPassword'));
+
+ // folders
+ this.namespace = '';
+ this.folderList = ko.observableArray([]);
+ this.folderList.focused = ko.observable(false);
+
+ this.foldersListError = ko.observable('');
+
+ this.foldersLoading = ko.observable(false);
+ this.foldersCreating = ko.observable(false);
+ this.foldersDeleting = ko.observable(false);
+ this.foldersRenaming = ko.observable(false);
+
+ this.foldersChanging = ko.computed(function () {
+ var
+ bLoading = this.foldersLoading(),
+ bCreating = this.foldersCreating(),
+ bDeleting = this.foldersDeleting(),
+ bRenaming = this.foldersRenaming()
+ ;
+ return bLoading || bCreating || bDeleting || bRenaming;
+ }, this);
+
+ this.foldersInboxUnreadCount = ko.observable(0);
+
+ this.currentFolder = ko.observable(null).extend({'toggleSubscribe': [null,
+ function (oPrev) {
+ if (oPrev)
+ {
+ oPrev.selected(false);
+ }
+ }, function (oNext) {
+ if (oNext)
+ {
+ oNext.selected(true);
+ }
+ }
+ ]});
+
+ this.currentFolderFullNameRaw = ko.computed(function () {
+ return this.currentFolder() ? this.currentFolder().fullNameRaw : '';
+ }, this);
+
+ this.currentFolderFullName = ko.computed(function () {
+ return this.currentFolder() ? this.currentFolder().fullName : '';
+ }, this);
+
+ this.currentFolderFullNameHash = ko.computed(function () {
+ return this.currentFolder() ? this.currentFolder().fullNameHash : '';
+ }, this);
+
+ this.currentFolderName = ko.computed(function () {
+ return this.currentFolder() ? this.currentFolder().name() : '';
+ }, this);
+
+ this.folderListSystemNames = ko.computed(function () {
+
+ var
+ aList = ['INBOX'],
+ aFolders = this.folderList(),
+ sSentFolder = this.sentFolder(),
+ sDraftFolder = this.draftFolder(),
+ sSpamFolder = this.spamFolder(),
+ sTrashFolder = this.trashFolder(),
+ sArchiveFolder = this.archiveFolder()
+ ;
+
+ if (Utils.isArray(aFolders) && 0 < aFolders.length)
+ {
+ if ('' !== sSentFolder && Consts.Values.UnuseOptionValue !== sSentFolder)
+ {
+ aList.push(sSentFolder);
+ }
+ if ('' !== sDraftFolder && Consts.Values.UnuseOptionValue !== sDraftFolder)
+ {
+ aList.push(sDraftFolder);
+ }
+ if ('' !== sSpamFolder && Consts.Values.UnuseOptionValue !== sSpamFolder)
+ {
+ aList.push(sSpamFolder);
+ }
+ if ('' !== sTrashFolder && Consts.Values.UnuseOptionValue !== sTrashFolder)
+ {
+ aList.push(sTrashFolder);
+ }
+ if ('' !== sArchiveFolder && Consts.Values.UnuseOptionValue !== sArchiveFolder)
+ {
+ aList.push(sArchiveFolder);
+ }
+ }
+
+ return aList;
+
+ }, this);
+
+ this.folderListSystem = ko.computed(function () {
+ return _.compact(_.map(this.folderListSystemNames(), function (sName) {
+ return Cache.getFolderFromCacheList(sName);
+ }));
+ }, this);
+
+ this.folderMenuForMove = ko.computed(function () {
+ return Utils.folderListOptionsBuilder(this.folderListSystem(), this.folderList(), [
+ this.currentFolderFullNameRaw()
+ ], null, null, null, null, function (oItem) {
+ return oItem ? oItem.localName() : '';
+ });
+ }, this);
+
+ // message list
+ this.staticMessageList = [];
+
+ this.messageList = ko.observableArray([]).extend({'rateLimit': 0});
+
+ this.messageListCount = ko.observable(0);
+ this.messageListSearch = ko.observable('');
+ this.messageListPage = ko.observable(1);
+
+ this.messageListThreadFolder = ko.observable('');
+ this.messageListThreadUids = ko.observableArray([]);
+
+ this.messageListThreadFolder.subscribe(function () {
+ this.messageListThreadUids([]);
+ }, this);
+
+ this.messageListEndFolder = ko.observable('');
+ this.messageListEndSearch = ko.observable('');
+ this.messageListEndPage = ko.observable(1);
+
+ this.messageListEndHash = ko.computed(function () {
+ return this.messageListEndFolder() + '|' + this.messageListEndSearch() + '|' + this.messageListEndPage();
+ }, this);
+
+ this.messageListPageCount = ko.computed(function () {
+ var iPage = window.Math.ceil(this.messageListCount() / this.messagesPerPage());
+ return 0 >= iPage ? 1 : iPage;
+ }, this);
+
+ this.mainMessageListSearch = ko.computed({
+ 'read': this.messageListSearch,
+ 'write': function (sValue) {
+ kn.setHash(LinkBuilder.mailBox(
+ this.currentFolderFullNameHash(), 1, Utils.trim(sValue.toString())
+ ));
+ },
+ 'owner': this
+ });
+
+ this.messageListError = ko.observable('');
+
+ this.messageListLoading = ko.observable(false);
+ this.messageListIsNotCompleted = ko.observable(false);
+ this.messageListCompleteLoadingThrottle = ko.observable(false).extend({'throttle': 200});
+
+ this.messageListCompleteLoading = ko.computed(function () {
+ var
+ bOne = this.messageListLoading(),
+ bTwo = this.messageListIsNotCompleted()
+ ;
+ return bOne || bTwo;
+ }, this);
+
+ this.messageListCompleteLoading.subscribe(function (bValue) {
+ this.messageListCompleteLoadingThrottle(bValue);
+ }, this);
+
+ this.messageList.subscribe(_.debounce(function (aList) {
+ _.each(aList, function (oItem) {
+ if (oItem.newForAnimation())
+ {
+ oItem.newForAnimation(false);
+ }
+ });
+ }, 500));
+
+ // message preview
+ this.staticMessageList = new MessageModel();
+ this.message = ko.observable(null);
+ this.messageLoading = ko.observable(false);
+ this.messageLoadingThrottle = ko.observable(false).extend({'throttle': 50});
+
+ this.message.focused = ko.observable(false);
+
+ this.message.subscribe(function (oMessage) {
+ if (!oMessage)
+ {
+ this.message.focused(false);
+ this.messageFullScreenMode(false);
+ this.hideMessageBodies();
+
+ if (Enums.Layout.NoPreview === this.layout() &&
+ -1 < window.location.hash.indexOf('message-preview'))
+ {
+ RL.historyBack(); // TODO cjs
+ }
+ }
+ else if (Enums.Layout.NoPreview === this.layout())
+ {
+ this.message.focused(true);
+ }
+ }, this);
+
+ this.message.focused.subscribe(function (bValue) {
+ if (bValue)
+ {
+ this.folderList.focused(false);
+ Globals.keyScope(Enums.KeyState.MessageView);
+ }
+ else if (Enums.KeyState.MessageView === Globals.keyScope())
+ {
+ if (Enums.Layout.NoPreview === this.layout() && this.message())
+ {
+ Globals.keyScope(Enums.KeyState.MessageView);
+ }
+ else
+ {
+ Globals.keyScope(Enums.KeyState.MessageList);
+ }
+ }
+ }, this);
+
+ this.folderList.focused.subscribe(function (bValue) {
+ if (bValue)
+ {
+ Globals.keyScope(Enums.KeyState.FolderList);
+ }
+ else if (Enums.KeyState.FolderList === Globals.keyScope())
+ {
+ Globals.keyScope(Enums.KeyState.MessageList);
+ }
+ });
+
+ this.messageLoading.subscribe(function (bValue) {
+ this.messageLoadingThrottle(bValue);
+ }, this);
+
+ this.messageFullScreenMode = ko.observable(false);
+
+ this.messageError = ko.observable('');
+
+ this.messagesBodiesDom = ko.observable(null);
+
+ this.messagesBodiesDom.subscribe(function (oDom) {
+ if (oDom && !(oDom instanceof $))
+ {
+ this.messagesBodiesDom($(oDom));
+ }
+ }, this);
+
+ this.messageActiveDom = ko.observable(null);
+
+ this.isMessageSelected = ko.computed(function () {
+ return null !== this.message();
+ }, this);
+
+ this.currentMessage = ko.observable(null);
+
+ this.messageListChecked = ko.computed(function () {
+ return _.filter(this.messageList(), function (oItem) {
+ return oItem.checked();
+ });
+ }, this).extend({'rateLimit': 0});
+
+ this.hasCheckedMessages = ko.computed(function () {
+ return 0 < this.messageListChecked().length;
+ }, this).extend({'rateLimit': 0});
+
+ this.messageListCheckedOrSelected = ko.computed(function () {
+
+ var
+ aChecked = this.messageListChecked(),
+ oSelectedMessage = this.currentMessage()
+ ;
+
+ return _.union(aChecked, oSelectedMessage ? [oSelectedMessage] : []);
+
+ }, this);
+
+ this.messageListCheckedOrSelectedUidsWithSubMails = ko.computed(function () {
+ var aList = [];
+ _.each(this.messageListCheckedOrSelected(), function (oMessage) {
+ if (oMessage)
+ {
+ aList.push(oMessage.uid);
+ if (0 < oMessage.threadsLen() && 0 === oMessage.parentUid() && oMessage.lastInCollapsedThread())
+ {
+ aList = _.union(aList, oMessage.threads());
+ }
+ }
+ });
+ return aList;
+ }, this);
+
+ // quota
+ this.userQuota = ko.observable(0);
+ this.userUsageSize = ko.observable(0);
+ this.userUsageProc = ko.computed(function () {
+
+ var
+ iQuota = this.userQuota(),
+ iUsed = this.userUsageSize()
+ ;
+
+ return 0 < iQuota ? window.Math.ceil((iUsed / iQuota) * 100) : 0;
+
+ }, this);
+
+ // other
+ this.capaOpenPGP = ko.observable(false);
+ this.openpgpkeys = ko.observableArray([]);
+ this.openpgpKeyring = null;
+
+ this.openpgpkeysPublic = this.openpgpkeys.filter(function (oItem) {
+ return !!(oItem && !oItem.isPrivate);
+ });
+
+ this.openpgpkeysPrivate = this.openpgpkeys.filter(function (oItem) {
+ return !!(oItem && oItem.isPrivate);
+ });
+
+ // google
+ this.googleActions = ko.observable(false);
+ this.googleLoggined = ko.observable(false);
+ this.googleUserName = ko.observable('');
+
+ // facebook
+ this.facebookActions = ko.observable(false);
+ this.facebookLoggined = ko.observable(false);
+ this.facebookUserName = ko.observable('');
+
+ // twitter
+ this.twitterActions = ko.observable(false);
+ this.twitterLoggined = ko.observable(false);
+ this.twitterUserName = ko.observable('');
+
+ this.customThemeType = ko.observable(Enums.CustomThemeType.Light);
+
+ this.purgeMessageBodyCacheThrottle = _.throttle(this.purgeMessageBodyCache, 1000 * 30);
+ }
+
+ _.extend(WebMailDataStorage.prototype, AbstractData.prototype);
+
+ WebMailDataStorage.prototype.purgeMessageBodyCache = function()
+ {
+ var
+ iCount = 0,
+ oMessagesBodiesDom = null,
+ iEnd = Globals.iMessageBodyCacheCount - Consts.Values.MessageBodyCacheLimit
+ ;
+
+ if (0 < iEnd)
+ {
+ oMessagesBodiesDom = this.messagesBodiesDom();
+ if (oMessagesBodiesDom)
+ {
+ oMessagesBodiesDom.find('.rl-cache-class').each(function () {
+ var oItem = $(this);
+ if (iEnd > oItem.data('rl-cache-count'))
+ {
+ oItem.addClass('rl-cache-purge');
+ iCount++;
+ }
+ });
+
+ if (0 < iCount)
+ {
+ _.delay(function () {
+ oMessagesBodiesDom.find('.rl-cache-purge').remove();
+ }, 300);
+ }
+ }
+ }
+ };
+
+ WebMailDataStorage.prototype.populateDataOnStart = function()
+ {
+ AbstractData.prototype.populateDataOnStart.call(this);
+
+ this.accountEmail(AppSettings.settingsGet('Email'));
+ this.accountIncLogin(AppSettings.settingsGet('IncLogin'));
+ this.accountOutLogin(AppSettings.settingsGet('OutLogin'));
+ this.projectHash(AppSettings.settingsGet('ProjectHash'));
+
+ this.defaultIdentityID(AppSettings.settingsGet('DefaultIdentityID'));
+
+ this.displayName(AppSettings.settingsGet('DisplayName'));
+ this.replyTo(AppSettings.settingsGet('ReplyTo'));
+ this.signature(AppSettings.settingsGet('Signature'));
+ this.signatureToAll(!!AppSettings.settingsGet('SignatureToAll'));
+ this.enableTwoFactor(!!AppSettings.settingsGet('EnableTwoFactor'));
+
+ this.lastFoldersHash = LocalStorage.get(Enums.ClientSideKeyName.FoldersLashHash) || '';
+
+ this.remoteSuggestions = !!AppSettings.settingsGet('RemoteSuggestions');
+
+ this.devEmail = AppSettings.settingsGet('DevEmail');
+ this.devPassword = AppSettings.settingsGet('DevPassword');
+ };
+
+ WebMailDataStorage.prototype.initUidNextAndNewMessages = function (sFolder, sUidNext, aNewMessages)
+ {
+ if ('INBOX' === sFolder && Utils.isNormal(sUidNext) && sUidNext !== '')
+ {
+ if (Utils.isArray(aNewMessages) && 0 < aNewMessages.length)
+ {
+ var
+ self = this,
+ iIndex = 0,
+ iLen = aNewMessages.length,
+ fNotificationHelper = function (sImageSrc, sTitle, sText)
+ {
+ var oNotification = null;
+ if (NotificationClass && self.useDesktopNotifications())
+ {
+ oNotification = new NotificationClass(sTitle, {
+ 'body': sText,
+ 'icon': sImageSrc
+ });
+
+ if (oNotification)
{
- this.submitError(Utils.getNotification(Enums.Notification.UnknownError));
+ if (oNotification.show)
+ {
+ oNotification.show();
+ }
+
+ window.setTimeout((function (oLocalNotifications) {
+ return function () {
+ if (oLocalNotifications.cancel)
+ {
+ oLocalNotifications.cancel();
+ }
+ else if (oLocalNotifications.close)
+ {
+ oLocalNotifications.close();
+ }
+ };
+ }(oNotification)), 7000);
+ }
+ }
+ }
+ ;
+
+ _.each(aNewMessages, function (oItem) {
+ Cache.addNewMessageCache(sFolder, oItem.Uid);
+ });
+
+ if (3 < iLen)
+ {
+ fNotificationHelper(
+ LinkBuilder.notificationMailIcon(),
+ this.accountEmail(),
+ Utils.i18n('MESSAGE_LIST/NEW_MESSAGE_NOTIFICATION', {
+ 'COUNT': iLen
+ })
+ );
+ }
+ else
+ {
+ for (; iIndex < iLen; iIndex++)
+ {
+ fNotificationHelper(
+ LinkBuilder.notificationMailIcon(),
+ MessageModel.emailsToLine(MessageModel.initEmailsFromJson(aNewMessages[iIndex].From), false),
+ aNewMessages[iIndex].Subject
+ );
+ }
+ }
+ }
+
+ Cache.setFolderUidNext(sFolder, sUidNext);
+ }
+ };
+
+ WebMailDataStorage.prototype.hideMessageBodies = function ()
+ {
+ var oMessagesBodiesDom = this.messagesBodiesDom();
+ if (oMessagesBodiesDom)
+ {
+ oMessagesBodiesDom.find('.b-text-part').hide();
+ }
+ };
+
+ /**
+ * @param {boolean=} bBoot = false
+ * @returns {Array}
+ */
+ WebMailDataStorage.prototype.getNextFolderNames = function (bBoot)
+ {
+ bBoot = Utils.isUnd(bBoot) ? false : !!bBoot;
+
+ var
+ aResult = [],
+ iLimit = 10,
+ iUtc = moment().unix(),
+ iTimeout = iUtc - 60 * 5,
+ aTimeouts = [],
+ fSearchFunction = function (aList) {
+ _.each(aList, function (oFolder) {
+ if (oFolder && 'INBOX' !== oFolder.fullNameRaw &&
+ oFolder.selectable && oFolder.existen &&
+ iTimeout > oFolder.interval &&
+ (!bBoot || oFolder.subScribed()))
+ {
+ aTimeouts.push([oFolder.interval, oFolder.fullNameRaw]);
+ }
+
+ if (oFolder && 0 < oFolder.subFolders().length)
+ {
+ fSearchFunction(oFolder.subFolders());
+ }
+ });
+ }
+ ;
+
+ fSearchFunction(this.folderList());
+
+ aTimeouts.sort(function(a, b) {
+ if (a[0] < b[0])
+ {
+ return -1;
+ }
+ else if (a[0] > b[0])
+ {
+ return 1;
+ }
+
+ return 0;
+ });
+
+ _.find(aTimeouts, function (aItem) {
+ var oFolder = Cache.getFolderFromCacheList(aItem[1]);
+ if (oFolder)
+ {
+ oFolder.interval = iUtc;
+ aResult.push(aItem[1]);
+ }
+
+ return iLimit <= aResult.length;
+ });
+
+ return _.uniq(aResult);
+ };
+
+ /**
+ * @param {string} sFromFolderFullNameRaw
+ * @param {Array} aUidForRemove
+ * @param {string=} sToFolderFullNameRaw = ''
+ * @param {bCopy=} bCopy = false
+ */
+ WebMailDataStorage.prototype.removeMessagesFromList = function (
+ sFromFolderFullNameRaw, aUidForRemove, sToFolderFullNameRaw, bCopy)
+ {
+ sToFolderFullNameRaw = Utils.isNormal(sToFolderFullNameRaw) ? sToFolderFullNameRaw : '';
+ bCopy = Utils.isUnd(bCopy) ? false : !!bCopy;
+
+ aUidForRemove = _.map(aUidForRemove, function (mValue) {
+ return Utils.pInt(mValue);
+ });
+
+ var
+ self = this,
+ iUnseenCount = 0,
+ aMessageList = this.messageList(),
+ oFromFolder = Cache.getFolderFromCacheList(sFromFolderFullNameRaw),
+ oToFolder = '' === sToFolderFullNameRaw ? null : Cache.getFolderFromCacheList(sToFolderFullNameRaw || ''),
+ sCurrentFolderFullNameRaw = this.currentFolderFullNameRaw(),
+ oCurrentMessage = this.message(),
+ aMessages = sCurrentFolderFullNameRaw === sFromFolderFullNameRaw ? _.filter(aMessageList, function (oMessage) {
+ return oMessage && -1 < Utils.inArray(Utils.pInt(oMessage.uid), aUidForRemove);
+ }) : []
+ ;
+
+ _.each(aMessages, function (oMessage) {
+ if (oMessage && oMessage.unseen())
+ {
+ iUnseenCount++;
+ }
+ });
+
+ if (oFromFolder && !bCopy)
+ {
+ oFromFolder.messageCountAll(0 <= oFromFolder.messageCountAll() - aUidForRemove.length ?
+ oFromFolder.messageCountAll() - aUidForRemove.length : 0);
+
+ if (0 < iUnseenCount)
+ {
+ oFromFolder.messageCountUnread(0 <= oFromFolder.messageCountUnread() - iUnseenCount ?
+ oFromFolder.messageCountUnread() - iUnseenCount : 0);
+ }
+ }
+
+ if (oToFolder)
+ {
+ oToFolder.messageCountAll(oToFolder.messageCountAll() + aUidForRemove.length);
+ if (0 < iUnseenCount)
+ {
+ oToFolder.messageCountUnread(oToFolder.messageCountUnread() + iUnseenCount);
+ }
+
+ oToFolder.actionBlink(true);
+ }
+
+ if (0 < aMessages.length)
+ {
+ if (bCopy)
+ {
+ _.each(aMessages, function (oMessage) {
+ oMessage.checked(false);
+ });
+ }
+ else
+ {
+ this.messageListIsNotCompleted(true);
+
+ _.each(aMessages, function (oMessage) {
+ if (oCurrentMessage && oCurrentMessage.hash === oMessage.hash)
+ {
+ oCurrentMessage = null;
+ self.message(null);
+ }
+
+ oMessage.deleted(true);
+ });
+
+ _.delay(function () {
+ _.each(aMessages, function (oMessage) {
+ self.messageList.remove(oMessage);
+ });
+ }, 400);
+ }
+ }
+
+ if ('' !== sFromFolderFullNameRaw)
+ {
+ Cache.setFolderHash(sFromFolderFullNameRaw, '');
+ }
+
+ if ('' !== sToFolderFullNameRaw)
+ {
+ Cache.setFolderHash(sToFolderFullNameRaw, '');
+ }
+ };
+
+ WebMailDataStorage.prototype.setMessage = function (oData, bCached)
+ {
+ var
+ bIsHtml = false,
+ bHasExternals = false,
+ bHasInternals = false,
+ oBody = null,
+ oTextBody = null,
+ sId = '',
+ sResultHtml = '',
+ bPgpSigned = false,
+ bPgpEncrypted = false,
+ oMessagesBodiesDom = this.messagesBodiesDom(),
+ oMessage = this.message()
+ ;
+
+ if (oData && oMessage && oData.Result && 'Object/Message' === oData.Result['@Object'] &&
+ oMessage.folderFullNameRaw === oData.Result.Folder && oMessage.uid === oData.Result.Uid)
+ {
+ this.messageError('');
+
+ oMessage.initUpdateByMessageJson(oData.Result);
+ Cache.addRequestedMessage(oMessage.folderFullNameRaw, oMessage.uid);
+
+ if (!bCached)
+ {
+ oMessage.initFlagsByJson(oData.Result);
+ }
+
+ oMessagesBodiesDom = oMessagesBodiesDom && oMessagesBodiesDom[0] ? oMessagesBodiesDom : null;
+ if (oMessagesBodiesDom)
+ {
+ sId = 'rl-mgs-' + oMessage.hash.replace(/[^a-zA-Z0-9]/g, '');
+ oTextBody = oMessagesBodiesDom.find('#' + sId);
+ if (!oTextBody || !oTextBody[0])
+ {
+ bHasExternals = !!oData.Result.HasExternals;
+ bHasInternals = !!oData.Result.HasInternals;
+
+ oBody = $('').hide().addClass('rl-cache-class');
+ oBody.data('rl-cache-count', ++Globals.iMessageBodyCacheCount);
+
+ if (Utils.isNormal(oData.Result.Html) && '' !== oData.Result.Html)
+ {
+ bIsHtml = true;
+ sResultHtml = oData.Result.Html.toString();
+ }
+ else if (Utils.isNormal(oData.Result.Plain) && '' !== oData.Result.Plain)
+ {
+ bIsHtml = false;
+ sResultHtml = Utils.plainToHtml(oData.Result.Plain.toString(), false);
+
+ if ((oMessage.isPgpSigned() || oMessage.isPgpEncrypted()) && this.capaOpenPGP())
+ {
+ oMessage.plainRaw = Utils.pString(oData.Result.Plain);
+
+ bPgpEncrypted = /---BEGIN PGP MESSAGE---/.test(oMessage.plainRaw);
+ if (!bPgpEncrypted)
+ {
+ bPgpSigned = /-----BEGIN PGP SIGNED MESSAGE-----/.test(oMessage.plainRaw) &&
+ /-----BEGIN PGP SIGNATURE-----/.test(oMessage.plainRaw);
+ }
+
+ $div.empty();
+ if (bPgpSigned && oMessage.isPgpSigned())
+ {
+ sResultHtml =
+ $div.append(
+ $('').text(oMessage.plainRaw)
+ ).html()
+ ;
+ }
+ else if (bPgpEncrypted && oMessage.isPgpEncrypted())
+ {
+ sResultHtml =
+ $div.append(
+ $('').text(oMessage.plainRaw)
+ ).html()
+ ;
+ }
+
+ $div.empty();
+
+ oMessage.isPgpSigned(bPgpSigned);
+ oMessage.isPgpEncrypted(bPgpEncrypted);
+ }
+ }
+ else
+ {
+ bIsHtml = false;
+ }
+
+ oBody
+ .html(Utils.linkify(sResultHtml))
+ .addClass('b-text-part ' + (bIsHtml ? 'html' : 'plain'))
+ ;
+
+ oMessage.isHtml(!!bIsHtml);
+ oMessage.hasImages(!!bHasExternals);
+ oMessage.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.None);
+ oMessage.pgpSignedVerifyUser('');
+
+ oMessage.body = oBody;
+ if (oMessage.body)
+ {
+ oMessagesBodiesDom.append(oMessage.body);
+ }
+
+ oMessage.storeDataToDom();
+
+ if (bHasInternals)
+ {
+ oMessage.showInternalImages(true);
+ }
+
+ if (oMessage.hasImages() && this.showImages())
+ {
+ oMessage.showExternalImages(true);
+ }
+
+ this.purgeMessageBodyCacheThrottle();
+ }
+ else
+ {
+ oMessage.body = oTextBody;
+ if (oMessage.body)
+ {
+ oMessage.body.data('rl-cache-count', ++Globals.iMessageBodyCacheCount);
+ oMessage.fetchDataToDom();
+ }
+ }
+
+ this.messageActiveDom(oMessage.body);
+
+ this.hideMessageBodies();
+ oMessage.body.show();
+
+ if (oBody)
+ {
+ Utils.initBlockquoteSwitcher(oBody);
+ }
+ }
+
+ Cache.initMessageFlagsFromCache(oMessage);
+ if (oMessage.unseen())
+ {
+ RL.setMessageSeen(oMessage);
+ }
+
+ Utils.windowResize();
+ }
+ };
+
+ /**
+ * @param {Array} aList
+ * @returns {string}
+ */
+ WebMailDataStorage.prototype.calculateMessageListHash = function (aList)
+ {
+ return _.map(aList, function (oMessage) {
+ return '' + oMessage.hash + '_' + oMessage.threadsLen() + '_' + oMessage.flagHash();
+ }).join('|');
+ };
+
+ WebMailDataStorage.prototype.findPublicKeyByHex = function (sHash)
+ {
+ return _.find(this.openpgpkeysPublic(), function (oItem) {
+ return oItem && sHash === oItem.id;
+ });
+ };
+
+ WebMailDataStorage.prototype.findPublicKeysByEmail = function (sEmail)
+ {
+ return _.compact(_.map(this.openpgpkeysPublic(), function (oItem) {
+
+ var oKey = null;
+ if (oItem && sEmail === oItem.email)
+ {
+ try
+ {
+ oKey = window.openpgp.key.readArmored(oItem.armor);
+ if (oKey && !oKey.err && oKey.keys && oKey.keys[0])
+ {
+ return oKey.keys[0];
+ }
+ }
+ catch (e) {}
+ }
+
+ return null;
+
+ }));
+ };
+
+ /**
+ * @param {string} sEmail
+ * @param {string=} sPassword
+ * @returns {?}
+ */
+ WebMailDataStorage.prototype.findPrivateKeyByEmail = function (sEmail, sPassword)
+ {
+ var
+ oPrivateKey = null,
+ oKey = _.find(this.openpgpkeysPrivate(), function (oItem) {
+ return oItem && sEmail === oItem.email;
+ })
+ ;
+
+ if (oKey)
+ {
+ try
+ {
+ oPrivateKey = window.openpgp.key.readArmored(oKey.armor);
+ if (oPrivateKey && !oPrivateKey.err && oPrivateKey.keys && oPrivateKey.keys[0])
+ {
+ oPrivateKey = oPrivateKey.keys[0];
+ oPrivateKey.decrypt(Utils.pString(sPassword));
+ }
+ else
+ {
+ oPrivateKey = null;
+ }
+ }
+ catch (e)
+ {
+ oPrivateKey = null;
+ }
+ }
+
+ return oPrivateKey;
+ };
+
+ /**
+ * @param {string=} sPassword
+ * @returns {?}
+ */
+ WebMailDataStorage.prototype.findSelfPrivateKey = function (sPassword)
+ {
+ return this.findPrivateKeyByEmail(this.accountEmail(), sPassword);
+ };
+
+ module.exports = new WebMailDataStorage();
+
+}(module));
+
+},{"../Common/Consts.js":6,"../Common/Enums.js":7,"../Common/Globals.js":9,"../Common/LinkBuilder.js":10,"../Common/Utils.js":14,"../External/$div.js":15,"../External/NotificationClass.js":22,"../External/jquery.js":26,"../External/ko.js":28,"../External/moment.js":29,"../External/underscore.js":31,"../External/window.js":32,"../Knoin/Knoin.js":33,"../Models/MessageModel.js":42,"./AbstractData.js":60,"./AppSettings.js":61,"./LocalStorage.js":62,"./WebMailCacheStorage.js":66}],68:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ _ = require('../External/underscore.js'),
+ ko = require('../External/ko.js'),
+ window = require('../External/window.js'),
+ key = require('../External/key.js'),
+
+ Enums = require('../Common/Enums.js'),
+ Utils = require('../Common/Utils.js'),
+ LinkBuilder = require('../Common/LinkBuilder.js'),
+
+ AppSettings = require('../Storages/AppSettings.js'),
+ Data = require('../Storages/WebMailDataStorage.js'),
+ Remote = require('../Storages/WebMailAjaxRemoteStorage.js'),
+
+ RL = require('../Boots/RainLoopApp.js'),
+
+ PopupsKeyboardShortcutsHelpViewModel = require('../ViewModels/Popups/PopupsKeyboardShortcutsHelpViewModel.js'),
+ PopupsAddAccountViewModel = require('../ViewModels/Popups/PopupsKeyboardShortcutsHelpViewModel.js'),
+
+ kn = require('../Knoin/Knoin.js'),
+ KnoinAbstractViewModel = require('../Knoin/KnoinAbstractViewModel.js')
+ ;
+
+ /**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+ function AbstractSystemDropDownViewModel()
+ {
+ KnoinAbstractViewModel.call(this, 'Right', 'SystemDropDown');
+
+ this.accounts = Data.accounts;
+ this.accountEmail = Data.accountEmail;
+ this.accountsLoading = Data.accountsLoading;
+
+ this.accountMenuDropdownTrigger = ko.observable(false);
+
+ this.capaAdditionalAccounts = AppSettings.capa(Enums.Capa.AdditionalAccounts);
+
+ this.loading = ko.computed(function () {
+ return this.accountsLoading();
+ }, this);
+
+ this.accountClick = _.bind(this.accountClick, this);
+ }
+
+ _.extend(AbstractSystemDropDownViewModel.prototype, KnoinAbstractViewModel.prototype);
+
+ AbstractSystemDropDownViewModel.prototype.accountClick = function (oAccount, oEvent)
+ {
+ if (oAccount && oEvent && !Utils.isUnd(oEvent.which) && 1 === oEvent.which)
+ {
+ var self = this;
+ this.accountsLoading(true);
+ _.delay(function () {
+ self.accountsLoading(false);
+ }, 1000);
+ }
+
+ return true;
+ };
+
+ AbstractSystemDropDownViewModel.prototype.emailTitle = function ()
+ {
+ return Data.accountEmail();
+ };
+
+ AbstractSystemDropDownViewModel.prototype.settingsClick = function ()
+ {
+ kn.setHash(LinkBuilder.settings());
+ };
+
+ AbstractSystemDropDownViewModel.prototype.settingsHelp = function ()
+ {
+ kn.showScreenPopup(PopupsKeyboardShortcutsHelpViewModel);
+ };
+
+ AbstractSystemDropDownViewModel.prototype.addAccountClick = function ()
+ {
+ if (this.capaAdditionalAccounts)
+ {
+ kn.showScreenPopup(PopupsAddAccountViewModel);
+ }
+ };
+
+ AbstractSystemDropDownViewModel.prototype.logoutClick = function ()
+ {
+ Remote.logout(function () {
+ if (window.__rlah_clear)
+ {
+ window.__rlah_clear();
+ }
+
+ RL.loginAndLogoutReload(true, AppSettings.settingsGet('ParentEmail') && 0 < AppSettings.settingsGet('ParentEmail').length);
+ });
+ };
+
+ AbstractSystemDropDownViewModel.prototype.onBuild = function ()
+ {
+ var self = this;
+ key('`', [Enums.KeyState.MessageList, Enums.KeyState.MessageView, Enums.KeyState.Settings], function () {
+ if (self.viewModelVisibility())
+ {
+ self.accountMenuDropdownTrigger(true);
+ }
+ });
+
+ // shortcuts help
+ key('shift+/', [Enums.KeyState.MessageList, Enums.KeyState.MessageView, Enums.KeyState.Settings], function () {
+ if (self.viewModelVisibility())
+ {
+ kn.showScreenPopup(PopupsKeyboardShortcutsHelpViewModel);
+ return false;
+ }
+ });
+ };
+
+ module.exports = AbstractSystemDropDownViewModel;
+
+}(module));
+},{"../Boots/RainLoopApp.js":4,"../Common/Enums.js":7,"../Common/LinkBuilder.js":10,"../Common/Utils.js":14,"../External/key.js":27,"../External/ko.js":28,"../External/underscore.js":31,"../External/window.js":32,"../Knoin/Knoin.js":33,"../Knoin/KnoinAbstractViewModel.js":36,"../Storages/AppSettings.js":61,"../Storages/WebMailAjaxRemoteStorage.js":65,"../Storages/WebMailDataStorage.js":67,"../ViewModels/Popups/PopupsKeyboardShortcutsHelpViewModel.js":85}],69:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ window = require('../External/window.js'),
+ $ = require('../External/jquery.js'),
+ _ = require('../External/underscore.js'),
+ ko = require('../External/ko.js'),
+
+ Utils = require('../Common/Utils.js'),
+ Enums = require('../Common/Enums.js'),
+ LinkBuilder = require('../Common/LinkBuilder.js'),
+
+ AppSettings = require('../Storages/AppSettings.js'),
+ Data = require('../Storages/WebMailDataStorage.js'),
+ Remote = require('../Storages/WebMailAjaxRemoteStorage.js'),
+
+ RL = require('../Boots/RainLoopApp.js'),
+
+ kn = require('../Knoin/Knoin.js'),
+ KnoinAbstractViewModel = require('../Knoin/KnoinAbstractViewModel.js'),
+
+ PopupsLanguagesViewModel = require('../ViewModels/Popups/PopupsLanguagesViewModel.js')
+ ;
+
+ /**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+ function LoginViewModel()
+ {
+ KnoinAbstractViewModel.call(this, 'Center', 'Login');
+
+ this.email = ko.observable('');
+ this.password = ko.observable('');
+ this.signMe = ko.observable(false);
+
+ this.additionalCode = ko.observable('');
+ this.additionalCode.error = ko.observable(false);
+ this.additionalCode.focused = ko.observable(false);
+ this.additionalCode.visibility = ko.observable(false);
+ this.additionalCodeSignMe = ko.observable(false);
+
+ this.logoImg = Utils.trim(AppSettings.settingsGet('LoginLogo'));
+ this.loginDescription = Utils.trim(AppSettings.settingsGet('LoginDescription'));
+ this.logoCss = Utils.trim(AppSettings.settingsGet('LoginCss'));
+
+ this.emailError = ko.observable(false);
+ this.passwordError = ko.observable(false);
+
+ this.emailFocus = ko.observable(false);
+ this.submitFocus = ko.observable(false);
+
+ this.email.subscribe(function () {
+ this.emailError(false);
+ this.additionalCode('');
+ this.additionalCode.visibility(false);
+ }, this);
+
+ this.password.subscribe(function () {
+ this.passwordError(false);
+ }, this);
+
+ this.additionalCode.subscribe(function () {
+ this.additionalCode.error(false);
+ }, this);
+
+ this.additionalCode.visibility.subscribe(function () {
+ this.additionalCode.error(false);
+ }, this);
+
+ this.submitRequest = ko.observable(false);
+ this.submitError = ko.observable('');
+
+ this.allowLanguagesOnLogin = Data.allowLanguagesOnLogin;
+
+ this.langRequest = ko.observable(false);
+ this.mainLanguage = Data.mainLanguage;
+ this.bSendLanguage = false;
+
+ this.mainLanguageFullName = ko.computed(function () {
+ return Utils.convertLangName(this.mainLanguage());
+ }, this);
+
+ this.signMeType = ko.observable(Enums.LoginSignMeType.Unused);
+
+ this.signMeType.subscribe(function (iValue) {
+ this.signMe(Enums.LoginSignMeType.DefaultOn === iValue);
+ }, this);
+
+ this.signMeVisibility = ko.computed(function () {
+ return Enums.LoginSignMeType.Unused !== this.signMeType();
+ }, this);
+
+ this.submitCommand = Utils.createCommand(this, function () {
+
+ Utils.triggerAutocompleteInputChange();
+
+ this.emailError('' === Utils.trim(this.email()));
+ this.passwordError('' === Utils.trim(this.password()));
+
+ if (this.additionalCode.visibility())
+ {
+ this.additionalCode.error('' === Utils.trim(this.additionalCode()));
+ }
+
+ if (this.emailError() || this.passwordError() || this.additionalCode.error())
+ {
+ return false;
+ }
+
+ this.submitRequest(true);
+
+ var
+ sPassword = this.password(),
+
+ fLoginRequest = _.bind(function (sPassword) {
+
+ Remote.login(_.bind(function (sResult, oData) {
+
+ if (Enums.StorageResultType.Success === sResult && oData && 'Login' === oData.Action)
+ {
+ if (oData.Result)
+ {
+ if (oData.TwoFactorAuth)
+ {
+ this.additionalCode('');
+ this.additionalCode.visibility(true);
+ this.additionalCode.focused(true);
+
+ this.submitRequest(false);
+ }
+ else
+ {
+ RL.loginAndLogoutReload();
+ }
+ }
+ else if (oData.ErrorCode)
+ {
+ this.submitRequest(false);
+ this.submitError(Utils.getNotification(oData.ErrorCode));
+
+ if ('' === this.submitError())
+ {
+ this.submitError(Utils.getNotification(Enums.Notification.UnknownError));
+ }
+ }
+ else
+ {
+ this.submitRequest(false);
}
}
else
{
this.submitRequest(false);
+ this.submitError(Utils.getNotification(Enums.Notification.UnknownError));
+ }
+
+ }, this), this.email(), '', sPassword, !!this.signMe(),
+ this.bSendLanguage ? this.mainLanguage() : '',
+ this.additionalCode.visibility() ? this.additionalCode() : '',
+ this.additionalCode.visibility() ? !!this.additionalCodeSignMe() : false
+ );
+
+ }, this)
+ ;
+
+ if (!!AppSettings.settingsGet('UseRsaEncryption') && Utils.rsaEncode.supported)
+ {
+ Remote.getPublicKey(_.bind(function (sResult, oData) {
+
+ var bRequest = false;
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result &&
+ Utils.isArray(oData.Result) && oData.Result[0] && oData.Result[1] && oData.Result[2])
+ {
+ var sEncryptedPassword = Utils.rsaEncode(sPassword, oData.Result[0], oData.Result[1], oData.Result[2]);
+ if (sEncryptedPassword)
+ {
+ fLoginRequest(sEncryptedPassword);
+ bRequest = true;
}
}
- else
+
+ if (!bRequest)
{
this.submitRequest(false);
this.submitError(Utils.getNotification(Enums.Notification.UnknownError));
}
- }, this), this.email(), '', sPassword, !!this.signMe(),
- this.bSendLanguage ? this.mainLanguage() : '',
- this.additionalCode.visibility() ? this.additionalCode() : '',
- this.additionalCode.visibility() ? !!this.additionalCodeSignMe() : false
- );
-
- }, this)
- ;
-
- if (!!RL.settingsGet('UseRsaEncryption') && Utils.rsaEncode.supported)
- {
- RL.remote().getPublicKey(_.bind(function (sResult, oData) {
-
- var bRequest = false;
- if (Enums.StorageResultType.Success === sResult && oData && oData.Result &&
- Utils.isArray(oData.Result) && oData.Result[0] && oData.Result[1] && oData.Result[2])
- {
- var sEncryptedPassword = Utils.rsaEncode(sPassword, oData.Result[0], oData.Result[1], oData.Result[2]);
- if (sEncryptedPassword)
- {
- fLoginRequest(sEncryptedPassword);
- bRequest = true;
- }
- }
-
- if (!bRequest)
- {
- this.submitRequest(false);
- this.submitError(Utils.getNotification(Enums.Notification.UnknownError));
- }
-
- }, this));
- }
- else
- {
- fLoginRequest(sPassword);
- }
-
- return true;
-
- }, function () {
- return !this.submitRequest();
- });
-
- this.facebookLoginEnabled = ko.observable(false);
-
- this.facebookCommand = Utils.createCommand(this, function () {
-
- window.open(RL.link().socialFacebook(), 'Facebook', 'left=200,top=100,width=650,height=335,menubar=no,status=no,resizable=yes,scrollbars=yes');
- return true;
-
- }, function () {
- return !this.submitRequest() && this.facebookLoginEnabled();
- });
-
- this.googleLoginEnabled = ko.observable(false);
-
- this.googleCommand = Utils.createCommand(this, function () {
-
- window.open(RL.link().socialGoogle(), 'Google', 'left=200,top=100,width=650,height=335,menubar=no,status=no,resizable=yes,scrollbars=yes');
- return true;
-
- }, function () {
- return !this.submitRequest() && this.googleLoginEnabled();
- });
-
- this.twitterLoginEnabled = ko.observable(false);
-
- this.twitterCommand = Utils.createCommand(this, function () {
-
- window.open(RL.link().socialTwitter(), 'Twitter', 'left=200,top=100,width=650,height=335,menubar=no,status=no,resizable=yes,scrollbars=yes');
- return true;
-
- }, function () {
- return !this.submitRequest() && this.twitterLoginEnabled();
- });
-
- this.socialLoginEnabled = ko.computed(function () {
-
- var
- bF = this.facebookLoginEnabled(),
- bG = this.googleLoginEnabled(),
- bT = this.twitterLoginEnabled()
- ;
-
- return bF || bG || bT;
- }, this);
-
- Knoin.constructorEnd(this);
-}
-
-Utils.extendAsViewModel('LoginViewModel', LoginViewModel);
-
-LoginViewModel.prototype.onShow = function ()
-{
- kn.routeOff();
-
- _.delay(_.bind(function () {
- if ('' !== this.email() && '' !== this.password())
- {
- this.submitFocus(true);
- }
- else
- {
- this.emailFocus(true);
- }
-
- if (RL.settingsGet('UserLanguage'))
- {
- $.cookie('rllang', RL.data().language(), {'expires': 30});
- }
-
- }, this), 100);
-};
-
-LoginViewModel.prototype.onHide = function ()
-{
- this.submitFocus(false);
- this.emailFocus(false);
-};
-
-LoginViewModel.prototype.onBuild = function ()
-{
- var
- self = this,
- sJsHash = RL.settingsGet('JsHash'),
- fSocial = function (iErrorCode) {
- iErrorCode = Utils.pInt(iErrorCode);
- if (0 === iErrorCode)
- {
- self.submitRequest(true);
- RL.loginAndLogoutReload();
+ }, this));
}
else
{
- self.submitError(Utils.getNotification(iErrorCode));
+ fLoginRequest(sPassword);
}
- }
- ;
- this.facebookLoginEnabled(!!RL.settingsGet('AllowFacebookSocial'));
- this.twitterLoginEnabled(!!RL.settingsGet('AllowTwitterSocial'));
- this.googleLoginEnabled(!!RL.settingsGet('AllowGoogleSocial'));
+ return true;
- switch ((RL.settingsGet('SignMe') || 'unused').toLowerCase())
- {
- case Enums.LoginSignMeTypeAsString.DefaultOff:
- this.signMeType(Enums.LoginSignMeType.DefaultOff);
- break;
- case Enums.LoginSignMeTypeAsString.DefaultOn:
- this.signMeType(Enums.LoginSignMeType.DefaultOn);
- break;
- default:
- case Enums.LoginSignMeTypeAsString.Unused:
- this.signMeType(Enums.LoginSignMeType.Unused);
- break;
- }
-
- this.email(RL.data().devEmail);
- this.password(RL.data().devPassword);
-
- if (this.googleLoginEnabled())
- {
- window['rl_' + sJsHash + '_google_login_service'] = fSocial;
- }
-
- if (this.facebookLoginEnabled())
- {
- window['rl_' + sJsHash + '_facebook_login_service'] = fSocial;
- }
-
- if (this.twitterLoginEnabled())
- {
- window['rl_' + sJsHash + '_twitter_login_service'] = fSocial;
- }
-
- _.delay(function () {
- RL.data().language.subscribe(function (sValue) {
- self.langRequest(true);
- $.ajax({
- 'url': RL.link().langLink(sValue),
- 'dataType': 'script',
- 'cache': true
- }).done(function() {
- self.bSendLanguage = true;
- Utils.i18nToDoc();
- $.cookie('rllang', RL.data().language(), {'expires': 30});
- }).always(function() {
- self.langRequest(false);
- });
+ }, function () {
+ return !this.submitRequest();
});
- }, 50);
- Utils.triggerAutocompleteInputChange(true);
+ this.facebookLoginEnabled = ko.observable(false);
-};
+ this.facebookCommand = Utils.createCommand(this, function () {
-LoginViewModel.prototype.submitForm = function ()
-{
- this.submitCommand();
-};
+ window.open(LinkBuilder.socialFacebook(), 'Facebook',
+ 'left=200,top=100,width=650,height=335,menubar=no,status=no,resizable=yes,scrollbars=yes');
+ return true;
-LoginViewModel.prototype.selectLanguage = function ()
-{
- kn.showScreenPopup(PopupsLanguagesViewModel);
-};
+ }, function () {
+ return !this.submitRequest() && this.facebookLoginEnabled();
+ });
-
+ this.googleLoginEnabled = ko.observable(false);
+
+ this.googleCommand = Utils.createCommand(this, function () {
+
+ window.open(LinkBuilder.socialGoogle(), 'Google',
+ 'left=200,top=100,width=650,height=335,menubar=no,status=no,resizable=yes,scrollbars=yes');
+ return true;
+
+ }, function () {
+ return !this.submitRequest() && this.googleLoginEnabled();
+ });
+
+ this.twitterLoginEnabled = ko.observable(false);
+
+ this.twitterCommand = Utils.createCommand(this, function () {
+
+ window.open(LinkBuilder.socialTwitter(), 'Twitter',
+ 'left=200,top=100,width=650,height=335,menubar=no,status=no,resizable=yes,scrollbars=yes');
+ return true;
+
+ }, function () {
+ return !this.submitRequest() && this.twitterLoginEnabled();
+ });
+
+ this.socialLoginEnabled = ko.computed(function () {
+
+ var
+ bF = this.facebookLoginEnabled(),
+ bG = this.googleLoginEnabled(),
+ bT = this.twitterLoginEnabled()
+ ;
+
+ return bF || bG || bT;
+ }, this);
+
+ kn.constructorEnd(this);
+ }
+
+ kn.extendAsViewModel('LoginViewModel', LoginViewModel);
+
+ LoginViewModel.prototype.onShow = function ()
+ {
+ kn.routeOff();
+
+ _.delay(_.bind(function () {
+ if ('' !== this.email() && '' !== this.password())
+ {
+ this.submitFocus(true);
+ }
+ else
+ {
+ this.emailFocus(true);
+ }
+
+ if (AppSettings.settingsGet('UserLanguage'))
+ {
+ $.cookie('rllang', Data.language(), {'expires': 30});
+ }
+
+ }, this), 100);
+ };
+
+ LoginViewModel.prototype.onHide = function ()
+ {
+ this.submitFocus(false);
+ this.emailFocus(false);
+ };
+
+ LoginViewModel.prototype.onBuild = function ()
+ {
+ var
+ self = this,
+ sJsHash = AppSettings.settingsGet('JsHash'),
+ fSocial = function (iErrorCode) {
+ iErrorCode = Utils.pInt(iErrorCode);
+ if (0 === iErrorCode)
+ {
+ self.submitRequest(true);
+ RL.loginAndLogoutReload();
+ }
+ else
+ {
+ self.submitError(Utils.getNotification(iErrorCode));
+ }
+ }
+ ;
+
+ this.facebookLoginEnabled(!!AppSettings.settingsGet('AllowFacebookSocial'));
+ this.twitterLoginEnabled(!!AppSettings.settingsGet('AllowTwitterSocial'));
+ this.googleLoginEnabled(!!AppSettings.settingsGet('AllowGoogleSocial'));
+
+ switch ((AppSettings.settingsGet('SignMe') || 'unused').toLowerCase())
+ {
+ case Enums.LoginSignMeTypeAsString.DefaultOff:
+ this.signMeType(Enums.LoginSignMeType.DefaultOff);
+ break;
+ case Enums.LoginSignMeTypeAsString.DefaultOn:
+ this.signMeType(Enums.LoginSignMeType.DefaultOn);
+ break;
+ default:
+ case Enums.LoginSignMeTypeAsString.Unused:
+ this.signMeType(Enums.LoginSignMeType.Unused);
+ break;
+ }
+
+ this.email(Data.devEmail);
+ this.password(Data.devPassword);
+
+ if (this.googleLoginEnabled())
+ {
+ window['rl_' + sJsHash + '_google_login_service'] = fSocial;
+ }
+
+ if (this.facebookLoginEnabled())
+ {
+ window['rl_' + sJsHash + '_facebook_login_service'] = fSocial;
+ }
+
+ if (this.twitterLoginEnabled())
+ {
+ window['rl_' + sJsHash + '_twitter_login_service'] = fSocial;
+ }
+
+ _.delay(function () {
+ Data.language.subscribe(function (sValue) {
+ self.langRequest(true);
+ $.ajax({
+ 'url': LinkBuilder.langLink(sValue),
+ 'dataType': 'script',
+ 'cache': true
+ }).done(function() {
+ self.bSendLanguage = true;
+ Utils.i18nReload();
+ $.cookie('rllang', Data.language(), {'expires': 30});
+ }).always(function() {
+ self.langRequest(false);
+ });
+ });
+ }, 50);
+
+ Utils.triggerAutocompleteInputChange(true);
+ };
+
+ LoginViewModel.prototype.submitForm = function ()
+ {
+ this.submitCommand();
+ };
+
+ LoginViewModel.prototype.selectLanguage = function ()
+ {
+ kn.showScreenPopup(PopupsLanguagesViewModel);
+ };
+
+ module.exports = LoginViewModel;
+
+}(module));
+},{"../Boots/RainLoopApp.js":4,"../Common/Enums.js":7,"../Common/LinkBuilder.js":10,"../Common/Utils.js":14,"../External/jquery.js":26,"../External/ko.js":28,"../External/underscore.js":31,"../External/window.js":32,"../Knoin/Knoin.js":33,"../Knoin/KnoinAbstractViewModel.js":36,"../Storages/AppSettings.js":61,"../Storages/WebMailAjaxRemoteStorage.js":65,"../Storages/WebMailDataStorage.js":67,"../ViewModels/Popups/PopupsLanguagesViewModel.js":86}],70:[function(require,module,exports){
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-/**
- * @constructor
- * @extends KnoinAbstractViewModel
- */
-function AbstractSystemDropDownViewModel()
-{
- KnoinAbstractViewModel.call(this, 'Right', 'SystemDropDown');
+(function (module) {
- var oData = RL.data();
+ 'use strict';
- this.accounts = oData.accounts;
- this.accountEmail = oData.accountEmail;
- this.accountsLoading = oData.accountsLoading;
+ var
+ window = require('../External/window.js'),
+ $ = require('../External/jquery.js'),
+ ko = require('../External/ko.js'),
+ key = require('../External/key.js'),
+ $html = require('../External/$html.js'),
+
+ Utils = require('../Common/Utils.js'),
+ Enums = require('../Common/Enums.js'),
+ Globals = require('../Common/Globals.js'),
+ LinkBuilder = require('../Common/LinkBuilder.js'),
- this.accountMenuDropdownTrigger = ko.observable(false);
+ AppSettings = require('../Storages/AppSettings.js'),
+ Cache = require('../Storages/WebMailCacheStorage.js'),
+ Data = require('../Storages/WebMailDataStorage.js'),
- this.capaAdditionalAccounts = RL.capa(Enums.Capa.AdditionalAccounts);
+ RL = require('../Boots/RainLoopApp.js'),
- this.loading = ko.computed(function () {
- return this.accountsLoading();
- }, this);
+ PopupsComposeViewModel = require('./Popups/PopupsComposeViewModel.js'),
+ PopupsFolderCreateViewModel = require('./Popups/PopupsFolderCreateViewModel.js'),
+ PopupsContactsViewModel = require('./Popups/PopupsContactsViewModel.js'),
- this.accountClick = _.bind(this.accountClick, this);
-}
+ kn = require('../Knoin/Knoin.js'),
+ KnoinAbstractViewModel = require('../Knoin/KnoinAbstractViewModel.js')
+ ;
-_.extend(AbstractSystemDropDownViewModel.prototype, KnoinAbstractViewModel.prototype);
-
-AbstractSystemDropDownViewModel.prototype.accountClick = function (oAccount, oEvent)
-{
- if (oAccount && oEvent && !Utils.isUnd(oEvent.which) && 1 === oEvent.which)
+ /**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+ function MailBoxFolderListViewModel()
{
+ KnoinAbstractViewModel.call(this, 'Left', 'MailFolderList');
+
+ this.oContentVisible = null;
+ this.oContentScrollable = null;
+
+ this.messageList = Data.messageList;
+ this.folderList = Data.folderList;
+ this.folderListSystem = Data.folderListSystem;
+ this.foldersChanging = Data.foldersChanging;
+
+ this.leftPanelDisabled = Globals.leftPanelDisabled;
+
+ this.iDropOverTimer = 0;
+
+ this.allowContacts = !!AppSettings.settingsGet('ContactsIsAllowed');
+
+ kn.constructorEnd(this);
+ }
+
+ kn.extendAsViewModel('MailBoxFolderListViewModel', MailBoxFolderListViewModel);
+
+ MailBoxFolderListViewModel.prototype.onBuild = function (oDom)
+ {
+ this.oContentVisible = $('.b-content', oDom);
+ this.oContentScrollable = $('.content', this.oContentVisible);
+
var self = this;
- this.accountsLoading(true);
- _.delay(function () {
- self.accountsLoading(false);
- }, 1000);
- }
- return true;
-};
+ oDom
+ .on('click', '.b-folders .e-item .e-link .e-collapsed-sign', function (oEvent) {
-AbstractSystemDropDownViewModel.prototype.emailTitle = function ()
-{
- return RL.data().accountEmail();
-};
+ var
+ oFolder = ko.dataFor(this),
+ bCollapsed = false
+ ;
-AbstractSystemDropDownViewModel.prototype.settingsClick = function ()
-{
- kn.setHash(RL.link().settings());
-};
+ if (oFolder && oEvent)
+ {
+ bCollapsed = oFolder.collapsed();
+ RL.setExpandedFolder(oFolder.fullNameHash, bCollapsed);
-AbstractSystemDropDownViewModel.prototype.settingsHelp = function ()
-{
- kn.showScreenPopup(PopupsKeyboardShortcutsHelpViewModel);
-};
+ oFolder.collapsed(!bCollapsed);
+ oEvent.preventDefault();
+ oEvent.stopPropagation();
+ }
+ })
+ .on('click', '.b-folders .e-item .e-link.selectable', function (oEvent) {
-AbstractSystemDropDownViewModel.prototype.addAccountClick = function ()
-{
- if (this.capaAdditionalAccounts)
+ oEvent.preventDefault();
+
+ var
+ oFolder = ko.dataFor(this)
+ ;
+
+ if (oFolder)
+ {
+ if (Enums.Layout.NoPreview === Data.layout())
+ {
+ Data.message(null);
+ }
+
+ if (oFolder.fullNameRaw === Data.currentFolderFullNameRaw())
+ {
+ Cache.setFolderHash(oFolder.fullNameRaw, '');
+ }
+
+ kn.setHash(LinkBuilder.mailBox(oFolder.fullNameHash));
+ }
+ })
+ ;
+
+ key('up, down', Enums.KeyState.FolderList, function (event, handler) {
+
+ var
+ iIndex = -1,
+ iKeyCode = handler && 'up' === handler.shortcut ? 38 : 40,
+ $items = $('.b-folders .e-item .e-link:not(.hidden):visible', oDom)
+ ;
+
+ if (event && $items.length)
+ {
+ iIndex = $items.index($items.filter('.focused'));
+ if (-1 < iIndex)
+ {
+ $items.eq(iIndex).removeClass('focused');
+ }
+
+ if (iKeyCode === 38 && iIndex > 0)
+ {
+ iIndex--;
+ }
+ else if (iKeyCode === 40 && iIndex < $items.length - 1)
+ {
+ iIndex++;
+ }
+
+ $items.eq(iIndex).addClass('focused');
+ self.scrollToFocused();
+ }
+
+ return false;
+ });
+
+ key('enter', Enums.KeyState.FolderList, function () {
+ var $items = $('.b-folders .e-item .e-link:not(.hidden).focused', oDom);
+ if ($items.length && $items[0])
+ {
+ self.folderList.focused(false);
+ $items.click();
+ }
+
+ return false;
+ });
+
+ key('space', Enums.KeyState.FolderList, function () {
+ var bCollapsed = true, oFolder = null, $items = $('.b-folders .e-item .e-link:not(.hidden).focused', oDom);
+ if ($items.length && $items[0])
+ {
+ oFolder = ko.dataFor($items[0]);
+ if (oFolder)
+ {
+ bCollapsed = oFolder.collapsed();
+ RL.setExpandedFolder(oFolder.fullNameHash, bCollapsed);
+ oFolder.collapsed(!bCollapsed);
+ }
+ }
+
+ return false;
+ });
+
+ key('esc, tab, shift+tab, right', Enums.KeyState.FolderList, function () {
+ self.folderList.focused(false);
+ return false;
+ });
+
+ self.folderList.focused.subscribe(function (bValue) {
+ $('.b-folders .e-item .e-link.focused', oDom).removeClass('focused');
+ if (bValue)
+ {
+ $('.b-folders .e-item .e-link.selected', oDom).addClass('focused');
+ }
+ });
+ };
+
+ MailBoxFolderListViewModel.prototype.messagesDropOver = function (oFolder)
{
- kn.showScreenPopup(PopupsAddAccountViewModel);
- }
-};
-
-AbstractSystemDropDownViewModel.prototype.logoutClick = function ()
-{
- RL.remote().logout(function () {
- if (window.__rlah_clear)
+ window.clearTimeout(this.iDropOverTimer);
+ if (oFolder && oFolder.collapsed())
{
- window.__rlah_clear();
+ this.iDropOverTimer = window.setTimeout(function () {
+ oFolder.collapsed(false);
+ RL.setExpandedFolder(oFolder.fullNameHash, true);
+ Utils.windowResize();
+ }, 500);
}
+ };
- RL.loginAndLogoutReload(true, RL.settingsGet('ParentEmail') && 0 < RL.settingsGet('ParentEmail').length);
- });
-};
+ MailBoxFolderListViewModel.prototype.messagesDropOut = function ()
+ {
+ window.clearTimeout(this.iDropOverTimer);
+ };
-AbstractSystemDropDownViewModel.prototype.onBuild = function ()
-{
- var self = this;
- key('`', [Enums.KeyState.MessageList, Enums.KeyState.MessageView, Enums.KeyState.Settings], function () {
- if (self.viewModelVisibility())
+ MailBoxFolderListViewModel.prototype.scrollToFocused = function ()
+ {
+ if (!this.oContentVisible || !this.oContentScrollable)
{
- self.accountMenuDropdownTrigger(true);
- }
- });
-
- // shortcuts help
- key('shift+/', [Enums.KeyState.MessageList, Enums.KeyState.MessageView, Enums.KeyState.Settings], function () {
- if (self.viewModelVisibility())
- {
- kn.showScreenPopup(PopupsKeyboardShortcutsHelpViewModel);
return false;
}
- });
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-/**
- * @constructor
- * @extends AbstractSystemDropDownViewModel
- */
-function MailBoxSystemDropDownViewModel()
-{
- AbstractSystemDropDownViewModel.call(this);
- Knoin.constructorEnd(this);
-}
+ var
+ iOffset = 20,
+ oFocused = $('.e-item .e-link.focused', this.oContentScrollable),
+ oPos = oFocused.position(),
+ iVisibleHeight = this.oContentVisible.height(),
+ iFocusedHeight = oFocused.outerHeight()
+ ;
-Utils.extendAsViewModel('MailBoxSystemDropDownViewModel', MailBoxSystemDropDownViewModel, AbstractSystemDropDownViewModel);
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+ if (oPos && (oPos.top < 0 || oPos.top + iFocusedHeight > iVisibleHeight))
+ {
+ if (oPos.top < 0)
+ {
+ this.oContentScrollable.scrollTop(this.oContentScrollable.scrollTop() + oPos.top - iOffset);
+ }
+ else
+ {
+ this.oContentScrollable.scrollTop(this.oContentScrollable.scrollTop() + oPos.top - iVisibleHeight + iFocusedHeight + iOffset);
+ }
-/**
- * @constructor
- * @extends AbstractSystemDropDownViewModel
- */
-function SettingsSystemDropDownViewModel()
-{
- AbstractSystemDropDownViewModel.call(this);
- Knoin.constructorEnd(this);
-}
+ return true;
+ }
-Utils.extendAsViewModel('SettingsSystemDropDownViewModel', SettingsSystemDropDownViewModel, AbstractSystemDropDownViewModel);
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends KnoinAbstractViewModel
- */
-function MailBoxFolderListViewModel()
-{
- KnoinAbstractViewModel.call(this, 'Left', 'MailFolderList');
-
- var oData = RL.data();
-
- this.oContentVisible = null;
- this.oContentScrollable = null;
-
- this.messageList = oData.messageList;
- this.folderList = oData.folderList;
- this.folderListSystem = oData.folderListSystem;
- this.foldersChanging = oData.foldersChanging;
-
- this.leftPanelDisabled = oData.leftPanelDisabled;
-
- this.iDropOverTimer = 0;
-
- this.allowContacts = !!RL.settingsGet('ContactsIsAllowed');
-
- Knoin.constructorEnd(this);
-}
-
-Utils.extendAsViewModel('MailBoxFolderListViewModel', MailBoxFolderListViewModel);
-
-MailBoxFolderListViewModel.prototype.onBuild = function (oDom)
-{
- this.oContentVisible = $('.b-content', oDom);
- this.oContentScrollable = $('.content', this.oContentVisible);
-
- var self = this;
-
- oDom
- .on('click', '.b-folders .e-item .e-link .e-collapsed-sign', function (oEvent) {
+ return false;
+ };
+ /**
+ *
+ * @param {FolderModel} oToFolder
+ * @param {{helper:jQuery}} oUi
+ */
+ MailBoxFolderListViewModel.prototype.messagesDrop = function (oToFolder, oUi)
+ {
+ if (oToFolder && oUi && oUi.helper)
+ {
var
- oFolder = ko.dataFor(this),
- bCollapsed = false
+ sFromFolderFullNameRaw = oUi.helper.data('rl-folder'),
+ bCopy = $html.hasClass('rl-ctrl-key-pressed'),
+ aUids = oUi.helper.data('rl-uids')
;
- if (oFolder && oEvent)
+ if (Utils.isNormal(sFromFolderFullNameRaw) && '' !== sFromFolderFullNameRaw && Utils.isArray(aUids))
{
- bCollapsed = oFolder.collapsed();
- Utils.setExpandedFolder(oFolder.fullNameHash, bCollapsed);
-
- oFolder.collapsed(!bCollapsed);
- oEvent.preventDefault();
- oEvent.stopPropagation();
- }
- })
- .on('click', '.b-folders .e-item .e-link.selectable', function (oEvent) {
-
- oEvent.preventDefault();
-
- var
- oData = RL.data(),
- oFolder = ko.dataFor(this)
- ;
-
- if (oFolder)
- {
- if (Enums.Layout.NoPreview === oData.layout())
- {
- oData.message(null);
- }
-
- if (oFolder.fullNameRaw === oData.currentFolderFullNameRaw())
- {
- RL.cache().setFolderHash(oFolder.fullNameRaw, '');
- }
-
- kn.setHash(RL.link().mailBox(oFolder.fullNameHash));
- }
- })
- ;
-
- key('up, down', Enums.KeyState.FolderList, function (event, handler) {
-
- var
- iIndex = -1,
- iKeyCode = handler && 'up' === handler.shortcut ? 38 : 40,
- $items = $('.b-folders .e-item .e-link:not(.hidden):visible', oDom)
- ;
-
- if (event && $items.length)
- {
- iIndex = $items.index($items.filter('.focused'));
- if (-1 < iIndex)
- {
- $items.eq(iIndex).removeClass('focused');
- }
-
- if (iKeyCode === 38 && iIndex > 0)
- {
- iIndex--;
- }
- else if (iKeyCode === 40 && iIndex < $items.length - 1)
- {
- iIndex++;
- }
-
- $items.eq(iIndex).addClass('focused');
- self.scrollToFocused();
- }
-
- return false;
- });
-
- key('enter', Enums.KeyState.FolderList, function () {
- var $items = $('.b-folders .e-item .e-link:not(.hidden).focused', oDom);
- if ($items.length && $items[0])
- {
- self.folderList.focused(false);
- $items.click();
- }
-
- return false;
- });
-
- key('space', Enums.KeyState.FolderList, function () {
- var bCollapsed = true, oFolder = null, $items = $('.b-folders .e-item .e-link:not(.hidden).focused', oDom);
- if ($items.length && $items[0])
- {
- oFolder = ko.dataFor($items[0]);
- if (oFolder)
- {
- bCollapsed = oFolder.collapsed();
- Utils.setExpandedFolder(oFolder.fullNameHash, bCollapsed);
- oFolder.collapsed(!bCollapsed);
+ RL.moveMessagesToFolder(sFromFolderFullNameRaw, aUids, oToFolder.fullNameRaw, bCopy);
}
}
+ };
- return false;
- });
-
- key('esc, tab, shift+tab, right', Enums.KeyState.FolderList, function () {
- self.folderList.focused(false);
- return false;
- });
-
- self.folderList.focused.subscribe(function (bValue) {
- $('.b-folders .e-item .e-link.focused', oDom).removeClass('focused');
- if (bValue)
- {
- $('.b-folders .e-item .e-link.selected', oDom).addClass('focused');
- }
- });
-};
-
-MailBoxFolderListViewModel.prototype.messagesDropOver = function (oFolder)
-{
- window.clearTimeout(this.iDropOverTimer);
- if (oFolder && oFolder.collapsed())
+ MailBoxFolderListViewModel.prototype.composeClick = function ()
{
- this.iDropOverTimer = window.setTimeout(function () {
- oFolder.collapsed(false);
- Utils.setExpandedFolder(oFolder.fullNameHash, true);
- Utils.windowResize();
- }, 500);
- }
-};
+ kn.showScreenPopup(PopupsComposeViewModel);
+ };
-MailBoxFolderListViewModel.prototype.messagesDropOut = function ()
-{
- window.clearTimeout(this.iDropOverTimer);
-};
-
-MailBoxFolderListViewModel.prototype.scrollToFocused = function ()
-{
- if (!this.oContentVisible || !this.oContentScrollable)
+ MailBoxFolderListViewModel.prototype.createFolder = function ()
{
- return false;
- }
+ kn.showScreenPopup(PopupsFolderCreateViewModel);
+ };
- var
- iOffset = 20,
- oFocused = $('.e-item .e-link.focused', this.oContentScrollable),
- oPos = oFocused.position(),
- iVisibleHeight = this.oContentVisible.height(),
- iFocusedHeight = oFocused.outerHeight()
- ;
-
- if (oPos && (oPos.top < 0 || oPos.top + iFocusedHeight > iVisibleHeight))
+ MailBoxFolderListViewModel.prototype.configureFolders = function ()
{
- if (oPos.top < 0)
+ kn.setHash(LinkBuilder.settings('folders'));
+ };
+
+ MailBoxFolderListViewModel.prototype.contactsClick = function ()
+ {
+ if (this.allowContacts)
{
- this.oContentScrollable.scrollTop(this.oContentScrollable.scrollTop() + oPos.top - iOffset);
- }
- else
- {
- this.oContentScrollable.scrollTop(this.oContentScrollable.scrollTop() + oPos.top - iVisibleHeight + iFocusedHeight + iOffset);
+ kn.showScreenPopup(PopupsContactsViewModel);
}
+ };
- return true;
- }
+ module.exports = MailBoxFolderListViewModel;
- return false;
-};
+}(module));
-/**
- *
- * @param {FolderModel} oToFolder
- * @param {{helper:jQuery}} oUi
- */
-MailBoxFolderListViewModel.prototype.messagesDrop = function (oToFolder, oUi)
-{
- if (oToFolder && oUi && oUi.helper)
- {
- var
- sFromFolderFullNameRaw = oUi.helper.data('rl-folder'),
- bCopy = $html.hasClass('rl-ctrl-key-pressed'),
- aUids = oUi.helper.data('rl-uids')
- ;
-
- if (Utils.isNormal(sFromFolderFullNameRaw) && '' !== sFromFolderFullNameRaw && Utils.isArray(aUids))
- {
- RL.moveMessagesToFolder(sFromFolderFullNameRaw, aUids, oToFolder.fullNameRaw, bCopy);
- }
- }
-};
-
-MailBoxFolderListViewModel.prototype.composeClick = function ()
-{
- kn.showScreenPopup(PopupsComposeViewModel);
-};
-
-MailBoxFolderListViewModel.prototype.createFolder = function ()
-{
- kn.showScreenPopup(PopupsFolderCreateViewModel);
-};
-
-MailBoxFolderListViewModel.prototype.configureFolders = function ()
-{
- kn.setHash(RL.link().settings('folders'));
-};
-
-MailBoxFolderListViewModel.prototype.contactsClick = function ()
-{
- if (this.allowContacts)
- {
- kn.showScreenPopup(PopupsContactsViewModel);
- }
-};
-
+},{"../Boots/RainLoopApp.js":4,"../Common/Enums.js":7,"../Common/Globals.js":9,"../Common/LinkBuilder.js":10,"../Common/Utils.js":14,"../External/$html.js":17,"../External/jquery.js":26,"../External/key.js":27,"../External/ko.js":28,"../External/window.js":32,"../Knoin/Knoin.js":33,"../Knoin/KnoinAbstractViewModel.js":36,"../Storages/AppSettings.js":61,"../Storages/WebMailCacheStorage.js":66,"../Storages/WebMailDataStorage.js":67,"./Popups/PopupsComposeViewModel.js":78,"./Popups/PopupsContactsViewModel.js":79,"./Popups/PopupsFolderCreateViewModel.js":81}],71:[function(require,module,exports){
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-/**
- * @constructor
- * @extends KnoinAbstractViewModel
- */
-function MailBoxMessageListViewModel()
-{
- KnoinAbstractViewModel.call(this, 'Right', 'MailMessageList');
+(function (module) {
- this.sLastUid = null;
- this.bPrefetch = false;
- this.emptySubjectValue = '';
-
- this.hideDangerousActions = !!RL.settingsGet('HideDangerousActions');
-
- var oData = RL.data();
-
- this.popupVisibility = RL.popupVisibility;
-
- this.message = oData.message;
- this.messageList = oData.messageList;
- this.folderList = oData.folderList;
- this.currentMessage = oData.currentMessage;
- this.isMessageSelected = oData.isMessageSelected;
- this.messageListSearch = oData.messageListSearch;
- this.messageListError = oData.messageListError;
- this.folderMenuForMove = oData.folderMenuForMove;
-
- this.useCheckboxesInList = oData.useCheckboxesInList;
-
- this.mainMessageListSearch = oData.mainMessageListSearch;
- this.messageListEndFolder = oData.messageListEndFolder;
-
- this.messageListChecked = oData.messageListChecked;
- this.messageListCheckedOrSelected = oData.messageListCheckedOrSelected;
- this.messageListCheckedOrSelectedUidsWithSubMails = oData.messageListCheckedOrSelectedUidsWithSubMails;
- this.messageListCompleteLoadingThrottle = oData.messageListCompleteLoadingThrottle;
-
- Utils.initOnStartOrLangChange(function () {
- this.emptySubjectValue = Utils.i18n('MESSAGE_LIST/EMPTY_SUBJECT_TEXT');
- }, this);
-
- this.userQuota = oData.userQuota;
- this.userUsageSize = oData.userUsageSize;
- this.userUsageProc = oData.userUsageProc;
-
- this.moveDropdownTrigger = ko.observable(false);
- this.moreDropdownTrigger = ko.observable(false);
-
- // append drag and drop
- this.dragOver = ko.observable(false).extend({'throttle': 1});
- this.dragOverEnter = ko.observable(false).extend({'throttle': 1});
- this.dragOverArea = ko.observable(null);
- this.dragOverBodyArea = ko.observable(null);
-
- this.messageListItemTemplate = ko.computed(function () {
- return Enums.Layout.NoPreview !== oData.layout() ?
- 'MailMessageListItem' : 'MailMessageListItemNoPreviewPane';
- });
-
- this.messageListSearchDesc = ko.computed(function () {
- var sValue = oData.messageListEndSearch();
- return '' === sValue ? '' : Utils.i18n('MESSAGE_LIST/SEARCH_RESULT_FOR', {'SEARCH': sValue});
- });
-
- this.messageListPagenator = ko.computed(Utils.computedPagenatorHelper(oData.messageListPage, oData.messageListPageCount));
-
- this.checkAll = ko.computed({
- 'read': function () {
- return 0 < RL.data().messageListChecked().length;
- },
-
- 'write': function (bValue) {
- bValue = !!bValue;
- _.each(RL.data().messageList(), function (oMessage) {
- oMessage.checked(bValue);
- });
- }
- });
-
- this.inputMessageListSearchFocus = ko.observable(false);
-
- this.sLastSearchValue = '';
- this.inputProxyMessageListSearch = ko.computed({
- 'read': this.mainMessageListSearch,
- 'write': function (sValue) {
- this.sLastSearchValue = sValue;
- },
- 'owner': this
- });
-
- this.isIncompleteChecked = ko.computed(function () {
- var
- iM = RL.data().messageList().length,
- iC = RL.data().messageListChecked().length
- ;
- return 0 < iM && 0 < iC && iM > iC;
- }, this);
-
- this.hasMessages = ko.computed(function () {
- return 0 < this.messageList().length;
- }, this);
-
- this.hasCheckedOrSelectedLines = ko.computed(function () {
- return 0 < this.messageListCheckedOrSelected().length;
- }, this);
-
- this.isSpamFolder = ko.computed(function () {
- return oData.spamFolder() === this.messageListEndFolder() &&
- '' !== oData.spamFolder();
- }, this);
-
- this.isSpamDisabled = ko.computed(function () {
- return Consts.Values.UnuseOptionValue === oData.spamFolder();
- }, this);
-
- this.isTrashFolder = ko.computed(function () {
- return oData.trashFolder() === this.messageListEndFolder() &&
- '' !== oData.trashFolder();
- }, this);
-
- this.isDraftFolder = ko.computed(function () {
- return oData.draftFolder() === this.messageListEndFolder() &&
- '' !== oData.draftFolder();
- }, this);
-
- this.isSentFolder = ko.computed(function () {
- return oData.sentFolder() === this.messageListEndFolder() &&
- '' !== oData.sentFolder();
- }, this);
-
- this.isArchiveFolder = ko.computed(function () {
- return oData.archiveFolder() === this.messageListEndFolder() &&
- '' !== oData.archiveFolder();
- }, this);
-
- this.isArchiveDisabled = ko.computed(function () {
- return Consts.Values.UnuseOptionValue === RL.data().archiveFolder();
- }, this);
-
- this.canBeMoved = this.hasCheckedOrSelectedLines;
-
- this.clearCommand = Utils.createCommand(this, function () {
- kn.showScreenPopup(PopupsFolderClearViewModel, [RL.data().currentFolder()]);
- });
-
- this.multyForwardCommand = Utils.createCommand(this, function () {
- kn.showScreenPopup(PopupsComposeViewModel, [Enums.ComposeType.ForwardAsAttachment, RL.data().messageListCheckedOrSelected()]);
- }, this.canBeMoved);
-
- this.deleteWithoutMoveCommand = Utils.createCommand(this, function () {
- RL.deleteMessagesFromFolder(Enums.FolderType.Trash,
- RL.data().currentFolderFullNameRaw(),
- RL.data().messageListCheckedOrSelectedUidsWithSubMails(), false);
- }, this.canBeMoved);
-
- this.deleteCommand = Utils.createCommand(this, function () {
- RL.deleteMessagesFromFolder(Enums.FolderType.Trash,
- RL.data().currentFolderFullNameRaw(),
- RL.data().messageListCheckedOrSelectedUidsWithSubMails(), true);
- }, this.canBeMoved);
-
- this.archiveCommand = Utils.createCommand(this, function () {
- RL.deleteMessagesFromFolder(Enums.FolderType.Archive,
- RL.data().currentFolderFullNameRaw(),
- RL.data().messageListCheckedOrSelectedUidsWithSubMails(), true);
- }, this.canBeMoved);
-
- this.spamCommand = Utils.createCommand(this, function () {
- RL.deleteMessagesFromFolder(Enums.FolderType.Spam,
- RL.data().currentFolderFullNameRaw(),
- RL.data().messageListCheckedOrSelectedUidsWithSubMails(), true);
- }, this.canBeMoved);
-
- this.notSpamCommand = Utils.createCommand(this, function () {
- RL.deleteMessagesFromFolder(Enums.FolderType.NotSpam,
- RL.data().currentFolderFullNameRaw(),
- RL.data().messageListCheckedOrSelectedUidsWithSubMails(), true);
- }, this.canBeMoved);
-
- this.moveCommand = Utils.createCommand(this, Utils.emptyFunction, this.canBeMoved);
-
- this.reloadCommand = Utils.createCommand(this, function () {
- if (!RL.data().messageListCompleteLoadingThrottle())
- {
- RL.reloadMessageList(false, true);
- }
- });
-
- this.quotaTooltip = _.bind(this.quotaTooltip, this);
-
- this.selector = new Selector(this.messageList, this.currentMessage,
- '.messageListItem .actionHandle', '.messageListItem.selected', '.messageListItem .checkboxMessage',
- '.messageListItem.focused');
-
- this.selector.on('onItemSelect', _.bind(function (oMessage) {
- if (oMessage)
- {
- oData.message(oData.staticMessageList.populateByMessageListItem(oMessage));
- this.populateMessageBody(oData.message());
-
- if (Enums.Layout.NoPreview === oData.layout())
- {
- kn.setHash(RL.link().messagePreview(), true);
- oData.message.focused(true);
- }
- }
- else
- {
- oData.message(null);
- }
- }, this));
-
- this.selector.on('onItemGetUid', function (oMessage) {
- return oMessage ? oMessage.generateUid() : '';
- });
-
- oData.messageListEndHash.subscribe(function () {
- this.selector.scrollToTop();
- }, this);
-
- oData.layout.subscribe(function (mValue) {
- this.selector.autoSelect(Enums.Layout.NoPreview !== mValue);
- }, this);
-
- oData.layout.valueHasMutated();
-
- RL
- .sub('mailbox.message-list.selector.go-down', function () {
- this.selector.goDown(true);
- }, this)
- .sub('mailbox.message-list.selector.go-up', function () {
- this.selector.goUp(true);
- }, this)
- ;
-
- Knoin.constructorEnd(this);
-}
-
-Utils.extendAsViewModel('MailBoxMessageListViewModel', MailBoxMessageListViewModel);
-
-/**
- * @type {string}
- */
-MailBoxMessageListViewModel.prototype.emptySubjectValue = '';
-
-MailBoxMessageListViewModel.prototype.searchEnterAction = function ()
-{
- this.mainMessageListSearch(this.sLastSearchValue);
- this.inputMessageListSearchFocus(false);
-};
-
-/**
- * @returns {string}
- */
-MailBoxMessageListViewModel.prototype.printableMessageCountForDeletion = function ()
-{
- var iCnt = this.messageListCheckedOrSelectedUidsWithSubMails().length;
- return 1 < iCnt ? ' (' + (100 > iCnt ? iCnt : '99+') + ')' : '';
-};
-
-MailBoxMessageListViewModel.prototype.cancelSearch = function ()
-{
- this.mainMessageListSearch('');
- this.inputMessageListSearchFocus(false);
-};
-
-/**
- * @param {string} sToFolderFullNameRaw
- * @return {boolean}
- */
-MailBoxMessageListViewModel.prototype.moveSelectedMessagesToFolder = function (sToFolderFullNameRaw, bCopy)
-{
- if (this.canBeMoved())
- {
- RL.moveMessagesToFolder(
- RL.data().currentFolderFullNameRaw(),
- RL.data().messageListCheckedOrSelectedUidsWithSubMails(), sToFolderFullNameRaw, bCopy);
- }
-
- return false;
-};
-
-MailBoxMessageListViewModel.prototype.dragAndDronHelper = function (oMessageListItem)
-{
- if (oMessageListItem)
- {
- oMessageListItem.checked(true);
- }
+ 'use strict';
var
- oEl = Utils.draggeblePlace(),
- aUids = RL.data().messageListCheckedOrSelectedUidsWithSubMails()
+ $ = require('../External/jquery.js'),
+ _ = require('../External/underscore.js'),
+ ko = require('../External/ko.js'),
+ key = require('../External/key.js'),
+ ifvisible = require('../External/ifvisible.js'),
+ Jua = require('../External/Jua.js'),
+
+ Utils = require('../Common/Utils.js'),
+ Enums = require('../Common/Enums.js'),
+ Consts = require('../Common/Consts.js'),
+ Globals = require('../Common/Globals.js'),
+ LinkBuilder = require('../Common/LinkBuilder.js'),
+ Events = require('../Common/Events.js'),
+ Selector = require('../Common/Selector.js'),
+
+ AppSettings = require('../Storages/AppSettings.js'),
+ Cache = require('../Storages/WebMailCacheStorage.js'),
+ Data = require('../Storages/WebMailDataStorage.js'),
+ Remote = require('../Storages/WebMailAjaxRemoteStorage.js'),
+
+ RL = require('../Boots/RainLoopApp.js'),
+
+ kn = require('../Knoin/Knoin.js'),
+ KnoinAbstractViewModel = require('../Knoin/KnoinAbstractViewModel.js'),
+
+ PopupsComposeViewModel = require('./Popups/PopupsComposeViewModel.js')
;
- oEl.data('rl-folder', RL.data().currentFolderFullNameRaw());
- oEl.data('rl-uids', aUids);
- oEl.find('.text').text('' + aUids.length);
+ /**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+ function MailBoxMessageListViewModel()
+ {
+ KnoinAbstractViewModel.call(this, 'Right', 'MailMessageList');
- _.defer(function () {
- var aUids = RL.data().messageListCheckedOrSelectedUidsWithSubMails();
+ this.sLastUid = null;
+ this.bPrefetch = false;
+ this.emptySubjectValue = '';
+ this.hideDangerousActions = !!AppSettings.settingsGet('HideDangerousActions');
+
+ this.popupVisibility = Globals.popupVisibility;
+
+ this.message = Data.message;
+ this.messageList = Data.messageList;
+ this.folderList = Data.folderList;
+ this.currentMessage = Data.currentMessage;
+ this.isMessageSelected = Data.isMessageSelected;
+ this.messageListSearch = Data.messageListSearch;
+ this.messageListError = Data.messageListError;
+ this.folderMenuForMove = Data.folderMenuForMove;
+
+ this.useCheckboxesInList = Data.useCheckboxesInList;
+
+ this.mainMessageListSearch = Data.mainMessageListSearch;
+ this.messageListEndFolder = Data.messageListEndFolder;
+
+ this.messageListChecked = Data.messageListChecked;
+ this.messageListCheckedOrSelected = Data.messageListCheckedOrSelected;
+ this.messageListCheckedOrSelectedUidsWithSubMails = Data.messageListCheckedOrSelectedUidsWithSubMails;
+ this.messageListCompleteLoadingThrottle = Data.messageListCompleteLoadingThrottle;
+
+ Utils.initOnStartOrLangChange(function () {
+ this.emptySubjectValue = Utils.i18n('MESSAGE_LIST/EMPTY_SUBJECT_TEXT');
+ }, this);
+
+ this.userQuota = Data.userQuota;
+ this.userUsageSize = Data.userUsageSize;
+ this.userUsageProc = Data.userUsageProc;
+
+ this.moveDropdownTrigger = ko.observable(false);
+ this.moreDropdownTrigger = ko.observable(false);
+
+ // append drag and drop
+ this.dragOver = ko.observable(false).extend({'throttle': 1});
+ this.dragOverEnter = ko.observable(false).extend({'throttle': 1});
+ this.dragOverArea = ko.observable(null);
+ this.dragOverBodyArea = ko.observable(null);
+
+ this.messageListItemTemplate = ko.computed(function () {
+ return Enums.Layout.NoPreview !== Data.layout() ?
+ 'MailMessageListItem' : 'MailMessageListItemNoPreviewPane';
+ });
+
+ this.messageListSearchDesc = ko.computed(function () {
+ var sValue = Data.messageListEndSearch();
+ return '' === sValue ? '' : Utils.i18n('MESSAGE_LIST/SEARCH_RESULT_FOR', {'SEARCH': sValue});
+ });
+
+ this.messageListPagenator = ko.computed(Utils.computedPagenatorHelper(Data.messageListPage, Data.messageListPageCount));
+
+ this.checkAll = ko.computed({
+ 'read': function () {
+ return 0 < Data.messageListChecked().length;
+ },
+
+ 'write': function (bValue) {
+ bValue = !!bValue;
+ _.each(Data.messageList(), function (oMessage) {
+ oMessage.checked(bValue);
+ });
+ }
+ });
+
+ this.inputMessageListSearchFocus = ko.observable(false);
+
+ this.sLastSearchValue = '';
+ this.inputProxyMessageListSearch = ko.computed({
+ 'read': this.mainMessageListSearch,
+ 'write': function (sValue) {
+ this.sLastSearchValue = sValue;
+ },
+ 'owner': this
+ });
+
+ this.isIncompleteChecked = ko.computed(function () {
+ var
+ iM = Data.messageList().length,
+ iC = Data.messageListChecked().length
+ ;
+ return 0 < iM && 0 < iC && iM > iC;
+ }, this);
+
+ this.hasMessages = ko.computed(function () {
+ return 0 < this.messageList().length;
+ }, this);
+
+ this.hasCheckedOrSelectedLines = ko.computed(function () {
+ return 0 < this.messageListCheckedOrSelected().length;
+ }, this);
+
+ this.isSpamFolder = ko.computed(function () {
+ return Data.spamFolder() === this.messageListEndFolder() &&
+ '' !== Data.spamFolder();
+ }, this);
+
+ this.isSpamDisabled = ko.computed(function () {
+ return Consts.Values.UnuseOptionValue === Data.spamFolder();
+ }, this);
+
+ this.isTrashFolder = ko.computed(function () {
+ return Data.trashFolder() === this.messageListEndFolder() &&
+ '' !== Data.trashFolder();
+ }, this);
+
+ this.isDraftFolder = ko.computed(function () {
+ return Data.draftFolder() === this.messageListEndFolder() &&
+ '' !== Data.draftFolder();
+ }, this);
+
+ this.isSentFolder = ko.computed(function () {
+ return Data.sentFolder() === this.messageListEndFolder() &&
+ '' !== Data.sentFolder();
+ }, this);
+
+ this.isArchiveFolder = ko.computed(function () {
+ return Data.archiveFolder() === this.messageListEndFolder() &&
+ '' !== Data.archiveFolder();
+ }, this);
+
+ this.isArchiveDisabled = ko.computed(function () {
+ return Consts.Values.UnuseOptionValue === Data.archiveFolder();
+ }, this);
+
+ this.canBeMoved = this.hasCheckedOrSelectedLines;
+
+ this.clearCommand = Utils.createCommand(this, function () {
+ kn.showScreenPopup(PopupsFolderClearViewModel, [Data.currentFolder()]);
+ });
+
+ this.multyForwardCommand = Utils.createCommand(this, function () {
+ kn.showScreenPopup(PopupsComposeViewModel, [Enums.ComposeType.ForwardAsAttachment, Data.messageListCheckedOrSelected()]);
+ }, this.canBeMoved);
+
+ this.deleteWithoutMoveCommand = Utils.createCommand(this, function () {
+ RL.deleteMessagesFromFolder(Enums.FolderType.Trash,
+ Data.currentFolderFullNameRaw(),
+ Data.messageListCheckedOrSelectedUidsWithSubMails(), false);
+ }, this.canBeMoved);
+
+ this.deleteCommand = Utils.createCommand(this, function () {
+ RL.deleteMessagesFromFolder(Enums.FolderType.Trash,
+ Data.currentFolderFullNameRaw(),
+ Data.messageListCheckedOrSelectedUidsWithSubMails(), true);
+ }, this.canBeMoved);
+
+ this.archiveCommand = Utils.createCommand(this, function () {
+ RL.deleteMessagesFromFolder(Enums.FolderType.Archive,
+ Data.currentFolderFullNameRaw(),
+ Data.messageListCheckedOrSelectedUidsWithSubMails(), true);
+ }, this.canBeMoved);
+
+ this.spamCommand = Utils.createCommand(this, function () {
+ RL.deleteMessagesFromFolder(Enums.FolderType.Spam,
+ Data.currentFolderFullNameRaw(),
+ Data.messageListCheckedOrSelectedUidsWithSubMails(), true);
+ }, this.canBeMoved);
+
+ this.notSpamCommand = Utils.createCommand(this, function () {
+ RL.deleteMessagesFromFolder(Enums.FolderType.NotSpam,
+ Data.currentFolderFullNameRaw(),
+ Data.messageListCheckedOrSelectedUidsWithSubMails(), true);
+ }, this.canBeMoved);
+
+ this.moveCommand = Utils.createCommand(this, Utils.emptyFunction, this.canBeMoved);
+
+ this.reloadCommand = Utils.createCommand(this, function () {
+ if (!Data.messageListCompleteLoadingThrottle())
+ {
+ RL.reloadMessageList(false, true);
+ }
+ });
+
+ this.quotaTooltip = _.bind(this.quotaTooltip, this);
+
+ this.selector = new Selector(this.messageList, this.currentMessage,
+ '.messageListItem .actionHandle', '.messageListItem.selected', '.messageListItem .checkboxMessage',
+ '.messageListItem.focused');
+
+ this.selector.on('onItemSelect', _.bind(function (oMessage) {
+ if (oMessage)
+ {
+ Data.message(Data.staticMessageList.populateByMessageListItem(oMessage));
+ this.populateMessageBody(Data.message());
+
+ if (Enums.Layout.NoPreview === Data.layout())
+ {
+ kn.setHash(LinkBuilder.messagePreview(), true);
+ Data.message.focused(true);
+ }
+ }
+ else
+ {
+ Data.message(null);
+ }
+ }, this));
+
+ this.selector.on('onItemGetUid', function (oMessage) {
+ return oMessage ? oMessage.generateUid() : '';
+ });
+
+ Data.messageListEndHash.subscribe(function () {
+ this.selector.scrollToTop();
+ }, this);
+
+ Data.layout.subscribe(function (mValue) {
+ this.selector.autoSelect(Enums.Layout.NoPreview !== mValue);
+ }, this);
+
+ Data.layout.valueHasMutated();
+
+ Events
+ .sub('mailbox.message-list.selector.go-down', function () {
+ this.selector.goDown(true);
+ }, this)
+ .sub('mailbox.message-list.selector.go-up', function () {
+ this.selector.goUp(true);
+ }, this)
+ ;
+
+ kn.constructorEnd(this);
+ }
+
+ kn.extendAsViewModel('MailBoxMessageListViewModel', MailBoxMessageListViewModel);
+
+ /**
+ * @type {string}
+ */
+ MailBoxMessageListViewModel.prototype.emptySubjectValue = '';
+
+ MailBoxMessageListViewModel.prototype.searchEnterAction = function ()
+ {
+ this.mainMessageListSearch(this.sLastSearchValue);
+ this.inputMessageListSearchFocus(false);
+ };
+
+ /**
+ * @returns {string}
+ */
+ MailBoxMessageListViewModel.prototype.printableMessageCountForDeletion = function ()
+ {
+ var iCnt = this.messageListCheckedOrSelectedUidsWithSubMails().length;
+ return 1 < iCnt ? ' (' + (100 > iCnt ? iCnt : '99+') + ')' : '';
+ };
+
+ MailBoxMessageListViewModel.prototype.cancelSearch = function ()
+ {
+ this.mainMessageListSearch('');
+ this.inputMessageListSearchFocus(false);
+ };
+
+ /**
+ * @param {string} sToFolderFullNameRaw
+ * @return {boolean}
+ */
+ MailBoxMessageListViewModel.prototype.moveSelectedMessagesToFolder = function (sToFolderFullNameRaw, bCopy)
+ {
+ if (this.canBeMoved())
+ {
+ RL.moveMessagesToFolder(
+ Data.currentFolderFullNameRaw(),
+ Data.messageListCheckedOrSelectedUidsWithSubMails(), sToFolderFullNameRaw, bCopy);
+ }
+
+ return false;
+ };
+
+ MailBoxMessageListViewModel.prototype.dragAndDronHelper = function (oMessageListItem)
+ {
+ if (oMessageListItem)
+ {
+ oMessageListItem.checked(true);
+ }
+
+ var
+ oEl = Utils.draggeblePlace(),
+ aUids = Data.messageListCheckedOrSelectedUidsWithSubMails()
+ ;
+
+ oEl.data('rl-folder', Data.currentFolderFullNameRaw());
oEl.data('rl-uids', aUids);
oEl.find('.text').text('' + aUids.length);
- });
- return oEl;
-};
+ _.defer(function () {
+ var aUids = Data.messageListCheckedOrSelectedUidsWithSubMails();
-/**
- * @param {string} sResult
- * @param {AjaxJsonDefaultResponse} oData
- * @param {boolean} bCached
- */
-MailBoxMessageListViewModel.prototype.onMessageResponse = function (sResult, oData, bCached)
-{
- var oRainLoopData = RL.data();
+ oEl.data('rl-uids', aUids);
+ oEl.find('.text').text('' + aUids.length);
+ });
- oRainLoopData.hideMessageBodies();
- oRainLoopData.messageLoading(false);
+ return oEl;
+ };
- if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ /**
+ * @param {string} sResult
+ * @param {AjaxJsonDefaultResponse} oData
+ * @param {boolean} bCached
+ */
+ MailBoxMessageListViewModel.prototype.onMessageResponse = function (sResult, oData, bCached)
{
- oRainLoopData.setMessage(oData, bCached);
- }
- else if (Enums.StorageResultType.Unload === sResult)
- {
- oRainLoopData.message(null);
- oRainLoopData.messageError('');
- }
- else if (Enums.StorageResultType.Abort !== sResult)
- {
- oRainLoopData.message(null);
- oRainLoopData.messageError((oData && oData.ErrorCode ?
- Utils.getNotification(oData.ErrorCode) :
- Utils.getNotification(Enums.Notification.UnknownError)));
- }
-};
+ Data.hideMessageBodies();
+ Data.messageLoading(false);
-MailBoxMessageListViewModel.prototype.populateMessageBody = function (oMessage)
-{
- if (oMessage)
- {
- if (RL.remote().message(this.onMessageResponse, oMessage.folderFullNameRaw, oMessage.uid))
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
{
- RL.data().messageLoading(true);
+ Data.setMessage(oData, bCached);
}
- else
+ else if (Enums.StorageResultType.Unload === sResult)
{
- Utils.log('Error: Unknown message request: ' + oMessage.folderFullNameRaw + ' ~ ' + oMessage.uid + ' [e-101]');
+ Data.message(null);
+ Data.messageError('');
}
- }
-};
+ else if (Enums.StorageResultType.Abort !== sResult)
+ {
+ Data.message(null);
+ Data.messageError((oData && oData.ErrorCode ?
+ Utils.getNotification(oData.ErrorCode) :
+ Utils.getNotification(Enums.Notification.UnknownError)));
+ }
+ };
-/**
- * @param {string} sFolderFullNameRaw
- * @param {number} iSetAction
- * @param {Array=} aMessages = null
- */
-MailBoxMessageListViewModel.prototype.setAction = function (sFolderFullNameRaw, iSetAction, aMessages)
-{
- var
- aUids = [],
- oFolder = null,
- oCache = RL.cache(),
- iAlreadyUnread = 0
- ;
-
- if (Utils.isUnd(aMessages))
+ MailBoxMessageListViewModel.prototype.populateMessageBody = function (oMessage)
{
- aMessages = RL.data().messageListChecked();
- }
+ if (oMessage)
+ {
+ if (Remote.message(this.onMessageResponse, oMessage.folderFullNameRaw, oMessage.uid))
+ {
+ Data.messageLoading(true);
+ }
+ else
+ {
+ Utils.log('Error: Unknown message request: ' + oMessage.folderFullNameRaw + ' ~ ' + oMessage.uid + ' [e-101]');
+ }
+ }
+ };
- aUids = _.map(aMessages, function (oMessage) {
- return oMessage.uid;
- });
-
- if ('' !== sFolderFullNameRaw && 0 < aUids.length)
+ /**
+ * @param {string} sFolderFullNameRaw
+ * @param {number} iSetAction
+ * @param {Array=} aMessages = null
+ */
+ MailBoxMessageListViewModel.prototype.setAction = function (sFolderFullNameRaw, iSetAction, aMessages)
{
- switch (iSetAction) {
- case Enums.MessageSetAction.SetSeen:
- _.each(aMessages, function (oMessage) {
- if (oMessage.unseen())
- {
- iAlreadyUnread++;
- }
+ var
+ aUids = [],
+ oFolder = null,
+ iAlreadyUnread = 0
+ ;
- oMessage.unseen(false);
- oCache.storeMessageFlagsToCache(oMessage);
- });
-
- oFolder = oCache.getFolderFromCacheList(sFolderFullNameRaw);
- if (oFolder)
- {
- oFolder.messageCountUnread(oFolder.messageCountUnread() - iAlreadyUnread);
- }
-
- RL.remote().messageSetSeen(Utils.emptyFunction, sFolderFullNameRaw, aUids, true);
- break;
- case Enums.MessageSetAction.UnsetSeen:
- _.each(aMessages, function (oMessage) {
- if (oMessage.unseen())
- {
- iAlreadyUnread++;
- }
-
- oMessage.unseen(true);
- oCache.storeMessageFlagsToCache(oMessage);
- });
-
- oFolder = oCache.getFolderFromCacheList(sFolderFullNameRaw);
- if (oFolder)
- {
- oFolder.messageCountUnread(oFolder.messageCountUnread() - iAlreadyUnread + aUids.length);
- }
- RL.remote().messageSetSeen(Utils.emptyFunction, sFolderFullNameRaw, aUids, false);
- break;
- case Enums.MessageSetAction.SetFlag:
- _.each(aMessages, function (oMessage) {
- oMessage.flagged(true);
- oCache.storeMessageFlagsToCache(oMessage);
- });
- RL.remote().messageSetFlagged(Utils.emptyFunction, sFolderFullNameRaw, aUids, true);
- break;
- case Enums.MessageSetAction.UnsetFlag:
- _.each(aMessages, function (oMessage) {
- oMessage.flagged(false);
- oCache.storeMessageFlagsToCache(oMessage);
- });
- RL.remote().messageSetFlagged(Utils.emptyFunction, sFolderFullNameRaw, aUids, false);
- break;
+ if (Utils.isUnd(aMessages))
+ {
+ aMessages = Data.messageListChecked();
}
- RL.reloadFlagsCurrentMessageListAndMessageFromCache();
- }
-};
+ aUids = _.map(aMessages, function (oMessage) {
+ return oMessage.uid;
+ });
-/**
- * @param {string} sFolderFullNameRaw
- * @param {number} iSetAction
- */
-MailBoxMessageListViewModel.prototype.setActionForAll = function (sFolderFullNameRaw, iSetAction)
-{
- var
- oFolder = null,
- aMessages = RL.data().messageList(),
- oCache = RL.cache()
- ;
-
- if ('' !== sFolderFullNameRaw)
- {
- oFolder = oCache.getFolderFromCacheList(sFolderFullNameRaw);
-
- if (oFolder)
+ if ('' !== sFolderFullNameRaw && 0 < aUids.length)
{
switch (iSetAction) {
case Enums.MessageSetAction.SetSeen:
- oFolder = oCache.getFolderFromCacheList(sFolderFullNameRaw);
+ _.each(aMessages, function (oMessage) {
+ if (oMessage.unseen())
+ {
+ iAlreadyUnread++;
+ }
+
+ oMessage.unseen(false);
+ Cache.storeMessageFlagsToCache(oMessage);
+ });
+
+ oFolder = Cache.getFolderFromCacheList(sFolderFullNameRaw);
if (oFolder)
{
- _.each(aMessages, function (oMessage) {
- oMessage.unseen(false);
- });
-
- oFolder.messageCountUnread(0);
- oCache.clearMessageFlagsFromCacheByFolder(sFolderFullNameRaw);
+ oFolder.messageCountUnread(oFolder.messageCountUnread() - iAlreadyUnread);
}
- RL.remote().messageSetSeenToAll(Utils.emptyFunction, sFolderFullNameRaw, true);
+ Remote.messageSetSeen(Utils.emptyFunction, sFolderFullNameRaw, aUids, true);
break;
case Enums.MessageSetAction.UnsetSeen:
- oFolder = oCache.getFolderFromCacheList(sFolderFullNameRaw);
+ _.each(aMessages, function (oMessage) {
+ if (oMessage.unseen())
+ {
+ iAlreadyUnread++;
+ }
+
+ oMessage.unseen(true);
+ Cache.storeMessageFlagsToCache(oMessage);
+ });
+
+ oFolder = Cache.getFolderFromCacheList(sFolderFullNameRaw);
if (oFolder)
{
- _.each(aMessages, function (oMessage) {
- oMessage.unseen(true);
- });
-
- oFolder.messageCountUnread(oFolder.messageCountAll());
- oCache.clearMessageFlagsFromCacheByFolder(sFolderFullNameRaw);
+ oFolder.messageCountUnread(oFolder.messageCountUnread() - iAlreadyUnread + aUids.length);
}
- RL.remote().messageSetSeenToAll(Utils.emptyFunction, sFolderFullNameRaw, false);
+ Remote.messageSetSeen(Utils.emptyFunction, sFolderFullNameRaw, aUids, false);
+ break;
+ case Enums.MessageSetAction.SetFlag:
+ _.each(aMessages, function (oMessage) {
+ oMessage.flagged(true);
+ Cache.storeMessageFlagsToCache(oMessage);
+ });
+ Remote.messageSetFlagged(Utils.emptyFunction, sFolderFullNameRaw, aUids, true);
+ break;
+ case Enums.MessageSetAction.UnsetFlag:
+ _.each(aMessages, function (oMessage) {
+ oMessage.flagged(false);
+ Cache.storeMessageFlagsToCache(oMessage);
+ });
+ Remote.messageSetFlagged(Utils.emptyFunction, sFolderFullNameRaw, aUids, false);
break;
}
RL.reloadFlagsCurrentMessageListAndMessageFromCache();
}
- }
-};
+ };
-MailBoxMessageListViewModel.prototype.listSetSeen = function ()
-{
- this.setAction(RL.data().currentFolderFullNameRaw(), Enums.MessageSetAction.SetSeen, RL.data().messageListCheckedOrSelected());
-};
-
-MailBoxMessageListViewModel.prototype.listSetAllSeen = function ()
-{
- this.setActionForAll(RL.data().currentFolderFullNameRaw(), Enums.MessageSetAction.SetSeen);
-};
-
-MailBoxMessageListViewModel.prototype.listUnsetSeen = function ()
-{
- this.setAction(RL.data().currentFolderFullNameRaw(), Enums.MessageSetAction.UnsetSeen, RL.data().messageListCheckedOrSelected());
-};
-
-MailBoxMessageListViewModel.prototype.listSetFlags = function ()
-{
- this.setAction(RL.data().currentFolderFullNameRaw(), Enums.MessageSetAction.SetFlag, RL.data().messageListCheckedOrSelected());
-};
-
-MailBoxMessageListViewModel.prototype.listUnsetFlags = function ()
-{
- this.setAction(RL.data().currentFolderFullNameRaw(), Enums.MessageSetAction.UnsetFlag, RL.data().messageListCheckedOrSelected());
-};
-
-MailBoxMessageListViewModel.prototype.flagMessages = function (oCurrentMessage)
-{
- var
- aChecked = this.messageListCheckedOrSelected(),
- aCheckedUids = []
- ;
-
- if (oCurrentMessage)
+ /**
+ * @param {string} sFolderFullNameRaw
+ * @param {number} iSetAction
+ */
+ MailBoxMessageListViewModel.prototype.setActionForAll = function (sFolderFullNameRaw, iSetAction)
{
- if (0 < aChecked.length)
- {
- aCheckedUids = _.map(aChecked, function (oMessage) {
- return oMessage.uid;
- });
- }
-
- if (0 < aCheckedUids.length && -1 < Utils.inArray(oCurrentMessage.uid, aCheckedUids))
- {
- this.setAction(oCurrentMessage.folderFullNameRaw, oCurrentMessage.flagged() ?
- Enums.MessageSetAction.UnsetFlag : Enums.MessageSetAction.SetFlag, aChecked);
- }
- else
- {
- this.setAction(oCurrentMessage.folderFullNameRaw, oCurrentMessage.flagged() ?
- Enums.MessageSetAction.UnsetFlag : Enums.MessageSetAction.SetFlag, [oCurrentMessage]);
- }
- }
-};
-
-MailBoxMessageListViewModel.prototype.flagMessagesFast = function (bFlag)
-{
- var
- aChecked = this.messageListCheckedOrSelected(),
- aFlagged = []
- ;
-
- if (0 < aChecked.length)
- {
- aFlagged = _.filter(aChecked, function (oMessage) {
- return oMessage.flagged();
- });
-
- if (Utils.isUnd(bFlag))
- {
- this.setAction(aChecked[0].folderFullNameRaw,
- aChecked.length === aFlagged.length ? Enums.MessageSetAction.UnsetFlag : Enums.MessageSetAction.SetFlag, aChecked);
- }
- else
- {
- this.setAction(aChecked[0].folderFullNameRaw,
- !bFlag ? Enums.MessageSetAction.UnsetFlag : Enums.MessageSetAction.SetFlag, aChecked);
- }
- }
-};
-
-MailBoxMessageListViewModel.prototype.seenMessagesFast = function (bSeen)
-{
- var
- aChecked = this.messageListCheckedOrSelected(),
- aUnseen = []
- ;
-
- if (0 < aChecked.length)
- {
- aUnseen = _.filter(aChecked, function (oMessage) {
- return oMessage.unseen();
- });
-
- if (Utils.isUnd(bSeen))
- {
- this.setAction(aChecked[0].folderFullNameRaw,
- 0 < aUnseen.length ? Enums.MessageSetAction.SetSeen : Enums.MessageSetAction.UnsetSeen, aChecked);
- }
- else
- {
- this.setAction(aChecked[0].folderFullNameRaw,
- bSeen ? Enums.MessageSetAction.SetSeen : Enums.MessageSetAction.UnsetSeen, aChecked);
- }
- }
-};
-
-MailBoxMessageListViewModel.prototype.onBuild = function (oDom)
-{
- var
- self = this,
- oData = RL.data()
- ;
-
- this.oContentVisible = $('.b-content', oDom);
- this.oContentScrollable = $('.content', this.oContentVisible);
-
- this.oContentVisible.on('click', '.fullThreadHandle', function () {
var
- aList = [],
- oMessage = ko.dataFor(this)
+ oFolder = null,
+ aMessages = Data.messageList()
;
- if (oMessage && !oMessage.lastInCollapsedThreadLoading())
+ if ('' !== sFolderFullNameRaw)
{
- RL.data().messageListThreadFolder(oMessage.folderFullNameRaw);
+ oFolder = Cache.getFolderFromCacheList(sFolderFullNameRaw);
- aList = RL.data().messageListThreadUids();
-
- if (oMessage.lastInCollapsedThread())
+ if (oFolder)
{
- aList.push(0 < oMessage.parentUid() ? oMessage.parentUid() : oMessage.uid);
+ switch (iSetAction) {
+ case Enums.MessageSetAction.SetSeen:
+ oFolder = Cache.getFolderFromCacheList(sFolderFullNameRaw);
+ if (oFolder)
+ {
+ _.each(aMessages, function (oMessage) {
+ oMessage.unseen(false);
+ });
+
+ oFolder.messageCountUnread(0);
+ Cache.clearMessageFlagsFromCacheByFolder(sFolderFullNameRaw);
+ }
+
+ Remote.messageSetSeenToAll(Utils.emptyFunction, sFolderFullNameRaw, true);
+ break;
+ case Enums.MessageSetAction.UnsetSeen:
+ oFolder = Cache.getFolderFromCacheList(sFolderFullNameRaw);
+ if (oFolder)
+ {
+ _.each(aMessages, function (oMessage) {
+ oMessage.unseen(true);
+ });
+
+ oFolder.messageCountUnread(oFolder.messageCountAll());
+ Cache.clearMessageFlagsFromCacheByFolder(sFolderFullNameRaw);
+ }
+ Remote.messageSetSeenToAll(Utils.emptyFunction, sFolderFullNameRaw, false);
+ break;
+ }
+
+ RL.reloadFlagsCurrentMessageListAndMessageFromCache();
+ }
+ }
+ };
+
+ MailBoxMessageListViewModel.prototype.listSetSeen = function ()
+ {
+ this.setAction(Data.currentFolderFullNameRaw(), Enums.MessageSetAction.SetSeen, Data.messageListCheckedOrSelected());
+ };
+
+ MailBoxMessageListViewModel.prototype.listSetAllSeen = function ()
+ {
+ this.setActionForAll(Data.currentFolderFullNameRaw(), Enums.MessageSetAction.SetSeen);
+ };
+
+ MailBoxMessageListViewModel.prototype.listUnsetSeen = function ()
+ {
+ this.setAction(Data.currentFolderFullNameRaw(), Enums.MessageSetAction.UnsetSeen, Data.messageListCheckedOrSelected());
+ };
+
+ MailBoxMessageListViewModel.prototype.listSetFlags = function ()
+ {
+ this.setAction(Data.currentFolderFullNameRaw(), Enums.MessageSetAction.SetFlag, Data.messageListCheckedOrSelected());
+ };
+
+ MailBoxMessageListViewModel.prototype.listUnsetFlags = function ()
+ {
+ this.setAction(Data.currentFolderFullNameRaw(), Enums.MessageSetAction.UnsetFlag, Data.messageListCheckedOrSelected());
+ };
+
+ MailBoxMessageListViewModel.prototype.flagMessages = function (oCurrentMessage)
+ {
+ var
+ aChecked = this.messageListCheckedOrSelected(),
+ aCheckedUids = []
+ ;
+
+ if (oCurrentMessage)
+ {
+ if (0 < aChecked.length)
+ {
+ aCheckedUids = _.map(aChecked, function (oMessage) {
+ return oMessage.uid;
+ });
+ }
+
+ if (0 < aCheckedUids.length && -1 < Utils.inArray(oCurrentMessage.uid, aCheckedUids))
+ {
+ this.setAction(oCurrentMessage.folderFullNameRaw, oCurrentMessage.flagged() ?
+ Enums.MessageSetAction.UnsetFlag : Enums.MessageSetAction.SetFlag, aChecked);
}
else
{
- aList = _.without(aList, 0 < oMessage.parentUid() ? oMessage.parentUid() : oMessage.uid);
+ this.setAction(oCurrentMessage.folderFullNameRaw, oCurrentMessage.flagged() ?
+ Enums.MessageSetAction.UnsetFlag : Enums.MessageSetAction.SetFlag, [oCurrentMessage]);
+ }
+ }
+ };
+
+ MailBoxMessageListViewModel.prototype.flagMessagesFast = function (bFlag)
+ {
+ var
+ aChecked = this.messageListCheckedOrSelected(),
+ aFlagged = []
+ ;
+
+ if (0 < aChecked.length)
+ {
+ aFlagged = _.filter(aChecked, function (oMessage) {
+ return oMessage.flagged();
+ });
+
+ if (Utils.isUnd(bFlag))
+ {
+ this.setAction(aChecked[0].folderFullNameRaw,
+ aChecked.length === aFlagged.length ? Enums.MessageSetAction.UnsetFlag : Enums.MessageSetAction.SetFlag, aChecked);
+ }
+ else
+ {
+ this.setAction(aChecked[0].folderFullNameRaw,
+ !bFlag ? Enums.MessageSetAction.UnsetFlag : Enums.MessageSetAction.SetFlag, aChecked);
+ }
+ }
+ };
+
+ MailBoxMessageListViewModel.prototype.seenMessagesFast = function (bSeen)
+ {
+ var
+ aChecked = this.messageListCheckedOrSelected(),
+ aUnseen = []
+ ;
+
+ if (0 < aChecked.length)
+ {
+ aUnseen = _.filter(aChecked, function (oMessage) {
+ return oMessage.unseen();
+ });
+
+ if (Utils.isUnd(bSeen))
+ {
+ this.setAction(aChecked[0].folderFullNameRaw,
+ 0 < aUnseen.length ? Enums.MessageSetAction.SetSeen : Enums.MessageSetAction.UnsetSeen, aChecked);
+ }
+ else
+ {
+ this.setAction(aChecked[0].folderFullNameRaw,
+ bSeen ? Enums.MessageSetAction.SetSeen : Enums.MessageSetAction.UnsetSeen, aChecked);
+ }
+ }
+ };
+
+ MailBoxMessageListViewModel.prototype.onBuild = function (oDom)
+ {
+ var
+ self = this
+ ;
+
+ this.oContentVisible = $('.b-content', oDom);
+ this.oContentScrollable = $('.content', this.oContentVisible);
+
+ this.oContentVisible.on('click', '.fullThreadHandle', function () {
+ var
+ aList = [],
+ oMessage = ko.dataFor(this)
+ ;
+
+ if (oMessage && !oMessage.lastInCollapsedThreadLoading())
+ {
+ Data.messageListThreadFolder(oMessage.folderFullNameRaw);
+
+ aList = Data.messageListThreadUids();
+
+ if (oMessage.lastInCollapsedThread())
+ {
+ aList.push(0 < oMessage.parentUid() ? oMessage.parentUid() : oMessage.uid);
+ }
+ else
+ {
+ aList = _.without(aList, 0 < oMessage.parentUid() ? oMessage.parentUid() : oMessage.uid);
+ }
+
+ Data.messageListThreadUids(_.uniq(aList));
+
+ oMessage.lastInCollapsedThreadLoading(true);
+ oMessage.lastInCollapsedThread(!oMessage.lastInCollapsedThread());
+ RL.reloadMessageList();
}
- RL.data().messageListThreadUids(_.uniq(aList));
+ return false;
+ });
- oMessage.lastInCollapsedThreadLoading(true);
- oMessage.lastInCollapsedThread(!oMessage.lastInCollapsedThread());
- RL.reloadMessageList();
+ this.selector.init(this.oContentVisible, this.oContentScrollable, Enums.KeyState.MessageList);
+
+ oDom
+ .on('click', '.messageList .b-message-list-wrapper', function () {
+ if (self.message.focused())
+ {
+ self.message.focused(false);
+ }
+ })
+ .on('click', '.e-pagenator .e-page', function () {
+ var oPage = ko.dataFor(this);
+ if (oPage)
+ {
+ kn.setHash(LinkBuilder.mailBox(
+ Data.currentFolderFullNameHash(),
+ oPage.value,
+ Data.messageListSearch()
+ ));
+ }
+ })
+ .on('click', '.messageList .checkboxCkeckAll', function () {
+ self.checkAll(!self.checkAll());
+ })
+ .on('click', '.messageList .messageListItem .flagParent', function () {
+ self.flagMessages(ko.dataFor(this));
+ })
+ ;
+
+ this.initUploaderForAppend();
+ this.initShortcuts();
+
+ if (!Globals.bMobileDevice && AppSettings.capa(Enums.Capa.Prefetch) && ifvisible)
+ {
+ ifvisible.setIdleDuration(10);
+
+ ifvisible.idle(function () {
+ self.prefetchNextTick();
+ });
+ }
+ };
+
+ MailBoxMessageListViewModel.prototype.initShortcuts = function ()
+ {
+ var self = this;
+
+ // disable print
+ key('ctrl+p, command+p', Enums.KeyState.MessageList, function () {
+ return false;
+ });
+
+ // archive (zip)
+ key('z', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
+ self.archiveCommand();
+ return false;
+ });
+
+ // delete
+ key('delete, shift+delete, shift+3', Enums.KeyState.MessageList, function (event, handler) {
+ if (event)
+ {
+ if (0 < Data.messageListCheckedOrSelected().length)
+ {
+ if (handler && 'shift+delete' === handler.shortcut)
+ {
+ self.deleteWithoutMoveCommand();
+ }
+ else
+ {
+ self.deleteCommand();
+ }
+ }
+
+ return false;
+ }
+ });
+
+ // check mail
+ key('ctrl+r, command+r', [Enums.KeyState.FolderList, Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
+ self.reloadCommand();
+ return false;
+ });
+
+ // check all
+ key('ctrl+a, command+a', Enums.KeyState.MessageList, function () {
+ self.checkAll(!(self.checkAll() && !self.isIncompleteChecked()));
+ return false;
+ });
+
+ // write/compose (open compose popup)
+ key('w,c', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
+ kn.showScreenPopup(PopupsComposeViewModel);
+ return false;
+ });
+
+ // important - star/flag messages
+ key('i', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
+ self.flagMessagesFast();
+ return false;
+ });
+
+ // move
+ key('m', Enums.KeyState.MessageList, function () {
+ self.moveDropdownTrigger(true);
+ return false;
+ });
+
+ // read
+ key('q', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
+ self.seenMessagesFast(true);
+ return false;
+ });
+
+ // unread
+ key('u', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
+ self.seenMessagesFast(false);
+ return false;
+ });
+
+ key('shift+f', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
+ self.multyForwardCommand();
+ return false;
+ });
+
+ // search input focus
+ key('/', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
+ self.inputMessageListSearchFocus(true);
+ return false;
+ });
+
+ // cancel search
+ key('esc', Enums.KeyState.MessageList, function () {
+ if ('' !== self.messageListSearchDesc())
+ {
+ self.cancelSearch();
+ return false;
+ }
+ });
+
+ // change focused state
+ key('tab, shift+tab, left, right', Enums.KeyState.MessageList, function (event, handler) {
+ if (event && handler && 'shift+tab' === handler.shortcut || 'left' === handler.shortcut)
+ {
+ self.folderList.focused(true);
+ }
+ else if (self.message())
+ {
+ self.message.focused(true);
+ }
+
+ return false;
+ });
+
+ // TODO
+ key('ctrl+left, command+left', Enums.KeyState.MessageView, function () {
+ return false;
+ });
+
+ // TODO
+ key('ctrl+right, command+right', Enums.KeyState.MessageView, function () {
+ return false;
+ });
+ };
+
+ MailBoxMessageListViewModel.prototype.prefetchNextTick = function ()
+ {
+ if (!this.bPrefetch && !ifvisible.now() && this.viewModelVisibility())
+ {
+ var
+ self = this,
+ oMessage = _.find(this.messageList(), function (oMessage) {
+ return oMessage &&
+ !Cache.hasRequestedMessage(oMessage.folderFullNameRaw, oMessage.uid);
+ })
+ ;
+
+ if (oMessage)
+ {
+ this.bPrefetch = true;
+
+ Cache.addRequestedMessage(oMessage.folderFullNameRaw, oMessage.uid);
+
+ Remote.message(function (sResult, oData) {
+
+ var bNext = !!(Enums.StorageResultType.Success === sResult && oData && oData.Result);
+
+ _.delay(function () {
+ self.bPrefetch = false;
+ if (bNext)
+ {
+ self.prefetchNextTick();
+ }
+ }, 1000);
+
+ }, oMessage.folderFullNameRaw, oMessage.uid);
+ }
+ }
+ };
+
+ MailBoxMessageListViewModel.prototype.composeClick = function ()
+ {
+ kn.showScreenPopup(PopupsComposeViewModel);
+ };
+
+ MailBoxMessageListViewModel.prototype.advancedSearchClick = function ()
+ {
+ kn.showScreenPopup(PopupsAdvancedSearchViewModel);
+ };
+
+ MailBoxMessageListViewModel.prototype.quotaTooltip = function ()
+ {
+ return Utils.i18n('MESSAGE_LIST/QUOTA_SIZE', {
+ 'SIZE': Utils.friendlySize(this.userUsageSize()),
+ 'PROC': this.userUsageProc(),
+ 'LIMIT': Utils.friendlySize(this.userQuota())
+ });
+ };
+
+ MailBoxMessageListViewModel.prototype.initUploaderForAppend = function ()
+ {
+ if (!AppSettings.settingsGet('AllowAppendMessage') || !this.dragOverArea())
+ {
+ return false;
}
- return false;
- });
+ var oJua = new Jua({
+ 'action': LinkBuilder.append(),
+ 'name': 'AppendFile',
+ 'queueSize': 1,
+ 'multipleSizeLimit': 1,
+ 'disableFolderDragAndDrop': true,
+ 'hidden': {
+ 'Folder': function () {
+ return Data.currentFolderFullNameRaw();
+ }
+ },
+ 'dragAndDropElement': this.dragOverArea(),
+ 'dragAndDropBodyElement': this.dragOverBodyArea()
+ });
- this.selector.init(this.oContentVisible, this.oContentScrollable, Enums.KeyState.MessageList);
+ oJua
+ .on('onDragEnter', _.bind(function () {
+ this.dragOverEnter(true);
+ }, this))
+ .on('onDragLeave', _.bind(function () {
+ this.dragOverEnter(false);
+ }, this))
+ .on('onBodyDragEnter', _.bind(function () {
+ this.dragOver(true);
+ }, this))
+ .on('onBodyDragLeave', _.bind(function () {
+ this.dragOver(false);
+ }, this))
+ .on('onSelect', _.bind(function (sUid, oData) {
+ if (sUid && oData && 'message/rfc822' === oData['Type'])
+ {
+ Data.messageListLoading(true);
+ return true;
+ }
- oDom
- .on('click', '.messageList .b-message-list-wrapper', function () {
- if (self.message.focused())
- {
- self.message.focused(false);
- }
- })
- .on('click', '.e-pagenator .e-page', function () {
- var oPage = ko.dataFor(this);
- if (oPage)
- {
- kn.setHash(RL.link().mailBox(
- oData.currentFolderFullNameHash(),
- oPage.value,
- oData.messageListSearch()
- ));
- }
- })
- .on('click', '.messageList .checkboxCkeckAll', function () {
- self.checkAll(!self.checkAll());
- })
- .on('click', '.messageList .messageListItem .flagParent', function () {
- self.flagMessages(ko.dataFor(this));
- })
+ return false;
+ }, this))
+ .on('onComplete', _.bind(function () {
+ RL.reloadMessageList(true, true);
+ }, this))
+ ;
+
+ return !!oJua;
+ };
+
+ module.exports = MailBoxMessageListViewModel;
+
+}(module));
+
+},{"../Boots/RainLoopApp.js":4,"../Common/Consts.js":6,"../Common/Enums.js":7,"../Common/Events.js":8,"../Common/Globals.js":9,"../Common/LinkBuilder.js":10,"../Common/Selector.js":13,"../Common/Utils.js":14,"../External/Jua.js":21,"../External/ifvisible.js":25,"../External/jquery.js":26,"../External/key.js":27,"../External/ko.js":28,"../External/underscore.js":31,"../Knoin/Knoin.js":33,"../Knoin/KnoinAbstractViewModel.js":36,"../Storages/AppSettings.js":61,"../Storages/WebMailAjaxRemoteStorage.js":65,"../Storages/WebMailCacheStorage.js":66,"../Storages/WebMailDataStorage.js":67,"./Popups/PopupsComposeViewModel.js":78}],72:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ $ = require('../External/jquery.js'),
+ ko = require('../External/ko.js'),
+ key = require('../External/key.js'),
+ $html = require('../External/$html.js'),
+
+ Consts = require('../Common/Consts.js'),
+ Enums = require('../Common/Enums.js'),
+ Globals = require('../Common/Globals.js'),
+ Utils = require('../Common/Utils.js'),
+ Events = require('../Common/Events.js'),
+
+ Cache = require('../Storages/WebMailCacheStorage.js'),
+ Data = require('../Storages/WebMailDataStorage.js'),
+ Remote = require('../Storages/WebMailAjaxRemoteStorage.js'),
+
+ RL = require('../Boots/RainLoopApp.js'),
+
+ kn = require('../Knoin/Knoin.js'),
+ KnoinAbstractViewModel = require('../Knoin/KnoinAbstractViewModel.js')
;
- this.initUploaderForAppend();
- this.initShortcuts();
-
- if (!Globals.bMobileDevice && RL.capa(Enums.Capa.Prefetch) && ifvisible)
+ /**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+ function MailBoxMessageViewViewModel()
{
- ifvisible.setIdleDuration(10);
+ KnoinAbstractViewModel.call(this, 'Right', 'MailMessageView');
- ifvisible.idle(function () {
- self.prefetchNextTick();
+ var
+ self = this,
+ sLastEmail = '',
+ createCommandHelper = function (sType) {
+ return Utils.createCommand(self, function () {
+ this.replyOrforward(sType);
+ }, self.canBeRepliedOrForwarded);
+ }
+ ;
+
+ this.oMessageScrollerDom = null;
+
+ this.message = Data.message;
+ this.currentMessage = Data.currentMessage;
+ this.messageListChecked = Data.messageListChecked;
+ this.hasCheckedMessages = Data.hasCheckedMessages;
+ this.messageListCheckedOrSelectedUidsWithSubMails = Data.messageListCheckedOrSelectedUidsWithSubMails;
+ this.messageLoading = Data.messageLoading;
+ this.messageLoadingThrottle = Data.messageLoadingThrottle;
+ this.messagesBodiesDom = Data.messagesBodiesDom;
+ this.useThreads = Data.useThreads;
+ this.replySameFolder = Data.replySameFolder;
+ this.layout = Data.layout;
+ this.usePreviewPane = Data.usePreviewPane;
+ this.isMessageSelected = Data.isMessageSelected;
+ this.messageActiveDom = Data.messageActiveDom;
+ this.messageError = Data.messageError;
+
+ this.fullScreenMode = Data.messageFullScreenMode;
+
+ this.showFullInfo = ko.observable(false);
+ this.moreDropdownTrigger = ko.observable(false);
+ this.messageDomFocused = ko.observable(false).extend({'rateLimit': 0});
+
+ this.messageVisibility = ko.computed(function () {
+ return !this.messageLoadingThrottle() && !!this.message();
+ }, this);
+
+ this.message.subscribe(function (oMessage) {
+ if (!oMessage)
+ {
+ this.currentMessage(null);
+ }
+ }, this);
+
+ this.canBeRepliedOrForwarded = this.messageVisibility;
+
+ // commands
+ this.closeMessage = Utils.createCommand(this, function () {
+ Data.message(null);
});
+
+ this.replyCommand = createCommandHelper(Enums.ComposeType.Reply);
+ this.replyAllCommand = createCommandHelper(Enums.ComposeType.ReplyAll);
+ this.forwardCommand = createCommandHelper(Enums.ComposeType.Forward);
+ this.forwardAsAttachmentCommand = createCommandHelper(Enums.ComposeType.ForwardAsAttachment);
+ this.editAsNewCommand = createCommandHelper(Enums.ComposeType.EditAsNew);
+
+ this.messageVisibilityCommand = Utils.createCommand(this, Utils.emptyFunction, this.messageVisibility);
+
+ this.messageEditCommand = Utils.createCommand(this, function () {
+ this.editMessage();
+ }, this.messageVisibility);
+
+ this.deleteCommand = Utils.createCommand(this, function () {
+ if (this.message())
+ {
+ RL.deleteMessagesFromFolder(Enums.FolderType.Trash,
+ this.message().folderFullNameRaw,
+ [this.message().uid], true);
+ }
+ }, this.messageVisibility);
+
+ this.deleteWithoutMoveCommand = Utils.createCommand(this, function () {
+ if (this.message())
+ {
+ RL.deleteMessagesFromFolder(Enums.FolderType.Trash,
+ Data.currentFolderFullNameRaw(),
+ [this.message().uid], false);
+ }
+ }, this.messageVisibility);
+
+ this.archiveCommand = Utils.createCommand(this, function () {
+ if (this.message())
+ {
+ RL.deleteMessagesFromFolder(Enums.FolderType.Archive,
+ this.message().folderFullNameRaw,
+ [this.message().uid], true);
+ }
+ }, this.messageVisibility);
+
+ this.spamCommand = Utils.createCommand(this, function () {
+ if (this.message())
+ {
+ RL.deleteMessagesFromFolder(Enums.FolderType.Spam,
+ this.message().folderFullNameRaw,
+ [this.message().uid], true);
+ }
+ }, this.messageVisibility);
+
+ this.notSpamCommand = Utils.createCommand(this, function () {
+ if (this.message())
+ {
+ RL.deleteMessagesFromFolder(Enums.FolderType.NotSpam,
+ this.message().folderFullNameRaw,
+ [this.message().uid], true);
+ }
+ }, this.messageVisibility);
+
+ // viewer
+ this.viewHash = '';
+ this.viewSubject = ko.observable('');
+ this.viewFromShort = ko.observable('');
+ this.viewToShort = ko.observable('');
+ this.viewFrom = ko.observable('');
+ this.viewTo = ko.observable('');
+ this.viewCc = ko.observable('');
+ this.viewBcc = ko.observable('');
+ this.viewDate = ko.observable('');
+ this.viewMoment = ko.observable('');
+ this.viewLineAsCcc = ko.observable('');
+ this.viewViewLink = ko.observable('');
+ this.viewDownloadLink = ko.observable('');
+ this.viewUserPic = ko.observable(Consts.DataImages.UserDotPic);
+ this.viewUserPicVisible = ko.observable(false);
+
+ this.viewPgpPassword = ko.observable('');
+ this.viewPgpSignedVerifyStatus = ko.computed(function () {
+ return this.message() ? this.message().pgpSignedVerifyStatus() : Enums.SignedVerifyStatus.None;
+ }, this);
+
+ this.viewPgpSignedVerifyUser = ko.computed(function () {
+ return this.message() ? this.message().pgpSignedVerifyUser() : '';
+ }, this);
+
+ this.message.subscribe(function (oMessage) {
+
+ this.messageActiveDom(null);
+
+ this.viewPgpPassword('');
+
+ if (oMessage)
+ {
+ if (this.viewHash !== oMessage.hash)
+ {
+ this.scrollMessageToTop();
+ }
+
+ this.viewHash = oMessage.hash;
+ this.viewSubject(oMessage.subject());
+ this.viewFromShort(oMessage.fromToLine(true, true));
+ this.viewToShort(oMessage.toToLine(true, true));
+ this.viewFrom(oMessage.fromToLine(false));
+ this.viewTo(oMessage.toToLine(false));
+ this.viewCc(oMessage.ccToLine(false));
+ this.viewBcc(oMessage.bccToLine(false));
+ this.viewDate(oMessage.fullFormatDateValue());
+ this.viewMoment(oMessage.momentDate());
+ this.viewLineAsCcc(oMessage.lineAsCcc());
+ this.viewViewLink(oMessage.viewLink());
+ this.viewDownloadLink(oMessage.downloadLink());
+
+ sLastEmail = oMessage.fromAsSingleEmail();
+ Cache.getUserPic(sLastEmail, function (sPic, $sEmail) {
+ if (sPic !== self.viewUserPic() && sLastEmail === $sEmail)
+ {
+ self.viewUserPicVisible(false);
+ self.viewUserPic(Consts.DataImages.UserDotPic);
+ if ('' !== sPic)
+ {
+ self.viewUserPicVisible(true);
+ self.viewUserPic(sPic);
+ }
+ }
+ });
+ }
+ else
+ {
+ this.viewHash = '';
+ this.scrollMessageToTop();
+ }
+
+ }, this);
+
+ this.fullScreenMode.subscribe(function (bValue) {
+ if (bValue)
+ {
+ $html.addClass('rl-message-fullscreen');
+ }
+ else
+ {
+ $html.removeClass('rl-message-fullscreen');
+ }
+
+ Utils.windowResize();
+ });
+
+ this.messageLoadingThrottle.subscribe(function (bV) {
+ if (bV)
+ {
+ Utils.windowResize();
+ }
+ });
+
+ this.goUpCommand = Utils.createCommand(this, function () {
+ Events.pub('mailbox.message-list.selector.go-up');
+ });
+
+ this.goDownCommand = Utils.createCommand(this, function () {
+ Events.pub('mailbox.message-list.selector.go-down');
+ });
+
+ kn.constructorEnd(this);
}
-};
-MailBoxMessageListViewModel.prototype.initShortcuts = function ()
-{
- var self = this;
+ kn.extendAsViewModel('MailBoxMessageViewViewModel', MailBoxMessageViewViewModel);
- // disable print
- key('ctrl+p, command+p', Enums.KeyState.MessageList, function () {
- return false;
- });
+ MailBoxMessageViewViewModel.prototype.isPgpActionVisible = function ()
+ {
+ return Enums.SignedVerifyStatus.Success !== this.viewPgpSignedVerifyStatus();
+ };
- // archive (zip)
- key('z', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
- self.archiveCommand();
- return false;
- });
+ MailBoxMessageViewViewModel.prototype.isPgpStatusVerifyVisible = function ()
+ {
+ return Enums.SignedVerifyStatus.None !== this.viewPgpSignedVerifyStatus();
+ };
- // delete
- key('delete, shift+delete, shift+3', Enums.KeyState.MessageList, function (event, handler) {
- if (event)
+ MailBoxMessageViewViewModel.prototype.isPgpStatusVerifySuccess = function ()
+ {
+ return Enums.SignedVerifyStatus.Success === this.viewPgpSignedVerifyStatus();
+ };
+
+ MailBoxMessageViewViewModel.prototype.pgpStatusVerifyMessage = function ()
+ {
+ var sResult = '';
+ switch (this.viewPgpSignedVerifyStatus())
{
- if (0 < RL.data().messageListCheckedOrSelected().length)
+ case Enums.SignedVerifyStatus.UnknownPublicKeys:
+ sResult = Utils.i18n('PGP_NOTIFICATIONS/NO_PUBLIC_KEYS_FOUND');
+ break;
+ case Enums.SignedVerifyStatus.UnknownPrivateKey:
+ sResult = Utils.i18n('PGP_NOTIFICATIONS/NO_PRIVATE_KEY_FOUND');
+ break;
+ case Enums.SignedVerifyStatus.Unverified:
+ sResult = Utils.i18n('PGP_NOTIFICATIONS/UNVERIFIRED_SIGNATURE');
+ break;
+ case Enums.SignedVerifyStatus.Error:
+ sResult = Utils.i18n('PGP_NOTIFICATIONS/DECRYPTION_ERROR');
+ break;
+ case Enums.SignedVerifyStatus.Success:
+ sResult = Utils.i18n('PGP_NOTIFICATIONS/GOOD_SIGNATURE', {
+ 'USER': this.viewPgpSignedVerifyUser()
+ });
+ break;
+ }
+
+ return sResult;
+ };
+
+ MailBoxMessageViewViewModel.prototype.scrollToTop = function ()
+ {
+ var oCont = $('.messageItem.nano .content', this.viewModelDom);
+ if (oCont && oCont[0])
+ {
+ // oCont.animate({'scrollTop': 0}, 300);
+ oCont.scrollTop(0);
+ }
+ else
+ {
+ // $('.messageItem', this.viewModelDom).animate({'scrollTop': 0}, 300);
+ $('.messageItem', this.viewModelDom).scrollTop(0);
+ }
+
+ Utils.windowResize();
+ };
+
+ MailBoxMessageViewViewModel.prototype.fullScreen = function ()
+ {
+ this.fullScreenMode(true);
+ Utils.windowResize();
+ };
+
+ MailBoxMessageViewViewModel.prototype.unFullScreen = function ()
+ {
+ this.fullScreenMode(false);
+ Utils.windowResize();
+ };
+
+ MailBoxMessageViewViewModel.prototype.toggleFullScreen = function ()
+ {
+ Utils.removeSelection();
+
+ this.fullScreenMode(!this.fullScreenMode());
+ Utils.windowResize();
+ };
+
+ /**
+ * @param {string} sType
+ */
+ MailBoxMessageViewViewModel.prototype.replyOrforward = function (sType)
+ {
+ kn.showScreenPopup(PopupsComposeViewModel, [sType, Data.message()]);
+ };
+
+ MailBoxMessageViewViewModel.prototype.onBuild = function (oDom)
+ {
+ var
+ self = this
+ ;
+
+ this.fullScreenMode.subscribe(function (bValue) {
+ if (bValue)
+ {
+ self.message.focused(true);
+ }
+ }, this);
+
+ $('.attachmentsPlace', oDom).magnificPopup({
+ 'delegate': '.magnificPopupImage:visible',
+ 'type': 'image',
+ 'gallery': {
+ 'enabled': true,
+ 'preload': [1, 1],
+ 'navigateByImgClick': true
+ },
+ 'callbacks': {
+ 'open': function() {
+ Globals.useKeyboardShortcuts(false);
+ },
+ 'close': function() {
+ Globals.useKeyboardShortcuts(true);
+ }
+ },
+ 'mainClass': 'mfp-fade',
+ 'removalDelay': 400
+ });
+
+ oDom
+ .on('click', '.messageView .messageItem .messageItemHeader', function () {
+ if (Globals.useKeyboardShortcuts() && self.message())
+ {
+ self.message.focused(true);
+ }
+ })
+ .on('click', 'a', function (oEvent) {
+ // setup maito protocol
+ return !(!!oEvent && 3 !== oEvent['which'] && RL.mailToHelper($(this).attr('href')));
+ })
+ .on('click', '.attachmentsPlace .attachmentPreview', function (oEvent) {
+ if (oEvent && oEvent.stopPropagation)
+ {
+ oEvent.stopPropagation();
+ }
+ })
+ .on('click', '.attachmentsPlace .attachmentItem', function () {
+
+ var
+ oAttachment = ko.dataFor(this)
+ ;
+
+ if (oAttachment && oAttachment.download)
+ {
+ RL.download(oAttachment.linkDownload());
+ }
+ })
+ ;
+
+ this.message.focused.subscribe(function (bValue) {
+ if (bValue && !Utils.inFocus()) {
+ this.messageDomFocused(true);
+ } else {
+ this.messageDomFocused(false);
+ }
+ }, this);
+
+ this.messageDomFocused.subscribe(function (bValue) {
+ if (!bValue && Enums.KeyState.MessageView === Globals.keyScope())
+ {
+ this.message.focused(false);
+ }
+ }, this);
+
+ Globals.keyScope.subscribe(function (sValue) {
+ if (Enums.KeyState.MessageView === sValue && this.message.focused())
+ {
+ this.messageDomFocused(true);
+ }
+ }, this);
+
+ this.oMessageScrollerDom = oDom.find('.messageItem .content');
+ this.oMessageScrollerDom = this.oMessageScrollerDom && this.oMessageScrollerDom[0] ? this.oMessageScrollerDom : null;
+
+ this.initShortcuts();
+ };
+
+ /**
+ * @return {boolean}
+ */
+ MailBoxMessageViewViewModel.prototype.escShortcuts = function ()
+ {
+ if (this.viewModelVisibility() && this.message())
+ {
+ if (this.fullScreenMode())
+ {
+ this.fullScreenMode(false);
+ }
+ else if (Enums.Layout.NoPreview === Data.layout())
+ {
+ this.message(null);
+ }
+ else
+ {
+ this.message.focused(false);
+ }
+
+ return false;
+ }
+ };
+
+ MailBoxMessageViewViewModel.prototype.initShortcuts = function ()
+ {
+ var
+ self = this
+ ;
+
+ // exit fullscreen, back
+ key('esc', Enums.KeyState.MessageView, _.bind(this.escShortcuts, this));
+
+ // fullscreen
+ key('enter', Enums.KeyState.MessageView, function () {
+ self.toggleFullScreen();
+ return false;
+ });
+
+ key('enter', Enums.KeyState.MessageList, function () {
+ if (Enums.Layout.NoPreview !== Data.layout() && self.message())
+ {
+ self.toggleFullScreen();
+ return false;
+ }
+ });
+
+ // TODO // more toggle
+ // key('', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
+ // self.moreDropdownTrigger(true);
+ // return false;
+ // });
+
+ // reply
+ key('r', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
+ if (Data.message())
+ {
+ self.replyCommand();
+ return false;
+ }
+ });
+
+ // replaAll
+ key('a', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
+ if (Data.message())
+ {
+ self.replyAllCommand();
+ return false;
+ }
+ });
+
+ // forward
+ key('f', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
+ if (Data.message())
+ {
+ self.forwardCommand();
+ return false;
+ }
+ });
+
+ // message information
+ // key('i', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
+ // if (oData.message())
+ // {
+ // self.showFullInfo(!self.showFullInfo());
+ // return false;
+ // }
+ // });
+
+ // toggle message blockquotes
+ key('b', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
+ if (Data.message() && Data.message().body)
+ {
+ Utils.toggleMessageBlockquote(Data.message().body);
+ return false;
+ }
+ });
+
+ key('ctrl+left, command+left, ctrl+up, command+up', Enums.KeyState.MessageView, function () {
+ self.goUpCommand();
+ return false;
+ });
+
+ key('ctrl+right, command+right, ctrl+down, command+down', Enums.KeyState.MessageView, function () {
+ self.goDownCommand();
+ return false;
+ });
+
+ // print
+ key('ctrl+p, command+p', Enums.KeyState.MessageView, function () {
+ if (self.message())
+ {
+ self.message().printMessage();
+ }
+
+ return false;
+ });
+
+ // delete
+ key('delete, shift+delete', Enums.KeyState.MessageView, function (event, handler) {
+ if (event)
{
if (handler && 'shift+delete' === handler.shortcut)
{
@@ -14171,7245 +17835,4392 @@ MailBoxMessageListViewModel.prototype.initShortcuts = function ()
{
self.deleteCommand();
}
+
+ return false;
+ }
+ });
+
+ // change focused state
+ key('tab, shift+tab, left', Enums.KeyState.MessageView, function () {
+ if (!self.fullScreenMode() && self.message() && Enums.Layout.NoPreview !== Data.layout())
+ {
+ self.message.focused(false);
}
return false;
- }
- });
+ });
+ };
- // check mail
- key('ctrl+r, command+r', [Enums.KeyState.FolderList, Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
- self.reloadCommand();
- return false;
- });
+ /**
+ * @return {boolean}
+ */
+ MailBoxMessageViewViewModel.prototype.isDraftFolder = function ()
+ {
+ return Data.message() && Data.draftFolder() === Data.message().folderFullNameRaw;
+ };
- // check all
- key('ctrl+a, command+a', Enums.KeyState.MessageList, function () {
- self.checkAll(!(self.checkAll() && !self.isIncompleteChecked()));
- return false;
- });
+ /**
+ * @return {boolean}
+ */
+ MailBoxMessageViewViewModel.prototype.isSentFolder = function ()
+ {
+ return Data.message() && Data.sentFolder() === Data.message().folderFullNameRaw;
+ };
- // write/compose (open compose popup)
- key('w,c', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
+ /**
+ * @return {boolean}
+ */
+ MailBoxMessageViewViewModel.prototype.isSpamFolder = function ()
+ {
+ return Data.message() && Data.spamFolder() === Data.message().folderFullNameRaw;
+ };
+
+ /**
+ * @return {boolean}
+ */
+ MailBoxMessageViewViewModel.prototype.isSpamDisabled = function ()
+ {
+ return Data.message() && Data.spamFolder() === Consts.Values.UnuseOptionValue;
+ };
+
+ /**
+ * @return {boolean}
+ */
+ MailBoxMessageViewViewModel.prototype.isArchiveFolder = function ()
+ {
+ return Data.message() && Data.archiveFolder() === Data.message().folderFullNameRaw;
+ };
+
+ /**
+ * @return {boolean}
+ */
+ MailBoxMessageViewViewModel.prototype.isArchiveDisabled = function ()
+ {
+ return Data.message() && Data.archiveFolder() === Consts.Values.UnuseOptionValue;
+ };
+
+ /**
+ * @return {boolean}
+ */
+ MailBoxMessageViewViewModel.prototype.isDraftOrSentFolder = function ()
+ {
+ return this.isDraftFolder() || this.isSentFolder();
+ };
+
+ MailBoxMessageViewViewModel.prototype.composeClick = function ()
+ {
kn.showScreenPopup(PopupsComposeViewModel);
- return false;
- });
+ };
- // important - star/flag messages
- key('i', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
- self.flagMessagesFast();
- return false;
- });
-
- // move
- key('m', Enums.KeyState.MessageList, function () {
- self.moveDropdownTrigger(true);
- return false;
- });
-
- // read
- key('q', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
- self.seenMessagesFast(true);
- return false;
- });
-
- // unread
- key('u', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
- self.seenMessagesFast(false);
- return false;
- });
-
- key('shift+f', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
- self.multyForwardCommand();
- return false;
- });
-
- // search input focus
- key('/', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
- self.inputMessageListSearchFocus(true);
- return false;
- });
-
- // cancel search
- key('esc', Enums.KeyState.MessageList, function () {
- if ('' !== self.messageListSearchDesc())
- {
- self.cancelSearch();
- return false;
- }
- });
-
- // change focused state
- key('tab, shift+tab, left, right', Enums.KeyState.MessageList, function (event, handler) {
- if (event && handler && 'shift+tab' === handler.shortcut || 'left' === handler.shortcut)
- {
- self.folderList.focused(true);
- }
- else if (self.message())
- {
- self.message.focused(true);
- }
-
- return false;
- });
-
- // TODO
- key('ctrl+left, command+left', Enums.KeyState.MessageView, function () {
- return false;
- });
-
- // TODO
- key('ctrl+right, command+right', Enums.KeyState.MessageView, function () {
- return false;
- });
-};
-
-MailBoxMessageListViewModel.prototype.prefetchNextTick = function ()
-{
- if (!this.bPrefetch && !ifvisible.now() && this.viewModelVisibility())
+ MailBoxMessageViewViewModel.prototype.editMessage = function ()
{
- var
- self = this,
- oCache = RL.cache(),
- oMessage = _.find(this.messageList(), function (oMessage) {
- return oMessage &&
- !oCache.hasRequestedMessage(oMessage.folderFullNameRaw, oMessage.uid);
- })
- ;
+ if (Data.message())
+ {
+ kn.showScreenPopup(PopupsComposeViewModel, [Enums.ComposeType.Draft, Data.message()]);
+ }
+ };
+ MailBoxMessageViewViewModel.prototype.scrollMessageToTop = function ()
+ {
+ if (this.oMessageScrollerDom)
+ {
+ this.oMessageScrollerDom.scrollTop(0);
+ }
+ };
+
+ /**
+ * @param {MessageModel} oMessage
+ */
+ MailBoxMessageViewViewModel.prototype.showImages = function (oMessage)
+ {
+ if (oMessage && oMessage.showExternalImages)
+ {
+ oMessage.showExternalImages(true);
+ }
+ };
+
+ /**
+ * @returns {string}
+ */
+ MailBoxMessageViewViewModel.prototype.printableCheckedMessageCount = function ()
+ {
+ var iCnt = this.messageListCheckedOrSelectedUidsWithSubMails().length;
+ return 0 < iCnt ? (100 > iCnt ? iCnt : '99+') : '';
+ };
+
+
+ /**
+ * @param {MessageModel} oMessage
+ */
+ MailBoxMessageViewViewModel.prototype.verifyPgpSignedClearMessage = function (oMessage)
+ {
if (oMessage)
{
- this.bPrefetch = true;
-
- RL.cache().addRequestedMessage(oMessage.folderFullNameRaw, oMessage.uid);
-
- RL.remote().message(function (sResult, oData) {
-
- var bNext = !!(Enums.StorageResultType.Success === sResult && oData && oData.Result);
-
- _.delay(function () {
- self.bPrefetch = false;
- if (bNext)
- {
- self.prefetchNextTick();
- }
- }, 1000);
-
- }, oMessage.folderFullNameRaw, oMessage.uid);
+ oMessage.verifyPgpSignedClearMessage();
}
- }
-};
+ };
-MailBoxMessageListViewModel.prototype.composeClick = function ()
-{
- kn.showScreenPopup(PopupsComposeViewModel);
-};
-
-MailBoxMessageListViewModel.prototype.advancedSearchClick = function ()
-{
- kn.showScreenPopup(PopupsAdvancedSearchViewModel);
-};
-
-MailBoxMessageListViewModel.prototype.quotaTooltip = function ()
-{
- return Utils.i18n('MESSAGE_LIST/QUOTA_SIZE', {
- 'SIZE': Utils.friendlySize(this.userUsageSize()),
- 'PROC': this.userUsageProc(),
- 'LIMIT': Utils.friendlySize(this.userQuota())
- });
-};
-
-MailBoxMessageListViewModel.prototype.initUploaderForAppend = function ()
-{
- if (!RL.settingsGet('AllowAppendMessage') || !this.dragOverArea())
+ /**
+ * @param {MessageModel} oMessage
+ */
+ MailBoxMessageViewViewModel.prototype.decryptPgpEncryptedMessage = function (oMessage)
{
- return false;
- }
-
- var oJua = new Jua({
- 'action': RL.link().append(),
- 'name': 'AppendFile',
- 'queueSize': 1,
- 'multipleSizeLimit': 1,
- 'disableFolderDragAndDrop': true,
- 'hidden': {
- 'Folder': function () {
- return RL.data().currentFolderFullNameRaw();
- }
- },
- 'dragAndDropElement': this.dragOverArea(),
- 'dragAndDropBodyElement': this.dragOverBodyArea()
- });
-
- oJua
- .on('onDragEnter', _.bind(function () {
- this.dragOverEnter(true);
- }, this))
- .on('onDragLeave', _.bind(function () {
- this.dragOverEnter(false);
- }, this))
- .on('onBodyDragEnter', _.bind(function () {
- this.dragOver(true);
- }, this))
- .on('onBodyDragLeave', _.bind(function () {
- this.dragOver(false);
- }, this))
- .on('onSelect', _.bind(function (sUid, oData) {
- if (sUid && oData && 'message/rfc822' === oData['Type'])
- {
- RL.data().messageListLoading(true);
- return true;
- }
-
- return false;
- }, this))
- .on('onComplete', _.bind(function () {
- RL.reloadMessageList(true, true);
- }, this))
- ;
-
- return !!oJua;
-};
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends KnoinAbstractViewModel
- */
-function MailBoxMessageViewViewModel()
-{
- KnoinAbstractViewModel.call(this, 'Right', 'MailMessageView');
-
- var
- self = this,
- sLastEmail = '',
- oData = RL.data(),
- createCommandHelper = function (sType) {
- return Utils.createCommand(self, function () {
- this.replyOrforward(sType);
- }, self.canBeRepliedOrForwarded);
- }
- ;
-
- this.oMessageScrollerDom = null;
-
- this.keyScope = oData.keyScope;
- this.message = oData.message;
- this.currentMessage = oData.currentMessage;
- this.messageListChecked = oData.messageListChecked;
- this.hasCheckedMessages = oData.hasCheckedMessages;
- this.messageListCheckedOrSelectedUidsWithSubMails = oData.messageListCheckedOrSelectedUidsWithSubMails;
- this.messageLoading = oData.messageLoading;
- this.messageLoadingThrottle = oData.messageLoadingThrottle;
- this.messagesBodiesDom = oData.messagesBodiesDom;
- this.useThreads = oData.useThreads;
- this.replySameFolder = oData.replySameFolder;
- this.layout = oData.layout;
- this.usePreviewPane = oData.usePreviewPane;
- this.isMessageSelected = oData.isMessageSelected;
- this.messageActiveDom = oData.messageActiveDom;
- this.messageError = oData.messageError;
-
- this.fullScreenMode = oData.messageFullScreenMode;
-
- this.showFullInfo = ko.observable(false);
- this.moreDropdownTrigger = ko.observable(false);
- this.messageDomFocused = ko.observable(false).extend({'rateLimit': 0});
-
- this.messageVisibility = ko.computed(function () {
- return !this.messageLoadingThrottle() && !!this.message();
- }, this);
-
- this.message.subscribe(function (oMessage) {
- if (!oMessage)
- {
- this.currentMessage(null);
- }
- }, this);
-
- this.canBeRepliedOrForwarded = this.messageVisibility;
-
- // commands
- this.closeMessage = Utils.createCommand(this, function () {
- oData.message(null);
- });
-
- this.replyCommand = createCommandHelper(Enums.ComposeType.Reply);
- this.replyAllCommand = createCommandHelper(Enums.ComposeType.ReplyAll);
- this.forwardCommand = createCommandHelper(Enums.ComposeType.Forward);
- this.forwardAsAttachmentCommand = createCommandHelper(Enums.ComposeType.ForwardAsAttachment);
- this.editAsNewCommand = createCommandHelper(Enums.ComposeType.EditAsNew);
-
- this.messageVisibilityCommand = Utils.createCommand(this, Utils.emptyFunction, this.messageVisibility);
-
- this.messageEditCommand = Utils.createCommand(this, function () {
- this.editMessage();
- }, this.messageVisibility);
-
- this.deleteCommand = Utils.createCommand(this, function () {
- if (this.message())
- {
- RL.deleteMessagesFromFolder(Enums.FolderType.Trash,
- this.message().folderFullNameRaw,
- [this.message().uid], true);
- }
- }, this.messageVisibility);
-
- this.deleteWithoutMoveCommand = Utils.createCommand(this, function () {
- if (this.message())
- {
- RL.deleteMessagesFromFolder(Enums.FolderType.Trash,
- RL.data().currentFolderFullNameRaw(),
- [this.message().uid], false);
- }
- }, this.messageVisibility);
-
- this.archiveCommand = Utils.createCommand(this, function () {
- if (this.message())
- {
- RL.deleteMessagesFromFolder(Enums.FolderType.Archive,
- this.message().folderFullNameRaw,
- [this.message().uid], true);
- }
- }, this.messageVisibility);
-
- this.spamCommand = Utils.createCommand(this, function () {
- if (this.message())
- {
- RL.deleteMessagesFromFolder(Enums.FolderType.Spam,
- this.message().folderFullNameRaw,
- [this.message().uid], true);
- }
- }, this.messageVisibility);
-
- this.notSpamCommand = Utils.createCommand(this, function () {
- if (this.message())
- {
- RL.deleteMessagesFromFolder(Enums.FolderType.NotSpam,
- this.message().folderFullNameRaw,
- [this.message().uid], true);
- }
- }, this.messageVisibility);
-
- // viewer
- this.viewHash = '';
- this.viewSubject = ko.observable('');
- this.viewFromShort = ko.observable('');
- this.viewToShort = ko.observable('');
- this.viewFrom = ko.observable('');
- this.viewTo = ko.observable('');
- this.viewCc = ko.observable('');
- this.viewBcc = ko.observable('');
- this.viewDate = ko.observable('');
- this.viewMoment = ko.observable('');
- this.viewLineAsCcc = ko.observable('');
- this.viewViewLink = ko.observable('');
- this.viewDownloadLink = ko.observable('');
- this.viewUserPic = ko.observable(Consts.DataImages.UserDotPic);
- this.viewUserPicVisible = ko.observable(false);
-
- this.viewPgpPassword = ko.observable('');
- this.viewPgpSignedVerifyStatus = ko.computed(function () {
- return this.message() ? this.message().pgpSignedVerifyStatus() : Enums.SignedVerifyStatus.None;
- }, this);
-
- this.viewPgpSignedVerifyUser = ko.computed(function () {
- return this.message() ? this.message().pgpSignedVerifyUser() : '';
- }, this);
-
- this.message.subscribe(function (oMessage) {
-
- this.messageActiveDom(null);
-
- this.viewPgpPassword('');
-
if (oMessage)
{
- if (this.viewHash !== oMessage.hash)
+ oMessage.decryptPgpEncryptedMessage(this.viewPgpPassword());
+ }
+ };
+
+ /**
+ * @param {MessageModel} oMessage
+ */
+ MailBoxMessageViewViewModel.prototype.readReceipt = function (oMessage)
+ {
+ if (oMessage && '' !== oMessage.readReceipt())
+ {
+ Remote.sendReadReceiptMessage(Utils.emptyFunction, oMessage.folderFullNameRaw, oMessage.uid,
+ oMessage.readReceipt(),
+ Utils.i18n('READ_RECEIPT/SUBJECT', {'SUBJECT': oMessage.subject()}),
+ Utils.i18n('READ_RECEIPT/BODY', {'READ-RECEIPT': Data.accountEmail()}));
+
+ oMessage.isReadReceipt(true);
+
+ Cache.storeMessageFlagsToCache(oMessage);
+ RL.reloadFlagsCurrentMessageListAndMessageFromCache();
+ }
+ };
+
+ module.exports = MailBoxMessageViewViewModel;
+
+}(module));
+},{"../Boots/RainLoopApp.js":4,"../Common/Consts.js":6,"../Common/Enums.js":7,"../Common/Events.js":8,"../Common/Globals.js":9,"../Common/Utils.js":14,"../External/$html.js":17,"../External/jquery.js":26,"../External/key.js":27,"../External/ko.js":28,"../Knoin/Knoin.js":33,"../Knoin/KnoinAbstractViewModel.js":36,"../Storages/WebMailAjaxRemoteStorage.js":65,"../Storages/WebMailCacheStorage.js":66,"../Storages/WebMailDataStorage.js":67}],73:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ Utils = require('../Common/Utils.js'),
+ kn = require('../Knoin/Knoin.js'),
+ AbstractSystemDropDownViewModel = require('./AbstractSystemDropDownViewModel.js')
+ ;
+
+ /**
+ * @constructor
+ * @extends AbstractSystemDropDownViewModel
+ */
+ function MailBoxSystemDropDownViewModel()
+ {
+ AbstractSystemDropDownViewModel.call(this);
+ kn.constructorEnd(this);
+ }
+
+ kn.extendAsViewModel('MailBoxSystemDropDownViewModel', MailBoxSystemDropDownViewModel, AbstractSystemDropDownViewModel);
+
+ module.exports = MailBoxSystemDropDownViewModel;
+
+}(module));
+
+},{"../Common/Utils.js":14,"../Knoin/Knoin.js":33,"./AbstractSystemDropDownViewModel.js":68}],74:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ ko = require('../../External/ko.js'),
+
+ Enums = require('../../Common/Enums.js'),
+ Utils = require('../../Common/Utils.js'),
+
+ Remote = require('../../Storages/WebMailAjaxRemoteStorage.js'),
+
+ RL = require('../../Boots/RainLoopApp.js'),
+
+ kn = require('../../Knoin/Knoin.js'),
+ KnoinAbstractViewModel = require('../../Knoin/KnoinAbstractViewModel.js')
+ ;
+
+ /**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+ function PopupsAddAccountViewModel()
+ {
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsAddAccount');
+
+ this.email = ko.observable('');
+ this.password = ko.observable('');
+
+ this.emailError = ko.observable(false);
+ this.passwordError = ko.observable(false);
+
+ this.email.subscribe(function () {
+ this.emailError(false);
+ }, this);
+
+ this.password.subscribe(function () {
+ this.passwordError(false);
+ }, this);
+
+ this.submitRequest = ko.observable(false);
+ this.submitError = ko.observable('');
+
+ this.emailFocus = ko.observable(false);
+
+ this.addAccountCommand = Utils.createCommand(this, function () {
+
+ this.emailError('' === Utils.trim(this.email()));
+ this.passwordError('' === Utils.trim(this.password()));
+
+ if (this.emailError() || this.passwordError())
{
- this.scrollMessageToTop();
+ return false;
}
- this.viewHash = oMessage.hash;
- this.viewSubject(oMessage.subject());
- this.viewFromShort(oMessage.fromToLine(true, true));
- this.viewToShort(oMessage.toToLine(true, true));
- this.viewFrom(oMessage.fromToLine(false));
- this.viewTo(oMessage.toToLine(false));
- this.viewCc(oMessage.ccToLine(false));
- this.viewBcc(oMessage.bccToLine(false));
- this.viewDate(oMessage.fullFormatDateValue());
- this.viewMoment(oMessage.momentDate());
- this.viewLineAsCcc(oMessage.lineAsCcc());
- this.viewViewLink(oMessage.viewLink());
- this.viewDownloadLink(oMessage.downloadLink());
+ this.submitRequest(true);
- sLastEmail = oMessage.fromAsSingleEmail();
- RL.cache().getUserPic(sLastEmail, function (sPic, $sEmail) {
- if (sPic !== self.viewUserPic() && sLastEmail === $sEmail)
+ Remote.accountAdd(_.bind(function (sResult, oData) {
+
+ this.submitRequest(false);
+ if (Enums.StorageResultType.Success === sResult && oData && 'AccountAdd' === oData.Action)
{
- self.viewUserPicVisible(false);
- self.viewUserPic(Consts.DataImages.UserDotPic);
- if ('' !== sPic)
+ if (oData.Result)
{
- self.viewUserPicVisible(true);
- self.viewUserPic(sPic);
+ RL.accountsAndIdentities();
+ this.cancelCommand();
+ }
+ else if (oData.ErrorCode)
+ {
+ this.submitError(Utils.getNotification(oData.ErrorCode));
}
- }
- });
- }
- else
- {
- this.viewHash = '';
- this.scrollMessageToTop();
- }
-
- }, this);
-
- this.fullScreenMode.subscribe(function (bValue) {
- if (bValue)
- {
- $html.addClass('rl-message-fullscreen');
- }
- else
- {
- $html.removeClass('rl-message-fullscreen');
- }
-
- Utils.windowResize();
- });
-
- this.messageLoadingThrottle.subscribe(function (bV) {
- if (bV)
- {
- Utils.windowResize();
- }
- });
-
- this.goUpCommand = Utils.createCommand(this, function () {
- RL.pub('mailbox.message-list.selector.go-up');
- });
-
- this.goDownCommand = Utils.createCommand(this, function () {
- RL.pub('mailbox.message-list.selector.go-down');
- });
-
- Knoin.constructorEnd(this);
-}
-
-Utils.extendAsViewModel('MailBoxMessageViewViewModel', MailBoxMessageViewViewModel);
-
-MailBoxMessageViewViewModel.prototype.isPgpActionVisible = function ()
-{
- return Enums.SignedVerifyStatus.Success !== this.viewPgpSignedVerifyStatus();
-};
-
-MailBoxMessageViewViewModel.prototype.isPgpStatusVerifyVisible = function ()
-{
- return Enums.SignedVerifyStatus.None !== this.viewPgpSignedVerifyStatus();
-};
-
-MailBoxMessageViewViewModel.prototype.isPgpStatusVerifySuccess = function ()
-{
- return Enums.SignedVerifyStatus.Success === this.viewPgpSignedVerifyStatus();
-};
-
-MailBoxMessageViewViewModel.prototype.pgpStatusVerifyMessage = function ()
-{
- var sResult = '';
- switch (this.viewPgpSignedVerifyStatus())
- {
- case Enums.SignedVerifyStatus.UnknownPublicKeys:
- sResult = Utils.i18n('PGP_NOTIFICATIONS/NO_PUBLIC_KEYS_FOUND');
- break;
- case Enums.SignedVerifyStatus.UnknownPrivateKey:
- sResult = Utils.i18n('PGP_NOTIFICATIONS/NO_PRIVATE_KEY_FOUND');
- break;
- case Enums.SignedVerifyStatus.Unverified:
- sResult = Utils.i18n('PGP_NOTIFICATIONS/UNVERIFIRED_SIGNATURE');
- break;
- case Enums.SignedVerifyStatus.Error:
- sResult = Utils.i18n('PGP_NOTIFICATIONS/DECRYPTION_ERROR');
- break;
- case Enums.SignedVerifyStatus.Success:
- sResult = Utils.i18n('PGP_NOTIFICATIONS/GOOD_SIGNATURE', {
- 'USER': this.viewPgpSignedVerifyUser()
- });
- break;
- }
-
- return sResult;
-};
-
-MailBoxMessageViewViewModel.prototype.scrollToTop = function ()
-{
- var oCont = $('.messageItem.nano .content', this.viewModelDom);
- if (oCont && oCont[0])
- {
-// oCont.animate({'scrollTop': 0}, 300);
- oCont.scrollTop(0);
- }
- else
- {
-// $('.messageItem', this.viewModelDom).animate({'scrollTop': 0}, 300);
- $('.messageItem', this.viewModelDom).scrollTop(0);
- }
-
- Utils.windowResize();
-};
-
-MailBoxMessageViewViewModel.prototype.fullScreen = function ()
-{
- this.fullScreenMode(true);
- Utils.windowResize();
-};
-
-MailBoxMessageViewViewModel.prototype.unFullScreen = function ()
-{
- this.fullScreenMode(false);
- Utils.windowResize();
-};
-
-MailBoxMessageViewViewModel.prototype.toggleFullScreen = function ()
-{
- Utils.removeSelection();
-
- this.fullScreenMode(!this.fullScreenMode());
- Utils.windowResize();
-};
-
-/**
- * @param {string} sType
- */
-MailBoxMessageViewViewModel.prototype.replyOrforward = function (sType)
-{
- kn.showScreenPopup(PopupsComposeViewModel, [sType, RL.data().message()]);
-};
-
-MailBoxMessageViewViewModel.prototype.onBuild = function (oDom)
-{
- var
- self = this,
- oData = RL.data()
- ;
-
- this.fullScreenMode.subscribe(function (bValue) {
- if (bValue)
- {
- self.message.focused(true);
- }
- }, this);
-
- $('.attachmentsPlace', oDom).magnificPopup({
- 'delegate': '.magnificPopupImage:visible',
- 'type': 'image',
- 'gallery': {
- 'enabled': true,
- 'preload': [1, 1],
- 'navigateByImgClick': true
- },
- 'callbacks': {
- 'open': function() {
- oData.useKeyboardShortcuts(false);
- },
- 'close': function() {
- oData.useKeyboardShortcuts(true);
- }
- },
- 'mainClass': 'mfp-fade',
- 'removalDelay': 400
- });
-
- oDom
- .on('click', '.messageView .messageItem .messageItemHeader', function () {
- if (oData.useKeyboardShortcuts() && self.message())
- {
- self.message.focused(true);
- }
- })
- .on('click', 'a', function (oEvent) {
- // setup maito protocol
- return !(!!oEvent && 3 !== oEvent['which'] && RL.mailToHelper($(this).attr('href')));
- })
- .on('click', '.attachmentsPlace .attachmentPreview', function (oEvent) {
- if (oEvent && oEvent.stopPropagation)
- {
- oEvent.stopPropagation();
- }
- })
- .on('click', '.attachmentsPlace .attachmentItem', function () {
-
- var
- oAttachment = ko.dataFor(this)
- ;
-
- if (oAttachment && oAttachment.download)
- {
- RL.download(oAttachment.linkDownload());
- }
- })
- ;
-
- this.message.focused.subscribe(function (bValue) {
- if (bValue && !Utils.inFocus()) {
- this.messageDomFocused(true);
- } else {
- this.messageDomFocused(false);
- }
- }, this);
-
- this.messageDomFocused.subscribe(function (bValue) {
- if (!bValue && Enums.KeyState.MessageView === this.keyScope())
- {
- this.message.focused(false);
- }
- }, this);
-
- this.keyScope.subscribe(function (sValue) {
- if (Enums.KeyState.MessageView === sValue && this.message.focused())
- {
- this.messageDomFocused(true);
- }
- }, this);
-
- this.oMessageScrollerDom = oDom.find('.messageItem .content');
- this.oMessageScrollerDom = this.oMessageScrollerDom && this.oMessageScrollerDom[0] ? this.oMessageScrollerDom : null;
-
- this.initShortcuts();
-};
-
-/**
- * @return {boolean}
- */
-MailBoxMessageViewViewModel.prototype.escShortcuts = function ()
-{
- if (this.viewModelVisibility() && this.message())
- {
- if (this.fullScreenMode())
- {
- this.fullScreenMode(false);
- }
- else if (Enums.Layout.NoPreview === RL.data().layout())
- {
- this.message(null);
- }
- else
- {
- this.message.focused(false);
- }
-
- return false;
- }
-};
-
-MailBoxMessageViewViewModel.prototype.initShortcuts = function ()
-{
- var
- self = this,
- oData = RL.data()
- ;
-
- // exit fullscreen, back
- key('esc', Enums.KeyState.MessageView, _.bind(this.escShortcuts, this));
-
- // fullscreen
- key('enter', Enums.KeyState.MessageView, function () {
- self.toggleFullScreen();
- return false;
- });
-
- key('enter', Enums.KeyState.MessageList, function () {
- if (Enums.Layout.NoPreview !== oData.layout() && self.message())
- {
- self.toggleFullScreen();
- return false;
- }
- });
-
- // TODO // more toggle
-// key('', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
-// self.moreDropdownTrigger(true);
-// return false;
-// });
-
- // reply
- key('r', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
- if (oData.message())
- {
- self.replyCommand();
- return false;
- }
- });
-
- // replaAll
- key('a', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
- if (oData.message())
- {
- self.replyAllCommand();
- return false;
- }
- });
-
- // forward
- key('f', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
- if (oData.message())
- {
- self.forwardCommand();
- return false;
- }
- });
-
- // message information
-// key('i', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
-// if (oData.message())
-// {
-// self.showFullInfo(!self.showFullInfo());
-// return false;
-// }
-// });
-
- // toggle message blockquotes
- key('b', [Enums.KeyState.MessageList, Enums.KeyState.MessageView], function () {
- if (oData.message() && oData.message().body)
- {
- Utils.toggleMessageBlockquote(oData.message().body);
- return false;
- }
- });
-
- key('ctrl+left, command+left, ctrl+up, command+up', Enums.KeyState.MessageView, function () {
- self.goUpCommand();
- return false;
- });
-
- key('ctrl+right, command+right, ctrl+down, command+down', Enums.KeyState.MessageView, function () {
- self.goDownCommand();
- return false;
- });
-
- // print
- key('ctrl+p, command+p', Enums.KeyState.MessageView, function () {
- if (self.message())
- {
- self.message().printMessage();
- }
-
- return false;
- });
-
- // delete
- key('delete, shift+delete', Enums.KeyState.MessageView, function (event, handler) {
- if (event)
- {
- if (handler && 'shift+delete' === handler.shortcut)
- {
- self.deleteWithoutMoveCommand();
- }
- else
- {
- self.deleteCommand();
- }
-
- return false;
- }
- });
-
- // change focused state
- key('tab, shift+tab, left', Enums.KeyState.MessageView, function () {
- if (!self.fullScreenMode() && self.message() && Enums.Layout.NoPreview !== oData.layout())
- {
- self.message.focused(false);
- }
-
- return false;
- });
-};
-
-/**
- * @return {boolean}
- */
-MailBoxMessageViewViewModel.prototype.isDraftFolder = function ()
-{
- return RL.data().message() && RL.data().draftFolder() === RL.data().message().folderFullNameRaw;
-};
-
-/**
- * @return {boolean}
- */
-MailBoxMessageViewViewModel.prototype.isSentFolder = function ()
-{
- return RL.data().message() && RL.data().sentFolder() === RL.data().message().folderFullNameRaw;
-};
-
-/**
- * @return {boolean}
- */
-MailBoxMessageViewViewModel.prototype.isSpamFolder = function ()
-{
- return RL.data().message() && RL.data().spamFolder() === RL.data().message().folderFullNameRaw;
-};
-
-/**
- * @return {boolean}
- */
-MailBoxMessageViewViewModel.prototype.isSpamDisabled = function ()
-{
- return RL.data().message() && RL.data().spamFolder() === Consts.Values.UnuseOptionValue;
-};
-
-/**
- * @return {boolean}
- */
-MailBoxMessageViewViewModel.prototype.isArchiveFolder = function ()
-{
- return RL.data().message() && RL.data().archiveFolder() === RL.data().message().folderFullNameRaw;
-};
-
-/**
- * @return {boolean}
- */
-MailBoxMessageViewViewModel.prototype.isArchiveDisabled = function ()
-{
- return RL.data().message() && RL.data().archiveFolder() === Consts.Values.UnuseOptionValue;
-};
-
-/**
- * @return {boolean}
- */
-MailBoxMessageViewViewModel.prototype.isDraftOrSentFolder = function ()
-{
- return this.isDraftFolder() || this.isSentFolder();
-};
-
-MailBoxMessageViewViewModel.prototype.composeClick = function ()
-{
- kn.showScreenPopup(PopupsComposeViewModel);
-};
-
-MailBoxMessageViewViewModel.prototype.editMessage = function ()
-{
- if (RL.data().message())
- {
- kn.showScreenPopup(PopupsComposeViewModel, [Enums.ComposeType.Draft, RL.data().message()]);
- }
-};
-
-MailBoxMessageViewViewModel.prototype.scrollMessageToTop = function ()
-{
- if (this.oMessageScrollerDom)
- {
- this.oMessageScrollerDom.scrollTop(0);
- }
-};
-
-/**
- * @param {MessageModel} oMessage
- */
-MailBoxMessageViewViewModel.prototype.showImages = function (oMessage)
-{
- if (oMessage && oMessage.showExternalImages)
- {
- oMessage.showExternalImages(true);
- }
-};
-
-/**
- * @returns {string}
- */
-MailBoxMessageViewViewModel.prototype.printableCheckedMessageCount = function ()
-{
- var iCnt = this.messageListCheckedOrSelectedUidsWithSubMails().length;
- return 0 < iCnt ? (100 > iCnt ? iCnt : '99+') : '';
-};
-
-
-/**
- * @param {MessageModel} oMessage
- */
-MailBoxMessageViewViewModel.prototype.verifyPgpSignedClearMessage = function (oMessage)
-{
- if (oMessage)
- {
- oMessage.verifyPgpSignedClearMessage();
- }
-};
-
-/**
- * @param {MessageModel} oMessage
- */
-MailBoxMessageViewViewModel.prototype.decryptPgpEncryptedMessage = function (oMessage)
-{
- if (oMessage)
- {
- oMessage.decryptPgpEncryptedMessage(this.viewPgpPassword());
- }
-};
-
-/**
- * @param {MessageModel} oMessage
- */
-MailBoxMessageViewViewModel.prototype.readReceipt = function (oMessage)
-{
- if (oMessage && '' !== oMessage.readReceipt())
- {
- RL.remote().sendReadReceiptMessage(Utils.emptyFunction, oMessage.folderFullNameRaw, oMessage.uid,
- oMessage.readReceipt(),
- Utils.i18n('READ_RECEIPT/SUBJECT', {'SUBJECT': oMessage.subject()}),
- Utils.i18n('READ_RECEIPT/BODY', {'READ-RECEIPT': RL.data().accountEmail()}));
-
- oMessage.isReadReceipt(true);
-
- RL.cache().storeMessageFlagsToCache(oMessage);
- RL.reloadFlagsCurrentMessageListAndMessageFromCache();
- }
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @param {?} oScreen
- *
- * @constructor
- * @extends KnoinAbstractViewModel
- */
-function SettingsMenuViewModel(oScreen)
-{
- KnoinAbstractViewModel.call(this, 'Left', 'SettingsMenu');
-
- this.leftPanelDisabled = RL.data().leftPanelDisabled;
-
- this.menu = oScreen.menu;
-
- Knoin.constructorEnd(this);
-}
-
-Utils.extendAsViewModel('SettingsMenuViewModel', SettingsMenuViewModel);
-
-SettingsMenuViewModel.prototype.link = function (sRoute)
-{
- return RL.link().settings(sRoute);
-};
-
-SettingsMenuViewModel.prototype.backToMailBoxClick = function ()
-{
- kn.setHash(RL.link().inbox());
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends KnoinAbstractViewModel
- */
-function SettingsPaneViewModel()
-{
- KnoinAbstractViewModel.call(this, 'Right', 'SettingsPane');
-
- Knoin.constructorEnd(this);
-}
-
-Utils.extendAsViewModel('SettingsPaneViewModel', SettingsPaneViewModel);
-
-SettingsPaneViewModel.prototype.onBuild = function ()
-{
- var self = this;
- key('esc', Enums.KeyState.Settings, function () {
- self.backToMailBoxClick();
- });
-};
-
-SettingsPaneViewModel.prototype.onShow = function ()
-{
- RL.data().message(null);
-};
-
-SettingsPaneViewModel.prototype.backToMailBoxClick = function ()
-{
- kn.setHash(RL.link().inbox());
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function SettingsGeneral()
-{
- var oData = RL.data();
-
- this.mainLanguage = oData.mainLanguage;
- this.mainMessagesPerPage = oData.mainMessagesPerPage;
- this.mainMessagesPerPageArray = Consts.Defaults.MessagesPerPageArray;
- this.editorDefaultType = oData.editorDefaultType;
- this.showImages = oData.showImages;
- this.interfaceAnimation = oData.interfaceAnimation;
- this.useDesktopNotifications = oData.useDesktopNotifications;
- this.threading = oData.threading;
- this.useThreads = oData.useThreads;
- this.replySameFolder = oData.replySameFolder;
- this.layout = oData.layout;
- this.usePreviewPane = oData.usePreviewPane;
- this.useCheckboxesInList = oData.useCheckboxesInList;
- this.allowLanguagesOnSettings = oData.allowLanguagesOnSettings;
-
- this.isDesktopNotificationsSupported = ko.computed(function () {
- return Enums.DesktopNotifications.NotSupported !== oData.desktopNotificationsPermisions();
- });
-
- this.isDesktopNotificationsDenied = ko.computed(function () {
- return Enums.DesktopNotifications.NotSupported === oData.desktopNotificationsPermisions() ||
- Enums.DesktopNotifications.Denied === oData.desktopNotificationsPermisions();
- });
-
- this.mainLanguageFullName = ko.computed(function () {
- return Utils.convertLangName(this.mainLanguage());
- }, this);
-
- this.languageTrigger = ko.observable(Enums.SaveSettingsStep.Idle).extend({'throttle': 100});
- this.mppTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
-
- this.isAnimationSupported = Globals.bAnimationSupported;
-}
-
-Utils.addSettingsViewModel(SettingsGeneral, 'SettingsGeneral', 'SETTINGS_LABELS/LABEL_GENERAL_NAME', 'general', true);
-
-SettingsGeneral.prototype.toggleLayout = function ()
-{
- this.layout(Enums.Layout.NoPreview === this.layout() ? Enums.Layout.SidePreview : Enums.Layout.NoPreview);
-};
-
-SettingsGeneral.prototype.onBuild = function ()
-{
- var self = this;
-
- _.delay(function () {
-
- var
- oData = RL.data(),
- f1 = Utils.settingsSaveHelperSimpleFunction(self.mppTrigger, self)
- ;
-
- oData.language.subscribe(function (sValue) {
-
- self.languageTrigger(Enums.SaveSettingsStep.Animate);
-
- $.ajax({
- 'url': RL.link().langLink(sValue),
- 'dataType': 'script',
- 'cache': true
- }).done(function() {
- Utils.i18nToDoc();
- self.languageTrigger(Enums.SaveSettingsStep.TrueResult);
- }).fail(function() {
- self.languageTrigger(Enums.SaveSettingsStep.FalseResult);
- }).always(function() {
- _.delay(function () {
- self.languageTrigger(Enums.SaveSettingsStep.Idle);
- }, 1000);
- });
-
- RL.remote().saveSettings(Utils.emptyFunction, {
- 'Language': sValue
- });
- });
-
- oData.editorDefaultType.subscribe(function (sValue) {
- RL.remote().saveSettings(Utils.emptyFunction, {
- 'EditorDefaultType': sValue
- });
- });
-
- oData.messagesPerPage.subscribe(function (iValue) {
- RL.remote().saveSettings(f1, {
- 'MPP': iValue
- });
- });
-
- oData.showImages.subscribe(function (bValue) {
- RL.remote().saveSettings(Utils.emptyFunction, {
- 'ShowImages': bValue ? '1' : '0'
- });
- });
-
- oData.interfaceAnimation.subscribe(function (sValue) {
- RL.remote().saveSettings(Utils.emptyFunction, {
- 'InterfaceAnimation': sValue
- });
- });
-
- oData.useDesktopNotifications.subscribe(function (bValue) {
- Utils.timeOutAction('SaveDesktopNotifications', function () {
- RL.remote().saveSettings(Utils.emptyFunction, {
- 'DesktopNotifications': bValue ? '1' : '0'
- });
- }, 3000);
- });
-
- oData.replySameFolder.subscribe(function (bValue) {
- Utils.timeOutAction('SaveReplySameFolder', function () {
- RL.remote().saveSettings(Utils.emptyFunction, {
- 'ReplySameFolder': bValue ? '1' : '0'
- });
- }, 3000);
- });
-
- oData.useThreads.subscribe(function (bValue) {
-
- oData.messageList([]);
-
- RL.remote().saveSettings(Utils.emptyFunction, {
- 'UseThreads': bValue ? '1' : '0'
- });
- });
-
- oData.layout.subscribe(function (nValue) {
-
- oData.messageList([]);
-
- RL.remote().saveSettings(Utils.emptyFunction, {
- 'Layout': nValue
- });
- });
-
- oData.useCheckboxesInList.subscribe(function (bValue) {
- RL.remote().saveSettings(Utils.emptyFunction, {
- 'UseCheckboxesInList': bValue ? '1' : '0'
- });
- });
-
- }, 50);
-};
-
-SettingsGeneral.prototype.onShow = function ()
-{
- RL.data().desktopNotifications.valueHasMutated();
-};
-
-SettingsGeneral.prototype.selectLanguage = function ()
-{
- kn.showScreenPopup(PopupsLanguagesViewModel);
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function SettingsContacts()
-{
- var oData = RL.data();
-
- this.contactsAutosave = oData.contactsAutosave;
-
- this.allowContactsSync = oData.allowContactsSync;
- this.enableContactsSync = oData.enableContactsSync;
- this.contactsSyncUrl = oData.contactsSyncUrl;
- this.contactsSyncUser = oData.contactsSyncUser;
- this.contactsSyncPass = oData.contactsSyncPass;
-
- this.saveTrigger = ko.computed(function () {
- return [
- this.enableContactsSync() ? '1' : '0',
- this.contactsSyncUrl(),
- this.contactsSyncUser(),
- this.contactsSyncPass()
- ].join('|');
- }, this).extend({'throttle': 500});
-
- this.saveTrigger.subscribe(function () {
- RL.remote().saveContactsSyncData(null,
- this.enableContactsSync(),
- this.contactsSyncUrl(),
- this.contactsSyncUser(),
- this.contactsSyncPass()
- );
- }, this);
-}
-
-Utils.addSettingsViewModel(SettingsContacts, 'SettingsContacts', 'SETTINGS_LABELS/LABEL_CONTACTS_NAME', 'contacts');
-
-SettingsContacts.prototype.onBuild = function ()
-{
- RL.data().contactsAutosave.subscribe(function (bValue) {
- RL.remote().saveSettings(Utils.emptyFunction, {
- 'ContactsAutosave': bValue ? '1' : '0'
- });
- });
-};
-
-//SettingsContacts.prototype.onShow = function ()
-//{
-//
-//};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function SettingsAccounts()
-{
- var oData = RL.data();
-
- this.accounts = oData.accounts;
-
- this.processText = ko.computed(function () {
- return oData.accountsLoading() ? Utils.i18n('SETTINGS_ACCOUNTS/LOADING_PROCESS') : '';
- }, this);
-
- this.visibility = ko.computed(function () {
- return '' === this.processText() ? 'hidden' : 'visible';
- }, this);
-
- this.accountForDeletion = ko.observable(null).extend({'falseTimeout': 3000}).extend({'toggleSubscribe': [this,
- function (oPrev) {
- if (oPrev)
- {
- oPrev.deleteAccess(false);
- }
- }, function (oNext) {
- if (oNext)
- {
- oNext.deleteAccess(true);
- }
- }
- ]});
-}
-
-Utils.addSettingsViewModel(SettingsAccounts, 'SettingsAccounts', 'SETTINGS_LABELS/LABEL_ACCOUNTS_NAME', 'accounts');
-
-SettingsAccounts.prototype.addNewAccount = function ()
-{
- kn.showScreenPopup(PopupsAddAccountViewModel);
-};
-
-/**
- * @param {AccountModel} oAccountToRemove
- */
-SettingsAccounts.prototype.deleteAccount = function (oAccountToRemove)
-{
- if (oAccountToRemove && oAccountToRemove.deleteAccess())
- {
- this.accountForDeletion(null);
-
- var
- fRemoveAccount = function (oAccount) {
- return oAccountToRemove === oAccount;
- }
- ;
-
- if (oAccountToRemove)
- {
- this.accounts.remove(fRemoveAccount);
-
- RL.remote().accountDelete(function (sResult, oData) {
-
- if (Enums.StorageResultType.Success === sResult && oData &&
- oData.Result && oData.Reload)
- {
- kn.routeOff();
- kn.setHash(RL.link().root(), true);
- kn.routeOff();
-
- _.defer(function () {
- window.location.reload();
- });
}
else
{
- RL.accountsAndIdentities();
+ this.submitError(Utils.getNotification(Enums.Notification.UnknownError));
}
-
- }, oAccountToRemove.email);
- }
- }
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-/**
- * @constructor
- */
-function SettingsIdentity()
-{
- var oData = RL.data();
+ }, this), this.email(), '', this.password());
- this.editor = null;
-
- this.displayName = oData.displayName;
- this.signature = oData.signature;
- this.signatureToAll = oData.signatureToAll;
- this.replyTo = oData.replyTo;
+ return true;
- this.signatureDom = ko.observable(null);
-
- this.displayNameTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
- this.replyTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
- this.signatureTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
-}
-
-Utils.addSettingsViewModel(SettingsIdentity, 'SettingsIdentity', 'SETTINGS_LABELS/LABEL_IDENTITY_NAME', 'identity');
-
-SettingsIdentity.prototype.onFocus = function ()
-{
- if (!this.editor && this.signatureDom())
- {
- var
- self = this,
- sSignature = RL.data().signature()
- ;
-
- this.editor = new NewHtmlEditorWrapper(self.signatureDom(), function () {
- RL.data().signature(
- (self.editor.isHtml() ? ':HTML:' : '') + self.editor.getData()
- );
}, function () {
- if (':HTML:' === sSignature.substr(0, 6))
- {
- self.editor.setHtml(sSignature.substr(6), false);
- }
- else
- {
- self.editor.setPlain(sSignature, false);
- }
+ return !this.submitRequest();
});
+
+ kn.constructorEnd(this);
}
-};
-SettingsIdentity.prototype.onBuild = function ()
-{
- var self = this;
- _.delay(function () {
+ kn.extendAsViewModel('PopupsAddAccountViewModel', PopupsAddAccountViewModel);
- var
- oData = RL.data(),
- f1 = Utils.settingsSaveHelperSimpleFunction(self.displayNameTrigger, self),
- f2 = Utils.settingsSaveHelperSimpleFunction(self.replyTrigger, self),
- f3 = Utils.settingsSaveHelperSimpleFunction(self.signatureTrigger, self)
- ;
+ PopupsAddAccountViewModel.prototype.clearPopup = function ()
+ {
+ this.email('');
+ this.password('');
- oData.displayName.subscribe(function (sValue) {
- RL.remote().saveSettings(f1, {
- 'DisplayName': sValue
- });
- });
+ this.emailError(false);
+ this.passwordError(false);
- oData.replyTo.subscribe(function (sValue) {
- RL.remote().saveSettings(f2, {
- 'ReplyTo': sValue
- });
- });
+ this.submitRequest(false);
+ this.submitError('');
+ };
- oData.signature.subscribe(function (sValue) {
- RL.remote().saveSettings(f3, {
- 'Signature': sValue
- });
- });
+ PopupsAddAccountViewModel.prototype.onShow = function ()
+ {
+ this.clearPopup();
+ };
- oData.signatureToAll.subscribe(function (bValue) {
- RL.remote().saveSettings(null, {
- 'SignatureToAll': bValue ? '1' : '0'
- });
- });
-
- }, 50);
-};
-
+ PopupsAddAccountViewModel.prototype.onFocus = function ()
+ {
+ this.emailFocus(true);
+ };
+
+ module.exports = PopupsAddAccountViewModel;
+
+}(module));
+},{"../../Boots/RainLoopApp.js":4,"../../Common/Enums.js":7,"../../Common/Utils.js":14,"../../External/ko.js":28,"../../Knoin/Knoin.js":33,"../../Knoin/KnoinAbstractViewModel.js":36,"../../Storages/WebMailAjaxRemoteStorage.js":65}],75:[function(require,module,exports){
/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-/**
- * @constructor
- */
-function SettingsIdentities()
-{
- var oData = RL.data();
+(function (module) {
- this.editor = null;
- this.defautOptionsAfterRender = Utils.defautOptionsAfterRender;
+ 'use strict';
- this.accountEmail = oData.accountEmail;
- this.displayName = oData.displayName;
- this.signature = oData.signature;
- this.signatureToAll = oData.signatureToAll;
- this.replyTo = oData.replyTo;
-
- this.signatureDom = ko.observable(null);
-
- this.defaultIdentityIDTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
- this.displayNameTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
- this.replyTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
- this.signatureTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
-
- this.identities = oData.identities;
- this.defaultIdentityID = oData.defaultIdentityID;
-
- this.identitiesOptions = ko.computed(function () {
-
- var
- aList = this.identities(),
- aResult = []
- ;
-
- if (0 < aList.length)
- {
- aResult.push({
- 'id': this.accountEmail.peek(),
- 'name': this.formattedAccountIdentity(),
- 'seporator': false
- });
-
- aResult.push({
- 'id': '---',
- 'name': '---',
- 'seporator': true,
- 'disabled': true
- });
-
- _.each(aList, function (oItem) {
- aResult.push({
- 'id': oItem.id,
- 'name': oItem.formattedNameForEmail(),
- 'seporator': false
- });
- });
- }
-
- return aResult;
- }, this);
-
- this.processText = ko.computed(function () {
- return oData.identitiesLoading() ? Utils.i18n('SETTINGS_IDENTITIES/LOADING_PROCESS') : '';
- }, this);
-
- this.visibility = ko.computed(function () {
- return '' === this.processText() ? 'hidden' : 'visible';
- }, this);
-
- this.identityForDeletion = ko.observable(null).extend({'falseTimeout': 3000}).extend({'toggleSubscribe': [this,
- function (oPrev) {
- if (oPrev)
- {
- oPrev.deleteAccess(false);
- }
- }, function (oNext) {
- if (oNext)
- {
- oNext.deleteAccess(true);
- }
- }
- ]});
-}
-
-Utils.addSettingsViewModel(SettingsIdentities, 'SettingsIdentities', 'SETTINGS_LABELS/LABEL_IDENTITIES_NAME', 'identities');
-
-/**
- *
- * @return {string}
- */
-SettingsIdentities.prototype.formattedAccountIdentity = function ()
-{
var
- sDisplayName = this.displayName.peek(),
- sEmail = this.accountEmail.peek()
+ ko = require('../../External/ko.js'),
+
+ Utils = require('../../Common/Utils.js'),
+
+ Data = require('../../Storages/WebMailDataStorage.js'),
+
+ RL = require('../../Boots/RainLoopApp.js'),
+
+ kn = require('../../Knoin/Knoin.js'),
+ KnoinAbstractViewModel = require('../../Knoin/KnoinAbstractViewModel.js')
+ ;
+
+ /**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+ function PopupsAddOpenPgpKeyViewModel()
+ {
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsAddOpenPgpKey');
+
+ this.key = ko.observable('');
+ this.key.error = ko.observable(false);
+ this.key.focus = ko.observable(false);
+
+ this.key.subscribe(function () {
+ this.key.error(false);
+ }, this);
+
+ this.addOpenPgpKeyCommand = Utils.createCommand(this, function () {
+
+ var
+ iCount = 30,
+ aMatch = null,
+ sKey = Utils.trim(this.key()),
+ oReg = /[\-]{3,6}BEGIN[\s]PGP[\s](PRIVATE|PUBLIC)[\s]KEY[\s]BLOCK[\-]{3,6}[\s\S]+?[\-]{3,6}END[\s]PGP[\s](PRIVATE|PUBLIC)[\s]KEY[\s]BLOCK[\-]{3,6}/gi,
+ oOpenpgpKeyring = Data.openpgpKeyring
+ ;
+
+ sKey = sKey.replace(/[\r\n]([a-zA-Z0-9]{2,}:[^\r\n]+)[\r\n]+([a-zA-Z0-9\/\\+=]{10,})/g, '\n$1!-!N!-!$2')
+ .replace(/[\n\r]+/g, '\n').replace(/!-!N!-!/g, '\n\n');
+
+ this.key.error('' === sKey);
+
+ if (!oOpenpgpKeyring || this.key.error())
+ {
+ return false;
+ }
+
+ do
+ {
+ aMatch = oReg.exec(sKey);
+ if (!aMatch || 0 > iCount)
+ {
+ break;
+ }
+
+ if (aMatch[0] && aMatch[1] && aMatch[2] && aMatch[1] === aMatch[2])
+ {
+ if ('PRIVATE' === aMatch[1])
+ {
+ oOpenpgpKeyring.privateKeys.importKey(aMatch[0]);
+ }
+ else if ('PUBLIC' === aMatch[1])
+ {
+ oOpenpgpKeyring.publicKeys.importKey(aMatch[0]);
+ }
+ }
+
+ iCount--;
+ }
+ while (true);
+
+ oOpenpgpKeyring.store();
+
+ RL.reloadOpenPgpKeys();
+ Utils.delegateRun(this, 'cancelCommand');
+
+ return true;
+ });
+
+ kn.constructorEnd(this);
+ }
+
+ kn.extendAsViewModel('PopupsAddOpenPgpKeyViewModel', PopupsAddOpenPgpKeyViewModel);
+
+ PopupsAddOpenPgpKeyViewModel.prototype.clearPopup = function ()
+ {
+ this.key('');
+ this.key.error(false);
+ };
+
+ PopupsAddOpenPgpKeyViewModel.prototype.onShow = function ()
+ {
+ this.clearPopup();
+ };
+
+ PopupsAddOpenPgpKeyViewModel.prototype.onFocus = function ()
+ {
+ this.key.focus(true);
+ };
+
+ module.exports = PopupsAddOpenPgpKeyViewModel;
+
+}(module));
+},{"../../Boots/RainLoopApp.js":4,"../../Common/Utils.js":14,"../../External/ko.js":28,"../../Knoin/Knoin.js":33,"../../Knoin/KnoinAbstractViewModel.js":36,"../../Storages/WebMailDataStorage.js":67}],76:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ ko = require('../../External/ko.js'),
+ key = require('../../External/key.js'),
+ Enums = require('../../Common/Enums.js'),
+ Utils = require('../../Common/Utils.js'),
+ kn = require('../../Knoin/Knoin.js'),
+ KnoinAbstractViewModel = require('../../Knoin/KnoinAbstractViewModel.js')
;
- return '' === sDisplayName ? sEmail : '"' + Utils.quoteName(sDisplayName) + '" <' + sEmail + '>';
-};
-
-SettingsIdentities.prototype.addNewIdentity = function ()
-{
- kn.showScreenPopup(PopupsIdentityViewModel);
-};
-
-SettingsIdentities.prototype.editIdentity = function (oIdentity)
-{
- kn.showScreenPopup(PopupsIdentityViewModel, [oIdentity]);
-};
-
-/**
- * @param {IdentityModel} oIdentityToRemove
- */
-SettingsIdentities.prototype.deleteIdentity = function (oIdentityToRemove)
-{
- if (oIdentityToRemove && oIdentityToRemove.deleteAccess())
+ /**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+ function PopupsAskViewModel()
{
- this.identityForDeletion(null);
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsAsk');
- var
- fRemoveFolder = function (oIdentity) {
- return oIdentityToRemove === oIdentity;
- }
- ;
+ this.askDesc = ko.observable('');
+ this.yesButton = ko.observable('');
+ this.noButton = ko.observable('');
- if (oIdentityToRemove)
- {
- this.identities.remove(fRemoveFolder);
+ this.yesFocus = ko.observable(false);
+ this.noFocus = ko.observable(false);
- RL.remote().identityDelete(function () {
- RL.accountsAndIdentities();
- }, oIdentityToRemove.id);
- }
+ this.fYesAction = null;
+ this.fNoAction = null;
+
+ this.bDisabeCloseOnEsc = true;
+ this.sDefaultKeyScope = Enums.KeyState.PopupAsk;
+
+ kn.constructorEnd(this);
}
-};
-SettingsIdentities.prototype.onFocus = function ()
-{
- if (!this.editor && this.signatureDom())
+ kn.extendAsViewModel('PopupsAskViewModel', PopupsAskViewModel);
+
+ PopupsAskViewModel.prototype.clearPopup = function ()
{
- var
- self = this,
- sSignature = RL.data().signature()
- ;
+ this.askDesc('');
+ this.yesButton(Utils.i18n('POPUPS_ASK/BUTTON_YES'));
+ this.noButton(Utils.i18n('POPUPS_ASK/BUTTON_NO'));
- this.editor = new NewHtmlEditorWrapper(self.signatureDom(), function () {
- RL.data().signature(
- (self.editor.isHtml() ? ':HTML:' : '') + self.editor.getData()
- );
- }, function () {
- if (':HTML:' === sSignature.substr(0, 6))
+ this.yesFocus(false);
+ this.noFocus(false);
+
+ this.fYesAction = null;
+ this.fNoAction = null;
+ };
+
+ PopupsAskViewModel.prototype.yesClick = function ()
+ {
+ this.cancelCommand();
+
+ if (Utils.isFunc(this.fYesAction))
+ {
+ this.fYesAction.call(null);
+ }
+ };
+
+ PopupsAskViewModel.prototype.noClick = function ()
+ {
+ this.cancelCommand();
+
+ if (Utils.isFunc(this.fNoAction))
+ {
+ this.fNoAction.call(null);
+ }
+ };
+
+ /**
+ * @param {string} sAskDesc
+ * @param {Function=} fYesFunc
+ * @param {Function=} fNoFunc
+ * @param {string=} sYesButton
+ * @param {string=} sNoButton
+ */
+ PopupsAskViewModel.prototype.onShow = function (sAskDesc, fYesFunc, fNoFunc, sYesButton, sNoButton)
+ {
+ this.clearPopup();
+
+ this.fYesAction = fYesFunc || null;
+ this.fNoAction = fNoFunc || null;
+
+ this.askDesc(sAskDesc || '');
+ if (sYesButton)
+ {
+ this.yesButton(sYesButton);
+ }
+
+ if (sYesButton)
+ {
+ this.yesButton(sNoButton);
+ }
+ };
+
+ PopupsAskViewModel.prototype.onFocus = function ()
+ {
+ this.yesFocus(true);
+ };
+
+ PopupsAskViewModel.prototype.onBuild = function ()
+ {
+ key('tab, shift+tab, right, left', Enums.KeyState.PopupAsk, _.bind(function () {
+ if (this.yesFocus())
{
- self.editor.setHtml(sSignature.substr(6), false);
+ this.noFocus(true);
}
else
{
- self.editor.setPlain(sSignature, false);
+ this.yesFocus(true);
}
- });
- }
-};
+ return false;
+ }, this));
-SettingsIdentities.prototype.onBuild = function (oDom)
-{
- var self = this;
+ key('esc', Enums.KeyState.PopupAsk, _.bind(function () {
+ this.noClick();
+ return false;
+ }, this));
+ };
- oDom
- .on('click', '.identity-item .e-action', function () {
- var oIdentityItem = ko.dataFor(this);
- if (oIdentityItem)
- {
- self.editIdentity(oIdentityItem);
- }
- })
+ module.exports = PopupsAskViewModel;
+
+}(module));
+},{"../../Common/Enums.js":7,"../../Common/Utils.js":14,"../../External/key.js":27,"../../External/ko.js":28,"../../Knoin/Knoin.js":33,"../../Knoin/KnoinAbstractViewModel.js":36}],77:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ window = require('../../External/window.js'),
+ ko = require('../../External/ko.js'),
+ key = require('../../External/key.js'),
+
+ Utils = require('../../Common/Utils.js'),
+ Enums = require('../../Common/Enums.js'),
+
+ Data = require('../../Storages/WebMailDataStorage.js'),
+
+ kn = require('../../Knoin/Knoin.js'),
+ KnoinAbstractViewModel = require('../../Knoin/KnoinAbstractViewModel.js')
;
-
- _.delay(function () {
-
- var
- oData = RL.data(),
- f1 = Utils.settingsSaveHelperSimpleFunction(self.displayNameTrigger, self),
- f2 = Utils.settingsSaveHelperSimpleFunction(self.replyTrigger, self),
- f3 = Utils.settingsSaveHelperSimpleFunction(self.signatureTrigger, self),
- f4 = Utils.settingsSaveHelperSimpleFunction(self.defaultIdentityIDTrigger, self)
- ;
-
- oData.defaultIdentityID.subscribe(function (sValue) {
- RL.remote().saveSettings(f4, {
- 'DefaultIdentityID': sValue
- });
- });
-
- oData.displayName.subscribe(function (sValue) {
- RL.remote().saveSettings(f1, {
- 'DisplayName': sValue
- });
- });
-
- oData.replyTo.subscribe(function (sValue) {
- RL.remote().saveSettings(f2, {
- 'ReplyTo': sValue
- });
- });
-
- oData.signature.subscribe(function (sValue) {
- RL.remote().saveSettings(f3, {
- 'Signature': sValue
- });
- });
-
- oData.signatureToAll.subscribe(function (bValue) {
- RL.remote().saveSettings(null, {
- 'SignatureToAll': bValue ? '1' : '0'
- });
- });
-
- }, 50);
-};
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function SettingsFilters()
-{
-// var oData = RL.data();
-
- this.filters = ko.observableArray([]);
- this.filters.loading = ko.observable(false);
-
- this.filters.subscribe(function () {
- Utils.windowResize();
- });
-}
-
-Utils.addSettingsViewModel(SettingsFilters, 'SettingsFilters', 'SETTINGS_LABELS/LABEL_FILTERS_NAME', 'filters');
-
-//SettingsFilters.prototype.onBuild = function ()
-//{
-//};
-
-SettingsFilters.prototype.deleteFilter = function (oFilter)
-{
- this.filters.remove(oFilter);
-};
-
-SettingsFilters.prototype.addFilter = function ()
-{
- kn.showScreenPopup(PopupsFilterViewModel, [new FilterModel()]);
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function SettingsSecurity()
-{
- this.processing = ko.observable(false);
- this.clearing = ko.observable(false);
- this.secreting = ko.observable(false);
-
- this.viewUser = ko.observable('');
- this.viewEnable = ko.observable(false);
- this.viewEnable.subs = true;
- this.twoFactorStatus = ko.observable(false);
-
- this.viewSecret = ko.observable('');
- this.viewBackupCodes = ko.observable('');
- this.viewUrl = ko.observable('');
-
- this.bFirst = true;
-
- this.viewTwoFactorStatus = ko.computed(function () {
- Globals.langChangeTrigger();
- return Utils.i18n(
- this.twoFactorStatus() ?
- 'SETTINGS_SECURITY/TWO_FACTOR_SECRET_CONFIGURED_DESC' :
- 'SETTINGS_SECURITY/TWO_FACTOR_SECRET_NOT_CONFIGURED_DESC'
- );
- }, this);
- this.onResult = _.bind(this.onResult, this);
- this.onSecretResult = _.bind(this.onSecretResult, this);
-}
-
-Utils.addSettingsViewModel(SettingsSecurity, 'SettingsSecurity', 'SETTINGS_LABELS/LABEL_SECURITY_NAME', 'security');
-
-SettingsSecurity.prototype.showSecret = function ()
-{
- this.secreting(true);
- RL.remote().showTwoFactorSecret(this.onSecretResult);
-};
-
-SettingsSecurity.prototype.hideSecret = function ()
-{
- this.viewSecret('');
- this.viewBackupCodes('');
- this.viewUrl('');
-};
-
-SettingsSecurity.prototype.createTwoFactor = function ()
-{
- this.processing(true);
- RL.remote().createTwoFactor(this.onResult);
-};
-
-SettingsSecurity.prototype.enableTwoFactor = function ()
-{
- this.processing(true);
- RL.remote().enableTwoFactor(this.onResult, this.viewEnable());
-};
-
-SettingsSecurity.prototype.testTwoFactor = function ()
-{
- kn.showScreenPopup(PopupsTwoFactorTestViewModel);
-};
-
-SettingsSecurity.prototype.clearTwoFactor = function ()
-{
- this.viewSecret('');
- this.viewBackupCodes('');
- this.viewUrl('');
-
- this.clearing(true);
- RL.remote().clearTwoFactor(this.onResult);
-};
-
-SettingsSecurity.prototype.onShow = function ()
-{
- this.viewSecret('');
- this.viewBackupCodes('');
- this.viewUrl('');
-};
-
-SettingsSecurity.prototype.onResult = function (sResult, oData)
-{
- this.processing(false);
- this.clearing(false);
-
- if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ /**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+ function PopupsComposeOpenPgpViewModel()
{
- this.viewUser(Utils.pString(oData.Result.User));
- this.viewEnable(!!oData.Result.Enable);
- this.twoFactorStatus(!!oData.Result.IsSet);
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsComposeOpenPgp');
- this.viewSecret(Utils.pString(oData.Result.Secret));
- this.viewBackupCodes(Utils.pString(oData.Result.BackupCodes).replace(/[\s]+/g, ' '));
- this.viewUrl(Utils.pString(oData.Result.Url));
- }
- else
- {
- this.viewUser('');
- this.viewEnable(false);
- this.twoFactorStatus(false);
+ this.notification = ko.observable('');
- this.viewSecret('');
- this.viewBackupCodes('');
- this.viewUrl('');
- }
+ this.sign = ko.observable(true);
+ this.encrypt = ko.observable(true);
- if (this.bFirst)
- {
- this.bFirst = false;
- var self = this;
- this.viewEnable.subscribe(function (bValue) {
- if (this.viewEnable.subs)
+ this.password = ko.observable('');
+ this.password.focus = ko.observable(false);
+ this.buttonFocus = ko.observable(false);
+
+ this.from = ko.observable('');
+ this.to = ko.observableArray([]);
+ this.text = ko.observable('');
+
+ this.resultCallback = null;
+
+ this.submitRequest = ko.observable(false);
+
+ // commands
+ this.doCommand = Utils.createCommand(this, function () {
+
+ var
+ self = this,
+ bResult = true,
+ oPrivateKey = null,
+ aPublicKeys = []
+ ;
+
+ this.submitRequest(true);
+
+ if (bResult && this.sign() && '' === this.from())
{
- RL.remote().enableTwoFactor(function (sResult, oData) {
- if (Enums.StorageResultType.Success !== sResult || !oData || !oData.Result)
- {
- self.viewEnable.subs = false;
- self.viewEnable(false);
- self.viewEnable.subs = true;
- }
- }, bValue);
+ this.notification(Utils.i18n('PGP_NOTIFICATIONS/SPECIFY_FROM_EMAIL'));
+ bResult = false;
}
- }, this);
+
+ if (bResult && this.sign())
+ {
+ oPrivateKey = Data.findPrivateKeyByEmail(this.from(), this.password());
+ if (!oPrivateKey)
+ {
+ this.notification(Utils.i18n('PGP_NOTIFICATIONS/NO_PRIVATE_KEY_FOUND_FOR', {
+ 'EMAIL': this.from()
+ }));
+
+ bResult = false;
+ }
+ }
+
+ if (bResult && this.encrypt() && 0 === this.to().length)
+ {
+ this.notification(Utils.i18n('PGP_NOTIFICATIONS/SPECIFY_AT_LEAST_ONE_RECIPIENT'));
+ bResult = false;
+ }
+
+ if (bResult && this.encrypt())
+ {
+ aPublicKeys = [];
+ _.each(this.to(), function (sEmail) {
+ var aKeys = Data.findPublicKeysByEmail(sEmail);
+ if (0 === aKeys.length && bResult)
+ {
+ self.notification(Utils.i18n('PGP_NOTIFICATIONS/NO_PUBLIC_KEYS_FOUND_FOR', {
+ 'EMAIL': sEmail
+ }));
+
+ bResult = false;
+ }
+
+ aPublicKeys = aPublicKeys.concat(aKeys);
+ });
+
+ if (bResult && (0 === aPublicKeys.length || this.to().length !== aPublicKeys.length))
+ {
+ bResult = false;
+ }
+ }
+
+ _.delay(function () {
+
+ if (self.resultCallback && bResult)
+ {
+ try {
+
+ if (oPrivateKey && 0 === aPublicKeys.length)
+ {
+ self.resultCallback(
+ window.openpgp.signClearMessage([oPrivateKey], self.text())
+ );
+ }
+ else if (oPrivateKey && 0 < aPublicKeys.length)
+ {
+ self.resultCallback(
+ window.openpgp.signAndEncryptMessage(aPublicKeys, oPrivateKey, self.text())
+ );
+ }
+ else if (!oPrivateKey && 0 < aPublicKeys.length)
+ {
+ self.resultCallback(
+ window.openpgp.encryptMessage(aPublicKeys, self.text())
+ );
+ }
+ }
+ catch (e)
+ {
+ self.notification(Utils.i18n('PGP_NOTIFICATIONS/PGP_ERROR', {
+ 'ERROR': '' + e
+ }));
+
+ bResult = false;
+ }
+ }
+
+ if (bResult)
+ {
+ self.cancelCommand();
+ }
+
+ self.submitRequest(false);
+
+ }, 10);
+
+ }, function () {
+ return !this.submitRequest() && (this.sign() || this.encrypt());
+ });
+
+ this.sDefaultKeyScope = Enums.KeyState.PopupComposeOpenPGP;
+
+ kn.constructorEnd(this);
}
-};
-SettingsSecurity.prototype.onSecretResult = function (sResult, oData)
-{
- this.secreting(false);
+ kn.extendAsViewModel('PopupsComposeOpenPgpViewModel', PopupsComposeOpenPgpViewModel);
- if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ PopupsComposeOpenPgpViewModel.prototype.clearPopup = function ()
{
- this.viewSecret(Utils.pString(oData.Result.Secret));
- this.viewUrl(Utils.pString(oData.Result.Url));
- }
- else
+ this.notification('');
+
+ this.password('');
+ this.password.focus(false);
+ this.buttonFocus(false);
+
+ this.from('');
+ this.to([]);
+ this.text('');
+
+ this.submitRequest(false);
+
+ this.resultCallback = null;
+ };
+
+ PopupsComposeOpenPgpViewModel.prototype.onBuild = function ()
{
- this.viewSecret('');
- this.viewUrl('');
- }
-};
+ key('tab,shift+tab', Enums.KeyState.PopupComposeOpenPGP, _.bind(function () {
-SettingsSecurity.prototype.onBuild = function ()
-{
- this.processing(true);
- RL.remote().getTwoFactor(this.onResult);
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+ switch (true)
+ {
+ case this.password.focus():
+ this.buttonFocus(true);
+ break;
+ case this.buttonFocus():
+ this.password.focus(true);
+ break;
+ }
-/**
- * @constructor
- */
-function SettingsSocialScreen()
-{
- var oData = RL.data();
+ return false;
- this.googleEnable = oData.googleEnable;
+ }, this));
+ };
- this.googleActions = oData.googleActions;
- this.googleLoggined = oData.googleLoggined;
- this.googleUserName = oData.googleUserName;
+ PopupsComposeOpenPgpViewModel.prototype.onHide = function ()
+ {
+ this.clearPopup();
+ };
- this.facebookEnable = oData.facebookEnable;
-
- this.facebookActions = oData.facebookActions;
- this.facebookLoggined = oData.facebookLoggined;
- this.facebookUserName = oData.facebookUserName;
-
- this.twitterEnable = oData.twitterEnable;
-
- this.twitterActions = oData.twitterActions;
- this.twitterLoggined = oData.twitterLoggined;
- this.twitterUserName = oData.twitterUserName;
-
- this.connectGoogle = Utils.createCommand(this, function () {
- if (!this.googleLoggined())
+ PopupsComposeOpenPgpViewModel.prototype.onFocus = function ()
+ {
+ if (this.sign())
{
- RL.googleConnect();
- }
- }, function () {
- return !this.googleLoggined() && !this.googleActions();
- });
-
- this.disconnectGoogle = Utils.createCommand(this, function () {
- RL.googleDisconnect();
- });
-
- this.connectFacebook = Utils.createCommand(this, function () {
- if (!this.facebookLoggined())
- {
- RL.facebookConnect();
- }
- }, function () {
- return !this.facebookLoggined() && !this.facebookActions();
- });
-
- this.disconnectFacebook = Utils.createCommand(this, function () {
- RL.facebookDisconnect();
- });
-
- this.connectTwitter = Utils.createCommand(this, function () {
- if (!this.twitterLoggined())
- {
- RL.twitterConnect();
- }
- }, function () {
- return !this.twitterLoggined() && !this.twitterActions();
- });
-
- this.disconnectTwitter = Utils.createCommand(this, function () {
- RL.twitterDisconnect();
- });
-}
-
-Utils.addSettingsViewModel(SettingsSocialScreen, 'SettingsSocial', 'SETTINGS_LABELS/LABEL_SOCIAL_NAME', 'social');
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function SettingsChangePasswordScreen()
-{
- this.changeProcess = ko.observable(false);
-
- this.errorDescription = ko.observable('');
- this.passwordMismatch = ko.observable(false);
- this.passwordUpdateError = ko.observable(false);
- this.passwordUpdateSuccess = ko.observable(false);
-
- this.currentPassword = ko.observable('');
- this.currentPassword.error = ko.observable(false);
- this.newPassword = ko.observable('');
- this.newPassword2 = ko.observable('');
-
- this.currentPassword.subscribe(function () {
- this.passwordUpdateError(false);
- this.passwordUpdateSuccess(false);
- this.currentPassword.error(false);
- }, this);
-
- this.newPassword.subscribe(function () {
- this.passwordUpdateError(false);
- this.passwordUpdateSuccess(false);
- this.passwordMismatch(false);
- }, this);
-
- this.newPassword2.subscribe(function () {
- this.passwordUpdateError(false);
- this.passwordUpdateSuccess(false);
- this.passwordMismatch(false);
- }, this);
-
- this.saveNewPasswordCommand = Utils.createCommand(this, function () {
-
- if (this.newPassword() !== this.newPassword2())
- {
- this.passwordMismatch(true);
- this.errorDescription(Utils.i18n('SETTINGS_CHANGE_PASSWORD/ERROR_PASSWORD_MISMATCH'));
+ this.password.focus(true);
}
else
{
- this.changeProcess(true);
-
- this.passwordUpdateError(false);
- this.passwordUpdateSuccess(false);
- this.currentPassword.error(false);
- this.passwordMismatch(false);
- this.errorDescription('');
-
- RL.remote().changePassword(this.onChangePasswordResponse, this.currentPassword(), this.newPassword());
+ this.buttonFocus(true);
}
+ };
- }, function () {
- return !this.changeProcess() && '' !== this.currentPassword() &&
- '' !== this.newPassword() && '' !== this.newPassword2();
- });
-
- this.onChangePasswordResponse = _.bind(this.onChangePasswordResponse, this);
-}
-
-Utils.addSettingsViewModel(SettingsChangePasswordScreen, 'SettingsChangePassword', 'SETTINGS_LABELS/LABEL_CHANGE_PASSWORD_NAME', 'change-password');
-
-SettingsChangePasswordScreen.prototype.onHide = function ()
-{
- this.changeProcess(false);
- this.currentPassword('');
- this.newPassword('');
- this.newPassword2('');
- this.errorDescription('');
- this.passwordMismatch(false);
- this.currentPassword.error(false);
-};
-
-SettingsChangePasswordScreen.prototype.onChangePasswordResponse = function (sResult, oData)
-{
- this.changeProcess(false);
- this.passwordMismatch(false);
- this.errorDescription('');
- this.currentPassword.error(false);
-
- if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ PopupsComposeOpenPgpViewModel.prototype.onShow = function (fCallback, sText, sFromEmail, sTo, sCc, sBcc)
{
- this.currentPassword('');
- this.newPassword('');
- this.newPassword2('');
-
- this.passwordUpdateSuccess(true);
- this.currentPassword.error(false);
- }
- else
- {
- if (oData && Enums.Notification.CurrentPasswordIncorrect === oData.ErrorCode)
- {
- this.currentPassword.error(true);
- }
-
- this.passwordUpdateError(true);
- this.errorDescription(oData && oData.ErrorCode ? Utils.getNotification(oData.ErrorCode) :
- Utils.getNotification(Enums.Notification.CouldNotSaveNewPassword));
- }
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function SettingsFolders()
-{
- var oData = RL.data();
-
- this.foldersListError = oData.foldersListError;
- this.folderList = oData.folderList;
-
- this.processText = ko.computed(function () {
+ this.clearPopup();
var
- oData = RL.data(),
- bLoading = oData.foldersLoading(),
- bCreating = oData.foldersCreating(),
- bDeleting = oData.foldersDeleting(),
- bRenaming = oData.foldersRenaming()
+ oEmail = new EmailModel(),
+ sResultFromEmail = '',
+ aRec = []
;
- if (bCreating)
+ this.resultCallback = fCallback;
+
+ oEmail.clear();
+ oEmail.mailsoParse(sFromEmail);
+ if ('' !== oEmail.email)
{
- return Utils.i18n('SETTINGS_FOLDERS/CREATING_PROCESS');
+ sResultFromEmail = oEmail.email;
}
- else if (bDeleting)
+
+ if ('' !== sTo)
{
- return Utils.i18n('SETTINGS_FOLDERS/DELETING_PROCESS');
+ aRec.push(sTo);
}
- else if (bRenaming)
+
+ if ('' !== sCc)
{
- return Utils.i18n('SETTINGS_FOLDERS/RENAMING_PROCESS');
+ aRec.push(sCc);
}
- else if (bLoading)
+
+ if ('' !== sBcc)
{
- return Utils.i18n('SETTINGS_FOLDERS/LOADING_PROCESS');
+ aRec.push(sBcc);
}
- return '';
+ aRec = aRec.join(', ').split(',');
+ aRec = _.compact(_.map(aRec, function (sValue) {
+ oEmail.clear();
+ oEmail.mailsoParse(Utils.trim(sValue));
+ return '' === oEmail.email ? false : oEmail.email;
+ }));
- }, this);
+ this.from(sResultFromEmail);
+ this.to(aRec);
+ this.text(sText);
+ };
- this.visibility = ko.computed(function () {
- return '' === this.processText() ? 'hidden' : 'visible';
- }, this);
+ module.exports = PopupsComposeOpenPgpViewModel;
- this.folderForDeletion = ko.observable(null).extend({'falseTimeout': 3000}).extend({'toggleSubscribe': [this,
- function (oPrev) {
- if (oPrev)
- {
- oPrev.deleteAccess(false);
- }
- }, function (oNext) {
- if (oNext)
- {
- oNext.deleteAccess(true);
- }
- }
- ]});
+}(module));
+},{"../../Common/Enums.js":7,"../../Common/Utils.js":14,"../../External/key.js":27,"../../External/ko.js":28,"../../External/window.js":32,"../../Knoin/Knoin.js":33,"../../Knoin/KnoinAbstractViewModel.js":36,"../../Storages/WebMailDataStorage.js":67}],78:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
- this.folderForEdit = ko.observable(null).extend({'toggleSubscribe': [this,
- function (oPrev) {
- if (oPrev)
- {
- oPrev.edited(false);
- }
- }, function (oNext) {
- if (oNext && oNext.canBeEdited())
- {
- oNext.edited(true);
- }
- }
- ]});
+(function (module) {
- this.useImapSubscribe = !!RL.settingsGet('UseImapSubscribe');
-}
+ 'use strict';
-Utils.addSettingsViewModel(SettingsFolders, 'SettingsFolders', 'SETTINGS_LABELS/LABEL_FOLDERS_NAME', 'folders');
-
-SettingsFolders.prototype.folderEditOnEnter = function (oFolder)
-{
- var sEditName = oFolder ? Utils.trim(oFolder.nameForEdit()) : '';
- if ('' !== sEditName && oFolder.name() !== sEditName)
- {
- RL.local().set(Enums.ClientSideKeyName.FoldersLashHash, '');
-
- RL.data().foldersRenaming(true);
- RL.remote().folderRename(function (sResult, oData) {
-
- RL.data().foldersRenaming(false);
- if (Enums.StorageResultType.Success !== sResult || !oData || !oData.Result)
- {
- RL.data().foldersListError(
- oData && oData.ErrorCode ? Utils.getNotification(oData.ErrorCode) : Utils.i18n('NOTIFICATIONS/CANT_RENAME_FOLDER'));
- }
-
- RL.folders();
-
- }, oFolder.fullNameRaw, sEditName);
-
- RL.cache().removeFolderFromCacheList(oFolder.fullNameRaw);
+ var
+ window = require('../../External/window.js'),
+ $ = require('../../External/jquery.js'),
+ _ = require('../../External/underscore.js'),
+ ko = require('../../External/ko.js'),
+ moment = require('../../External/moment.js'),
- oFolder.name(sEditName);
- }
-
- oFolder.edited(false);
-};
+ Enums = require('../../Common/Enums.js'),
+ Consts = require('../../Common/Consts.js'),
+ Utils = require('../../Common/Utils.js'),
+ Globals = require('../../Common/Globals.js'),
+ LinkBuilder = require('../../Common/LinkBuilder.js'),
+ Events = require('../../Common/Events.js'),
+ NewHtmlEditorWrapper = require('../../Common/NewHtmlEditorWrapper.js'),
-SettingsFolders.prototype.folderEditOnEsc = function (oFolder)
-{
- if (oFolder)
+ AppSettings = require('../../Storages/AppSettings.js'),
+ Data = require('../../Storages/WebMailDataStorage.js'),
+ Cache = require('../../Storages/WebMailCacheStorage.js'),
+ Remote = require('../../Storages/WebMailAjaxRemoteStorage.js'),
+
+ RL = require('../../Boots/RainLoopApp.js'),
+
+ PopupsComposeOpenPgpViewModel = require('./PopupsComposeOpenPgpViewModel.js'),
+
+ kn = require('../../Knoin/Knoin.js'),
+ KnoinAbstractViewModel = require('../../Knoin/KnoinAbstractViewModel.js')
+ ;
+
+ /**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+ function PopupsComposeViewModel()
{
- oFolder.edited(false);
- }
-};
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsCompose');
-SettingsFolders.prototype.onShow = function ()
-{
- RL.data().foldersListError('');
-};
+ this.oEditor = null;
+ this.aDraftInfo = null;
+ this.sInReplyTo = '';
+ this.bFromDraft = false;
+ this.bSkipNext = false;
+ this.sReferences = '';
-SettingsFolders.prototype.createFolder = function ()
-{
- kn.showScreenPopup(PopupsFolderCreateViewModel);
-};
+ this.bCapaAdditionalIdentities = AppSettings.capa(Enums.Capa.AdditionalIdentities);
-SettingsFolders.prototype.systemFolder = function ()
-{
- kn.showScreenPopup(PopupsFolderSystemViewModel);
-};
-
-SettingsFolders.prototype.deleteFolder = function (oFolderToRemove)
-{
- if (oFolderToRemove && oFolderToRemove.canBeDeleted() && oFolderToRemove.deleteAccess() &&
- 0 === oFolderToRemove.privateMessageCountAll())
- {
- this.folderForDeletion(null);
-
var
- fRemoveFolder = function (oFolder) {
-
- if (oFolderToRemove === oFolder)
+ self = this,
+ fCcAndBccCheckHelper = function (aValue) {
+ if (false === self.showCcAndBcc() && 0 < aValue.length)
{
+ self.showCcAndBcc(true);
+ }
+ }
+ ;
+
+ this.capaOpenPGP = Data.capaOpenPGP;
+
+ this.resizer = ko.observable(false).extend({'throttle': 50});
+
+ this.identitiesDropdownTrigger = ko.observable(false);
+
+ this.to = ko.observable('');
+ this.to.focusTrigger = ko.observable(false);
+ this.cc = ko.observable('');
+ this.bcc = ko.observable('');
+
+ this.replyTo = ko.observable('');
+ this.subject = ko.observable('');
+ this.isHtml = ko.observable(false);
+
+ this.requestReadReceipt = ko.observable(false);
+
+ this.sendError = ko.observable(false);
+ this.sendSuccessButSaveError = ko.observable(false);
+ this.savedError = ko.observable(false);
+
+ this.savedTime = ko.observable(0);
+ this.savedOrSendingText = ko.observable('');
+
+ this.emptyToError = ko.observable(false);
+ this.attachmentsInProcessError = ko.observable(false);
+ this.showCcAndBcc = ko.observable(false);
+
+ this.cc.subscribe(fCcAndBccCheckHelper, this);
+ this.bcc.subscribe(fCcAndBccCheckHelper, this);
+
+ this.draftFolder = ko.observable('');
+ this.draftUid = ko.observable('');
+ this.sending = ko.observable(false);
+ this.saving = ko.observable(false);
+ this.attachments = ko.observableArray([]);
+
+ this.attachmentsInProcess = this.attachments.filter(function (oItem) {
+ return oItem && '' === oItem.tempName();
+ });
+
+ this.attachmentsInReady = this.attachments.filter(function (oItem) {
+ return oItem && '' !== oItem.tempName();
+ });
+
+ this.attachments.subscribe(function () {
+ this.triggerForResize();
+ }, this);
+
+ this.isDraftFolderMessage = ko.computed(function () {
+ return '' !== this.draftFolder() && '' !== this.draftUid();
+ }, this);
+
+ this.composeUploaderButton = ko.observable(null);
+ this.composeUploaderDropPlace = ko.observable(null);
+ this.dragAndDropEnabled = ko.observable(false);
+ this.dragAndDropOver = ko.observable(false).extend({'throttle': 1});
+ this.dragAndDropVisible = ko.observable(false).extend({'throttle': 1});
+ this.attacheMultipleAllowed = ko.observable(false);
+ this.addAttachmentEnabled = ko.observable(false);
+
+ this.composeEditorArea = ko.observable(null);
+
+ this.identities = Data.identities;
+ this.defaultIdentityID = Data.defaultIdentityID;
+ this.currentIdentityID = ko.observable('');
+
+ this.currentIdentityString = ko.observable('');
+ this.currentIdentityResultEmail = ko.observable('');
+
+ this.identitiesOptions = ko.computed(function () {
+
+ var aList = [{
+ 'optValue': Data.accountEmail(),
+ 'optText': this.formattedFrom(false)
+ }];
+
+ _.each(Data.identities(), function (oItem) {
+ aList.push({
+ 'optValue': oItem.id,
+ 'optText': oItem.formattedNameForCompose()
+ });
+ });
+
+ return aList;
+
+ }, this);
+
+ ko.computed(function () {
+
+ var
+ sResult = '',
+ sResultEmail = '',
+ oItem = null,
+ aList = this.identities(),
+ sID = this.currentIdentityID()
+ ;
+
+ if (this.bCapaAdditionalIdentities && sID && sID !== Data.accountEmail())
+ {
+ oItem = _.find(aList, function (oItem) {
+ return oItem && sID === oItem['id'];
+ });
+
+ sResult = oItem ? oItem.formattedNameForCompose() : '';
+ sResultEmail = oItem ? oItem.formattedNameForEmail() : '';
+
+ if ('' === sResult && aList[0])
+ {
+ this.currentIdentityID(aList[0]['id']);
+ return '';
+ }
+ }
+
+ if ('' === sResult)
+ {
+ sResult = this.formattedFrom(false);
+ sResultEmail = this.formattedFrom(true);
+ }
+
+ this.currentIdentityString(sResult);
+ this.currentIdentityResultEmail(sResultEmail);
+
+ return sResult;
+
+ }, this);
+
+ this.to.subscribe(function (sValue) {
+ if (this.emptyToError() && 0 < sValue.length)
+ {
+ this.emptyToError(false);
+ }
+ }, this);
+
+ this.attachmentsInProcess.subscribe(function (aValue) {
+ if (this.attachmentsInProcessError() && Utils.isArray(aValue) && 0 === aValue.length)
+ {
+ this.attachmentsInProcessError(false);
+ }
+ }, this);
+
+ this.editorResizeThrottle = _.throttle(_.bind(this.editorResize, this), 100);
+
+ this.resizer.subscribe(function () {
+ this.editorResizeThrottle();
+ }, this);
+
+ this.canBeSendedOrSaved = ko.computed(function () {
+ return !this.sending() && !this.saving();
+ }, this);
+
+ this.deleteCommand = Utils.createCommand(this, function () {
+
+ RL.deleteMessagesFromFolderWithoutCheck(this.draftFolder(), [this.draftUid()]);
+ kn.hideScreenPopup(PopupsComposeViewModel);
+
+ }, function () {
+ return this.isDraftFolderMessage();
+ });
+
+ this.sendMessageResponse = _.bind(this.sendMessageResponse, this);
+ this.saveMessageResponse = _.bind(this.saveMessageResponse, this);
+
+ this.sendCommand = Utils.createCommand(this, function () {
+ var
+ sTo = Utils.trim(this.to()),
+ sSentFolder = Data.sentFolder(),
+ aFlagsCache = []
+ ;
+
+ if (0 < this.attachmentsInProcess().length)
+ {
+ this.attachmentsInProcessError(true);
+ }
+ else if (0 === sTo.length)
+ {
+ this.emptyToError(true);
+ }
+ else
+ {
+ if (Data.replySameFolder())
+ {
+ if (Utils.isArray(this.aDraftInfo) && 3 === this.aDraftInfo.length && Utils.isNormal(this.aDraftInfo[2]) && 0 < this.aDraftInfo[2].length)
+ {
+ sSentFolder = this.aDraftInfo[2];
+ }
+ }
+
+ if ('' === sSentFolder)
+ {
+ kn.showScreenPopup(PopupsFolderSystemViewModel, [Enums.SetSystemFoldersNotification.Sent]);
+ }
+ else
+ {
+ this.sendError(false);
+ this.sending(true);
+
+ if (Utils.isArray(this.aDraftInfo) && 3 === this.aDraftInfo.length)
+ {
+ aFlagsCache = Cache.getMessageFlagsFromCache(this.aDraftInfo[2], this.aDraftInfo[1]);
+ if (aFlagsCache)
+ {
+ if ('forward' === this.aDraftInfo[0])
+ {
+ aFlagsCache[3] = true;
+ }
+ else
+ {
+ aFlagsCache[2] = true;
+ }
+
+ Cache.setMessageFlagsToCache(this.aDraftInfo[2], this.aDraftInfo[1], aFlagsCache);
+ RL.reloadFlagsCurrentMessageListAndMessageFromCache();
+ Cache.setFolderHash(this.aDraftInfo[2], '');
+ }
+ }
+
+ sSentFolder = Consts.Values.UnuseOptionValue === sSentFolder ? '' : sSentFolder;
+
+ Cache.setFolderHash(this.draftFolder(), '');
+ Cache.setFolderHash(sSentFolder, '');
+
+ Remote.sendMessage(
+ this.sendMessageResponse,
+ this.draftFolder(),
+ this.draftUid(),
+ sSentFolder,
+ this.currentIdentityResultEmail(),
+ sTo,
+ this.cc(),
+ this.bcc(),
+ this.subject(),
+ this.oEditor ? this.oEditor.isHtml() : false,
+ this.oEditor ? this.oEditor.getData(true) : '',
+ this.prepearAttachmentsForSendOrSave(),
+ this.aDraftInfo,
+ this.sInReplyTo,
+ this.sReferences,
+ this.requestReadReceipt()
+ );
+ }
+ }
+ }, this.canBeSendedOrSaved);
+
+ this.saveCommand = Utils.createCommand(this, function () {
+
+ if (Data.draftFolderNotEnabled())
+ {
+ kn.showScreenPopup(PopupsFolderSystemViewModel, [Enums.SetSystemFoldersNotification.Draft]);
+ }
+ else
+ {
+ this.savedError(false);
+ this.saving(true);
+
+ this.bSkipNext = true;
+
+ Cache.setFolderHash(Data.draftFolder(), '');
+
+ Remote.saveMessage(
+ this.saveMessageResponse,
+ this.draftFolder(),
+ this.draftUid(),
+ Data.draftFolder(),
+ this.currentIdentityResultEmail(),
+ this.to(),
+ this.cc(),
+ this.bcc(),
+ this.subject(),
+ this.oEditor ? this.oEditor.isHtml() : false,
+ this.oEditor ? this.oEditor.getData(true) : '',
+ this.prepearAttachmentsForSendOrSave(),
+ this.aDraftInfo,
+ this.sInReplyTo,
+ this.sReferences
+ );
+ }
+
+ }, this.canBeSendedOrSaved);
+
+ Events.sub('interval.1m', function () {
+ if (this.modalVisibility() && !Data.draftFolderNotEnabled() && !this.isEmptyForm(false) &&
+ !this.bSkipNext && !this.saving() && !this.sending() && !this.savedError())
+ {
+ this.bSkipNext = false;
+ this.saveCommand();
+ }
+ }, this);
+
+ this.showCcAndBcc.subscribe(function () {
+ this.triggerForResize();
+ }, this);
+
+ this.dropboxEnabled = ko.observable(!!AppSettings.settingsGet('DropboxApiKey'));
+
+ this.dropboxCommand = Utils.createCommand(this, function () {
+
+ if (window.Dropbox)
+ {
+ window.Dropbox.choose({
+ //'iframe': true,
+ 'success': function(aFiles) {
+
+ if (aFiles && aFiles[0] && aFiles[0]['link'])
+ {
+ self.addDropboxAttachment(aFiles[0]);
+ }
+ },
+ 'linkType': "direct",
+ 'multiselect': false
+ });
+ }
+
+ return true;
+
+ }, function () {
+ return this.dropboxEnabled();
+ });
+
+ this.driveEnabled = ko.observable(Globals.bXMLHttpRequestSupported &&
+ !!AppSettings.settingsGet('GoogleClientID') && !!AppSettings.settingsGet('GoogleApiKey'));
+
+ this.driveVisible = ko.observable(false);
+
+ this.driveCommand = Utils.createCommand(this, function () {
+
+ this.driveOpenPopup();
+ return true;
+
+ }, function () {
+ return this.driveEnabled();
+ });
+
+ this.driveCallback = _.bind(this.driveCallback, this);
+
+ this.bDisabeCloseOnEsc = true;
+ this.sDefaultKeyScope = Enums.KeyState.Compose;
+
+ this.tryToClosePopup = _.debounce(_.bind(this.tryToClosePopup, this), 200);
+
+ this.emailsSource = _.bind(this.emailsSource, this);
+
+ kn.constructorEnd(this);
+ }
+
+ kn.extendAsViewModel('PopupsComposeViewModel', PopupsComposeViewModel);
+
+ PopupsComposeViewModel.prototype.emailsSource = function (oData, fResponse)
+ {
+ RL.getAutocomplete(oData.term, function (aData) {
+ fResponse(_.map(aData, function (oEmailItem) {
+ return oEmailItem.toLine(false);
+ }));
+ });
+ };
+
+ PopupsComposeViewModel.prototype.openOpenPgpPopup = function ()
+ {
+ if (this.capaOpenPGP() && this.oEditor && !this.oEditor.isHtml())
+ {
+ var self = this;
+ kn.showScreenPopup(PopupsComposeOpenPgpViewModel, [
+ function (sResult) {
+ self.editor(function (oEditor) {
+ oEditor.setPlain(sResult);
+ });
+ },
+ this.oEditor.getData(),
+ this.currentIdentityResultEmail(),
+ this.to(),
+ this.cc(),
+ this.bcc()
+ ]);
+ }
+ };
+
+ PopupsComposeViewModel.prototype.reloadDraftFolder = function ()
+ {
+ var sDraftFolder = Data.draftFolder();
+ if ('' !== sDraftFolder)
+ {
+ Cache.setFolderHash(sDraftFolder, '');
+ if (Data.currentFolderFullNameRaw() === sDraftFolder)
+ {
+ RL.reloadMessageList(true);
+ }
+ else
+ {
+ RL.folderInformation(sDraftFolder);
+ }
+ }
+ };
+
+ PopupsComposeViewModel.prototype.findIdentityIdByMessage = function (sComposeType, oMessage)
+ {
+ var
+ oIDs = {},
+ sResult = '',
+ fFindHelper = function (oItem) {
+ if (oItem && oItem.email && oIDs[oItem.email])
+ {
+ sResult = oIDs[oItem.email];
return true;
}
- oFolder.subFolders.remove(fRemoveFolder);
return false;
}
;
- if (oFolderToRemove)
+ if (this.bCapaAdditionalIdentities)
{
- RL.local().set(Enums.ClientSideKeyName.FoldersLashHash, '');
-
- RL.data().folderList.remove(fRemoveFolder);
-
- RL.data().foldersDeleting(true);
- RL.remote().folderDelete(function (sResult, oData) {
-
- RL.data().foldersDeleting(false);
- if (Enums.StorageResultType.Success !== sResult || !oData || !oData.Result)
- {
- RL.data().foldersListError(
- oData && oData.ErrorCode ? Utils.getNotification(oData.ErrorCode) : Utils.i18n('NOTIFICATIONS/CANT_DELETE_FOLDER'));
- }
-
- RL.folders();
-
- }, oFolderToRemove.fullNameRaw);
-
- RL.cache().removeFolderFromCacheList(oFolderToRemove.fullNameRaw);
- }
- }
- else if (0 < oFolderToRemove.privateMessageCountAll())
- {
- RL.data().foldersListError(Utils.getNotification(Enums.Notification.CantDeleteNonEmptyFolder));
- }
-};
-
-SettingsFolders.prototype.subscribeFolder = function (oFolder)
-{
- RL.local().set(Enums.ClientSideKeyName.FoldersLashHash, '');
- RL.remote().folderSetSubscribe(Utils.emptyFunction, oFolder.fullNameRaw, true);
-
- oFolder.subScribed(true);
-};
-
-SettingsFolders.prototype.unSubscribeFolder = function (oFolder)
-{
- RL.local().set(Enums.ClientSideKeyName.FoldersLashHash, '');
- RL.remote().folderSetSubscribe(Utils.emptyFunction, oFolder.fullNameRaw, false);
-
- oFolder.subScribed(false);
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function SettingsThemes()
-{
- var
- self = this,
- oData = RL.data()
- ;
-
- this.mainTheme = oData.mainTheme;
- this.themesObjects = ko.observableArray([]);
-
- this.themeTrigger = ko.observable(Enums.SaveSettingsStep.Idle).extend({'throttle': 100});
-
- this.oLastAjax = null;
- this.iTimer = 0;
-
- RL.data().theme.subscribe(function (sValue) {
-
- _.each(this.themesObjects(), function (oTheme) {
- oTheme.selected(sValue === oTheme.name);
- });
-
- var
- oThemeLink = $('#rlThemeLink'),
- oThemeStyle = $('#rlThemeStyle'),
- sUrl = oThemeLink.attr('href')
- ;
-
- if (!sUrl)
- {
- sUrl = oThemeStyle.attr('data-href');
- }
-
- if (sUrl)
- {
- sUrl = sUrl.toString().replace(/\/-\/[^\/]+\/\-\//, '/-/' + sValue + '/-/');
- sUrl = sUrl.toString().replace(/\/Css\/[^\/]+\/User\//, '/Css/0/User/');
-
- if ('Json/' !== sUrl.substring(sUrl.length - 5, sUrl.length))
- {
- sUrl += 'Json/';
- }
-
- window.clearTimeout(self.iTimer);
- self.themeTrigger(Enums.SaveSettingsStep.Animate);
-
- if (this.oLastAjax && this.oLastAjax.abort)
- {
- this.oLastAjax.abort();
- }
-
- this.oLastAjax = $.ajax({
- 'url': sUrl,
- 'dataType': 'json'
- }).done(function(aData) {
- if (aData && Utils.isArray(aData) && 2 === aData.length)
- {
- if (oThemeLink && oThemeLink[0] && (!oThemeStyle || !oThemeStyle[0]))
- {
- oThemeStyle = $('');
- oThemeLink.after(oThemeStyle);
- oThemeLink.remove();
- }
-
- if (oThemeStyle && oThemeStyle[0])
- {
- oThemeStyle.attr('data-href', sUrl).attr('data-theme', aData[0]);
- if (oThemeStyle && oThemeStyle[0] && oThemeStyle[0].styleSheet && !Utils.isUnd(oThemeStyle[0].styleSheet.cssText))
- {
- oThemeStyle[0].styleSheet.cssText = aData[1];
- }
- else
- {
- oThemeStyle.text(aData[1]);
- }
- }
-
- self.themeTrigger(Enums.SaveSettingsStep.TrueResult);
- }
-
- }).always(function() {
-
- self.iTimer = window.setTimeout(function () {
- self.themeTrigger(Enums.SaveSettingsStep.Idle);
- }, 1000);
-
- self.oLastAjax = null;
+ _.each(this.identities(), function (oItem) {
+ oIDs[oItem.email()] = oItem['id'];
});
}
- RL.remote().saveSettings(null, {
- 'Theme': sValue
- });
+ oIDs[Data.accountEmail()] = Data.accountEmail();
- }, this);
-}
-
-Utils.addSettingsViewModel(SettingsThemes, 'SettingsThemes', 'SETTINGS_LABELS/LABEL_THEMES_NAME', 'themes');
-
-SettingsThemes.prototype.onBuild = function ()
-{
- var sCurrentTheme = RL.data().theme();
- this.themesObjects(_.map(RL.data().themes(), function (sTheme) {
- return {
- 'name': sTheme,
- 'nameDisplay': Utils.convertThemeName(sTheme),
- 'selected': ko.observable(sTheme === sCurrentTheme),
- 'themePreviewSrc': RL.link().themePreviewLink(sTheme)
- };
- }));
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function SettingsOpenPGP()
-{
- this.openpgpkeys = RL.data().openpgpkeys;
- this.openpgpkeysPublic = RL.data().openpgpkeysPublic;
- this.openpgpkeysPrivate = RL.data().openpgpkeysPrivate;
-
- this.openPgpKeyForDeletion = ko.observable(null).extend({'falseTimeout': 3000}).extend({'toggleSubscribe': [this,
- function (oPrev) {
- if (oPrev)
+ if (oMessage)
+ {
+ switch (sComposeType)
{
- oPrev.deleteAccess(false);
- }
- }, function (oNext) {
- if (oNext)
- {
- oNext.deleteAccess(true);
+ case Enums.ComposeType.Empty:
+ break;
+ case Enums.ComposeType.Reply:
+ case Enums.ComposeType.ReplyAll:
+ case Enums.ComposeType.Forward:
+ case Enums.ComposeType.ForwardAsAttachment:
+ _.find(_.union(oMessage.to, oMessage.cc, oMessage.bcc, oMessage.deliveredTo), fFindHelper);
+ break;
+ case Enums.ComposeType.Draft:
+ _.find(_.union(oMessage.from, oMessage.replyTo), fFindHelper);
+ break;
}
}
- ]});
-}
-Utils.addSettingsViewModel(SettingsOpenPGP, 'SettingsOpenPGP', 'SETTINGS_LABELS/LABEL_OPEN_PGP_NAME', 'openpgp');
-
-SettingsOpenPGP.prototype.addOpenPgpKey = function ()
-{
- kn.showScreenPopup(PopupsAddOpenPgpKeyViewModel);
-};
-
-SettingsOpenPGP.prototype.generateOpenPgpKey = function ()
-{
- kn.showScreenPopup(PopupsGenerateNewOpenPgpKeyViewModel);
-};
-
-SettingsOpenPGP.prototype.viewOpenPgpKey = function (oOpenPgpKey)
-{
- if (oOpenPgpKey)
- {
- kn.showScreenPopup(PopupsViewOpenPgpKeyViewModel, [oOpenPgpKey]);
- }
-};
-
-/**
- * @param {OpenPgpKeyModel} oOpenPgpKeyToRemove
- */
-SettingsOpenPGP.prototype.deleteOpenPgpKey = function (oOpenPgpKeyToRemove)
-{
- if (oOpenPgpKeyToRemove && oOpenPgpKeyToRemove.deleteAccess())
- {
- this.openPgpKeyForDeletion(null);
-
- if (oOpenPgpKeyToRemove && RL.data().openpgpKeyring)
+ if ('' === sResult)
{
- this.openpgpkeys.remove(function (oOpenPgpKey) {
- return oOpenPgpKeyToRemove === oOpenPgpKey;
- });
-
- RL.data().openpgpKeyring[oOpenPgpKeyToRemove.isPrivate ? 'privateKeys' : 'publicKeys']
- .removeForId(oOpenPgpKeyToRemove.guid);
-
- RL.data().openpgpKeyring.store();
-
- RL.reloadOpenPgpKeys();
+ sResult = this.defaultIdentityID();
}
- }
-};
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-/**
- * @constructor
- */
-function AbstractData()
-{
- this.leftPanelDisabled = ko.observable(false);
- this.useKeyboardShortcuts = ko.observable(true);
-
- this.keyScopeReal = ko.observable(Enums.KeyState.All);
- this.keyScopeFake = ko.observable(Enums.KeyState.All);
-
- this.keyScope = ko.computed({
- 'owner': this,
- 'read': function () {
- return this.keyScopeFake();
- },
- 'write': function (sValue) {
-
- if (Enums.KeyState.Menu !== sValue)
- {
- if (Enums.KeyState.Compose === sValue)
- {
- Utils.disableKeyFilter();
- }
- else
- {
- Utils.restoreKeyFilter();
- }
-
- this.keyScopeFake(sValue);
- if (Globals.dropdownVisibility())
- {
- sValue = Enums.KeyState.Menu;
- }
- }
-
- this.keyScopeReal(sValue);
- }
- });
-
- this.keyScopeReal.subscribe(function (sValue) {
-// window.console.log(sValue);
- key.setScope(sValue);
- });
-
- this.leftPanelDisabled.subscribe(function (bValue) {
- RL.pub('left-panel.' + (bValue ? 'off' : 'on'));
- });
-
- Globals.dropdownVisibility.subscribe(function (bValue) {
- if (bValue)
+ if ('' === sResult)
{
- Globals.tooltipTrigger(!Globals.tooltipTrigger());
- this.keyScope(Enums.KeyState.Menu);
+ sResult = Data.accountEmail();
}
- else if (Enums.KeyState.Menu === key.getScope())
+
+ return sResult;
+ };
+
+ PopupsComposeViewModel.prototype.selectIdentity = function (oIdentity)
+ {
+ if (oIdentity)
{
- this.keyScope(this.keyScopeFake());
+ this.currentIdentityID(oIdentity.optValue);
}
- }, this);
+ };
- Utils.initDataConstructorBySettings(this);
-}
-
-AbstractData.prototype.populateDataOnStart = function()
-{
- var
- mLayout = Utils.pInt(RL.settingsGet('Layout')),
- aLanguages = RL.settingsGet('Languages'),
- aThemes = RL.settingsGet('Themes')
- ;
-
- if (Utils.isArray(aLanguages))
+ /**
+ *
+ * @param {boolean=} bHeaderResult = false
+ * @returns {string}
+ */
+ PopupsComposeViewModel.prototype.formattedFrom = function (bHeaderResult)
{
- this.languages(aLanguages);
- }
-
- if (Utils.isArray(aThemes))
- {
- this.themes(aThemes);
- }
-
- this.mainLanguage(RL.settingsGet('Language'));
- this.mainTheme(RL.settingsGet('Theme'));
-
- this.capaAdditionalAccounts(RL.capa(Enums.Capa.AdditionalAccounts));
- this.capaAdditionalIdentities(RL.capa(Enums.Capa.AdditionalIdentities));
- this.capaGravatar(RL.capa(Enums.Capa.Gravatar));
- this.determineUserLanguage(!!RL.settingsGet('DetermineUserLanguage'));
- this.determineUserDomain(!!RL.settingsGet('DetermineUserDomain'));
-
- this.capaThemes(RL.capa(Enums.Capa.Themes));
- this.allowLanguagesOnLogin(!!RL.settingsGet('AllowLanguagesOnLogin'));
- this.allowLanguagesOnSettings(!!RL.settingsGet('AllowLanguagesOnSettings'));
- this.useLocalProxyForExternalImages(!!RL.settingsGet('UseLocalProxyForExternalImages'));
-
- this.editorDefaultType(RL.settingsGet('EditorDefaultType'));
- this.showImages(!!RL.settingsGet('ShowImages'));
- this.contactsAutosave(!!RL.settingsGet('ContactsAutosave'));
- this.interfaceAnimation(RL.settingsGet('InterfaceAnimation'));
-
- this.mainMessagesPerPage(RL.settingsGet('MPP'));
-
- this.desktopNotifications(!!RL.settingsGet('DesktopNotifications'));
- this.useThreads(!!RL.settingsGet('UseThreads'));
- this.replySameFolder(!!RL.settingsGet('ReplySameFolder'));
- this.useCheckboxesInList(!!RL.settingsGet('UseCheckboxesInList'));
-
- this.layout(Enums.Layout.SidePreview);
- if (-1 < Utils.inArray(mLayout, [Enums.Layout.NoPreview, Enums.Layout.SidePreview, Enums.Layout.BottomPreview]))
- {
- this.layout(mLayout);
- }
- this.facebookSupported(!!RL.settingsGet('SupportedFacebookSocial'));
- this.facebookEnable(!!RL.settingsGet('AllowFacebookSocial'));
- this.facebookAppID(RL.settingsGet('FacebookAppID'));
- this.facebookAppSecret(RL.settingsGet('FacebookAppSecret'));
-
- this.twitterEnable(!!RL.settingsGet('AllowTwitterSocial'));
- this.twitterConsumerKey(RL.settingsGet('TwitterConsumerKey'));
- this.twitterConsumerSecret(RL.settingsGet('TwitterConsumerSecret'));
-
- this.googleEnable(!!RL.settingsGet('AllowGoogleSocial'));
- this.googleClientID(RL.settingsGet('GoogleClientID'));
- this.googleClientSecret(RL.settingsGet('GoogleClientSecret'));
- this.googleApiKey(RL.settingsGet('GoogleApiKey'));
-
- this.dropboxEnable(!!RL.settingsGet('AllowDropboxSocial'));
- this.dropboxApiKey(RL.settingsGet('DropboxApiKey'));
-
- this.contactsIsAllowed(!!RL.settingsGet('ContactsIsAllowed'));
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends AbstractData
- */
-function WebMailDataStorage()
-{
- AbstractData.call(this);
-
- var
- fRemoveSystemFolderType = function (observable) {
- return function () {
- var oFolder = RL.cache().getFolderFromCacheList(observable());
- if (oFolder)
- {
- oFolder.type(Enums.FolderType.User);
- }
- };
- },
- fSetSystemFolderType = function (iType) {
- return function (sValue) {
- var oFolder = RL.cache().getFolderFromCacheList(sValue);
- if (oFolder)
- {
- oFolder.type(iType);
- }
- };
- }
- ;
-
- this.devEmail = '';
- this.devPassword = '';
-
- this.accountEmail = ko.observable('');
- this.accountIncLogin = ko.observable('');
- this.accountOutLogin = ko.observable('');
- this.projectHash = ko.observable('');
- this.threading = ko.observable(false);
-
- this.lastFoldersHash = '';
- this.remoteSuggestions = false;
-
- // system folders
- this.sentFolder = ko.observable('');
- this.draftFolder = ko.observable('');
- this.spamFolder = ko.observable('');
- this.trashFolder = ko.observable('');
- this.archiveFolder = ko.observable('');
-
- this.sentFolder.subscribe(fRemoveSystemFolderType(this.sentFolder), this, 'beforeChange');
- this.draftFolder.subscribe(fRemoveSystemFolderType(this.draftFolder), this, 'beforeChange');
- this.spamFolder.subscribe(fRemoveSystemFolderType(this.spamFolder), this, 'beforeChange');
- this.trashFolder.subscribe(fRemoveSystemFolderType(this.trashFolder), this, 'beforeChange');
- this.archiveFolder.subscribe(fRemoveSystemFolderType(this.archiveFolder), this, 'beforeChange');
-
- this.sentFolder.subscribe(fSetSystemFolderType(Enums.FolderType.SentItems), this);
- this.draftFolder.subscribe(fSetSystemFolderType(Enums.FolderType.Draft), this);
- this.spamFolder.subscribe(fSetSystemFolderType(Enums.FolderType.Spam), this);
- this.trashFolder.subscribe(fSetSystemFolderType(Enums.FolderType.Trash), this);
- this.archiveFolder.subscribe(fSetSystemFolderType(Enums.FolderType.Archive), this);
-
- this.draftFolderNotEnabled = ko.computed(function () {
- return '' === this.draftFolder() || Consts.Values.UnuseOptionValue === this.draftFolder();
- }, this);
-
- // personal
- this.displayName = ko.observable('');
- this.signature = ko.observable('');
- this.signatureToAll = ko.observable(false);
- this.replyTo = ko.observable('');
-
- // security
- this.enableTwoFactor = ko.observable(false);
-
- // accounts
- this.accounts = ko.observableArray([]);
- this.accountsLoading = ko.observable(false).extend({'throttle': 100});
-
- // identities
- this.defaultIdentityID = ko.observable('');
- this.identities = ko.observableArray([]);
- this.identitiesLoading = ko.observable(false).extend({'throttle': 100});
-
- // contacts
- this.contactTags = ko.observableArray([]);
- this.contacts = ko.observableArray([]);
- this.contacts.loading = ko.observable(false).extend({'throttle': 200});
- this.contacts.importing = ko.observable(false).extend({'throttle': 200});
- this.contacts.syncing = ko.observable(false).extend({'throttle': 200});
- this.contacts.exportingVcf = ko.observable(false).extend({'throttle': 200});
- this.contacts.exportingCsv = ko.observable(false).extend({'throttle': 200});
-
- this.allowContactsSync = ko.observable(false);
- this.enableContactsSync = ko.observable(false);
- this.contactsSyncUrl = ko.observable('');
- this.contactsSyncUser = ko.observable('');
- this.contactsSyncPass = ko.observable('');
-
- this.allowContactsSync = ko.observable(!!RL.settingsGet('ContactsSyncIsAllowed'));
- this.enableContactsSync = ko.observable(!!RL.settingsGet('EnableContactsSync'));
- this.contactsSyncUrl = ko.observable(RL.settingsGet('ContactsSyncUrl'));
- this.contactsSyncUser = ko.observable(RL.settingsGet('ContactsSyncUser'));
- this.contactsSyncPass = ko.observable(RL.settingsGet('ContactsSyncPassword'));
-
- // folders
- this.namespace = '';
- this.folderList = ko.observableArray([]);
- this.folderList.focused = ko.observable(false);
-
- this.foldersListError = ko.observable('');
-
- this.foldersLoading = ko.observable(false);
- this.foldersCreating = ko.observable(false);
- this.foldersDeleting = ko.observable(false);
- this.foldersRenaming = ko.observable(false);
-
- this.foldersChanging = ko.computed(function () {
var
- bLoading = this.foldersLoading(),
- bCreating = this.foldersCreating(),
- bDeleting = this.foldersDeleting(),
- bRenaming = this.foldersRenaming()
- ;
- return bLoading || bCreating || bDeleting || bRenaming;
- }, this);
-
- this.foldersInboxUnreadCount = ko.observable(0);
-
- this.currentFolder = ko.observable(null).extend({'toggleSubscribe': [null,
- function (oPrev) {
- if (oPrev)
- {
- oPrev.selected(false);
- }
- }, function (oNext) {
- if (oNext)
- {
- oNext.selected(true);
- }
- }
- ]});
-
- this.currentFolderFullNameRaw = ko.computed(function () {
- return this.currentFolder() ? this.currentFolder().fullNameRaw : '';
- }, this);
-
- this.currentFolderFullName = ko.computed(function () {
- return this.currentFolder() ? this.currentFolder().fullName : '';
- }, this);
-
- this.currentFolderFullNameHash = ko.computed(function () {
- return this.currentFolder() ? this.currentFolder().fullNameHash : '';
- }, this);
-
- this.currentFolderName = ko.computed(function () {
- return this.currentFolder() ? this.currentFolder().name() : '';
- }, this);
-
- this.folderListSystemNames = ko.computed(function () {
-
- var
- aList = ['INBOX'],
- aFolders = this.folderList(),
- sSentFolder = this.sentFolder(),
- sDraftFolder = this.draftFolder(),
- sSpamFolder = this.spamFolder(),
- sTrashFolder = this.trashFolder(),
- sArchiveFolder = this.archiveFolder()
+ sDisplayName = Data.displayName(),
+ sEmail = Data.accountEmail()
;
- if (Utils.isArray(aFolders) && 0 < aFolders.length)
- {
- if ('' !== sSentFolder && Consts.Values.UnuseOptionValue !== sSentFolder)
- {
- aList.push(sSentFolder);
- }
- if ('' !== sDraftFolder && Consts.Values.UnuseOptionValue !== sDraftFolder)
- {
- aList.push(sDraftFolder);
- }
- if ('' !== sSpamFolder && Consts.Values.UnuseOptionValue !== sSpamFolder)
- {
- aList.push(sSpamFolder);
- }
- if ('' !== sTrashFolder && Consts.Values.UnuseOptionValue !== sTrashFolder)
- {
- aList.push(sTrashFolder);
- }
- if ('' !== sArchiveFolder && Consts.Values.UnuseOptionValue !== sArchiveFolder)
- {
- aList.push(sArchiveFolder);
- }
- }
-
- return aList;
-
- }, this);
-
- this.folderListSystem = ko.computed(function () {
- return _.compact(_.map(this.folderListSystemNames(), function (sName) {
- return RL.cache().getFolderFromCacheList(sName);
- }));
- }, this);
-
- this.folderMenuForMove = ko.computed(function () {
- return RL.folderListOptionsBuilder(this.folderListSystem(), this.folderList(), [
- this.currentFolderFullNameRaw()
- ], null, null, null, null, function (oItem) {
- return oItem ? oItem.localName() : '';
- });
- }, this);
-
- // message list
- this.staticMessageList = [];
-
- this.messageList = ko.observableArray([]).extend({'rateLimit': 0});
-
- this.messageListCount = ko.observable(0);
- this.messageListSearch = ko.observable('');
- this.messageListPage = ko.observable(1);
-
- this.messageListThreadFolder = ko.observable('');
- this.messageListThreadUids = ko.observableArray([]);
-
- this.messageListThreadFolder.subscribe(function () {
- this.messageListThreadUids([]);
- }, this);
-
- this.messageListEndFolder = ko.observable('');
- this.messageListEndSearch = ko.observable('');
- this.messageListEndPage = ko.observable(1);
-
- this.messageListEndHash = ko.computed(function () {
- return this.messageListEndFolder() + '|' + this.messageListEndSearch() + '|' + this.messageListEndPage();
- }, this);
-
- this.messageListPageCount = ko.computed(function () {
- var iPage = Math.ceil(this.messageListCount() / this.messagesPerPage());
- return 0 >= iPage ? 1 : iPage;
- }, this);
-
- this.mainMessageListSearch = ko.computed({
- 'read': this.messageListSearch,
- 'write': function (sValue) {
- kn.setHash(RL.link().mailBox(
- this.currentFolderFullNameHash(), 1, Utils.trim(sValue.toString())
- ));
- },
- 'owner': this
- });
-
- this.messageListError = ko.observable('');
-
- this.messageListLoading = ko.observable(false);
- this.messageListIsNotCompleted = ko.observable(false);
- this.messageListCompleteLoadingThrottle = ko.observable(false).extend({'throttle': 200});
-
- this.messageListCompleteLoading = ko.computed(function () {
- var
- bOne = this.messageListLoading(),
- bTwo = this.messageListIsNotCompleted()
+ return '' === sDisplayName ? sEmail :
+ ((Utils.isUnd(bHeaderResult) ? false : !!bHeaderResult) ?
+ '"' + Utils.quoteName(sDisplayName) + '" <' + sEmail + '>' :
+ sDisplayName + ' (' + sEmail + ')')
;
- return bOne || bTwo;
- }, this);
+ };
- this.messageListCompleteLoading.subscribe(function (bValue) {
- this.messageListCompleteLoadingThrottle(bValue);
- }, this);
+ PopupsComposeViewModel.prototype.sendMessageResponse = function (sResult, oData)
+ {
+ var
+ bResult = false,
+ sMessage = ''
+ ;
- this.messageList.subscribe(_.debounce(function (aList) {
- _.each(aList, function (oItem) {
- if (oItem.newForAnimation())
- {
- oItem.newForAnimation(false);
- }
- });
- }, 500));
+ this.sending(false);
- // message preview
- this.staticMessageList = new MessageModel();
- this.message = ko.observable(null);
- this.messageLoading = ko.observable(false);
- this.messageLoadingThrottle = ko.observable(false).extend({'throttle': 50});
-
- this.message.focused = ko.observable(false);
-
- this.message.subscribe(function (oMessage) {
- if (!oMessage)
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
{
- this.message.focused(false);
- this.messageFullScreenMode(false);
- this.hideMessageBodies();
-
- if (Enums.Layout.NoPreview === RL.data().layout() &&
- -1 < window.location.hash.indexOf('message-preview'))
+ bResult = true;
+ if (this.modalVisibility())
{
- RL.historyBack();
+ Utils.delegateRun(this, 'closeCommand');
}
}
- else if (Enums.Layout.NoPreview === this.layout())
- {
- this.message.focused(true);
- }
- }, this);
- this.message.focused.subscribe(function (bValue) {
- if (bValue)
+ if (this.modalVisibility() && !bResult)
{
- this.folderList.focused(false);
- this.keyScope(Enums.KeyState.MessageView);
- }
- else if (Enums.KeyState.MessageView === RL.data().keyScope())
- {
- if (Enums.Layout.NoPreview === RL.data().layout() && this.message())
+ if (oData && Enums.Notification.CantSaveMessage === oData.ErrorCode)
{
- this.keyScope(Enums.KeyState.MessageView);
+ this.sendSuccessButSaveError(true);
+ window.alert(Utils.trim(Utils.i18n('COMPOSE/SAVED_ERROR_ON_SEND')));
}
else
{
- this.keyScope(Enums.KeyState.MessageList);
+ sMessage = Utils.getNotification(oData && oData.ErrorCode ? oData.ErrorCode : Enums.Notification.CantSendMessage,
+ oData && oData.ErrorMessage ? oData.ErrorMessage : '');
+
+ this.sendError(true);
+ window.alert(sMessage || Utils.getNotification(Enums.Notification.CantSendMessage));
}
}
- }, this);
- this.folderList.focused.subscribe(function (bValue) {
- if (bValue)
- {
- RL.data().keyScope(Enums.KeyState.FolderList);
- }
- else if (Enums.KeyState.FolderList === RL.data().keyScope())
- {
- RL.data().keyScope(Enums.KeyState.MessageList);
- }
- });
+ this.reloadDraftFolder();
+ };
- this.messageLoading.subscribe(function (bValue) {
- this.messageLoadingThrottle(bValue);
- }, this);
-
- this.messageFullScreenMode = ko.observable(false);
-
- this.messageError = ko.observable('');
-
- this.messagesBodiesDom = ko.observable(null);
-
- this.messagesBodiesDom.subscribe(function (oDom) {
- if (oDom && !(oDom instanceof jQuery))
- {
- this.messagesBodiesDom($(oDom));
- }
- }, this);
-
- this.messageActiveDom = ko.observable(null);
-
- this.isMessageSelected = ko.computed(function () {
- return null !== this.message();
- }, this);
-
- this.currentMessage = ko.observable(null);
-
- this.messageListChecked = ko.computed(function () {
- return _.filter(this.messageList(), function (oItem) {
- return oItem.checked();
- });
- }, this).extend({'rateLimit': 0});
-
- this.hasCheckedMessages = ko.computed(function () {
- return 0 < this.messageListChecked().length;
- }, this).extend({'rateLimit': 0});
-
- this.messageListCheckedOrSelected = ko.computed(function () {
-
- var
- aChecked = this.messageListChecked(),
- oSelectedMessage = this.currentMessage()
- ;
-
- return _.union(aChecked, oSelectedMessage ? [oSelectedMessage] : []);
-
- }, this);
-
- this.messageListCheckedOrSelectedUidsWithSubMails = ko.computed(function () {
- var aList = [];
- _.each(this.messageListCheckedOrSelected(), function (oMessage) {
- if (oMessage)
- {
- aList.push(oMessage.uid);
- if (0 < oMessage.threadsLen() && 0 === oMessage.parentUid() && oMessage.lastInCollapsedThread())
- {
- aList = _.union(aList, oMessage.threads());
- }
- }
- });
- return aList;
- }, this);
-
- // quota
- this.userQuota = ko.observable(0);
- this.userUsageSize = ko.observable(0);
- this.userUsageProc = ko.computed(function () {
-
- var
- iQuota = this.userQuota(),
- iUsed = this.userUsageSize()
- ;
-
- return 0 < iQuota ? Math.ceil((iUsed / iQuota) * 100) : 0;
-
- }, this);
-
- // other
- this.capaOpenPGP = ko.observable(false);
- this.openpgpkeys = ko.observableArray([]);
- this.openpgpKeyring = null;
-
- this.openpgpkeysPublic = this.openpgpkeys.filter(function (oItem) {
- return !!(oItem && !oItem.isPrivate);
- });
-
- this.openpgpkeysPrivate = this.openpgpkeys.filter(function (oItem) {
- return !!(oItem && oItem.isPrivate);
- });
-
- // google
- this.googleActions = ko.observable(false);
- this.googleLoggined = ko.observable(false);
- this.googleUserName = ko.observable('');
-
- // facebook
- this.facebookActions = ko.observable(false);
- this.facebookLoggined = ko.observable(false);
- this.facebookUserName = ko.observable('');
-
- // twitter
- this.twitterActions = ko.observable(false);
- this.twitterLoggined = ko.observable(false);
- this.twitterUserName = ko.observable('');
-
- this.customThemeType = ko.observable(Enums.CustomThemeType.Light);
-
- this.purgeMessageBodyCacheThrottle = _.throttle(this.purgeMessageBodyCache, 1000 * 30);
-}
-
-_.extend(WebMailDataStorage.prototype, AbstractData.prototype);
-
-WebMailDataStorage.prototype.purgeMessageBodyCache = function()
-{
- var
- iCount = 0,
- oMessagesBodiesDom = null,
- iEnd = Globals.iMessageBodyCacheCount - Consts.Values.MessageBodyCacheLimit
- ;
-
- if (0 < iEnd)
+ PopupsComposeViewModel.prototype.saveMessageResponse = function (sResult, oData)
{
- oMessagesBodiesDom = this.messagesBodiesDom();
- if (oMessagesBodiesDom)
- {
- oMessagesBodiesDom.find('.rl-cache-class').each(function () {
- var oItem = $(this);
- if (iEnd > oItem.data('rl-cache-count'))
- {
- oItem.addClass('rl-cache-purge');
- iCount++;
- }
- });
+ var
+ bResult = false,
+ oMessage = null
+ ;
- if (0 < iCount)
+ this.saving(false);
+
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ {
+ if (oData.Result.NewFolder && oData.Result.NewUid)
+ {
+ if (this.bFromDraft)
+ {
+ oMessage = Data.message();
+ if (oMessage && this.draftFolder() === oMessage.folderFullNameRaw && this.draftUid() === oMessage.uid)
+ {
+ Data.message(null);
+ }
+ }
+
+ this.draftFolder(oData.Result.NewFolder);
+ this.draftUid(oData.Result.NewUid);
+
+ if (this.modalVisibility())
+ {
+ this.savedTime(window.Math.round((new window.Date()).getTime() / 1000));
+
+ this.savedOrSendingText(
+ 0 < this.savedTime() ? Utils.i18n('COMPOSE/SAVED_TIME', {
+ 'TIME': moment.unix(this.savedTime() - 1).format('LT')
+ }) : ''
+ );
+
+ bResult = true;
+
+ if (this.bFromDraft)
+ {
+ Cache.setFolderHash(this.draftFolder(), '');
+ }
+ }
+ }
+ }
+
+ if (!this.modalVisibility() && !bResult)
+ {
+ this.savedError(true);
+ this.savedOrSendingText(Utils.getNotification(Enums.Notification.CantSaveMessage));
+ }
+
+ this.reloadDraftFolder();
+ };
+
+ PopupsComposeViewModel.prototype.onHide = function ()
+ {
+ this.reset();
+ kn.routeOn();
+ };
+
+ /**
+ * @param {string} sSignature
+ * @param {string=} sFrom
+ * @param {string=} sData
+ * @param {string=} sComposeType
+ * @return {string}
+ */
+ PopupsComposeViewModel.prototype.convertSignature = function (sSignature, sFrom, sData, sComposeType)
+ {
+ var bHtml = false, bData = false;
+ if ('' !== sSignature)
+ {
+ if (':HTML:' === sSignature.substr(0, 6))
+ {
+ bHtml = true;
+ sSignature = sSignature.substr(6);
+ }
+
+ sSignature = sSignature.replace(/[\r]/, '');
+
+ sFrom = Utils.pString(sFrom);
+ if ('' !== sFrom)
+ {
+ sSignature = sSignature.replace(/{{FROM}}/, sFrom);
+ }
+
+ sSignature = sSignature.replace(/[\s]{1,2}{{FROM}}/, '{{FROM}}');
+
+ sSignature = sSignature.replace(/{{FROM}}/, '');
+ sSignature = sSignature.replace(/{{DATE}}/, moment().format('llll'));
+
+ if (sData && Enums.ComposeType.Empty === sComposeType &&
+ -1 < sSignature.indexOf('{{DATA}}'))
+ {
+ bData = true;
+ sSignature = sSignature.replace('{{DATA}}', sData);
+ }
+
+ sSignature = sSignature.replace(/{{DATA}}/, '');
+
+ if (!bHtml)
+ {
+ sSignature = Utils.convertPlainTextToHtml(sSignature);
+ }
+ }
+
+ if (sData && !bData)
+ {
+ switch (sComposeType)
+ {
+ case Enums.ComposeType.Empty:
+ sSignature = sData + '
' + sSignature;
+ break;
+ default:
+ sSignature = sSignature + '
' + sData;
+ break;
+ }
+ }
+
+ return sSignature;
+ };
+
+ PopupsComposeViewModel.prototype.editor = function (fOnInit)
+ {
+ if (fOnInit)
+ {
+ var self = this;
+ if (!this.oEditor && this.composeEditorArea())
{
_.delay(function () {
- oMessagesBodiesDom.find('.rl-cache-purge').remove();
+ self.oEditor = new NewHtmlEditorWrapper(self.composeEditorArea(), null, function () {
+ fOnInit(self.oEditor);
+ }, function (bHtml) {
+ self.isHtml(!!bHtml);
+ });
}, 300);
}
+ else if (this.oEditor)
+ {
+ fOnInit(this.oEditor);
+ }
}
- }
-};
+ };
-WebMailDataStorage.prototype.populateDataOnStart = function()
-{
- AbstractData.prototype.populateDataOnStart.call(this);
-
- this.accountEmail(RL.settingsGet('Email'));
- this.accountIncLogin(RL.settingsGet('IncLogin'));
- this.accountOutLogin(RL.settingsGet('OutLogin'));
- this.projectHash(RL.settingsGet('ProjectHash'));
-
- this.defaultIdentityID(RL.settingsGet('DefaultIdentityID'));
-
- this.displayName(RL.settingsGet('DisplayName'));
- this.replyTo(RL.settingsGet('ReplyTo'));
- this.signature(RL.settingsGet('Signature'));
- this.signatureToAll(!!RL.settingsGet('SignatureToAll'));
- this.enableTwoFactor(!!RL.settingsGet('EnableTwoFactor'));
-
- this.lastFoldersHash = RL.local().get(Enums.ClientSideKeyName.FoldersLashHash) || '';
-
- this.remoteSuggestions = !!RL.settingsGet('RemoteSuggestions');
-
- this.devEmail = RL.settingsGet('DevEmail');
- this.devPassword = RL.settingsGet('DevPassword');
-};
-
-WebMailDataStorage.prototype.initUidNextAndNewMessages = function (sFolder, sUidNext, aNewMessages)
-{
- if ('INBOX' === sFolder && Utils.isNormal(sUidNext) && sUidNext !== '')
+ /**
+ * @param {string=} sType = Enums.ComposeType.Empty
+ * @param {?MessageModel|Array=} oMessageOrArray = null
+ * @param {Array=} aToEmails = null
+ * @param {string=} sCustomSubject = null
+ * @param {string=} sCustomPlainText = null
+ */
+ PopupsComposeViewModel.prototype.onShow = function (sType, oMessageOrArray, aToEmails, sCustomSubject, sCustomPlainText)
{
- if (Utils.isArray(aNewMessages) && 0 < aNewMessages.length)
- {
- var
- oCache = RL.cache(),
- iIndex = 0,
- iLen = aNewMessages.length,
- fNotificationHelper = function (sImageSrc, sTitle, sText)
+ kn.routeOff();
+
+ var
+ self = this,
+ sFrom = '',
+ sTo = '',
+ sCc = '',
+ sDate = '',
+ sSubject = '',
+ oText = null,
+ oSubText = null,
+ sText = '',
+ sReplyTitle = '',
+ aResplyAllParts = [],
+ oExcludeEmail = {},
+ mEmail = Data.accountEmail(),
+ sSignature = Data.signature(),
+ bSignatureToAll = Data.signatureToAll(),
+ aDownloads = [],
+ aDraftInfo = null,
+ oMessage = null,
+ sComposeType = sType || Enums.ComposeType.Empty,
+ fEmailArrayToStringLineHelper = function (aList, bFriendly) {
+
+ var
+ iIndex = 0,
+ iLen = aList.length,
+ aResult = []
+ ;
+
+ for (; iIndex < iLen; iIndex++)
{
- var oNotification = null;
- if (NotificationClass && RL.data().useDesktopNotifications())
+ aResult.push(aList[iIndex].toLine(!!bFriendly));
+ }
+
+ return aResult.join(', ');
+ }
+ ;
+
+ oMessageOrArray = oMessageOrArray || null;
+ if (oMessageOrArray && Utils.isNormal(oMessageOrArray))
+ {
+ oMessage = Utils.isArray(oMessageOrArray) && 1 === oMessageOrArray.length ? oMessageOrArray[0] :
+ (!Utils.isArray(oMessageOrArray) ? oMessageOrArray : null);
+ }
+
+ if (null !== mEmail)
+ {
+ oExcludeEmail[mEmail] = true;
+ }
+
+ this.currentIdentityID(this.findIdentityIdByMessage(sComposeType, oMessage));
+ this.reset();
+
+ if (Utils.isNonEmptyArray(aToEmails))
+ {
+ this.to(fEmailArrayToStringLineHelper(aToEmails));
+ }
+
+ if ('' !== sComposeType && oMessage)
+ {
+ sDate = oMessage.fullFormatDateValue();
+ sSubject = oMessage.subject();
+ aDraftInfo = oMessage.aDraftInfo;
+
+ oText = $(oMessage.body).clone();
+ Utils.removeBlockquoteSwitcher(oText);
+
+ oSubText = oText.find('[data-html-editor-font-wrapper=true]');
+ sText = oSubText && oSubText[0] ? oSubText.html() : oText.html();
+
+ switch (sComposeType)
+ {
+ case Enums.ComposeType.Empty:
+ break;
+
+ case Enums.ComposeType.Reply:
+ this.to(fEmailArrayToStringLineHelper(oMessage.replyEmails(oExcludeEmail)));
+ this.subject(Utils.replySubjectAdd('Re', sSubject));
+ this.prepearMessageAttachments(oMessage, sComposeType);
+ this.aDraftInfo = ['reply', oMessage.uid, oMessage.folderFullNameRaw];
+ this.sInReplyTo = oMessage.sMessageId;
+ this.sReferences = Utils.trim(this.sInReplyTo + ' ' + oMessage.sReferences);
+ break;
+
+ case Enums.ComposeType.ReplyAll:
+ aResplyAllParts = oMessage.replyAllEmails(oExcludeEmail);
+ this.to(fEmailArrayToStringLineHelper(aResplyAllParts[0]));
+ this.cc(fEmailArrayToStringLineHelper(aResplyAllParts[1]));
+ this.subject(Utils.replySubjectAdd('Re', sSubject));
+ this.prepearMessageAttachments(oMessage, sComposeType);
+ this.aDraftInfo = ['reply', oMessage.uid, oMessage.folderFullNameRaw];
+ this.sInReplyTo = oMessage.sMessageId;
+ this.sReferences = Utils.trim(this.sInReplyTo + ' ' + oMessage.references());
+ break;
+
+ case Enums.ComposeType.Forward:
+ this.subject(Utils.replySubjectAdd('Fwd', sSubject));
+ this.prepearMessageAttachments(oMessage, sComposeType);
+ this.aDraftInfo = ['forward', oMessage.uid, oMessage.folderFullNameRaw];
+ this.sInReplyTo = oMessage.sMessageId;
+ this.sReferences = Utils.trim(this.sInReplyTo + ' ' + oMessage.sReferences);
+ break;
+
+ case Enums.ComposeType.ForwardAsAttachment:
+ this.subject(Utils.replySubjectAdd('Fwd', sSubject));
+ this.prepearMessageAttachments(oMessage, sComposeType);
+ this.aDraftInfo = ['forward', oMessage.uid, oMessage.folderFullNameRaw];
+ this.sInReplyTo = oMessage.sMessageId;
+ this.sReferences = Utils.trim(this.sInReplyTo + ' ' + oMessage.sReferences);
+ break;
+
+ case Enums.ComposeType.Draft:
+ this.to(fEmailArrayToStringLineHelper(oMessage.to));
+ this.cc(fEmailArrayToStringLineHelper(oMessage.cc));
+ this.bcc(fEmailArrayToStringLineHelper(oMessage.bcc));
+
+ this.bFromDraft = true;
+
+ this.draftFolder(oMessage.folderFullNameRaw);
+ this.draftUid(oMessage.uid);
+
+ this.subject(sSubject);
+ this.prepearMessageAttachments(oMessage, sComposeType);
+
+ this.aDraftInfo = Utils.isNonEmptyArray(aDraftInfo) && 3 === aDraftInfo.length ? aDraftInfo : null;
+ this.sInReplyTo = oMessage.sInReplyTo;
+ this.sReferences = oMessage.sReferences;
+ break;
+
+ case Enums.ComposeType.EditAsNew:
+ this.to(fEmailArrayToStringLineHelper(oMessage.to));
+ this.cc(fEmailArrayToStringLineHelper(oMessage.cc));
+ this.bcc(fEmailArrayToStringLineHelper(oMessage.bcc));
+
+ this.subject(sSubject);
+ this.prepearMessageAttachments(oMessage, sComposeType);
+
+ this.aDraftInfo = Utils.isNonEmptyArray(aDraftInfo) && 3 === aDraftInfo.length ? aDraftInfo : null;
+ this.sInReplyTo = oMessage.sInReplyTo;
+ this.sReferences = oMessage.sReferences;
+ break;
+ }
+
+ switch (sComposeType)
+ {
+ case Enums.ComposeType.Reply:
+ case Enums.ComposeType.ReplyAll:
+ sFrom = oMessage.fromToLine(false, true);
+ sReplyTitle = Utils.i18n('COMPOSE/REPLY_MESSAGE_TITLE', {
+ 'DATETIME': sDate,
+ 'EMAIL': sFrom
+ });
+
+ sText = '
' + sReplyTitle + ':' +
+ '' + sText + '
';
+
+ break;
+
+ case Enums.ComposeType.Forward:
+ sFrom = oMessage.fromToLine(false, true);
+ sTo = oMessage.toToLine(false, true);
+ sCc = oMessage.ccToLine(false, true);
+ sText = '
' + Utils.i18n('COMPOSE/FORWARD_MESSAGE_TOP_TITLE') +
+ '
' + Utils.i18n('COMPOSE/FORWARD_MESSAGE_TOP_FROM') + ': ' + sFrom +
+ '
' + Utils.i18n('COMPOSE/FORWARD_MESSAGE_TOP_TO') + ': ' + sTo +
+ (0 < sCc.length ? '
' + Utils.i18n('COMPOSE/FORWARD_MESSAGE_TOP_CC') + ': ' + sCc : '') +
+ '
' + Utils.i18n('COMPOSE/FORWARD_MESSAGE_TOP_SENT') + ': ' + Utils.encodeHtml(sDate) +
+ '
' + Utils.i18n('COMPOSE/FORWARD_MESSAGE_TOP_SUBJECT') + ': ' + Utils.encodeHtml(sSubject) +
+ '
' + sText;
+ break;
+ case Enums.ComposeType.ForwardAsAttachment:
+ sText = '';
+ break;
+ }
+
+ if (bSignatureToAll && '' !== sSignature &&
+ Enums.ComposeType.EditAsNew !== sComposeType && Enums.ComposeType.Draft !== sComposeType)
+ {
+ sText = this.convertSignature(sSignature, fEmailArrayToStringLineHelper(oMessage.from, true), sText, sComposeType);
+ }
+
+ this.editor(function (oEditor) {
+ oEditor.setHtml(sText, false);
+ if (!oMessage.isHtml())
+ {
+ oEditor.modeToggle(false);
+ }
+ });
+ }
+ else if (Enums.ComposeType.Empty === sComposeType)
+ {
+ this.subject(Utils.isNormal(sCustomSubject) ? '' + sCustomSubject : '');
+
+ sText = Utils.isNormal(sCustomPlainText) ? '' + sCustomPlainText : '';
+ if (bSignatureToAll && '' !== sSignature)
+ {
+ sText = this.convertSignature(sSignature, '',
+ Utils.convertPlainTextToHtml(sText), sComposeType);
+ }
+
+ this.editor(function (oEditor) {
+ oEditor.setHtml(sText, false);
+ if (Enums.EditorDefaultType.Html !== Data.editorDefaultType())
+ {
+ oEditor.modeToggle(false);
+ }
+ });
+ }
+ else if (Utils.isNonEmptyArray(oMessageOrArray))
+ {
+ _.each(oMessageOrArray, function (oMessage) {
+ self.addMessageAsAttachment(oMessage);
+ });
+ }
+
+ aDownloads = this.getAttachmentsDownloadsForUpload();
+ if (Utils.isNonEmptyArray(aDownloads))
+ {
+ Remote.messageUploadAttachments(function (sResult, oData) {
+
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ {
+ var
+ oAttachment = null,
+ sTempName = ''
+ ;
+
+ if (!self.viewModelVisibility())
{
- oNotification = new NotificationClass(sTitle, {
- 'body': sText,
- 'icon': sImageSrc
- });
-
- if (oNotification)
+ for (sTempName in oData.Result)
{
- if (oNotification.show)
+ if (oData.Result.hasOwnProperty(sTempName))
{
- oNotification.show();
+ oAttachment = self.getAttachmentById(oData.Result[sTempName]);
+ if (oAttachment)
+ {
+ oAttachment.tempName(sTempName);
+ }
}
-
- window.setTimeout((function (oLocalNotifications) {
- return function () {
- if (oLocalNotifications.cancel)
- {
- oLocalNotifications.cancel();
- }
- else if (oLocalNotifications.close)
- {
- oLocalNotifications.close();
- }
- };
- }(oNotification)), 7000);
}
}
}
+ else
+ {
+ self.setMessageAttachmentFailedDowbloadText();
+ }
+
+ }, aDownloads);
+ }
+
+ this.triggerForResize();
+ };
+
+ PopupsComposeViewModel.prototype.onFocus = function ()
+ {
+ if ('' === this.to())
+ {
+ this.to.focusTrigger(!this.to.focusTrigger());
+ }
+ else if (this.oEditor)
+ {
+ this.oEditor.focus();
+ }
+
+ this.triggerForResize();
+ };
+
+ PopupsComposeViewModel.prototype.editorResize = function ()
+ {
+ if (this.oEditor)
+ {
+ this.oEditor.resize();
+ }
+ };
+
+ PopupsComposeViewModel.prototype.tryToClosePopup = function ()
+ {
+ var self = this;
+ if (!kn.isPopupVisible(PopupsAskViewModel))
+ {
+ kn.showScreenPopup(PopupsAskViewModel, [Utils.i18n('POPUPS_ASK/DESC_WANT_CLOSE_THIS_WINDOW'), function () {
+ if (self.modalVisibility())
+ {
+ Utils.delegateRun(self, 'closeCommand');
+ }
+ }]);
+ }
+ };
+
+ PopupsComposeViewModel.prototype.onBuild = function ()
+ {
+ this.initUploader();
+
+ var
+ self = this,
+ oScript = null
+ ;
+
+ key('ctrl+q, command+q', Enums.KeyState.Compose, function () {
+ self.identitiesDropdownTrigger(true);
+ return false;
+ });
+
+ key('ctrl+s, command+s', Enums.KeyState.Compose, function () {
+ self.saveCommand();
+ return false;
+ });
+
+ key('ctrl+enter, command+enter', Enums.KeyState.Compose, function () {
+ self.sendCommand();
+ return false;
+ });
+
+ key('esc', Enums.KeyState.Compose, function () {
+ if (self.modalVisibility())
+ {
+ self.tryToClosePopup();
+ }
+ return false;
+ });
+
+ $window.on('resize', function () {
+ self.triggerForResize();
+ });
+
+ if (this.dropboxEnabled())
+ {
+ oScript = document.createElement('script');
+ oScript.type = 'text/javascript';
+ oScript.src = 'https://www.dropbox.com/static/api/1/dropins.js';
+ $(oScript).attr('id', 'dropboxjs').attr('data-app-key', AppSettings.settingsGet('DropboxApiKey'));
+
+ document.body.appendChild(oScript);
+ }
+
+ if (this.driveEnabled())
+ {
+ $.getScript('https://apis.google.com/js/api.js', function () {
+ if (window.gapi)
+ {
+ self.driveVisible(true);
+ }
+ });
+ }
+ };
+
+ PopupsComposeViewModel.prototype.driveCallback = function (sAccessToken, oData)
+ {
+ if (oData && window.XMLHttpRequest && window.google &&
+ oData[window.google.picker.Response.ACTION] === window.google.picker.Action.PICKED &&
+ oData[window.google.picker.Response.DOCUMENTS] && oData[window.google.picker.Response.DOCUMENTS][0] &&
+ oData[window.google.picker.Response.DOCUMENTS][0]['id'])
+ {
+ var
+ self = this,
+ oRequest = new window.XMLHttpRequest()
;
- _.each(aNewMessages, function (oItem) {
- oCache.addNewMessageCache(sFolder, oItem.Uid);
+ oRequest.open('GET', 'https://www.googleapis.com/drive/v2/files/' + oData[window.google.picker.Response.DOCUMENTS][0]['id']);
+ oRequest.setRequestHeader('Authorization', 'Bearer ' + sAccessToken);
+ oRequest.addEventListener('load', function() {
+ if (oRequest && oRequest.responseText)
+ {
+ var oItem = JSON.parse(oRequest.responseText), fExport = function (oItem, sMimeType, sExt) {
+ if (oItem && oItem['exportLinks'])
+ {
+ if (oItem['exportLinks'][sMimeType])
+ {
+ oItem['downloadUrl'] = oItem['exportLinks'][sMimeType];
+ oItem['title'] = oItem['title'] + '.' + sExt;
+ oItem['mimeType'] = sMimeType;
+ }
+ else if (oItem['exportLinks']['application/pdf'])
+ {
+ oItem['downloadUrl'] = oItem['exportLinks']['application/pdf'];
+ oItem['title'] = oItem['title'] + '.pdf';
+ oItem['mimeType'] = 'application/pdf';
+ }
+ }
+ };
+
+ if (oItem && !oItem['downloadUrl'] && oItem['mimeType'] && oItem['exportLinks'])
+ {
+ switch (oItem['mimeType'].toString().toLowerCase())
+ {
+ case 'application/vnd.google-apps.document':
+ fExport(oItem, 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'docx');
+ break;
+ case 'application/vnd.google-apps.spreadsheet':
+ fExport(oItem, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'xlsx');
+ break;
+ case 'application/vnd.google-apps.drawing':
+ fExport(oItem, 'image/png', 'png');
+ break;
+ case 'application/vnd.google-apps.presentation':
+ fExport(oItem, 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'pptx');
+ break;
+ default:
+ fExport(oItem, 'application/pdf', 'pdf');
+ break;
+ }
+ }
+
+ if (oItem && oItem['downloadUrl'])
+ {
+ self.addDriveAttachment(oItem, sAccessToken);
+ }
+ }
});
- if (3 < iLen)
+ oRequest.send();
+ }
+ };
+
+ PopupsComposeViewModel.prototype.driveCreatePiker = function (oOauthToken)
+ {
+ if (window.gapi && oOauthToken && oOauthToken.access_token)
+ {
+ var self = this;
+
+ window.gapi.load('picker', {'callback': function () {
+
+ if (window.google && window.google.picker)
+ {
+ var drivePicker = new window.google.picker.PickerBuilder()
+ .addView(
+ new window.google.picker.DocsView()
+ .setIncludeFolders(true)
+ )
+ .setAppId(AppSettings.settingsGet('GoogleClientID'))
+ .setOAuthToken(oOauthToken.access_token)
+ .setCallback(_.bind(self.driveCallback, self, oOauthToken.access_token))
+ .enableFeature(window.google.picker.Feature.NAV_HIDDEN)
+ .build()
+ ;
+
+ drivePicker.setVisible(true);
+ }
+ }});
+ }
+ };
+
+ PopupsComposeViewModel.prototype.driveOpenPopup = function ()
+ {
+ if (window.gapi)
+ {
+ var self = this;
+
+ window.gapi.load('auth', {'callback': function () {
+
+ var oAuthToken = window.gapi.auth.getToken();
+ if (!oAuthToken)
+ {
+ window.gapi.auth.authorize({
+ 'client_id': AppSettings.settingsGet('GoogleClientID'),
+ 'scope': 'https://www.googleapis.com/auth/drive.readonly',
+ 'immediate': true
+ }, function (oAuthResult) {
+ if (oAuthResult && !oAuthResult.error)
+ {
+ var oAuthToken = window.gapi.auth.getToken();
+ if (oAuthToken)
+ {
+ self.driveCreatePiker(oAuthToken);
+ }
+ }
+ else
+ {
+ window.gapi.auth.authorize({
+ 'client_id': AppSettings.settingsGet('GoogleClientID'),
+ 'scope': 'https://www.googleapis.com/auth/drive.readonly',
+ 'immediate': false
+ }, function (oAuthResult) {
+ if (oAuthResult && !oAuthResult.error)
+ {
+ var oAuthToken = window.gapi.auth.getToken();
+ if (oAuthToken)
+ {
+ self.driveCreatePiker(oAuthToken);
+ }
+ }
+ });
+ }
+ });
+ }
+ else
+ {
+ self.driveCreatePiker(oAuthToken);
+ }
+ }});
+ }
+ };
+
+ /**
+ * @param {string} sId
+ * @return {?Object}
+ */
+ PopupsComposeViewModel.prototype.getAttachmentById = function (sId)
+ {
+ var
+ aAttachments = this.attachments(),
+ iIndex = 0,
+ iLen = aAttachments.length
+ ;
+
+ for (; iIndex < iLen; iIndex++)
+ {
+ if (aAttachments[iIndex] && sId === aAttachments[iIndex].id)
{
- fNotificationHelper(
- RL.link().notificationMailIcon(),
- RL.data().accountEmail(),
- Utils.i18n('MESSAGE_LIST/NEW_MESSAGE_NOTIFICATION', {
- 'COUNT': iLen
- })
- );
+ return aAttachments[iIndex];
+ }
+ }
+
+ return null;
+ };
+
+ PopupsComposeViewModel.prototype.initUploader = function ()
+ {
+ if (this.composeUploaderButton())
+ {
+ var
+ oUploadCache = {},
+ iAttachmentSizeLimit = Utils.pInt(AppSettings.settingsGet('AttachmentLimit')),
+ oJua = new Jua({
+ 'action': LinkBuilder.upload(),
+ 'name': 'uploader',
+ 'queueSize': 2,
+ 'multipleSizeLimit': 50,
+ 'disableFolderDragAndDrop': false,
+ 'clickElement': this.composeUploaderButton(),
+ 'dragAndDropElement': this.composeUploaderDropPlace()
+ })
+ ;
+
+ if (oJua)
+ {
+ oJua
+ // .on('onLimitReached', function (iLimit) {
+ // alert(iLimit);
+ // })
+ .on('onDragEnter', _.bind(function () {
+ this.dragAndDropOver(true);
+ }, this))
+ .on('onDragLeave', _.bind(function () {
+ this.dragAndDropOver(false);
+ }, this))
+ .on('onBodyDragEnter', _.bind(function () {
+ this.dragAndDropVisible(true);
+ }, this))
+ .on('onBodyDragLeave', _.bind(function () {
+ this.dragAndDropVisible(false);
+ }, this))
+ .on('onProgress', _.bind(function (sId, iLoaded, iTotal) {
+ var oItem = null;
+ if (Utils.isUnd(oUploadCache[sId]))
+ {
+ oItem = this.getAttachmentById(sId);
+ if (oItem)
+ {
+ oUploadCache[sId] = oItem;
+ }
+ }
+ else
+ {
+ oItem = oUploadCache[sId];
+ }
+
+ if (oItem)
+ {
+ oItem.progress(' - ' + Math.floor(iLoaded / iTotal * 100) + '%');
+ }
+
+ }, this))
+ .on('onSelect', _.bind(function (sId, oData) {
+
+ this.dragAndDropOver(false);
+
+ var
+ that = this,
+ sFileName = Utils.isUnd(oData.FileName) ? '' : oData.FileName.toString(),
+ mSize = Utils.isNormal(oData.Size) ? Utils.pInt(oData.Size) : null,
+ oAttachment = new ComposeAttachmentModel(sId, sFileName, mSize)
+ ;
+
+ oAttachment.cancel = (function (sId) {
+
+ return function () {
+ that.attachments.remove(function (oItem) {
+ return oItem && oItem.id === sId;
+ });
+
+ if (oJua)
+ {
+ oJua.cancel(sId);
+ }
+ };
+
+ }(sId));
+
+ this.attachments.push(oAttachment);
+
+ if (0 < mSize && 0 < iAttachmentSizeLimit && iAttachmentSizeLimit < mSize)
+ {
+ oAttachment.error(Utils.i18n('UPLOAD/ERROR_FILE_IS_TOO_BIG'));
+ return false;
+ }
+
+ return true;
+
+ }, this))
+ .on('onStart', _.bind(function (sId) {
+
+ var
+ oItem = null
+ ;
+
+ if (Utils.isUnd(oUploadCache[sId]))
+ {
+ oItem = this.getAttachmentById(sId);
+ if (oItem)
+ {
+ oUploadCache[sId] = oItem;
+ }
+ }
+ else
+ {
+ oItem = oUploadCache[sId];
+ }
+
+ if (oItem)
+ {
+ oItem.waiting(false);
+ oItem.uploading(true);
+ }
+
+ }, this))
+ .on('onComplete', _.bind(function (sId, bResult, oData) {
+
+ var
+ sError = '',
+ mErrorCode = null,
+ oAttachmentJson = null,
+ oAttachment = this.getAttachmentById(sId)
+ ;
+
+ oAttachmentJson = bResult && oData && oData.Result && oData.Result.Attachment ? oData.Result.Attachment : null;
+ mErrorCode = oData && oData.Result && oData.Result.ErrorCode ? oData.Result.ErrorCode : null;
+
+ if (null !== mErrorCode)
+ {
+ sError = Utils.getUploadErrorDescByCode(mErrorCode);
+ }
+ else if (!oAttachmentJson)
+ {
+ sError = Utils.i18n('UPLOAD/ERROR_UNKNOWN');
+ }
+
+ if (oAttachment)
+ {
+ if ('' !== sError && 0 < sError.length)
+ {
+ oAttachment
+ .waiting(false)
+ .uploading(false)
+ .error(sError)
+ ;
+ }
+ else if (oAttachmentJson)
+ {
+ oAttachment
+ .waiting(false)
+ .uploading(false)
+ ;
+
+ oAttachment.initByUploadJson(oAttachmentJson);
+ }
+
+ if (Utils.isUnd(oUploadCache[sId]))
+ {
+ delete (oUploadCache[sId]);
+ }
+ }
+
+ }, this))
+ ;
+
+ this
+ .addAttachmentEnabled(true)
+ .dragAndDropEnabled(oJua.isDragAndDropSupported())
+ ;
+ }
+ else
+ {
+ this
+ .addAttachmentEnabled(false)
+ .dragAndDropEnabled(false)
+ ;
+ }
+ }
+ };
+
+ /**
+ * @return {Object}
+ */
+ PopupsComposeViewModel.prototype.prepearAttachmentsForSendOrSave = function ()
+ {
+ var oResult = {};
+ _.each(this.attachmentsInReady(), function (oItem) {
+ if (oItem && '' !== oItem.tempName() && oItem.enabled())
+ {
+ oResult[oItem.tempName()] = [
+ oItem.fileName(),
+ oItem.isInline ? '1' : '0',
+ oItem.CID,
+ oItem.contentLocation
+ ];
+ }
+ });
+
+ return oResult;
+ };
+
+ /**
+ * @param {MessageModel} oMessage
+ */
+ PopupsComposeViewModel.prototype.addMessageAsAttachment = function (oMessage)
+ {
+ if (oMessage)
+ {
+ var
+ self = this,
+ oAttachment = null,
+ sTemp = oMessage.subject(),
+ fCancelFunc = function (sId) {
+ return function () {
+ self.attachments.remove(function (oItem) {
+ return oItem && oItem.id === sId;
+ });
+ };
+ }
+ ;
+
+ sTemp = '.eml' === sTemp.substr(-4).toLowerCase() ? sTemp : sTemp + '.eml';
+ oAttachment = new ComposeAttachmentModel(
+ oMessage.requestHash, sTemp, oMessage.size()
+ );
+
+ oAttachment.fromMessage = true;
+ oAttachment.cancel = fCancelFunc(oMessage.requestHash);
+ oAttachment.waiting(false).uploading(true);
+
+ this.attachments.push(oAttachment);
+ }
+ };
+
+ /**
+ * @param {Object} oDropboxFile
+ * @return {boolean}
+ */
+ PopupsComposeViewModel.prototype.addDropboxAttachment = function (oDropboxFile)
+ {
+ var
+ self = this,
+ oAttachment = null,
+ fCancelFunc = function (sId) {
+ return function () {
+ self.attachments.remove(function (oItem) {
+ return oItem && oItem.id === sId;
+ });
+ };
+ },
+ iAttachmentSizeLimit = Utils.pInt(AppSettings.settingsGet('AttachmentLimit')),
+ mSize = oDropboxFile['bytes']
+ ;
+
+ oAttachment = new ComposeAttachmentModel(
+ oDropboxFile['link'], oDropboxFile['name'], mSize
+ );
+
+ oAttachment.fromMessage = false;
+ oAttachment.cancel = fCancelFunc(oDropboxFile['link']);
+ oAttachment.waiting(false).uploading(true);
+
+ this.attachments.push(oAttachment);
+
+ if (0 < mSize && 0 < iAttachmentSizeLimit && iAttachmentSizeLimit < mSize)
+ {
+ oAttachment.uploading(false);
+ oAttachment.error(Utils.i18n('UPLOAD/ERROR_FILE_IS_TOO_BIG'));
+ return false;
+ }
+
+ Remote.composeUploadExternals(function (sResult, oData) {
+
+ var bResult = false;
+ oAttachment.uploading(false);
+
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ {
+ if (oData.Result[oAttachment.id])
+ {
+ bResult = true;
+ oAttachment.tempName(oData.Result[oAttachment.id]);
+ }
+ }
+
+ if (!bResult)
+ {
+ oAttachment.error(Utils.getUploadErrorDescByCode(Enums.UploadErrorCode.FileNoUploaded));
+ }
+
+ }, [oDropboxFile['link']]);
+
+ return true;
+ };
+
+ /**
+ * @param {Object} oDriveFile
+ * @param {string} sAccessToken
+ * @return {boolean}
+ */
+ PopupsComposeViewModel.prototype.addDriveAttachment = function (oDriveFile, sAccessToken)
+ {
+ var
+ self = this,
+ fCancelFunc = function (sId) {
+ return function () {
+ self.attachments.remove(function (oItem) {
+ return oItem && oItem.id === sId;
+ });
+ };
+ },
+ iAttachmentSizeLimit = Utils.pInt(AppSettings.settingsGet('AttachmentLimit')),
+ oAttachment = null,
+ mSize = oDriveFile['fileSize'] ? Utils.pInt(oDriveFile['fileSize']) : 0
+ ;
+
+ oAttachment = new ComposeAttachmentModel(
+ oDriveFile['downloadUrl'], oDriveFile['title'], mSize
+ );
+
+ oAttachment.fromMessage = false;
+ oAttachment.cancel = fCancelFunc(oDriveFile['downloadUrl']);
+ oAttachment.waiting(false).uploading(true);
+
+ this.attachments.push(oAttachment);
+
+ if (0 < mSize && 0 < iAttachmentSizeLimit && iAttachmentSizeLimit < mSize)
+ {
+ oAttachment.uploading(false);
+ oAttachment.error(Utils.i18n('UPLOAD/ERROR_FILE_IS_TOO_BIG'));
+ return false;
+ }
+
+ Remote.composeUploadDrive(function (sResult, oData) {
+
+ var bResult = false;
+ oAttachment.uploading(false);
+
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ {
+ if (oData.Result[oAttachment.id])
+ {
+ bResult = true;
+ oAttachment.tempName(oData.Result[oAttachment.id][0]);
+ oAttachment.size(Utils.pInt(oData.Result[oAttachment.id][1]));
+ }
+ }
+
+ if (!bResult)
+ {
+ oAttachment.error(Utils.getUploadErrorDescByCode(Enums.UploadErrorCode.FileNoUploaded));
+ }
+
+ }, oDriveFile['downloadUrl'], sAccessToken);
+
+ return true;
+ };
+
+ /**
+ * @param {MessageModel} oMessage
+ * @param {string} sType
+ */
+ PopupsComposeViewModel.prototype.prepearMessageAttachments = function (oMessage, sType)
+ {
+ if (oMessage)
+ {
+ var
+ self = this,
+ aAttachments = Utils.isNonEmptyArray(oMessage.attachments()) ? oMessage.attachments() : [],
+ iIndex = 0,
+ iLen = aAttachments.length,
+ oAttachment = null,
+ oItem = null,
+ bAdd = false,
+ fCancelFunc = function (sId) {
+ return function () {
+ self.attachments.remove(function (oItem) {
+ return oItem && oItem.id === sId;
+ });
+ };
+ }
+ ;
+
+ if (Enums.ComposeType.ForwardAsAttachment === sType)
+ {
+ this.addMessageAsAttachment(oMessage);
}
else
{
for (; iIndex < iLen; iIndex++)
{
- fNotificationHelper(
- RL.link().notificationMailIcon(),
- MessageModel.emailsToLine(MessageModel.initEmailsFromJson(aNewMessages[iIndex].From), false),
- aNewMessages[iIndex].Subject
- );
+ oItem = aAttachments[iIndex];
+
+ bAdd = false;
+ switch (sType) {
+ case Enums.ComposeType.Reply:
+ case Enums.ComposeType.ReplyAll:
+ bAdd = oItem.isLinked;
+ break;
+
+ case Enums.ComposeType.Forward:
+ case Enums.ComposeType.Draft:
+ case Enums.ComposeType.EditAsNew:
+ bAdd = true;
+ break;
+ }
+
+ if (bAdd)
+ {
+ oAttachment = new ComposeAttachmentModel(
+ oItem.download, oItem.fileName, oItem.estimatedSize,
+ oItem.isInline, oItem.isLinked, oItem.cid, oItem.contentLocation
+ );
+
+ oAttachment.fromMessage = true;
+ oAttachment.cancel = fCancelFunc(oItem.download);
+ oAttachment.waiting(false).uploading(true);
+
+ this.attachments.push(oAttachment);
+ }
}
}
}
+ };
- RL.cache().setFolderUidNext(sFolder, sUidNext);
- }
-};
-
-/**
- * @param {string} sNamespace
- * @param {Array} aFolders
- * @return {Array}
- */
-WebMailDataStorage.prototype.folderResponseParseRec = function (sNamespace, aFolders)
-{
- var
- iIndex = 0,
- iLen = 0,
- oFolder = null,
- oCacheFolder = null,
- sFolderFullNameRaw = '',
- aSubFolders = [],
- aList = []
- ;
-
- for (iIndex = 0, iLen = aFolders.length; iIndex < iLen; iIndex++)
+ PopupsComposeViewModel.prototype.removeLinkedAttachments = function ()
{
- oFolder = aFolders[iIndex];
- if (oFolder)
- {
- sFolderFullNameRaw = oFolder.FullNameRaw;
+ this.attachments.remove(function (oItem) {
+ return oItem && oItem.isLinked;
+ });
+ };
- oCacheFolder = RL.cache().getFolderFromCacheList(sFolderFullNameRaw);
- if (!oCacheFolder)
+ PopupsComposeViewModel.prototype.setMessageAttachmentFailedDowbloadText = function ()
+ {
+ _.each(this.attachments(), function(oAttachment) {
+ if (oAttachment && oAttachment.fromMessage)
{
- oCacheFolder = FolderModel.newInstanceFromJson(oFolder);
- if (oCacheFolder)
- {
- RL.cache().setFolderToCacheList(sFolderFullNameRaw, oCacheFolder);
- RL.cache().setFolderFullNameRaw(oCacheFolder.fullNameHash, sFolderFullNameRaw);
+ oAttachment
+ .waiting(false)
+ .uploading(false)
+ .error(Utils.getUploadErrorDescByCode(Enums.UploadErrorCode.FileNoUploaded))
+ ;
+ }
+ }, this);
+ };
+
+ /**
+ * @param {boolean=} bIncludeAttachmentInProgress = true
+ * @return {boolean}
+ */
+ PopupsComposeViewModel.prototype.isEmptyForm = function (bIncludeAttachmentInProgress)
+ {
+ bIncludeAttachmentInProgress = Utils.isUnd(bIncludeAttachmentInProgress) ? true : !!bIncludeAttachmentInProgress;
+ var bAttach = bIncludeAttachmentInProgress ?
+ 0 === this.attachments().length : 0 === this.attachmentsInReady().length;
+
+ return 0 === this.to().length &&
+ 0 === this.cc().length &&
+ 0 === this.bcc().length &&
+ 0 === this.subject().length &&
+ bAttach &&
+ (!this.oEditor || '' === this.oEditor.getData())
+ ;
+ };
+
+ PopupsComposeViewModel.prototype.reset = function ()
+ {
+ this.to('');
+ this.cc('');
+ this.bcc('');
+ this.replyTo('');
+ this.subject('');
+
+ this.requestReadReceipt(false);
+
+ this.aDraftInfo = null;
+ this.sInReplyTo = '';
+ this.bFromDraft = false;
+ this.sReferences = '';
+
+ this.sendError(false);
+ this.sendSuccessButSaveError(false);
+ this.savedError(false);
+ this.savedTime(0);
+ this.savedOrSendingText('');
+ this.emptyToError(false);
+ this.attachmentsInProcessError(false);
+ this.showCcAndBcc(false);
+
+ this.attachments([]);
+ this.dragAndDropOver(false);
+ this.dragAndDropVisible(false);
+
+ this.draftFolder('');
+ this.draftUid('');
+
+ this.sending(false);
+ this.saving(false);
+
+ if (this.oEditor)
+ {
+ this.oEditor.clear(false);
+ }
+ };
+
+ /**
+ * @return {Array}
+ */
+ PopupsComposeViewModel.prototype.getAttachmentsDownloadsForUpload = function ()
+ {
+ return _.map(_.filter(this.attachments(), function (oItem) {
+ return oItem && '' === oItem.tempName();
+ }), function (oItem) {
+ return oItem.id;
+ });
+ };
+
+ PopupsComposeViewModel.prototype.triggerForResize = function ()
+ {
+ this.resizer(!this.resizer());
+ this.editorResizeThrottle();
+ };
+
+ module.exports = PopupsComposeViewModel;
+
+}(module));
+},{"../../Boots/RainLoopApp.js":4,"../../Common/Consts.js":6,"../../Common/Enums.js":7,"../../Common/Events.js":8,"../../Common/Globals.js":9,"../../Common/LinkBuilder.js":10,"../../Common/NewHtmlEditorWrapper.js":11,"../../Common/Utils.js":14,"../../External/jquery.js":26,"../../External/ko.js":28,"../../External/moment.js":29,"../../External/underscore.js":31,"../../External/window.js":32,"../../Knoin/Knoin.js":33,"../../Knoin/KnoinAbstractViewModel.js":36,"../../Storages/AppSettings.js":61,"../../Storages/WebMailAjaxRemoteStorage.js":65,"../../Storages/WebMailCacheStorage.js":66,"../../Storages/WebMailDataStorage.js":67,"./PopupsComposeOpenPgpViewModel.js":77}],79:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ window = require('../../External/window.js'),
+ $ = require('../../External/jquery.js'),
+ _ = require('../../External/underscore.js'),
+ ko = require('../../External/ko.js'),
+ key = require('../../External/key.js'),
+
+ Enums = require('../../Common/Enums.js'),
+ Consts = require('../../Common/Consts.js'),
+ Globals = require('../../Common/Globals.js'),
+ Utils = require('../../Common/Utils.js'),
+ LinkBuilder = require('../../Common/LinkBuilder.js'),
+ Selector = require('../../Common/Selector.js'),
+
+ Data = require('../../Storages/WebMailDataStorage.js'),
+ Remote = require('../../Storages/WebMailAjaxRemoteStorage.js'),
+
+ RL = require('../../Boots/RainLoopApp.js'),
+
+ kn = require('../../Knoin/Knoin.js'),
+ KnoinAbstractViewModel = require('../../Knoin/KnoinAbstractViewModel.js')
+ ;
+
+ /**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+ function PopupsContactsViewModel()
+ {
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsContacts');
+
+ var
+ self = this,
+ fFastClearEmptyListHelper = function (aList) {
+ if (aList && 0 < aList.length) {
+ self.viewProperties.removeAll(aList);
}
}
+ ;
- if (oCacheFolder)
+ this.allowContactsSync = Data.allowContactsSync;
+ this.enableContactsSync = Data.enableContactsSync;
+ this.allowExport = !Globals.bMobileDevice;
+
+ this.search = ko.observable('');
+ this.contactsCount = ko.observable(0);
+ this.contacts = Data.contacts;
+ this.contactTags = Data.contactTags;
+
+ this.currentContact = ko.observable(null);
+
+ this.importUploaderButton = ko.observable(null);
+
+ this.contactsPage = ko.observable(1);
+ this.contactsPageCount = ko.computed(function () {
+ var iPage = window.Math.ceil(this.contactsCount() / Consts.Defaults.ContactsPerPage);
+ return 0 >= iPage ? 1 : iPage;
+ }, this);
+
+ this.contactsPagenator = ko.computed(Utils.computedPagenatorHelper(this.contactsPage, this.contactsPageCount));
+
+ this.emptySelection = ko.observable(true);
+ this.viewClearSearch = ko.observable(false);
+
+ this.viewID = ko.observable('');
+ this.viewReadOnly = ko.observable(false);
+ this.viewProperties = ko.observableArray([]);
+
+ this.viewTags = ko.observable('');
+ this.viewTags.visibility = ko.observable(false);
+ this.viewTags.focusTrigger = ko.observable(false);
+
+ this.viewTags.focusTrigger.subscribe(function (bValue) {
+ if (!bValue && '' === this.viewTags())
{
- oCacheFolder.collapsed(!Utils.isFolderExpanded(oCacheFolder.fullNameHash));
-
- if (oFolder.Extended)
- {
- if (oFolder.Extended.Hash)
- {
- RL.cache().setFolderHash(oCacheFolder.fullNameRaw, oFolder.Extended.Hash);
- }
-
- if (Utils.isNormal(oFolder.Extended.MessageCount))
- {
- oCacheFolder.messageCountAll(oFolder.Extended.MessageCount);
- }
-
- if (Utils.isNormal(oFolder.Extended.MessageUnseenCount))
- {
- oCacheFolder.messageCountUnread(oFolder.Extended.MessageUnseenCount);
- }
- }
-
- aSubFolders = oFolder['SubFolders'];
- if (aSubFolders && 'Collection/FolderCollection' === aSubFolders['@Object'] &&
- aSubFolders['@Collection'] && Utils.isArray(aSubFolders['@Collection']))
- {
- oCacheFolder.subFolders(
- this.folderResponseParseRec(sNamespace, aSubFolders['@Collection']));
- }
-
- aList.push(oCacheFolder);
+ this.viewTags.visibility(false);
}
- }
- }
+ else if (bValue)
+ {
+ this.viewTags.visibility(true);
+ }
+ }, this);
- return aList;
-};
+ this.viewSaveTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
-/**
- * @param {*} oData
- */
-WebMailDataStorage.prototype.setFolders = function (oData)
-{
- var
- aList = [],
- bUpdate = false,
- oRLData = RL.data(),
- fNormalizeFolder = function (sFolderFullNameRaw) {
- return ('' === sFolderFullNameRaw || Consts.Values.UnuseOptionValue === sFolderFullNameRaw ||
- null !== RL.cache().getFolderFromCacheList(sFolderFullNameRaw)) ? sFolderFullNameRaw : '';
- }
- ;
+ this.viewPropertiesNames = this.viewProperties.filter(function(oProperty) {
+ return -1 < Utils.inArray(oProperty.type(), [
+ Enums.ContactPropertyType.FirstName, Enums.ContactPropertyType.LastName
+ ]);
+ });
- if (oData && oData.Result && 'Collection/FolderCollection' === oData.Result['@Object'] &&
- oData.Result['@Collection'] && Utils.isArray(oData.Result['@Collection']))
- {
- if (!Utils.isUnd(oData.Result.Namespace))
- {
- oRLData.namespace = oData.Result.Namespace;
- }
+ this.viewPropertiesOther = this.viewProperties.filter(function(oProperty) {
+ return -1 < Utils.inArray(oProperty.type(), [
+ Enums.ContactPropertyType.Note
+ ]);
+ });
- this.threading(!!RL.settingsGet('UseImapThread') && oData.Result.IsThreadsSupported && true);
+ this.viewPropertiesOther = ko.computed(function () {
- aList = this.folderResponseParseRec(oRLData.namespace, oData.Result['@Collection']);
- oRLData.folderList(aList);
-
- if (oData.Result['SystemFolders'] &&
- '' === '' + RL.settingsGet('SentFolder') + RL.settingsGet('DraftFolder') +
- RL.settingsGet('SpamFolder') + RL.settingsGet('TrashFolder') + RL.settingsGet('ArchiveFolder') +
- RL.settingsGet('NullFolder'))
- {
- // TODO Magic Numbers
- RL.settingsSet('SentFolder', oData.Result['SystemFolders'][2] || null);
- RL.settingsSet('DraftFolder', oData.Result['SystemFolders'][3] || null);
- RL.settingsSet('SpamFolder', oData.Result['SystemFolders'][4] || null);
- RL.settingsSet('TrashFolder', oData.Result['SystemFolders'][5] || null);
- RL.settingsSet('ArchiveFolder', oData.Result['SystemFolders'][12] || null);
-
- bUpdate = true;
- }
-
- oRLData.sentFolder(fNormalizeFolder(RL.settingsGet('SentFolder')));
- oRLData.draftFolder(fNormalizeFolder(RL.settingsGet('DraftFolder')));
- oRLData.spamFolder(fNormalizeFolder(RL.settingsGet('SpamFolder')));
- oRLData.trashFolder(fNormalizeFolder(RL.settingsGet('TrashFolder')));
- oRLData.archiveFolder(fNormalizeFolder(RL.settingsGet('ArchiveFolder')));
-
- if (bUpdate)
- {
- RL.remote().saveSystemFolders(Utils.emptyFunction, {
- 'SentFolder': oRLData.sentFolder(),
- 'DraftFolder': oRLData.draftFolder(),
- 'SpamFolder': oRLData.spamFolder(),
- 'TrashFolder': oRLData.trashFolder(),
- 'ArchiveFolder': oRLData.archiveFolder(),
- 'NullFolder': 'NullFolder'
+ var aList = _.filter(this.viewProperties(), function (oProperty) {
+ return -1 < Utils.inArray(oProperty.type(), [
+ Enums.ContactPropertyType.Nick
+ ]);
});
- }
- RL.local().set(Enums.ClientSideKeyName.FoldersLashHash, oData.Result.FoldersHash);
- }
-};
+ return _.sortBy(aList, function (oProperty) {
+ return oProperty.type();
+ });
-WebMailDataStorage.prototype.hideMessageBodies = function ()
-{
- var oMessagesBodiesDom = this.messagesBodiesDom();
- if (oMessagesBodiesDom)
- {
- oMessagesBodiesDom.find('.b-text-part').hide();
- }
-};
+ }, this);
-/**
- * @param {boolean=} bBoot = false
- * @returns {Array}
- */
-WebMailDataStorage.prototype.getNextFolderNames = function (bBoot)
-{
- bBoot = Utils.isUnd(bBoot) ? false : !!bBoot;
+ this.viewPropertiesEmails = this.viewProperties.filter(function(oProperty) {
+ return Enums.ContactPropertyType.Email === oProperty.type();
+ });
- var
- aResult = [],
- iLimit = 10,
- iUtc = moment().unix(),
- iTimeout = iUtc - 60 * 5,
- aTimeouts = [],
- fSearchFunction = function (aList) {
- _.each(aList, function (oFolder) {
- if (oFolder && 'INBOX' !== oFolder.fullNameRaw &&
- oFolder.selectable && oFolder.existen &&
- iTimeout > oFolder.interval &&
- (!bBoot || oFolder.subScribed()))
- {
- aTimeouts.push([oFolder.interval, oFolder.fullNameRaw]);
+ this.viewPropertiesWeb = this.viewProperties.filter(function(oProperty) {
+ return Enums.ContactPropertyType.Web === oProperty.type();
+ });
+
+ this.viewHasNonEmptyRequaredProperties = ko.computed(function() {
+
+ var
+ aNames = this.viewPropertiesNames(),
+ aEmail = this.viewPropertiesEmails(),
+ fHelper = function (oProperty) {
+ return '' !== Utils.trim(oProperty.value());
}
+ ;
- if (oFolder && 0 < oFolder.subFolders().length)
+ return !!(_.find(aNames, fHelper) || _.find(aEmail, fHelper));
+ }, this);
+
+ this.viewPropertiesPhones = this.viewProperties.filter(function(oProperty) {
+ return Enums.ContactPropertyType.Phone === oProperty.type();
+ });
+
+ this.viewPropertiesEmailsNonEmpty = this.viewPropertiesNames.filter(function(oProperty) {
+ return '' !== Utils.trim(oProperty.value());
+ });
+
+ this.viewPropertiesEmailsEmptyAndOnFocused = this.viewPropertiesEmails.filter(function(oProperty) {
+ var bF = oProperty.focused();
+ return '' === Utils.trim(oProperty.value()) && !bF;
+ });
+
+ this.viewPropertiesPhonesEmptyAndOnFocused = this.viewPropertiesPhones.filter(function(oProperty) {
+ var bF = oProperty.focused();
+ return '' === Utils.trim(oProperty.value()) && !bF;
+ });
+
+ this.viewPropertiesWebEmptyAndOnFocused = this.viewPropertiesWeb.filter(function(oProperty) {
+ var bF = oProperty.focused();
+ return '' === Utils.trim(oProperty.value()) && !bF;
+ });
+
+ this.viewPropertiesOtherEmptyAndOnFocused = ko.computed(function () {
+ return _.filter(this.viewPropertiesOther(), function (oProperty) {
+ var bF = oProperty.focused();
+ return '' === Utils.trim(oProperty.value()) && !bF;
+ });
+ }, this);
+
+ this.viewPropertiesEmailsEmptyAndOnFocused.subscribe(function(aList) {
+ fFastClearEmptyListHelper(aList);
+ });
+
+ this.viewPropertiesPhonesEmptyAndOnFocused.subscribe(function(aList) {
+ fFastClearEmptyListHelper(aList);
+ });
+
+ this.viewPropertiesWebEmptyAndOnFocused.subscribe(function(aList) {
+ fFastClearEmptyListHelper(aList);
+ });
+
+ this.viewPropertiesOtherEmptyAndOnFocused.subscribe(function(aList) {
+ fFastClearEmptyListHelper(aList);
+ });
+
+ this.viewSaving = ko.observable(false);
+
+ this.useCheckboxesInList = Data.useCheckboxesInList;
+
+ this.search.subscribe(function () {
+ this.reloadContactList();
+ }, this);
+
+ this.contacts.subscribe(function () {
+ Utils.windowResize();
+ }, this);
+
+ this.viewProperties.subscribe(function () {
+ Utils.windowResize();
+ }, this);
+
+ this.contactsChecked = ko.computed(function () {
+ return _.filter(this.contacts(), function (oItem) {
+ return oItem.checked();
+ });
+ }, this);
+
+ this.contactsCheckedOrSelected = ko.computed(function () {
+
+ var
+ aChecked = this.contactsChecked(),
+ oSelected = this.currentContact()
+ ;
+
+ return _.union(aChecked, oSelected ? [oSelected] : []);
+
+ }, this);
+
+ this.contactsCheckedOrSelectedUids = ko.computed(function () {
+ return _.map(this.contactsCheckedOrSelected(), function (oContact) {
+ return oContact.idContact;
+ });
+ }, this);
+
+ this.selector = new Selector(this.contacts, this.currentContact,
+ '.e-contact-item .actionHandle', '.e-contact-item.selected', '.e-contact-item .checkboxItem',
+ '.e-contact-item.focused');
+
+ this.selector.on('onItemSelect', _.bind(function (oContact) {
+ this.populateViewContact(oContact ? oContact : null);
+ if (!oContact)
+ {
+ this.emptySelection(true);
+ }
+ }, this));
+
+ this.selector.on('onItemGetUid', function (oContact) {
+ return oContact ? oContact.generateUid() : '';
+ });
+
+ this.newCommand = Utils.createCommand(this, function () {
+ this.populateViewContact(null);
+ this.currentContact(null);
+ });
+
+ this.deleteCommand = Utils.createCommand(this, function () {
+ this.deleteSelectedContacts();
+ this.emptySelection(true);
+ }, function () {
+ return 0 < this.contactsCheckedOrSelected().length;
+ });
+
+ this.newMessageCommand = Utils.createCommand(this, function () {
+ var aC = this.contactsCheckedOrSelected(), aE = [];
+ if (Utils.isNonEmptyArray(aC))
+ {
+ aE = _.map(aC, function (oItem) {
+ if (oItem)
+ {
+ var
+ aData = oItem.getNameAndEmailHelper(),
+ oEmail = aData ? new EmailModel(aData[0], aData[1]) : null
+ ;
+
+ if (oEmail && oEmail.validate())
+ {
+ return oEmail;
+ }
+ }
+
+ return null;
+ });
+
+ aE = _.compact(aE);
+ }
+
+ if (Utils.isNonEmptyArray(aE))
+ {
+ kn.hideScreenPopup(PopupsContactsViewModel);
+ kn.showScreenPopup(PopupsComposeViewModel, [Enums.ComposeType.Empty, null, aE]);
+ }
+
+ }, function () {
+ return 0 < this.contactsCheckedOrSelected().length;
+ });
+
+ this.clearCommand = Utils.createCommand(this, function () {
+ this.search('');
+ });
+
+ this.saveCommand = Utils.createCommand(this, function () {
+
+ this.viewSaving(true);
+ this.viewSaveTrigger(Enums.SaveSettingsStep.Animate);
+
+ var
+ sRequestUid = Utils.fakeMd5(),
+ aProperties = []
+ ;
+
+ _.each(this.viewProperties(), function (oItem) {
+ if (oItem.type() && '' !== Utils.trim(oItem.value()))
{
- fSearchFunction(oFolder.subFolders());
+ aProperties.push([oItem.type(), oItem.value(), oItem.typeStr()]);
}
});
- }
- ;
- fSearchFunction(this.folderList());
+ Remote.contactSave(function (sResult, oData) {
- aTimeouts.sort(function(a, b) {
- if (a[0] < b[0])
- {
- return -1;
- }
- else if (a[0] > b[0])
- {
- return 1;
- }
+ var bRes = false;
+ self.viewSaving(false);
- return 0;
- });
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result &&
+ oData.Result.RequestUid === sRequestUid && 0 < Utils.pInt(oData.Result.ResultID))
+ {
+ if ('' === self.viewID())
+ {
+ self.viewID(Utils.pInt(oData.Result.ResultID));
+ }
- _.find(aTimeouts, function (aItem) {
- var oFolder = RL.cache().getFolderFromCacheList(aItem[1]);
- if (oFolder)
- {
- oFolder.interval = iUtc;
- aResult.push(aItem[1]);
- }
+ self.reloadContactList();
+ bRes = true;
+ }
- return iLimit <= aResult.length;
- });
+ _.delay(function () {
+ self.viewSaveTrigger(bRes ? Enums.SaveSettingsStep.TrueResult : Enums.SaveSettingsStep.FalseResult);
+ }, 300);
- return _.uniq(aResult);
-};
+ if (bRes)
+ {
+ self.watchDirty(false);
-/**
- * @param {string} sFromFolderFullNameRaw
- * @param {Array} aUidForRemove
- * @param {string=} sToFolderFullNameRaw = ''
- * @param {bCopy=} bCopy = false
- */
-WebMailDataStorage.prototype.removeMessagesFromList = function (
- sFromFolderFullNameRaw, aUidForRemove, sToFolderFullNameRaw, bCopy)
-{
- sToFolderFullNameRaw = Utils.isNormal(sToFolderFullNameRaw) ? sToFolderFullNameRaw : '';
- bCopy = Utils.isUnd(bCopy) ? false : !!bCopy;
+ _.delay(function () {
+ self.viewSaveTrigger(Enums.SaveSettingsStep.Idle);
+ }, 1000);
+ }
- aUidForRemove = _.map(aUidForRemove, function (mValue) {
- return Utils.pInt(mValue);
- });
+ }, sRequestUid, this.viewID(), this.viewTags(), aProperties);
- var
- iUnseenCount = 0,
- oData = RL.data(),
- oCache = RL.cache(),
- aMessageList = oData.messageList(),
- oFromFolder = RL.cache().getFolderFromCacheList(sFromFolderFullNameRaw),
- oToFolder = '' === sToFolderFullNameRaw ? null : oCache.getFolderFromCacheList(sToFolderFullNameRaw || ''),
- sCurrentFolderFullNameRaw = oData.currentFolderFullNameRaw(),
- oCurrentMessage = oData.message(),
- aMessages = sCurrentFolderFullNameRaw === sFromFolderFullNameRaw ? _.filter(aMessageList, function (oMessage) {
- return oMessage && -1 < Utils.inArray(Utils.pInt(oMessage.uid), aUidForRemove);
- }) : []
- ;
+ }, function () {
+ var
+ bV = this.viewHasNonEmptyRequaredProperties(),
+ bReadOnly = this.viewReadOnly()
+ ;
+ return !this.viewSaving() && bV && !bReadOnly;
+ });
- _.each(aMessages, function (oMessage) {
- if (oMessage && oMessage.unseen())
- {
- iUnseenCount++;
- }
- });
+ this.syncCommand = Utils.createCommand(this, function () {
- if (oFromFolder && !bCopy)
- {
- oFromFolder.messageCountAll(0 <= oFromFolder.messageCountAll() - aUidForRemove.length ?
- oFromFolder.messageCountAll() - aUidForRemove.length : 0);
+ var self = this;
+ RL.contactsSync(function (sResult, oData) {
+ if (Enums.StorageResultType.Success !== sResult || !oData || !oData.Result)
+ {
+ window.alert(Utils.getNotification(
+ oData && oData.ErrorCode ? oData.ErrorCode : Enums.Notification.ContactsSyncError));
+ }
- if (0 < iUnseenCount)
- {
- oFromFolder.messageCountUnread(0 <= oFromFolder.messageCountUnread() - iUnseenCount ?
- oFromFolder.messageCountUnread() - iUnseenCount : 0);
- }
- }
-
- if (oToFolder)
- {
- oToFolder.messageCountAll(oToFolder.messageCountAll() + aUidForRemove.length);
- if (0 < iUnseenCount)
- {
- oToFolder.messageCountUnread(oToFolder.messageCountUnread() + iUnseenCount);
- }
-
- oToFolder.actionBlink(true);
- }
-
- if (0 < aMessages.length)
- {
- if (bCopy)
- {
- _.each(aMessages, function (oMessage) {
- oMessage.checked(false);
+ self.reloadContactList(true);
});
+
+ }, function () {
+ return !this.contacts.syncing() && !this.contacts.importing();
+ });
+
+ this.bDropPageAfterDelete = false;
+
+ this.watchDirty = ko.observable(false);
+ this.watchHash = ko.observable(false);
+
+ this.viewHash = ko.computed(function () {
+ return '' + self.viewTags() + '|' + _.map(self.viewProperties(), function (oItem) {
+ return oItem.value();
+ }).join('');
+ });
+
+ // this.saveCommandDebounce = _.debounce(_.bind(this.saveCommand, this), 1000);
+
+ this.viewHash.subscribe(function () {
+ if (this.watchHash() && !this.viewReadOnly() && !this.watchDirty())
+ {
+ this.watchDirty(true);
+ }
+ }, this);
+
+ this.sDefaultKeyScope = Enums.KeyState.ContactList;
+
+ this.contactTagsSource = _.bind(this.contactTagsSource, this);
+
+ kn.constructorEnd(this);
+ }
+
+ kn.extendAsViewModel('PopupsContactsViewModel', PopupsContactsViewModel);
+
+ PopupsContactsViewModel.prototype.contactTagsSource = function (oData, fResponse)
+ {
+ RL.getContactTagsAutocomplete(oData.term, function (aData) {
+ fResponse(_.map(aData, function (oTagItem) {
+ return oTagItem.toLine(false);
+ }));
+ });
+ };
+
+ PopupsContactsViewModel.prototype.getPropertyPlceholder = function (sType)
+ {
+ var sResult = '';
+ switch (sType)
+ {
+ case Enums.ContactPropertyType.LastName:
+ sResult = 'CONTACTS/PLACEHOLDER_ENTER_LAST_NAME';
+ break;
+ case Enums.ContactPropertyType.FirstName:
+ sResult = 'CONTACTS/PLACEHOLDER_ENTER_FIRST_NAME';
+ break;
+ case Enums.ContactPropertyType.Nick:
+ sResult = 'CONTACTS/PLACEHOLDER_ENTER_NICK_NAME';
+ break;
+ }
+
+ return sResult;
+ };
+
+ PopupsContactsViewModel.prototype.addNewProperty = function (sType, sTypeStr)
+ {
+ this.viewProperties.push(new ContactPropertyModel(sType, sTypeStr || '', '', true, this.getPropertyPlceholder(sType)));
+ };
+
+ PopupsContactsViewModel.prototype.addNewOrFocusProperty = function (sType, sTypeStr)
+ {
+ var oItem = _.find(this.viewProperties(), function (oItem) {
+ return sType === oItem.type();
+ });
+
+ if (oItem)
+ {
+ oItem.focused(true);
}
else
{
- oData.messageListIsNotCompleted(true);
-
- _.each(aMessages, function (oMessage) {
- if (oCurrentMessage && oCurrentMessage.hash === oMessage.hash)
- {
- oCurrentMessage = null;
- oData.message(null);
- }
-
- oMessage.deleted(true);
- });
-
- _.delay(function () {
- _.each(aMessages, function (oMessage) {
- oData.messageList.remove(oMessage);
- });
- }, 400);
+ this.addNewProperty(sType, sTypeStr);
}
- }
+ };
- if ('' !== sFromFolderFullNameRaw)
+ PopupsContactsViewModel.prototype.addNewTag = function ()
{
- oCache.setFolderHash(sFromFolderFullNameRaw, '');
- }
+ this.viewTags.visibility(true);
+ this.viewTags.focusTrigger(true);
+ };
- if ('' !== sToFolderFullNameRaw)
+ PopupsContactsViewModel.prototype.addNewEmail = function ()
{
- oCache.setFolderHash(sToFolderFullNameRaw, '');
- }
-};
+ this.addNewProperty(Enums.ContactPropertyType.Email, 'Home');
+ };
-WebMailDataStorage.prototype.setMessage = function (oData, bCached)
-{
- var
- bIsHtml = false,
- bHasExternals = false,
- bHasInternals = false,
- oBody = null,
- oTextBody = null,
- sId = '',
- sResultHtml = '',
- bPgpSigned = false,
- bPgpEncrypted = false,
- oMessagesBodiesDom = this.messagesBodiesDom(),
- oMessage = this.message()
- ;
-
- if (oData && oMessage && oData.Result && 'Object/Message' === oData.Result['@Object'] &&
- oMessage.folderFullNameRaw === oData.Result.Folder && oMessage.uid === oData.Result.Uid)
+ PopupsContactsViewModel.prototype.addNewPhone = function ()
{
- this.messageError('');
+ this.addNewProperty(Enums.ContactPropertyType.Phone, 'Mobile');
+ };
- oMessage.initUpdateByMessageJson(oData.Result);
- RL.cache().addRequestedMessage(oMessage.folderFullNameRaw, oMessage.uid);
+ PopupsContactsViewModel.prototype.addNewWeb = function ()
+ {
+ this.addNewProperty(Enums.ContactPropertyType.Web);
+ };
- if (!bCached)
+ PopupsContactsViewModel.prototype.addNewNickname = function ()
+ {
+ this.addNewOrFocusProperty(Enums.ContactPropertyType.Nick);
+ };
+
+ PopupsContactsViewModel.prototype.addNewNotes = function ()
+ {
+ this.addNewOrFocusProperty(Enums.ContactPropertyType.Note);
+ };
+
+ PopupsContactsViewModel.prototype.addNewBirthday = function ()
+ {
+ this.addNewOrFocusProperty(Enums.ContactPropertyType.Birthday);
+ };
+
+ //PopupsContactsViewModel.prototype.addNewAddress = function ()
+ //{
+ //};
+
+ PopupsContactsViewModel.prototype.exportVcf = function ()
+ {
+ RL.download(LinkBuilder.exportContactsVcf());
+ };
+
+ PopupsContactsViewModel.prototype.exportCsv = function ()
+ {
+ RL.download(LinkBuilder.exportContactsCsv());
+ };
+
+ PopupsContactsViewModel.prototype.initUploader = function ()
+ {
+ if (this.importUploaderButton())
{
- oMessage.initFlagsByJson(oData.Result);
- }
+ var
+ oJua = new Jua({
+ 'action': LinkBuilder.uploadContacts(),
+ 'name': 'uploader',
+ 'queueSize': 1,
+ 'multipleSizeLimit': 1,
+ 'disableFolderDragAndDrop': true,
+ 'disableDragAndDrop': true,
+ 'disableMultiple': true,
+ 'disableDocumentDropPrevent': true,
+ 'clickElement': this.importUploaderButton()
+ })
+ ;
- oMessagesBodiesDom = oMessagesBodiesDom && oMessagesBodiesDom[0] ? oMessagesBodiesDom : null;
- if (oMessagesBodiesDom)
- {
- sId = 'rl-mgs-' + oMessage.hash.replace(/[^a-zA-Z0-9]/g, '');
- oTextBody = oMessagesBodiesDom.find('#' + sId);
- if (!oTextBody || !oTextBody[0])
+ if (oJua)
{
- bHasExternals = !!oData.Result.HasExternals;
- bHasInternals = !!oData.Result.HasInternals;
+ oJua
+ .on('onStart', _.bind(function () {
+ this.contacts.importing(true);
+ }, this))
+ .on('onComplete', _.bind(function (sId, bResult, oData) {
- oBody = $('').hide().addClass('rl-cache-class');
- oBody.data('rl-cache-count', ++Globals.iMessageBodyCacheCount);
+ this.contacts.importing(false);
+ this.reloadContactList();
- if (Utils.isNormal(oData.Result.Html) && '' !== oData.Result.Html)
- {
- bIsHtml = true;
- sResultHtml = oData.Result.Html.toString();
- }
- else if (Utils.isNormal(oData.Result.Plain) && '' !== oData.Result.Plain)
- {
- bIsHtml = false;
- sResultHtml = Utils.plainToHtml(oData.Result.Plain.toString(), false);
-
- if ((oMessage.isPgpSigned() || oMessage.isPgpEncrypted()) && RL.data().capaOpenPGP())
- {
- oMessage.plainRaw = Utils.pString(oData.Result.Plain);
-
- bPgpEncrypted = /---BEGIN PGP MESSAGE---/.test(oMessage.plainRaw);
- if (!bPgpEncrypted)
+ if (!sId || !bResult || !oData || !oData.Result)
{
- bPgpSigned = /-----BEGIN PGP SIGNED MESSAGE-----/.test(oMessage.plainRaw) &&
- /-----BEGIN PGP SIGNATURE-----/.test(oMessage.plainRaw);
+ window.alert(Utils.i18n('CONTACTS/ERROR_IMPORT_FILE'));
}
- $proxyDiv.empty();
- if (bPgpSigned && oMessage.isPgpSigned())
- {
- sResultHtml =
- $proxyDiv.append(
- $('').text(oMessage.plainRaw)
- ).html()
- ;
- }
- else if (bPgpEncrypted && oMessage.isPgpEncrypted())
- {
- sResultHtml =
- $proxyDiv.append(
- $('').text(oMessage.plainRaw)
- ).html()
- ;
- }
-
- $proxyDiv.empty();
-
- oMessage.isPgpSigned(bPgpSigned);
- oMessage.isPgpEncrypted(bPgpEncrypted);
- }
- }
- else
- {
- bIsHtml = false;
- }
-
- oBody
- .html(Utils.linkify(sResultHtml))
- .addClass('b-text-part ' + (bIsHtml ? 'html' : 'plain'))
+ }, this))
;
-
- oMessage.isHtml(!!bIsHtml);
- oMessage.hasImages(!!bHasExternals);
- oMessage.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.None);
- oMessage.pgpSignedVerifyUser('');
-
- oMessage.body = oBody;
- if (oMessage.body)
- {
- oMessagesBodiesDom.append(oMessage.body);
- }
-
- oMessage.storeDataToDom();
-
- if (bHasInternals)
- {
- oMessage.showInternalImages(true);
- }
-
- if (oMessage.hasImages() && this.showImages())
- {
- oMessage.showExternalImages(true);
- }
-
- this.purgeMessageBodyCacheThrottle();
- }
- else
- {
- oMessage.body = oTextBody;
- if (oMessage.body)
- {
- oMessage.body.data('rl-cache-count', ++Globals.iMessageBodyCacheCount);
- oMessage.fetchDataToDom();
- }
- }
-
- this.messageActiveDom(oMessage.body);
-
- this.hideMessageBodies();
- oMessage.body.show();
-
- if (oBody)
- {
- Utils.initBlockquoteSwitcher(oBody);
}
}
+ };
- RL.cache().initMessageFlagsFromCache(oMessage);
- if (oMessage.unseen())
- {
- RL.setMessageSeen(oMessage);
- }
-
- Utils.windowResize();
- }
-};
-
-/**
- * @param {Array} aList
- * @returns {string}
- */
-WebMailDataStorage.prototype.calculateMessageListHash = function (aList)
-{
- return _.map(aList, function (oMessage) {
- return '' + oMessage.hash + '_' + oMessage.threadsLen() + '_' + oMessage.flagHash();
- }).join('|');
-};
-
-WebMailDataStorage.prototype.setMessageList = function (oData, bCached)
-{
- if (oData && oData.Result && 'Collection/MessageCollection' === oData.Result['@Object'] &&
- oData.Result['@Collection'] && Utils.isArray(oData.Result['@Collection']))
- {
- var
- oRainLoopData = RL.data(),
- oCache = RL.cache(),
- mLastCollapsedThreadUids = null,
- iIndex = 0,
- iLen = 0,
- iCount = 0,
- iOffset = 0,
- aList = [],
- iUtc = moment().unix(),
- aStaticList = oRainLoopData.staticMessageList,
- oJsonMessage = null,
- oMessage = null,
- oFolder = null,
- iNewCount = 0,
- bUnreadCountChange = false
- ;
-
- iCount = Utils.pInt(oData.Result.MessageResultCount);
- iOffset = Utils.pInt(oData.Result.Offset);
-
- if (Utils.isNonEmptyArray(oData.Result.LastCollapsedThreadUids))
- {
- mLastCollapsedThreadUids = oData.Result.LastCollapsedThreadUids;
- }
-
- oFolder = RL.cache().getFolderFromCacheList(
- Utils.isNormal(oData.Result.Folder) ? oData.Result.Folder : '');
-
- if (oFolder && !bCached)
- {
- oFolder.interval = iUtc;
-
- RL.cache().setFolderHash(oData.Result.Folder, oData.Result.FolderHash);
-
- if (Utils.isNormal(oData.Result.MessageCount))
- {
- oFolder.messageCountAll(oData.Result.MessageCount);
- }
-
- if (Utils.isNormal(oData.Result.MessageUnseenCount))
- {
- if (Utils.pInt(oFolder.messageCountUnread()) !== Utils.pInt(oData.Result.MessageUnseenCount))
- {
- bUnreadCountChange = true;
- }
-
- oFolder.messageCountUnread(oData.Result.MessageUnseenCount);
- }
-
- this.initUidNextAndNewMessages(oFolder.fullNameRaw, oData.Result.UidNext, oData.Result.NewMessages);
- }
-
- if (bUnreadCountChange && oFolder)
- {
- RL.cache().clearMessageFlagsFromCacheByFolder(oFolder.fullNameRaw);
- }
-
- for (iIndex = 0, iLen = oData.Result['@Collection'].length; iIndex < iLen; iIndex++)
- {
- oJsonMessage = oData.Result['@Collection'][iIndex];
- if (oJsonMessage && 'Object/Message' === oJsonMessage['@Object'])
- {
- oMessage = aStaticList[iIndex];
- if (!oMessage || !oMessage.initByJson(oJsonMessage))
- {
- oMessage = MessageModel.newInstanceFromJson(oJsonMessage);
- }
-
- if (oMessage)
- {
- if (oCache.hasNewMessageAndRemoveFromCache(oMessage.folderFullNameRaw, oMessage.uid) && 5 >= iNewCount)
- {
- iNewCount++;
- oMessage.newForAnimation(true);
- }
-
- oMessage.deleted(false);
-
- if (bCached)
- {
- RL.cache().initMessageFlagsFromCache(oMessage);
- }
- else
- {
- RL.cache().storeMessageFlagsToCache(oMessage);
- }
-
- oMessage.lastInCollapsedThread(mLastCollapsedThreadUids && -1 < Utils.inArray(Utils.pInt(oMessage.uid), mLastCollapsedThreadUids) ? true : false);
-
- aList.push(oMessage);
- }
- }
- }
-
- oRainLoopData.messageListCount(iCount);
- oRainLoopData.messageListSearch(Utils.isNormal(oData.Result.Search) ? oData.Result.Search : '');
- oRainLoopData.messageListPage(Math.ceil((iOffset / oRainLoopData.messagesPerPage()) + 1));
- oRainLoopData.messageListEndFolder(Utils.isNormal(oData.Result.Folder) ? oData.Result.Folder : '');
- oRainLoopData.messageListEndSearch(Utils.isNormal(oData.Result.Search) ? oData.Result.Search : '');
- oRainLoopData.messageListEndPage(oRainLoopData.messageListPage());
-
- oRainLoopData.messageList(aList);
- oRainLoopData.messageListIsNotCompleted(false);
-
- if (aStaticList.length < aList.length)
- {
- oRainLoopData.staticMessageList = aList;
- }
-
- oCache.clearNewMessageCache();
-
- if (oFolder && (bCached || bUnreadCountChange || RL.data().useThreads()))
- {
- RL.folderInformation(oFolder.fullNameRaw, aList);
- }
- }
- else
- {
- RL.data().messageListCount(0);
- RL.data().messageList([]);
- RL.data().messageListError(Utils.getNotification(
- oData && oData.ErrorCode ? oData.ErrorCode : Enums.Notification.CantGetMessageList
- ));
- }
-};
-
-WebMailDataStorage.prototype.findPublicKeyByHex = function (sHash)
-{
- return _.find(this.openpgpkeysPublic(), function (oItem) {
- return oItem && sHash === oItem.id;
- });
-};
-
-WebMailDataStorage.prototype.findPublicKeysByEmail = function (sEmail)
-{
- return _.compact(_.map(this.openpgpkeysPublic(), function (oItem) {
-
- var oKey = null;
- if (oItem && sEmail === oItem.email)
- {
- try
- {
- oKey = window.openpgp.key.readArmored(oItem.armor);
- if (oKey && !oKey.err && oKey.keys && oKey.keys[0])
- {
- return oKey.keys[0];
- }
- }
- catch (e) {}
- }
-
- return null;
-
- }));
-};
-
-/**
- * @param {string} sEmail
- * @param {string=} sPassword
- * @returns {?}
- */
-WebMailDataStorage.prototype.findPrivateKeyByEmail = function (sEmail, sPassword)
-{
- var
- oPrivateKey = null,
- oKey = _.find(this.openpgpkeysPrivate(), function (oItem) {
- return oItem && sEmail === oItem.email;
- })
- ;
-
- if (oKey)
- {
- try
- {
- oPrivateKey = window.openpgp.key.readArmored(oKey.armor);
- if (oPrivateKey && !oPrivateKey.err && oPrivateKey.keys && oPrivateKey.keys[0])
- {
- oPrivateKey = oPrivateKey.keys[0];
- oPrivateKey.decrypt(Utils.pString(sPassword));
- }
- else
- {
- oPrivateKey = null;
- }
- }
- catch (e)
- {
- oPrivateKey = null;
- }
- }
-
- return oPrivateKey;
-};
-
-/**
- * @param {string=} sPassword
- * @returns {?}
- */
-WebMailDataStorage.prototype.findSelfPrivateKey = function (sPassword)
-{
- return this.findPrivateKeyByEmail(this.accountEmail(), sPassword);
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function AbstractAjaxRemoteStorage()
-{
- this.oRequests = {};
-}
-
-AbstractAjaxRemoteStorage.prototype.oRequests = {};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sRequestAction
- * @param {string} sType
- * @param {?AjaxJsonDefaultResponse} oData
- * @param {boolean} bCached
- * @param {*=} oRequestParameters
- */
-AbstractAjaxRemoteStorage.prototype.defaultResponse = function (fCallback, sRequestAction, sType, oData, bCached, oRequestParameters)
-{
- var
- fCall = function () {
- if (Enums.StorageResultType.Success !== sType && Globals.bUnload)
- {
- sType = Enums.StorageResultType.Unload;
- }
-
- if (Enums.StorageResultType.Success === sType && oData && !oData.Result)
- {
- if (oData && -1 < Utils.inArray(oData.ErrorCode, [
- Enums.Notification.AuthError, Enums.Notification.AccessError,
- Enums.Notification.ConnectionError, Enums.Notification.DomainNotAllowed, Enums.Notification.AccountNotAllowed,
- Enums.Notification.MailServerError, Enums.Notification.UnknownNotification, Enums.Notification.UnknownError
- ]))
- {
- Globals.iAjaxErrorCount++;
- }
-
- if (oData && Enums.Notification.InvalidToken === oData.ErrorCode)
- {
- Globals.iTokenErrorCount++;
- }
-
- if (Consts.Values.TokenErrorLimit < Globals.iTokenErrorCount)
- {
- RL.loginAndLogoutReload(true);
- }
-
- if (oData.Logout || Consts.Values.AjaxErrorLimit < Globals.iAjaxErrorCount)
- {
- if (window.__rlah_clear)
- {
- window.__rlah_clear();
- }
-
- RL.loginAndLogoutReload(true);
- }
- }
- else if (Enums.StorageResultType.Success === sType && oData && oData.Result)
- {
- Globals.iAjaxErrorCount = 0;
- Globals.iTokenErrorCount = 0;
- }
-
- if (fCallback)
- {
- Plugins.runHook('ajax-default-response', [sRequestAction, Enums.StorageResultType.Success === sType ? oData : null, sType, bCached, oRequestParameters]);
-
- fCallback(
- sType,
- Enums.StorageResultType.Success === sType ? oData : null,
- bCached,
- sRequestAction,
- oRequestParameters
- );
- }
- }
- ;
-
- switch (sType)
- {
- case 'success':
- sType = Enums.StorageResultType.Success;
- break;
- case 'abort':
- sType = Enums.StorageResultType.Abort;
- break;
- default:
- sType = Enums.StorageResultType.Error;
- break;
- }
-
- if (Enums.StorageResultType.Error === sType)
- {
- _.delay(fCall, 300);
- }
- else
- {
- fCall();
- }
-};
-
-/**
- * @param {?Function} fResultCallback
- * @param {Object} oParameters
- * @param {?number=} iTimeOut = 20000
- * @param {string=} sGetAdd = ''
- * @param {Array=} aAbortActions = []
- * @return {jQuery.jqXHR}
- */
-AbstractAjaxRemoteStorage.prototype.ajaxRequest = function (fResultCallback, oParameters, iTimeOut, sGetAdd, aAbortActions)
-{
- var
- self = this,
- bPost = '' === sGetAdd,
- oHeaders = {},
- iStart = (new window.Date()).getTime(),
- oDefAjax = null,
- sAction = ''
- ;
-
- oParameters = oParameters || {};
- iTimeOut = Utils.isNormal(iTimeOut) ? iTimeOut : 20000;
- sGetAdd = Utils.isUnd(sGetAdd) ? '' : Utils.pString(sGetAdd);
- aAbortActions = Utils.isArray(aAbortActions) ? aAbortActions : [];
-
- sAction = oParameters.Action || '';
-
- if (sAction && 0 < aAbortActions.length)
- {
- _.each(aAbortActions, function (sActionToAbort) {
- if (self.oRequests[sActionToAbort])
- {
- self.oRequests[sActionToAbort].__aborted = true;
- if (self.oRequests[sActionToAbort].abort)
- {
- self.oRequests[sActionToAbort].abort();
- }
- self.oRequests[sActionToAbort] = null;
- }
- });
- }
-
- if (bPost)
- {
- oParameters['XToken'] = RL.settingsGet('Token');
- }
-
- oDefAjax = $.ajax({
- 'type': bPost ? 'POST' : 'GET',
- 'url': RL.link().ajax(sGetAdd),
- 'async': true,
- 'dataType': 'json',
- 'data': bPost ? oParameters : {},
- 'headers': oHeaders,
- 'timeout': iTimeOut,
- 'global': true
- });
-
- oDefAjax.always(function (oData, sType) {
-
- var bCached = false;
- if (oData && oData['Time'])
- {
- bCached = Utils.pInt(oData['Time']) > (new window.Date()).getTime() - iStart;
- }
-
- if (sAction && self.oRequests[sAction])
- {
- if (self.oRequests[sAction].__aborted)
- {
- sType = 'abort';
- }
-
- self.oRequests[sAction] = null;
- }
-
- self.defaultResponse(fResultCallback, sAction, sType, oData, bCached, oParameters);
- });
-
- if (sAction && 0 < aAbortActions.length && -1 < Utils.inArray(sAction, aAbortActions))
- {
- if (this.oRequests[sAction])
- {
- this.oRequests[sAction].__aborted = true;
- if (this.oRequests[sAction].abort)
- {
- this.oRequests[sAction].abort();
- }
- this.oRequests[sAction] = null;
- }
-
- this.oRequests[sAction] = oDefAjax;
- }
-
- return oDefAjax;
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sAction
- * @param {Object=} oParameters
- * @param {?number=} iTimeout
- * @param {string=} sGetAdd = ''
- * @param {Array=} aAbortActions = []
- */
-AbstractAjaxRemoteStorage.prototype.defaultRequest = function (fCallback, sAction, oParameters, iTimeout, sGetAdd, aAbortActions)
-{
- oParameters = oParameters || {};
- oParameters.Action = sAction;
-
- sGetAdd = Utils.pString(sGetAdd);
-
- Plugins.runHook('ajax-default-request', [sAction, oParameters, sGetAdd]);
-
- this.ajaxRequest(fCallback, oParameters,
- Utils.isUnd(iTimeout) ? Consts.Defaults.DefaultAjaxTimeout : Utils.pInt(iTimeout), sGetAdd, aAbortActions);
-};
-
-/**
- * @param {?Function} fCallback
- */
-AbstractAjaxRemoteStorage.prototype.noop = function (fCallback)
-{
- this.defaultRequest(fCallback, 'Noop');
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sMessage
- * @param {string} sFileName
- * @param {number} iLineNo
- * @param {string} sLocation
- * @param {string} sHtmlCapa
- * @param {number} iTime
- */
-AbstractAjaxRemoteStorage.prototype.jsError = function (fCallback, sMessage, sFileName, iLineNo, sLocation, sHtmlCapa, iTime)
-{
- this.defaultRequest(fCallback, 'JsError', {
- 'Message': sMessage,
- 'FileName': sFileName,
- 'LineNo': iLineNo,
- 'Location': sLocation,
- 'HtmlCapa': sHtmlCapa,
- 'TimeOnPage': iTime
- });
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sType
- * @param {Array=} mData = null
- * @param {boolean=} bIsError = false
- */
-AbstractAjaxRemoteStorage.prototype.jsInfo = function (fCallback, sType, mData, bIsError)
-{
- this.defaultRequest(fCallback, 'JsInfo', {
- 'Type': sType,
- 'Data': mData,
- 'IsError': (Utils.isUnd(bIsError) ? false : !!bIsError) ? '1' : '0'
- });
-};
-
-/**
- * @param {?Function} fCallback
- */
-AbstractAjaxRemoteStorage.prototype.getPublicKey = function (fCallback)
-{
- this.defaultRequest(fCallback, 'GetPublicKey');
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sVersion
- */
-AbstractAjaxRemoteStorage.prototype.jsVersion = function (fCallback, sVersion)
-{
- this.defaultRequest(fCallback, 'Version', {
- 'Version': sVersion
- });
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends AbstractAjaxRemoteStorage
- */
-function WebMailAjaxRemoteStorage()
-{
- AbstractAjaxRemoteStorage.call(this);
-
- this.oRequests = {};
-}
-
-_.extend(WebMailAjaxRemoteStorage.prototype, AbstractAjaxRemoteStorage.prototype);
-
-/**
- * @param {?Function} fCallback
- */
-WebMailAjaxRemoteStorage.prototype.folders = function (fCallback)
-{
- this.defaultRequest(fCallback, 'Folders', {
- 'SentFolder': RL.settingsGet('SentFolder'),
- 'DraftFolder': RL.settingsGet('DraftFolder'),
- 'SpamFolder': RL.settingsGet('SpamFolder'),
- 'TrashFolder': RL.settingsGet('TrashFolder'),
- 'ArchiveFolder': RL.settingsGet('ArchiveFolder')
- }, null, '', ['Folders']);
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sEmail
- * @param {string} sLogin
- * @param {string} sPassword
- * @param {boolean} bSignMe
- * @param {string=} sLanguage
- * @param {string=} sAdditionalCode
- * @param {boolean=} bAdditionalCodeSignMe
- */
-WebMailAjaxRemoteStorage.prototype.login = function (fCallback, sEmail, sLogin, sPassword, bSignMe, sLanguage, sAdditionalCode, bAdditionalCodeSignMe)
-{
- this.defaultRequest(fCallback, 'Login', {
- 'Email': sEmail,
- 'Login': sLogin,
- 'Password': sPassword,
- 'Language': sLanguage || '',
- 'AdditionalCode': sAdditionalCode || '',
- 'AdditionalCodeSignMe': bAdditionalCodeSignMe ? '1' : '0',
- 'SignMe': bSignMe ? '1' : '0'
- });
-};
-
-/**
- * @param {?Function} fCallback
- */
-WebMailAjaxRemoteStorage.prototype.getTwoFactor = function (fCallback)
-{
- this.defaultRequest(fCallback, 'GetTwoFactorInfo');
-};
-
-/**
- * @param {?Function} fCallback
- */
-WebMailAjaxRemoteStorage.prototype.createTwoFactor = function (fCallback)
-{
- this.defaultRequest(fCallback, 'CreateTwoFactorSecret');
-};
-
-/**
- * @param {?Function} fCallback
- */
-WebMailAjaxRemoteStorage.prototype.clearTwoFactor = function (fCallback)
-{
- this.defaultRequest(fCallback, 'ClearTwoFactorInfo');
-};
-
-/**
- * @param {?Function} fCallback
- */
-WebMailAjaxRemoteStorage.prototype.showTwoFactorSecret = function (fCallback)
-{
- this.defaultRequest(fCallback, 'ShowTwoFactorSecret');
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sCode
- */
-WebMailAjaxRemoteStorage.prototype.testTwoFactor = function (fCallback, sCode)
-{
- this.defaultRequest(fCallback, 'TestTwoFactorInfo', {
- 'Code': sCode
- });
-};
-
-/**
- * @param {?Function} fCallback
- * @param {boolean} bEnable
- */
-WebMailAjaxRemoteStorage.prototype.enableTwoFactor = function (fCallback, bEnable)
-{
- this.defaultRequest(fCallback, 'EnableTwoFactor', {
- 'Enable': bEnable ? '1' : '0'
- });
-};
-
-/**
- * @param {?Function} fCallback
- */
-WebMailAjaxRemoteStorage.prototype.clearTwoFactorInfo = function (fCallback)
-{
- this.defaultRequest(fCallback, 'ClearTwoFactorInfo');
-};
-
-/**
- * @param {?Function} fCallback
- */
-WebMailAjaxRemoteStorage.prototype.contactsSync = function (fCallback)
-{
- this.defaultRequest(fCallback, 'ContactsSync', null, Consts.Defaults.ContactsSyncAjaxTimeout);
-};
-
-/**
- * @param {?Function} fCallback
- * @param {boolean} bEnable
- * @param {string} sUrl
- * @param {string} sUser
- * @param {string} sPassword
- */
-WebMailAjaxRemoteStorage.prototype.saveContactsSyncData = function (fCallback, bEnable, sUrl, sUser, sPassword)
-{
- this.defaultRequest(fCallback, 'SaveContactsSyncData', {
- 'Enable': bEnable ? '1' : '0',
- 'Url': sUrl,
- 'User': sUser,
- 'Password': sPassword
- });
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sEmail
- * @param {string} sLogin
- * @param {string} sPassword
- */
-WebMailAjaxRemoteStorage.prototype.accountAdd = function (fCallback, sEmail, sLogin, sPassword)
-{
- this.defaultRequest(fCallback, 'AccountAdd', {
- 'Email': sEmail,
- 'Login': sLogin,
- 'Password': sPassword
- });
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sEmailToDelete
- */
-WebMailAjaxRemoteStorage.prototype.accountDelete = function (fCallback, sEmailToDelete)
-{
- this.defaultRequest(fCallback, 'AccountDelete', {
- 'EmailToDelete': sEmailToDelete
- });
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sId
- * @param {string} sEmail
- * @param {string} sName
- * @param {string} sReplyTo
- * @param {string} sBcc
- */
-WebMailAjaxRemoteStorage.prototype.identityUpdate = function (fCallback, sId, sEmail, sName, sReplyTo, sBcc)
-{
- this.defaultRequest(fCallback, 'IdentityUpdate', {
- 'Id': sId,
- 'Email': sEmail,
- 'Name': sName,
- 'ReplyTo': sReplyTo,
- 'Bcc': sBcc
- });
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sIdToDelete
- */
-WebMailAjaxRemoteStorage.prototype.identityDelete = function (fCallback, sIdToDelete)
-{
- this.defaultRequest(fCallback, 'IdentityDelete', {
- 'IdToDelete': sIdToDelete
- });
-};
-
-/**
- * @param {?Function} fCallback
- */
-WebMailAjaxRemoteStorage.prototype.accountsAndIdentities = function (fCallback)
-{
- this.defaultRequest(fCallback, 'AccountsAndIdentities');
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sFolderFullNameRaw
- * @param {number=} iOffset = 0
- * @param {number=} iLimit = 20
- * @param {string=} sSearch = ''
- * @param {boolean=} bSilent = false
- */
-WebMailAjaxRemoteStorage.prototype.messageList = function (fCallback, sFolderFullNameRaw, iOffset, iLimit, sSearch, bSilent)
-{
- sFolderFullNameRaw = Utils.pString(sFolderFullNameRaw);
-
- var
- oData = RL.data(),
- sFolderHash = RL.cache().getFolderHash(sFolderFullNameRaw)
- ;
-
- bSilent = Utils.isUnd(bSilent) ? false : !!bSilent;
- iOffset = Utils.isUnd(iOffset) ? 0 : Utils.pInt(iOffset);
- iLimit = Utils.isUnd(iOffset) ? 20 : Utils.pInt(iLimit);
- sSearch = Utils.pString(sSearch);
-
- if ('' !== sFolderHash && ('' === sSearch || -1 === sSearch.indexOf('is:')))
- {
- this.defaultRequest(fCallback, 'MessageList', {},
- '' === sSearch ? Consts.Defaults.DefaultAjaxTimeout : Consts.Defaults.SearchAjaxTimeout,
- 'MessageList/' + Base64.urlsafe_encode([
- sFolderFullNameRaw,
- iOffset,
- iLimit,
- sSearch,
- oData.projectHash(),
- sFolderHash,
- 'INBOX' === sFolderFullNameRaw ? RL.cache().getFolderUidNext(sFolderFullNameRaw) : '',
- oData.threading() && oData.useThreads() ? '1' : '0',
- oData.threading() && sFolderFullNameRaw === oData.messageListThreadFolder() ? oData.messageListThreadUids().join(',') : ''
- ].join(String.fromCharCode(0))), bSilent ? [] : ['MessageList']);
- }
- else
- {
- this.defaultRequest(fCallback, 'MessageList', {
- 'Folder': sFolderFullNameRaw,
- 'Offset': iOffset,
- 'Limit': iLimit,
- 'Search': sSearch,
- 'UidNext': 'INBOX' === sFolderFullNameRaw ? RL.cache().getFolderUidNext(sFolderFullNameRaw) : '',
- 'UseThreads': RL.data().threading() && RL.data().useThreads() ? '1' : '0',
- 'ExpandedThreadUid': oData.threading() && sFolderFullNameRaw === oData.messageListThreadFolder() ? oData.messageListThreadUids().join(',') : ''
- }, '' === sSearch ? Consts.Defaults.DefaultAjaxTimeout : Consts.Defaults.SearchAjaxTimeout, '', bSilent ? [] : ['MessageList']);
- }
-};
-
-/**
- * @param {?Function} fCallback
- * @param {Array} aDownloads
- */
-WebMailAjaxRemoteStorage.prototype.messageUploadAttachments = function (fCallback, aDownloads)
-{
- this.defaultRequest(fCallback, 'MessageUploadAttachments', {
- 'Attachments': aDownloads
- }, 999000);
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sFolderFullNameRaw
- * @param {number} iUid
- * @return {boolean}
- */
-WebMailAjaxRemoteStorage.prototype.message = function (fCallback, sFolderFullNameRaw, iUid)
-{
- sFolderFullNameRaw = Utils.pString(sFolderFullNameRaw);
- iUid = Utils.pInt(iUid);
-
- if (RL.cache().getFolderFromCacheList(sFolderFullNameRaw) && 0 < iUid)
- {
- this.defaultRequest(fCallback, 'Message', {}, null,
- 'Message/' + Base64.urlsafe_encode([
- sFolderFullNameRaw,
- iUid,
- RL.data().projectHash(),
- RL.data().threading() && RL.data().useThreads() ? '1' : '0'
- ].join(String.fromCharCode(0))), ['Message']);
-
- return true;
- }
-
- return false;
-};
-
-/**
- * @param {?Function} fCallback
- * @param {Array} aExternals
- */
-WebMailAjaxRemoteStorage.prototype.composeUploadExternals = function (fCallback, aExternals)
-{
- this.defaultRequest(fCallback, 'ComposeUploadExternals', {
- 'Externals': aExternals
- }, 999000);
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sUrl
- * @param {string} sAccessToken
- */
-WebMailAjaxRemoteStorage.prototype.composeUploadDrive = function (fCallback, sUrl, sAccessToken)
-{
- this.defaultRequest(fCallback, 'ComposeUploadDrive', {
- 'AccessToken': sAccessToken,
- 'Url': sUrl
- }, 999000);
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sFolder
- * @param {Array=} aList = []
- */
-WebMailAjaxRemoteStorage.prototype.folderInformation = function (fCallback, sFolder, aList)
-{
- var
- bRequest = true,
- oCache = RL.cache(),
- aUids = []
- ;
-
- if (Utils.isArray(aList) && 0 < aList.length)
- {
- bRequest = false;
- _.each(aList, function (oMessageListItem) {
- if (!oCache.getMessageFlagsFromCache(oMessageListItem.folderFullNameRaw, oMessageListItem.uid))
- {
- aUids.push(oMessageListItem.uid);
- }
-
- if (0 < oMessageListItem.threads().length)
- {
- _.each(oMessageListItem.threads(), function (sUid) {
- if (!oCache.getMessageFlagsFromCache(oMessageListItem.folderFullNameRaw, sUid))
- {
- aUids.push(sUid);
- }
- });
- }
- });
-
- if (0 < aUids.length)
- {
- bRequest = true;
- }
- }
-
- if (bRequest)
- {
- this.defaultRequest(fCallback, 'FolderInformation', {
- 'Folder': sFolder,
- 'FlagsUids': Utils.isArray(aUids) ? aUids.join(',') : '',
- 'UidNext': 'INBOX' === sFolder ? RL.cache().getFolderUidNext(sFolder) : ''
- });
- }
- else if (RL.data().useThreads())
- {
- RL.reloadFlagsCurrentMessageListAndMessageFromCache();
- }
-};
-
-/**
- * @param {?Function} fCallback
- * @param {Array} aFolders
- */
-WebMailAjaxRemoteStorage.prototype.folderInformationMultiply = function (fCallback, aFolders)
-{
- this.defaultRequest(fCallback, 'FolderInformationMultiply', {
- 'Folders': aFolders
- });
-};
-
-/**
- * @param {?Function} fCallback
- */
-WebMailAjaxRemoteStorage.prototype.logout = function (fCallback)
-{
- this.defaultRequest(fCallback, 'Logout');
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sFolderFullNameRaw
- * @param {Array} aUids
- * @param {boolean} bSetFlagged
- */
-WebMailAjaxRemoteStorage.prototype.messageSetFlagged = function (fCallback, sFolderFullNameRaw, aUids, bSetFlagged)
-{
- this.defaultRequest(fCallback, 'MessageSetFlagged', {
- 'Folder': sFolderFullNameRaw,
- 'Uids': aUids.join(','),
- 'SetAction': bSetFlagged ? '1' : '0'
- });
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sFolderFullNameRaw
- * @param {Array} aUids
- * @param {boolean} bSetSeen
- */
-WebMailAjaxRemoteStorage.prototype.messageSetSeen = function (fCallback, sFolderFullNameRaw, aUids, bSetSeen)
-{
- this.defaultRequest(fCallback, 'MessageSetSeen', {
- 'Folder': sFolderFullNameRaw,
- 'Uids': aUids.join(','),
- 'SetAction': bSetSeen ? '1' : '0'
- });
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sFolderFullNameRaw
- * @param {boolean} bSetSeen
- */
-WebMailAjaxRemoteStorage.prototype.messageSetSeenToAll = function (fCallback, sFolderFullNameRaw, bSetSeen)
-{
- this.defaultRequest(fCallback, 'MessageSetSeenToAll', {
- 'Folder': sFolderFullNameRaw,
- 'SetAction': bSetSeen ? '1' : '0'
- });
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sMessageFolder
- * @param {string} sMessageUid
- * @param {string} sDraftFolder
- * @param {string} sFrom
- * @param {string} sTo
- * @param {string} sCc
- * @param {string} sBcc
- * @param {string} sSubject
- * @param {boolean} bTextIsHtml
- * @param {string} sText
- * @param {Array} aAttachments
- * @param {(Array|null)} aDraftInfo
- * @param {string} sInReplyTo
- * @param {string} sReferences
- */
-WebMailAjaxRemoteStorage.prototype.saveMessage = function (fCallback, sMessageFolder, sMessageUid, sDraftFolder,
- sFrom, sTo, sCc, sBcc, sSubject, bTextIsHtml, sText, aAttachments, aDraftInfo, sInReplyTo, sReferences)
-{
- this.defaultRequest(fCallback, 'SaveMessage', {
- 'MessageFolder': sMessageFolder,
- 'MessageUid': sMessageUid,
- 'DraftFolder': sDraftFolder,
- 'From': sFrom,
- 'To': sTo,
- 'Cc': sCc,
- 'Bcc': sBcc,
- 'Subject': sSubject,
- 'TextIsHtml': bTextIsHtml ? '1' : '0',
- 'Text': sText,
- 'DraftInfo': aDraftInfo,
- 'InReplyTo': sInReplyTo,
- 'References': sReferences,
- 'Attachments': aAttachments
- }, Consts.Defaults.SaveMessageAjaxTimeout);
-};
-
-
-/**
- * @param {?Function} fCallback
- * @param {string} sMessageFolder
- * @param {string} sMessageUid
- * @param {string} sReadReceipt
- * @param {string} sSubject
- * @param {string} sText
- */
-WebMailAjaxRemoteStorage.prototype.sendReadReceiptMessage = function (fCallback, sMessageFolder, sMessageUid, sReadReceipt, sSubject, sText)
-{
- this.defaultRequest(fCallback, 'SendReadReceiptMessage', {
- 'MessageFolder': sMessageFolder,
- 'MessageUid': sMessageUid,
- 'ReadReceipt': sReadReceipt,
- 'Subject': sSubject,
- 'Text': sText
- });
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sMessageFolder
- * @param {string} sMessageUid
- * @param {string} sSentFolder
- * @param {string} sFrom
- * @param {string} sTo
- * @param {string} sCc
- * @param {string} sBcc
- * @param {string} sSubject
- * @param {boolean} bTextIsHtml
- * @param {string} sText
- * @param {Array} aAttachments
- * @param {(Array|null)} aDraftInfo
- * @param {string} sInReplyTo
- * @param {string} sReferences
- * @param {boolean} bRequestReadReceipt
- */
-WebMailAjaxRemoteStorage.prototype.sendMessage = function (fCallback, sMessageFolder, sMessageUid, sSentFolder,
- sFrom, sTo, sCc, sBcc, sSubject, bTextIsHtml, sText, aAttachments, aDraftInfo, sInReplyTo, sReferences, bRequestReadReceipt)
-{
- this.defaultRequest(fCallback, 'SendMessage', {
- 'MessageFolder': sMessageFolder,
- 'MessageUid': sMessageUid,
- 'SentFolder': sSentFolder,
- 'From': sFrom,
- 'To': sTo,
- 'Cc': sCc,
- 'Bcc': sBcc,
- 'Subject': sSubject,
- 'TextIsHtml': bTextIsHtml ? '1' : '0',
- 'Text': sText,
- 'DraftInfo': aDraftInfo,
- 'InReplyTo': sInReplyTo,
- 'References': sReferences,
- 'ReadReceiptRequest': bRequestReadReceipt ? '1' : '0',
- 'Attachments': aAttachments
- }, Consts.Defaults.SendMessageAjaxTimeout);
-};
-
-/**
- * @param {?Function} fCallback
- * @param {Object} oData
- */
-WebMailAjaxRemoteStorage.prototype.saveSystemFolders = function (fCallback, oData)
-{
- this.defaultRequest(fCallback, 'SystemFoldersUpdate', oData);
-};
-
-/**
- * @param {?Function} fCallback
- * @param {Object} oData
- */
-WebMailAjaxRemoteStorage.prototype.saveSettings = function (fCallback, oData)
-{
- this.defaultRequest(fCallback, 'SettingsUpdate', oData);
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sPrevPassword
- * @param {string} sNewPassword
- */
-WebMailAjaxRemoteStorage.prototype.changePassword = function (fCallback, sPrevPassword, sNewPassword)
-{
- this.defaultRequest(fCallback, 'ChangePassword', {
- 'PrevPassword': sPrevPassword,
- 'NewPassword': sNewPassword
- });
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sNewFolderName
- * @param {string} sParentName
- */
-WebMailAjaxRemoteStorage.prototype.folderCreate = function (fCallback, sNewFolderName, sParentName)
-{
- this.defaultRequest(fCallback, 'FolderCreate', {
- 'Folder': sNewFolderName,
- 'Parent': sParentName
- }, null, '', ['Folders']);
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sFolderFullNameRaw
- */
-WebMailAjaxRemoteStorage.prototype.folderDelete = function (fCallback, sFolderFullNameRaw)
-{
- this.defaultRequest(fCallback, 'FolderDelete', {
- 'Folder': sFolderFullNameRaw
- }, null, '', ['Folders']);
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sPrevFolderFullNameRaw
- * @param {string} sNewFolderName
- */
-WebMailAjaxRemoteStorage.prototype.folderRename = function (fCallback, sPrevFolderFullNameRaw, sNewFolderName)
-{
- this.defaultRequest(fCallback, 'FolderRename', {
- 'Folder': sPrevFolderFullNameRaw,
- 'NewFolderName': sNewFolderName
- }, null, '', ['Folders']);
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sFolderFullNameRaw
- */
-WebMailAjaxRemoteStorage.prototype.folderClear = function (fCallback, sFolderFullNameRaw)
-{
- this.defaultRequest(fCallback, 'FolderClear', {
- 'Folder': sFolderFullNameRaw
- });
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sFolderFullNameRaw
- * @param {boolean} bSubscribe
- */
-WebMailAjaxRemoteStorage.prototype.folderSetSubscribe = function (fCallback, sFolderFullNameRaw, bSubscribe)
-{
- this.defaultRequest(fCallback, 'FolderSubscribe', {
- 'Folder': sFolderFullNameRaw,
- 'Subscribe': bSubscribe ? '1' : '0'
- });
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sFolder
- * @param {string} sToFolder
- * @param {Array} aUids
- * @param {string=} sLearning
- */
-WebMailAjaxRemoteStorage.prototype.messagesMove = function (fCallback, sFolder, sToFolder, aUids, sLearning)
-{
- this.defaultRequest(fCallback, 'MessageMove', {
- 'FromFolder': sFolder,
- 'ToFolder': sToFolder,
- 'Uids': aUids.join(','),
- 'Learning': sLearning || ''
- }, null, '', ['MessageList']);
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sFolder
- * @param {string} sToFolder
- * @param {Array} aUids
- */
-WebMailAjaxRemoteStorage.prototype.messagesCopy = function (fCallback, sFolder, sToFolder, aUids)
-{
- this.defaultRequest(fCallback, 'MessageCopy', {
- 'FromFolder': sFolder,
- 'ToFolder': sToFolder,
- 'Uids': aUids.join(',')
- });
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sFolder
- * @param {Array} aUids
- */
-WebMailAjaxRemoteStorage.prototype.messagesDelete = function (fCallback, sFolder, aUids)
-{
- this.defaultRequest(fCallback, 'MessageDelete', {
- 'Folder': sFolder,
- 'Uids': aUids.join(',')
- }, null, '', ['MessageList']);
-};
-
-/**
- * @param {?Function} fCallback
- */
-WebMailAjaxRemoteStorage.prototype.appDelayStart = function (fCallback)
-{
- this.defaultRequest(fCallback, 'AppDelayStart');
-};
-
-/**
- * @param {?Function} fCallback
- */
-WebMailAjaxRemoteStorage.prototype.quota = function (fCallback)
-{
- this.defaultRequest(fCallback, 'Quota');
-};
-
-/**
- * @param {?Function} fCallback
- * @param {number} iOffset
- * @param {number} iLimit
- * @param {string} sSearch
- */
-WebMailAjaxRemoteStorage.prototype.contacts = function (fCallback, iOffset, iLimit, sSearch)
-{
- this.defaultRequest(fCallback, 'Contacts', {
- 'Offset': iOffset,
- 'Limit': iLimit,
- 'Search': sSearch
- }, null, '', ['Contacts']);
-};
-
-/**
- * @param {?Function} fCallback
- */
-WebMailAjaxRemoteStorage.prototype.contactSave = function (fCallback, sRequestUid, sUid, sTags, aProperties)
-{
- this.defaultRequest(fCallback, 'ContactSave', {
- 'RequestUid': sRequestUid,
- 'Uid': Utils.trim(sUid),
- 'Tags': Utils.trim(sTags),
- 'Properties': aProperties
- });
-};
-
-/**
- * @param {?Function} fCallback
- * @param {Array} aUids
- */
-WebMailAjaxRemoteStorage.prototype.contactsDelete = function (fCallback, aUids)
-{
- this.defaultRequest(fCallback, 'ContactsDelete', {
- 'Uids': aUids.join(',')
- });
-};
-
-/**
- * @param {?Function} fCallback
- * @param {string} sQuery
- * @param {number} iPage
- */
-WebMailAjaxRemoteStorage.prototype.suggestions = function (fCallback, sQuery, iPage)
-{
- this.defaultRequest(fCallback, 'Suggestions', {
- 'Query': sQuery,
- 'Page': iPage
- }, null, '', ['Suggestions']);
-};
-
-/**
- * @param {?Function} fCallback
- */
-WebMailAjaxRemoteStorage.prototype.facebookUser = function (fCallback)
-{
- this.defaultRequest(fCallback, 'SocialFacebookUserInformation');
-};
-
-/**
- * @param {?Function} fCallback
- */
-WebMailAjaxRemoteStorage.prototype.facebookDisconnect = function (fCallback)
-{
- this.defaultRequest(fCallback, 'SocialFacebookDisconnect');
-};
-
-/**
- * @param {?Function} fCallback
- */
-WebMailAjaxRemoteStorage.prototype.twitterUser = function (fCallback)
-{
- this.defaultRequest(fCallback, 'SocialTwitterUserInformation');
-};
-
-/**
- * @param {?Function} fCallback
- */
-WebMailAjaxRemoteStorage.prototype.twitterDisconnect = function (fCallback)
-{
- this.defaultRequest(fCallback, 'SocialTwitterDisconnect');
-};
-
-/**
- * @param {?Function} fCallback
- */
-WebMailAjaxRemoteStorage.prototype.googleUser = function (fCallback)
-{
- this.defaultRequest(fCallback, 'SocialGoogleUserInformation');
-};
-
-/**
- * @param {?Function} fCallback
- */
-WebMailAjaxRemoteStorage.prototype.googleDisconnect = function (fCallback)
-{
- this.defaultRequest(fCallback, 'SocialGoogleDisconnect');
-};
-
-/**
- * @param {?Function} fCallback
- */
-WebMailAjaxRemoteStorage.prototype.socialUsers = function (fCallback)
-{
- this.defaultRequest(fCallback, 'SocialUsers');
-};
-
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- */
-function AbstractCacheStorage()
-{
- this.bCapaGravatar = RL.capa(Enums.Capa.Gravatar);
-}
-
-/**
- * @type {Object}
- */
-AbstractCacheStorage.prototype.oServices = {};
-
-/**
- * @type {boolean}
- */
-AbstractCacheStorage.prototype.bCapaGravatar = false;
-
-AbstractCacheStorage.prototype.clear = function ()
-{
- this.bCapaGravatar = !!this.bCapaGravatar; // TODO
-};
-
-/**
- * @param {string} sEmail
- * @return {string}
- */
-AbstractCacheStorage.prototype.getUserPic = function (sEmail, fCallback)
-{
- sEmail = Utils.trim(sEmail);
- fCallback(this.bCapaGravatar && '' !== sEmail ? RL.link().avatarLink(sEmail) : '', sEmail);
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends AbstractCacheStorage
- */
-function WebMailCacheStorage()
-{
- AbstractCacheStorage.call(this);
-
- this.oFoldersCache = {};
- this.oFoldersNamesCache = {};
- this.oFolderHashCache = {};
- this.oFolderUidNextCache = {};
- this.oMessageListHashCache = {};
- this.oMessageFlagsCache = {};
- this.oNewMessage = {};
- this.oRequestedMessage = {};
-}
-
-_.extend(WebMailCacheStorage.prototype, AbstractCacheStorage.prototype);
-
-/**
- * @type {Object}
- */
-WebMailCacheStorage.prototype.oFoldersCache = {};
-
-/**
- * @type {Object}
- */
-WebMailCacheStorage.prototype.oFoldersNamesCache = {};
-
-/**
- * @type {Object}
- */
-WebMailCacheStorage.prototype.oFolderHashCache = {};
-
-/**
- * @type {Object}
- */
-WebMailCacheStorage.prototype.oFolderUidNextCache = {};
-
-/**
- * @type {Object}
- */
-WebMailCacheStorage.prototype.oMessageListHashCache = {};
-
-/**
- * @type {Object}
- */
-WebMailCacheStorage.prototype.oMessageFlagsCache = {};
-
-/**
- * @type {Object}
- */
-WebMailCacheStorage.prototype.oBodies = {};
-
-/**
- * @type {Object}
- */
-WebMailCacheStorage.prototype.oNewMessage = {};
-
-/**
- * @type {Object}
- */
-WebMailCacheStorage.prototype.oRequestedMessage = {};
-
-WebMailCacheStorage.prototype.clear = function ()
-{
- AbstractCacheStorage.prototype.clear.call(this);
-
- this.oFoldersCache = {};
- this.oFoldersNamesCache = {};
- this.oFolderHashCache = {};
- this.oFolderUidNextCache = {};
- this.oMessageListHashCache = {};
- this.oMessageFlagsCache = {};
- this.oBodies = {};
-};
-
-/**
- * @param {string} sFolderFullNameRaw
- * @param {string} sUid
- * @return {string}
- */
-WebMailCacheStorage.prototype.getMessageKey = function (sFolderFullNameRaw, sUid)
-{
- return sFolderFullNameRaw + '#' + sUid;
-};
-
-/**
- * @param {string} sFolder
- * @param {string} sUid
- */
-WebMailCacheStorage.prototype.addRequestedMessage = function (sFolder, sUid)
-{
- this.oRequestedMessage[this.getMessageKey(sFolder, sUid)] = true;
-};
-
-/**
- * @param {string} sFolder
- * @param {string} sUid
- * @return {boolean}
- */
-WebMailCacheStorage.prototype.hasRequestedMessage = function (sFolder, sUid)
-{
- return true === this.oRequestedMessage[this.getMessageKey(sFolder, sUid)];
-};
-
-/**
- * @param {string} sFolderFullNameRaw
- * @param {string} sUid
- */
-WebMailCacheStorage.prototype.addNewMessageCache = function (sFolderFullNameRaw, sUid)
-{
- this.oNewMessage[this.getMessageKey(sFolderFullNameRaw, sUid)] = true;
-};
-
-/**
- * @param {string} sFolderFullNameRaw
- * @param {string} sUid
- */
-WebMailCacheStorage.prototype.hasNewMessageAndRemoveFromCache = function (sFolderFullNameRaw, sUid)
-{
- if (this.oNewMessage[this.getMessageKey(sFolderFullNameRaw, sUid)])
- {
- this.oNewMessage[this.getMessageKey(sFolderFullNameRaw, sUid)] = null;
- return true;
- }
-
- return false;
-};
-
-WebMailCacheStorage.prototype.clearNewMessageCache = function ()
-{
- this.oNewMessage = {};
-};
-
-/**
- * @param {string} sFolderHash
- * @return {string}
- */
-WebMailCacheStorage.prototype.getFolderFullNameRaw = function (sFolderHash)
-{
- return '' !== sFolderHash && this.oFoldersNamesCache[sFolderHash] ? this.oFoldersNamesCache[sFolderHash] : '';
-};
-
-/**
- * @param {string} sFolderHash
- * @param {string} sFolderFullNameRaw
- */
-WebMailCacheStorage.prototype.setFolderFullNameRaw = function (sFolderHash, sFolderFullNameRaw)
-{
- this.oFoldersNamesCache[sFolderHash] = sFolderFullNameRaw;
-};
-
-/**
- * @param {string} sFolderFullNameRaw
- * @return {string}
- */
-WebMailCacheStorage.prototype.getFolderHash = function (sFolderFullNameRaw)
-{
- return '' !== sFolderFullNameRaw && this.oFolderHashCache[sFolderFullNameRaw] ? this.oFolderHashCache[sFolderFullNameRaw] : '';
-};
-
-/**
- * @param {string} sFolderFullNameRaw
- * @param {string} sFolderHash
- */
-WebMailCacheStorage.prototype.setFolderHash = function (sFolderFullNameRaw, sFolderHash)
-{
- this.oFolderHashCache[sFolderFullNameRaw] = sFolderHash;
-};
-
-/**
- * @param {string} sFolderFullNameRaw
- * @return {string}
- */
-WebMailCacheStorage.prototype.getFolderUidNext = function (sFolderFullNameRaw)
-{
- return '' !== sFolderFullNameRaw && this.oFolderUidNextCache[sFolderFullNameRaw] ? this.oFolderUidNextCache[sFolderFullNameRaw] : '';
-};
-
-/**
- * @param {string} sFolderFullNameRaw
- * @param {string} sUidNext
- */
-WebMailCacheStorage.prototype.setFolderUidNext = function (sFolderFullNameRaw, sUidNext)
-{
- this.oFolderUidNextCache[sFolderFullNameRaw] = sUidNext;
-};
-
-/**
- * @param {string} sFolderFullNameRaw
- * @return {?FolderModel}
- */
-WebMailCacheStorage.prototype.getFolderFromCacheList = function (sFolderFullNameRaw)
-{
- return '' !== sFolderFullNameRaw && this.oFoldersCache[sFolderFullNameRaw] ? this.oFoldersCache[sFolderFullNameRaw] : null;
-};
-
-/**
- * @param {string} sFolderFullNameRaw
- * @param {?FolderModel} oFolder
- */
-WebMailCacheStorage.prototype.setFolderToCacheList = function (sFolderFullNameRaw, oFolder)
-{
- this.oFoldersCache[sFolderFullNameRaw] = oFolder;
-};
-
-/**
- * @param {string} sFolderFullNameRaw
- */
-WebMailCacheStorage.prototype.removeFolderFromCacheList = function (sFolderFullNameRaw)
-{
- this.setFolderToCacheList(sFolderFullNameRaw, null);
-};
-
-/**
- * @param {string} sFolderFullName
- * @param {string} sUid
- * @return {?Array}
- */
-WebMailCacheStorage.prototype.getMessageFlagsFromCache = function (sFolderFullName, sUid)
-{
- return this.oMessageFlagsCache[sFolderFullName] && this.oMessageFlagsCache[sFolderFullName][sUid] ?
- this.oMessageFlagsCache[sFolderFullName][sUid] : null;
-};
-
-/**
- * @param {string} sFolderFullName
- * @param {string} sUid
- * @param {Array} aFlagsCache
- */
-WebMailCacheStorage.prototype.setMessageFlagsToCache = function (sFolderFullName, sUid, aFlagsCache)
-{
- if (!this.oMessageFlagsCache[sFolderFullName])
- {
- this.oMessageFlagsCache[sFolderFullName] = {};
- }
-
- this.oMessageFlagsCache[sFolderFullName][sUid] = aFlagsCache;
-};
-
-/**
- * @param {string} sFolderFullName
- */
-WebMailCacheStorage.prototype.clearMessageFlagsFromCacheByFolder = function (sFolderFullName)
-{
- this.oMessageFlagsCache[sFolderFullName] = {};
-};
-
-/**
- * @param {(MessageModel|null)} oMessage
- */
-WebMailCacheStorage.prototype.initMessageFlagsFromCache = function (oMessage)
-{
- if (oMessage)
+ PopupsContactsViewModel.prototype.removeCheckedOrSelectedContactsFromList = function ()
{
var
self = this,
- aFlags = this.getMessageFlagsFromCache(oMessage.folderFullNameRaw, oMessage.uid),
- mUnseenSubUid = null,
- mFlaggedSubUid = null
+ oKoContacts = this.contacts,
+ oCurrentContact = this.currentContact(),
+ iCount = this.contacts().length,
+ aContacts = this.contactsCheckedOrSelected()
;
- if (aFlags && 0 < aFlags.length)
+ if (0 < aContacts.length)
{
- oMessage.unseen(!!aFlags[0]);
- oMessage.flagged(!!aFlags[1]);
- oMessage.answered(!!aFlags[2]);
- oMessage.forwarded(!!aFlags[3]);
- oMessage.isReadReceipt(!!aFlags[4]);
- }
+ _.each(aContacts, function (oContact) {
- if (0 < oMessage.threads().length)
- {
- mUnseenSubUid = _.find(oMessage.threads(), function (iSubUid) {
- var aFlags = self.getMessageFlagsFromCache(oMessage.folderFullNameRaw, iSubUid);
- return aFlags && 0 < aFlags.length && !!aFlags[0];
+ if (oCurrentContact && oCurrentContact.idContact === oContact.idContact)
+ {
+ oCurrentContact = null;
+ self.currentContact(null);
+ }
+
+ oContact.deleted(true);
+ iCount--;
});
- mFlaggedSubUid = _.find(oMessage.threads(), function (iSubUid) {
- var aFlags = self.getMessageFlagsFromCache(oMessage.folderFullNameRaw, iSubUid);
- return aFlags && 0 < aFlags.length && !!aFlags[1];
- });
-
- oMessage.hasUnseenSubMessage(mUnseenSubUid && 0 < Utils.pInt(mUnseenSubUid));
- oMessage.hasFlaggedSubMessage(mFlaggedSubUid && 0 < Utils.pInt(mFlaggedSubUid));
- }
- }
-};
-
-/**
- * @param {(MessageModel|null)} oMessage
- */
-WebMailCacheStorage.prototype.storeMessageFlagsToCache = function (oMessage)
-{
- if (oMessage)
- {
- this.setMessageFlagsToCache(
- oMessage.folderFullNameRaw,
- oMessage.uid,
- [oMessage.unseen(), oMessage.flagged(), oMessage.answered(), oMessage.forwarded(), oMessage.isReadReceipt()]
- );
- }
-};
-/**
- * @param {string} sFolder
- * @param {string} sUid
- * @param {Array} aFlags
- */
-WebMailCacheStorage.prototype.storeMessageFlagsToCacheByFolderAndUid = function (sFolder, sUid, aFlags)
-{
- if (Utils.isArray(aFlags) && 0 < aFlags.length)
- {
- this.setMessageFlagsToCache(sFolder, sUid, aFlags);
- }
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @param {Array} aViewModels
- * @constructor
- * @extends KnoinAbstractScreen
- */
-function AbstractSettings(aViewModels)
-{
- KnoinAbstractScreen.call(this, 'settings', aViewModels);
-
- this.menu = ko.observableArray([]);
-
- this.oCurrentSubScreen = null;
- this.oViewModelPlace = null;
-}
-
-_.extend(AbstractSettings.prototype, KnoinAbstractScreen.prototype);
-
-AbstractSettings.prototype.onRoute = function (sSubName)
-{
- var
- self = this,
- oSettingsScreen = null,
- RoutedSettingsViewModel = null,
- oViewModelPlace = null,
- oViewModelDom = null
- ;
-
- RoutedSettingsViewModel = _.find(ViewModels['settings'], function (SettingsViewModel) {
- return SettingsViewModel && SettingsViewModel.__rlSettingsData &&
- sSubName === SettingsViewModel.__rlSettingsData.Route;
- });
-
- if (RoutedSettingsViewModel)
- {
- if (_.find(ViewModels['settings-removed'], function (DisabledSettingsViewModel) {
- return DisabledSettingsViewModel && DisabledSettingsViewModel === RoutedSettingsViewModel;
- }))
- {
- RoutedSettingsViewModel = null;
- }
-
- if (RoutedSettingsViewModel && _.find(ViewModels['settings-disabled'], function (DisabledSettingsViewModel) {
- return DisabledSettingsViewModel && DisabledSettingsViewModel === RoutedSettingsViewModel;
- }))
- {
- RoutedSettingsViewModel = null;
- }
- }
-
- if (RoutedSettingsViewModel)
- {
- if (RoutedSettingsViewModel.__builded && RoutedSettingsViewModel.__vm)
- {
- oSettingsScreen = RoutedSettingsViewModel.__vm;
- }
- else
- {
- oViewModelPlace = this.oViewModelPlace;
- if (oViewModelPlace && 1 === oViewModelPlace.length)
+ if (iCount <= 0)
{
- RoutedSettingsViewModel = /** @type {?Function} */ RoutedSettingsViewModel;
- oSettingsScreen = new RoutedSettingsViewModel();
-
- oViewModelDom = $('').addClass('rl-settings-view-model').hide();
- oViewModelDom.appendTo(oViewModelPlace);
-
- oSettingsScreen.data = RL.data();
- oSettingsScreen.viewModelDom = oViewModelDom;
-
- oSettingsScreen.__rlSettingsData = RoutedSettingsViewModel.__rlSettingsData;
-
- RoutedSettingsViewModel.__dom = oViewModelDom;
- RoutedSettingsViewModel.__builded = true;
- RoutedSettingsViewModel.__vm = oSettingsScreen;
-
- ko.applyBindingAccessorsToNode(oViewModelDom[0], {
- 'i18nInit': true,
- 'template': function () { return {'name': RoutedSettingsViewModel.__rlSettingsData.Template}; }
- }, oSettingsScreen);
-
- Utils.delegateRun(oSettingsScreen, 'onBuild', [oViewModelDom]);
+ this.bDropPageAfterDelete = true;
}
- else
- {
- Utils.log('Cannot find sub settings view model position: SettingsSubScreen');
- }
- }
-
- if (oSettingsScreen)
- {
- _.defer(function () {
- // hide
- if (self.oCurrentSubScreen)
- {
- Utils.delegateRun(self.oCurrentSubScreen, 'onHide');
- self.oCurrentSubScreen.viewModelDom.hide();
- }
- // --
-
- self.oCurrentSubScreen = oSettingsScreen;
-
- // show
- if (self.oCurrentSubScreen)
- {
- self.oCurrentSubScreen.viewModelDom.show();
- Utils.delegateRun(self.oCurrentSubScreen, 'onShow');
- Utils.delegateRun(self.oCurrentSubScreen, 'onFocus', [], 200);
-
- _.each(self.menu(), function (oItem) {
- oItem.selected(oSettingsScreen && oSettingsScreen.__rlSettingsData && oItem.route === oSettingsScreen.__rlSettingsData.Route);
- });
-
- $('#rl-content .b-settings .b-content .content').scrollTop(0);
- }
- // --
-
- Utils.windowResize();
- });
- }
- }
- else
- {
- kn.setHash(RL.link().settings(), false, true);
- }
-};
-
-AbstractSettings.prototype.onHide = function ()
-{
- if (this.oCurrentSubScreen && this.oCurrentSubScreen.viewModelDom)
- {
- Utils.delegateRun(this.oCurrentSubScreen, 'onHide');
- this.oCurrentSubScreen.viewModelDom.hide();
- }
-};
-
-AbstractSettings.prototype.onBuild = function ()
-{
- _.each(ViewModels['settings'], function (SettingsViewModel) {
- if (SettingsViewModel && SettingsViewModel.__rlSettingsData &&
- !_.find(ViewModels['settings-removed'], function (RemoveSettingsViewModel) {
- return RemoveSettingsViewModel && RemoveSettingsViewModel === SettingsViewModel;
- }))
- {
- this.menu.push({
- 'route': SettingsViewModel.__rlSettingsData.Route,
- 'label': SettingsViewModel.__rlSettingsData.Label,
- 'selected': ko.observable(false),
- 'disabled': !!_.find(ViewModels['settings-disabled'], function (DisabledSettingsViewModel) {
- return DisabledSettingsViewModel && DisabledSettingsViewModel === SettingsViewModel;
- })
- });
- }
- }, this);
-
- this.oViewModelPlace = $('#rl-content #rl-settings-subscreen');
-};
-
-AbstractSettings.prototype.routes = function ()
-{
- var
- DefaultViewModel = _.find(ViewModels['settings'], function (SettingsViewModel) {
- return SettingsViewModel && SettingsViewModel.__rlSettingsData && SettingsViewModel.__rlSettingsData['IsDefault'];
- }),
- sDefaultRoute = DefaultViewModel ? DefaultViewModel.__rlSettingsData['Route'] : 'general',
- oRules = {
- 'subname': /^(.*)$/,
- 'normalize_': function (oRequest, oVals) {
- oVals.subname = Utils.isUnd(oVals.subname) ? sDefaultRoute : Utils.pString(oVals.subname);
- return [oVals.subname];
- }
- }
- ;
-
- return [
- ['{subname}/', oRules],
- ['{subname}', oRules],
- ['', oRules]
- ];
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends KnoinAbstractScreen
- */
-function LoginScreen()
-{
- KnoinAbstractScreen.call(this, 'login', [LoginViewModel]);
-}
-
-_.extend(LoginScreen.prototype, KnoinAbstractScreen.prototype);
-
-LoginScreen.prototype.onShow = function ()
-{
- RL.setTitle('');
-};
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends KnoinAbstractScreen
- */
-function MailBoxScreen()
-{
- KnoinAbstractScreen.call(this, 'mailbox', [
- MailBoxSystemDropDownViewModel,
- MailBoxFolderListViewModel,
- MailBoxMessageListViewModel,
- MailBoxMessageViewViewModel
- ]);
-
- this.oLastRoute = {};
-}
-
-_.extend(MailBoxScreen.prototype, KnoinAbstractScreen.prototype);
-
-/**
- * @type {Object}
- */
-MailBoxScreen.prototype.oLastRoute = {};
-
-MailBoxScreen.prototype.setNewTitle = function ()
-{
- var
- sEmail = RL.data().accountEmail(),
- ifoldersInboxUnreadCount = RL.data().foldersInboxUnreadCount()
- ;
-
- RL.setTitle(('' === sEmail ? '' :
- (0 < ifoldersInboxUnreadCount ? '(' + ifoldersInboxUnreadCount + ') ' : ' ') + sEmail + ' - ') + Utils.i18n('TITLES/MAILBOX'));
-};
-
-MailBoxScreen.prototype.onShow = function ()
-{
- this.setNewTitle();
- RL.data().keyScope(Enums.KeyState.MessageList);
-};
-
-/**
- * @param {string} sFolderHash
- * @param {number} iPage
- * @param {string} sSearch
- * @param {boolean=} bPreview = false
- */
-MailBoxScreen.prototype.onRoute = function (sFolderHash, iPage, sSearch, bPreview)
-{
- if (Utils.isUnd(bPreview) ? false : !!bPreview)
- {
- if (Enums.Layout.NoPreview === RL.data().layout() && !RL.data().message())
- {
- RL.historyBack();
- }
- }
- else
- {
- var
- oData = RL.data(),
- sFolderFullNameRaw = RL.cache().getFolderFullNameRaw(sFolderHash),
- oFolder = RL.cache().getFolderFromCacheList(sFolderFullNameRaw)
- ;
-
- if (oFolder)
- {
- oData
- .currentFolder(oFolder)
- .messageListPage(iPage)
- .messageListSearch(sSearch)
- ;
-
- if (Enums.Layout.NoPreview === oData.layout() && oData.message())
- {
- oData.message(null);
- }
-
- RL.reloadMessageList();
- }
- }
-};
-
-MailBoxScreen.prototype.onStart = function ()
-{
- var
- oData = RL.data(),
- fResizeFunction = function () {
- Utils.windowResize();
- }
- ;
-
- if (RL.capa(Enums.Capa.AdditionalAccounts) || RL.capa(Enums.Capa.AdditionalIdentities))
- {
- RL.accountsAndIdentities();
- }
-
- _.delay(function () {
- if ('INBOX' !== oData.currentFolderFullNameRaw())
- {
- RL.folderInformation('INBOX');
- }
- }, 1000);
-
- _.delay(function () {
- RL.quota();
- }, 5000);
-
- _.delay(function () {
- RL.remote().appDelayStart(Utils.emptyFunction);
- }, 35000);
-
- $html.toggleClass('rl-no-preview-pane', Enums.Layout.NoPreview === oData.layout());
-
- oData.folderList.subscribe(fResizeFunction);
- oData.messageList.subscribe(fResizeFunction);
- oData.message.subscribe(fResizeFunction);
-
- oData.layout.subscribe(function (nValue) {
- $html.toggleClass('rl-no-preview-pane', Enums.Layout.NoPreview === nValue);
- });
-
- oData.foldersInboxUnreadCount.subscribe(function () {
- this.setNewTitle();
- }, this);
-};
-
-/**
- * @return {Array}
- */
-MailBoxScreen.prototype.routes = function ()
-{
- var
- fNormP = function () {
- return ['Inbox', 1, '', true];
- },
- fNormS = function (oRequest, oVals) {
- oVals[0] = Utils.pString(oVals[0]);
- oVals[1] = Utils.pInt(oVals[1]);
- oVals[1] = 0 >= oVals[1] ? 1 : oVals[1];
- oVals[2] = Utils.pString(oVals[2]);
-
- if ('' === oRequest)
- {
- oVals[0] = 'Inbox';
- oVals[1] = 1;
- }
-
- return [decodeURI(oVals[0]), oVals[1], decodeURI(oVals[2]), false];
- },
- fNormD = function (oRequest, oVals) {
- oVals[0] = Utils.pString(oVals[0]);
- oVals[1] = Utils.pString(oVals[1]);
-
- if ('' === oRequest)
- {
- oVals[0] = 'Inbox';
- }
-
- return [decodeURI(oVals[0]), 1, decodeURI(oVals[1]), false];
- }
- ;
-
- return [
- [/^([a-zA-Z0-9]+)\/p([1-9][0-9]*)\/(.+)\/?$/, {'normalize_': fNormS}],
- [/^([a-zA-Z0-9]+)\/p([1-9][0-9]*)$/, {'normalize_': fNormS}],
- [/^([a-zA-Z0-9]+)\/(.+)\/?$/, {'normalize_': fNormD}],
- [/^message-preview$/, {'normalize_': fNormP}],
- [/^([^\/]*)$/, {'normalize_': fNormS}]
- ];
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends AbstractSettings
- */
-function SettingsScreen()
-{
- AbstractSettings.call(this, [
- SettingsSystemDropDownViewModel,
- SettingsMenuViewModel,
- SettingsPaneViewModel
- ]);
-
- Utils.initOnStartOrLangChange(function () {
- this.sSettingsTitle = Utils.i18n('TITLES/SETTINGS');
- }, this, function () {
- RL.setTitle(this.sSettingsTitle);
- });
-}
-
-_.extend(SettingsScreen.prototype, AbstractSettings.prototype);
-
-SettingsScreen.prototype.onShow = function ()
-{
- RL.setTitle(this.sSettingsTitle);
- RL.data().keyScope(Enums.KeyState.Settings);
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends KnoinAbstractBoot
- */
-function AbstractApp()
-{
- KnoinAbstractBoot.call(this);
-
- this.oSettings = null;
- this.oPlugins = null;
- this.oLocal = null;
- this.oLink = null;
- this.oSubs = {};
-
- this.isLocalAutocomplete = true;
-
- this.popupVisibilityNames = ko.observableArray([]);
-
- this.popupVisibility = ko.computed(function () {
- return 0 < this.popupVisibilityNames().length;
- }, this);
-
- this.iframe = $('').appendTo('body');
-
- $window.on('error', function (oEvent) {
- if (RL && oEvent && oEvent.originalEvent && oEvent.originalEvent.message &&
- -1 === Utils.inArray(oEvent.originalEvent.message, [
- 'Script error.', 'Uncaught Error: Error calling method on NPObject.'
- ]))
- {
- RL.remote().jsError(
- Utils.emptyFunction,
- oEvent.originalEvent.message,
- oEvent.originalEvent.filename,
- oEvent.originalEvent.lineno,
- location && location.toString ? location.toString() : '',
- $html.attr('class'),
- Utils.microtime() - Globals.now
- );
- }
- });
-
- $document.on('keydown', function (oEvent) {
- if (oEvent && oEvent.ctrlKey)
- {
- $html.addClass('rl-ctrl-key-pressed');
- }
- }).on('keyup', function (oEvent) {
- if (oEvent && !oEvent.ctrlKey)
- {
- $html.removeClass('rl-ctrl-key-pressed');
- }
- });
-}
-
-_.extend(AbstractApp.prototype, KnoinAbstractBoot.prototype);
-
-AbstractApp.prototype.oSettings = null;
-AbstractApp.prototype.oPlugins = null;
-AbstractApp.prototype.oLocal = null;
-AbstractApp.prototype.oLink = null;
-AbstractApp.prototype.oSubs = {};
-
-/**
- * @param {string} sLink
- * @return {boolean}
- */
-AbstractApp.prototype.download = function (sLink)
-{
- var
- oLink = null,
- oE = null,
- sUserAgent = navigator.userAgent.toLowerCase()
- ;
-
- if (sUserAgent && (sUserAgent.indexOf('chrome') > -1 || sUserAgent.indexOf('chrome') > -1))
- {
- oLink = document.createElement('a');
- oLink['href'] = sLink;
-
- if (document['createEvent'])
- {
- oE = document['createEvent']('MouseEvents');
- if (oE && oE['initEvent'] && oLink['dispatchEvent'])
- {
- oE['initEvent']('click', true, true);
- oLink['dispatchEvent'](oE);
- return true;
- }
- }
- }
-
- if (Globals.bMobileDevice)
- {
- window.open(sLink, '_self');
- window.focus();
- }
- else
- {
- this.iframe.attr('src', sLink);
-// window.document.location.href = sLink;
- }
-
- return true;
-};
-
-/**
- * @return {LinkBuilder}
- */
-AbstractApp.prototype.link = function ()
-{
- if (null === this.oLink)
- {
- this.oLink = new LinkBuilder();
- }
-
- return this.oLink;
-};
-
-/**
- * @return {LocalStorage}
- */
-AbstractApp.prototype.local = function ()
-{
- if (null === this.oLocal)
- {
- this.oLocal = new LocalStorage();
- }
-
- return this.oLocal;
-};
-
-/**
- * @param {string} sName
- * @return {?}
- */
-AbstractApp.prototype.settingsGet = function (sName)
-{
- if (null === this.oSettings)
- {
- this.oSettings = Utils.isNormal(AppData) ? AppData : {};
- }
-
- return Utils.isUnd(this.oSettings[sName]) ? null : this.oSettings[sName];
-};
-
-/**
- * @param {string} sName
- * @param {?} mValue
- */
-AbstractApp.prototype.settingsSet = function (sName, mValue)
-{
- if (null === this.oSettings)
- {
- this.oSettings = Utils.isNormal(AppData) ? AppData : {};
- }
-
- this.oSettings[sName] = mValue;
-};
-
-AbstractApp.prototype.setTitle = function (sTitle)
-{
- sTitle = ((Utils.isNormal(sTitle) && 0 < sTitle.length) ? sTitle + ' - ' : '') +
- RL.settingsGet('Title') || '';
-
- window.document.title = '_';
- window.document.title = sTitle;
-};
-
-/**
- * @param {boolean=} bLogout = false
- * @param {boolean=} bClose = false
- */
-AbstractApp.prototype.loginAndLogoutReload = function (bLogout, bClose)
-{
- var
- sCustomLogoutLink = Utils.pString(RL.settingsGet('CustomLogoutLink')),
- bInIframe = !!RL.settingsGet('InIframe')
- ;
-
- bLogout = Utils.isUnd(bLogout) ? false : !!bLogout;
- bClose = Utils.isUnd(bClose) ? false : !!bClose;
-
- if (bLogout && bClose && window.close)
- {
- window.close();
- }
-
- if (bLogout && '' !== sCustomLogoutLink && window.location.href !== sCustomLogoutLink)
- {
- _.delay(function () {
- if (bInIframe && window.parent)
- {
- window.parent.location.href = sCustomLogoutLink;
- }
- else
- {
- window.location.href = sCustomLogoutLink;
- }
- }, 100);
- }
- else
- {
- kn.routeOff();
- kn.setHash(RL.link().root(), true);
- kn.routeOff();
-
- _.delay(function () {
- if (bInIframe && window.parent)
- {
- window.parent.location.reload();
- }
- else
- {
- window.location.reload();
- }
- }, 100);
- }
-};
-
-AbstractApp.prototype.historyBack = function ()
-{
- window.history.back();
-};
-
-/**
- * @param {string} sQuery
- * @param {Function} fCallback
- */
-AbstractApp.prototype.getAutocomplete = function (sQuery, fCallback)
-{
- fCallback([], sQuery);
-};
-
-/**
- * @param {string} sName
- * @param {Function} fFunc
- * @param {Object=} oContext
- * @return {AbstractApp}
- */
-AbstractApp.prototype.sub = function (sName, fFunc, oContext)
-{
- if (Utils.isUnd(this.oSubs[sName]))
- {
- this.oSubs[sName] = [];
- }
-
- this.oSubs[sName].push([fFunc, oContext]);
-
- return this;
-};
-
-/**
- * @param {string} sName
- * @param {Array=} aArgs
- * @return {AbstractApp}
- */
-AbstractApp.prototype.pub = function (sName, aArgs)
-{
- Plugins.runHook('rl-pub', [sName, aArgs]);
- if (!Utils.isUnd(this.oSubs[sName]))
- {
- _.each(this.oSubs[sName], function (aItem) {
- if (aItem[0])
- {
- aItem[0].apply(aItem[1] || null, aArgs || []);
- }
- });
- }
-
- return this;
-};
-
-/**
- * @param {string} sName
- * @return {boolean}
- */
-AbstractApp.prototype.capa = function (sName)
-{
- var mCapa = this.settingsGet('Capa');
- return Utils.isArray(mCapa) && Utils.isNormal(sName) && -1 < Utils.inArray(sName, mCapa);
-};
-
-AbstractApp.prototype.bootstart = function ()
-{
- var self = this;
-
- Utils.initOnStartOrLangChange(function () {
- Utils.initNotificationLanguage();
- }, null);
-
- _.delay(function () {
- Utils.windowResize();
- }, 1000);
-
- ssm.addState({
- 'id': 'mobile',
- 'maxWidth': 767,
- 'onEnter': function() {
- $html.addClass('ssm-state-mobile');
- self.pub('ssm.mobile-enter');
- },
- 'onLeave': function() {
- $html.removeClass('ssm-state-mobile');
- self.pub('ssm.mobile-leave');
- }
- });
-
- ssm.addState({
- 'id': 'tablet',
- 'minWidth': 768,
- 'maxWidth': 999,
- 'onEnter': function() {
- $html.addClass('ssm-state-tablet');
- },
- 'onLeave': function() {
- $html.removeClass('ssm-state-tablet');
- }
- });
-
- ssm.addState({
- 'id': 'desktop',
- 'minWidth': 1000,
- 'maxWidth': 1400,
- 'onEnter': function() {
- $html.addClass('ssm-state-desktop');
- },
- 'onLeave': function() {
- $html.removeClass('ssm-state-desktop');
- }
- });
-
- ssm.addState({
- 'id': 'desktop-large',
- 'minWidth': 1400,
- 'onEnter': function() {
- $html.addClass('ssm-state-desktop-large');
- },
- 'onLeave': function() {
- $html.removeClass('ssm-state-desktop-large');
- }
- });
-
- RL.sub('ssm.mobile-enter', function () {
- RL.data().leftPanelDisabled(true);
- });
-
- RL.sub('ssm.mobile-leave', function () {
- RL.data().leftPanelDisabled(false);
- });
-
- RL.data().leftPanelDisabled.subscribe(function (bValue) {
- $html.toggleClass('rl-left-panel-disabled', bValue);
- });
-
- ssm.ready();
-};
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-/**
- * @constructor
- * @extends AbstractApp
- */
-function RainLoopApp()
-{
- AbstractApp.call(this);
-
- this.oData = null;
- this.oRemote = null;
- this.oCache = null;
- this.oMoveCache = {};
-
- this.quotaDebounce = _.debounce(this.quota, 1000 * 30);
- this.moveOrDeleteResponseHelper = _.bind(this.moveOrDeleteResponseHelper, this);
-
- this.messagesMoveTrigger = _.debounce(this.messagesMoveTrigger, 500);
-
- window.setInterval(function () {
- RL.pub('interval.30s');
- }, 30000);
-
- window.setInterval(function () {
- RL.pub('interval.1m');
- }, 60000);
-
- window.setInterval(function () {
- RL.pub('interval.2m');
- }, 60000 * 2);
-
- window.setInterval(function () {
- RL.pub('interval.3m');
- }, 60000 * 3);
-
- window.setInterval(function () {
- RL.pub('interval.5m');
- }, 60000 * 5);
-
- window.setInterval(function () {
- RL.pub('interval.10m');
- }, 60000 * 10);
-
- window.setTimeout(function () {
- window.setInterval(function () {
- RL.pub('interval.10m-after5m');
- }, 60000 * 10);
- }, 60000 * 5);
-
- $.wakeUp(function () {
- RL.remote().jsVersion(function (sResult, oData) {
- if (Enums.StorageResultType.Success === sResult && oData && !oData.Result)
- {
- if (window.parent && !!RL.settingsGet('InIframe'))
- {
- window.parent.location.reload();
- }
- else
- {
- window.location.reload();
- }
- }
- }, RL.settingsGet('Version'));
- }, {}, 60 * 60 * 1000);
-}
-
-_.extend(RainLoopApp.prototype, AbstractApp.prototype);
-
-RainLoopApp.prototype.oData = null;
-RainLoopApp.prototype.oRemote = null;
-RainLoopApp.prototype.oCache = null;
-
-/**
- * @return {WebMailDataStorage}
- */
-RainLoopApp.prototype.data = function ()
-{
- if (null === this.oData)
- {
- this.oData = new WebMailDataStorage();
- }
-
- return this.oData;
-};
-
-/**
- * @return {WebMailAjaxRemoteStorage}
- */
-RainLoopApp.prototype.remote = function ()
-{
- if (null === this.oRemote)
- {
- this.oRemote = new WebMailAjaxRemoteStorage();
- }
-
- return this.oRemote;
-};
-
-/**
- * @return {WebMailCacheStorage}
- */
-RainLoopApp.prototype.cache = function ()
-{
- if (null === this.oCache)
- {
- this.oCache = new WebMailCacheStorage();
- }
-
- return this.oCache;
-};
-
-RainLoopApp.prototype.reloadFlagsCurrentMessageListAndMessageFromCache = function ()
-{
- var oCache = RL.cache();
- _.each(RL.data().messageList(), function (oMessage) {
- oCache.initMessageFlagsFromCache(oMessage);
- });
-
- oCache.initMessageFlagsFromCache(RL.data().message());
-};
-
-/**
- * @param {boolean=} bDropPagePosition = false
- * @param {boolean=} bDropCurrenFolderCache = false
- */
-RainLoopApp.prototype.reloadMessageList = function (bDropPagePosition, bDropCurrenFolderCache)
-{
- var
- oRLData = RL.data(),
- iOffset = (oRLData.messageListPage() - 1) * oRLData.messagesPerPage()
- ;
-
- if (Utils.isUnd(bDropCurrenFolderCache) ? false : !!bDropCurrenFolderCache)
- {
- RL.cache().setFolderHash(oRLData.currentFolderFullNameRaw(), '');
- }
-
- if (Utils.isUnd(bDropPagePosition) ? false : !!bDropPagePosition)
- {
- oRLData.messageListPage(1);
- iOffset = 0;
- }
-
- oRLData.messageListLoading(true);
- RL.remote().messageList(function (sResult, oData, bCached) {
-
- if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
- {
- oRLData.messageListError('');
- oRLData.messageListLoading(false);
- oRLData.setMessageList(oData, bCached);
- }
- else if (Enums.StorageResultType.Unload === sResult)
- {
- oRLData.messageListError('');
- oRLData.messageListLoading(false);
- }
- else if (Enums.StorageResultType.Abort !== sResult)
- {
- oRLData.messageList([]);
- oRLData.messageListLoading(false);
- oRLData.messageListError(oData && oData.ErrorCode ?
- Utils.getNotification(oData.ErrorCode) : Utils.i18n('NOTIFICATIONS/CANT_GET_MESSAGE_LIST')
- );
- }
-
- }, oRLData.currentFolderFullNameRaw(), iOffset, oRLData.messagesPerPage(), oRLData.messageListSearch());
-};
-
-RainLoopApp.prototype.recacheInboxMessageList = function ()
-{
- RL.remote().messageList(Utils.emptyFunction, 'INBOX', 0, RL.data().messagesPerPage(), '', true);
-};
-
-RainLoopApp.prototype.reloadMessageListHelper = function (bEmptyList)
-{
- RL.reloadMessageList(bEmptyList);
-};
-
-/**
- * @param {Function} fResultFunc
- * @returns {boolean}
- */
-RainLoopApp.prototype.contactsSync = function (fResultFunc)
-{
- var oContacts = RL.data().contacts;
- if (oContacts.importing() || oContacts.syncing() || !RL.data().enableContactsSync() || !RL.data().allowContactsSync())
- {
- return false;
- }
-
- oContacts.syncing(true);
-
- RL.remote().contactsSync(function (sResult, oData) {
-
- oContacts.syncing(false);
-
- if (fResultFunc)
- {
- fResultFunc(sResult, oData);
- }
- });
-
- return true;
-};
-
-RainLoopApp.prototype.messagesMoveTrigger = function ()
-{
- var
- self = this,
- sSpamFolder = RL.data().spamFolder()
- ;
-
- _.each(this.oMoveCache, function (oItem) {
-
- var
- bSpam = sSpamFolder === oItem['To'],
- bHam = !bSpam && sSpamFolder === oItem['From'] && 'INBOX' === oItem['To']
- ;
-
- RL.remote().messagesMove(self.moveOrDeleteResponseHelper, oItem['From'], oItem['To'], oItem['Uid'],
- bSpam ? 'SPAM' : (bHam ? 'HAM' : ''));
- });
-
- this.oMoveCache = {};
-};
-
-RainLoopApp.prototype.messagesMoveHelper = function (sFromFolderFullNameRaw, sToFolderFullNameRaw, aUidForMove)
-{
- var sH = '$$' + sFromFolderFullNameRaw + '$$' + sToFolderFullNameRaw + '$$';
- if (!this.oMoveCache[sH])
- {
- this.oMoveCache[sH] = {
- 'From': sFromFolderFullNameRaw,
- 'To': sToFolderFullNameRaw,
- 'Uid': []
- };
- }
-
- this.oMoveCache[sH]['Uid'] = _.union(this.oMoveCache[sH]['Uid'], aUidForMove);
- this.messagesMoveTrigger();
-};
-
-RainLoopApp.prototype.messagesCopyHelper = function (sFromFolderFullNameRaw, sToFolderFullNameRaw, aUidForCopy)
-{
- RL.remote().messagesCopy(
- this.moveOrDeleteResponseHelper,
- sFromFolderFullNameRaw,
- sToFolderFullNameRaw,
- aUidForCopy
- );
-};
-
-RainLoopApp.prototype.messagesDeleteHelper = function (sFromFolderFullNameRaw, aUidForRemove)
-{
- RL.remote().messagesDelete(
- this.moveOrDeleteResponseHelper,
- sFromFolderFullNameRaw,
- aUidForRemove
- );
-};
-
-RainLoopApp.prototype.moveOrDeleteResponseHelper = function (sResult, oData)
-{
- if (Enums.StorageResultType.Success === sResult && RL.data().currentFolder())
- {
- if (oData && Utils.isArray(oData.Result) && 2 === oData.Result.length)
- {
- RL.cache().setFolderHash(oData.Result[0], oData.Result[1]);
- }
- else
- {
- RL.cache().setFolderHash(RL.data().currentFolderFullNameRaw(), '');
-
- if (oData && -1 < Utils.inArray(oData.ErrorCode,
- [Enums.Notification.CantMoveMessage, Enums.Notification.CantCopyMessage]))
- {
- window.alert(Utils.getNotification(oData.ErrorCode));
- }
- }
-
- RL.reloadMessageListHelper(0 === RL.data().messageList().length);
- RL.quotaDebounce();
- }
-};
-
-/**
- * @param {string} sFromFolderFullNameRaw
- * @param {Array} aUidForRemove
- */
-RainLoopApp.prototype.deleteMessagesFromFolderWithoutCheck = function (sFromFolderFullNameRaw, aUidForRemove)
-{
- this.messagesDeleteHelper(sFromFolderFullNameRaw, aUidForRemove);
- RL.data().removeMessagesFromList(sFromFolderFullNameRaw, aUidForRemove);
-};
-
-/**
- * @param {number} iDeleteType
- * @param {string} sFromFolderFullNameRaw
- * @param {Array} aUidForRemove
- * @param {boolean=} bUseFolder = true
- */
-RainLoopApp.prototype.deleteMessagesFromFolder = function (iDeleteType, sFromFolderFullNameRaw, aUidForRemove, bUseFolder)
-{
- var
- self = this,
- oData = RL.data(),
- oCache = RL.cache(),
- oMoveFolder = null,
- nSetSystemFoldersNotification = null
- ;
-
- switch (iDeleteType)
- {
- case Enums.FolderType.Spam:
- oMoveFolder = oCache.getFolderFromCacheList(oData.spamFolder());
- nSetSystemFoldersNotification = Enums.SetSystemFoldersNotification.Spam;
- break;
- case Enums.FolderType.NotSpam:
- oMoveFolder = oCache.getFolderFromCacheList('INBOX');
- break;
- case Enums.FolderType.Trash:
- oMoveFolder = oCache.getFolderFromCacheList(oData.trashFolder());
- nSetSystemFoldersNotification = Enums.SetSystemFoldersNotification.Trash;
- break;
- case Enums.FolderType.Archive:
- oMoveFolder = oCache.getFolderFromCacheList(oData.archiveFolder());
- nSetSystemFoldersNotification = Enums.SetSystemFoldersNotification.Archive;
- break;
- }
-
- bUseFolder = Utils.isUnd(bUseFolder) ? true : !!bUseFolder;
- if (bUseFolder)
- {
- if ((Enums.FolderType.Spam === iDeleteType && Consts.Values.UnuseOptionValue === oData.spamFolder()) ||
- (Enums.FolderType.Trash === iDeleteType && Consts.Values.UnuseOptionValue === oData.trashFolder()) ||
- (Enums.FolderType.Archive === iDeleteType && Consts.Values.UnuseOptionValue === oData.archiveFolder()))
- {
- bUseFolder = false;
- }
- }
-
- if (!oMoveFolder && bUseFolder)
- {
- kn.showScreenPopup(PopupsFolderSystemViewModel, [nSetSystemFoldersNotification]);
- }
- else if (!bUseFolder || (Enums.FolderType.Trash === iDeleteType &&
- (sFromFolderFullNameRaw === oData.spamFolder() || sFromFolderFullNameRaw === oData.trashFolder())))
- {
- kn.showScreenPopup(PopupsAskViewModel, [Utils.i18n('POPUPS_ASK/DESC_WANT_DELETE_MESSAGES'), function () {
-
- self.messagesDeleteHelper(sFromFolderFullNameRaw, aUidForRemove);
- oData.removeMessagesFromList(sFromFolderFullNameRaw, aUidForRemove);
-
- }]);
- }
- else if (oMoveFolder)
- {
- this.messagesMoveHelper(sFromFolderFullNameRaw, oMoveFolder.fullNameRaw, aUidForRemove);
- oData.removeMessagesFromList(sFromFolderFullNameRaw, aUidForRemove, oMoveFolder.fullNameRaw);
- }
-};
-
-/**
- * @param {string} sFromFolderFullNameRaw
- * @param {Array} aUidForMove
- * @param {string} sToFolderFullNameRaw
- * @param {boolean=} bCopy = false
- */
-RainLoopApp.prototype.moveMessagesToFolder = function (sFromFolderFullNameRaw, aUidForMove, sToFolderFullNameRaw, bCopy)
-{
- if (sFromFolderFullNameRaw !== sToFolderFullNameRaw && Utils.isArray(aUidForMove) && 0 < aUidForMove.length)
- {
- var
- oFromFolder = RL.cache().getFolderFromCacheList(sFromFolderFullNameRaw),
- oToFolder = RL.cache().getFolderFromCacheList(sToFolderFullNameRaw)
- ;
-
- if (oFromFolder && oToFolder)
- {
- if (Utils.isUnd(bCopy) ? false : !!bCopy)
- {
- this.messagesCopyHelper(oFromFolder.fullNameRaw, oToFolder.fullNameRaw, aUidForMove);
- }
- else
- {
- this.messagesMoveHelper(oFromFolder.fullNameRaw, oToFolder.fullNameRaw, aUidForMove);
- }
-
- RL.data().removeMessagesFromList(oFromFolder.fullNameRaw, aUidForMove, oToFolder.fullNameRaw, bCopy);
- return true;
- }
- }
-
- return false;
-};
-
-/**
- * @param {Function=} fCallback
- */
-RainLoopApp.prototype.folders = function (fCallback)
-{
- this.data().foldersLoading(true);
- this.remote().folders(_.bind(function (sResult, oData) {
-
- RL.data().foldersLoading(false);
- if (Enums.StorageResultType.Success === sResult)
- {
- this.data().setFolders(oData);
- if (fCallback)
- {
- fCallback(true);
- }
- }
- else
- {
- if (fCallback)
- {
- fCallback(false);
- }
- }
- }, this));
-};
-
-RainLoopApp.prototype.reloadOpenPgpKeys = function ()
-{
- if (RL.data().capaOpenPGP())
- {
- var
- aKeys = [],
- oEmail = new EmailModel(),
- oOpenpgpKeyring = RL.data().openpgpKeyring,
- oOpenpgpKeys = oOpenpgpKeyring ? oOpenpgpKeyring.getAllKeys() : []
- ;
-
- _.each(oOpenpgpKeys, function (oItem, iIndex) {
- if (oItem && oItem.primaryKey)
- {
- var
-
- oPrimaryUser = oItem.getPrimaryUser(),
- sUser = (oPrimaryUser && oPrimaryUser.user) ? oPrimaryUser.user.userId.userid
- : (oItem.users && oItem.users[0] ? oItem.users[0].userId.userid : '')
- ;
-
- oEmail.clear();
- oEmail.mailsoParse(sUser);
-
- if (oEmail.validate())
- {
- aKeys.push(new OpenPgpKeyModel(
- iIndex,
- oItem.primaryKey.getFingerprint(),
- oItem.primaryKey.getKeyId().toHex().toLowerCase(),
- sUser,
- oEmail.email,
- oItem.isPrivate(),
- oItem.armor())
- );
- }
- }
- });
-
- RL.data().openpgpkeys(aKeys);
- }
-};
-
-RainLoopApp.prototype.accountsAndIdentities = function ()
-{
- var oRainLoopData = RL.data();
-
- oRainLoopData.accountsLoading(true);
- oRainLoopData.identitiesLoading(true);
-
- RL.remote().accountsAndIdentities(function (sResult, oData) {
-
- oRainLoopData.accountsLoading(false);
- oRainLoopData.identitiesLoading(false);
-
- if (Enums.StorageResultType.Success === sResult && oData.Result)
- {
- var
- sParentEmail = RL.settingsGet('ParentEmail'),
- sAccountEmail = oRainLoopData.accountEmail()
- ;
-
- sParentEmail = '' === sParentEmail ? sAccountEmail : sParentEmail;
-
- if (Utils.isArray(oData.Result['Accounts']))
- {
- oRainLoopData.accounts(_.map(oData.Result['Accounts'], function (sValue) {
- return new AccountModel(sValue, sValue !== sParentEmail);
- }));
- }
-
- if (Utils.isArray(oData.Result['Identities']))
- {
- oRainLoopData.identities(_.map(oData.Result['Identities'], function (oIdentityData) {
-
- var
- sId = Utils.pString(oIdentityData['Id']),
- sEmail = Utils.pString(oIdentityData['Email']),
- oIdentity = new IdentityModel(sId, sEmail, sId !== sAccountEmail)
- ;
-
- oIdentity.name(Utils.pString(oIdentityData['Name']));
- oIdentity.replyTo(Utils.pString(oIdentityData['ReplyTo']));
- oIdentity.bcc(Utils.pString(oIdentityData['Bcc']));
-
- return oIdentity;
- }));
- }
- }
- });
-};
-
-RainLoopApp.prototype.quota = function ()
-{
- this.remote().quota(function (sResult, oData) {
- if (Enums.StorageResultType.Success === sResult && oData && oData.Result &&
- Utils.isArray(oData.Result) && 1 < oData.Result.length &&
- Utils.isPosNumeric(oData.Result[0], true) && Utils.isPosNumeric(oData.Result[1], true))
- {
- RL.data().userQuota(Utils.pInt(oData.Result[1]) * 1024);
- RL.data().userUsageSize(Utils.pInt(oData.Result[0]) * 1024);
- }
- });
-};
-
-/**
- * @param {string} sFolder
- * @param {Array=} aList = []
- */
-RainLoopApp.prototype.folderInformation = function (sFolder, aList)
-{
- if ('' !== Utils.trim(sFolder))
- {
- this.remote().folderInformation(function (sResult, oData) {
- if (Enums.StorageResultType.Success === sResult)
- {
- if (oData && oData.Result && oData.Result.Hash && oData.Result.Folder)
- {
- var
- iUtc = moment().unix(),
- sHash = RL.cache().getFolderHash(oData.Result.Folder),
- oFolder = RL.cache().getFolderFromCacheList(oData.Result.Folder),
- bCheck = false,
- sUid = '',
- aList = [],
- bUnreadCountChange = false,
- oFlags = null
- ;
-
- if (oFolder)
- {
- oFolder.interval = iUtc;
-
- if (oData.Result.Hash)
- {
- RL.cache().setFolderHash(oData.Result.Folder, oData.Result.Hash);
- }
-
- if (Utils.isNormal(oData.Result.MessageCount))
- {
- oFolder.messageCountAll(oData.Result.MessageCount);
- }
-
- if (Utils.isNormal(oData.Result.MessageUnseenCount))
- {
- if (Utils.pInt(oFolder.messageCountUnread()) !== Utils.pInt(oData.Result.MessageUnseenCount))
- {
- bUnreadCountChange = true;
- }
-
- oFolder.messageCountUnread(oData.Result.MessageUnseenCount);
- }
-
- if (bUnreadCountChange)
- {
- RL.cache().clearMessageFlagsFromCacheByFolder(oFolder.fullNameRaw);
- }
-
- if (oData.Result.Flags)
- {
- for (sUid in oData.Result.Flags)
- {
- if (oData.Result.Flags.hasOwnProperty(sUid))
- {
- bCheck = true;
- oFlags = oData.Result.Flags[sUid];
- RL.cache().storeMessageFlagsToCacheByFolderAndUid(oFolder.fullNameRaw, sUid.toString(), [
- !oFlags['IsSeen'], !!oFlags['IsFlagged'], !!oFlags['IsAnswered'], !!oFlags['IsForwarded'], !!oFlags['IsReadReceipt']
- ]);
- }
- }
-
- if (bCheck)
- {
- RL.reloadFlagsCurrentMessageListAndMessageFromCache();
- }
- }
-
- RL.data().initUidNextAndNewMessages(oFolder.fullNameRaw, oData.Result.UidNext, oData.Result.NewMessages);
-
- if (oData.Result.Hash !== sHash || '' === sHash)
- {
- if (oFolder.fullNameRaw === RL.data().currentFolderFullNameRaw())
- {
- RL.reloadMessageList();
- }
- else if ('INBOX' === oFolder.fullNameRaw)
- {
- RL.recacheInboxMessageList();
- }
- }
- else if (bUnreadCountChange)
- {
- if (oFolder.fullNameRaw === RL.data().currentFolderFullNameRaw())
- {
- aList = RL.data().messageList();
- if (Utils.isNonEmptyArray(aList))
- {
- RL.folderInformation(oFolder.fullNameRaw, aList);
- }
- }
- }
- }
- }
- }
- }, sFolder, aList);
- }
-};
-
-/**
- * @param {boolean=} bBoot = false
- */
-RainLoopApp.prototype.folderInformationMultiply = function (bBoot)
-{
- bBoot = Utils.isUnd(bBoot) ? false : !!bBoot;
-
- var
- iUtc = moment().unix(),
- aFolders = RL.data().getNextFolderNames(bBoot)
- ;
-
- if (Utils.isNonEmptyArray(aFolders))
- {
- this.remote().folderInformationMultiply(function (sResult, oData) {
- if (Enums.StorageResultType.Success === sResult)
- {
- if (oData && oData.Result && oData.Result.List && Utils.isNonEmptyArray(oData.Result.List))
- {
- _.each(oData.Result.List, function (oItem) {
-
- var
- aList = [],
- sHash = RL.cache().getFolderHash(oItem.Folder),
- oFolder = RL.cache().getFolderFromCacheList(oItem.Folder),
- bUnreadCountChange = false
- ;
-
- if (oFolder)
- {
- oFolder.interval = iUtc;
-
- if (oItem.Hash)
- {
- RL.cache().setFolderHash(oItem.Folder, oItem.Hash);
- }
-
- if (Utils.isNormal(oItem.MessageCount))
- {
- oFolder.messageCountAll(oItem.MessageCount);
- }
-
- if (Utils.isNormal(oItem.MessageUnseenCount))
- {
- if (Utils.pInt(oFolder.messageCountUnread()) !== Utils.pInt(oItem.MessageUnseenCount))
- {
- bUnreadCountChange = true;
- }
-
- oFolder.messageCountUnread(oItem.MessageUnseenCount);
- }
-
- if (bUnreadCountChange)
- {
- RL.cache().clearMessageFlagsFromCacheByFolder(oFolder.fullNameRaw);
- }
-
- if (oItem.Hash !== sHash || '' === sHash)
- {
- if (oFolder.fullNameRaw === RL.data().currentFolderFullNameRaw())
- {
- RL.reloadMessageList();
- }
- }
- else if (bUnreadCountChange)
- {
- if (oFolder.fullNameRaw === RL.data().currentFolderFullNameRaw())
- {
- aList = RL.data().messageList();
- if (Utils.isNonEmptyArray(aList))
- {
- RL.folderInformation(oFolder.fullNameRaw, aList);
- }
- }
- }
- }
- });
-
- if (bBoot)
- {
- RL.folderInformationMultiply(true);
- }
- }
- }
- }, aFolders);
- }
-};
-
-RainLoopApp.prototype.setMessageSeen = function (oMessage)
-{
- if (oMessage.unseen())
- {
- oMessage.unseen(false);
-
- var oFolder = RL.cache().getFolderFromCacheList(oMessage.folderFullNameRaw);
- if (oFolder)
- {
- oFolder.messageCountUnread(0 <= oFolder.messageCountUnread() - 1 ?
- oFolder.messageCountUnread() - 1 : 0);
- }
-
- RL.cache().storeMessageFlagsToCache(oMessage);
- RL.reloadFlagsCurrentMessageListAndMessageFromCache();
- }
-
- RL.remote().messageSetSeen(Utils.emptyFunction, oMessage.folderFullNameRaw, [oMessage.uid], true);
-};
-
-RainLoopApp.prototype.googleConnect = function ()
-{
- window.open(RL.link().socialGoogle(), 'Google', 'left=200,top=100,width=650,height=600,menubar=no,status=no,resizable=yes,scrollbars=yes');
-};
-
-RainLoopApp.prototype.twitterConnect = function ()
-{
- window.open(RL.link().socialTwitter(), 'Twitter', 'left=200,top=100,width=650,height=350,menubar=no,status=no,resizable=yes,scrollbars=yes');
-};
-
-RainLoopApp.prototype.facebookConnect = function ()
-{
- window.open(RL.link().socialFacebook(), 'Facebook', 'left=200,top=100,width=650,height=335,menubar=no,status=no,resizable=yes,scrollbars=yes');
-};
-
-/**
- * @param {boolean=} bFireAllActions
- */
-RainLoopApp.prototype.socialUsers = function (bFireAllActions)
-{
- var oRainLoopData = RL.data();
-
- if (bFireAllActions)
- {
- oRainLoopData.googleActions(true);
- oRainLoopData.facebookActions(true);
- oRainLoopData.twitterActions(true);
- }
-
- RL.remote().socialUsers(function (sResult, oData) {
-
- if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
- {
- oRainLoopData.googleUserName(oData.Result['Google'] || '');
- oRainLoopData.facebookUserName(oData.Result['Facebook'] || '');
- oRainLoopData.twitterUserName(oData.Result['Twitter'] || '');
- }
- else
- {
- oRainLoopData.googleUserName('');
- oRainLoopData.facebookUserName('');
- oRainLoopData.twitterUserName('');
- }
-
- oRainLoopData.googleLoggined('' !== oRainLoopData.googleUserName());
- oRainLoopData.facebookLoggined('' !== oRainLoopData.facebookUserName());
- oRainLoopData.twitterLoggined('' !== oRainLoopData.twitterUserName());
-
- oRainLoopData.googleActions(false);
- oRainLoopData.facebookActions(false);
- oRainLoopData.twitterActions(false);
- });
-};
-
-RainLoopApp.prototype.googleDisconnect = function ()
-{
- RL.data().googleActions(true);
- RL.remote().googleDisconnect(function () {
- RL.socialUsers();
- });
-};
-
-RainLoopApp.prototype.facebookDisconnect = function ()
-{
- RL.data().facebookActions(true);
- RL.remote().facebookDisconnect(function () {
- RL.socialUsers();
- });
-};
-
-RainLoopApp.prototype.twitterDisconnect = function ()
-{
- RL.data().twitterActions(true);
- RL.remote().twitterDisconnect(function () {
- RL.socialUsers();
- });
-};
-
-/**
- * @param {Array} aSystem
- * @param {Array} aList
- * @param {Array=} aDisabled
- * @param {Array=} aHeaderLines
- * @param {?number=} iUnDeep
- * @param {Function=} fDisableCallback
- * @param {Function=} fVisibleCallback
- * @param {Function=} fRenameCallback
- * @param {boolean=} bSystem
- * @param {boolean=} bBuildUnvisible
- * @return {Array}
- */
-RainLoopApp.prototype.folderListOptionsBuilder = function (aSystem, aList, aDisabled, aHeaderLines, iUnDeep, fDisableCallback, fVisibleCallback, fRenameCallback, bSystem, bBuildUnvisible)
-{
- var
- iIndex = 0,
- iLen = 0,
- /**
- * @type {?FolderModel}
- */
- oItem = null,
- bSep = false,
- sDeepPrefix = '\u00A0\u00A0\u00A0',
- aResult = []
- ;
-
- bSystem = !Utils.isNormal(bSystem) ? 0 < aSystem.length : bSystem;
- bBuildUnvisible = Utils.isUnd(bBuildUnvisible) ? false : !!bBuildUnvisible;
- iUnDeep = !Utils.isNormal(iUnDeep) ? 0 : iUnDeep;
- fDisableCallback = Utils.isNormal(fDisableCallback) ? fDisableCallback : null;
- fVisibleCallback = Utils.isNormal(fVisibleCallback) ? fVisibleCallback : null;
- fRenameCallback = Utils.isNormal(fRenameCallback) ? fRenameCallback : null;
-
- if (!Utils.isArray(aDisabled))
- {
- aDisabled = [];
- }
-
- if (!Utils.isArray(aHeaderLines))
- {
- aHeaderLines = [];
- }
-
- for (iIndex = 0, iLen = aHeaderLines.length; iIndex < iLen; iIndex++)
- {
- aResult.push({
- 'id': aHeaderLines[iIndex][0],
- 'name': aHeaderLines[iIndex][1],
- 'system': false,
- 'seporator': false,
- 'disabled': false
- });
- }
-
- bSep = true;
- for (iIndex = 0, iLen = aSystem.length; iIndex < iLen; iIndex++)
- {
- oItem = aSystem[iIndex];
- if (fVisibleCallback ? fVisibleCallback.call(null, oItem) : true)
- {
- if (bSep && 0 < aResult.length)
- {
- aResult.push({
- 'id': '---',
- 'name': '---',
- 'system': false,
- 'seporator': true,
- 'disabled': true
- });
- }
-
- bSep = false;
- aResult.push({
- 'id': oItem.fullNameRaw,
- 'name': fRenameCallback ? fRenameCallback.call(null, oItem) : oItem.name(),
- 'system': true,
- 'seporator': false,
- 'disabled': !oItem.selectable || -1 < Utils.inArray(oItem.fullNameRaw, aDisabled) ||
- (fDisableCallback ? fDisableCallback.call(null, oItem) : false)
- });
- }
- }
-
- bSep = true;
- for (iIndex = 0, iLen = aList.length; iIndex < iLen; iIndex++)
- {
- oItem = aList[iIndex];
- if (oItem.subScribed() || !oItem.existen)
- {
- if (fVisibleCallback ? fVisibleCallback.call(null, oItem) : true)
- {
- if (Enums.FolderType.User === oItem.type() || !bSystem || 0 < oItem.subFolders().length)
- {
- if (bSep && 0 < aResult.length)
- {
- aResult.push({
- 'id': '---',
- 'name': '---',
- 'system': false,
- 'seporator': true,
- 'disabled': true
- });
- }
-
- bSep = false;
- aResult.push({
- 'id': oItem.fullNameRaw,
- 'name': (new window.Array(oItem.deep + 1 - iUnDeep)).join(sDeepPrefix) +
- (fRenameCallback ? fRenameCallback.call(null, oItem) : oItem.name()),
- 'system': false,
- 'seporator': false,
- 'disabled': !oItem.selectable || -1 < Utils.inArray(oItem.fullNameRaw, aDisabled) ||
- (fDisableCallback ? fDisableCallback.call(null, oItem) : false)
- });
- }
- }
- }
-
- if (oItem.subScribed() && 0 < oItem.subFolders().length)
- {
- aResult = aResult.concat(RL.folderListOptionsBuilder([], oItem.subFolders(), aDisabled, [],
- iUnDeep, fDisableCallback, fVisibleCallback, fRenameCallback, bSystem, bBuildUnvisible));
- }
- }
-
- return aResult;
-};
-
-/**
- * @param {string} sQuery
- * @param {Function} fCallback
- */
-RainLoopApp.prototype.getAutocomplete = function (sQuery, fCallback)
-{
- var
- aData = []
- ;
-
- RL.remote().suggestions(function (sResult, oData) {
- if (Enums.StorageResultType.Success === sResult && oData && Utils.isArray(oData.Result))
- {
- aData = _.map(oData.Result, function (aItem) {
- return aItem && aItem[0] ? new EmailModel(aItem[0], aItem[1]) : null;
- });
-
- fCallback(_.compact(aData));
- }
- else if (Enums.StorageResultType.Abort !== sResult)
- {
- fCallback([]);
- }
-
- }, sQuery);
-};
-
-/**
- * @param {string} sQuery
- * @param {Function} fCallback
- */
-RainLoopApp.prototype.getContactTagsAutocomplete = function (sQuery, fCallback)
-{
- fCallback(_.filter(RL.data().contactTags(), function (oContactTag) {
- return oContactTag && oContactTag.filterHelper(sQuery);
- }));
-};
-
-/**
- * @param {string} sMailToUrl
- * @returns {boolean}
- */
-RainLoopApp.prototype.mailToHelper = function (sMailToUrl)
-{
- if (sMailToUrl && 'mailto:' === sMailToUrl.toString().substr(0, 7).toLowerCase())
- {
- sMailToUrl = sMailToUrl.toString().substr(7);
-
- var
- oParams = {},
- oEmailModel = null,
- sEmail = sMailToUrl.replace(/\?.+$/, ''),
- sQueryString = sMailToUrl.replace(/^[^\?]*\?/, '')
- ;
-
- oEmailModel = new EmailModel();
- oEmailModel.parse(window.decodeURIComponent(sEmail));
-
- if (oEmailModel && oEmailModel.email)
- {
- oParams = Utils.simpleQueryParser(sQueryString);
- kn.showScreenPopup(PopupsComposeViewModel, [Enums.ComposeType.Empty, null, [oEmailModel],
- Utils.isUnd(oParams.subject) ? null : Utils.pString(oParams.subject),
- Utils.isUnd(oParams.body) ? null : Utils.plainToHtml(Utils.pString(oParams.body))
- ]);
- }
-
- return true;
- }
-
- return false;
-};
-
-RainLoopApp.prototype.bootstart = function ()
-{
- RL.pub('rl.bootstart');
- AbstractApp.prototype.bootstart.call(this);
-
- RL.data().populateDataOnStart();
-
- var
- sCustomLoginLink = '',
- sJsHash = RL.settingsGet('JsHash'),
- iContactsSyncInterval = Utils.pInt(RL.settingsGet('ContactsSyncInterval')),
- bGoogle = RL.settingsGet('AllowGoogleSocial'),
- bFacebook = RL.settingsGet('AllowFacebookSocial'),
- bTwitter = RL.settingsGet('AllowTwitterSocial')
- ;
-
- if (!RL.settingsGet('ChangePasswordIsAllowed'))
- {
- Utils.removeSettingsViewModel(SettingsChangePasswordScreen);
- }
-
- if (!RL.settingsGet('ContactsIsAllowed'))
- {
- Utils.removeSettingsViewModel(SettingsContacts);
- }
-
- if (!RL.capa(Enums.Capa.AdditionalAccounts))
- {
- Utils.removeSettingsViewModel(SettingsAccounts);
- }
-
- if (RL.capa(Enums.Capa.AdditionalIdentities))
- {
- Utils.removeSettingsViewModel(SettingsIdentity);
- }
- else
- {
- Utils.removeSettingsViewModel(SettingsIdentities);
- }
-
- if (!RL.capa(Enums.Capa.OpenPGP))
- {
- Utils.removeSettingsViewModel(SettingsOpenPGP);
- }
-
- if (!RL.capa(Enums.Capa.TwoFactor))
- {
- Utils.removeSettingsViewModel(SettingsSecurity);
- }
-
- if (!RL.capa(Enums.Capa.Themes))
- {
- Utils.removeSettingsViewModel(SettingsThemes);
- }
-
- if (!RL.capa(Enums.Capa.Filters))
- {
- Utils.removeSettingsViewModel(SettingsFilters);
- }
-
- if (!bGoogle && !bFacebook && !bTwitter)
- {
- Utils.removeSettingsViewModel(SettingsSocialScreen);
- }
-
- Utils.initOnStartOrLangChange(function () {
-
- $.extend(true, $.magnificPopup.defaults, {
- 'tClose': Utils.i18n('MAGNIFIC_POPUP/CLOSE'),
- 'tLoading': Utils.i18n('MAGNIFIC_POPUP/LOADING'),
- 'gallery': {
- 'tPrev': Utils.i18n('MAGNIFIC_POPUP/GALLERY_PREV'),
- 'tNext': Utils.i18n('MAGNIFIC_POPUP/GALLERY_NEXT'),
- 'tCounter': Utils.i18n('MAGNIFIC_POPUP/GALLERY_COUNTER')
- },
- 'image': {
- 'tError': Utils.i18n('MAGNIFIC_POPUP/IMAGE_ERROR')
- },
- 'ajax': {
- 'tError': Utils.i18n('MAGNIFIC_POPUP/AJAX_ERROR')
- }
- });
-
- }, this);
-
- if (window.SimplePace)
- {
- window.SimplePace.set(70);
- window.SimplePace.sleep();
- }
-
- if (!!RL.settingsGet('Auth'))
- {
- this.setTitle(Utils.i18n('TITLES/LOADING'));
-
- this.folders(_.bind(function (bValue) {
-
- kn.hideLoading();
-
- if (bValue)
- {
- if (window.$LAB && window.crypto && window.crypto.getRandomValues && RL.capa(Enums.Capa.OpenPGP))
- {
- window.$LAB.script(window.openpgp ? '' : RL.link().openPgpJs()).wait(function () {
- if (window.openpgp)
- {
- RL.data().openpgpKeyring = new window.openpgp.Keyring();
- RL.data().capaOpenPGP(true);
-
- RL.pub('openpgp.init');
-
- RL.reloadOpenPgpKeys();
- }
- });
- }
- else
- {
- RL.data().capaOpenPGP(false);
- }
-
- kn.startScreens([MailBoxScreen, SettingsScreen]);
-
- if (bGoogle || bFacebook || bTwitter)
- {
- RL.socialUsers(true);
- }
-
- RL.sub('interval.2m', function () {
- RL.folderInformation('INBOX');
- });
-
- RL.sub('interval.2m', function () {
- var sF = RL.data().currentFolderFullNameRaw();
- if ('INBOX' !== sF)
- {
- RL.folderInformation(sF);
- }
- });
-
- RL.sub('interval.3m', function () {
- RL.folderInformationMultiply();
- });
-
- RL.sub('interval.5m', function () {
- RL.quota();
- });
-
- RL.sub('interval.10m', function () {
- RL.folders();
- });
-
- iContactsSyncInterval = 5 <= iContactsSyncInterval ? iContactsSyncInterval : 20;
- iContactsSyncInterval = 320 >= iContactsSyncInterval ? iContactsSyncInterval : 320;
-
- window.setInterval(function () {
- RL.contactsSync();
- }, iContactsSyncInterval * 60000 + 5000);
-
- _.delay(function () {
- RL.contactsSync();
- }, 5000);
-
- _.delay(function () {
- RL.folderInformationMultiply(true);
- }, 500);
-
- Plugins.runHook('rl-start-user-screens');
- RL.pub('rl.bootstart-user-screens');
-
- if (!!RL.settingsGet('AccountSignMe') && window.navigator.registerProtocolHandler)
- {
- _.delay(function () {
- try {
- window.navigator.registerProtocolHandler('mailto',
- window.location.protocol + '//' + window.location.host + window.location.pathname + '?mailto&to=%s',
- '' + (RL.settingsGet('Title') || 'RainLoop'));
- } catch(e) {}
-
- if (RL.settingsGet('MailToEmail'))
- {
- RL.mailToHelper(RL.settingsGet('MailToEmail'));
- }
- }, 500);
- }
- }
- else
- {
- kn.startScreens([LoginScreen]);
-
- Plugins.runHook('rl-start-login-screens');
- RL.pub('rl.bootstart-login-screens');
- }
-
- if (window.SimplePace)
- {
- window.SimplePace.set(100);
- }
-
- if (!Globals.bMobileDevice)
- {
- _.defer(function () {
- Utils.initLayoutResizer('#rl-left', '#rl-right', Enums.ClientSideKeyName.FolderListSize);
- });
- }
-
- }, this));
- }
- else
- {
- sCustomLoginLink = Utils.pString(RL.settingsGet('CustomLoginLink'));
- if (!sCustomLoginLink)
- {
- kn.hideLoading();
- kn.startScreens([LoginScreen]);
-
- Plugins.runHook('rl-start-login-screens');
- RL.pub('rl.bootstart-login-screens');
-
- if (window.SimplePace)
- {
- window.SimplePace.set(100);
- }
- }
- else
- {
- kn.routeOff();
- kn.setHash(RL.link().root(), true);
- kn.routeOff();
-
- _.defer(function () {
- window.location.href = sCustomLoginLink;
- });
- }
- }
-
- if (bGoogle)
- {
- window['rl_' + sJsHash + '_google_service'] = function () {
- RL.data().googleActions(true);
- RL.socialUsers();
- };
- }
-
- if (bFacebook)
- {
- window['rl_' + sJsHash + '_facebook_service'] = function () {
- RL.data().facebookActions(true);
- RL.socialUsers();
- };
- }
-
- if (bTwitter)
- {
- window['rl_' + sJsHash + '_twitter_service'] = function () {
- RL.data().twitterActions(true);
- RL.socialUsers();
- };
- }
-
- RL.sub('interval.1m', function () {
- Globals.momentTrigger(!Globals.momentTrigger());
- });
-
- Plugins.runHook('rl-start-screens');
- RL.pub('rl.bootstart-end');
-};
-
-/**
- * @type {RainLoopApp}
- */
-RL = new RainLoopApp();
-
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-$html.addClass(Globals.bMobileDevice ? 'mobile' : 'no-mobile');
-
-$window.keydown(Utils.killCtrlAandS).keyup(Utils.killCtrlAandS);
-$window.unload(function () {
- Globals.bUnload = true;
-});
-
-$html.on('click.dropdown.data-api', function () {
- Utils.detectDropdownVisibility();
-});
-
-// export
-window['rl'] = window['rl'] || {};
-window['rl']['addHook'] = Plugins.addHook;
-window['rl']['settingsGet'] = Plugins.mainSettingsGet;
-window['rl']['remoteRequest'] = Plugins.remoteRequest;
-window['rl']['pluginSettingsGet'] = Plugins.settingsGet;
-window['rl']['addSettingsViewModel'] = Utils.addSettingsViewModel;
-window['rl']['createCommand'] = Utils.createCommand;
-
-window['rl']['EmailModel'] = EmailModel;
-window['rl']['Enums'] = Enums;
-
-window['__RLBOOT'] = function (fCall) {
-
- // boot
- $(function () {
-
- if (window['rainloopTEMPLATES'] && window['rainloopTEMPLATES'][0])
- {
- $('#rl-templates').html(window['rainloopTEMPLATES'][0]);
_.delay(function () {
- window['rainloopAppData'] = {};
- window['rainloopI18N'] = {};
- window['rainloopTEMPLATES'] = {};
- kn.setBoot(RL).bootstart();
- $html.removeClass('no-js rl-booted-trigger').addClass('rl-booted');
-
- }, 50);
+ _.each(aContacts, function (oContact) {
+ oKoContacts.remove(oContact);
+ });
+
+ }, 500);
+ }
+ };
+
+ PopupsContactsViewModel.prototype.deleteSelectedContacts = function ()
+ {
+ if (0 < this.contactsCheckedOrSelected().length)
+ {
+ Remote.contactsDelete(
+ _.bind(this.deleteResponse, this),
+ this.contactsCheckedOrSelectedUids()
+ );
+
+ this.removeCheckedOrSelectedContactsFromList();
+ }
+ };
+
+ /**
+ * @param {string} sResult
+ * @param {AjaxJsonDefaultResponse} oData
+ */
+ PopupsContactsViewModel.prototype.deleteResponse = function (sResult, oData)
+ {
+ if (500 < (Enums.StorageResultType.Success === sResult && oData && oData.Time ? Utils.pInt(oData.Time) : 0))
+ {
+ this.reloadContactList(this.bDropPageAfterDelete);
}
else
{
- fCall(false);
+ _.delay((function (self) {
+ return function () {
+ self.reloadContactList(self.bDropPageAfterDelete);
+ };
+ }(this)), 500);
+ }
+ };
+
+ PopupsContactsViewModel.prototype.removeProperty = function (oProp)
+ {
+ this.viewProperties.remove(oProp);
+ };
+
+ /**
+ * @param {?ContactModel} oContact
+ */
+ PopupsContactsViewModel.prototype.populateViewContact = function (oContact)
+ {
+ var
+ sId = '',
+ sLastName = '',
+ sFirstName = '',
+ aList = []
+ ;
+
+ this.watchHash(false);
+
+ this.emptySelection(false);
+ this.viewReadOnly(false);
+ this.viewTags('');
+
+ if (oContact)
+ {
+ sId = oContact.idContact;
+ if (Utils.isNonEmptyArray(oContact.properties))
+ {
+ _.each(oContact.properties, function (aProperty) {
+ if (aProperty && aProperty[0])
+ {
+ if (Enums.ContactPropertyType.LastName === aProperty[0])
+ {
+ sLastName = aProperty[1];
+ }
+ else if (Enums.ContactPropertyType.FirstName === aProperty[0])
+ {
+ sFirstName = aProperty[1];
+ }
+ else
+ {
+ aList.push(new ContactPropertyModel(aProperty[0], aProperty[2] || '', aProperty[1]));
+ }
+ }
+ });
+ }
+
+ this.viewTags(oContact.tags);
+
+ this.viewReadOnly(!!oContact.readOnly);
}
- window['__RLBOOT'] = null;
- });
-};
+ this.viewTags.focusTrigger.valueHasMutated();
+ this.viewTags.visibility('' !== this.viewTags());
+ aList.unshift(new ContactPropertyModel(Enums.ContactPropertyType.LastName, '', sLastName, false,
+ this.getPropertyPlceholder(Enums.ContactPropertyType.LastName)));
-}(window, jQuery, ko, crossroads, hasher, moment, Jua, _, ifvisible, key));
\ No newline at end of file
+ aList.unshift(new ContactPropertyModel(Enums.ContactPropertyType.FirstName, '', sFirstName, !oContact,
+ this.getPropertyPlceholder(Enums.ContactPropertyType.FirstName)));
+
+ this.viewID(sId);
+ this.viewProperties([]);
+ this.viewProperties(aList);
+
+ this.watchDirty(false);
+ this.watchHash(true);
+ };
+
+ /**
+ * @param {boolean=} bDropPagePosition = false
+ */
+ PopupsContactsViewModel.prototype.reloadContactList = function (bDropPagePosition)
+ {
+ var
+ self = this,
+ iOffset = (this.contactsPage() - 1) * Consts.Defaults.ContactsPerPage
+ ;
+
+ this.bDropPageAfterDelete = false;
+
+ if (Utils.isUnd(bDropPagePosition) ? false : !!bDropPagePosition)
+ {
+ this.contactsPage(1);
+ iOffset = 0;
+ }
+
+ this.contacts.loading(true);
+ Remote.contacts(function (sResult, oData) {
+ var
+ iCount = 0,
+ aList = [],
+ aTagsList = []
+ ;
+
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result && oData.Result.List)
+ {
+ if (Utils.isNonEmptyArray(oData.Result.List))
+ {
+ aList = _.map(oData.Result.List, function (oItem) {
+ var oContact = new ContactModel();
+ return oContact.parse(oItem) ? oContact : null;
+ });
+
+ aList = _.compact(aList);
+
+ iCount = Utils.pInt(oData.Result.Count);
+ iCount = 0 < iCount ? iCount : 0;
+ }
+
+ if (Utils.isNonEmptyArray(oData.Result.Tags))
+ {
+ aTagsList = _.map(oData.Result.Tags, function (oItem) {
+ var oContactTag = new ContactTagModel();
+ return oContactTag.parse(oItem) ? oContactTag : null;
+ });
+
+ aTagsList = _.compact(aTagsList);
+ }
+ }
+
+ self.contactsCount(iCount);
+
+ self.contacts(aList);
+ self.contacts.loading(false);
+ self.contactTags(aTagsList);
+
+ self.viewClearSearch('' !== self.search());
+
+ }, iOffset, Consts.Defaults.ContactsPerPage, this.search());
+ };
+
+ PopupsContactsViewModel.prototype.onBuild = function (oDom)
+ {
+ this.oContentVisible = $('.b-list-content', oDom);
+ this.oContentScrollable = $('.content', this.oContentVisible);
+
+ this.selector.init(this.oContentVisible, this.oContentScrollable, Enums.KeyState.ContactList);
+
+ var self = this;
+
+ key('delete', Enums.KeyState.ContactList, function () {
+ self.deleteCommand();
+ return false;
+ });
+
+ oDom
+ .on('click', '.e-pagenator .e-page', function () {
+ var oPage = ko.dataFor(this);
+ if (oPage)
+ {
+ self.contactsPage(Utils.pInt(oPage.value));
+ self.reloadContactList();
+ }
+ })
+ ;
+
+ this.initUploader();
+ };
+
+ PopupsContactsViewModel.prototype.onShow = function ()
+ {
+ kn.routeOff();
+ this.reloadContactList(true);
+ };
+
+ PopupsContactsViewModel.prototype.onHide = function ()
+ {
+ kn.routeOn();
+ this.currentContact(null);
+ this.emptySelection(true);
+ this.search('');
+ this.contactsCount(0);
+ this.contacts([]);
+ };
+
+ module.exports = PopupsContactsViewModel;
+
+}(module));
+},{"../../Boots/RainLoopApp.js":4,"../../Common/Consts.js":6,"../../Common/Enums.js":7,"../../Common/Globals.js":9,"../../Common/LinkBuilder.js":10,"../../Common/Selector.js":13,"../../Common/Utils.js":14,"../../External/jquery.js":26,"../../External/key.js":27,"../../External/ko.js":28,"../../External/underscore.js":31,"../../External/window.js":32,"../../Knoin/Knoin.js":33,"../../Knoin/KnoinAbstractViewModel.js":36,"../../Storages/WebMailAjaxRemoteStorage.js":65,"../../Storages/WebMailDataStorage.js":67}],80:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ ko = require('../../External/ko.js'),
+
+ Consts = require('../../Common/Consts.js'),
+ Utils = require('../../Common/Utils.js'),
+
+ Data = require('../../Storages/WebMailDataStorage.js'),
+
+ kn = require('../../Knoin/Knoin.js'),
+ KnoinAbstractViewModel = require('../../Knoin/KnoinAbstractViewModel.js')
+ ;
+
+ /**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+ function PopupsFilterViewModel()
+ {
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsFilter');
+
+ this.filter = ko.observable(null);
+
+ this.selectedFolderValue = ko.observable(Consts.Values.UnuseOptionValue);
+ this.folderSelectList = Data.folderMenuForMove;
+ this.defautOptionsAfterRender = Utils.defautOptionsAfterRender;
+
+ kn.constructorEnd(this);
+ }
+
+ kn.extendAsViewModel('PopupsFilterViewModel', PopupsFilterViewModel);
+
+ PopupsFilterViewModel.prototype.clearPopup = function ()
+ {
+ // TODO
+ };
+
+ PopupsFilterViewModel.prototype.onShow = function (oFilter)
+ {
+ this.clearPopup();
+
+ this.filter(oFilter);
+ };
+
+ module.exports = PopupsFilterViewModel;
+
+}(module));
+},{"../../Common/Consts.js":6,"../../Common/Utils.js":14,"../../External/ko.js":28,"../../Knoin/Knoin.js":33,"../../Knoin/KnoinAbstractViewModel.js":36,"../../Storages/WebMailDataStorage.js":67}],81:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ ko = require('../../External/ko.js'),
+
+ Enums = require('../../Common/Enums.js'),
+ Consts = require('../../Common/Consts.js'),
+ Utils = require('../../Common/Utils.js'),
+
+ Data = require('../../Storages/WebMailDataStorage.js'),
+ Remote = require('../../Storages/WebMailAjaxRemoteStorage.js'),
+
+ RL = require('../../Boots/RainLoopApp.js'),
+
+ kn = require('../../Knoin/Knoin.js'),
+ KnoinAbstractViewModel = require('../../Knoin/KnoinAbstractViewModel.js')
+ ;
+
+ /**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+ function PopupsFolderCreateViewModel()
+ {
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsFolderCreate');
+
+ Utils.initOnStartOrLangChange(function () {
+ this.sNoParentText = Utils.i18n('POPUPS_CREATE_FOLDER/SELECT_NO_PARENT');
+ }, this);
+
+ this.folderName = ko.observable('');
+ this.folderName.focused = ko.observable(false);
+
+ this.selectedParentValue = ko.observable(Consts.Values.UnuseOptionValue);
+
+ this.parentFolderSelectList = ko.computed(function () {
+
+ var
+ aTop = [],
+ fDisableCallback = null,
+ fVisibleCallback = null,
+ aList = Data.folderList(),
+ fRenameCallback = function (oItem) {
+ return oItem ? (oItem.isSystemFolder() ? oItem.name() + ' ' + oItem.manageFolderSystemName() : oItem.name()) : '';
+ }
+ ;
+
+ aTop.push(['', this.sNoParentText]);
+
+ if ('' !== Data.namespace)
+ {
+ fDisableCallback = function (oItem)
+ {
+ return Data.namespace !== oItem.fullNameRaw.substr(0, Data.namespace.length);
+ };
+ }
+
+ return Utils.folderListOptionsBuilder([], aList, [], aTop, null, fDisableCallback, fVisibleCallback, fRenameCallback);
+
+ }, this);
+
+ // commands
+ this.createFolder = Utils.createCommand(this, function () {
+
+ var sParentFolderName = this.selectedParentValue();
+ if ('' === sParentFolderName && 1 < Data.namespace.length)
+ {
+ sParentFolderName = Data.namespace.substr(0, Data.namespace.length - 1);
+ }
+
+ Data.foldersCreating(true);
+ Remote.folderCreate(function (sResult, oData) {
+
+ Data.foldersCreating(false);
+ if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
+ {
+ RL.folders();
+ }
+ else
+ {
+ Data.foldersListError(
+ oData && oData.ErrorCode ? Utils.getNotification(oData.ErrorCode) : Utils.i18n('NOTIFICATIONS/CANT_CREATE_FOLDER'));
+ }
+
+ }, this.folderName(), sParentFolderName);
+
+ this.cancelCommand();
+
+ }, function () {
+ return this.simpleFolderNameValidation(this.folderName());
+ });
+
+ this.defautOptionsAfterRender = Utils.defautOptionsAfterRender;
+
+ kn.constructorEnd(this);
+ }
+
+ kn.extendAsViewModel('PopupsFolderCreateViewModel', PopupsFolderCreateViewModel);
+
+ PopupsFolderCreateViewModel.prototype.sNoParentText = '';
+
+ PopupsFolderCreateViewModel.prototype.simpleFolderNameValidation = function (sName)
+ {
+ return (/^[^\\\/]+$/g).test(Utils.trim(sName));
+ };
+
+ PopupsFolderCreateViewModel.prototype.clearPopup = function ()
+ {
+ this.folderName('');
+ this.selectedParentValue('');
+ this.folderName.focused(false);
+ };
+
+ PopupsFolderCreateViewModel.prototype.onShow = function ()
+ {
+ this.clearPopup();
+ };
+
+ PopupsFolderCreateViewModel.prototype.onFocus = function ()
+ {
+ this.folderName.focused(true);
+ };
+
+ module.exports = PopupsFolderCreateViewModel;
+
+}(module));
+},{"../../Boots/RainLoopApp.js":4,"../../Common/Consts.js":6,"../../Common/Enums.js":7,"../../Common/Utils.js":14,"../../External/ko.js":28,"../../Knoin/Knoin.js":33,"../../Knoin/KnoinAbstractViewModel.js":36,"../../Storages/WebMailAjaxRemoteStorage.js":65,"../../Storages/WebMailDataStorage.js":67}],82:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ ko = require('../../External/ko.js'),
+
+ Enums = require('../../Common/Enums.js'),
+ Consts = require('../../Common/Consts.js'),
+ Utils = require('../../Common/Utils.js'),
+
+ AppSettings = require('../../Storages/AppSettings.js'),
+ Data = require('../../Storages/WebMailDataStorage.js'),
+ Remote = require('../../Storages/WebMailAjaxRemoteStorage.js'),
+
+ RL = require('../../Boots/RainLoopApp.js'),
+
+ kn = require('../../Knoin/Knoin.js'),
+ KnoinAbstractViewModel = require('../../Knoin/KnoinAbstractViewModel.js')
+ ;
+
+ /**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+ function PopupsFolderSystemViewModel()
+ {
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsFolderSystem');
+
+ Utils.initOnStartOrLangChange(function () {
+ this.sChooseOnText = Utils.i18n('POPUPS_SYSTEM_FOLDERS/SELECT_CHOOSE_ONE');
+ this.sUnuseText = Utils.i18n('POPUPS_SYSTEM_FOLDERS/SELECT_UNUSE_NAME');
+ }, this);
+
+ this.notification = ko.observable('');
+
+ this.folderSelectList = ko.computed(function () {
+ return Utils.folderListOptionsBuilder([], Data.folderList(), Data.folderListSystemNames(), [
+ ['', this.sChooseOnText],
+ [Consts.Values.UnuseOptionValue, this.sUnuseText]
+ ]);
+ }, this);
+
+ var
+ self = this,
+ fSaveSystemFolders = null,
+ fCallback = null
+ ;
+
+ this.sentFolder = Data.sentFolder;
+ this.draftFolder = Data.draftFolder;
+ this.spamFolder = Data.spamFolder;
+ this.trashFolder = Data.trashFolder;
+ this.archiveFolder = Data.archiveFolder;
+
+ fSaveSystemFolders = _.debounce(function () {
+
+ AppSettings.settingsSet('SentFolder', self.sentFolder());
+ AppSettings.settingsSet('DraftFolder', self.draftFolder());
+ AppSettings.settingsSet('SpamFolder', self.spamFolder());
+ AppSettings.settingsSet('TrashFolder', self.trashFolder());
+ AppSettings.settingsSet('ArchiveFolder', self.archiveFolder());
+
+ Remote.saveSystemFolders(Utils.emptyFunction, {
+ 'SentFolder': self.sentFolder(),
+ 'DraftFolder': self.draftFolder(),
+ 'SpamFolder': self.spamFolder(),
+ 'TrashFolder': self.trashFolder(),
+ 'ArchiveFolder': self.archiveFolder(),
+ 'NullFolder': 'NullFolder'
+ });
+
+ }, 1000);
+
+ fCallback = function () {
+
+ AppSettings.settingsSet('SentFolder', self.sentFolder());
+ AppSettings.settingsSet('DraftFolder', self.draftFolder());
+ AppSettings.settingsSet('SpamFolder', self.spamFolder());
+ AppSettings.settingsSet('TrashFolder', self.trashFolder());
+ AppSettings.settingsSet('ArchiveFolder', self.archiveFolder());
+
+ fSaveSystemFolders();
+ };
+
+ this.sentFolder.subscribe(fCallback);
+ this.draftFolder.subscribe(fCallback);
+ this.spamFolder.subscribe(fCallback);
+ this.trashFolder.subscribe(fCallback);
+ this.archiveFolder.subscribe(fCallback);
+
+ this.defautOptionsAfterRender = Utils.defautOptionsAfterRender;
+
+ kn.constructorEnd(this);
+ }
+
+ kn.extendAsViewModel('PopupsFolderSystemViewModel', PopupsFolderSystemViewModel);
+
+ PopupsFolderSystemViewModel.prototype.sChooseOnText = '';
+ PopupsFolderSystemViewModel.prototype.sUnuseText = '';
+
+ /**
+ * @param {number=} iNotificationType = Enums.SetSystemFoldersNotification.None
+ */
+ PopupsFolderSystemViewModel.prototype.onShow = function (iNotificationType)
+ {
+ var sNotification = '';
+
+ iNotificationType = Utils.isUnd(iNotificationType) ? Enums.SetSystemFoldersNotification.None : iNotificationType;
+
+ switch (iNotificationType)
+ {
+ case Enums.SetSystemFoldersNotification.Sent:
+ sNotification = Utils.i18n('POPUPS_SYSTEM_FOLDERS/NOTIFICATION_SENT');
+ break;
+ case Enums.SetSystemFoldersNotification.Draft:
+ sNotification = Utils.i18n('POPUPS_SYSTEM_FOLDERS/NOTIFICATION_DRAFTS');
+ break;
+ case Enums.SetSystemFoldersNotification.Spam:
+ sNotification = Utils.i18n('POPUPS_SYSTEM_FOLDERS/NOTIFICATION_SPAM');
+ break;
+ case Enums.SetSystemFoldersNotification.Trash:
+ sNotification = Utils.i18n('POPUPS_SYSTEM_FOLDERS/NOTIFICATION_TRASH');
+ break;
+ case Enums.SetSystemFoldersNotification.Archive:
+ sNotification = Utils.i18n('POPUPS_SYSTEM_FOLDERS/NOTIFICATION_ARCHIVE');
+ break;
+ }
+
+ this.notification(sNotification);
+ };
+
+ module.exports = PopupsFolderSystemViewModel;
+
+}(module));
+},{"../../Boots/RainLoopApp.js":4,"../../Common/Consts.js":6,"../../Common/Enums.js":7,"../../Common/Utils.js":14,"../../External/ko.js":28,"../../Knoin/Knoin.js":33,"../../Knoin/KnoinAbstractViewModel.js":36,"../../Storages/AppSettings.js":61,"../../Storages/WebMailAjaxRemoteStorage.js":65,"../../Storages/WebMailDataStorage.js":67}],83:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ window = require('../../External/window.js'),
+ ko = require('../../External/ko.js'),
+
+ Utils = require('../../Common/Utils.js'),
+
+ Data = require('../../Storages/WebMailDataStorage.js'),
+
+ RL = require('../../Boots/RainLoopApp.js'),
+
+ kn = require('../../Knoin/Knoin.js'),
+ KnoinAbstractViewModel = require('../../Knoin/KnoinAbstractViewModel.js')
+ ;
+
+ /**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+ function PopupsGenerateNewOpenPgpKeyViewModel()
+ {
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsGenerateNewOpenPgpKey');
+
+ this.email = ko.observable('');
+ this.email.focus = ko.observable('');
+ this.email.error = ko.observable(false);
+
+ this.name = ko.observable('');
+ this.password = ko.observable('');
+ this.keyBitLength = ko.observable(2048);
+
+ this.submitRequest = ko.observable(false);
+
+ this.email.subscribe(function () {
+ this.email.error(false);
+ }, this);
+
+ this.generateOpenPgpKeyCommand = Utils.createCommand(this, function () {
+
+ var
+ self = this,
+ sUserID = '',
+ mKeyPair = null,
+ oOpenpgpKeyring = Data.openpgpKeyring
+ ;
+
+ this.email.error('' === Utils.trim(this.email()));
+ if (!oOpenpgpKeyring || this.email.error())
+ {
+ return false;
+ }
+
+ sUserID = this.email();
+ if ('' !== this.name())
+ {
+ sUserID = this.name() + ' <' + sUserID + '>';
+ }
+
+ this.submitRequest(true);
+
+ _.delay(function () {
+ // mKeyPair = window.openpgp.generateKeyPair(1, Utils.pInt(self.keyBitLength()), sUserID, Utils.trim(self.password()));
+ mKeyPair = window.openpgp.generateKeyPair({
+ 'userId': sUserID,
+ 'numBits': Utils.pInt(self.keyBitLength()),
+ 'passphrase': Utils.trim(self.password())
+ });
+
+ if (mKeyPair && mKeyPair.privateKeyArmored)
+ {
+ oOpenpgpKeyring.privateKeys.importKey(mKeyPair.privateKeyArmored);
+ oOpenpgpKeyring.publicKeys.importKey(mKeyPair.publicKeyArmored);
+ oOpenpgpKeyring.store();
+
+ RL.reloadOpenPgpKeys();
+ Utils.delegateRun(self, 'cancelCommand');
+ }
+
+ self.submitRequest(false);
+ }, 100);
+
+ return true;
+ });
+
+ kn.constructorEnd(this);
+ }
+
+ kn.extendAsViewModel('PopupsGenerateNewOpenPgpKeyViewModel', PopupsGenerateNewOpenPgpKeyViewModel);
+
+ PopupsGenerateNewOpenPgpKeyViewModel.prototype.clearPopup = function ()
+ {
+ this.name('');
+ this.password('');
+
+ this.email('');
+ this.email.error(false);
+ this.keyBitLength(2048);
+ };
+
+ PopupsGenerateNewOpenPgpKeyViewModel.prototype.onShow = function ()
+ {
+ this.clearPopup();
+ };
+
+ PopupsGenerateNewOpenPgpKeyViewModel.prototype.onFocus = function ()
+ {
+ this.email.focus(true);
+ };
+
+ module.exports = PopupsGenerateNewOpenPgpKeyViewModel;
+
+}(module));
+},{"../../Boots/RainLoopApp.js":4,"../../Common/Utils.js":14,"../../External/ko.js":28,"../../External/window.js":32,"../../Knoin/Knoin.js":33,"../../Knoin/KnoinAbstractViewModel.js":36,"../../Storages/WebMailDataStorage.js":67}],84:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ ko = require('../../External/ko.js'),
+
+ Enums = require('../../Common/Enums.js'),
+ Utils = require('../../Common/Utils.js'),
+ kn = require('../../Knoin/Knoin.js'),
+
+ Remote = require('../../Storages/WebMailAjaxRemoteStorage.js'),
+ Data = require('../../Storages/WebMailDataStorage.js'),
+
+ RL = require('../../Boots/RainLoopApp.js'),
+
+ KnoinAbstractViewModel = require('../../Knoin/KnoinAbstractViewModel.js')
+ ;
+
+ /**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+ function PopupsIdentityViewModel()
+ {
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsIdentity');
+
+ this.id = '';
+ this.edit = ko.observable(false);
+ this.owner = ko.observable(false);
+
+ this.email = ko.observable('').validateEmail();
+ this.email.focused = ko.observable(false);
+ this.name = ko.observable('');
+ this.name.focused = ko.observable(false);
+ this.replyTo = ko.observable('').validateSimpleEmail();
+ this.replyTo.focused = ko.observable(false);
+ this.bcc = ko.observable('').validateSimpleEmail();
+ this.bcc.focused = ko.observable(false);
+
+ // this.email.subscribe(function () {
+ // this.email.hasError(false);
+ // }, this);
+
+ this.submitRequest = ko.observable(false);
+ this.submitError = ko.observable('');
+
+ this.addOrEditIdentityCommand = Utils.createCommand(this, function () {
+
+ if (!this.email.hasError())
+ {
+ this.email.hasError('' === Utils.trim(this.email()));
+ }
+
+ if (this.email.hasError())
+ {
+ if (!this.owner())
+ {
+ this.email.focused(true);
+ }
+
+ return false;
+ }
+
+ if (this.replyTo.hasError())
+ {
+ this.replyTo.focused(true);
+ return false;
+ }
+
+ if (this.bcc.hasError())
+ {
+ this.bcc.focused(true);
+ return false;
+ }
+
+ this.submitRequest(true);
+
+ Remote.identityUpdate(_.bind(function (sResult, oData) {
+
+ this.submitRequest(false);
+ if (Enums.StorageResultType.Success === sResult && oData)
+ {
+ if (oData.Result)
+ {
+ RL.accountsAndIdentities();
+ this.cancelCommand();
+ }
+ else if (oData.ErrorCode)
+ {
+ this.submitError(Utils.getNotification(oData.ErrorCode));
+ }
+ }
+ else
+ {
+ this.submitError(Utils.getNotification(Enums.Notification.UnknownError));
+ }
+
+ }, this), this.id, this.email(), this.name(), this.replyTo(), this.bcc());
+
+ return true;
+
+ }, function () {
+ return !this.submitRequest();
+ });
+
+ this.label = ko.computed(function () {
+ return Utils.i18n('POPUPS_IDENTITIES/' + (this.edit() ? 'TITLE_UPDATE_IDENTITY': 'TITLE_ADD_IDENTITY'));
+ }, this);
+
+ this.button = ko.computed(function () {
+ return Utils.i18n('POPUPS_IDENTITIES/' + (this.edit() ? 'BUTTON_UPDATE_IDENTITY': 'BUTTON_ADD_IDENTITY'));
+ }, this);
+
+ kn.constructorEnd(this);
+ }
+
+ kn.extendAsViewModel('PopupsIdentityViewModel', PopupsIdentityViewModel);
+
+ PopupsIdentityViewModel.prototype.clearPopup = function ()
+ {
+ this.id = '';
+ this.edit(false);
+ this.owner(false);
+
+ this.name('');
+ this.email('');
+ this.replyTo('');
+ this.bcc('');
+
+ this.email.hasError(false);
+ this.replyTo.hasError(false);
+ this.bcc.hasError(false);
+
+ this.submitRequest(false);
+ this.submitError('');
+ };
+
+ /**
+ * @param {?IdentityModel} oIdentity
+ */
+ PopupsIdentityViewModel.prototype.onShow = function (oIdentity)
+ {
+ this.clearPopup();
+
+ if (oIdentity)
+ {
+ this.edit(true);
+
+ this.id = oIdentity.id;
+ this.name(oIdentity.name());
+ this.email(oIdentity.email());
+ this.replyTo(oIdentity.replyTo());
+ this.bcc(oIdentity.bcc());
+
+ this.owner(this.id === Data.accountEmail());
+ }
+ };
+
+ PopupsIdentityViewModel.prototype.onFocus = function ()
+ {
+ if (!this.owner())
+ {
+ this.email.focused(true);
+ }
+ };
+
+ module.exports = PopupsIdentityViewModel;
+
+}(module));
+},{"../../Boots/RainLoopApp.js":4,"../../Common/Enums.js":7,"../../Common/Utils.js":14,"../../External/ko.js":28,"../../Knoin/Knoin.js":33,"../../Knoin/KnoinAbstractViewModel.js":36,"../../Storages/WebMailAjaxRemoteStorage.js":65,"../../Storages/WebMailDataStorage.js":67}],85:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ _ = require('../../External/underscore.js'),
+ key = require('../../External/key.js'),
+ Enums = require('../../Common/Enums.js'),
+ Utils = require('../../Common/Utils.js'),
+ kn = require('../../Knoin/Knoin.js'),
+ KnoinAbstractViewModel = require('../../Knoin/KnoinAbstractViewModel.js')
+ ;
+
+ /**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+ function PopupsKeyboardShortcutsHelpViewModel()
+ {
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsKeyboardShortcutsHelp');
+
+ this.sDefaultKeyScope = Enums.KeyState.PopupKeyboardShortcutsHelp;
+
+ kn.constructorEnd(this);
+ }
+
+ kn.extendAsViewModel('PopupsKeyboardShortcutsHelpViewModel', PopupsKeyboardShortcutsHelpViewModel);
+
+ PopupsKeyboardShortcutsHelpViewModel.prototype.onBuild = function (oDom)
+ {
+ key('tab, shift+tab, left, right', Enums.KeyState.PopupKeyboardShortcutsHelp, _.bind(function (event, handler) {
+ if (event && handler)
+ {
+ var
+ $tabs = oDom.find('.nav.nav-tabs > li'),
+ bNext = handler && ('tab' === handler.shortcut || 'right' === handler.shortcut),
+ iIndex = $tabs.index($tabs.filter('.active'))
+ ;
+
+ if (!bNext && iIndex > 0)
+ {
+ iIndex--;
+ }
+ else if (bNext && iIndex < $tabs.length - 1)
+ {
+ iIndex++;
+ }
+ else
+ {
+ iIndex = bNext ? 0 : $tabs.length - 1;
+ }
+
+ $tabs.eq(iIndex).find('a[data-toggle="tab"]').tab('show');
+ return false;
+ }
+ }, this));
+ };
+
+ module.exports = PopupsKeyboardShortcutsHelpViewModel;
+
+}(module));
+},{"../../Common/Enums.js":7,"../../Common/Utils.js":14,"../../External/key.js":27,"../../External/underscore.js":31,"../../Knoin/Knoin.js":33,"../../Knoin/KnoinAbstractViewModel.js":36}],86:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ _ = require('../../External/underscore.js'),
+ ko = require('../../External/ko.js'),
+
+ Utils = require('../../Common/Utils.js'),
+
+ Data = require('../../Storages/WebMailDataStorage.js'),
+
+ kn = require('../../Knoin/Knoin.js'),
+ KnoinAbstractViewModel = require('../../Knoin/KnoinAbstractViewModel.js')
+ ;
+
+ /**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+ function PopupsLanguagesViewModel()
+ {
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsLanguages');
+
+ this.exp = ko.observable(false);
+
+ this.languages = ko.computed(function () {
+ return _.map(Data.languages(), function (sLanguage) {
+ return {
+ 'key': sLanguage,
+ 'selected': ko.observable(false),
+ 'fullName': Utils.convertLangName(sLanguage)
+ };
+ });
+ });
+
+ Data.mainLanguage.subscribe(function () {
+ this.resetMainLanguage();
+ }, this);
+
+ kn.constructorEnd(this);
+ }
+
+ kn.extendAsViewModel('PopupsLanguagesViewModel', PopupsLanguagesViewModel);
+
+ PopupsLanguagesViewModel.prototype.languageEnName = function (sLanguage)
+ {
+ return Utils.convertLangName(sLanguage, true);
+ };
+
+ PopupsLanguagesViewModel.prototype.resetMainLanguage = function ()
+ {
+ var sCurrent = Data.mainLanguage();
+ _.each(this.languages(), function (oItem) {
+ oItem['selected'](oItem['key'] === sCurrent);
+ });
+ };
+
+ PopupsLanguagesViewModel.prototype.onShow = function ()
+ {
+ this.exp(true);
+
+ this.resetMainLanguage();
+ };
+
+ PopupsLanguagesViewModel.prototype.onHide = function ()
+ {
+ this.exp(false);
+ };
+
+ PopupsLanguagesViewModel.prototype.changeLanguage = function (sLang)
+ {
+ Data.mainLanguage(sLang);
+ this.cancelCommand();
+ };
+
+ module.exports = PopupsLanguagesViewModel;
+
+}(module));
+},{"../../Common/Utils.js":14,"../../External/ko.js":28,"../../External/underscore.js":31,"../../Knoin/Knoin.js":33,"../../Knoin/KnoinAbstractViewModel.js":36,"../../Storages/WebMailDataStorage.js":67}],87:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ ko = require('../../External/ko.js'),
+
+ Enums = require('../../Common/Enums.js'),
+ Utils = require('../../Common/Utils.js'),
+
+ Remote = require('../../Storages/WebMailAjaxRemoteStorage.js'),
+
+ kn = require('../../Knoin/Knoin.js'),
+ KnoinAbstractViewModel = require('../../Knoin/KnoinAbstractViewModel.js')
+ ;
+
+ /**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+ function PopupsTwoFactorTestViewModel()
+ {
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsTwoFactorTest');
+
+ var self = this;
+
+ this.code = ko.observable('');
+ this.code.focused = ko.observable(false);
+ this.code.status = ko.observable(null);
+
+ this.testing = ko.observable(false);
+
+ // commands
+ this.testCode = Utils.createCommand(this, function () {
+
+ this.testing(true);
+ Remote.testTwoFactor(function (sResult, oData) {
+
+ self.testing(false);
+ self.code.status(Enums.StorageResultType.Success === sResult && oData && oData.Result ? true : false);
+
+ }, this.code());
+
+ }, function () {
+ return '' !== this.code() && !this.testing();
+ });
+
+ kn.constructorEnd(this);
+ }
+
+ kn.extendAsViewModel('PopupsTwoFactorTestViewModel', PopupsTwoFactorTestViewModel);
+
+ PopupsTwoFactorTestViewModel.prototype.clearPopup = function ()
+ {
+ this.code('');
+ this.code.focused(false);
+ this.code.status(null);
+ this.testing(false);
+ };
+
+ PopupsTwoFactorTestViewModel.prototype.onShow = function ()
+ {
+ this.clearPopup();
+ };
+
+ PopupsTwoFactorTestViewModel.prototype.onFocus = function ()
+ {
+ this.code.focused(true);
+ };
+
+ module.exports = PopupsTwoFactorTestViewModel;
+
+}(module));
+},{"../../Common/Enums.js":7,"../../Common/Utils.js":14,"../../External/ko.js":28,"../../Knoin/Knoin.js":33,"../../Knoin/KnoinAbstractViewModel.js":36,"../../Storages/WebMailAjaxRemoteStorage.js":65}],88:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ ko = require('../../External/ko.js'),
+ Utils = require('../../Common/Utils.js'),
+ kn = require('../../Knoin/Knoin.js'),
+ KnoinAbstractViewModel = require('../../Knoin/KnoinAbstractViewModel.js')
+ ;
+
+ /**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+ function PopupsViewOpenPgpKeyViewModel()
+ {
+ KnoinAbstractViewModel.call(this, 'Popups', 'PopupsViewOpenPgpKey');
+
+ this.key = ko.observable('');
+ this.keyDom = ko.observable(null);
+
+ kn.constructorEnd(this);
+ }
+
+ kn.extendAsViewModel('PopupsViewOpenPgpKeyViewModel', PopupsViewOpenPgpKeyViewModel);
+
+ PopupsViewOpenPgpKeyViewModel.prototype.clearPopup = function ()
+ {
+ this.key('');
+ };
+
+ PopupsViewOpenPgpKeyViewModel.prototype.selectKey = function ()
+ {
+ var oEl = this.keyDom();
+ if (oEl)
+ {
+ Utils.selectElement(oEl);
+ }
+ };
+
+ PopupsViewOpenPgpKeyViewModel.prototype.onShow = function (oOpenPgpKey)
+ {
+ this.clearPopup();
+
+ if (oOpenPgpKey)
+ {
+ this.key(oOpenPgpKey.armor);
+ }
+ };
+
+ module.exports = PopupsViewOpenPgpKeyViewModel;
+
+}(module));
+},{"../../Common/Utils.js":14,"../../External/ko.js":28,"../../Knoin/Knoin.js":33,"../../Knoin/KnoinAbstractViewModel.js":36}],89:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ LinkBuilder = require('../Common/LinkBuilder.js'),
+ Globals = require('../Common/Globals.js'),
+
+ kn = require('../Knoin/Knoin.js'),
+ KnoinAbstractViewModel = require('../Knoin/KnoinAbstractViewModel.js')
+ ;
+
+ /**
+ * @param {?} oScreen
+ *
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+ function SettingsMenuViewModel(oScreen)
+ {
+ KnoinAbstractViewModel.call(this, 'Left', 'SettingsMenu');
+
+ this.leftPanelDisabled = Globals.leftPanelDisabled;
+
+ this.menu = oScreen.menu;
+
+ kn.constructorEnd(this);
+ }
+
+ kn.extendAsViewModel('SettingsMenuViewModel', SettingsMenuViewModel);
+
+ SettingsMenuViewModel.prototype.link = function (sRoute)
+ {
+ return LinkBuilder.settings(sRoute);
+ };
+
+ SettingsMenuViewModel.prototype.backToMailBoxClick = function ()
+ {
+ kn.setHash(LinkBuilder.inbox());
+ };
+
+ module.exports = SettingsMenuViewModel;
+
+}(module));
+},{"../Common/Globals.js":9,"../Common/LinkBuilder.js":10,"../Knoin/Knoin.js":33,"../Knoin/KnoinAbstractViewModel.js":36}],90:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ key = require('../External/key.js'),
+
+ Enums = require('../Common/Enums.js'),
+ LinkBuilder = require('../Common/LinkBuilder.js'),
+
+ Data = require('../Storages/WebMailDataStorage.js'),
+
+ kn = require('../Knoin/Knoin.js'),
+ KnoinAbstractViewModel = require('../Knoin/KnoinAbstractViewModel.js')
+ ;
+
+ /**
+ * @constructor
+ * @extends KnoinAbstractViewModel
+ */
+ function SettingsPaneViewModel()
+ {
+ KnoinAbstractViewModel.call(this, 'Right', 'SettingsPane');
+
+ kn.constructorEnd(this);
+ }
+
+ kn.extendAsViewModel('SettingsPaneViewModel', SettingsPaneViewModel);
+
+ SettingsPaneViewModel.prototype.onBuild = function ()
+ {
+ var self = this;
+ key('esc', Enums.KeyState.Settings, function () {
+ self.backToMailBoxClick();
+ });
+ };
+
+ SettingsPaneViewModel.prototype.onShow = function ()
+ {
+ Data.message(null);
+ };
+
+ SettingsPaneViewModel.prototype.backToMailBoxClick = function ()
+ {
+ kn.setHash(LinkBuilder.inbox());
+ };
+
+ module.exports = SettingsPaneViewModel;
+
+}(module));
+},{"../Common/Enums.js":7,"../Common/LinkBuilder.js":10,"../External/key.js":27,"../Knoin/Knoin.js":33,"../Knoin/KnoinAbstractViewModel.js":36,"../Storages/WebMailDataStorage.js":67}],91:[function(require,module,exports){
+/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
+
+(function (module) {
+
+ 'use strict';
+
+ var
+ kn = require('../Knoin/Knoin.js'),
+ AbstractSystemDropDownViewModel = require('./AbstractSystemDropDownViewModel.js')
+ ;
+
+ /**
+ * @constructor
+ * @extends AbstractSystemDropDownViewModel
+ */
+ function SettingsSystemDropDownViewModel()
+ {
+ AbstractSystemDropDownViewModel.call(this);
+ kn.constructorEnd(this);
+ }
+
+ kn.extendAsViewModel('SettingsSystemDropDownViewModel', SettingsSystemDropDownViewModel, AbstractSystemDropDownViewModel);
+
+ module.exports = SettingsSystemDropDownViewModel;
+
+}(module));
+},{"../Knoin/Knoin.js":33,"./AbstractSystemDropDownViewModel.js":68}]},{},[1]);
diff --git a/rainloop/v/0.0.0/static/js/app.min.js b/rainloop/v/0.0.0/static/js/app.min.js
index b580fa7e0..6694ef538 100644
--- a/rainloop/v/0.0.0/static/js/app.min.js
+++ b/rainloop/v/0.0.0/static/js/app.min.js
@@ -1,11 +1,10 @@
-/*! RainLoop Webmail Main Module (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-!function(e,t,s,i,o,n,a,r,l,c){"use strict";function u(){this.sBase="#/",this.sServer="./?",this.sVersion=jt.settingsGet("Version"),this.sSpecSuffix=jt.settingsGet("AuthAccountHash")||"0",this.sStaticPrefix=jt.settingsGet("StaticPrefix")||"rainloop/v/"+this.sVersion+"/static/"}function d(e,s,i,o){var n=this;n.editor=null,n.iBlurTimer=0,n.fOnBlur=s||null,n.fOnReady=i||null,n.fOnModeChange=o||null,n.$element=t(e),n.resize=r.throttle(r.bind(n.resize,n),100),n.init()}function h(e,t,i,o,n,a){this.list=e,this.listChecked=s.computed(function(){return r.filter(this.list(),function(e){return e.checked()})},this).extend({rateLimit:0}),this.isListChecked=s.computed(function(){return 00&&-1t?t:e))},this),this.body=null,this.plainRaw="",this.isHtml=s.observable(!1),this.hasImages=s.observable(!1),this.attachments=s.observableArray([]),this.isPgpSigned=s.observable(!1),this.isPgpEncrypted=s.observable(!1),this.pgpSignedVerifyStatus=s.observable(Lt.SignedVerifyStatus.None),this.pgpSignedVerifyUser=s.observable(""),this.priority=s.observable(Lt.MessagePriority.Normal),this.readReceipt=s.observable(""),this.aDraftInfo=[],this.sMessageId="",this.sInReplyTo="",this.sReferences="",this.parentUid=s.observable(0),this.threads=s.observableArray([]),this.threadsLen=s.observable(0),this.hasUnseenSubMessage=s.observable(!1),this.hasFlaggedSubMessage=s.observable(!1),this.lastInCollapsedThread=s.observable(!1),this.lastInCollapsedThreadLoading=s.observable(!1),this.threadsLenResult=s.computed(function(){var e=this.threadsLen();return 0===this.parentUid()&&e>0?e+1:""},this)}function N(){this.name=s.observable(""),this.fullName="",this.fullNameRaw="",this.fullNameHash="",this.delimiter="",this.namespace="",this.deep=0,this.interval=0,this.selectable=!1,this.existen=!0,this.type=s.observable(Lt.FolderType.User),this.focused=s.observable(!1),this.selected=s.observable(!1),this.edited=s.observable(!1),this.collapsed=s.observable(!0),this.subScribed=s.observable(!0),this.subFolders=s.observableArray([]),this.deleteAccess=s.observable(!1),this.actionBlink=s.observable(!1).extend({falseTimeout:1e3}),this.nameForEdit=s.observable(""),this.name.subscribe(function(e){this.nameForEdit(e)},this),this.edited.subscribe(function(e){e&&this.nameForEdit(this.name())},this),this.privateMessageCountAll=s.observable(0),this.privateMessageCountUnread=s.observable(0),this.collapsedPrivate=s.observable(!0)}function R(e,t){this.email=e,this.deleteAccess=s.observable(!1),this.canBeDalete=s.observable(t)}function I(e,t,i){this.id=e,this.email=s.observable(t),this.name=s.observable(""),this.replyTo=s.observable(""),this.bcc=s.observable(""),this.deleteAccess=s.observable(!1),this.canBeDalete=s.observable(i)}function L(e){this.parentList=e,this.field=s.observable(Lt.FilterConditionField.From),this.fieldOptions=[{id:Lt.FilterConditionField.From,name:"From"},{id:Lt.FilterConditionField.Recipient,name:"Recipient (To or CC)"},{id:Lt.FilterConditionField.To,name:"To"},{id:Lt.FilterConditionField.Subject,name:"Subject"}],this.type=s.observable(Lt.FilterConditionType.EqualTo),this.typeOptions=[{id:Lt.FilterConditionType.EqualTo,name:"Equal To"},{id:Lt.FilterConditionType.NotEqualTo,name:"Not Equal To"},{id:Lt.FilterConditionType.Contains,name:"Contains"},{id:Lt.FilterConditionType.NotContains,name:"Not Contains"}],this.value=s.observable(""),this.template=s.computed(function(){var e="";switch(this.type()){default:e="SettingsFiltersConditionDefault"}return e},this)}function P(){this.new=s.observable(!0),this.enabled=s.observable(!0),this.name=s.observable(""),this.conditionsType=s.observable(Lt.FilterRulesType.And),this.conditions=s.observableArray([]),this.conditions.subscribe(function(){Mt.windowResize()}),this.actionMarkAsRead=s.observable(!1),this.actionSkipOtherFilters=s.observable(!0),this.actionValue=s.observable(""),this.actionType=s.observable(Lt.FiltersAction.Move),this.actionTypeOptions=[{id:Lt.FiltersAction.None,name:"Action - None"},{id:Lt.FiltersAction.Move,name:"Action - Move to"},{id:Lt.FiltersAction.Discard,name:"Action - Discard"}],this.actionMarkAsReadVisiblity=s.computed(function(){return-1=e?1:e},this),this.contactsPagenator=s.computed(Mt.computedPagenatorHelper(this.contactsPage,this.contactsPageCount)),this.emptySelection=s.observable(!0),this.viewClearSearch=s.observable(!1),this.viewID=s.observable(""),this.viewReadOnly=s.observable(!1),this.viewProperties=s.observableArray([]),this.viewTags=s.observable(""),this.viewTags.visibility=s.observable(!1),this.viewTags.focusTrigger=s.observable(!1),this.viewTags.focusTrigger.subscribe(function(e){e||""!==this.viewTags()?e&&this.viewTags.visibility(!0):this.viewTags.visibility(!1)},this),this.viewSaveTrigger=s.observable(Lt.SaveSettingsStep.Idle),this.viewPropertiesNames=this.viewProperties.filter(function(e){return-1e)break;t[0]&&t[1]&&t[2]&&t[1]===t[2]&&("PRIVATE"===t[1]?o.privateKeys.importKey(t[0]):"PUBLIC"===t[1]&&o.publicKeys.importKey(t[0])),e--}return o.store(),jt.reloadOpenPgpKeys(),Mt.delegateRun(this,"cancelCommand"),!0}),S.constructorEnd(this)}function B(){b.call(this,"Popups","PopupsViewOpenPgpKey"),this.key=s.observable(""),this.keyDom=s.observable(null),S.constructorEnd(this)}function G(){b.call(this,"Popups","PopupsGenerateNewOpenPgpKey"),this.email=s.observable(""),this.email.focus=s.observable(""),this.email.error=s.observable(!1),this.name=s.observable(""),this.password=s.observable(""),this.keyBitLength=s.observable(2048),this.submitRequest=s.observable(!1),this.email.subscribe(function(){this.email.error(!1)},this),this.generateOpenPgpKeyCommand=Mt.createCommand(this,function(){var t=this,s="",i=null,o=jt.data().openpgpKeyring;return this.email.error(""===Mt.trim(this.email())),!o||this.email.error()?!1:(s=this.email(),""!==this.name()&&(s=this.name()+" <"+s+">"),this.submitRequest(!0),r.delay(function(){i=e.openpgp.generateKeyPair({userId:s,numBits:Mt.pInt(t.keyBitLength()),passphrase:Mt.trim(t.password())}),i&&i.privateKeyArmored&&(o.privateKeys.importKey(i.privateKeyArmored),o.publicKeys.importKey(i.publicKeyArmored),o.store(),jt.reloadOpenPgpKeys(),Mt.delegateRun(t,"cancelCommand")),t.submitRequest(!1)
-},100),!0)}),S.constructorEnd(this)}function K(){b.call(this,"Popups","PopupsComposeOpenPgp"),this.notification=s.observable(""),this.sign=s.observable(!0),this.encrypt=s.observable(!0),this.password=s.observable(""),this.password.focus=s.observable(!1),this.buttonFocus=s.observable(!1),this.from=s.observable(""),this.to=s.observableArray([]),this.text=s.observable(""),this.resultCallback=null,this.submitRequest=s.observable(!1),this.doCommand=Mt.createCommand(this,function(){var t=this,s=!0,i=jt.data(),o=null,n=[];this.submitRequest(!0),s&&this.sign()&&""===this.from()&&(this.notification(Mt.i18n("PGP_NOTIFICATIONS/SPECIFY_FROM_EMAIL")),s=!1),s&&this.sign()&&(o=i.findPrivateKeyByEmail(this.from(),this.password()),o||(this.notification(Mt.i18n("PGP_NOTIFICATIONS/NO_PRIVATE_KEY_FOUND_FOR",{EMAIL:this.from()})),s=!1)),s&&this.encrypt()&&0===this.to().length&&(this.notification(Mt.i18n("PGP_NOTIFICATIONS/SPECIFY_AT_LEAST_ONE_RECIPIENT")),s=!1),s&&this.encrypt()&&(n=[],r.each(this.to(),function(e){var o=i.findPublicKeysByEmail(e);0===o.length&&s&&(t.notification(Mt.i18n("PGP_NOTIFICATIONS/NO_PUBLIC_KEYS_FOUND_FOR",{EMAIL:e})),s=!1),n=n.concat(o)}),!s||0!==n.length&&this.to().length===n.length||(s=!1)),r.delay(function(){if(t.resultCallback&&s)try{o&&0===n.length?t.resultCallback(e.openpgp.signClearMessage([o],t.text())):o&&00&&t>0&&e>t},this),this.hasMessages=s.computed(function(){return 0'),o.after(n),o.remove()),n&&n[0]&&(n.attr("data-href",a).attr("data-theme",e[0]),n&&n[0]&&n[0].styleSheet&&!Mt.isUnd(n[0].styleSheet.cssText)?n[0].styleSheet.cssText=e[1]:n.text(e[1])),i.themeTrigger(Lt.SaveSettingsStep.TrueResult))}).always(function(){i.iTimer=e.setTimeout(function(){i.themeTrigger(Lt.SaveSettingsStep.Idle)},1e3),i.oLastAjax=null})),jt.remote().saveSettings(null,{Theme:s})},this)}function ft(){this.openpgpkeys=jt.data().openpgpkeys,this.openpgpkeysPublic=jt.data().openpgpkeysPublic,this.openpgpkeysPrivate=jt.data().openpgpkeysPrivate,this.openPgpKeyForDeletion=s.observable(null).extend({falseTimeout:3e3}).extend({toggleSubscribe:[this,function(e){e&&e.deleteAccess(!1)},function(e){e&&e.deleteAccess(!0)}]})}function bt(){this.leftPanelDisabled=s.observable(!1),this.useKeyboardShortcuts=s.observable(!0),this.keyScopeReal=s.observable(Lt.KeyState.All),this.keyScopeFake=s.observable(Lt.KeyState.All),this.keyScope=s.computed({owner:this,read:function(){return this.keyScopeFake()},write:function(e){Lt.KeyState.Menu!==e&&(Lt.KeyState.Compose===e?Mt.disableKeyFilter():Mt.restoreKeyFilter(),this.keyScopeFake(e),Ot.dropdownVisibility()&&(e=Lt.KeyState.Menu)),this.keyScopeReal(e)}}),this.keyScopeReal.subscribe(function(e){c.setScope(e)}),this.leftPanelDisabled.subscribe(function(e){jt.pub("left-panel."+(e?"off":"on"))}),Ot.dropdownVisibility.subscribe(function(e){e?(Ot.tooltipTrigger(!Ot.tooltipTrigger()),this.keyScope(Lt.KeyState.Menu)):Lt.KeyState.Menu===c.getScope()&&this.keyScope(this.keyScopeFake())
-},this),Mt.initDataConstructorBySettings(this)}function yt(){bt.call(this);var i=function(e){return function(){var t=jt.cache().getFolderFromCacheList(e());t&&t.type(Lt.FolderType.User)}},o=function(e){return function(t){var s=jt.cache().getFolderFromCacheList(t);s&&s.type(e)}};this.devEmail="",this.devPassword="",this.accountEmail=s.observable(""),this.accountIncLogin=s.observable(""),this.accountOutLogin=s.observable(""),this.projectHash=s.observable(""),this.threading=s.observable(!1),this.lastFoldersHash="",this.remoteSuggestions=!1,this.sentFolder=s.observable(""),this.draftFolder=s.observable(""),this.spamFolder=s.observable(""),this.trashFolder=s.observable(""),this.archiveFolder=s.observable(""),this.sentFolder.subscribe(i(this.sentFolder),this,"beforeChange"),this.draftFolder.subscribe(i(this.draftFolder),this,"beforeChange"),this.spamFolder.subscribe(i(this.spamFolder),this,"beforeChange"),this.trashFolder.subscribe(i(this.trashFolder),this,"beforeChange"),this.archiveFolder.subscribe(i(this.archiveFolder),this,"beforeChange"),this.sentFolder.subscribe(o(Lt.FolderType.SentItems),this),this.draftFolder.subscribe(o(Lt.FolderType.Draft),this),this.spamFolder.subscribe(o(Lt.FolderType.Spam),this),this.trashFolder.subscribe(o(Lt.FolderType.Trash),this),this.archiveFolder.subscribe(o(Lt.FolderType.Archive),this),this.draftFolderNotEnabled=s.computed(function(){return""===this.draftFolder()||It.Values.UnuseOptionValue===this.draftFolder()},this),this.displayName=s.observable(""),this.signature=s.observable(""),this.signatureToAll=s.observable(!1),this.replyTo=s.observable(""),this.enableTwoFactor=s.observable(!1),this.accounts=s.observableArray([]),this.accountsLoading=s.observable(!1).extend({throttle:100}),this.defaultIdentityID=s.observable(""),this.identities=s.observableArray([]),this.identitiesLoading=s.observable(!1).extend({throttle:100}),this.contactTags=s.observableArray([]),this.contacts=s.observableArray([]),this.contacts.loading=s.observable(!1).extend({throttle:200}),this.contacts.importing=s.observable(!1).extend({throttle:200}),this.contacts.syncing=s.observable(!1).extend({throttle:200}),this.contacts.exportingVcf=s.observable(!1).extend({throttle:200}),this.contacts.exportingCsv=s.observable(!1).extend({throttle:200}),this.allowContactsSync=s.observable(!1),this.enableContactsSync=s.observable(!1),this.contactsSyncUrl=s.observable(""),this.contactsSyncUser=s.observable(""),this.contactsSyncPass=s.observable(""),this.allowContactsSync=s.observable(!!jt.settingsGet("ContactsSyncIsAllowed")),this.enableContactsSync=s.observable(!!jt.settingsGet("EnableContactsSync")),this.contactsSyncUrl=s.observable(jt.settingsGet("ContactsSyncUrl")),this.contactsSyncUser=s.observable(jt.settingsGet("ContactsSyncUser")),this.contactsSyncPass=s.observable(jt.settingsGet("ContactsSyncPassword")),this.namespace="",this.folderList=s.observableArray([]),this.folderList.focused=s.observable(!1),this.foldersListError=s.observable(""),this.foldersLoading=s.observable(!1),this.foldersCreating=s.observable(!1),this.foldersDeleting=s.observable(!1),this.foldersRenaming=s.observable(!1),this.foldersChanging=s.computed(function(){var e=this.foldersLoading(),t=this.foldersCreating(),s=this.foldersDeleting(),i=this.foldersRenaming();return e||t||s||i},this),this.foldersInboxUnreadCount=s.observable(0),this.currentFolder=s.observable(null).extend({toggleSubscribe:[null,function(e){e&&e.selected(!1)},function(e){e&&e.selected(!0)}]}),this.currentFolderFullNameRaw=s.computed(function(){return this.currentFolder()?this.currentFolder().fullNameRaw:""},this),this.currentFolderFullName=s.computed(function(){return this.currentFolder()?this.currentFolder().fullName:""},this),this.currentFolderFullNameHash=s.computed(function(){return this.currentFolder()?this.currentFolder().fullNameHash:""},this),this.currentFolderName=s.computed(function(){return this.currentFolder()?this.currentFolder().name():""},this),this.folderListSystemNames=s.computed(function(){var e=["INBOX"],t=this.folderList(),s=this.sentFolder(),i=this.draftFolder(),o=this.spamFolder(),n=this.trashFolder(),a=this.archiveFolder();return Mt.isArray(t)&&0=e?1:e},this),this.mainMessageListSearch=s.computed({read:this.messageListSearch,write:function(e){xt.setHash(jt.link().mailBox(this.currentFolderFullNameHash(),1,Mt.trim(e.toString())))},owner:this}),this.messageListError=s.observable(""),this.messageListLoading=s.observable(!1),this.messageListIsNotCompleted=s.observable(!1),this.messageListCompleteLoadingThrottle=s.observable(!1).extend({throttle:200}),this.messageListCompleteLoading=s.computed(function(){var e=this.messageListLoading(),t=this.messageListIsNotCompleted();return e||t},this),this.messageListCompleteLoading.subscribe(function(e){this.messageListCompleteLoadingThrottle(e)},this),this.messageList.subscribe(r.debounce(function(e){r.each(e,function(e){e.newForAnimation()&&e.newForAnimation(!1)})},500)),this.staticMessageList=new E,this.message=s.observable(null),this.messageLoading=s.observable(!1),this.messageLoadingThrottle=s.observable(!1).extend({throttle:50}),this.message.focused=s.observable(!1),this.message.subscribe(function(t){t?Lt.Layout.NoPreview===this.layout()&&this.message.focused(!0):(this.message.focused(!1),this.messageFullScreenMode(!1),this.hideMessageBodies(),Lt.Layout.NoPreview===jt.data().layout()&&-10?Math.ceil(t/e*100):0},this),this.capaOpenPGP=s.observable(!1),this.openpgpkeys=s.observableArray([]),this.openpgpKeyring=null,this.openpgpkeysPublic=this.openpgpkeys.filter(function(e){return!(!e||e.isPrivate)}),this.openpgpkeysPrivate=this.openpgpkeys.filter(function(e){return!(!e||!e.isPrivate)}),this.googleActions=s.observable(!1),this.googleLoggined=s.observable(!1),this.googleUserName=s.observable(""),this.facebookActions=s.observable(!1),this.facebookLoggined=s.observable(!1),this.facebookUserName=s.observable(""),this.twitterActions=s.observable(!1),this.twitterLoggined=s.observable(!1),this.twitterUserName=s.observable(""),this.customThemeType=s.observable(Lt.CustomThemeType.Light),this.purgeMessageBodyCacheThrottle=r.throttle(this.purgeMessageBodyCache,3e4)}function St(){this.oRequests={}}function vt(){St.call(this),this.oRequests={}}function Ct(){this.bCapaGravatar=jt.capa(Lt.Capa.Gravatar)}function wt(){Ct.call(this),this.oFoldersCache={},this.oFoldersNamesCache={},this.oFolderHashCache={},this.oFolderUidNextCache={},this.oMessageListHashCache={},this.oMessageFlagsCache={},this.oNewMessage={},this.oRequestedMessage={}}function Tt(e){y.call(this,"settings",e),this.menu=s.observableArray([]),this.oCurrentSubScreen=null,this.oViewModelPlace=null}function Ft(){y.call(this,"login",[$])}function At(){y.call(this,"mailbox",[Q,et,tt,st]),this.oLastRoute={}}function Et(){Tt.call(this,[Z,it,ot]),Mt.initOnStartOrLangChange(function(){this.sSettingsTitle=Mt.i18n("TITLES/SETTINGS")},this,function(){jt.setTitle(this.sSettingsTitle)})}function Nt(){f.call(this),this.oSettings=null,this.oPlugins=null,this.oLocal=null,this.oLink=null,this.oSubs={},this.isLocalAutocomplete=!0,this.popupVisibilityNames=s.observableArray([]),this.popupVisibility=s.computed(function(){return 0').appendTo("body"),Gt.on("error",function(e){jt&&e&&e.originalEvent&&e.originalEvent.message&&-1===Mt.inArray(e.originalEvent.message,["Script error.","Uncaught Error: Error calling method on NPObject."])&&jt.remote().jsError(Mt.emptyFunction,e.originalEvent.message,e.originalEvent.filename,e.originalEvent.lineno,location&&location.toString?location.toString():"",Bt.attr("class"),Mt.microtime()-Ot.now)}),Kt.on("keydown",function(e){e&&e.ctrlKey&&Bt.addClass("rl-ctrl-key-pressed")}).on("keyup",function(e){e&&!e.ctrlKey&&Bt.removeClass("rl-ctrl-key-pressed")})}function Rt(){Nt.call(this),this.oData=null,this.oRemote=null,this.oCache=null,this.oMoveCache={},this.quotaDebounce=r.debounce(this.quota,3e4),this.moveOrDeleteResponseHelper=r.bind(this.moveOrDeleteResponseHelper,this),this.messagesMoveTrigger=r.debounce(this.messagesMoveTrigger,500),e.setInterval(function(){jt.pub("interval.30s")},3e4),e.setInterval(function(){jt.pub("interval.1m")},6e4),e.setInterval(function(){jt.pub("interval.2m")},12e4),e.setInterval(function(){jt.pub("interval.3m")},18e4),e.setInterval(function(){jt.pub("interval.5m")},3e5),e.setInterval(function(){jt.pub("interval.10m")},6e5),e.setTimeout(function(){e.setInterval(function(){jt.pub("interval.10m-after5m")},6e5)},3e5),t.wakeUp(function(){jt.remote().jsVersion(function(t,s){Lt.StorageResultType.Success===t&&s&&!s.Result&&(e.parent&&jt.settingsGet("InIframe")?e.parent.location.reload():e.location.reload())},jt.settingsGet("Version"))},{},36e5)}var It={},Lt={},Pt={},Mt={},Dt={},kt={},Ot={},_t={settings:[],"settings-removed":[],"settings-disabled":[]},Ut=[],xt=null,Vt=e.rainloopAppData||{},Ht=e.rainloopI18N||{},Bt=t("html"),Gt=t(e),Kt=t(e.document),qt=e.Notification&&e.Notification.requestPermission?e.Notification:null,jt=null,zt=t("");Ot.now=(new Date).getTime(),Ot.momentTrigger=s.observable(!0),Ot.dropdownVisibility=s.observable(!1).extend({rateLimit:0}),Ot.tooltipTrigger=s.observable(!1).extend({rateLimit:0}),Ot.langChangeTrigger=s.observable(!0),Ot.iAjaxErrorCount=0,Ot.iTokenErrorCount=0,Ot.iMessageBodyCacheCount=0,Ot.bUnload=!1,Ot.sUserAgent=(navigator.userAgent||"").toLowerCase(),Ot.bIsiOSDevice=-1n;n++)o=i[n].split("="),s[e.decodeURIComponent(o[0])]=e.decodeURIComponent(o[1]);return s},Mt.rsaEncode=function(t,s,i,o){if(e.crypto&&e.crypto.getRandomValues&&e.RSAKey&&s&&i&&o){var n=new e.RSAKey;if(n.setPublic(o,i),t=n.encrypt(Mt.fakeMd5()+":"+t+":"+Mt.fakeMd5()),!1!==t)return"rsa:"+s+":"+t}return!1},Mt.rsaEncode.supported=!!(e.crypto&&e.crypto.getRandomValues&&e.RSAKey),Mt.exportPath=function(t,s,i){for(var o=null,n=t.split("."),a=i||e;n.length&&(o=n.shift());)n.length||Mt.isUnd(s)?a=a[o]?a[o]:a[o]={}:a[o]=s},Mt.pImport=function(e,t,s){e[t]=s},Mt.pExport=function(e,t,s){return Mt.isUnd(e[t])?s:e[t]},Mt.encodeHtml=function(e){return Mt.isNormal(e)?e.toString().replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"):""},Mt.splitPlainText=function(e,t){var s="",i="",o=e,n=0,a=0;for(t=Mt.isUnd(t)?100:t;o.length>t;)i=o.substring(0,t),n=i.lastIndexOf(" "),a=i.lastIndexOf("\n"),-1!==a&&(n=a),-1===n&&(n=t),s+=i.substring(0,n)+"\n",o=o.substring(n+1);return s+o},Mt.timeOutAction=function(){var t={};return function(s,i,o){Mt.isUnd(t[s])&&(t[s]=0),e.clearTimeout(t[s]),t[s]=e.setTimeout(i,o)}}(),Mt.timeOutActionSecond=function(){var t={};return function(s,i,o){t[s]||(t[s]=e.setTimeout(function(){i(),t[s]=0},o))}}(),Mt.audio=function(){var t=!1;return function(s,i){if(!1===t)if(Ot.bIsiOSDevice)t=null;else{var o=!1,n=!1,a=e.Audio?new e.Audio:null;a&&a.canPlayType&&a.play?(o=""!==a.canPlayType('audio/mpeg; codecs="mp3"'),o||(n=""!==a.canPlayType('audio/ogg; codecs="vorbis"')),o||n?(t=a,t.preload="none",t.loop=!1,t.autoplay=!1,t.muted=!1,t.src=o?s:i):t=null):t=null}return t}}(),Mt.hos=function(e,t){return e&&Object.hasOwnProperty?Object.hasOwnProperty.call(e,t):!1},Mt.i18n=function(e,t,s){var i="",o=Mt.isUnd(Ht[e])?Mt.isUnd(s)?e:s:Ht[e];if(!Mt.isUnd(t)&&!Mt.isNull(t))for(i in t)Mt.hos(t,i)&&(o=o.replace("%"+i+"%",t[i]));return o},Mt.i18nToNode=function(e){r.defer(function(){t(".i18n",e).each(function(){var e=t(this),s="";s=e.data("i18n-text"),s?e.text(Mt.i18n(s)):(s=e.data("i18n-html"),s&&e.html(Mt.i18n(s)),s=e.data("i18n-placeholder"),s&&e.attr("placeholder",Mt.i18n(s)),s=e.data("i18n-title"),s&&e.attr("title",Mt.i18n(s)))})})},Mt.i18nToDoc=function(){e.rainloopI18N&&(Ht=e.rainloopI18N||{},Mt.i18nToNode(Kt),Ot.langChangeTrigger(!Ot.langChangeTrigger())),e.rainloopI18N={}},Mt.initOnStartOrLangChange=function(e,t,s){e&&e.call(t),s?Ot.langChangeTrigger.subscribe(function(){e&&e.call(t),s.call(t)}):e&&Ot.langChangeTrigger.subscribe(e,t)},Mt.inFocus=function(){return document.activeElement?(Mt.isUnd(document.activeElement.__inFocusCache)&&(document.activeElement.__inFocusCache=t(document.activeElement).is("input,textarea,iframe,.cke_editable")),!!document.activeElement.__inFocusCache):!1},Mt.removeInFocus=function(){if(document&&document.activeElement&&document.activeElement.blur){var e=t(document.activeElement);e.is("input,textarea")&&document.activeElement.blur()}},Mt.removeSelection=function(){if(e&&e.getSelection){var t=e.getSelection();t&&t.removeAllRanges&&t.removeAllRanges()}else document&&document.selection&&document.selection.empty&&document.selection.empty()},Mt.replySubjectAdd=function(e,t){e=Mt.trim(e.toUpperCase()),t=Mt.trim(t.replace(/[\s]+/," "));var s=0,i="",o=!1,n="",a=[],r=[],l="RE"===e,c="FWD"===e,u=!c;if(""!==t){for(o=!1,r=t.split(":"),s=0;s0);return e.replace(/[\s]+/," ")},Mt._replySubjectAdd_=function(t,s,i){var o=null,n=Mt.trim(s);return n=null===(o=new e.RegExp("^"+t+"[\\s]?\\:(.*)$","gi").exec(s))||Mt.isUnd(o[1])?null===(o=new e.RegExp("^("+t+"[\\s]?[\\[\\(]?)([\\d]+)([\\]\\)]?[\\s]?\\:.*)$","gi").exec(s))||Mt.isUnd(o[1])||Mt.isUnd(o[2])||Mt.isUnd(o[3])?t+": "+s:o[1]+(Mt.pInt(o[2])+1)+o[3]:t+"[2]: "+o[1],n=n.replace(/[\s]+/g," "),n=(Mt.isUnd(i)?!0:i)?Mt.fixLongSubject(n):n},Mt._fixLongSubject_=function(e){var t=0,s=null;e=Mt.trim(e.replace(/[\s]+/," "));do s=/^Re(\[([\d]+)\]|):[\s]{0,3}Re(\[([\d]+)\]|):/gi.exec(e),(!s||Mt.isUnd(s[0]))&&(s=null),s&&(t=0,t+=Mt.isUnd(s[2])?1:0+Mt.pInt(s[2]),t+=Mt.isUnd(s[4])?1:0+Mt.pInt(s[4]),e=e.replace(/^Re(\[[\d]+\]|):[\s]{0,3}Re(\[[\d]+\]|):/gi,"Re"+(t>0?"["+t+"]":"")+":"));while(s);return e=e.replace(/[\s]+/," ")},Mt.roundNumber=function(e,t){return Math.round(e*Math.pow(10,t))/Math.pow(10,t)},Mt.friendlySize=function(e){return e=Mt.pInt(e),e>=1073741824?Mt.roundNumber(e/1073741824,1)+"GB":e>=1048576?Mt.roundNumber(e/1048576,1)+"MB":e>=1024?Mt.roundNumber(e/1024,0)+"KB":e+"B"},Mt.log=function(t){e.console&&e.console.log&&e.console.log(t)},Mt.getNotification=function(e,t){return e=Mt.pInt(e),Lt.Notification.ClientViewError===e&&t?t:Mt.isUnd(Pt[e])?"":Pt[e]},Mt.initNotificationLanguage=function(){Pt[Lt.Notification.InvalidToken]=Mt.i18n("NOTIFICATIONS/INVALID_TOKEN"),Pt[Lt.Notification.AuthError]=Mt.i18n("NOTIFICATIONS/AUTH_ERROR"),Pt[Lt.Notification.AccessError]=Mt.i18n("NOTIFICATIONS/ACCESS_ERROR"),Pt[Lt.Notification.ConnectionError]=Mt.i18n("NOTIFICATIONS/CONNECTION_ERROR"),Pt[Lt.Notification.CaptchaError]=Mt.i18n("NOTIFICATIONS/CAPTCHA_ERROR"),Pt[Lt.Notification.SocialFacebookLoginAccessDisable]=Mt.i18n("NOTIFICATIONS/SOCIAL_FACEBOOK_LOGIN_ACCESS_DISABLE"),Pt[Lt.Notification.SocialTwitterLoginAccessDisable]=Mt.i18n("NOTIFICATIONS/SOCIAL_TWITTER_LOGIN_ACCESS_DISABLE"),Pt[Lt.Notification.SocialGoogleLoginAccessDisable]=Mt.i18n("NOTIFICATIONS/SOCIAL_GOOGLE_LOGIN_ACCESS_DISABLE"),Pt[Lt.Notification.DomainNotAllowed]=Mt.i18n("NOTIFICATIONS/DOMAIN_NOT_ALLOWED"),Pt[Lt.Notification.AccountNotAllowed]=Mt.i18n("NOTIFICATIONS/ACCOUNT_NOT_ALLOWED"),Pt[Lt.Notification.AccountTwoFactorAuthRequired]=Mt.i18n("NOTIFICATIONS/ACCOUNT_TWO_FACTOR_AUTH_REQUIRED"),Pt[Lt.Notification.AccountTwoFactorAuthError]=Mt.i18n("NOTIFICATIONS/ACCOUNT_TWO_FACTOR_AUTH_ERROR"),Pt[Lt.Notification.CouldNotSaveNewPassword]=Mt.i18n("NOTIFICATIONS/COULD_NOT_SAVE_NEW_PASSWORD"),Pt[Lt.Notification.CurrentPasswordIncorrect]=Mt.i18n("NOTIFICATIONS/CURRENT_PASSWORD_INCORRECT"),Pt[Lt.Notification.NewPasswordShort]=Mt.i18n("NOTIFICATIONS/NEW_PASSWORD_SHORT"),Pt[Lt.Notification.NewPasswordWeak]=Mt.i18n("NOTIFICATIONS/NEW_PASSWORD_WEAK"),Pt[Lt.Notification.NewPasswordForbidden]=Mt.i18n("NOTIFICATIONS/NEW_PASSWORD_FORBIDDENT"),Pt[Lt.Notification.ContactsSyncError]=Mt.i18n("NOTIFICATIONS/CONTACTS_SYNC_ERROR"),Pt[Lt.Notification.CantGetMessageList]=Mt.i18n("NOTIFICATIONS/CANT_GET_MESSAGE_LIST"),Pt[Lt.Notification.CantGetMessage]=Mt.i18n("NOTIFICATIONS/CANT_GET_MESSAGE"),Pt[Lt.Notification.CantDeleteMessage]=Mt.i18n("NOTIFICATIONS/CANT_DELETE_MESSAGE"),Pt[Lt.Notification.CantMoveMessage]=Mt.i18n("NOTIFICATIONS/CANT_MOVE_MESSAGE"),Pt[Lt.Notification.CantCopyMessage]=Mt.i18n("NOTIFICATIONS/CANT_MOVE_MESSAGE"),Pt[Lt.Notification.CantSaveMessage]=Mt.i18n("NOTIFICATIONS/CANT_SAVE_MESSAGE"),Pt[Lt.Notification.CantSendMessage]=Mt.i18n("NOTIFICATIONS/CANT_SEND_MESSAGE"),Pt[Lt.Notification.InvalidRecipients]=Mt.i18n("NOTIFICATIONS/INVALID_RECIPIENTS"),Pt[Lt.Notification.CantCreateFolder]=Mt.i18n("NOTIFICATIONS/CANT_CREATE_FOLDER"),Pt[Lt.Notification.CantRenameFolder]=Mt.i18n("NOTIFICATIONS/CANT_RENAME_FOLDER"),Pt[Lt.Notification.CantDeleteFolder]=Mt.i18n("NOTIFICATIONS/CANT_DELETE_FOLDER"),Pt[Lt.Notification.CantDeleteNonEmptyFolder]=Mt.i18n("NOTIFICATIONS/CANT_DELETE_NON_EMPTY_FOLDER"),Pt[Lt.Notification.CantSubscribeFolder]=Mt.i18n("NOTIFICATIONS/CANT_SUBSCRIBE_FOLDER"),Pt[Lt.Notification.CantUnsubscribeFolder]=Mt.i18n("NOTIFICATIONS/CANT_UNSUBSCRIBE_FOLDER"),Pt[Lt.Notification.CantSaveSettings]=Mt.i18n("NOTIFICATIONS/CANT_SAVE_SETTINGS"),Pt[Lt.Notification.CantSavePluginSettings]=Mt.i18n("NOTIFICATIONS/CANT_SAVE_PLUGIN_SETTINGS"),Pt[Lt.Notification.DomainAlreadyExists]=Mt.i18n("NOTIFICATIONS/DOMAIN_ALREADY_EXISTS"),Pt[Lt.Notification.CantInstallPackage]=Mt.i18n("NOTIFICATIONS/CANT_INSTALL_PACKAGE"),Pt[Lt.Notification.CantDeletePackage]=Mt.i18n("NOTIFICATIONS/CANT_DELETE_PACKAGE"),Pt[Lt.Notification.InvalidPluginPackage]=Mt.i18n("NOTIFICATIONS/INVALID_PLUGIN_PACKAGE"),Pt[Lt.Notification.UnsupportedPluginPackage]=Mt.i18n("NOTIFICATIONS/UNSUPPORTED_PLUGIN_PACKAGE"),Pt[Lt.Notification.LicensingServerIsUnavailable]=Mt.i18n("NOTIFICATIONS/LICENSING_SERVER_IS_UNAVAILABLE"),Pt[Lt.Notification.LicensingExpired]=Mt.i18n("NOTIFICATIONS/LICENSING_EXPIRED"),Pt[Lt.Notification.LicensingBanned]=Mt.i18n("NOTIFICATIONS/LICENSING_BANNED"),Pt[Lt.Notification.DemoSendMessageError]=Mt.i18n("NOTIFICATIONS/DEMO_SEND_MESSAGE_ERROR"),Pt[Lt.Notification.AccountAlreadyExists]=Mt.i18n("NOTIFICATIONS/ACCOUNT_ALREADY_EXISTS"),Pt[Lt.Notification.MailServerError]=Mt.i18n("NOTIFICATIONS/MAIL_SERVER_ERROR"),Pt[Lt.Notification.InvalidInputArgument]=Mt.i18n("NOTIFICATIONS/INVALID_INPUT_ARGUMENT"),Pt[Lt.Notification.UnknownNotification]=Mt.i18n("NOTIFICATIONS/UNKNOWN_ERROR"),Pt[Lt.Notification.UnknownError]=Mt.i18n("NOTIFICATIONS/UNKNOWN_ERROR")},Mt.getUploadErrorDescByCode=function(e){var t="";switch(Mt.pInt(e)){case Lt.UploadErrorCode.FileIsTooBig:t=Mt.i18n("UPLOAD/ERROR_FILE_IS_TOO_BIG");break;case Lt.UploadErrorCode.FilePartiallyUploaded:t=Mt.i18n("UPLOAD/ERROR_FILE_PARTIALLY_UPLOADED");break;case Lt.UploadErrorCode.FileNoUploaded:t=Mt.i18n("UPLOAD/ERROR_NO_FILE_UPLOADED");break;case Lt.UploadErrorCode.MissingTempFolder:t=Mt.i18n("UPLOAD/ERROR_MISSING_TEMP_FOLDER");break;case Lt.UploadErrorCode.FileOnSaveingError:t=Mt.i18n("UPLOAD/ERROR_ON_SAVING_FILE");break;case Lt.UploadErrorCode.FileType:t=Mt.i18n("UPLOAD/ERROR_FILE_TYPE");break;default:t=Mt.i18n("UPLOAD/ERROR_UNKNOWN")}return t},Mt.delegateRun=function(e,t,s,i){e&&e[t]&&(i=Mt.pInt(i),0>=i?e[t].apply(e,Mt.isArray(s)?s:[]):r.delay(function(){e[t].apply(e,Mt.isArray(s)?s:[])},i))},Mt.killCtrlAandS=function(t){if(t=t||e.event,t&&t.ctrlKey&&!t.shiftKey&&!t.altKey){var s=t.target||t.srcElement,i=t.keyCode||t.which;if(i===Lt.EventKeyCode.S)return void t.preventDefault();if(s&&s.tagName&&s.tagName.match(/INPUT|TEXTAREA/i))return;i===Lt.EventKeyCode.A&&(e.getSelection?e.getSelection().removeAllRanges():e.document.selection&&e.document.selection.clear&&e.document.selection.clear(),t.preventDefault())}},Mt.createCommand=function(e,t,i){var o=t?function(){return o.canExecute&&o.canExecute()&&t.apply(e,Array.prototype.slice.call(arguments)),!1}:function(){};return o.enabled=s.observable(!0),i=Mt.isUnd(i)?!0:i,o.canExecute=s.computed(Mt.isFunc(i)?function(){return o.enabled()&&i.call(e)}:function(){return o.enabled()&&!!i}),o},Mt.initDataConstructorBySettings=function(t){t.editorDefaultType=s.observable(Lt.EditorDefaultType.Html),t.showImages=s.observable(!1),t.interfaceAnimation=s.observable(Lt.InterfaceAnimation.Full),t.contactsAutosave=s.observable(!1),Ot.sAnimationType=Lt.InterfaceAnimation.Full,t.capaThemes=s.observable(!1),t.allowLanguagesOnSettings=s.observable(!0),t.allowLanguagesOnLogin=s.observable(!0),t.useLocalProxyForExternalImages=s.observable(!1),t.desktopNotifications=s.observable(!1),t.useThreads=s.observable(!0),t.replySameFolder=s.observable(!0),t.useCheckboxesInList=s.observable(!0),t.layout=s.observable(Lt.Layout.SidePreview),t.usePreviewPane=s.computed(function(){return Lt.Layout.NoPreview!==t.layout()}),t.interfaceAnimation.subscribe(function(e){if(Ot.bMobileDevice||e===Lt.InterfaceAnimation.None)Bt.removeClass("rl-anim rl-anim-full").addClass("no-rl-anim"),Ot.sAnimationType=Lt.InterfaceAnimation.None;else switch(e){case Lt.InterfaceAnimation.Full:Bt.removeClass("no-rl-anim").addClass("rl-anim rl-anim-full"),Ot.sAnimationType=e;break;case Lt.InterfaceAnimation.Normal:Bt.removeClass("no-rl-anim rl-anim-full").addClass("rl-anim"),Ot.sAnimationType=e
-}}),t.interfaceAnimation.valueHasMutated(),t.desktopNotificationsPermisions=s.computed(function(){t.desktopNotifications();var s=Lt.DesktopNotifications.NotSupported;if(qt&&qt.permission)switch(qt.permission.toLowerCase()){case"granted":s=Lt.DesktopNotifications.Allowed;break;case"denied":s=Lt.DesktopNotifications.Denied;break;case"default":s=Lt.DesktopNotifications.NotAllowed}else e.webkitNotifications&&e.webkitNotifications.checkPermission&&(s=e.webkitNotifications.checkPermission());return s}),t.useDesktopNotifications=s.computed({read:function(){return t.desktopNotifications()&&Lt.DesktopNotifications.Allowed===t.desktopNotificationsPermisions()},write:function(e){if(e){var s=t.desktopNotificationsPermisions();Lt.DesktopNotifications.Allowed===s?t.desktopNotifications(!0):Lt.DesktopNotifications.NotAllowed===s?qt.requestPermission(function(){t.desktopNotifications.valueHasMutated(),Lt.DesktopNotifications.Allowed===t.desktopNotificationsPermisions()?t.desktopNotifications()?t.desktopNotifications.valueHasMutated():t.desktopNotifications(!0):t.desktopNotifications()?t.desktopNotifications(!1):t.desktopNotifications.valueHasMutated()}):t.desktopNotifications(!1)}else t.desktopNotifications(!1)}}),t.language=s.observable(""),t.languages=s.observableArray([]),t.mainLanguage=s.computed({read:t.language,write:function(e){e!==t.language()?-1=t.diff(s,"hours")?i:t.format("L")===s.format("L")?Mt.i18n("MESSAGE_LIST/TODAY_AT",{TIME:s.format("LT")}):t.clone().subtract("days",1).format("L")===s.format("L")?Mt.i18n("MESSAGE_LIST/YESTERDAY_AT",{TIME:s.format("LT")}):s.format(t.year()===s.year()?"D MMM.":"LL")},e)},Mt.isFolderExpanded=function(e){var t=jt.local().get(Lt.ClientSideKeyName.ExpandedFolders);return r.isArray(t)&&-1!==r.indexOf(t,e)},Mt.setExpandedFolder=function(e,t){var s=jt.local().get(Lt.ClientSideKeyName.ExpandedFolders);r.isArray(s)||(s=[]),t?(s.push(e),s=r.uniq(s)):s=r.without(s,e),jt.local().set(Lt.ClientSideKeyName.ExpandedFolders,s)},Mt.initLayoutResizer=function(e,s,i){var o=60,n=155,a=t(e),r=t(s),l=jt.local().get(i)||null,c=function(e){e&&(a.css({width:""+e+"px"}),r.css({left:""+e+"px"}))},u=function(e){if(e)a.resizable("disable"),c(o);else{a.resizable("enable");var t=Mt.pInt(jt.local().get(i))||n;c(t>n?t:n)}},d=function(e,t){t&&t.size&&t.size.width&&(jt.local().set(i,t.size.width),r.css({left:""+t.size.width+"px"}))};null!==l&&c(l>n?l:n),a.resizable({helper:"ui-resizable-helper",minWidth:n,maxWidth:350,handles:"e",stop:d}),jt.sub("left-panel.off",function(){u(!0)}),jt.sub("left-panel.on",function(){u(!1)})},Mt.initBlockquoteSwitcher=function(e){if(e){var s=t("blockquote:not(.rl-bq-switcher)",e).filter(function(){return 0===t(this).parent().closest("blockquote",e).length});s&&0100)&&(e.addClass("rl-bq-switcher hidden-bq"),t('').insertBefore(e).click(function(){e.toggleClass("hidden-bq"),Mt.windowResize()}).after("
").before("
"))})}},Mt.removeBlockquoteSwitcher=function(e){e&&(t(e).find("blockquote.rl-bq-switcher").each(function(){t(this).removeClass("rl-bq-switcher hidden-bq")}),t(e).find(".rlBlockquoteSwitcher").each(function(){t(this).remove()}))},Mt.toggleMessageBlockquote=function(e){e&&e.find(".rlBlockquoteSwitcher").click()},Mt.extendAsViewModel=function(e,t,s){t&&(s||(s=b),t.__name=e,Dt.regViewModelHook(e,t),r.extend(t.prototype,s.prototype))},Mt.addSettingsViewModel=function(e,t,s,i,o){e.__rlSettingsData={Label:s,Template:t,Route:i,IsDefault:!!o},_t.settings.push(e)},Mt.removeSettingsViewModel=function(e){_t["settings-removed"].push(e)},Mt.disableSettingsViewModel=function(e){_t["settings-disabled"].push(e)},Mt.convertThemeName=function(e){return"@custom"===e.substr(-7)&&(e=Mt.trim(e.substring(0,e.length-7))),Mt.trim(e.replace(/[^a-zA-Z]+/g," ").replace(/([A-Z])/g," $1").replace(/[\s]+/g," "))},Mt.quoteName=function(e){return e.replace(/["]/g,'\\"')},Mt.microtime=function(){return(new Date).getTime()},Mt.convertLangName=function(e,t){return Mt.i18n("LANGS_NAMES"+(!0===t?"_EN":"")+"/LANG_"+e.toUpperCase().replace(/[^a-zA-Z0-9]+/,"_"),null,e)},Mt.fakeMd5=function(e){var t="",s="0123456789abcdefghijklmnopqrstuvwxyz";for(e=Mt.isUnd(e)?32:Mt.pInt(e);t.length>>32-t}function s(e,t){var s,i,o,n,a;return o=2147483648&e,n=2147483648&t,s=1073741824&e,i=1073741824&t,a=(1073741823&e)+(1073741823&t),s&i?2147483648^a^o^n:s|i?1073741824&a?3221225472^a^o^n:1073741824^a^o^n:a^o^n}function i(e,t,s){return e&t|~e&s}function o(e,t,s){return e&s|t&~s}function n(e,t,s){return e^t^s}function a(e,t,s){return t^(e|~s)}function r(e,o,n,a,r,l,c){return e=s(e,s(s(i(o,n,a),r),c)),s(t(e,l),o)}function l(e,i,n,a,r,l,c){return e=s(e,s(s(o(i,n,a),r),c)),s(t(e,l),i)}function c(e,i,o,a,r,l,c){return e=s(e,s(s(n(i,o,a),r),c)),s(t(e,l),i)}function u(e,i,o,n,r,l,c){return e=s(e,s(s(a(i,o,n),r),c)),s(t(e,l),i)}function d(e){for(var t,s=e.length,i=s+8,o=(i-i%64)/64,n=16*(o+1),a=Array(n-1),r=0,l=0;s>l;)t=(l-l%4)/4,r=l%4*8,a[t]=a[t]|e.charCodeAt(l)<>>29,a}function h(e){var t,s,i="",o="";for(s=0;3>=s;s++)t=e>>>8*s&255,o="0"+t.toString(16),i+=o.substr(o.length-2,2);return i}function p(e){e=e.replace(/rn/g,"n");for(var t="",s=0;si?t+=String.fromCharCode(i):i>127&&2048>i?(t+=String.fromCharCode(i>>6|192),t+=String.fromCharCode(63&i|128)):(t+=String.fromCharCode(i>>12|224),t+=String.fromCharCode(i>>6&63|128),t+=String.fromCharCode(63&i|128))}return t}var m,g,f,b,y,S,v,C,w,T=Array(),F=7,A=12,E=17,N=22,R=5,I=9,L=14,P=20,M=4,D=11,k=16,O=23,_=6,U=10,x=15,V=21;for(e=p(e),T=d(e),S=1732584193,v=4023233417,C=2562383102,w=271733878,m=0;m /g,">").replace(/")},Mt.draggeblePlace=function(){return t(' ').appendTo("#rl-hidden")},Mt.defautOptionsAfterRender=function(e,s){s&&!Mt.isUnd(s.disabled)&&e&&t(e).toggleClass("disabled",s.disabled).prop("disabled",s.disabled)},Mt.windowPopupKnockout=function(s,i,o,n){var a=null,r=e.open(""),l="__OpenerApplyBindingsUid"+Mt.fakeMd5()+"__",c=t("#"+i);e[l]=function(){if(r&&r.document.body&&c&&c[0]){var i=t(r.document.body);t("#rl-content",i).html(c.html()),t("html",r.document).addClass("external "+t("html").attr("class")),Mt.i18nToNode(i),S.prototype.applyExternal(s,t("#rl-content",i)[0]),e[l]=null,n(r)}},r.document.open(),r.document.write(''+Mt.encodeHtml(o)+' '),r.document.close(),a=r.document.createElement("script"),a.type="text/javascript",a.innerHTML="if(window&&window.opener&&window.opener['"+l+"']){window.opener['"+l+"']();window.opener['"+l+"']=null}",r.document.getElementsByTagName("head")[0].appendChild(a)},Mt.settingsSaveHelperFunction=function(e,t,s,i){return s=s||null,i=Mt.isUnd(i)?1e3:Mt.pInt(i),function(o,n,a,l,c){t.call(s,n&&n.Result?Lt.SaveSettingsStep.TrueResult:Lt.SaveSettingsStep.FalseResult),e&&e.call(s,o,n,a,l,c),r.delay(function(){t.call(s,Lt.SaveSettingsStep.Idle)},i)}},Mt.settingsSaveHelperSimpleFunction=function(e,t){return Mt.settingsSaveHelperFunction(null,e,t,1e3)},Mt.$div=t(""),Mt.htmlToPlain=function(e){var s=0,i=0,o=0,n=0,a=0,r="",l=function(e){for(var t=100,s="",i="",o=e,n=0,a=0;o.length>t;)i=o.substring(0,t),n=i.lastIndexOf(" "),a=i.lastIndexOf("\n"),-1!==a&&(n=a),-1===n&&(n=t),s+=i.substring(0,n)+"\n",o=o.substring(n+1);return s+o},c=function(e){return e=l(t.trim(e)),e="> "+e.replace(/\n/gm,"\n> "),e.replace(/(^|\n)([> ]+)/gm,function(){return arguments&&2]*>([\s\S\r\n]*)<\/div>/gim,u),e="\n"+t.trim(e)+"\n"),e}return""},d=function(){return arguments&&1 "):""},h=function(){return arguments&&1 /g,">"):""},p=function(){return arguments&&1]*>([\s\S\r\n]*)<\/pre>/gim,d).replace(/[\s]+/gm," ").replace(/((?:href|data)\s?=\s?)("[^"]+?"|'[^']+?')/gim,h).replace(/
]*>/gim,"\n").replace(/<\/h[\d]>/gi,"\n").replace(/<\/p>/gi,"\n\n").replace(/<\/li>/gi,"\n").replace(/<\/td>/gi,"\n").replace(/<\/tr>/gi,"\n").replace(/
]*>/gim,"\n_______________________________\n\n").replace(/]*>([\s\S\r\n]*)<\/div>/gim,u).replace(/]*>/gim,"\n__bq__start__\n").replace(/<\/blockquote>/gim,"\n__bq__end__\n").replace(/]*>([\s\S\r\n]*?)<\/a>/gim,p).replace(/<\/div>/gi,"\n").replace(/ /gi," ").replace(/"/gi,'"').replace(/<[^>]*>/gm,""),r=Mt.$div.html(r).text(),r=r.replace(/\n[ \t]+/gm,"\n").replace(/[\n]{3,}/gm,"\n\n").replace(/>/gi,">").replace(/</gi,"<").replace(/&/gi,"&"),s=0,a=100;a>0&&(a--,i=r.indexOf("__bq__start__",s),i>-1);)o=r.indexOf("__bq__start__",i+5),n=r.indexOf("__bq__end__",i+5),(-1===o||o>n)&&n>i?(r=r.substring(0,i)+c(r.substring(i+13,n))+r.substring(n+11),s=0):s=o>-1&&n>o?o-1:0;return r=r.replace(/__bq__start__/gm,"").replace(/__bq__end__/gm,"")},Mt.plainToHtml=function(e,t){e=e.toString().replace(/\r/g,"");var s=!1,i=!0,o=!0,n=[],a="",r=0,l=e.split("\n");do{for(i=!1,n=[],r=0;r"===a.substr(0,1),o&&!s?(i=!0,s=!0,n.push("~~~blockquote~~~"),n.push(a.substr(1))):!o&&s?(s=!1,n.push("~~~/blockquote~~~"),n.push(a)):n.push(o&&s?a.substr(1):a);s&&(s=!1,n.push("~~~/blockquote~~~")),l=n}while(i);return e=l.join("\n"),e=e.replace(/&/g,"&").replace(/>/g,">").replace(/").replace(/[\s]*~~~\/blockquote~~~/g,"
").replace(/[\-_~]{10,}/g,"
").replace(/\n/g,"
"),t?Mt.linkify(e):e},e.rainloop_Utils_htmlToPlain=Mt.htmlToPlain,e.rainloop_Utils_plainToHtml=Mt.plainToHtml,Mt.linkify=function(e){return t.fn&&t.fn.linkify&&(e=Mt.$div.html(e.replace(/&/gi,"amp_amp_12345_amp_amp")).linkify().find(".linkified").removeClass("linkified").end().html().replace(/amp_amp_12345_amp_amp/g,"&")),e},Mt.resizeAndCrop=function(t,s,i){var o=new e.Image;o.onload=function(){var e=[0,0],t=document.createElement("canvas"),o=t.getContext("2d");t.width=s,t.height=s,e=this.width>this.height?[this.width-this.height,0]:[0,this.height-this.width],o.fillStyle="#fff",o.fillRect(0,0,s,s),o.drawImage(this,e[0]/2,e[1]/2,this.width-e[0],this.height-e[1],0,0,s,s),i(t.toDataURL("image/jpeg"))},o.src=t},Mt.computedPagenatorHelper=function(e,t){return function(){var s=0,i=0,o=2,n=[],a=e(),r=t(),l=function(e,t,s){var i={current:e===a,name:Mt.isUnd(s)?e.toString():s.toString(),custom:Mt.isUnd(s)?!1:!0,title:Mt.isUnd(s)?"":e.toString(),value:e.toString()};(Mt.isUnd(t)?0:!t)?n.unshift(i):n.push(i)};if(r>1||r>0&&a>r){for(a>r?(l(r),s=r,i=r):((3>=a||a>=r-2)&&(o+=2),l(a),s=a,i=a);o>0;)if(s-=1,i+=1,s>0&&(l(s,!1),o--),r>=i)l(i,!0),o--;else if(0>=s)break;3===s?l(2,!1):s>3&&l(Math.round((s-1)/2),!1,"..."),r-2===i?l(r-1,!0):r-2>i&&l(Math.round((r+i)/2),!0,"..."),s>1&&l(1,!1),r>i&&l(r,!0)}return n}},Mt.selectElement=function(t){if(e.getSelection){var s=e.getSelection();s.removeAllRanges();var i=document.createRange();i.selectNodeContents(t),s.addRange(i)}else if(document.selection){var o=document.body.createTextRange();o.moveToElementText(t),o.select()}},Mt.disableKeyFilter=function(){e.key&&(c.filter=function(){return jt.data().useKeyboardShortcuts()})},Mt.restoreKeyFilter=function(){e.key&&(c.filter=function(e){if(jt.data().useKeyboardShortcuts()){var t=e.target||e.srcElement,s=t?t.tagName:"";return s=s.toUpperCase(),!("INPUT"===s||"SELECT"===s||"TEXTAREA"===s||t&&"DIV"===s&&"editorHtmlArea"===t.className&&t.contentEditable)}return!1})},Mt.detectDropdownVisibility=r.debounce(function(){Ot.dropdownVisibility(!!r.find(Ut,function(e){return e.hasClass("open")}))},50),Mt.triggerAutocompleteInputChange=function(e){var s=function(){t(".checkAutocomplete").trigger("change")};e?r.delay(s,100):s()},kt={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",urlsafe_encode:function(e){return kt.encode(e).replace(/[+]/g,"-").replace(/[\/]/g,"_").replace(/[=]/g,".")},encode:function(e){var t,s,i,o,n,a,r,l="",c=0;for(e=kt._utf8_encode(e);c>2,n=(3&t)<<4|s>>4,a=(15&s)<<2|i>>6,r=63&i,isNaN(s)?a=r=64:isNaN(i)&&(r=64),l=l+this._keyStr.charAt(o)+this._keyStr.charAt(n)+this._keyStr.charAt(a)+this._keyStr.charAt(r);return l},decode:function(e){var t,s,i,o,n,a,r,l="",c=0;for(e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");c>4,s=(15&n)<<4|a>>2,i=(3&a)<<6|r,l+=String.fromCharCode(t),64!==a&&(l+=String.fromCharCode(s)),64!==r&&(l+=String.fromCharCode(i));return kt._utf8_decode(l)},_utf8_encode:function(e){e=e.replace(/\r\n/g,"\n");for(var t="",s=0,i=e.length,o=0;i>s;s++)o=e.charCodeAt(s),128>o?t+=String.fromCharCode(o):o>127&&2048>o?(t+=String.fromCharCode(o>>6|192),t+=String.fromCharCode(63&o|128)):(t+=String.fromCharCode(o>>12|224),t+=String.fromCharCode(o>>6&63|128),t+=String.fromCharCode(63&o|128));return t},_utf8_decode:function(e){for(var t="",s=0,i=0,o=0,n=0;si?(t+=String.fromCharCode(i),s++):i>191&&224>i?(o=e.charCodeAt(s+1),t+=String.fromCharCode((31&i)<<6|63&o),s+=2):(o=e.charCodeAt(s+1),n=e.charCodeAt(s+2),t+=String.fromCharCode((15&i)<<12|(63&o)<<6|63&n),s+=3);return t}},s.bindingHandlers.tooltip={init:function(e,i){if(!Ot.bMobileDevice){var o=t(e),n=o.data("tooltip-class")||"",a=o.data("tooltip-placement")||"top";o.tooltip({delay:{show:500,hide:100},html:!0,container:"body",placement:a,trigger:"hover",title:function(){return o.is(".disabled")||Ot.dropdownVisibility()?"":''+Mt.i18n(s.utils.unwrapObservable(i()))+""}}).click(function(){o.tooltip("hide")}),Ot.tooltipTrigger.subscribe(function(){o.tooltip("hide")})}}},s.bindingHandlers.tooltip2={init:function(e,s){var i=t(e),o=i.data("tooltip-class")||"",n=i.data("tooltip-placement")||"top";i.tooltip({delay:{show:500,hide:100},html:!0,container:"body",placement:n,title:function(){return i.is(".disabled")||Ot.dropdownVisibility()?"":''+s()()+""}}).click(function(){i.tooltip("hide")}),Ot.tooltipTrigger.subscribe(function(){i.tooltip("hide")})}},s.bindingHandlers.tooltip3={init:function(e){var s=t(e);s.tooltip({container:"body",trigger:"hover manual",title:function(){return s.data("tooltip3-data")||""}}),Kt.click(function(){s.tooltip("hide")}),Ot.tooltipTrigger.subscribe(function(){s.tooltip("hide")})},update:function(e,i){var o=s.utils.unwrapObservable(i());""===o?t(e).data("tooltip3-data","").tooltip("hide"):t(e).data("tooltip3-data",o).tooltip("show")}},s.bindingHandlers.registrateBootstrapDropdown={init:function(e){Ut.push(t(e))}},s.bindingHandlers.openDropdownTrigger={update:function(e,i){if(s.utils.unwrapObservable(i())){var o=t(e);o.hasClass("open")||(o.find(".dropdown-toggle").dropdown("toggle"),Mt.detectDropdownVisibility()),i()(!1)}}},s.bindingHandlers.dropdownCloser={init:function(e){t(e).closest(".dropdown").on("click",".e-item",function(){t(e).dropdown("toggle")})}},s.bindingHandlers.popover={init:function(e,i){t(e).popover(s.utils.unwrapObservable(i()))}},s.bindingHandlers.csstext={init:function(e,i){e&&e.styleSheet&&!Mt.isUnd(e.styleSheet.cssText)?e.styleSheet.cssText=s.utils.unwrapObservable(i()):t(e).text(s.utils.unwrapObservable(i()))},update:function(e,i){e&&e.styleSheet&&!Mt.isUnd(e.styleSheet.cssText)?e.styleSheet.cssText=s.utils.unwrapObservable(i()):t(e).text(s.utils.unwrapObservable(i()))}},s.bindingHandlers.resizecrop={init:function(e){t(e).addClass("resizecrop").resizecrop({width:"100",height:"100",wrapperCSS:{"border-radius":"10px"}})},update:function(e,s){s()(),t(e).resizecrop({width:"100",height:"100"})}},s.bindingHandlers.onEnter={init:function(s,i,o,n){t(s).on("keypress",function(o){o&&13===e.parseInt(o.keyCode,10)&&(t(s).trigger("change"),i().call(n))})}},s.bindingHandlers.onEsc={init:function(s,i,o,n){t(s).on("keypress",function(o){o&&27===e.parseInt(o.keyCode,10)&&(t(s).trigger("change"),i().call(n))})}},s.bindingHandlers.clickOnTrue={update:function(e,i){s.utils.unwrapObservable(i())&&t(e).click()}},s.bindingHandlers.modal={init:function(e,i){t(e).toggleClass("fade",!Ot.bMobileDevice).modal({keyboard:!1,show:s.utils.unwrapObservable(i())}).on("shown",function(){Mt.windowResize()}).find(".close").click(function(){i()(!1)})},update:function(e,i){t(e).modal(s.utils.unwrapObservable(i())?"show":"hide")}},s.bindingHandlers.i18nInit={init:function(e){Mt.i18nToNode(e)}},s.bindingHandlers.i18nUpdate={update:function(e,t){s.utils.unwrapObservable(t()),Mt.i18nToNode(e)}},s.bindingHandlers.link={update:function(e,i){t(e).attr("href",s.utils.unwrapObservable(i()))}},s.bindingHandlers.title={update:function(e,i){t(e).attr("title",s.utils.unwrapObservable(i()))}},s.bindingHandlers.textF={init:function(e,i){t(e).text(s.utils.unwrapObservable(i()))}},s.bindingHandlers.initDom={init:function(e,t){t()(e)}},s.bindingHandlers.initResizeTrigger={init:function(e,i){var o=s.utils.unwrapObservable(i());t(e).css({height:o[1],"min-height":o[1]})},update:function(e,i){var o=s.utils.unwrapObservable(i()),n=Mt.pInt(o[1]),a=0,r=t(e).offset().top;r>0&&(r+=Mt.pInt(o[2]),a=Gt.height()-r,a>n&&(n=a),t(e).css({height:n,"min-height":n}))}},s.bindingHandlers.appendDom={update:function(e,i){t(e).hide().empty().append(s.utils.unwrapObservable(i())).show()}},s.bindingHandlers.draggable={init:function(i,o,n){if(!Ot.bMobileDevice){var a=100,r=3,l=n(),c=l&&l.droppableSelector?l.droppableSelector:"",u={distance:20,handle:".dragHandle",cursorAt:{top:22,left:3},refreshPositions:!0,scroll:!0};c&&(u.drag=function(s){t(c).each(function(){var i=null,o=null,n=t(this),l=n.offset(),c=l.top+n.height();e.clearInterval(n.data("timerScroll")),n.data("timerScroll",!1),s.pageX>=l.left&&s.pageX<=l.left+n.width()&&(s.pageY>=c-a&&s.pageY<=c&&(i=function(){n.scrollTop(n.scrollTop()+r),Mt.windowResize()},n.data("timerScroll",e.setInterval(i,10)),i()),s.pageY>=l.top&&s.pageY<=l.top+a&&(o=function(){n.scrollTop(n.scrollTop()-r),Mt.windowResize()},n.data("timerScroll",e.setInterval(o,10)),o()))})},u.stop=function(){t(c).each(function(){e.clearInterval(t(this).data("timerScroll")),t(this).data("timerScroll",!1)})}),u.helper=function(e){return o()(e&&e.target?s.dataFor(e.target):null)},t(i).draggable(u).on("mousedown",function(){Mt.removeInFocus()})}}},s.bindingHandlers.droppable={init:function(e,s,i){if(!Ot.bMobileDevice){var o=s(),n=i(),a=n&&n.droppableOver?n.droppableOver:null,r=n&&n.droppableOut?n.droppableOut:null,l={tolerance:"pointer",hoverClass:"droppableHover"};o&&(l.drop=function(e,t){o(e,t)},a&&(l.over=function(e,t){a(e,t)}),r&&(l.out=function(e,t){r(e,t)}),t(e).droppable(l))}}},s.bindingHandlers.nano={init:function(e){Ot.bDisableNanoScroll||t(e).addClass("nano").nanoScroller({iOSNativeScrolling:!1,preventPageScrolling:!0})}},s.bindingHandlers.saveTrigger={init:function(e){var s=t(e);s.data("save-trigger-type",s.is("input[type=text],input[type=email],input[type=password],select,textarea")?"input":"custom"),"custom"===s.data("save-trigger-type")?s.append(' ').addClass("settings-saved-trigger"):s.addClass("settings-saved-trigger-input")},update:function(e,i){var o=s.utils.unwrapObservable(i()),n=t(e);if("custom"===n.data("save-trigger-type"))switch(o.toString()){case"1":n.find(".animated,.error").hide().removeClass("visible").end().find(".success").show().addClass("visible");break;case"0":n.find(".animated,.success").hide().removeClass("visible").end().find(".error").show().addClass("visible");break;case"-2":n.find(".error,.success").hide().removeClass("visible").end().find(".animated").show().addClass("visible");break;default:n.find(".animated").hide().end().find(".error,.success").removeClass("visible")}else switch(o.toString()){case"1":n.addClass("success").removeClass("error");break;case"0":n.addClass("error").removeClass("success");break;case"-2":break;default:n.removeClass("error success")}}},s.bindingHandlers.emailsTags={init:function(e,s){var i=t(e),o=s(),n=function(e){o&&o.focusTrigger&&o.focusTrigger(e)};i.inputosaurus({parseOnBlur:!0,allowDragAndDrop:!0,focusCallback:n,inputDelimiters:[",",";"],autoCompleteSource:function(e,t){jt.getAutocomplete(e.term,function(e){t(r.map(e,function(e){return e.toLine(!1)}))})},parseHook:function(e){return r.map(e,function(e){var t=Mt.trim(e),s=null;return""!==t?(s=new v,s.mailsoParse(t),s.clearDuplicateName(),[s.toLine(!1),s]):[t,null]})},change:r.bind(function(e){i.data("EmailsTagsValue",e.target.value),o(e.target.value)},this)})},update:function(e,i,o){var n=t(e),a=o(),r=a.emailsTagsFilter||null,l=s.utils.unwrapObservable(i());n.data("EmailsTagsValue")!==l&&(n.val(l),n.data("EmailsTagsValue",l),n.inputosaurus("refresh")),r&&s.utils.unwrapObservable(r)&&n.inputosaurus("focus")}},s.bindingHandlers.contactTags={init:function(e,s){var i=t(e),o=s(),n=function(e){o&&o.focusTrigger&&o.focusTrigger(e)};i.inputosaurus({parseOnBlur:!0,allowDragAndDrop:!1,focusCallback:n,inputDelimiters:[",",";"],outputDelimiter:",",autoCompleteSource:function(e,t){jt.getContactTagsAutocomplete(e.term,function(e){t(r.map(e,function(e){return e.toLine(!1)}))})},parseHook:function(e){return r.map(e,function(e){var t=Mt.trim(e),s=null;return""!==t?(s=new T,s.name(t),[s.toLine(!1),s]):[t,null]})},change:r.bind(function(e){i.data("ContactTagsValue",e.target.value),o(e.target.value)},this)})},update:function(e,i,o){var n=t(e),a=o(),r=a.contactTagsFilter||null,l=s.utils.unwrapObservable(i());n.data("ContactTagsValue")!==l&&(n.val(l),n.data("ContactTagsValue",l),n.inputosaurus("refresh")),r&&s.utils.unwrapObservable(r)&&n.inputosaurus("focus")}},s.bindingHandlers.command={init:function(e,i,o,n){var a=t(e),r=i();if(!r||!r.enabled||!r.canExecute)throw new Error("You are not using command function");a.addClass("command"),s.bindingHandlers[a.is("form")?"submit":"click"].init.apply(n,arguments)},update:function(e,s){var i=!0,o=t(e),n=s();i=n.enabled(),o.toggleClass("command-not-enabled",!i),i&&(i=n.canExecute(),o.toggleClass("command-can-not-be-execute",!i)),o.toggleClass("command-disabled disable disabled",!i).toggleClass("no-disabled",!!i),(o.is("input")||o.is("button"))&&o.prop("disabled",!i)}},s.extenders.trimmer=function(e){var t=s.computed({read:e,write:function(t){e(Mt.trim(t.toString()))},owner:this});return t(e()),t},s.extenders.posInterer=function(e,t){var i=s.computed({read:e,write:function(s){var i=Mt.pInt(s.toString(),t);0>=i&&(i=t),i===e()&&""+i!=""+s&&e(i+1),e(i)}});return i(e()),i},s.extenders.reversible=function(e){var t=e();return e.commit=function(){t=e()},e.reverse=function(){e(t)},e.commitedValue=function(){return t},e},s.extenders.toggleSubscribe=function(e,t){return e.subscribe(t[1],t[0],"beforeChange"),e.subscribe(t[2],t[0]),e},s.extenders.falseTimeout=function(t,s){return t.iTimeout=0,t.subscribe(function(i){i&&(e.clearTimeout(t.iTimeout),t.iTimeout=e.setTimeout(function(){t(!1),t.iTimeout=0},Mt.pInt(s)))}),t},s.observable.fn.validateNone=function(){return this.hasError=s.observable(!1),this},s.observable.fn.validateEmail=function(){return this.hasError=s.observable(!1),this.subscribe(function(e){e=Mt.trim(e),this.hasError(""!==e&&!/^[^@\s]+@[^@\s]+$/.test(e))},this),this.valueHasMutated(),this},s.observable.fn.validateSimpleEmail=function(){return this.hasError=s.observable(!1),this.subscribe(function(e){e=Mt.trim(e),this.hasError(""!==e&&!/^.+@.+$/.test(e))},this),this.valueHasMutated(),this},s.observable.fn.validateFunc=function(e){return this.hasFuncError=s.observable(!1),Mt.isFunc(e)&&(this.subscribe(function(t){this.hasFuncError(!e(t))},this),this.valueHasMutated()),this},u.prototype.root=function(){return this.sBase},u.prototype.attachmentDownload=function(e){return this.sServer+"/Raw/"+this.sSpecSuffix+"/Download/"+e},u.prototype.attachmentPreview=function(e){return this.sServer+"/Raw/"+this.sSpecSuffix+"/View/"+e},u.prototype.attachmentPreviewAsPlain=function(e){return this.sServer+"/Raw/"+this.sSpecSuffix+"/ViewAsPlain/"+e},u.prototype.upload=function(){return this.sServer+"/Upload/"+this.sSpecSuffix+"/"},u.prototype.uploadContacts=function(){return this.sServer+"/UploadContacts/"+this.sSpecSuffix+"/"},u.prototype.uploadBackground=function(){return this.sServer+"/UploadBackground/"+this.sSpecSuffix+"/"},u.prototype.append=function(){return this.sServer+"/Append/"+this.sSpecSuffix+"/"},u.prototype.change=function(t){return this.sServer+"/Change/"+this.sSpecSuffix+"/"+e.encodeURIComponent(t)+"/"},u.prototype.ajax=function(e){return this.sServer+"/Ajax/"+this.sSpecSuffix+"/"+e},u.prototype.messageViewLink=function(e){return this.sServer+"/Raw/"+this.sSpecSuffix+"/ViewAsPlain/"+e},u.prototype.messageDownloadLink=function(e){return this.sServer+"/Raw/"+this.sSpecSuffix+"/Download/"+e},u.prototype.avatarLink=function(t){return this.sServer+"/Raw/0/Avatar/"+e.encodeURIComponent(t)+"/"},u.prototype.inbox=function(){return this.sBase+"mailbox/Inbox"},u.prototype.messagePreview=function(){return this.sBase+"mailbox/message-preview"},u.prototype.settings=function(e){var t=this.sBase+"settings";return Mt.isUnd(e)||""===e||(t+="/"+e),t},u.prototype.admin=function(e){var t=this.sBase;switch(e){case"AdminDomains":t+="domains";break;case"AdminSecurity":t+="security";break;case"AdminLicensing":t+="licensing"}return t},u.prototype.mailBox=function(e,t,s){t=Mt.isNormal(t)?Mt.pInt(t):1,s=Mt.pString(s);var i=this.sBase+"mailbox/";return""!==e&&(i+=encodeURI(e)),t>1&&(i=i.replace(/[\/]+$/,""),i+="/p"+t),""!==s&&(i=i.replace(/[\/]+$/,""),i+="/"+encodeURI(s)),i},u.prototype.phpInfo=function(){return this.sServer+"Info"},u.prototype.langLink=function(e){return this.sServer+"/Lang/0/"+encodeURI(e)+"/"+this.sVersion+"/"},u.prototype.exportContactsVcf=function(){return this.sServer+"/Raw/"+this.sSpecSuffix+"/ContactsVcf/"},u.prototype.exportContactsCsv=function(){return this.sServer+"/Raw/"+this.sSpecSuffix+"/ContactsCsv/"},u.prototype.emptyContactPic=function(){return this.sStaticPrefix+"css/images/empty-contact.png"},u.prototype.sound=function(e){return this.sStaticPrefix+"sounds/"+e},u.prototype.themePreviewLink=function(e){var t="rainloop/v/"+this.sVersion+"/";return"@custom"===e.substr(-7)&&(e=Mt.trim(e.substring(0,e.length-7)),t=""),t+"themes/"+encodeURI(e)+"/images/preview.png"},u.prototype.notificationMailIcon=function(){return this.sStaticPrefix+"css/images/icom-message-notification.png"},u.prototype.openPgpJs=function(){return this.sStaticPrefix+"js/openpgp.min.js"},u.prototype.socialGoogle=function(){return this.sServer+"SocialGoogle"+(""!==this.sSpecSuffix?"/"+this.sSpecSuffix+"/":"")},u.prototype.socialTwitter=function(){return this.sServer+"SocialTwitter"+(""!==this.sSpecSuffix?"/"+this.sSpecSuffix+"/":"")},u.prototype.socialFacebook=function(){return this.sServer+"SocialFacebook"+(""!==this.sSpecSuffix?"/"+this.sSpecSuffix+"/":"")},Dt.oViewModelsHooks={},Dt.oSimpleHooks={},Dt.regViewModelHook=function(e,t){t&&(t.__hookName=e)
-},Dt.addHook=function(e,t){Mt.isFunc(t)&&(Mt.isArray(Dt.oSimpleHooks[e])||(Dt.oSimpleHooks[e]=[]),Dt.oSimpleHooks[e].push(t))},Dt.runHook=function(e,t){Mt.isArray(Dt.oSimpleHooks[e])&&(t=t||[],r.each(Dt.oSimpleHooks[e],function(e){e.apply(null,t)}))},Dt.mainSettingsGet=function(e){return jt?jt.settingsGet(e):null},Dt.remoteRequest=function(e,t,s,i,o,n){jt&&jt.remote().defaultRequest(e,t,s,i,o,n)},Dt.settingsGet=function(e,t){var s=Dt.mainSettingsGet("Plugins");return s=s&&Mt.isUnd(s[e])?null:s[e],s?Mt.isUnd(s[t])?null:s[t]:null},d.prototype.blurTrigger=function(){if(this.fOnBlur){var t=this;e.clearTimeout(t.iBlurTimer),t.iBlurTimer=e.setTimeout(function(){t.fOnBlur()},200)}},d.prototype.focusTrigger=function(){this.fOnBlur&&e.clearTimeout(this.iBlurTimer)},d.prototype.isHtml=function(){return this.editor?"wysiwyg"===this.editor.mode:!1},d.prototype.checkDirty=function(){return this.editor?this.editor.checkDirty():!1},d.prototype.resetDirty=function(){this.editor&&this.editor.resetDirty()},d.prototype.getData=function(e){return this.editor?"plain"===this.editor.mode&&this.editor.plugins.plain&&this.editor.__plain?this.editor.__plain.getRawData():e?''+this.editor.getData()+"":this.editor.getData():""},d.prototype.modeToggle=function(e){this.editor&&(e?"plain"===this.editor.mode&&this.editor.setMode("wysiwyg"):"wysiwyg"===this.editor.mode&&this.editor.setMode("plain"),this.resize())},d.prototype.setHtml=function(e,t){this.editor&&(this.modeToggle(!0),this.editor.setData(e),t&&this.focus())},d.prototype.setPlain=function(e,t){if(this.editor){if(this.modeToggle(!1),"plain"===this.editor.mode&&this.editor.plugins.plain&&this.editor.__plain)return this.editor.__plain.setRawData(e);this.editor.setData(e),t&&this.focus()}},d.prototype.init=function(){if(this.$element&&this.$element[0]){var t=this,s=function(){var s=Ot.oHtmlEditorDefaultConfig,i=jt.settingsGet("Language"),o=!!jt.settingsGet("AllowHtmlEditorSourceButton");o&&s.toolbarGroups&&!s.toolbarGroups.__SourceInited&&(s.toolbarGroups.__SourceInited=!0,s.toolbarGroups.push({name:"document",groups:["mode","document","doctools"]})),s.enterMode=e.CKEDITOR.ENTER_BR,s.shiftEnterMode=e.CKEDITOR.ENTER_BR,s.language=Ot.oHtmlEditorLangsMap[i]||"en",e.CKEDITOR.env&&(e.CKEDITOR.env.isCompatible=!0),t.editor=e.CKEDITOR.appendTo(t.$element[0],s),t.editor.on("key",function(e){return e&&e.data&&9===e.data.keyCode?!1:void 0}),t.editor.on("blur",function(){t.blurTrigger()}),t.editor.on("mode",function(){t.blurTrigger(),t.fOnModeChange&&t.fOnModeChange("plain"!==t.editor.mode)}),t.editor.on("focus",function(){t.focusTrigger()}),t.fOnReady&&t.editor.on("instanceReady",function(){t.editor.setKeystroke(e.CKEDITOR.CTRL+65,"selectAll"),t.fOnReady(),t.__resizable=!0,t.resize()})};e.CKEDITOR?s():e.__initEditor=s}},d.prototype.focus=function(){this.editor&&this.editor.focus()},d.prototype.blur=function(){this.editor&&this.editor.focusManager.blur(!0)},d.prototype.resize=function(){if(this.editor&&this.__resizable)try{this.editor.resize(this.$element.width(),this.$element.innerHeight())}catch(e){}},d.prototype.clear=function(e){this.setHtml("",e)},h.prototype.itemSelected=function(e){this.isListChecked()?e||(this.oCallbacks.onItemSelect||this.emptyFunction)(e||null):e&&(this.oCallbacks.onItemSelect||this.emptyFunction)(e)},h.prototype.goDown=function(e){this.newSelectPosition(Lt.EventKeyCode.Down,!1,e)},h.prototype.goUp=function(e){this.newSelectPosition(Lt.EventKeyCode.Up,!1,e)},h.prototype.init=function(e,i,o){if(this.oContentVisible=e,this.oContentScrollable=i,o=o||"all",this.oContentVisible&&this.oContentScrollable){var n=this;t(this.oContentVisible).on("selectstart",function(e){e&&e.preventDefault&&e.preventDefault()}).on("click",this.sItemSelector,function(e){n.actionClick(s.dataFor(this),e)}).on("click",this.sItemCheckedSelector,function(e){var t=s.dataFor(this);t&&(e&&e.shiftKey?n.actionClick(t,e):(n.focusedItem(t),t.checked(!t.checked())))}),c("enter",o,function(){return n.focusedItem()&&!n.focusedItem().selected()?(n.actionClick(n.focusedItem()),!1):!0}),c("ctrl+up, command+up, ctrl+down, command+down",o,function(){return!1}),c("up, shift+up, down, shift+down, home, end, pageup, pagedown, insert, space",o,function(e,t){if(e&&t&&t.shortcut){var s=0;switch(t.shortcut){case"up":case"shift+up":s=Lt.EventKeyCode.Up;break;case"down":case"shift+down":s=Lt.EventKeyCode.Down;break;case"insert":s=Lt.EventKeyCode.Insert;break;case"space":s=Lt.EventKeyCode.Space;break;case"home":s=Lt.EventKeyCode.Home;break;case"end":s=Lt.EventKeyCode.End;break;case"pageup":s=Lt.EventKeyCode.PageUp;break;case"pagedown":s=Lt.EventKeyCode.PageDown}if(s>0)return n.newSelectPosition(s,c.shift),!1}})}},h.prototype.autoSelect=function(e){this.bAutoSelect=!!e},h.prototype.getItemUid=function(e){var t="",s=this.oCallbacks.onItemGetUid||null;return s&&e&&(t=s(e)),t.toString()},h.prototype.newSelectPosition=function(e,t,s){var i=0,o=10,n=!1,a=!1,l=null,c=this.list(),u=c?c.length:0,d=this.focusedItem();if(u>0)if(d){if(d)if(Lt.EventKeyCode.Down===e||Lt.EventKeyCode.Up===e||Lt.EventKeyCode.Insert===e||Lt.EventKeyCode.Space===e)r.each(c,function(t){if(!a)switch(e){case Lt.EventKeyCode.Up:d===t?a=!0:l=t;break;case Lt.EventKeyCode.Down:case Lt.EventKeyCode.Insert:n?(l=t,a=!0):d===t&&(n=!0)}});else if(Lt.EventKeyCode.Home===e||Lt.EventKeyCode.End===e)Lt.EventKeyCode.Home===e?l=c[0]:Lt.EventKeyCode.End===e&&(l=c[c.length-1]);else if(Lt.EventKeyCode.PageDown===e){for(;u>i;i++)if(d===c[i]){i+=o,i=i>u-1?u-1:i,l=c[i];break}}else if(Lt.EventKeyCode.PageUp===e)for(i=u;i>=0;i--)if(d===c[i]){i-=o,i=0>i?0:i,l=c[i];break}}else Lt.EventKeyCode.Down===e||Lt.EventKeyCode.Insert===e||Lt.EventKeyCode.Space===e||Lt.EventKeyCode.Home===e||Lt.EventKeyCode.PageUp===e?l=c[0]:(Lt.EventKeyCode.Up===e||Lt.EventKeyCode.End===e||Lt.EventKeyCode.PageDown===e)&&(l=c[c.length-1]);l?(this.focusedItem(l),d&&(t?(Lt.EventKeyCode.Up===e||Lt.EventKeyCode.Down===e)&&d.checked(!d.checked()):(Lt.EventKeyCode.Insert===e||Lt.EventKeyCode.Space===e)&&d.checked(!d.checked())),!this.bAutoSelect&&!s||this.isListChecked()||Lt.EventKeyCode.Space===e||this.selectedItem(l),this.scrollToFocused()):d&&(!t||Lt.EventKeyCode.Up!==e&&Lt.EventKeyCode.Down!==e?(Lt.EventKeyCode.Insert===e||Lt.EventKeyCode.Space===e)&&d.checked(!d.checked()):d.checked(!d.checked()),this.focusedItem(d))},h.prototype.scrollToFocused=function(){if(!this.oContentVisible||!this.oContentScrollable)return!1;var e=20,s=t(this.sItemFocusedSelector,this.oContentScrollable),i=s.position(),o=this.oContentVisible.height(),n=s.outerHeight();return i&&(i.top<0||i.top+n>o)?(this.oContentScrollable.scrollTop(i.top<0?this.oContentScrollable.scrollTop()+i.top-e:this.oContentScrollable.scrollTop()+i.top-o+n+e),!0):!1},h.prototype.scrollToTop=function(e){return this.oContentVisible&&this.oContentScrollable?(e?this.oContentScrollable.scrollTop(0):this.oContentScrollable.stop().animate({scrollTop:0},200),!0):!1},h.prototype.eventClickFunction=function(e,t){var s=this.getItemUid(e),i=0,o=0,n=null,a="",r=!1,l=!1,c=[],u=!1;if(t&&t.shiftKey&&""!==s&&""!==this.sLastUid&&s!==this.sLastUid)for(c=this.list(),u=e.checked(),i=0,o=c.length;o>i;i++)n=c[i],a=this.getItemUid(n),r=!1,(a===this.sLastUid||a===s)&&(r=!0),r&&(l=!l),(l||r)&&n.checked(u);this.sLastUid=""===s?"":s},h.prototype.actionClick=function(e,t){if(e){var s=!0,i=this.getItemUid(e);t&&(!t.shiftKey||t.ctrlKey||t.altKey?!t.ctrlKey||t.shiftKey||t.altKey||(s=!1,this.focusedItem(e),this.selectedItem()&&e!==this.selectedItem()&&this.selectedItem().checked(!0),e.checked(!e.checked())):(s=!1,""===this.sLastUid&&(this.sLastUid=i),e.checked(!e.checked()),this.eventClickFunction(e,t),this.focusedItem(e))),s&&(this.focusedItem(e),this.selectedItem(e),this.scrollToFocused())}},h.prototype.on=function(e,t){this.oCallbacks[e]=t},p.supported=function(){return!0},p.prototype.set=function(e,s){var i=t.cookie(It.Values.ClientSideCookieIndexName),o=!1,n=null;try{n=null===i?null:JSON.parse(i),n||(n={}),n[e]=s,t.cookie(It.Values.ClientSideCookieIndexName,JSON.stringify(n),{expires:30}),o=!0}catch(a){}return o},p.prototype.get=function(e){var s=t.cookie(It.Values.ClientSideCookieIndexName),i=null;try{i=null===s?null:JSON.parse(s),i=i&&!Mt.isUnd(i[e])?i[e]:null}catch(o){}return i},m.supported=function(){return!!e.localStorage},m.prototype.set=function(t,s){var i=e.localStorage[It.Values.ClientSideCookieIndexName]||null,o=!1,n=null;try{n=null===i?null:JSON.parse(i),n||(n={}),n[t]=s,e.localStorage[It.Values.ClientSideCookieIndexName]=JSON.stringify(n),o=!0}catch(a){}return o},m.prototype.get=function(t){var s=e.localStorage[It.Values.ClientSideCookieIndexName]||null,i=null;try{i=null===s?null:JSON.parse(s),i=i&&!Mt.isUnd(i[t])?i[t]:null}catch(o){}return i},g.prototype.oDriver=null,g.prototype.set=function(e,t){return this.oDriver?this.oDriver.set("p"+e,t):!1},g.prototype.get=function(e){return this.oDriver?this.oDriver.get("p"+e):null},f.prototype.bootstart=function(){},b.prototype.sPosition="",b.prototype.sTemplate="",b.prototype.viewModelName="",b.prototype.viewModelDom=null,b.prototype.viewModelTemplate=function(){return this.sTemplate},b.prototype.viewModelPosition=function(){return this.sPosition},b.prototype.cancelCommand=b.prototype.closeCommand=function(){},b.prototype.storeAndSetKeyScope=function(){this.sCurrentKeyScope=jt.data().keyScope(),jt.data().keyScope(this.sDefaultKeyScope)},b.prototype.restoreKeyScope=function(){jt.data().keyScope(this.sCurrentKeyScope)},b.prototype.registerPopupKeyDown=function(){var e=this;Gt.on("keydown",function(t){if(t&&e.modalVisibility&&e.modalVisibility()){if(!this.bDisabeCloseOnEsc&&Lt.EventKeyCode.Esc===t.keyCode)return Mt.delegateRun(e,"cancelCommand"),!1;if(Lt.EventKeyCode.Backspace===t.keyCode&&!Mt.inFocus())return!1}return!0})},y.prototype.oCross=null,y.prototype.sScreenName="",y.prototype.aViewModels=[],y.prototype.viewModels=function(){return this.aViewModels},y.prototype.screenName=function(){return this.sScreenName},y.prototype.routes=function(){return null},y.prototype.__cross=function(){return this.oCross},y.prototype.__start=function(){var e=this.routes(),t=null,s=null;Mt.isNonEmptyArray(e)&&(s=r.bind(this.onRoute||Mt.emptyFunction,this),t=i.create(),r.each(e,function(e){t.addRoute(e[0],s).rules=e[1]}),this.oCross=t)},S.constructorEnd=function(e){Mt.isFunc(e.__constructor_end)&&e.__constructor_end.call(e)},S.prototype.sDefaultScreenName="",S.prototype.oScreens={},S.prototype.oBoot=null,S.prototype.oCurrentScreen=null,S.prototype.hideLoading=function(){t("#rl-loading").hide()},S.prototype.routeOff=function(){o.changed.active=!1},S.prototype.routeOn=function(){o.changed.active=!0},S.prototype.setBoot=function(e){return Mt.isNormal(e)&&(this.oBoot=e),this},S.prototype.screen=function(e){return""===e||Mt.isUnd(this.oScreens[e])?null:this.oScreens[e]},S.prototype.buildViewModel=function(e,i){if(e&&!e.__builded){var o=new e(i),n=o.viewModelPosition(),a=t("#rl-content #rl-"+n.toLowerCase()),l=null;e.__builded=!0,e.__vm=o,o.data=jt.data(),o.viewModelName=e.__name,a&&1===a.length?(l=t("").addClass("rl-view-model").addClass("RL-"+o.viewModelTemplate()).hide(),l.appendTo(a),o.viewModelDom=l,e.__dom=l,"Popups"===n&&(o.cancelCommand=o.closeCommand=Mt.createCommand(o,function(){xt.hideScreenPopup(e)}),o.modalVisibility.subscribe(function(e){var t=this;e?(this.viewModelDom.show(),this.storeAndSetKeyScope(),jt.popupVisibilityNames.push(this.viewModelName),o.viewModelDom.css("z-index",3e3+jt.popupVisibilityNames().length+10),Mt.delegateRun(this,"onFocus",[],500)):(Mt.delegateRun(this,"onHide"),this.restoreKeyScope(),jt.popupVisibilityNames.remove(this.viewModelName),o.viewModelDom.css("z-index",2e3),Ot.tooltipTrigger(!Ot.tooltipTrigger()),r.delay(function(){t.viewModelDom.hide()},300))},o)),Dt.runHook("view-model-pre-build",[e.__name,o,l]),s.applyBindingAccessorsToNode(l[0],{i18nInit:!0,template:function(){return{name:o.viewModelTemplate()}}},o),Mt.delegateRun(o,"onBuild",[l]),o&&"Popups"===n&&o.registerPopupKeyDown(),Dt.runHook("view-model-post-build",[e.__name,o,l])):Mt.log("Cannot find view model position: "+n)}return e?e.__vm:null},S.prototype.applyExternal=function(e,t){e&&t&&s.applyBindings(e,t)},S.prototype.hideScreenPopup=function(e){e&&e.__vm&&e.__dom&&(e.__vm.modalVisibility(!1),Dt.runHook("view-model-on-hide",[e.__name,e.__vm]))},S.prototype.showScreenPopup=function(e,t){e&&(this.buildViewModel(e),e.__vm&&e.__dom&&(e.__vm.modalVisibility(!0),Mt.delegateRun(e.__vm,"onShow",t||[]),Dt.runHook("view-model-on-show",[e.__name,e.__vm,t||[]])))},S.prototype.isPopupVisible=function(e){return e&&e.__vm?e.__vm.modalVisibility():!1},S.prototype.screenOnRoute=function(e,t){var s=this,i=null,o=null;""===Mt.pString(e)&&(e=this.sDefaultScreenName),""!==e&&(i=this.screen(e),i||(i=this.screen(this.sDefaultScreenName),i&&(t=e+"/"+t,e=this.sDefaultScreenName)),i&&i.__started&&(i.__builded||(i.__builded=!0,Mt.isNonEmptyArray(i.viewModels())&&r.each(i.viewModels(),function(e){this.buildViewModel(e,i)},this),Mt.delegateRun(i,"onBuild")),r.defer(function(){s.oCurrentScreen&&(Mt.delegateRun(s.oCurrentScreen,"onHide"),Mt.isNonEmptyArray(s.oCurrentScreen.viewModels())&&r.each(s.oCurrentScreen.viewModels(),function(e){e.__vm&&e.__dom&&"Popups"!==e.__vm.viewModelPosition()&&(e.__dom.hide(),e.__vm.viewModelVisibility(!1),Mt.delegateRun(e.__vm,"onHide"))})),s.oCurrentScreen=i,s.oCurrentScreen&&(Mt.delegateRun(s.oCurrentScreen,"onShow"),Dt.runHook("screen-on-show",[s.oCurrentScreen.screenName(),s.oCurrentScreen]),Mt.isNonEmptyArray(s.oCurrentScreen.viewModels())&&r.each(s.oCurrentScreen.viewModels(),function(e){e.__vm&&e.__dom&&"Popups"!==e.__vm.viewModelPosition()&&(e.__dom.show(),e.__vm.viewModelVisibility(!0),Mt.delegateRun(e.__vm,"onShow"),Mt.delegateRun(e.__vm,"onFocus",[],200),Dt.runHook("view-model-on-show",[e.__name,e.__vm]))},s)),o=i.__cross(),o&&o.parse(t)})))},S.prototype.startScreens=function(e){t("#rl-content").css({visibility:"hidden"}),r.each(e,function(e){var t=new e,s=t?t.screenName():"";t&&""!==s&&(""===this.sDefaultScreenName&&(this.sDefaultScreenName=s),this.oScreens[s]=t)},this),r.each(this.oScreens,function(e){e&&!e.__started&&e.__start&&(e.__started=!0,e.__start(),Dt.runHook("screen-pre-start",[e.screenName(),e]),Mt.delegateRun(e,"onStart"),Dt.runHook("screen-post-start",[e.screenName(),e]))},this);var s=i.create();s.addRoute(/^([a-zA-Z0-9\-]*)\/?(.*)$/,r.bind(this.screenOnRoute,this)),o.initialized.add(s.parse,s),o.changed.add(s.parse,s),o.init(),t("#rl-content").css({visibility:"visible"}),r.delay(function(){Bt.removeClass("rl-started-trigger").addClass("rl-started")},50)},S.prototype.setHash=function(e,t,s){e="#"===e.substr(0,1)?e.substr(1):e,e="/"===e.substr(0,1)?e.substr(1):e,s=Mt.isUnd(s)?!1:!!s,(Mt.isUnd(t)?1:!t)?(o.changed.active=!0,o[s?"replaceHash":"setHash"](e),o.setHash(e)):(o.changed.active=!1,o[s?"replaceHash":"setHash"](e),o.changed.active=!0)},S.prototype.bootstart=function(){return this.oBoot&&this.oBoot.bootstart&&this.oBoot.bootstart(),this},xt=new S,v.newInstanceFromJson=function(e){var t=new v;return t.initByJson(e)?t:null},v.prototype.name="",v.prototype.email="",v.prototype.privateType=null,v.prototype.clear=function(){this.email="",this.name="",this.privateType=null},v.prototype.validate=function(){return""!==this.name||""!==this.email},v.prototype.hash=function(e){return"#"+(e?"":this.name)+"#"+this.email+"#"},v.prototype.clearDuplicateName=function(){this.name===this.email&&(this.name="")},v.prototype.type=function(){return null===this.privateType&&(this.email&&"@facebook.com"===this.email.substr(-13)&&(this.privateType=Lt.EmailType.Facebook),null===this.privateType&&(this.privateType=Lt.EmailType.Default)),this.privateType},v.prototype.search=function(e){return-1<(this.name+" "+this.email).toLowerCase().indexOf(e.toLowerCase())},v.prototype.parse=function(e){this.clear(),e=Mt.trim(e);var t=/(?:"([^"]+)")? ?(.*?@[^>,]+)>?,? ?/g,s=t.exec(e);s?(this.name=s[1]||"",this.email=s[2]||"",this.clearDuplicateName()):/^[^@]+@[^@]+$/.test(e)&&(this.name="",this.email=e)},v.prototype.initByJson=function(e){var t=!1;return e&&"Object/Email"===e["@Object"]&&(this.name=Mt.trim(e.Name),this.email=Mt.trim(e.Email),t=""!==this.email,this.clearDuplicateName()),t},v.prototype.toLine=function(e,t,s){var i="";return""!==this.email&&(t=Mt.isUnd(t)?!1:!!t,s=Mt.isUnd(s)?!1:!!s,e&&""!==this.name?i=t?'")+'" target="_blank" tabindex="-1">'+Mt.encodeHtml(this.name)+"":s?Mt.encodeHtml(this.name):this.name:(i=this.email,""!==this.name?t?i=Mt.encodeHtml('"'+this.name+'" <')+'")+'" target="_blank" tabindex="-1">'+Mt.encodeHtml(i)+""+Mt.encodeHtml(">"):(i='"'+this.name+'" <'+i+">",s&&(i=Mt.encodeHtml(i))):t&&(i=''+Mt.encodeHtml(this.email)+""))),i},v.prototype.mailsoParse=function(e){if(e=Mt.trim(e),""===e)return!1;for(var t=function(e,t,s){e+="";var i=e.length;return 0>t&&(t+=i),i="undefined"==typeof s?i:0>s?s+i:s+t,t>=e.length||0>t||t>i?!1:e.slice(t,i)},s=function(e,t,s,i){return 0>s&&(s+=e.length),i=void 0!==i?i:e.length,0>i&&(i=i+e.length-s),e.slice(0,s)+t.substr(0,i)+t.slice(i)+e.slice(s+i)},i="",o="",n="",a=!1,r=!1,l=!1,c=null,u=0,d=0,h=0;h0&&0===i.length&&(i=t(e,0,h)),r=!0,u=h);break;case">":r&&(d=h,o=t(e,u+1,d-u-1),e=s(e,"",u,d-u+1),d=0,h=0,u=0,r=!1);break;case"(":a||r||l||(l=!0,u=h);break;case")":l&&(d=h,n=t(e,u+1,d-u-1),e=s(e,"",u,d-u+1),d=0,h=0,u=0,l=!1);break;case"\\":h++}h++}return 0===o.length&&(c=e.match(/[^@\s]+@\S+/i),c&&c[0]?o=c[0]:i=e),o.length>0&&0===i.length&&0===n.length&&(i=e.replace(o,"")),o=Mt.trim(o).replace(/^[<]+/,"").replace(/[>]+$/,""),i=Mt.trim(i).replace(/^["']+/,"").replace(/["']+$/,""),n=Mt.trim(n).replace(/^[(]+/,"").replace(/[)]+$/,""),i=i.replace(/\\\\(.)/,"$1"),n=n.replace(/\\\\(.)/,"$1"),this.name=i,this.email=o,this.clearDuplicateName(),!0},v.prototype.inputoTagLine=function(){return 0 +$/,""),t=!0),t},F.prototype.isImage=function(){return-10?n.unix(e).format("LLL"):""},E.emailsToLine=function(e,t,s){var i=[],o=0,n=0;if(Mt.isNonEmptyArray(e))for(o=0,n=e.length;n>o;o++)i.push(e[o].toLine(t,s));return i.join(", ")},E.emailsToLineClear=function(e){var t=[],s=0,i=0;if(Mt.isNonEmptyArray(e))for(s=0,i=e.length;i>s;s++)e[s]&&e[s].email&&""!==e[s].name&&t.push(e[s].email);return t.join(", ")},E.initEmailsFromJson=function(e){var t=0,s=0,i=null,o=[];if(Mt.isNonEmptyArray(e))for(t=0,s=e.length;s>t;t++)i=v.newInstanceFromJson(e[t]),i&&o.push(i);return o},E.replyHelper=function(e,t,s){if(e&&0i;i++)Mt.isUnd(t[e[i].email])&&(t[e[i].email]=!0,s.push(e[i]))},E.prototype.clear=function(){this.folderFullNameRaw="",this.uid="",this.hash="",this.requestHash="",this.subject(""),this.subjectPrefix(""),this.subjectSuffix(""),this.size(0),this.dateTimeStampInUTC(0),this.priority(Lt.MessagePriority.Normal),this.proxy=!1,this.fromEmailString(""),this.fromClearEmailString(""),this.toEmailsString(""),this.toClearEmailsString(""),this.senderEmailsString(""),this.senderClearEmailsString(""),this.emails=[],this.from=[],this.to=[],this.cc=[],this.bcc=[],this.replyTo=[],this.deliveredTo=[],this.newForAnimation(!1),this.deleted(!1),this.unseen(!1),this.flagged(!1),this.answered(!1),this.forwarded(!1),this.isReadReceipt(!1),this.selected(!1),this.checked(!1),this.hasAttachments(!1),this.attachmentsMainType(""),this.body=null,this.isHtml(!1),this.hasImages(!1),this.attachments([]),this.isPgpSigned(!1),this.isPgpEncrypted(!1),this.pgpSignedVerifyStatus(Lt.SignedVerifyStatus.None),this.pgpSignedVerifyUser(""),this.priority(Lt.MessagePriority.Normal),this.readReceipt(""),this.aDraftInfo=[],this.sMessageId="",this.sInReplyTo="",this.sReferences="",this.parentUid(0),this.threads([]),this.threadsLen(0),this.hasUnseenSubMessage(!1),this.hasFlaggedSubMessage(!1),this.lastInCollapsedThread(!1),this.lastInCollapsedThreadLoading(!1)},E.prototype.computeSenderEmail=function(){var e=jt.data().sentFolder(),t=jt.data().draftFolder();this.senderEmailsString(this.folderFullNameRaw===e||this.folderFullNameRaw===t?this.toEmailsString():this.fromEmailString()),this.senderClearEmailsString(this.folderFullNameRaw===e||this.folderFullNameRaw===t?this.toClearEmailsString():this.fromClearEmailString())},E.prototype.initByJson=function(e){var t=!1;return e&&"Object/Message"===e["@Object"]&&(this.folderFullNameRaw=e.Folder,this.uid=e.Uid,this.hash=e.Hash,this.requestHash=e.RequestHash,this.proxy=!!e.ExternalProxy,this.size(Mt.pInt(e.Size)),this.from=E.initEmailsFromJson(e.From),this.to=E.initEmailsFromJson(e.To),this.cc=E.initEmailsFromJson(e.Cc),this.bcc=E.initEmailsFromJson(e.Bcc),this.replyTo=E.initEmailsFromJson(e.ReplyTo),this.deliveredTo=E.initEmailsFromJson(e.DeliveredTo),this.subject(e.Subject),Mt.isArray(e.SubjectParts)?(this.subjectPrefix(e.SubjectParts[0]),this.subjectSuffix(e.SubjectParts[1])):(this.subjectPrefix(""),this.subjectSuffix(this.subject())),this.dateTimeStampInUTC(Mt.pInt(e.DateTimeStampInUTC)),this.hasAttachments(!!e.HasAttachments),this.attachmentsMainType(e.AttachmentsMainType),this.fromEmailString(E.emailsToLine(this.from,!0)),this.fromClearEmailString(E.emailsToLineClear(this.from)),this.toEmailsString(E.emailsToLine(this.to,!0)),this.toClearEmailsString(E.emailsToLineClear(this.to)),this.parentUid(Mt.pInt(e.ParentThread)),this.threads(Mt.isArray(e.Threads)?e.Threads:[]),this.threadsLen(Mt.pInt(e.ThreadsLen)),this.initFlagsByJson(e),this.computeSenderEmail(),t=!0),t},E.prototype.initUpdateByMessageJson=function(e){var t=!1,s=Lt.MessagePriority.Normal;return e&&"Object/Message"===e["@Object"]&&(s=Mt.pInt(e.Priority),this.priority(-1t;t++)i=F.newInstanceFromJson(e["@Collection"][t]),i&&(""!==i.cidWithOutTags&&0 +$/,""),t=r.find(s,function(t){return e===t.cidWithOutTags})),t||null},E.prototype.findAttachmentByContentLocation=function(e){var t=null,s=this.attachments();return Mt.isNonEmptyArray(s)&&(t=r.find(s,function(t){return e===t.contentLocation})),t||null},E.prototype.messageId=function(){return this.sMessageId},E.prototype.inReplyTo=function(){return this.sInReplyTo},E.prototype.references=function(){return this.sReferences},E.prototype.fromAsSingleEmail=function(){return Mt.isArray(this.from)&&this.from[0]?this.from[0].email:""},E.prototype.viewLink=function(){return jt.link().messageViewLink(this.requestHash)},E.prototype.downloadLink=function(){return jt.link().messageDownloadLink(this.requestHash)},E.prototype.replyEmails=function(e){var t=[],s=Mt.isUnd(e)?{}:e;return E.replyHelper(this.replyTo,s,t),0===t.length&&E.replyHelper(this.from,s,t),t},E.prototype.replyAllEmails=function(e){var t=[],s=[],i=Mt.isUnd(e)?{}:e;return E.replyHelper(this.replyTo,i,t),0===t.length&&E.replyHelper(this.from,i,t),E.replyHelper(this.to,i,t),E.replyHelper(this.cc,i,s),[t,s]},E.prototype.textBodyToString=function(){return this.body?this.body.html():""},E.prototype.attachmentsToStringLine=function(){var e=r.map(this.attachments(),function(e){return e.fileName+" ("+e.friendlySize+")"});return e&&0=0&&o&&!n&&i.attr("src",o)}),s&&e.setTimeout(function(){i.print()},100))})},E.prototype.printMessage=function(){this.viewPopupMessage(!0)},E.prototype.generateUid=function(){return this.folderFullNameRaw+"/"+this.uid},E.prototype.populateByMessageListItem=function(e){return this.folderFullNameRaw=e.folderFullNameRaw,this.uid=e.uid,this.hash=e.hash,this.requestHash=e.requestHash,this.subject(e.subject()),this.subjectPrefix(this.subjectPrefix()),this.subjectSuffix(this.subjectSuffix()),this.size(e.size()),this.dateTimeStampInUTC(e.dateTimeStampInUTC()),this.priority(e.priority()),this.proxy=e.proxy,this.fromEmailString(e.fromEmailString()),this.fromClearEmailString(e.fromClearEmailString()),this.toEmailsString(e.toEmailsString()),this.toClearEmailsString(e.toClearEmailsString()),this.emails=e.emails,this.from=e.from,this.to=e.to,this.cc=e.cc,this.bcc=e.bcc,this.replyTo=e.replyTo,this.deliveredTo=e.deliveredTo,this.unseen(e.unseen()),this.flagged(e.flagged()),this.answered(e.answered()),this.forwarded(e.forwarded()),this.isReadReceipt(e.isReadReceipt()),this.selected(e.selected()),this.checked(e.checked()),this.hasAttachments(e.hasAttachments()),this.attachmentsMainType(e.attachmentsMainType()),this.moment(e.moment()),this.body=null,this.priority(Lt.MessagePriority.Normal),this.aDraftInfo=[],this.sMessageId="",this.sInReplyTo="",this.sReferences="",this.parentUid(e.parentUid()),this.threads(e.threads()),this.threadsLen(e.threadsLen()),this.computeSenderEmail(),this},E.prototype.showExternalImages=function(e){if(this.body&&this.body.data("rl-has-images")){var s="";e=Mt.isUnd(e)?!1:e,this.hasImages(!1),this.body.data("rl-has-images",!1),s=this.proxy?"data-x-additional-src":"data-x-src",t("["+s+"]",this.body).each(function(){e&&t(this).is("img")?t(this).addClass("lazy").attr("data-original",t(this).attr(s)).removeAttr(s):t(this).attr("src",t(this).attr(s)).removeAttr(s)}),s=this.proxy?"data-x-additional-style-url":"data-x-style-url",t("["+s+"]",this.body).each(function(){var e=Mt.trim(t(this).attr("style"));e=""===e?"":";"===e.substr(-1)?e+" ":e+"; ",t(this).attr("style",e+t(this).attr(s)).removeAttr(s)}),e&&(t("img.lazy",this.body).addClass("lazy-inited").lazyload({threshold:400,effect:"fadeIn",skip_invisible:!1,container:t(".RL-MailMessageView .messageView .messageItem .content")[0]}),Gt.resize()),Mt.windowResize(500)}},E.prototype.showInternalImages=function(e){if(this.body&&!this.body.data("rl-init-internal-images")){this.body.data("rl-init-internal-images",!0),e=Mt.isUnd(e)?!1:e;var s=this;t("[data-x-src-cid]",this.body).each(function(){var i=s.findAttachmentByCid(t(this).attr("data-x-src-cid"));i&&i.download&&(e&&t(this).is("img")?t(this).addClass("lazy").attr("data-original",i.linkPreview()):t(this).attr("src",i.linkPreview()))}),t("[data-x-src-location]",this.body).each(function(){var i=s.findAttachmentByContentLocation(t(this).attr("data-x-src-location"));i||(i=s.findAttachmentByCid(t(this).attr("data-x-src-location"))),i&&i.download&&(e&&t(this).is("img")?t(this).addClass("lazy").attr("data-original",i.linkPreview()):t(this).attr("src",i.linkPreview()))}),t("[data-x-style-cid]",this.body).each(function(){var e="",i="",o=s.findAttachmentByCid(t(this).attr("data-x-style-cid"));o&&o.linkPreview&&(i=t(this).attr("data-x-style-cid-name"),""!==i&&(e=Mt.trim(t(this).attr("style")),e=""===e?"":";"===e.substr(-1)?e+" ":e+"; ",t(this).attr("style",e+i+": url('"+o.linkPreview()+"')")))}),e&&!function(e,t){r.delay(function(){e.addClass("lazy-inited").lazyload({threshold:400,effect:"fadeIn",skip_invisible:!1,container:t})},300)}(t("img.lazy",s.body),t(".RL-MailMessageView .messageView .messageItem .content")[0]),Mt.windowResize(500)}},E.prototype.storeDataToDom=function(){this.body&&(this.body.data("rl-is-html",!!this.isHtml()),this.body.data("rl-has-images",!!this.hasImages()),this.body.data("rl-plain-raw",this.plainRaw),jt.data().capaOpenPGP()&&(this.body.data("rl-plain-pgp-signed",!!this.isPgpSigned()),this.body.data("rl-plain-pgp-encrypted",!!this.isPgpEncrypted()),this.body.data("rl-pgp-verify-status",this.pgpSignedVerifyStatus()),this.body.data("rl-pgp-verify-user",this.pgpSignedVerifyUser())))},E.prototype.storePgpVerifyDataToDom=function(){this.body&&jt.data().capaOpenPGP()&&(this.body.data("rl-pgp-verify-status",this.pgpSignedVerifyStatus()),this.body.data("rl-pgp-verify-user",this.pgpSignedVerifyUser()))},E.prototype.fetchDataToDom=function(){this.body&&(this.isHtml(!!this.body.data("rl-is-html")),this.hasImages(!!this.body.data("rl-has-images")),this.plainRaw=Mt.pString(this.body.data("rl-plain-raw")),jt.data().capaOpenPGP()?(this.isPgpSigned(!!this.body.data("rl-plain-pgp-signed")),this.isPgpEncrypted(!!this.body.data("rl-plain-pgp-encrypted")),this.pgpSignedVerifyStatus(this.body.data("rl-pgp-verify-status")),this.pgpSignedVerifyUser(this.body.data("rl-pgp-verify-user"))):(this.isPgpSigned(!1),this.isPgpEncrypted(!1),this.pgpSignedVerifyStatus(Lt.SignedVerifyStatus.None),this.pgpSignedVerifyUser("")))},E.prototype.verifyPgpSignedClearMessage=function(){if(this.isPgpSigned()){var s=[],i=null,o=this.from&&this.from[0]&&this.from[0].email?this.from[0].email:"",n=jt.data().findPublicKeysByEmail(o),a=null,l=null,c="";this.pgpSignedVerifyStatus(Lt.SignedVerifyStatus.Error),this.pgpSignedVerifyUser("");try{i=e.openpgp.cleartext.readArmored(this.plainRaw),i&&i.getText&&(this.pgpSignedVerifyStatus(n.length?Lt.SignedVerifyStatus.Unverified:Lt.SignedVerifyStatus.UnknownPublicKeys),s=i.verify(n),s&&0').text(c)).html(),zt.empty(),this.replacePlaneTextBody(c)))))}catch(u){}this.storePgpVerifyDataToDom()}},E.prototype.decryptPgpEncryptedMessage=function(s){if(this.isPgpEncrypted()){var i=[],o=null,n=null,a=this.from&&this.from[0]&&this.from[0].email?this.from[0].email:"",l=jt.data().findPublicKeysByEmail(a),c=jt.data().findSelfPrivateKey(s),u=null,d=null,h="";this.pgpSignedVerifyStatus(Lt.SignedVerifyStatus.Error),this.pgpSignedVerifyUser(""),c||this.pgpSignedVerifyStatus(Lt.SignedVerifyStatus.UnknownPrivateKey);try{o=e.openpgp.message.readArmored(this.plainRaw),o&&c&&o.decrypt&&(this.pgpSignedVerifyStatus(Lt.SignedVerifyStatus.Unverified),n=o.decrypt(c),n&&(i=n.verify(l),i&&0').text(h)).html(),zt.empty(),this.replacePlaneTextBody(h)))}catch(p){}this.storePgpVerifyDataToDom()}},E.prototype.replacePlaneTextBody=function(e){this.body&&this.body.html(e).addClass("b-text-part plain")},E.prototype.flagHash=function(){return[this.deleted(),this.unseen(),this.flagged(),this.answered(),this.forwarded(),this.isReadReceipt()].join("")},N.newInstanceFromJson=function(e){var t=new N;return t.initByJson(e)?t.initComputed():null},N.prototype.initComputed=function(){return this.hasSubScribedSubfolders=s.computed(function(){return!!r.find(this.subFolders(),function(e){return e.subScribed()&&!e.isSystemFolder()})},this),this.canBeEdited=s.computed(function(){return Lt.FolderType.User===this.type()&&this.existen&&this.selectable},this),this.visible=s.computed(function(){var e=this.subScribed(),t=this.hasSubScribedSubfolders();return e||t&&(!this.existen||!this.selectable)},this),this.isSystemFolder=s.computed(function(){return Lt.FolderType.User!==this.type()},this),this.hidden=s.computed(function(){var e=this.isSystemFolder(),t=this.hasSubScribedSubfolders();return e&&!t||!this.selectable&&!t},this),this.selectableForFolderList=s.computed(function(){return!this.isSystemFolder()&&this.selectable},this),this.messageCountAll=s.computed({read:this.privateMessageCountAll,write:function(e){Mt.isPosNumeric(e,!0)?this.privateMessageCountAll(e):this.privateMessageCountAll.valueHasMutated()},owner:this}),this.messageCountUnread=s.computed({read:this.privateMessageCountUnread,write:function(e){Mt.isPosNumeric(e,!0)?this.privateMessageCountUnread(e):this.privateMessageCountUnread.valueHasMutated()},owner:this}),this.printableUnreadCount=s.computed(function(){var e=this.messageCountAll(),t=this.messageCountUnread(),s=this.type();if(Lt.FolderType.Inbox===s&&jt.data().foldersInboxUnreadCount(t),e>0){if(Lt.FolderType.Draft===s)return""+e;if(t>0&&Lt.FolderType.Trash!==s&&Lt.FolderType.Archive!==s&&Lt.FolderType.SentItems!==s)return""+t}return""},this),this.canBeDeleted=s.computed(function(){var e=this.isSystemFolder();return!e&&0===this.subFolders().length&&"INBOX"!==this.fullNameRaw},this),this.canBeSubScribed=s.computed(function(){return!this.isSystemFolder()&&this.selectable&&"INBOX"!==this.fullNameRaw},this),this.visible.subscribe(function(){Mt.timeOutAction("folder-list-folder-visibility-change",function(){Gt.trigger("folder-list-folder-visibility-change")},100)}),this.localName=s.computed(function(){Ot.langChangeTrigger();var e=this.type(),t=this.name();if(this.isSystemFolder())switch(e){case Lt.FolderType.Inbox:t=Mt.i18n("FOLDER_LIST/INBOX_NAME");break;case Lt.FolderType.SentItems:t=Mt.i18n("FOLDER_LIST/SENT_NAME");break;case Lt.FolderType.Draft:t=Mt.i18n("FOLDER_LIST/DRAFTS_NAME");break;case Lt.FolderType.Spam:t=Mt.i18n("FOLDER_LIST/SPAM_NAME");break;case Lt.FolderType.Trash:t=Mt.i18n("FOLDER_LIST/TRASH_NAME");break;case Lt.FolderType.Archive:t=Mt.i18n("FOLDER_LIST/ARCHIVE_NAME")}return t},this),this.manageFolderSystemName=s.computed(function(){Ot.langChangeTrigger();var e="",t=this.type(),s=this.name();if(this.isSystemFolder())switch(t){case Lt.FolderType.Inbox:e="("+Mt.i18n("FOLDER_LIST/INBOX_NAME")+")";break;case Lt.FolderType.SentItems:e="("+Mt.i18n("FOLDER_LIST/SENT_NAME")+")";break;case Lt.FolderType.Draft:e="("+Mt.i18n("FOLDER_LIST/DRAFTS_NAME")+")";break;case Lt.FolderType.Spam:e="("+Mt.i18n("FOLDER_LIST/SPAM_NAME")+")";break;case Lt.FolderType.Trash:e="("+Mt.i18n("FOLDER_LIST/TRASH_NAME")+")";break;case Lt.FolderType.Archive:e="("+Mt.i18n("FOLDER_LIST/ARCHIVE_NAME")+")"}return(""!==e&&"("+s+")"===e||"(inbox)"===e.toLowerCase())&&(e=""),e},this),this.collapsed=s.computed({read:function(){return!this.hidden()&&this.collapsedPrivate()},write:function(e){this.collapsedPrivate(e)},owner:this}),this.hasUnreadMessages=s.computed(function(){return 0"},I.prototype.formattedNameForCompose=function(){var e=this.name();return""===e?this.email():e+" ("+this.email()+")"},I.prototype.formattedNameForEmail=function(){var e=this.name();return""===e?this.email():'"'+Mt.quoteName(e)+'" <'+this.email()+">"},L.prototype.removeSelf=function(){this.parentList.remove(this)},P.prototype.addCondition=function(){this.conditions.push(new L(this.conditions))},P.prototype.parse=function(e){var t=!1;return e&&"Object/Filter"===e["@Object"]&&(this.name(Mt.pString(e.Name)),t=!0),t},M.prototype.index=0,M.prototype.id="",M.prototype.guid="",M.prototype.user="",M.prototype.email="",M.prototype.armor="",M.prototype.isPrivate=!1,Mt.extendAsViewModel("PopupsFolderClearViewModel",D),D.prototype.clearPopup=function(){this.clearingProcess(!1),this.selectedFolder(null)},D.prototype.onShow=function(e){this.clearPopup(),e&&this.selectedFolder(e)},Mt.extendAsViewModel("PopupsFolderCreateViewModel",k),k.prototype.sNoParentText="",k.prototype.simpleFolderNameValidation=function(e){return/^[^\\\/]+$/g.test(Mt.trim(e))},k.prototype.clearPopup=function(){this.folderName(""),this.selectedParentValue(""),this.folderName.focused(!1)},k.prototype.onShow=function(){this.clearPopup()},k.prototype.onFocus=function(){this.folderName.focused(!0)},Mt.extendAsViewModel("PopupsFolderSystemViewModel",O),O.prototype.sChooseOnText="",O.prototype.sUnuseText="",O.prototype.onShow=function(e){var t="";switch(e=Mt.isUnd(e)?Lt.SetSystemFoldersNotification.None:e){case Lt.SetSystemFoldersNotification.Sent:t=Mt.i18n("POPUPS_SYSTEM_FOLDERS/NOTIFICATION_SENT");break;case Lt.SetSystemFoldersNotification.Draft:t=Mt.i18n("POPUPS_SYSTEM_FOLDERS/NOTIFICATION_DRAFTS");break;case Lt.SetSystemFoldersNotification.Spam:t=Mt.i18n("POPUPS_SYSTEM_FOLDERS/NOTIFICATION_SPAM");break;case Lt.SetSystemFoldersNotification.Trash:t=Mt.i18n("POPUPS_SYSTEM_FOLDERS/NOTIFICATION_TRASH");break;case Lt.SetSystemFoldersNotification.Archive:t=Mt.i18n("POPUPS_SYSTEM_FOLDERS/NOTIFICATION_ARCHIVE")}this.notification(t)},Mt.extendAsViewModel("PopupsComposeViewModel",_),_.prototype.openOpenPgpPopup=function(){if(this.capaOpenPGP()&&this.oEditor&&!this.oEditor.isHtml()){var e=this;xt.showScreenPopup(K,[function(t){e.editor(function(e){e.setPlain(t)})},this.oEditor.getData(),this.currentIdentityResultEmail(),this.to(),this.cc(),this.bcc()])}},_.prototype.reloadDraftFolder=function(){var e=jt.data().draftFolder();""!==e&&(jt.cache().setFolderHash(e,""),jt.data().currentFolderFullNameRaw()===e?jt.reloadMessageList(!0):jt.folderInformation(e))},_.prototype.findIdentityIdByMessage=function(e,t){var s={},i="",o=function(e){return e&&e.email&&s[e.email]?(i=s[e.email],!0):!1};if(this.bCapaAdditionalIdentities&&r.each(this.identities(),function(e){s[e.email()]=e.id}),s[jt.data().accountEmail()]=jt.data().accountEmail(),t)switch(e){case Lt.ComposeType.Empty:break;case Lt.ComposeType.Reply:case Lt.ComposeType.ReplyAll:case Lt.ComposeType.Forward:case Lt.ComposeType.ForwardAsAttachment:r.find(r.union(t.to,t.cc,t.bcc,t.deliveredTo),o);break;case Lt.ComposeType.Draft:r.find(r.union(t.from,t.replyTo),o)}return""===i&&(i=this.defaultIdentityID()),""===i&&(i=jt.data().accountEmail()),i},_.prototype.selectIdentity=function(e){e&&this.currentIdentityID(e.optValue)},_.prototype.formattedFrom=function(e){var t=jt.data().displayName(),s=jt.data().accountEmail();return""===t?s:(Mt.isUnd(e)?1:!e)?t+" ("+s+")":'"'+Mt.quoteName(t)+'" <'+s+">"},_.prototype.sendMessageResponse=function(t,s){var i=!1,o="";this.sending(!1),Lt.StorageResultType.Success===t&&s&&s.Result&&(i=!0,this.modalVisibility()&&Mt.delegateRun(this,"closeCommand")),this.modalVisibility()&&!i&&(s&&Lt.Notification.CantSaveMessage===s.ErrorCode?(this.sendSuccessButSaveError(!0),e.alert(Mt.trim(Mt.i18n("COMPOSE/SAVED_ERROR_ON_SEND")))):(o=Mt.getNotification(s&&s.ErrorCode?s.ErrorCode:Lt.Notification.CantSendMessage,s&&s.ErrorMessage?s.ErrorMessage:""),this.sendError(!0),e.alert(o||Mt.getNotification(Lt.Notification.CantSendMessage)))),this.reloadDraftFolder()},_.prototype.saveMessageResponse=function(t,s){var i=!1,o=null;this.saving(!1),Lt.StorageResultType.Success===t&&s&&s.Result&&s.Result.NewFolder&&s.Result.NewUid&&(this.bFromDraft&&(o=jt.data().message(),o&&this.draftFolder()===o.folderFullNameRaw&&this.draftUid()===o.uid&&jt.data().message(null)),this.draftFolder(s.Result.NewFolder),this.draftUid(s.Result.NewUid),this.modalVisibility()&&(this.savedTime(Math.round((new e.Date).getTime()/1e3)),this.savedOrSendingText(0 "+e;break;default:e=e+"
"+s}return e},_.prototype.editor=function(e){if(e){var t=this;!this.oEditor&&this.composeEditorArea()?r.delay(function(){t.oEditor=new d(t.composeEditorArea(),null,function(){e(t.oEditor)},function(e){t.isHtml(!!e)})},300):this.oEditor&&e(this.oEditor)}},_.prototype.onShow=function(e,s,i,o,n){xt.routeOff();var a=this,l="",c="",u="",d="",h="",p=null,m=null,g="",f="",b=[],y={},S=jt.data().accountEmail(),v=jt.data().signature(),C=jt.data().signatureToAll(),w=[],T=null,F=null,A=e||Lt.ComposeType.Empty,E=function(e,t){for(var s=0,i=e.length,o=[];i>s;s++)o.push(e[s].toLine(!!t));return o.join(", ")};if(s=s||null,s&&Mt.isNormal(s)&&(F=Mt.isArray(s)&&1===s.length?s[0]:Mt.isArray(s)?null:s),null!==S&&(y[S]=!0),this.currentIdentityID(this.findIdentityIdByMessage(A,F)),this.reset(),Mt.isNonEmptyArray(i)&&this.to(E(i)),""!==A&&F){switch(d=F.fullFormatDateValue(),h=F.subject(),T=F.aDraftInfo,p=t(F.body).clone(),Mt.removeBlockquoteSwitcher(p),m=p.find("[data-html-editor-font-wrapper=true]"),g=m&&m[0]?m.html():p.html(),A){case Lt.ComposeType.Empty:break;case Lt.ComposeType.Reply:this.to(E(F.replyEmails(y))),this.subject(Mt.replySubjectAdd("Re",h)),this.prepearMessageAttachments(F,A),this.aDraftInfo=["reply",F.uid,F.folderFullNameRaw],this.sInReplyTo=F.sMessageId,this.sReferences=Mt.trim(this.sInReplyTo+" "+F.sReferences);break;case Lt.ComposeType.ReplyAll:b=F.replyAllEmails(y),this.to(E(b[0])),this.cc(E(b[1])),this.subject(Mt.replySubjectAdd("Re",h)),this.prepearMessageAttachments(F,A),this.aDraftInfo=["reply",F.uid,F.folderFullNameRaw],this.sInReplyTo=F.sMessageId,this.sReferences=Mt.trim(this.sInReplyTo+" "+F.references());break;case Lt.ComposeType.Forward:this.subject(Mt.replySubjectAdd("Fwd",h)),this.prepearMessageAttachments(F,A),this.aDraftInfo=["forward",F.uid,F.folderFullNameRaw],this.sInReplyTo=F.sMessageId,this.sReferences=Mt.trim(this.sInReplyTo+" "+F.sReferences);break;case Lt.ComposeType.ForwardAsAttachment:this.subject(Mt.replySubjectAdd("Fwd",h)),this.prepearMessageAttachments(F,A),this.aDraftInfo=["forward",F.uid,F.folderFullNameRaw],this.sInReplyTo=F.sMessageId,this.sReferences=Mt.trim(this.sInReplyTo+" "+F.sReferences);break;case Lt.ComposeType.Draft:this.to(E(F.to)),this.cc(E(F.cc)),this.bcc(E(F.bcc)),this.bFromDraft=!0,this.draftFolder(F.folderFullNameRaw),this.draftUid(F.uid),this.subject(h),this.prepearMessageAttachments(F,A),this.aDraftInfo=Mt.isNonEmptyArray(T)&&3===T.length?T:null,this.sInReplyTo=F.sInReplyTo,this.sReferences=F.sReferences;break;case Lt.ComposeType.EditAsNew:this.to(E(F.to)),this.cc(E(F.cc)),this.bcc(E(F.bcc)),this.subject(h),this.prepearMessageAttachments(F,A),this.aDraftInfo=Mt.isNonEmptyArray(T)&&3===T.length?T:null,this.sInReplyTo=F.sInReplyTo,this.sReferences=F.sReferences}switch(A){case Lt.ComposeType.Reply:case Lt.ComposeType.ReplyAll:l=F.fromToLine(!1,!0),f=Mt.i18n("COMPOSE/REPLY_MESSAGE_TITLE",{DATETIME:d,EMAIL:l}),g="
"+f+":"+g+"
";break;case Lt.ComposeType.Forward:l=F.fromToLine(!1,!0),c=F.toToLine(!1,!0),u=F.ccToLine(!1,!0),g="
"+Mt.i18n("COMPOSE/FORWARD_MESSAGE_TOP_TITLE")+"
"+Mt.i18n("COMPOSE/FORWARD_MESSAGE_TOP_FROM")+": "+l+"
"+Mt.i18n("COMPOSE/FORWARD_MESSAGE_TOP_TO")+": "+c+(0 "+Mt.i18n("COMPOSE/FORWARD_MESSAGE_TOP_CC")+": "+u:"")+"
"+Mt.i18n("COMPOSE/FORWARD_MESSAGE_TOP_SENT")+": "+Mt.encodeHtml(d)+"
"+Mt.i18n("COMPOSE/FORWARD_MESSAGE_TOP_SUBJECT")+": "+Mt.encodeHtml(h)+"
"+g;break;case Lt.ComposeType.ForwardAsAttachment:g=""}C&&""!==v&&Lt.ComposeType.EditAsNew!==A&&Lt.ComposeType.Draft!==A&&(g=this.convertSignature(v,E(F.from,!0),g,A)),this.editor(function(e){e.setHtml(g,!1),F.isHtml()||e.modeToggle(!1)})}else Lt.ComposeType.Empty===A?(this.subject(Mt.isNormal(o)?""+o:""),g=Mt.isNormal(n)?""+n:"",C&&""!==v&&(g=this.convertSignature(v,"",Mt.convertPlainTextToHtml(g),A)),this.editor(function(e){e.setHtml(g,!1),Lt.EditorDefaultType.Html!==jt.data().editorDefaultType()&&e.modeToggle(!1)})):Mt.isNonEmptyArray(s)&&r.each(s,function(e){a.addMessageAsAttachment(e)});w=this.getAttachmentsDownloadsForUpload(),Mt.isNonEmptyArray(w)&&jt.remote().messageUploadAttachments(function(e,t){if(Lt.StorageResultType.Success===e&&t&&t.Result){var s=null,i="";if(!a.viewModelVisibility())for(i in t.Result)t.Result.hasOwnProperty(i)&&(s=a.getAttachmentById(t.Result[i]),s&&s.tempName(i))}else a.setMessageAttachmentFailedDowbloadText()},w),this.triggerForResize()},_.prototype.onFocus=function(){""===this.to()?this.to.focusTrigger(!this.to.focusTrigger()):this.oEditor&&this.oEditor.focus(),this.triggerForResize()},_.prototype.editorResize=function(){this.oEditor&&this.oEditor.resize()},_.prototype.tryToClosePopup=function(){var e=this;xt.isPopupVisible(W)||xt.showScreenPopup(W,[Mt.i18n("POPUPS_ASK/DESC_WANT_CLOSE_THIS_WINDOW"),function(){e.modalVisibility()&&Mt.delegateRun(e,"closeCommand")}])},_.prototype.onBuild=function(){this.initUploader();var s=this,i=null;c("ctrl+q, command+q",Lt.KeyState.Compose,function(){return s.identitiesDropdownTrigger(!0),!1}),c("ctrl+s, command+s",Lt.KeyState.Compose,function(){return s.saveCommand(),!1}),c("ctrl+enter, command+enter",Lt.KeyState.Compose,function(){return s.sendCommand(),!1}),c("esc",Lt.KeyState.Compose,function(){return s.modalVisibility()&&s.tryToClosePopup(),!1}),Gt.on("resize",function(){s.triggerForResize()}),this.dropboxEnabled()&&(i=document.createElement("script"),i.type="text/javascript",i.src="https://www.dropbox.com/static/api/1/dropins.js",t(i).attr("id","dropboxjs").attr("data-app-key",jt.settingsGet("DropboxApiKey")),document.body.appendChild(i)),this.driveEnabled()&&t.getScript("https://apis.google.com/js/api.js",function(){e.gapi&&s.driveVisible(!0)})},_.prototype.driveCallback=function(t,s){if(s&&e.XMLHttpRequest&&e.google&&s[e.google.picker.Response.ACTION]===e.google.picker.Action.PICKED&&s[e.google.picker.Response.DOCUMENTS]&&s[e.google.picker.Response.DOCUMENTS][0]&&s[e.google.picker.Response.DOCUMENTS][0].id){var i=this,o=new e.XMLHttpRequest;o.open("GET","https://www.googleapis.com/drive/v2/files/"+s[e.google.picker.Response.DOCUMENTS][0].id),o.setRequestHeader("Authorization","Bearer "+t),o.addEventListener("load",function(){if(o&&o.responseText){var e=JSON.parse(o.responseText),s=function(e,t,s){e&&e.exportLinks&&(e.exportLinks[t]?(e.downloadUrl=e.exportLinks[t],e.title=e.title+"."+s,e.mimeType=t):e.exportLinks["application/pdf"]&&(e.downloadUrl=e.exportLinks["application/pdf"],e.title=e.title+".pdf",e.mimeType="application/pdf"))};if(e&&!e.downloadUrl&&e.mimeType&&e.exportLinks)switch(e.mimeType.toString().toLowerCase()){case"application/vnd.google-apps.document":s(e,"application/vnd.openxmlformats-officedocument.wordprocessingml.document","docx");break;case"application/vnd.google-apps.spreadsheet":s(e,"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","xlsx");break;case"application/vnd.google-apps.drawing":s(e,"image/png","png");break;case"application/vnd.google-apps.presentation":s(e,"application/vnd.openxmlformats-officedocument.presentationml.presentation","pptx");break;default:s(e,"application/pdf","pdf")}e&&e.downloadUrl&&i.addDriveAttachment(e,t)}}),o.send()}},_.prototype.driveCreatePiker=function(t){if(e.gapi&&t&&t.access_token){var s=this;e.gapi.load("picker",{callback:function(){if(e.google&&e.google.picker){var i=(new e.google.picker.PickerBuilder).addView((new e.google.picker.DocsView).setIncludeFolders(!0)).setAppId(jt.settingsGet("GoogleClientID")).setOAuthToken(t.access_token).setCallback(r.bind(s.driveCallback,s,t.access_token)).enableFeature(e.google.picker.Feature.NAV_HIDDEN).build();i.setVisible(!0)}}})}},_.prototype.driveOpenPopup=function(){if(e.gapi){var t=this;e.gapi.load("auth",{callback:function(){var s=e.gapi.auth.getToken();s?t.driveCreatePiker(s):e.gapi.auth.authorize({client_id:jt.settingsGet("GoogleClientID"),scope:"https://www.googleapis.com/auth/drive.readonly",immediate:!0},function(s){if(s&&!s.error){var i=e.gapi.auth.getToken();i&&t.driveCreatePiker(i)}else e.gapi.auth.authorize({client_id:jt.settingsGet("GoogleClientID"),scope:"https://www.googleapis.com/auth/drive.readonly",immediate:!1},function(s){if(s&&!s.error){var i=e.gapi.auth.getToken();i&&t.driveCreatePiker(i)}})})}})}},_.prototype.getAttachmentById=function(e){for(var t=this.attachments(),s=0,i=t.length;i>s;s++)if(t[s]&&e===t[s].id)return t[s];return null},_.prototype.initUploader=function(){if(this.composeUploaderButton()){var e={},t=Mt.pInt(jt.settingsGet("AttachmentLimit")),s=new a({action:jt.link().upload(),name:"uploader",queueSize:2,multipleSizeLimit:50,disableFolderDragAndDrop:!1,clickElement:this.composeUploaderButton(),dragAndDropElement:this.composeUploaderDropPlace()});s?(s.on("onDragEnter",r.bind(function(){this.dragAndDropOver(!0)},this)).on("onDragLeave",r.bind(function(){this.dragAndDropOver(!1)},this)).on("onBodyDragEnter",r.bind(function(){this.dragAndDropVisible(!0)},this)).on("onBodyDragLeave",r.bind(function(){this.dragAndDropVisible(!1)},this)).on("onProgress",r.bind(function(t,s,i){var o=null;Mt.isUnd(e[t])?(o=this.getAttachmentById(t),o&&(e[t]=o)):o=e[t],o&&o.progress(" - "+Math.floor(s/i*100)+"%")},this)).on("onSelect",r.bind(function(e,i){this.dragAndDropOver(!1);var o=this,n=Mt.isUnd(i.FileName)?"":i.FileName.toString(),a=Mt.isNormal(i.Size)?Mt.pInt(i.Size):null,r=new A(e,n,a);return r.cancel=function(e){return function(){o.attachments.remove(function(t){return t&&t.id===e}),s&&s.cancel(e)}}(e),this.attachments.push(r),a>0&&t>0&&a>t?(r.error(Mt.i18n("UPLOAD/ERROR_FILE_IS_TOO_BIG")),!1):!0},this)).on("onStart",r.bind(function(t){var s=null;Mt.isUnd(e[t])?(s=this.getAttachmentById(t),s&&(e[t]=s)):s=e[t],s&&(s.waiting(!1),s.uploading(!0))},this)).on("onComplete",r.bind(function(t,s,i){var o="",n=null,a=null,r=this.getAttachmentById(t);a=s&&i&&i.Result&&i.Result.Attachment?i.Result.Attachment:null,n=i&&i.Result&&i.Result.ErrorCode?i.Result.ErrorCode:null,null!==n?o=Mt.getUploadErrorDescByCode(n):a||(o=Mt.i18n("UPLOAD/ERROR_UNKNOWN")),r&&(""!==o&&00&&o>0&&n>o?(s.uploading(!1),s.error(Mt.i18n("UPLOAD/ERROR_FILE_IS_TOO_BIG")),!1):(jt.remote().composeUploadExternals(function(e,t){var i=!1;s.uploading(!1),Lt.StorageResultType.Success===e&&t&&t.Result&&t.Result[s.id]&&(i=!0,s.tempName(t.Result[s.id])),i||s.error(Mt.getUploadErrorDescByCode(Lt.UploadErrorCode.FileNoUploaded))},[e.link]),!0)},_.prototype.addDriveAttachment=function(e,t){var s=this,i=function(e){return function(){s.attachments.remove(function(t){return t&&t.id===e})}},o=Mt.pInt(jt.settingsGet("AttachmentLimit")),n=null,a=e.fileSize?Mt.pInt(e.fileSize):0;return n=new A(e.downloadUrl,e.title,a),n.fromMessage=!1,n.cancel=i(e.downloadUrl),n.waiting(!1).uploading(!0),this.attachments.push(n),a>0&&o>0&&a>o?(n.uploading(!1),n.error(Mt.i18n("UPLOAD/ERROR_FILE_IS_TOO_BIG")),!1):(jt.remote().composeUploadDrive(function(e,t){var s=!1;n.uploading(!1),Lt.StorageResultType.Success===e&&t&&t.Result&&t.Result[n.id]&&(s=!0,n.tempName(t.Result[n.id][0]),n.size(Mt.pInt(t.Result[n.id][1]))),s||n.error(Mt.getUploadErrorDescByCode(Lt.UploadErrorCode.FileNoUploaded))},e.downloadUrl,t),!0)},_.prototype.prepearMessageAttachments=function(e,t){if(e){var s=this,i=Mt.isNonEmptyArray(e.attachments())?e.attachments():[],o=0,n=i.length,a=null,r=null,l=!1,c=function(e){return function(){s.attachments.remove(function(t){return t&&t.id===e})}};if(Lt.ComposeType.ForwardAsAttachment===t)this.addMessageAsAttachment(e);else for(;n>o;o++){switch(r=i[o],l=!1,t){case Lt.ComposeType.Reply:case Lt.ComposeType.ReplyAll:l=r.isLinked;break;case Lt.ComposeType.Forward:case Lt.ComposeType.Draft:case Lt.ComposeType.EditAsNew:l=!0}l&&(a=new A(r.download,r.fileName,r.estimatedSize,r.isInline,r.isLinked,r.cid,r.contentLocation),a.fromMessage=!0,a.cancel=c(r.download),a.waiting(!1).uploading(!0),this.attachments.push(a))}}},_.prototype.removeLinkedAttachments=function(){this.attachments.remove(function(e){return e&&e.isLinked})},_.prototype.setMessageAttachmentFailedDowbloadText=function(){r.each(this.attachments(),function(e){e&&e.fromMessage&&e.waiting(!1).uploading(!1).error(Mt.getUploadErrorDescByCode(Lt.UploadErrorCode.FileNoUploaded))},this)},_.prototype.isEmptyForm=function(e){e=Mt.isUnd(e)?!0:!!e;var t=e?0===this.attachments().length:0===this.attachmentsInReady().length;return 0===this.to().length&&0===this.cc().length&&0===this.bcc().length&&0===this.subject().length&&t&&(!this.oEditor||""===this.oEditor.getData())},_.prototype.reset=function(){this.to(""),this.cc(""),this.bcc(""),this.replyTo(""),this.subject(""),this.requestReadReceipt(!1),this.aDraftInfo=null,this.sInReplyTo="",this.bFromDraft=!1,this.sReferences="",this.sendError(!1),this.sendSuccessButSaveError(!1),this.savedError(!1),this.savedTime(0),this.savedOrSendingText(""),this.emptyToError(!1),this.attachmentsInProcessError(!1),this.showCcAndBcc(!1),this.attachments([]),this.dragAndDropOver(!1),this.dragAndDropVisible(!1),this.draftFolder(""),this.draftUid(""),this.sending(!1),this.saving(!1),this.oEditor&&this.oEditor.clear(!1)},_.prototype.getAttachmentsDownloadsForUpload=function(){return r.map(r.filter(this.attachments(),function(e){return e&&""===e.tempName()}),function(e){return e.id})},_.prototype.triggerForResize=function(){this.resizer(!this.resizer()),this.editorResizeThrottle()},Mt.extendAsViewModel("PopupsContactsViewModel",U),U.prototype.getPropertyPlceholder=function(e){var t="";
-switch(e){case Lt.ContactPropertyType.LastName:t="CONTACTS/PLACEHOLDER_ENTER_LAST_NAME";break;case Lt.ContactPropertyType.FirstName:t="CONTACTS/PLACEHOLDER_ENTER_FIRST_NAME";break;case Lt.ContactPropertyType.Nick:t="CONTACTS/PLACEHOLDER_ENTER_NICK_NAME"}return t},U.prototype.addNewProperty=function(e,t){this.viewProperties.push(new w(e,t||"","",!0,this.getPropertyPlceholder(e)))},U.prototype.addNewOrFocusProperty=function(e,t){var s=r.find(this.viewProperties(),function(t){return e===t.type()});s?s.focused(!0):this.addNewProperty(e,t)},U.prototype.addNewTag=function(){this.viewTags.visibility(!0),this.viewTags.focusTrigger(!0)},U.prototype.addNewEmail=function(){this.addNewProperty(Lt.ContactPropertyType.Email,"Home")},U.prototype.addNewPhone=function(){this.addNewProperty(Lt.ContactPropertyType.Phone,"Mobile")},U.prototype.addNewWeb=function(){this.addNewProperty(Lt.ContactPropertyType.Web)},U.prototype.addNewNickname=function(){this.addNewOrFocusProperty(Lt.ContactPropertyType.Nick)},U.prototype.addNewNotes=function(){this.addNewOrFocusProperty(Lt.ContactPropertyType.Note)},U.prototype.addNewBirthday=function(){this.addNewOrFocusProperty(Lt.ContactPropertyType.Birthday)},U.prototype.exportVcf=function(){jt.download(jt.link().exportContactsVcf())},U.prototype.exportCsv=function(){jt.download(jt.link().exportContactsCsv())},U.prototype.initUploader=function(){if(this.importUploaderButton()){var t=new a({action:jt.link().uploadContacts(),name:"uploader",queueSize:1,multipleSizeLimit:1,disableFolderDragAndDrop:!0,disableDragAndDrop:!0,disableMultiple:!0,disableDocumentDropPrevent:!0,clickElement:this.importUploaderButton()});t&&t.on("onStart",r.bind(function(){this.contacts.importing(!0)},this)).on("onComplete",r.bind(function(t,s,i){this.contacts.importing(!1),this.reloadContactList(),t&&s&&i&&i.Result||e.alert(Mt.i18n("CONTACTS/ERROR_IMPORT_FILE"))},this))}},U.prototype.removeCheckedOrSelectedContactsFromList=function(){var e=this,t=this.contacts,s=this.currentContact(),i=this.contacts().length,o=this.contactsCheckedOrSelected();0=i&&(this.bDropPageAfterDelete=!0),r.delay(function(){r.each(o,function(e){t.remove(e)})},500))},U.prototype.deleteSelectedContacts=function(){00?i:0),Mt.isNonEmptyArray(s.Result.Tags)&&(n=r.map(s.Result.Tags,function(e){var t=new T;return t.parse(e)?t:null}),n=r.compact(n))),t.contactsCount(i),t.contacts(o),t.contacts.loading(!1),t.contactTags(n),t.viewClearSearch(""!==t.search())},s,It.Defaults.ContactsPerPage,this.search())},U.prototype.onBuild=function(e){this.oContentVisible=t(".b-list-content",e),this.oContentScrollable=t(".content",this.oContentVisible),this.selector.init(this.oContentVisible,this.oContentScrollable,Lt.KeyState.ContactList);var i=this;c("delete",Lt.KeyState.ContactList,function(){return i.deleteCommand(),!1}),e.on("click",".e-pagenator .e-page",function(){var e=s.dataFor(this);e&&(i.contactsPage(Mt.pInt(e.value)),i.reloadContactList())}),this.initUploader()},U.prototype.onShow=function(){xt.routeOff(),this.reloadContactList(!0)},U.prototype.onHide=function(){xt.routeOn(),this.currentContact(null),this.emptySelection(!0),this.search(""),this.contactsCount(0),this.contacts([])},Mt.extendAsViewModel("PopupsAdvancedSearchViewModel",x),x.prototype.buildSearchStringValue=function(e){return-1 li"),o=s&&("tab"===s.shortcut||"right"===s.shortcut),n=i.index(i.filter(".active"));return!o&&n>0?n--:o&&n-1&&r.eq(n).removeClass("focused"),38===a&&n>0?n--:40===a&&no)?(this.oContentScrollable.scrollTop(i.top<0?this.oContentScrollable.scrollTop()+i.top-e:this.oContentScrollable.scrollTop()+i.top-o+n+e),!0):!1},et.prototype.messagesDrop=function(e,t){if(e&&t&&t.helper){var s=t.helper.data("rl-folder"),i=Bt.hasClass("rl-ctrl-key-pressed"),o=t.helper.data("rl-uids");Mt.isNormal(s)&&""!==s&&Mt.isArray(o)&&jt.moveMessagesToFolder(s,o,e.fullNameRaw,i)}},et.prototype.composeClick=function(){xt.showScreenPopup(_)},et.prototype.createFolder=function(){xt.showScreenPopup(k)},et.prototype.configureFolders=function(){xt.setHash(jt.link().settings("folders"))},et.prototype.contactsClick=function(){this.allowContacts&&xt.showScreenPopup(U)},Mt.extendAsViewModel("MailBoxMessageListViewModel",tt),tt.prototype.emptySubjectValue="",tt.prototype.searchEnterAction=function(){this.mainMessageListSearch(this.sLastSearchValue),this.inputMessageListSearchFocus(!1)},tt.prototype.printableMessageCountForDeletion=function(){var e=this.messageListCheckedOrSelectedUidsWithSubMails().length;return e>1?" ("+(100>e?e:"99+")+")":""},tt.prototype.cancelSearch=function(){this.mainMessageListSearch(""),this.inputMessageListSearchFocus(!1)},tt.prototype.moveSelectedMessagesToFolder=function(e,t){return this.canBeMoved()&&jt.moveMessagesToFolder(jt.data().currentFolderFullNameRaw(),jt.data().messageListCheckedOrSelectedUidsWithSubMails(),e,t),!1},tt.prototype.dragAndDronHelper=function(e){e&&e.checked(!0);var t=Mt.draggeblePlace(),s=jt.data().messageListCheckedOrSelectedUidsWithSubMails();return t.data("rl-folder",jt.data().currentFolderFullNameRaw()),t.data("rl-uids",s),t.find(".text").text(""+s.length),r.defer(function(){var e=jt.data().messageListCheckedOrSelectedUidsWithSubMails();t.data("rl-uids",e),t.find(".text").text(""+e.length)}),t},tt.prototype.onMessageResponse=function(e,t,s){var i=jt.data();i.hideMessageBodies(),i.messageLoading(!1),Lt.StorageResultType.Success===e&&t&&t.Result?i.setMessage(t,s):Lt.StorageResultType.Unload===e?(i.message(null),i.messageError("")):Lt.StorageResultType.Abort!==e&&(i.message(null),i.messageError(Mt.getNotification(t&&t.ErrorCode?t.ErrorCode:Lt.Notification.UnknownError)))},tt.prototype.populateMessageBody=function(e){e&&(jt.remote().message(this.onMessageResponse,e.folderFullNameRaw,e.uid)?jt.data().messageLoading(!0):Mt.log("Error: Unknown message request: "+e.folderFullNameRaw+" ~ "+e.uid+" [e-101]"))},tt.prototype.setAction=function(e,t,s){var i=[],o=null,n=jt.cache(),a=0;if(Mt.isUnd(s)&&(s=jt.data().messageListChecked()),i=r.map(s,function(e){return e.uid}),""!==e&&00?100>e?e:"99+":""},st.prototype.verifyPgpSignedClearMessage=function(e){e&&e.verifyPgpSignedClearMessage()},st.prototype.decryptPgpEncryptedMessage=function(e){e&&e.decryptPgpEncryptedMessage(this.viewPgpPassword())},st.prototype.readReceipt=function(e){e&&""!==e.readReceipt()&&(jt.remote().sendReadReceiptMessage(Mt.emptyFunction,e.folderFullNameRaw,e.uid,e.readReceipt(),Mt.i18n("READ_RECEIPT/SUBJECT",{SUBJECT:e.subject()}),Mt.i18n("READ_RECEIPT/BODY",{"READ-RECEIPT":jt.data().accountEmail()})),e.isReadReceipt(!0),jt.cache().storeMessageFlagsToCache(e),jt.reloadFlagsCurrentMessageListAndMessageFromCache())},Mt.extendAsViewModel("SettingsMenuViewModel",it),it.prototype.link=function(e){return jt.link().settings(e)},it.prototype.backToMailBoxClick=function(){xt.setHash(jt.link().inbox())},Mt.extendAsViewModel("SettingsPaneViewModel",ot),ot.prototype.onBuild=function(){var e=this;c("esc",Lt.KeyState.Settings,function(){e.backToMailBoxClick()})},ot.prototype.onShow=function(){jt.data().message(null)},ot.prototype.backToMailBoxClick=function(){xt.setHash(jt.link().inbox())},Mt.addSettingsViewModel(nt,"SettingsGeneral","SETTINGS_LABELS/LABEL_GENERAL_NAME","general",!0),nt.prototype.toggleLayout=function(){this.layout(Lt.Layout.NoPreview===this.layout()?Lt.Layout.SidePreview:Lt.Layout.NoPreview)},nt.prototype.onBuild=function(){var e=this;r.delay(function(){var s=jt.data(),i=Mt.settingsSaveHelperSimpleFunction(e.mppTrigger,e);s.language.subscribe(function(s){e.languageTrigger(Lt.SaveSettingsStep.Animate),t.ajax({url:jt.link().langLink(s),dataType:"script",cache:!0}).done(function(){Mt.i18nToDoc(),e.languageTrigger(Lt.SaveSettingsStep.TrueResult)}).fail(function(){e.languageTrigger(Lt.SaveSettingsStep.FalseResult)}).always(function(){r.delay(function(){e.languageTrigger(Lt.SaveSettingsStep.Idle)},1e3)}),jt.remote().saveSettings(Mt.emptyFunction,{Language:s})}),s.editorDefaultType.subscribe(function(e){jt.remote().saveSettings(Mt.emptyFunction,{EditorDefaultType:e})}),s.messagesPerPage.subscribe(function(e){jt.remote().saveSettings(i,{MPP:e})}),s.showImages.subscribe(function(e){jt.remote().saveSettings(Mt.emptyFunction,{ShowImages:e?"1":"0"})}),s.interfaceAnimation.subscribe(function(e){jt.remote().saveSettings(Mt.emptyFunction,{InterfaceAnimation:e})}),s.useDesktopNotifications.subscribe(function(e){Mt.timeOutAction("SaveDesktopNotifications",function(){jt.remote().saveSettings(Mt.emptyFunction,{DesktopNotifications:e?"1":"0"})},3e3)}),s.replySameFolder.subscribe(function(e){Mt.timeOutAction("SaveReplySameFolder",function(){jt.remote().saveSettings(Mt.emptyFunction,{ReplySameFolder:e?"1":"0"})},3e3)}),s.useThreads.subscribe(function(e){s.messageList([]),jt.remote().saveSettings(Mt.emptyFunction,{UseThreads:e?"1":"0"})}),s.layout.subscribe(function(e){s.messageList([]),jt.remote().saveSettings(Mt.emptyFunction,{Layout:e})}),s.useCheckboxesInList.subscribe(function(e){jt.remote().saveSettings(Mt.emptyFunction,{UseCheckboxesInList:e?"1":"0"})})},50)},nt.prototype.onShow=function(){jt.data().desktopNotifications.valueHasMutated()},nt.prototype.selectLanguage=function(){xt.showScreenPopup(j)},Mt.addSettingsViewModel(at,"SettingsContacts","SETTINGS_LABELS/LABEL_CONTACTS_NAME","contacts"),at.prototype.onBuild=function(){jt.data().contactsAutosave.subscribe(function(e){jt.remote().saveSettings(Mt.emptyFunction,{ContactsAutosave:e?"1":"0"})})},Mt.addSettingsViewModel(rt,"SettingsAccounts","SETTINGS_LABELS/LABEL_ACCOUNTS_NAME","accounts"),rt.prototype.addNewAccount=function(){xt.showScreenPopup(V)},rt.prototype.deleteAccount=function(t){if(t&&t.deleteAccess()){this.accountForDeletion(null);var s=function(e){return t===e};t&&(this.accounts.remove(s),jt.remote().accountDelete(function(t,s){Lt.StorageResultType.Success===t&&s&&s.Result&&s.Reload?(xt.routeOff(),xt.setHash(jt.link().root(),!0),xt.routeOff(),r.defer(function(){e.location.reload()})):jt.accountsAndIdentities()},t.email))}},Mt.addSettingsViewModel(lt,"SettingsIdentity","SETTINGS_LABELS/LABEL_IDENTITY_NAME","identity"),lt.prototype.onFocus=function(){if(!this.editor&&this.signatureDom()){var e=this,t=jt.data().signature();this.editor=new d(e.signatureDom(),function(){jt.data().signature((e.editor.isHtml()?":HTML:":"")+e.editor.getData())},function(){":HTML:"===t.substr(0,6)?e.editor.setHtml(t.substr(6),!1):e.editor.setPlain(t,!1)})}},lt.prototype.onBuild=function(){var e=this;r.delay(function(){var t=jt.data(),s=Mt.settingsSaveHelperSimpleFunction(e.displayNameTrigger,e),i=Mt.settingsSaveHelperSimpleFunction(e.replyTrigger,e),o=Mt.settingsSaveHelperSimpleFunction(e.signatureTrigger,e);t.displayName.subscribe(function(e){jt.remote().saveSettings(s,{DisplayName:e})}),t.replyTo.subscribe(function(e){jt.remote().saveSettings(i,{ReplyTo:e})}),t.signature.subscribe(function(e){jt.remote().saveSettings(o,{Signature:e})}),t.signatureToAll.subscribe(function(e){jt.remote().saveSettings(null,{SignatureToAll:e?"1":"0"})})},50)},Mt.addSettingsViewModel(ct,"SettingsIdentities","SETTINGS_LABELS/LABEL_IDENTITIES_NAME","identities"),ct.prototype.formattedAccountIdentity=function(){var e=this.displayName.peek(),t=this.accountEmail.peek();return""===e?t:'"'+Mt.quoteName(e)+'" <'+t+">"},ct.prototype.addNewIdentity=function(){xt.showScreenPopup(q)},ct.prototype.editIdentity=function(e){xt.showScreenPopup(q,[e])},ct.prototype.deleteIdentity=function(e){if(e&&e.deleteAccess()){this.identityForDeletion(null);var t=function(t){return e===t};e&&(this.identities.remove(t),jt.remote().identityDelete(function(){jt.accountsAndIdentities()},e.id))}},ct.prototype.onFocus=function(){if(!this.editor&&this.signatureDom()){var e=this,t=jt.data().signature();this.editor=new d(e.signatureDom(),function(){jt.data().signature((e.editor.isHtml()?":HTML:":"")+e.editor.getData())},function(){":HTML:"===t.substr(0,6)?e.editor.setHtml(t.substr(6),!1):e.editor.setPlain(t,!1)})}},ct.prototype.onBuild=function(e){var t=this;e.on("click",".identity-item .e-action",function(){var e=s.dataFor(this);e&&t.editIdentity(e)}),r.delay(function(){var e=jt.data(),s=Mt.settingsSaveHelperSimpleFunction(t.displayNameTrigger,t),i=Mt.settingsSaveHelperSimpleFunction(t.replyTrigger,t),o=Mt.settingsSaveHelperSimpleFunction(t.signatureTrigger,t),n=Mt.settingsSaveHelperSimpleFunction(t.defaultIdentityIDTrigger,t);e.defaultIdentityID.subscribe(function(e){jt.remote().saveSettings(n,{DefaultIdentityID:e})}),e.displayName.subscribe(function(e){jt.remote().saveSettings(s,{DisplayName:e})}),e.replyTo.subscribe(function(e){jt.remote().saveSettings(i,{ReplyTo:e})}),e.signature.subscribe(function(e){jt.remote().saveSettings(o,{Signature:e})}),e.signatureToAll.subscribe(function(e){jt.remote().saveSettings(null,{SignatureToAll:e?"1":"0"})})},50)},Mt.addSettingsViewModel(ut,"SettingsFilters","SETTINGS_LABELS/LABEL_FILTERS_NAME","filters"),ut.prototype.deleteFilter=function(e){this.filters.remove(e)},ut.prototype.addFilter=function(){xt.showScreenPopup(Y,[new P])},Mt.addSettingsViewModel(dt,"SettingsSecurity","SETTINGS_LABELS/LABEL_SECURITY_NAME","security"),dt.prototype.showSecret=function(){this.secreting(!0),jt.remote().showTwoFactorSecret(this.onSecretResult)},dt.prototype.hideSecret=function(){this.viewSecret(""),this.viewBackupCodes(""),this.viewUrl("")},dt.prototype.createTwoFactor=function(){this.processing(!0),jt.remote().createTwoFactor(this.onResult)},dt.prototype.enableTwoFactor=function(){this.processing(!0),jt.remote().enableTwoFactor(this.onResult,this.viewEnable())},dt.prototype.testTwoFactor=function(){xt.showScreenPopup(z)},dt.prototype.clearTwoFactor=function(){this.viewSecret(""),this.viewBackupCodes(""),this.viewUrl(""),this.clearing(!0),jt.remote().clearTwoFactor(this.onResult)},dt.prototype.onShow=function(){this.viewSecret(""),this.viewBackupCodes(""),this.viewUrl("")},dt.prototype.onResult=function(e,t){if(this.processing(!1),this.clearing(!1),Lt.StorageResultType.Success===e&&t&&t.Result?(this.viewUser(Mt.pString(t.Result.User)),this.viewEnable(!!t.Result.Enable),this.twoFactorStatus(!!t.Result.IsSet),this.viewSecret(Mt.pString(t.Result.Secret)),this.viewBackupCodes(Mt.pString(t.Result.BackupCodes).replace(/[\s]+/g," ")),this.viewUrl(Mt.pString(t.Result.Url))):(this.viewUser(""),this.viewEnable(!1),this.twoFactorStatus(!1),this.viewSecret(""),this.viewBackupCodes(""),this.viewUrl("")),this.bFirst){this.bFirst=!1;var s=this;this.viewEnable.subscribe(function(e){this.viewEnable.subs&&jt.remote().enableTwoFactor(function(e,t){Lt.StorageResultType.Success===e&&t&&t.Result||(s.viewEnable.subs=!1,s.viewEnable(!1),s.viewEnable.subs=!0)},e)},this)}},dt.prototype.onSecretResult=function(e,t){this.secreting(!1),Lt.StorageResultType.Success===e&&t&&t.Result?(this.viewSecret(Mt.pString(t.Result.Secret)),this.viewUrl(Mt.pString(t.Result.Url))):(this.viewSecret(""),this.viewUrl(""))},dt.prototype.onBuild=function(){this.processing(!0),jt.remote().getTwoFactor(this.onResult)},Mt.addSettingsViewModel(ht,"SettingsSocial","SETTINGS_LABELS/LABEL_SOCIAL_NAME","social"),Mt.addSettingsViewModel(pt,"SettingsChangePassword","SETTINGS_LABELS/LABEL_CHANGE_PASSWORD_NAME","change-password"),pt.prototype.onHide=function(){this.changeProcess(!1),this.currentPassword(""),this.newPassword(""),this.newPassword2(""),this.errorDescription(""),this.passwordMismatch(!1),this.currentPassword.error(!1)},pt.prototype.onChangePasswordResponse=function(e,t){this.changeProcess(!1),this.passwordMismatch(!1),this.errorDescription(""),this.currentPassword.error(!1),Lt.StorageResultType.Success===e&&t&&t.Result?(this.currentPassword(""),this.newPassword(""),this.newPassword2(""),this.passwordUpdateSuccess(!0),this.currentPassword.error(!1)):(t&&Lt.Notification.CurrentPasswordIncorrect===t.ErrorCode&&this.currentPassword.error(!0),this.passwordUpdateError(!0),this.errorDescription(Mt.getNotification(t&&t.ErrorCode?t.ErrorCode:Lt.Notification.CouldNotSaveNewPassword)))},Mt.addSettingsViewModel(mt,"SettingsFolders","SETTINGS_LABELS/LABEL_FOLDERS_NAME","folders"),mt.prototype.folderEditOnEnter=function(e){var t=e?Mt.trim(e.nameForEdit()):"";""!==t&&e.name()!==t&&(jt.local().set(Lt.ClientSideKeyName.FoldersLashHash,""),jt.data().foldersRenaming(!0),jt.remote().folderRename(function(e,t){jt.data().foldersRenaming(!1),Lt.StorageResultType.Success===e&&t&&t.Result||jt.data().foldersListError(t&&t.ErrorCode?Mt.getNotification(t.ErrorCode):Mt.i18n("NOTIFICATIONS/CANT_RENAME_FOLDER")),jt.folders()},e.fullNameRaw,t),jt.cache().removeFolderFromCacheList(e.fullNameRaw),e.name(t)),e.edited(!1)},mt.prototype.folderEditOnEsc=function(e){e&&e.edited(!1)},mt.prototype.onShow=function(){jt.data().foldersListError("")},mt.prototype.createFolder=function(){xt.showScreenPopup(k)},mt.prototype.systemFolder=function(){xt.showScreenPopup(O)},mt.prototype.deleteFolder=function(e){if(e&&e.canBeDeleted()&&e.deleteAccess()&&0===e.privateMessageCountAll()){this.folderForDeletion(null);var t=function(s){return e===s?!0:(s.subFolders.remove(t),!1)};e&&(jt.local().set(Lt.ClientSideKeyName.FoldersLashHash,""),jt.data().folderList.remove(t),jt.data().foldersDeleting(!0),jt.remote().folderDelete(function(e,t){jt.data().foldersDeleting(!1),Lt.StorageResultType.Success===e&&t&&t.Result||jt.data().foldersListError(t&&t.ErrorCode?Mt.getNotification(t.ErrorCode):Mt.i18n("NOTIFICATIONS/CANT_DELETE_FOLDER")),jt.folders()},e.fullNameRaw),jt.cache().removeFolderFromCacheList(e.fullNameRaw))}else 00&&(s=this.messagesBodiesDom(),s&&(s.find(".rl-cache-class").each(function(){var s=t(this);i>s.data("rl-cache-count")&&(s.addClass("rl-cache-purge"),e++)}),e>0&&r.delay(function(){s.find(".rl-cache-purge").remove()},300)))},yt.prototype.populateDataOnStart=function(){bt.prototype.populateDataOnStart.call(this),this.accountEmail(jt.settingsGet("Email")),this.accountIncLogin(jt.settingsGet("IncLogin")),this.accountOutLogin(jt.settingsGet("OutLogin")),this.projectHash(jt.settingsGet("ProjectHash")),this.defaultIdentityID(jt.settingsGet("DefaultIdentityID")),this.displayName(jt.settingsGet("DisplayName")),this.replyTo(jt.settingsGet("ReplyTo")),this.signature(jt.settingsGet("Signature")),this.signatureToAll(!!jt.settingsGet("SignatureToAll")),this.enableTwoFactor(!!jt.settingsGet("EnableTwoFactor")),this.lastFoldersHash=jt.local().get(Lt.ClientSideKeyName.FoldersLashHash)||"",this.remoteSuggestions=!!jt.settingsGet("RemoteSuggestions"),this.devEmail=jt.settingsGet("DevEmail"),this.devPassword=jt.settingsGet("DevPassword")},yt.prototype.initUidNextAndNewMessages=function(t,s,i){if("INBOX"===t&&Mt.isNormal(s)&&""!==s){if(Mt.isArray(i)&&03)l(jt.link().notificationMailIcon(),jt.data().accountEmail(),Mt.i18n("MESSAGE_LIST/NEW_MESSAGE_NOTIFICATION",{COUNT:a}));else for(;a>n;n++)l(jt.link().notificationMailIcon(),E.emailsToLine(E.initEmailsFromJson(i[n].From),!1),i[n].Subject)}jt.cache().setFolderUidNext(t,s)}},yt.prototype.folderResponseParseRec=function(e,t){var s=0,i=0,o=null,n=null,a="",r=[],l=[];for(s=0,i=t.length;i>s;s++)o=t[s],o&&(a=o.FullNameRaw,n=jt.cache().getFolderFromCacheList(a),n||(n=N.newInstanceFromJson(o),n&&(jt.cache().setFolderToCacheList(a,n),jt.cache().setFolderFullNameRaw(n.fullNameHash,a))),n&&(n.collapsed(!Mt.isFolderExpanded(n.fullNameHash)),o.Extended&&(o.Extended.Hash&&jt.cache().setFolderHash(n.fullNameRaw,o.Extended.Hash),Mt.isNormal(o.Extended.MessageCount)&&n.messageCountAll(o.Extended.MessageCount),Mt.isNormal(o.Extended.MessageUnseenCount)&&n.messageCountUnread(o.Extended.MessageUnseenCount)),r=o.SubFolders,r&&"Collection/FolderCollection"===r["@Object"]&&r["@Collection"]&&Mt.isArray(r["@Collection"])&&n.subFolders(this.folderResponseParseRec(e,r["@Collection"])),l.push(n)));return l},yt.prototype.setFolders=function(e){var t=[],s=!1,i=jt.data(),o=function(e){return""===e||It.Values.UnuseOptionValue===e||null!==jt.cache().getFolderFromCacheList(e)?e:""};e&&e.Result&&"Collection/FolderCollection"===e.Result["@Object"]&&e.Result["@Collection"]&&Mt.isArray(e.Result["@Collection"])&&(Mt.isUnd(e.Result.Namespace)||(i.namespace=e.Result.Namespace),this.threading(!!jt.settingsGet("UseImapThread")&&e.Result.IsThreadsSupported&&!0),t=this.folderResponseParseRec(i.namespace,e.Result["@Collection"]),i.folderList(t),e.Result.SystemFolders&&""==""+jt.settingsGet("SentFolder")+jt.settingsGet("DraftFolder")+jt.settingsGet("SpamFolder")+jt.settingsGet("TrashFolder")+jt.settingsGet("ArchiveFolder")+jt.settingsGet("NullFolder")&&(jt.settingsSet("SentFolder",e.Result.SystemFolders[2]||null),jt.settingsSet("DraftFolder",e.Result.SystemFolders[3]||null),jt.settingsSet("SpamFolder",e.Result.SystemFolders[4]||null),jt.settingsSet("TrashFolder",e.Result.SystemFolders[5]||null),jt.settingsSet("ArchiveFolder",e.Result.SystemFolders[12]||null),s=!0),i.sentFolder(o(jt.settingsGet("SentFolder"))),i.draftFolder(o(jt.settingsGet("DraftFolder"))),i.spamFolder(o(jt.settingsGet("SpamFolder"))),i.trashFolder(o(jt.settingsGet("TrashFolder"))),i.archiveFolder(o(jt.settingsGet("ArchiveFolder"))),s&&jt.remote().saveSystemFolders(Mt.emptyFunction,{SentFolder:i.sentFolder(),DraftFolder:i.draftFolder(),SpamFolder:i.spamFolder(),TrashFolder:i.trashFolder(),ArchiveFolder:i.archiveFolder(),NullFolder:"NullFolder"}),jt.local().set(Lt.ClientSideKeyName.FoldersLashHash,e.Result.FoldersHash))},yt.prototype.hideMessageBodies=function(){var e=this.messagesBodiesDom();e&&e.find(".b-text-part").hide()},yt.prototype.getNextFolderNames=function(e){e=Mt.isUnd(e)?!1:!!e;var t=[],s=10,i=n().unix(),o=i-300,a=[],l=function(t){r.each(t,function(t){t&&"INBOX"!==t.fullNameRaw&&t.selectable&&t.existen&&o>t.interval&&(!e||t.subScribed())&&a.push([t.interval,t.fullNameRaw]),t&&0t[0]?1:0}),r.find(a,function(e){var o=jt.cache().getFolderFromCacheList(e[1]);return o&&(o.interval=i,t.push(e[1])),s<=t.length}),r.uniq(t)},yt.prototype.removeMessagesFromList=function(e,t,s,i){s=Mt.isNormal(s)?s:"",i=Mt.isUnd(i)?!1:!!i,t=r.map(t,function(e){return Mt.pInt(e)});var o=0,n=jt.data(),a=jt.cache(),l=n.messageList(),c=jt.cache().getFolderFromCacheList(e),u=""===s?null:a.getFolderFromCacheList(s||""),d=n.currentFolderFullNameRaw(),h=n.message(),p=d===e?r.filter(l,function(e){return e&&-10&&c.messageCountUnread(0<=c.messageCountUnread()-o?c.messageCountUnread()-o:0)),u&&(u.messageCountAll(u.messageCountAll()+t.length),o>0&&u.messageCountUnread(u.messageCountUnread()+o),u.actionBlink(!0)),0 ').hide().addClass("rl-cache-class"),a.data("rl-cache-count",++Ot.iMessageBodyCacheCount),Mt.isNormal(e.Result.Html)&&""!==e.Result.Html?(i=!0,c=e.Result.Html.toString()):Mt.isNormal(e.Result.Plain)&&""!==e.Result.Plain?(i=!1,c=Mt.plainToHtml(e.Result.Plain.toString(),!1),(p.isPgpSigned()||p.isPgpEncrypted())&&jt.data().capaOpenPGP()&&(p.plainRaw=Mt.pString(e.Result.Plain),d=/---BEGIN PGP MESSAGE---/.test(p.plainRaw),d||(u=/-----BEGIN PGP SIGNED MESSAGE-----/.test(p.plainRaw)&&/-----BEGIN PGP SIGNATURE-----/.test(p.plainRaw)),zt.empty(),u&&p.isPgpSigned()?c=zt.append(t('').text(p.plainRaw)).html():d&&p.isPgpEncrypted()&&(c=zt.append(t('').text(p.plainRaw)).html()),zt.empty(),p.isPgpSigned(u),p.isPgpEncrypted(d))):i=!1,a.html(Mt.linkify(c)).addClass("b-text-part "+(i?"html":"plain")),p.isHtml(!!i),p.hasImages(!!o),p.pgpSignedVerifyStatus(Lt.SignedVerifyStatus.None),p.pgpSignedVerifyUser(""),p.body=a,p.body&&h.append(p.body),p.storeDataToDom(),n&&p.showInternalImages(!0),p.hasImages()&&this.showImages()&&p.showExternalImages(!0),this.purgeMessageBodyCacheThrottle()),this.messageActiveDom(p.body),this.hideMessageBodies(),p.body.show(),a&&Mt.initBlockquoteSwitcher(a)),jt.cache().initMessageFlagsFromCache(p),p.unseen()&&jt.setMessageSeen(p),Mt.windowResize())},yt.prototype.calculateMessageListHash=function(e){return r.map(e,function(e){return""+e.hash+"_"+e.threadsLen()+"_"+e.flagHash()}).join("|")},yt.prototype.setMessageList=function(e,t){if(e&&e.Result&&"Collection/MessageCollection"===e.Result["@Object"]&&e.Result["@Collection"]&&Mt.isArray(e.Result["@Collection"])){var s=jt.data(),i=jt.cache(),o=null,a=0,r=0,l=0,c=0,u=[],d=n().unix(),h=s.staticMessageList,p=null,m=null,g=null,f=0,b=!1;for(l=Mt.pInt(e.Result.MessageResultCount),c=Mt.pInt(e.Result.Offset),Mt.isNonEmptyArray(e.Result.LastCollapsedThreadUids)&&(o=e.Result.LastCollapsedThreadUids),g=jt.cache().getFolderFromCacheList(Mt.isNormal(e.Result.Folder)?e.Result.Folder:""),g&&!t&&(g.interval=d,jt.cache().setFolderHash(e.Result.Folder,e.Result.FolderHash),Mt.isNormal(e.Result.MessageCount)&&g.messageCountAll(e.Result.MessageCount),Mt.isNormal(e.Result.MessageUnseenCount)&&(Mt.pInt(g.messageCountUnread())!==Mt.pInt(e.Result.MessageUnseenCount)&&(b=!0),g.messageCountUnread(e.Result.MessageUnseenCount)),this.initUidNextAndNewMessages(g.fullNameRaw,e.Result.UidNext,e.Result.NewMessages)),b&&g&&jt.cache().clearMessageFlagsFromCacheByFolder(g.fullNameRaw),a=0,r=e.Result["@Collection"].length;r>a;a++)p=e.Result["@Collection"][a],p&&"Object/Message"===p["@Object"]&&(m=h[a],m&&m.initByJson(p)||(m=E.newInstanceFromJson(p)),m&&(i.hasNewMessageAndRemoveFromCache(m.folderFullNameRaw,m.uid)&&5>=f&&(f++,m.newForAnimation(!0)),m.deleted(!1),t?jt.cache().initMessageFlagsFromCache(m):jt.cache().storeMessageFlagsToCache(m),m.lastInCollapsedThread(o&&-1(new e.Date).getTime()-d),p&&l.oRequests[p]&&(l.oRequests[p].__aborted&&(o="abort"),l.oRequests[p]=null),l.defaultResponse(s,p,o,t,n,i)}),p&&00?(this.defaultRequest(e,"Message",{},null,"Message/"+kt.urlsafe_encode([t,s,jt.data().projectHash(),jt.data().threading()&&jt.data().useThreads()?"1":"0"].join(String.fromCharCode(0))),["Message"]),!0):!1},vt.prototype.composeUploadExternals=function(e,t){this.defaultRequest(e,"ComposeUploadExternals",{Externals:t},999e3)},vt.prototype.composeUploadDrive=function(e,t,s){this.defaultRequest(e,"ComposeUploadDrive",{AccessToken:s,Url:t},999e3)},vt.prototype.folderInformation=function(e,t,s){var i=!0,o=jt.cache(),n=[];Mt.isArray(s)&&0 ").addClass("rl-settings-view-model").hide(),l.appendTo(a),o.data=jt.data(),o.viewModelDom=l,o.__rlSettingsData=n.__rlSettingsData,n.__dom=l,n.__builded=!0,n.__vm=o,s.applyBindingAccessorsToNode(l[0],{i18nInit:!0,template:function(){return{name:n.__rlSettingsData.Template}}},o),Mt.delegateRun(o,"onBuild",[l])):Mt.log("Cannot find sub settings view model position: SettingsSubScreen")),o&&r.defer(function(){i.oCurrentSubScreen&&(Mt.delegateRun(i.oCurrentSubScreen,"onHide"),i.oCurrentSubScreen.viewModelDom.hide()),i.oCurrentSubScreen=o,i.oCurrentSubScreen&&(i.oCurrentSubScreen.viewModelDom.show(),Mt.delegateRun(i.oCurrentSubScreen,"onShow"),Mt.delegateRun(i.oCurrentSubScreen,"onFocus",[],200),r.each(i.menu(),function(e){e.selected(o&&o.__rlSettingsData&&e.route===o.__rlSettingsData.Route)}),t("#rl-content .b-settings .b-content .content").scrollTop(0)),Mt.windowResize()})):xt.setHash(jt.link().settings(),!1,!0)},Tt.prototype.onHide=function(){this.oCurrentSubScreen&&this.oCurrentSubScreen.viewModelDom&&(Mt.delegateRun(this.oCurrentSubScreen,"onHide"),this.oCurrentSubScreen.viewModelDom.hide())},Tt.prototype.onBuild=function(){r.each(_t.settings,function(e){e&&e.__rlSettingsData&&!r.find(_t["settings-removed"],function(t){return t&&t===e})&&this.menu.push({route:e.__rlSettingsData.Route,label:e.__rlSettingsData.Label,selected:s.observable(!1),disabled:!!r.find(_t["settings-disabled"],function(t){return t&&t===e})})},this),this.oViewModelPlace=t("#rl-content #rl-settings-subscreen")},Tt.prototype.routes=function(){var e=r.find(_t.settings,function(e){return e&&e.__rlSettingsData&&e.__rlSettingsData.IsDefault}),t=e?e.__rlSettingsData.Route:"general",s={subname:/^(.*)$/,normalize_:function(e,s){return s.subname=Mt.isUnd(s.subname)?t:Mt.pString(s.subname),[s.subname]}};return[["{subname}/",s],["{subname}",s],["",s]]},r.extend(Ft.prototype,y.prototype),Ft.prototype.onShow=function(){jt.setTitle("")},r.extend(At.prototype,y.prototype),At.prototype.oLastRoute={},At.prototype.setNewTitle=function(){var e=jt.data().accountEmail(),t=jt.data().foldersInboxUnreadCount();jt.setTitle((""===e?"":(t>0?"("+t+") ":" ")+e+" - ")+Mt.i18n("TITLES/MAILBOX"))},At.prototype.onShow=function(){this.setNewTitle(),jt.data().keyScope(Lt.KeyState.MessageList)},At.prototype.onRoute=function(e,t,s,i){if(Mt.isUnd(i)?1:!i){var o=jt.data(),n=jt.cache().getFolderFullNameRaw(e),a=jt.cache().getFolderFromCacheList(n);a&&(o.currentFolder(a).messageListPage(t).messageListSearch(s),Lt.Layout.NoPreview===o.layout()&&o.message()&&o.message(null),jt.reloadMessageList())}else Lt.Layout.NoPreview!==jt.data().layout()||jt.data().message()||jt.historyBack()},At.prototype.onStart=function(){var e=jt.data(),t=function(){Mt.windowResize()};(jt.capa(Lt.Capa.AdditionalAccounts)||jt.capa(Lt.Capa.AdditionalIdentities))&&jt.accountsAndIdentities(),r.delay(function(){"INBOX"!==e.currentFolderFullNameRaw()&&jt.folderInformation("INBOX")},1e3),r.delay(function(){jt.quota()},5e3),r.delay(function(){jt.remote().appDelayStart(Mt.emptyFunction)},35e3),Bt.toggleClass("rl-no-preview-pane",Lt.Layout.NoPreview===e.layout()),e.folderList.subscribe(t),e.messageList.subscribe(t),e.message.subscribe(t),e.layout.subscribe(function(e){Bt.toggleClass("rl-no-preview-pane",Lt.Layout.NoPreview===e)}),e.foldersInboxUnreadCount.subscribe(function(){this.setNewTitle()},this)},At.prototype.routes=function(){var e=function(){return["Inbox",1,"",!0]},t=function(e,t){return t[0]=Mt.pString(t[0]),t[1]=Mt.pInt(t[1]),t[1]=0>=t[1]?1:t[1],t[2]=Mt.pString(t[2]),""===e&&(t[0]="Inbox",t[1]=1),[decodeURI(t[0]),t[1],decodeURI(t[2]),!1]},s=function(e,t){return t[0]=Mt.pString(t[0]),t[1]=Mt.pString(t[1]),""===e&&(t[0]="Inbox"),[decodeURI(t[0]),1,decodeURI(t[1]),!1]};return[[/^([a-zA-Z0-9]+)\/p([1-9][0-9]*)\/(.+)\/?$/,{normalize_:t}],[/^([a-zA-Z0-9]+)\/p([1-9][0-9]*)$/,{normalize_:t}],[/^([a-zA-Z0-9]+)\/(.+)\/?$/,{normalize_:s}],[/^message-preview$/,{normalize_:e}],[/^([^\/]*)$/,{normalize_:t}]]},r.extend(Et.prototype,Tt.prototype),Et.prototype.onShow=function(){jt.setTitle(this.sSettingsTitle),jt.data().keyScope(Lt.KeyState.Settings)},r.extend(Nt.prototype,f.prototype),Nt.prototype.oSettings=null,Nt.prototype.oPlugins=null,Nt.prototype.oLocal=null,Nt.prototype.oLink=null,Nt.prototype.oSubs={},Nt.prototype.download=function(t){var s=null,i=null,o=navigator.userAgent.toLowerCase();return o&&(o.indexOf("chrome")>-1||o.indexOf("chrome")>-1)&&(s=document.createElement("a"),s.href=t,document.createEvent&&(i=document.createEvent("MouseEvents"),i&&i.initEvent&&s.dispatchEvent))?(i.initEvent("click",!0,!0),s.dispatchEvent(i),!0):(Ot.bMobileDevice?(e.open(t,"_self"),e.focus()):this.iframe.attr("src",t),!0)},Nt.prototype.link=function(){return null===this.oLink&&(this.oLink=new u),this.oLink},Nt.prototype.local=function(){return null===this.oLocal&&(this.oLocal=new g),this.oLocal},Nt.prototype.settingsGet=function(e){return null===this.oSettings&&(this.oSettings=Mt.isNormal(Vt)?Vt:{}),Mt.isUnd(this.oSettings[e])?null:this.oSettings[e]},Nt.prototype.settingsSet=function(e,t){null===this.oSettings&&(this.oSettings=Mt.isNormal(Vt)?Vt:{}),this.oSettings[e]=t},Nt.prototype.setTitle=function(t){t=(Mt.isNormal(t)&&0d;d++)f.push({id:o[d][0],name:o[d][1],system:!1,seporator:!1,disabled:!1});for(m=!0,d=0,h=t.length;h>d;d++)p=t[d],(r?r.call(null,p):!0)&&(m&&0d;d++)p=s[d],(p.subScribed()||!p.existen)&&(r?r.call(null,p):!0)&&(Lt.FolderType.User===p.type()||!c||0=5?o:20,o=320>=o?o:320,e.setInterval(function(){jt.contactsSync()},6e4*o+5e3),r.delay(function(){jt.contactsSync()},5e3),r.delay(function(){jt.folderInformationMultiply(!0)},500),Dt.runHook("rl-start-user-screens"),jt.pub("rl.bootstart-user-screens"),jt.settingsGet("AccountSignMe")&&e.navigator.registerProtocolHandler&&r.delay(function(){try{e.navigator.registerProtocolHandler("mailto",e.location.protocol+"//"+e.location.host+e.location.pathname+"?mailto&to=%s",""+(jt.settingsGet("Title")||"RainLoop"))}catch(t){}jt.settingsGet("MailToEmail")&&jt.mailToHelper(jt.settingsGet("MailToEmail"))},500)):(xt.startScreens([Ft]),Dt.runHook("rl-start-login-screens"),jt.pub("rl.bootstart-login-screens")),e.SimplePace&&e.SimplePace.set(100),Ot.bMobileDevice||r.defer(function(){Mt.initLayoutResizer("#rl-left","#rl-right",Lt.ClientSideKeyName.FolderListSize)})},this))):(s=Mt.pString(jt.settingsGet("CustomLoginLink")),s?(xt.routeOff(),xt.setHash(jt.link().root(),!0),xt.routeOff(),r.defer(function(){e.location.href=s})):(xt.hideLoading(),xt.startScreens([Ft]),Dt.runHook("rl-start-login-screens"),jt.pub("rl.bootstart-login-screens"),e.SimplePace&&e.SimplePace.set(100))),n&&(e["rl_"+i+"_google_service"]=function(){jt.data().googleActions(!0),jt.socialUsers()}),a&&(e["rl_"+i+"_facebook_service"]=function(){jt.data().facebookActions(!0),jt.socialUsers()}),l&&(e["rl_"+i+"_twitter_service"]=function(){jt.data().twitterActions(!0),jt.socialUsers()}),jt.sub("interval.1m",function(){Ot.momentTrigger(!Ot.momentTrigger())}),Dt.runHook("rl-start-screens"),jt.pub("rl.bootstart-end")},jt=new Rt,Bt.addClass(Ot.bMobileDevice?"mobile":"no-mobile"),Gt.keydown(Mt.killCtrlAandS).keyup(Mt.killCtrlAandS),Gt.unload(function(){Ot.bUnload=!0}),Bt.on("click.dropdown.data-api",function(){Mt.detectDropdownVisibility()}),e.rl=e.rl||{},e.rl.addHook=Dt.addHook,e.rl.settingsGet=Dt.mainSettingsGet,e.rl.remoteRequest=Dt.remoteRequest,e.rl.pluginSettingsGet=Dt.settingsGet,e.rl.addSettingsViewModel=Mt.addSettingsViewModel,e.rl.createCommand=Mt.createCommand,e.rl.EmailModel=v,e.rl.Enums=Lt,e.__RLBOOT=function(s){t(function(){e.rainloopTEMPLATES&&e.rainloopTEMPLATES[0]?(t("#rl-templates").html(e.rainloopTEMPLATES[0]),r.delay(function(){e.rainloopAppData={},e.rainloopI18N={},e.rainloopTEMPLATES={},xt.setBoot(jt).bootstart(),Bt.removeClass("no-js rl-booted-trigger").addClass("rl-booted")},50)):s(!1),e.__RLBOOT=null})}}(window,jQuery,ko,crossroads,hasher,moment,Jua,_,ifvisible,key);
\ No newline at end of file
+!function e(t,s,o){function i(r,a){if(!s[r]){if(!t[r]){var l="function"==typeof require&&require;if(!a&&l)return l(r,!0);if(n)return n(r,!0);var c=new Error("Cannot find module '"+r+"'");throw c.code="MODULE_NOT_FOUND",c}var u=s[r]={exports:{}};t[r][0].call(u.exports,function(e){var s=t[r][1][e];return i(s?s:e)},u,u.exports,e,t,s,o)}return s[r].exports}for(var n="function"==typeof require&&require,r=0;r').appendTo("body"),a.on("error",function(t){t&&t.originalEvent&&t.originalEvent.message&&-1===u.inArray(t.originalEvent.message,["Script error.","Uncaught Error: Error calling method on NPObject."])&&e.jsError(u.emptyFunction,t.originalEvent.message,t.originalEvent.filename,t.originalEvent.lineno,n.location&&n.location.toString?n.location.toString():"",r.attr("class"),u.microtime()-c.now)}),l.on("keydown",function(e){e&&e.ctrlKey&&r.addClass("rl-ctrl-key-pressed")}).on("keyup",function(e){e&&!e.ctrlKey&&r.removeClass("rl-ctrl-key-pressed")})}var o=e("../External/jquery.js"),i=e("../External/underscore.js"),n=e("../External/window.js"),r=e("../External/$html.js"),a=e("../External/$window.js"),l=e("../External/$doc.js"),c=e("../Common/Globals.js"),u=e("../Common/Utils.js"),d=e("../Common/LinkBuilder.js"),p=e("../Common/Events.js"),h=e("../Storages/AppSettings.js"),m=e("../Knoin/Knoin.js"),g=e("../Knoin/KnoinAbstractBoot.js");i.extend(s.prototype,g.prototype),s.prototype.remote=function(){return null},s.prototype.data=function(){return null},s.prototype.setupSettings=function(){return!0},s.prototype.download=function(e){var t=null,s=null,o=n.navigator.userAgent.toLowerCase();return o&&(o.indexOf("chrome")>-1||o.indexOf("chrome")>-1)&&(s=n.document.createElement("a"),s.href=e,n.document.createEvent&&(t=n.document.createEvent("MouseEvents"),t&&t.initEvent&&s.dispatchEvent))?(t.initEvent("click",!0,!0),s.dispatchEvent(t),!0):(c.bMobileDevice?(n.open(e,"_self"),n.focus()):this.iframe.attr("src",e),!0)},s.prototype.setTitle=function(e){e=(u.isNormal(e)&&0=5?r:20,r=320>=r?r:320,o.setInterval(function(){e.contactsSync()},6e4*r+5e3),n.delay(function(){e.contactsSync()},5e3),n.delay(function(){e.folderInformationMultiply(!0)},500),u.runHook("rl-start-user-screens"),h.pub("rl.bootstart-user-screens"),g.settingsGet("AccountSignMe")&&o.navigator.registerProtocolHandler&&n.delay(function(){try{o.navigator.registerProtocolHandler("mailto",o.location.protocol+"//"+o.location.host+o.location.pathname+"?mailto&to=%s",""+(g.settingsGet("Title")||"RainLoop"))}catch(t){}g.settingsGet("MailToEmail")&&e.mailToHelper(g.settingsGet("MailToEmail"))},500)):(m.startScreens([A]),u.runHook("rl-start-login-screens"),h.pub("rl.bootstart-login-screens")),o.SimplePace&&o.SimplePace.set(100),l.bMobileDevice||n.defer(function(){d.initLayoutResizer("#rl-left","#rl-right",a.ClientSideKeyName.FolderListSize)})},this))):(t=d.pString(g.settingsGet("CustomLoginLink")),t?(m.routeOff(),m.setHash(p.root(),!0),m.routeOff(),n.defer(function(){o.location.href=t})):(m.hideLoading(),m.startScreens([A]),u.runHook("rl-start-login-screens"),h.pub("rl.bootstart-login-screens"),o.SimplePace&&o.SimplePace.set(100))),c&&(o["rl_"+s+"_google_service"]=function(){f.googleActions(!0),e.socialUsers()}),b&&(o["rl_"+s+"_facebook_service"]=function(){f.facebookActions(!0),e.socialUsers()}),S&&(o["rl_"+s+"_twitter_service"]=function(){f.twitterActions(!0),e.socialUsers()}),h.sub("interval.1m",function(){l.momentTrigger(!l.momentTrigger())}),u.runHook("rl-start-screens"),h.pub("rl.bootstart-end")},t.exports=new s}(t)},{"../Common/Consts.js":6,"../Common/Enums.js":7,"../Common/Events.js":8,"../Common/Globals.js":9,"../Common/LinkBuilder.js":10,"../Common/Plugins.js":12,"../Common/Utils.js":14,"../External/jquery.js":26,"../External/moment.js":29,"../External/underscore.js":31,"../External/window.js":32,"../Knoin/Knoin.js":33,"../Screens/LoginScreen.js":42,"../Screens/MailBoxScreen.js":43,"../Screens/SettingsScreen.js":44,"../Settings/SettingsAccounts.js":45,"../Settings/SettingsChangePassword.js":46,"../Settings/SettingsContacts.js":47,"../Settings/SettingsFilters.js":48,"../Settings/SettingsFolders.js":49,"../Settings/SettingsGeneral.js":50,"../Settings/SettingsIdentities.js":51,"../Settings/SettingsIdentity.js":52,"../Settings/SettingsOpenPGP.js":53,"../Settings/SettingsSecurity.js":54,"../Settings/SettingsSocial.js":55,"../Settings/SettingsThemes.js":56,"../Storages/AppSettings.js":59,"../Storages/WebMailAjaxRemoteStorage.js":63,"../Storages/WebMailCacheStorage.js":64,"../Storages/WebMailDataStorage.js":65,"../ViewModels/Popups/PopupsAskViewModel.js":74,"../ViewModels/Popups/PopupsComposeViewModel.js":75,"./AbstractApp.js":2}],5:[function(e,t){!function(e){"use strict";var t={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",urlsafe_encode:function(e){return t.encode(e).replace(/[+]/g,"-").replace(/[\/]/g,"_").replace(/[=]/g,".")},encode:function(e){var s,o,i,n,r,a,l,c="",u=0;for(e=t._utf8_encode(e);u>2,r=(3&s)<<4|o>>4,a=(15&o)<<2|i>>6,l=63&i,isNaN(o)?a=l=64:isNaN(i)&&(l=64),c=c+this._keyStr.charAt(n)+this._keyStr.charAt(r)+this._keyStr.charAt(a)+this._keyStr.charAt(l);return c},decode:function(e){var s,o,i,n,r,a,l,c="",u=0;for(e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");u>4,o=(15&r)<<4|a>>2,i=(3&a)<<6|l,c+=String.fromCharCode(s),64!==a&&(c+=String.fromCharCode(o)),64!==l&&(c+=String.fromCharCode(i));return t._utf8_decode(c)},_utf8_encode:function(e){e=e.replace(/\r\n/g,"\n");for(var t="",s=0,o=e.length,i=0;o>s;s++)i=e.charCodeAt(s),128>i?t+=String.fromCharCode(i):i>127&&2048>i?(t+=String.fromCharCode(i>>6|192),t+=String.fromCharCode(63&i|128)):(t+=String.fromCharCode(i>>12|224),t+=String.fromCharCode(i>>6&63|128),t+=String.fromCharCode(63&i|128));return t},_utf8_decode:function(e){for(var t="",s=0,o=0,i=0,n=0;so?(t+=String.fromCharCode(o),s++):o>191&&224>o?(i=e.charCodeAt(s+1),t+=String.fromCharCode((31&o)<<6|63&i),s+=2):(i=e.charCodeAt(s+1),n=e.charCodeAt(s+2),t+=String.fromCharCode((15&o)<<12|(63&i)<<6|63&n),s+=3);return t}};e.exports=t}(t)},{}],6:[function(e,t){!function(e){"use strict";var t={};t.Values={},t.DataImages={},t.Defaults={},t.Defaults.MessagesPerPage=20,t.Defaults.ContactsPerPage=50,t.Defaults.MessagesPerPageArray=[10,20,30,50,100],t.Defaults.DefaultAjaxTimeout=3e4,t.Defaults.SearchAjaxTimeout=3e5,t.Defaults.SendMessageAjaxTimeout=3e5,t.Defaults.SaveMessageAjaxTimeout=2e5,t.Defaults.ContactsSyncAjaxTimeout=2e5,t.Values.UnuseOptionValue="__UNUSE__",t.Values.ClientSideCookieIndexName="rlcsc",t.Values.ImapDefaulPort=143,t.Values.ImapDefaulSecurePort=993,t.Values.SmtpDefaulPort=25,t.Values.SmtpDefaulSecurePort=465,t.Values.MessageBodyCacheLimit=15,t.Values.AjaxErrorLimit=7,t.Values.TokenErrorLimit=10,t.DataImages.UserDotPic="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQIW2P8DwQACgAD/il4QJ8AAAAASUVORK5CYII=",t.DataImages.TranspPic="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQIW2NkAAIAAAoAAggA9GkAAAAASUVORK5CYII=",e.exports=t}(t)},{}],7:[function(e,t){!function(e){"use strict";var t={};t.StorageResultType={Success:"success",Abort:"abort",Error:"error",Unload:"unload"},t.State={Empty:10,Login:20,Auth:30},t.StateType={Webmail:0,Admin:1},t.Capa={Prem:"PREM",TwoFactor:"TWO_FACTOR",OpenPGP:"OPEN_PGP",Prefetch:"PREFETCH",Gravatar:"GRAVATAR",Themes:"THEMES",Filters:"FILTERS",AdditionalAccounts:"ADDITIONAL_ACCOUNTS",AdditionalIdentities:"ADDITIONAL_IDENTITIES"},t.KeyState={All:"all",None:"none",ContactList:"contact-list",MessageList:"message-list",FolderList:"folder-list",MessageView:"message-view",Compose:"compose",Settings:"settings",Menu:"menu",PopupComposeOpenPGP:"compose-open-pgp",PopupKeyboardShortcutsHelp:"popup-keyboard-shortcuts-help",PopupAsk:"popup-ask"},t.FolderType={Inbox:10,SentItems:11,Draft:12,Trash:13,Spam:14,Archive:15,NotSpam:80,User:99},t.LoginSignMeTypeAsString={DefaultOff:"defaultoff",DefaultOn:"defaulton",Unused:"unused"},t.LoginSignMeType={DefaultOff:0,DefaultOn:1,Unused:2},t.ComposeType={Empty:"empty",Reply:"reply",ReplyAll:"replyall",Forward:"forward",ForwardAsAttachment:"forward-as-attachment",Draft:"draft",EditAsNew:"editasnew"},t.UploadErrorCode={Normal:0,FileIsTooBig:1,FilePartiallyUploaded:2,FileNoUploaded:3,MissingTempFolder:4,FileOnSaveingError:5,FileType:98,Unknown:99},t.SetSystemFoldersNotification={None:0,Sent:1,Draft:2,Spam:3,Trash:4,Archive:5},t.ClientSideKeyName={FoldersLashHash:0,MessagesInboxLastHash:1,MailBoxListSize:2,ExpandedFolders:3,FolderListSize:4},t.EventKeyCode={Backspace:8,Tab:9,Enter:13,Esc:27,PageUp:33,PageDown:34,Left:37,Right:39,Up:38,Down:40,End:35,Home:36,Space:32,Insert:45,Delete:46,A:65,S:83},t.MessageSetAction={SetSeen:0,UnsetSeen:1,SetFlag:2,UnsetFlag:3},t.MessageSelectAction={All:0,None:1,Invert:2,Unseen:3,Seen:4,Flagged:5,Unflagged:6},t.DesktopNotifications={Allowed:0,NotAllowed:1,Denied:2,NotSupported:9},t.MessagePriority={Low:5,Normal:3,High:1},t.EditorDefaultType={Html:"Html",Plain:"Plain"},t.CustomThemeType={Light:"Light",Dark:"Dark"},t.ServerSecure={None:0,SSL:1,TLS:2},t.SearchDateType={All:-1,Days3:3,Days7:7,Month:30},t.EmailType={Defailt:0,Facebook:1,Google:2},t.SaveSettingsStep={Animate:-2,Idle:-1,TrueResult:1,FalseResult:0},t.InterfaceAnimation={None:"None",Normal:"Normal",Full:"Full"},t.Layout={NoPreview:0,SidePreview:1,BottomPreview:2},t.FilterConditionField={From:"From",To:"To",Recipient:"Recipient",Subject:"Subject"},t.FilterConditionType={Contains:"Contains",NotContains:"NotContains",EqualTo:"EqualTo",NotEqualTo:"NotEqualTo"},t.FiltersAction={None:"None",Move:"Move",Discard:"Discard",Forward:"Forward"},t.FilterRulesType={And:"And",Or:"Or"},t.SignedVerifyStatus={UnknownPublicKeys:-4,UnknownPrivateKey:-3,Unverified:-2,Error:-1,None:0,Success:1},t.ContactPropertyType={Unknown:0,FullName:10,FirstName:15,LastName:16,MiddleName:16,Nick:18,NamePrefix:20,NameSuffix:21,Email:30,Phone:31,Web:32,Birthday:40,Facebook:90,Skype:91,GitHub:92,Note:110,Custom:250},t.Notification={InvalidToken:101,AuthError:102,AccessError:103,ConnectionError:104,CaptchaError:105,SocialFacebookLoginAccessDisable:106,SocialTwitterLoginAccessDisable:107,SocialGoogleLoginAccessDisable:108,DomainNotAllowed:109,AccountNotAllowed:110,AccountTwoFactorAuthRequired:120,AccountTwoFactorAuthError:121,CouldNotSaveNewPassword:130,CurrentPasswordIncorrect:131,NewPasswordShort:132,NewPasswordWeak:133,NewPasswordForbidden:134,ContactsSyncError:140,CantGetMessageList:201,CantGetMessage:202,CantDeleteMessage:203,CantMoveMessage:204,CantCopyMessage:205,CantSaveMessage:301,CantSendMessage:302,InvalidRecipients:303,CantCreateFolder:400,CantRenameFolder:401,CantDeleteFolder:402,CantSubscribeFolder:403,CantUnsubscribeFolder:404,CantDeleteNonEmptyFolder:405,CantSaveSettings:501,CantSavePluginSettings:502,DomainAlreadyExists:601,CantInstallPackage:701,CantDeletePackage:702,InvalidPluginPackage:703,UnsupportedPluginPackage:704,LicensingServerIsUnavailable:710,LicensingExpired:711,LicensingBanned:712,DemoSendMessageError:750,AccountAlreadyExists:801,MailServerError:901,ClientViewError:902,InvalidInputArgument:903,UnknownNotification:999,UnknownError:999},e.exports=t}(t)},{}],8:[function(e,t){!function(t){"use strict";function s(){this.oSubs={}}var o=e("../External/underscore.js"),i=e("./Utils.js"),n=e("./Plugins.js");s.prototype.oSubs={},s.prototype.sub=function(e,t,s){return i.isUnd(this.oSubs[e])&&(this.oSubs[e]=[]),this.oSubs[e].push([t,s]),this},s.prototype.pub=function(e,t){return n.runHook("rl-pub",[e,t]),i.isUnd(this.oSubs[e])||o.each(this.oSubs[e],function(e){e[0]&&e[0].apply(e[1]||null,t||[])}),this},t.exports=new s}(t)},{"../External/underscore.js":31,"./Plugins.js":12,"./Utils.js":14}],9:[function(e,t){!function(t){"use strict";var s={},o=e("../External/window.js"),i=e("../External/ko.js"),n=e("../External/key.js"),r=e("../External/$html.js"),a=e("../Common/Enums.js"),l=e("../Common/Events.js");s.now=(new o.Date).getTime(),s.momentTrigger=i.observable(!0),s.dropdownVisibility=i.observable(!1).extend({rateLimit:0}),s.tooltipTrigger=i.observable(!1).extend({rateLimit:0}),s.langChangeTrigger=i.observable(!0),s.useKeyboardShortcuts=i.observable(!0),s.iAjaxErrorCount=0,s.iTokenErrorCount=0,s.iMessageBodyCacheCount=0,s.bUnload=!1,s.sUserAgent=(o.navigator.userAgent||"").toLowerCase(),s.bIsiOSDevice=-11&&(o=o.replace(/[\/]+$/,""),o+="/p"+t),""!==s&&(o=o.replace(/[\/]+$/,""),o+="/"+encodeURI(s)),o},s.prototype.phpInfo=function(){return this.sServer+"Info"},s.prototype.langLink=function(e){return this.sServer+"/Lang/0/"+encodeURI(e)+"/"+this.sVersion+"/"},s.prototype.exportContactsVcf=function(){return this.sServer+"/Raw/"+this.sSpecSuffix+"/ContactsVcf/"},s.prototype.exportContactsCsv=function(){return this.sServer+"/Raw/"+this.sSpecSuffix+"/ContactsCsv/"},s.prototype.emptyContactPic=function(){return this.sStaticPrefix+"css/images/empty-contact.png"},s.prototype.sound=function(e){return this.sStaticPrefix+"sounds/"+e},s.prototype.themePreviewLink=function(e){var t="rainloop/v/"+this.sVersion+"/";return"@custom"===e.substr(-7)&&(e=i.trim(e.substring(0,e.length-7)),t=""),t+"themes/"+encodeURI(e)+"/images/preview.png"},s.prototype.notificationMailIcon=function(){return this.sStaticPrefix+"css/images/icom-message-notification.png"},s.prototype.openPgpJs=function(){return this.sStaticPrefix+"js/openpgp.min.js"},s.prototype.socialGoogle=function(){return this.sServer+"SocialGoogle"+(""!==this.sSpecSuffix?"/"+this.sSpecSuffix+"/":"")},s.prototype.socialTwitter=function(){return this.sServer+"SocialTwitter"+(""!==this.sSpecSuffix?"/"+this.sSpecSuffix+"/":"")},s.prototype.socialFacebook=function(){return this.sServer+"SocialFacebook"+(""!==this.sSpecSuffix?"/"+this.sSpecSuffix+"/":"")},t.exports=new s}(t)},{"../External/window.js":32,"../Storages/AppSettings.js":59,"./Utils.js":14}],11:[function(e,t){!function(t){"use strict";function s(e,t,s,o){var i=this;i.editor=null,i.iBlurTimer=0,i.fOnBlur=t||null,i.fOnReady=s||null,i.fOnModeChange=o||null,i.$element=$(e),i.resize=_.throttle(_.bind(i.resize,i),100),i.init()}var o=e("../External/window.js"),i=e("./Globals.js"),n=e("../Storages/AppSettings.js");s.prototype.blurTrigger=function(){if(this.fOnBlur){var e=this;o.clearTimeout(e.iBlurTimer),e.iBlurTimer=o.setTimeout(function(){e.fOnBlur()},200)}},s.prototype.focusTrigger=function(){this.fOnBlur&&o.clearTimeout(this.iBlurTimer)},s.prototype.isHtml=function(){return this.editor?"wysiwyg"===this.editor.mode:!1},s.prototype.checkDirty=function(){return this.editor?this.editor.checkDirty():!1},s.prototype.resetDirty=function(){this.editor&&this.editor.resetDirty()},s.prototype.getData=function(e){return this.editor?"plain"===this.editor.mode&&this.editor.plugins.plain&&this.editor.__plain?this.editor.__plain.getRawData():e?''+this.editor.getData()+"":this.editor.getData():""},s.prototype.modeToggle=function(e){this.editor&&(e?"plain"===this.editor.mode&&this.editor.setMode("wysiwyg"):"wysiwyg"===this.editor.mode&&this.editor.setMode("plain"),this.resize())},s.prototype.setHtml=function(e,t){this.editor&&(this.modeToggle(!0),this.editor.setData(e),t&&this.focus())},s.prototype.setPlain=function(e,t){if(this.editor){if(this.modeToggle(!1),"plain"===this.editor.mode&&this.editor.plugins.plain&&this.editor.__plain)return this.editor.__plain.setRawData(e);this.editor.setData(e),t&&this.focus()}},s.prototype.init=function(){if(this.$element&&this.$element[0]){var e=this,t=function(){var t=i.oHtmlEditorDefaultConfig,s=n.settingsGet("Language"),r=!!n.settingsGet("AllowHtmlEditorSourceButton");r&&t.toolbarGroups&&!t.toolbarGroups.__SourceInited&&(t.toolbarGroups.__SourceInited=!0,t.toolbarGroups.push({name:"document",groups:["mode","document","doctools"]})),t.enterMode=o.CKEDITOR.ENTER_BR,t.shiftEnterMode=o.CKEDITOR.ENTER_BR,t.language=i.oHtmlEditorLangsMap[s]||"en",o.CKEDITOR.env&&(o.CKEDITOR.env.isCompatible=!0),e.editor=o.CKEDITOR.appendTo(e.$element[0],t),e.editor.on("key",function(e){return e&&e.data&&9===e.data.keyCode?!1:void 0}),e.editor.on("blur",function(){e.blurTrigger()}),e.editor.on("mode",function(){e.blurTrigger(),e.fOnModeChange&&e.fOnModeChange("plain"!==e.editor.mode)}),e.editor.on("focus",function(){e.focusTrigger()}),e.fOnReady&&e.editor.on("instanceReady",function(){e.editor.setKeystroke(o.CKEDITOR.CTRL+65,"selectAll"),e.fOnReady(),e.__resizable=!0,e.resize()})};o.CKEDITOR?t():o.__initEditor=t}},s.prototype.focus=function(){this.editor&&this.editor.focus()},s.prototype.blur=function(){this.editor&&this.editor.focusManager.blur(!0)},s.prototype.resize=function(){if(this.editor&&this.__resizable)try{this.editor.resize(this.$element.width(),this.$element.innerHeight())}catch(e){}},s.prototype.clear=function(e){this.setHtml("",e)},t.exports=s}(t)},{"../External/window.js":32,"../Storages/AppSettings.js":59,"./Globals.js":9}],12:[function(e,t){!function(t){"use strict";var s={__boot:null,__remote:null,__data:null},o=e("../External/underscore.js"),i=e("./Utils.js");s.oViewModelsHooks={},s.oSimpleHooks={},s.regViewModelHook=function(e,t){t&&(t.__hookName=e)},s.addHook=function(e,t){i.isFunc(t)&&(i.isArray(s.oSimpleHooks[e])||(s.oSimpleHooks[e]=[]),s.oSimpleHooks[e].push(t))},s.runHook=function(e,t){i.isArray(s.oSimpleHooks[e])&&(t=t||[],o.each(s.oSimpleHooks[e],function(e){e.apply(null,t)}))},s.mainSettingsGet=function(e){return s.__boot?s.__boot.settingsGet(e):null},s.remoteRequest=function(e,t,o,i,n,r){s.__remote&&s.__remote.defaultRequest(e,t,o,i,n,r)},s.settingsGet=function(e,t){var o=s.mainSettingsGet("Plugins");return o=o&&i.isUnd(o[e])?null:o[e],o?i.isUnd(o[t])?null:o[t]:null},t.exports=s}(t)},{"../External/underscore.js":31,"./Utils.js":14}],13:[function(e,t){!function(t){"use strict";function s(e,t,s,o,r,a){this.list=e,this.listChecked=n.computed(function(){return i.filter(this.list(),function(e){return e.checked()})},this).extend({rateLimit:0}),this.isListChecked=n.computed(function(){return 00&&-10)return i.newSelectPosition(s,r.shift),!1}})}},s.prototype.autoSelect=function(e){this.bAutoSelect=!!e},s.prototype.getItemUid=function(e){var t="",s=this.oCallbacks.onItemGetUid||null;return s&&e&&(t=s(e)),t.toString()},s.prototype.newSelectPosition=function(e,t,s){var o=0,n=10,r=!1,l=!1,c=null,u=this.list(),d=u?u.length:0,p=this.focusedItem();if(d>0)if(p){if(p)if(a.EventKeyCode.Down===e||a.EventKeyCode.Up===e||a.EventKeyCode.Insert===e||a.EventKeyCode.Space===e)i.each(u,function(t){if(!l)switch(e){case a.EventKeyCode.Up:p===t?l=!0:c=t;break;case a.EventKeyCode.Down:case a.EventKeyCode.Insert:r?(c=t,l=!0):p===t&&(r=!0)}});else if(a.EventKeyCode.Home===e||a.EventKeyCode.End===e)a.EventKeyCode.Home===e?c=u[0]:a.EventKeyCode.End===e&&(c=u[u.length-1]);else if(a.EventKeyCode.PageDown===e){for(;d>o;o++)if(p===u[o]){o+=n,o=o>d-1?d-1:o,c=u[o];break}}else if(a.EventKeyCode.PageUp===e)for(o=d;o>=0;o--)if(p===u[o]){o-=n,o=0>o?0:o,c=u[o];break}}else a.EventKeyCode.Down===e||a.EventKeyCode.Insert===e||a.EventKeyCode.Space===e||a.EventKeyCode.Home===e||a.EventKeyCode.PageUp===e?c=u[0]:(a.EventKeyCode.Up===e||a.EventKeyCode.End===e||a.EventKeyCode.PageDown===e)&&(c=u[u.length-1]);c?(this.focusedItem(c),p&&(t?(a.EventKeyCode.Up===e||a.EventKeyCode.Down===e)&&p.checked(!p.checked()):(a.EventKeyCode.Insert===e||a.EventKeyCode.Space===e)&&p.checked(!p.checked())),!this.bAutoSelect&&!s||this.isListChecked()||a.EventKeyCode.Space===e||this.selectedItem(c),this.scrollToFocused()):p&&(!t||a.EventKeyCode.Up!==e&&a.EventKeyCode.Down!==e?(a.EventKeyCode.Insert===e||a.EventKeyCode.Space===e)&&p.checked(!p.checked()):p.checked(!p.checked()),this.focusedItem(p))},s.prototype.scrollToFocused=function(){if(!this.oContentVisible||!this.oContentScrollable)return!1;var e=20,t=o(this.sItemFocusedSelector,this.oContentScrollable),s=t.position(),i=this.oContentVisible.height(),n=t.outerHeight();return s&&(s.top<0||s.top+n>i)?(this.oContentScrollable.scrollTop(s.top<0?this.oContentScrollable.scrollTop()+s.top-e:this.oContentScrollable.scrollTop()+s.top-i+n+e),!0):!1},s.prototype.scrollToTop=function(e){return this.oContentVisible&&this.oContentScrollable?(e?this.oContentScrollable.scrollTop(0):this.oContentScrollable.stop().animate({scrollTop:0},200),!0):!1},s.prototype.eventClickFunction=function(e,t){var s=this.getItemUid(e),o=0,i=0,n=null,r="",a=!1,l=!1,c=[],u=!1;if(t&&t.shiftKey&&""!==s&&""!==this.sLastUid&&s!==this.sLastUid)for(c=this.list(),u=e.checked(),o=0,i=c.length;i>o;o++)n=c[o],r=this.getItemUid(n),a=!1,(r===this.sLastUid||r===s)&&(a=!0),a&&(l=!l),(l||a)&&n.checked(u);this.sLastUid=""===s?"":s},s.prototype.actionClick=function(e,t){if(e){var s=!0,o=this.getItemUid(e);t&&(!t.shiftKey||t.ctrlKey||t.altKey?!t.ctrlKey||t.shiftKey||t.altKey||(s=!1,this.focusedItem(e),this.selectedItem()&&e!==this.selectedItem()&&this.selectedItem().checked(!0),e.checked(!e.checked())):(s=!1,""===this.sLastUid&&(this.sLastUid=o),e.checked(!e.checked()),this.eventClickFunction(e,t),this.focusedItem(e))),s&&(this.focusedItem(e),this.selectedItem(e),this.scrollToFocused())}},s.prototype.on=function(e,t){this.oCallbacks[e]=t},t.exports=s}(t)},{"../External/jquery.js":26,"../External/key.js":27,"../External/ko.js":28,"../External/underscore.js":31,"./Enums.js":7,"./Utils.js":14}],14:[function(e,t){!function(t){"use strict";var s={},o=e("../External/jquery.js"),i=e("../External/underscore.js"),n=e("../External/ko.js"),r=e("../External/window.js"),a=e("../External/$window.js"),l=e("../External/$html.js"),c=e("../External/$doc.js"),u=e("../External/NotificationClass.js"),d=e("../Storages/LocalStorage.js"),p=e("../Knoin/Knoin.js"),h=e("./Enums.js"),m=e("./Consts.js"),g=e("./Globals.js"),f=e("./Events.js");s.trim=o.trim,s.inArray=o.inArray,s.isArray=i.isArray,s.isFunc=i.isFunction,s.isUnd=i.isUndefined,s.isNull=i.isNull,s.emptyFunction=function(){},s.isNormal=function(e){return!s.isUnd(e)&&!s.isNull(e)},s.windowResize=i.debounce(function(e){s.isUnd(e)?a.resize():r.setTimeout(function(){a.resize()},e)},50),s.isPosNumeric=function(e,t){return s.isNormal(e)?(s.isUnd(t)?0:!t)?/^[1-9]+[0-9]*$/.test(e.toString()):/^[0-9]*$/.test(e.toString()):!1},s.pInt=function(e,t){var o=s.isNormal(e)&&""!==e?r.parseInt(e,10):t||0;return r.isNaN(o)?t||0:o},s.pString=function(e){return s.isNormal(e)?""+e:""},s.isNonEmptyArray=function(e){return s.isArray(e)&&0i;i++)o=s[i].split("="),t[r.decodeURIComponent(o[0])]=r.decodeURIComponent(o[1]);return t},s.rsaEncode=function(e,t,o,i){if(r.crypto&&r.crypto.getRandomValues&&r.RSAKey&&t&&o&&i){var n=new r.RSAKey;if(n.setPublic(i,o),e=n.encrypt(s.fakeMd5()+":"+e+":"+s.fakeMd5()),!1!==e)return"rsa:"+t+":"+e}return!1},s.rsaEncode.supported=!!(r.crypto&&r.crypto.getRandomValues&&r.RSAKey),s.exportPath=function(e,t,o){for(var i=null,n=e.split("."),a=o||r;n.length&&(i=n.shift());)n.length||s.isUnd(t)?a=a[i]?a[i]:a[i]={}:a[i]=t},s.pImport=function(e,t,s){e[t]=s},s.pExport=function(e,t,o){return s.isUnd(e[t])?o:e[t]},s.encodeHtml=function(e){return s.isNormal(e)?e.toString().replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"):""},s.splitPlainText=function(e,t){var o="",i="",n=e,r=0,a=0;for(t=s.isUnd(t)?100:t;n.length>t;)i=n.substring(0,t),r=i.lastIndexOf(" "),a=i.lastIndexOf("\n"),-1!==a&&(r=a),-1===r&&(r=t),o+=i.substring(0,r)+"\n",n=n.substring(r+1);return o+n},s.timeOutAction=function(){var e={};return function(t,o,i){s.isUnd(e[t])&&(e[t]=0),r.clearTimeout(e[t]),e[t]=r.setTimeout(o,i)}}(),s.timeOutActionSecond=function(){var e={};return function(t,s,o){e[t]||(e[t]=r.setTimeout(function(){s(),e[t]=0},o))}}(),s.audio=function(){var e=!1;return function(t,s){if(!1===e)if(g.bIsiOSDevice)e=null;else{var o=!1,i=!1,n=r.Audio?new r.Audio:null;n&&n.canPlayType&&n.play?(o=""!==n.canPlayType('audio/mpeg; codecs="mp3"'),o||(i=""!==n.canPlayType('audio/ogg; codecs="vorbis"')),o||i?(e=n,e.preload="none",e.loop=!1,e.autoplay=!1,e.muted=!1,e.src=o?t:s):e=null):e=null}return e}}(),s.hos=function(e,t){return e&&r.Object&&r.Object.hasOwnProperty?r.Object.hasOwnProperty.call(e,t):!1},s.i18n=function(e,t,o){var i="",n=s.isUnd(g.oI18N[e])?s.isUnd(o)?e:o:g.oI18N[e];if(!s.isUnd(t)&&!s.isNull(t))for(i in t)s.hos(t,i)&&(n=n.replace("%"+i+"%",t[i]));return n},s.i18nToNode=function(e){i.defer(function(){o(".i18n",e).each(function(){var e=o(this),t="";t=e.data("i18n-text"),t?e.text(s.i18n(t)):(t=e.data("i18n-html"),t&&e.html(s.i18n(t)),t=e.data("i18n-placeholder"),t&&e.attr("placeholder",s.i18n(t)),t=e.data("i18n-title"),t&&e.attr("title",s.i18n(t)))})})},s.i18nReload=function(){r.rainloopI18N&&(g.oI18N=r.rainloopI18N||{},s.i18nToNode(c),g.langChangeTrigger(!g.langChangeTrigger())),r.rainloopI18N=null},s.initOnStartOrLangChange=function(e,t,s){e&&e.call(t),s?g.langChangeTrigger.subscribe(function(){e&&e.call(t),s.call(t)}):e&&g.langChangeTrigger.subscribe(e,t)},s.inFocus=function(){return document.activeElement?(s.isUnd(document.activeElement.__inFocusCache)&&(document.activeElement.__inFocusCache=o(document.activeElement).is("input,textarea,iframe,.cke_editable")),!!document.activeElement.__inFocusCache):!1},s.removeInFocus=function(){if(document&&document.activeElement&&document.activeElement.blur){var e=o(document.activeElement);e.is("input,textarea")&&document.activeElement.blur()}},s.removeSelection=function(){if(r&&r.getSelection){var e=r.getSelection();e&&e.removeAllRanges&&e.removeAllRanges()}else document&&document.selection&&document.selection.empty&&document.selection.empty()},s.replySubjectAdd=function(e,t){e=s.trim(e.toUpperCase()),t=s.trim(t.replace(/[\s]+/," "));var o=0,i="",n=!1,r="",a=[],l=[],c="RE"===e,u="FWD"===e,d=!u;if(""!==t){for(n=!1,l=t.split(":"),o=0;o0);return e.replace(/[\s]+/," ")},s._replySubjectAdd_=function(e,t,o){var i=null,n=s.trim(t);return n=null===(i=new r.RegExp("^"+e+"[\\s]?\\:(.*)$","gi").exec(t))||s.isUnd(i[1])?null===(i=new r.RegExp("^("+e+"[\\s]?[\\[\\(]?)([\\d]+)([\\]\\)]?[\\s]?\\:.*)$","gi").exec(t))||s.isUnd(i[1])||s.isUnd(i[2])||s.isUnd(i[3])?e+": "+t:i[1]+(s.pInt(i[2])+1)+i[3]:e+"[2]: "+i[1],n=n.replace(/[\s]+/g," "),n=(s.isUnd(o)?!0:o)?s.fixLongSubject(n):n},s._fixLongSubject_=function(e){var t=0,o=null;e=s.trim(e.replace(/[\s]+/," "));do o=/^Re(\[([\d]+)\]|):[\s]{0,3}Re(\[([\d]+)\]|):/gi.exec(e),(!o||s.isUnd(o[0]))&&(o=null),o&&(t=0,t+=s.isUnd(o[2])?1:0+s.pInt(o[2]),t+=s.isUnd(o[4])?1:0+s.pInt(o[4]),e=e.replace(/^Re(\[[\d]+\]|):[\s]{0,3}Re(\[[\d]+\]|):/gi,"Re"+(t>0?"["+t+"]":"")+":"));while(o);return e=e.replace(/[\s]+/," ")},s.roundNumber=function(e,t){return r.Math.round(e*r.Math.pow(10,t))/r.Math.pow(10,t)},s.friendlySize=function(e){return e=s.pInt(e),e>=1073741824?s.roundNumber(e/1073741824,1)+"GB":e>=1048576?s.roundNumber(e/1048576,1)+"MB":e>=1024?s.roundNumber(e/1024,0)+"KB":e+"B"},s.log=function(e){r.console&&r.console.log&&r.console.log(e)},s.getNotification=function(e,t){return e=s.pInt(e),h.Notification.ClientViewError===e&&t?t:s.isUnd(g.oNotificationI18N[e])?"":g.oNotificationI18N[e]},s.initNotificationLanguage=function(){var e=g.oNotificationI18N||{};e[h.Notification.InvalidToken]=s.i18n("NOTIFICATIONS/INVALID_TOKEN"),e[h.Notification.AuthError]=s.i18n("NOTIFICATIONS/AUTH_ERROR"),e[h.Notification.AccessError]=s.i18n("NOTIFICATIONS/ACCESS_ERROR"),e[h.Notification.ConnectionError]=s.i18n("NOTIFICATIONS/CONNECTION_ERROR"),e[h.Notification.CaptchaError]=s.i18n("NOTIFICATIONS/CAPTCHA_ERROR"),e[h.Notification.SocialFacebookLoginAccessDisable]=s.i18n("NOTIFICATIONS/SOCIAL_FACEBOOK_LOGIN_ACCESS_DISABLE"),e[h.Notification.SocialTwitterLoginAccessDisable]=s.i18n("NOTIFICATIONS/SOCIAL_TWITTER_LOGIN_ACCESS_DISABLE"),e[h.Notification.SocialGoogleLoginAccessDisable]=s.i18n("NOTIFICATIONS/SOCIAL_GOOGLE_LOGIN_ACCESS_DISABLE"),e[h.Notification.DomainNotAllowed]=s.i18n("NOTIFICATIONS/DOMAIN_NOT_ALLOWED"),e[h.Notification.AccountNotAllowed]=s.i18n("NOTIFICATIONS/ACCOUNT_NOT_ALLOWED"),e[h.Notification.AccountTwoFactorAuthRequired]=s.i18n("NOTIFICATIONS/ACCOUNT_TWO_FACTOR_AUTH_REQUIRED"),e[h.Notification.AccountTwoFactorAuthError]=s.i18n("NOTIFICATIONS/ACCOUNT_TWO_FACTOR_AUTH_ERROR"),e[h.Notification.CouldNotSaveNewPassword]=s.i18n("NOTIFICATIONS/COULD_NOT_SAVE_NEW_PASSWORD"),e[h.Notification.CurrentPasswordIncorrect]=s.i18n("NOTIFICATIONS/CURRENT_PASSWORD_INCORRECT"),e[h.Notification.NewPasswordShort]=s.i18n("NOTIFICATIONS/NEW_PASSWORD_SHORT"),e[h.Notification.NewPasswordWeak]=s.i18n("NOTIFICATIONS/NEW_PASSWORD_WEAK"),e[h.Notification.NewPasswordForbidden]=s.i18n("NOTIFICATIONS/NEW_PASSWORD_FORBIDDENT"),e[h.Notification.ContactsSyncError]=s.i18n("NOTIFICATIONS/CONTACTS_SYNC_ERROR"),e[h.Notification.CantGetMessageList]=s.i18n("NOTIFICATIONS/CANT_GET_MESSAGE_LIST"),e[h.Notification.CantGetMessage]=s.i18n("NOTIFICATIONS/CANT_GET_MESSAGE"),e[h.Notification.CantDeleteMessage]=s.i18n("NOTIFICATIONS/CANT_DELETE_MESSAGE"),e[h.Notification.CantMoveMessage]=s.i18n("NOTIFICATIONS/CANT_MOVE_MESSAGE"),e[h.Notification.CantCopyMessage]=s.i18n("NOTIFICATIONS/CANT_MOVE_MESSAGE"),e[h.Notification.CantSaveMessage]=s.i18n("NOTIFICATIONS/CANT_SAVE_MESSAGE"),e[h.Notification.CantSendMessage]=s.i18n("NOTIFICATIONS/CANT_SEND_MESSAGE"),e[h.Notification.InvalidRecipients]=s.i18n("NOTIFICATIONS/INVALID_RECIPIENTS"),e[h.Notification.CantCreateFolder]=s.i18n("NOTIFICATIONS/CANT_CREATE_FOLDER"),e[h.Notification.CantRenameFolder]=s.i18n("NOTIFICATIONS/CANT_RENAME_FOLDER"),e[h.Notification.CantDeleteFolder]=s.i18n("NOTIFICATIONS/CANT_DELETE_FOLDER"),e[h.Notification.CantDeleteNonEmptyFolder]=s.i18n("NOTIFICATIONS/CANT_DELETE_NON_EMPTY_FOLDER"),e[h.Notification.CantSubscribeFolder]=s.i18n("NOTIFICATIONS/CANT_SUBSCRIBE_FOLDER"),e[h.Notification.CantUnsubscribeFolder]=s.i18n("NOTIFICATIONS/CANT_UNSUBSCRIBE_FOLDER"),e[h.Notification.CantSaveSettings]=s.i18n("NOTIFICATIONS/CANT_SAVE_SETTINGS"),e[h.Notification.CantSavePluginSettings]=s.i18n("NOTIFICATIONS/CANT_SAVE_PLUGIN_SETTINGS"),e[h.Notification.DomainAlreadyExists]=s.i18n("NOTIFICATIONS/DOMAIN_ALREADY_EXISTS"),e[h.Notification.CantInstallPackage]=s.i18n("NOTIFICATIONS/CANT_INSTALL_PACKAGE"),e[h.Notification.CantDeletePackage]=s.i18n("NOTIFICATIONS/CANT_DELETE_PACKAGE"),e[h.Notification.InvalidPluginPackage]=s.i18n("NOTIFICATIONS/INVALID_PLUGIN_PACKAGE"),e[h.Notification.UnsupportedPluginPackage]=s.i18n("NOTIFICATIONS/UNSUPPORTED_PLUGIN_PACKAGE"),e[h.Notification.LicensingServerIsUnavailable]=s.i18n("NOTIFICATIONS/LICENSING_SERVER_IS_UNAVAILABLE"),e[h.Notification.LicensingExpired]=s.i18n("NOTIFICATIONS/LICENSING_EXPIRED"),e[h.Notification.LicensingBanned]=s.i18n("NOTIFICATIONS/LICENSING_BANNED"),e[h.Notification.DemoSendMessageError]=s.i18n("NOTIFICATIONS/DEMO_SEND_MESSAGE_ERROR"),e[h.Notification.AccountAlreadyExists]=s.i18n("NOTIFICATIONS/ACCOUNT_ALREADY_EXISTS"),e[h.Notification.MailServerError]=s.i18n("NOTIFICATIONS/MAIL_SERVER_ERROR"),e[h.Notification.InvalidInputArgument]=s.i18n("NOTIFICATIONS/INVALID_INPUT_ARGUMENT"),e[h.Notification.UnknownNotification]=s.i18n("NOTIFICATIONS/UNKNOWN_ERROR"),e[h.Notification.UnknownError]=s.i18n("NOTIFICATIONS/UNKNOWN_ERROR")},s.getUploadErrorDescByCode=function(e){var t="";switch(s.pInt(e)){case h.UploadErrorCode.FileIsTooBig:t=s.i18n("UPLOAD/ERROR_FILE_IS_TOO_BIG");break;case h.UploadErrorCode.FilePartiallyUploaded:t=s.i18n("UPLOAD/ERROR_FILE_PARTIALLY_UPLOADED");break;case h.UploadErrorCode.FileNoUploaded:t=s.i18n("UPLOAD/ERROR_NO_FILE_UPLOADED");break;case h.UploadErrorCode.MissingTempFolder:t=s.i18n("UPLOAD/ERROR_MISSING_TEMP_FOLDER");break;case h.UploadErrorCode.FileOnSaveingError:t=s.i18n("UPLOAD/ERROR_ON_SAVING_FILE");break;case h.UploadErrorCode.FileType:t=s.i18n("UPLOAD/ERROR_FILE_TYPE");break;default:t=s.i18n("UPLOAD/ERROR_UNKNOWN")}return t},s.delegateRun=function(e,t,o,n){e&&e[t]&&(n=s.pInt(n),0>=n?e[t].apply(e,s.isArray(o)?o:[]):i.delay(function(){e[t].apply(e,s.isArray(o)?o:[])},n))},s.killCtrlAandS=function(e){if(e=e||r.event,e&&e.ctrlKey&&!e.shiftKey&&!e.altKey){var t=e.target||e.srcElement,s=e.keyCode||e.which;if(s===h.EventKeyCode.S)return void e.preventDefault();if(t&&t.tagName&&t.tagName.match(/INPUT|TEXTAREA/i))return;s===h.EventKeyCode.A&&(r.getSelection?r.getSelection().removeAllRanges():r.document.selection&&r.document.selection.clear&&r.document.selection.clear(),e.preventDefault())}},s.createCommand=function(e,t,o){var i=t?function(){return i.canExecute&&i.canExecute()&&t.apply(e,Array.prototype.slice.call(arguments)),!1}:function(){};return i.enabled=n.observable(!0),o=s.isUnd(o)?!0:o,i.canExecute=n.computed(s.isFunc(o)?function(){return i.enabled()&&o.call(e)}:function(){return i.enabled()&&!!o}),i},s.initDataConstructorBySettings=function(e){e.editorDefaultType=n.observable(h.EditorDefaultType.Html),e.showImages=n.observable(!1),e.interfaceAnimation=n.observable(h.InterfaceAnimation.Full),e.contactsAutosave=n.observable(!1),g.sAnimationType=h.InterfaceAnimation.Full,e.capaThemes=n.observable(!1),e.allowLanguagesOnSettings=n.observable(!0),e.allowLanguagesOnLogin=n.observable(!0),e.useLocalProxyForExternalImages=n.observable(!1),e.desktopNotifications=n.observable(!1),e.useThreads=n.observable(!0),e.replySameFolder=n.observable(!0),e.useCheckboxesInList=n.observable(!0),e.layout=n.observable(h.Layout.SidePreview),e.usePreviewPane=n.computed(function(){return h.Layout.NoPreview!==e.layout()}),e.interfaceAnimation.subscribe(function(e){if(g.bMobileDevice||e===h.InterfaceAnimation.None)l.removeClass("rl-anim rl-anim-full").addClass("no-rl-anim"),g.sAnimationType=h.InterfaceAnimation.None;else switch(e){case h.InterfaceAnimation.Full:l.removeClass("no-rl-anim").addClass("rl-anim rl-anim-full"),g.sAnimationType=e;break;case h.InterfaceAnimation.Normal:l.removeClass("no-rl-anim rl-anim-full").addClass("rl-anim"),g.sAnimationType=e}}),e.interfaceAnimation.valueHasMutated(),e.desktopNotificationsPermisions=n.computed(function(){e.desktopNotifications();var t=h.DesktopNotifications.NotSupported;if(u&&u.permission)switch(u.permission.toLowerCase()){case"granted":t=h.DesktopNotifications.Allowed;break;case"denied":t=h.DesktopNotifications.Denied;break;case"default":t=h.DesktopNotifications.NotAllowed}else r.webkitNotifications&&r.webkitNotifications.checkPermission&&(t=r.webkitNotifications.checkPermission());return t}),e.useDesktopNotifications=n.computed({read:function(){return e.desktopNotifications()&&h.DesktopNotifications.Allowed===e.desktopNotificationsPermisions()},write:function(t){if(t){var s=e.desktopNotificationsPermisions();h.DesktopNotifications.Allowed===s?e.desktopNotifications(!0):h.DesktopNotifications.NotAllowed===s?u.requestPermission(function(){e.desktopNotifications.valueHasMutated(),h.DesktopNotifications.Allowed===e.desktopNotificationsPermisions()?e.desktopNotifications()?e.desktopNotifications.valueHasMutated():e.desktopNotifications(!0):e.desktopNotifications()?e.desktopNotifications(!1):e.desktopNotifications.valueHasMutated()}):e.desktopNotifications(!1)}else e.desktopNotifications(!1)}}),e.language=n.observable(""),e.languages=n.observableArray([]),e.mainLanguage=n.computed({read:e.language,write:function(t){t!==e.language()?-1=t.diff(o,"hours")?i:t.format("L")===o.format("L")?s.i18n("MESSAGE_LIST/TODAY_AT",{TIME:o.format("LT")}):t.clone().subtract("days",1).format("L")===o.format("L")?s.i18n("MESSAGE_LIST/YESTERDAY_AT",{TIME:o.format("LT")}):o.format(t.year()===o.year()?"D MMM.":"LL")},e)},s.isFolderExpanded=function(e){var t=d.get(h.ClientSideKeyName.ExpandedFolders);return i.isArray(t)&&-1!==i.indexOf(t,e)},s.setExpandedFolder=function(e,t){var s=d.get(h.ClientSideKeyName.ExpandedFolders);i.isArray(s)||(s=[]),t?(s.push(e),s=i.uniq(s)):s=i.without(s,e),d.set(h.ClientSideKeyName.ExpandedFolders,s)},s.initLayoutResizer=function(e,t,i){var n=60,r=155,a=o(e),l=o(t),c=d.get(i)||null,u=function(e){e&&(a.css({width:""+e+"px"}),l.css({left:""+e+"px"}))},p=function(e){if(e)a.resizable("disable"),u(n);else{a.resizable("enable");var t=s.pInt(d.get(i))||r;u(t>r?t:r)}},h=function(e,t){t&&t.size&&t.size.width&&(d.set(i,t.size.width),l.css({left:""+t.size.width+"px"}))};null!==c&&u(c>r?c:r),a.resizable({helper:"ui-resizable-helper",minWidth:r,maxWidth:350,handles:"e",stop:h}),f.sub("left-panel.off",function(){p(!0)}),f.sub("left-panel.on",function(){p(!1)})},s.initBlockquoteSwitcher=function(e){if(e){var t=o("blockquote:not(.rl-bq-switcher)",e).filter(function(){return 0===o(this).parent().closest("blockquote",e).length});t&&0100)&&(e.addClass("rl-bq-switcher hidden-bq"),o('').insertBefore(e).click(function(){e.toggleClass("hidden-bq"),s.windowResize()}).after("
").before("
"))})}},s.removeBlockquoteSwitcher=function(e){e&&(o(e).find("blockquote.rl-bq-switcher").each(function(){o(this).removeClass("rl-bq-switcher hidden-bq")}),o(e).find(".rlBlockquoteSwitcher").each(function(){o(this).remove()}))},s.toggleMessageBlockquote=function(e){e&&e.find(".rlBlockquoteSwitcher").click()},s.convertThemeName=function(e){return"@custom"===e.substr(-7)&&(e=s.trim(e.substring(0,e.length-7))),s.trim(e.replace(/[^a-zA-Z]+/g," ").replace(/([A-Z])/g," $1").replace(/[\s]+/g," "))},s.quoteName=function(e){return e.replace(/["]/g,'\\"')},s.microtime=function(){return(new Date).getTime()},s.convertLangName=function(e,t){return s.i18n("LANGS_NAMES"+(!0===t?"_EN":"")+"/LANG_"+e.toUpperCase().replace(/[^a-zA-Z0-9]+/,"_"),null,e)},s.fakeMd5=function(e){var t="",o="0123456789abcdefghijklmnopqrstuvwxyz";for(e=s.isUnd(e)?32:s.pInt(e);t.length>>32-t}function s(e,t){var s,o,i,n,r;return i=2147483648&e,n=2147483648&t,s=1073741824&e,o=1073741824&t,r=(1073741823&e)+(1073741823&t),s&o?2147483648^r^i^n:s|o?1073741824&r?3221225472^r^i^n:1073741824^r^i^n:r^i^n}function o(e,t,s){return e&t|~e&s}function i(e,t,s){return e&s|t&~s}function n(e,t,s){return e^t^s}function r(e,t,s){return t^(e|~s)}function a(e,i,n,r,a,l,c){return e=s(e,s(s(o(i,n,r),a),c)),s(t(e,l),i)}function l(e,o,n,r,a,l,c){return e=s(e,s(s(i(o,n,r),a),c)),s(t(e,l),o)}function c(e,o,i,r,a,l,c){return e=s(e,s(s(n(o,i,r),a),c)),s(t(e,l),o)}function u(e,o,i,n,a,l,c){return e=s(e,s(s(r(o,i,n),a),c)),s(t(e,l),o)}function d(e){for(var t,s=e.length,o=s+8,i=(o-o%64)/64,n=16*(i+1),r=Array(n-1),a=0,l=0;s>l;)t=(l-l%4)/4,a=l%4*8,r[t]=r[t]|e.charCodeAt(l)<>>29,r}function p(e){var t,s,o="",i="";for(s=0;3>=s;s++)t=e>>>8*s&255,i="0"+t.toString(16),o+=i.substr(i.length-2,2);return o}function h(e){e=e.replace(/rn/g,"n");for(var t="",s=0;so?t+=String.fromCharCode(o):o>127&&2048>o?(t+=String.fromCharCode(o>>6|192),t+=String.fromCharCode(63&o|128)):(t+=String.fromCharCode(o>>12|224),t+=String.fromCharCode(o>>6&63|128),t+=String.fromCharCode(63&o|128))}return t}var m,g,f,b,S,y,C,v,w,E=Array(),A=7,F=12,T=17,j=22,M=5,R=9,N=14,L=20,I=4,P=11,x=16,k=23,D=6,U=10,O=15,_=21;for(e=h(e),E=d(e),y=1732584193,C=4023233417,v=2562383102,w=271733878,m=0;m /g,">").replace(/")},s.draggeblePlace=function(){return o(' ').appendTo("#rl-hidden")},s.defautOptionsAfterRender=function(e,t){t&&!s.isUnd(t.disabled)&&e&&o(e).toggleClass("disabled",t.disabled).prop("disabled",t.disabled)},s.windowPopupKnockout=function(e,t,i,n){var a=null,l=r.open(""),c="__OpenerApplyBindingsUid"+s.fakeMd5()+"__",u=o("#"+t);r[c]=function(){if(l&&l.document.body&&u&&u[0]){var t=o(l.document.body);o("#rl-content",t).html(u.html()),o("html",l.document).addClass("external "+o("html").attr("class")),s.i18nToNode(t),p.applyExternal(e,o("#rl-content",t)[0]),r[c]=null,n(l)}},l.document.open(),l.document.write(''+s.encodeHtml(i)+' '),l.document.close(),a=l.document.createElement("script"),a.type="text/javascript",a.innerHTML="if(window&&window.opener&&window.opener['"+c+"']){window.opener['"+c+"']();window.opener['"+c+"']=null}",l.document.getElementsByTagName("head")[0].appendChild(a)},s.settingsSaveHelperFunction=function(e,t,o,n){return o=o||null,n=s.isUnd(n)?1e3:s.pInt(n),function(s,r,a,l,c){t.call(o,r&&r.Result?h.SaveSettingsStep.TrueResult:h.SaveSettingsStep.FalseResult),e&&e.call(o,s,r,a,l,c),i.delay(function(){t.call(o,h.SaveSettingsStep.Idle)},n)}},s.settingsSaveHelperSimpleFunction=function(e,t){return s.settingsSaveHelperFunction(null,e,t,1e3)},s.$div=o(""),s.htmlToPlain=function(e){var t=0,i=0,n=0,r=0,a=0,l="",c=function(e){for(var t=100,s="",o="",i=e,n=0,r=0;i.length>t;)o=i.substring(0,t),n=o.lastIndexOf(" "),r=o.lastIndexOf("\n"),-1!==r&&(n=r),-1===n&&(n=t),s+=o.substring(0,n)+"\n",i=i.substring(n+1);return s+i},u=function(e){return e=c(o.trim(e)),e="> "+e.replace(/\n/gm,"\n> "),e.replace(/(^|\n)([> ]+)/gm,function(){return arguments&&2]*>([\s\S\r\n]*)<\/div>/gim,d),e="\n"+o.trim(e)+"\n"),e}return""},p=function(){return arguments&&1 "):""},h=function(){return arguments&&1 /g,">"):""},m=function(){return arguments&&1]*>([\s\S\r\n]*)<\/pre>/gim,p).replace(/[\s]+/gm," ").replace(/((?:href|data)\s?=\s?)("[^"]+?"|'[^']+?')/gim,h).replace(/
]*>/gim,"\n").replace(/<\/h[\d]>/gi,"\n").replace(/<\/p>/gi,"\n\n").replace(/<\/li>/gi,"\n").replace(/<\/td>/gi,"\n").replace(/<\/tr>/gi,"\n").replace(/
]*>/gim,"\n_______________________________\n\n").replace(/]*>([\s\S\r\n]*)<\/div>/gim,d).replace(/]*>/gim,"\n__bq__start__\n").replace(/<\/blockquote>/gim,"\n__bq__end__\n").replace(/]*>([\s\S\r\n]*?)<\/a>/gim,m).replace(/<\/div>/gi,"\n").replace(/ /gi," ").replace(/"/gi,'"').replace(/<[^>]*>/gm,""),l=s.$div.html(l).text(),l=l.replace(/\n[ \t]+/gm,"\n").replace(/[\n]{3,}/gm,"\n\n").replace(/>/gi,">").replace(/</gi,"<").replace(/&/gi,"&"),t=0,a=100;a>0&&(a--,i=l.indexOf("__bq__start__",t),i>-1);)n=l.indexOf("__bq__start__",i+5),r=l.indexOf("__bq__end__",i+5),(-1===n||n>r)&&r>i?(l=l.substring(0,i)+u(l.substring(i+13,r))+l.substring(r+11),t=0):t=n>-1&&r>n?n-1:0;return l=l.replace(/__bq__start__/gm,"").replace(/__bq__end__/gm,"")},s.plainToHtml=function(e,t){e=e.toString().replace(/\r/g,"");var o=!1,i=!0,n=!0,r=[],a="",l=0,c=e.split("\n");do{for(i=!1,r=[],l=0;l"===a.substr(0,1),n&&!o?(i=!0,o=!0,r.push("~~~blockquote~~~"),r.push(a.substr(1))):!n&&o?(o=!1,r.push("~~~/blockquote~~~"),r.push(a)):r.push(n&&o?a.substr(1):a);o&&(o=!1,r.push("~~~/blockquote~~~")),c=r}while(i);return e=c.join("\n"),e=e.replace(/&/g,"&").replace(/>/g,">").replace(/").replace(/[\s]*~~~\/blockquote~~~/g,"
").replace(/[\-_~]{10,}/g,"
").replace(/\n/g,"
"),t?s.linkify(e):e},r.rainloop_Utils_htmlToPlain=s.htmlToPlain,r.rainloop_Utils_plainToHtml=s.plainToHtml,s.linkify=function(e){return o.fn&&o.fn.linkify&&(e=s.$div.html(e.replace(/&/gi,"amp_amp_12345_amp_amp")).linkify().find(".linkified").removeClass("linkified").end().html().replace(/amp_amp_12345_amp_amp/g,"&")),e},s.resizeAndCrop=function(e,t,s){var o=new r.Image;o.onload=function(){var e=[0,0],o=document.createElement("canvas"),i=o.getContext("2d");o.width=t,o.height=t,e=this.width>this.height?[this.width-this.height,0]:[0,this.height-this.width],i.fillStyle="#fff",i.fillRect(0,0,t,t),i.drawImage(this,e[0]/2,e[1]/2,this.width-e[0],this.height-e[1],0,0,t,t),s(o.toDataURL("image/jpeg"))},o.src=e},s.folderListOptionsBuilder=function(e,t,o,i,n,a,l,c,u,d){var p=null,m=!1,g=0,f=0,b="Â Â Â ",S=[];for(u=s.isNormal(u)?u:0g;g++)S.push({id:i[g][0],name:i[g][1],system:!1,seporator:!1,disabled:!1});for(m=!0,g=0,f=e.length;f>g;g++)p=e[g],(l?l.call(null,p):!0)&&(m&&0g;g++)p=t[g],(p.subScribed()||!p.existen)&&(l?l.call(null,p):!0)&&(h.FolderType.User===p.type()||!u||01||c>0&&l>c){for(l>c?(u(c),o=c,i=c):((3>=l||l>=c-2)&&(n+=2),u(l),o=l,i=l);n>0;)if(o-=1,i+=1,o>0&&(u(o,!1),n--),c>=i)u(i,!0),n--;else if(0>=o)break;3===o?u(2,!1):o>3&&u(r.Math.round((o-1)/2),!1,"..."),c-2===i?u(c-1,!0):c-2>i&&u(r.Math.round((c+i)/2),!0,"..."),o>1&&u(1,!1),c>i&&u(c,!0)}return a}},s.selectElement=function(e){if(r.getSelection){var t=r.getSelection();t.removeAllRanges();var s=r.document.createRange();s.selectNodeContents(e),t.addRange(s)}else if(r.document.selection){var o=r.document.body.createTextRange();o.moveToElementText(e),o.select()}},s.detectDropdownVisibility=i.debounce(function(){g.dropdownVisibility(!!i.find(g.aBootstrapDropdowns,function(e){return e.hasClass("open")}))},50),s.triggerAutocompleteInputChange=function(e){var t=function(){o(".checkAutocomplete").trigger("change")};e?i.delay(t,100):t()},t.exports=s}(t)},{"../External/$doc.js":16,"../External/$html.js":17,"../External/$window.js":18,"../External/NotificationClass.js":22,"../External/jquery.js":26,"../External/ko.js":28,"../External/underscore.js":31,"../External/window.js":32,"../Knoin/Knoin.js":33,"../Storages/LocalStorage.js":60,"./Consts.js":6,"./Enums.js":7,"./Events.js":8,"./Globals.js":9}],15:[function(e,t){"use strict";t.exports=e("./jquery.js")("")},{"./jquery.js":26}],16:[function(e,t){"use strict";t.exports=e("./jquery.js")(window.document)},{"./jquery.js":26}],17:[function(e,t){"use strict";t.exports=e("./jquery.js")("html")},{"./jquery.js":26}],18:[function(e,t){"use strict";t.exports=e("./jquery.js")(window)},{"./jquery.js":26}],19:[function(e,t){"use strict";t.exports=e("./window.js").rainloopAppData||{}},{"./window.js":32}],20:[function(e,t){"use strict";t.exports=JSON},{}],21:[function(e,t){"use strict";t.exports=Jua},{}],22:[function(e,t){"use strict";var s=e("./window.js");t.exports=s.Notification&&s.Notification.requestPermission?s.Notification:null},{"./window.js":32}],23:[function(e,t){"use strict";t.exports=crossroads},{}],24:[function(e,t){"use strict";t.exports=hasher},{}],25:[function(e,t){"use strict";t.exports=ifvisible},{}],26:[function(e,t){"use strict";t.exports=$},{}],27:[function(e,t){"use strict";t.exports=key},{}],28:[function(e,t){!function(t){"use strict";var s=e("./window.js"),o=e("./underscore.js"),i=e("./jquery.js"),n=e("./$window.js"),r=e("./$doc.js");ko.bindingHandlers.tooltip={init:function(t,s){var o=e("../Common/Globals.js"),n=e("../Common/Utils.js");if(!o.bMobileDevice){var r=i(t),a=r.data("tooltip-class")||"",l=r.data("tooltip-placement")||"top";r.tooltip({delay:{show:500,hide:100},html:!0,container:"body",placement:l,trigger:"hover",title:function(){return r.is(".disabled")||o.dropdownVisibility()?"":''+n.i18n(ko.utils.unwrapObservable(s()))+""}}).click(function(){r.tooltip("hide")}),o.tooltipTrigger.subscribe(function(){r.tooltip("hide")})}}},ko.bindingHandlers.tooltip2={init:function(t,s){var o=i(t),n=o.data("tooltip-class")||"",r=o.data("tooltip-placement")||"top",a=e("../Common/Globals.js");o.tooltip({delay:{show:500,hide:100},html:!0,container:"body",placement:r,title:function(){return o.is(".disabled")||a.dropdownVisibility()?"":''+s()()+""}}).click(function(){o.tooltip("hide")}),a.tooltipTrigger.subscribe(function(){o.tooltip("hide")})}},ko.bindingHandlers.tooltip3={init:function(t){var s=i(t),o=e("../Common/Globals.js");s.tooltip({container:"body",trigger:"hover manual",title:function(){return s.data("tooltip3-data")||""}}),r.click(function(){s.tooltip("hide")}),o.tooltipTrigger.subscribe(function(){s.tooltip("hide")})},update:function(e,t){var s=ko.utils.unwrapObservable(t());""===s?i(e).data("tooltip3-data","").tooltip("hide"):i(e).data("tooltip3-data",s).tooltip("show")}},ko.bindingHandlers.registrateBootstrapDropdown={init:function(t){var s=e("../Common/Globals.js");s.aBootstrapDropdowns.push(i(t))}},ko.bindingHandlers.openDropdownTrigger={update:function(t,s){if(ko.utils.unwrapObservable(s())){var o=i(t),n=e("../Common/Utils.js");o.hasClass("open")||(o.find(".dropdown-toggle").dropdown("toggle"),n.detectDropdownVisibility()),s()(!1)}}},ko.bindingHandlers.dropdownCloser={init:function(e){i(e).closest(".dropdown").on("click",".e-item",function(){i(e).dropdown("toggle")})}},ko.bindingHandlers.popover={init:function(e,t){i(e).popover(ko.utils.unwrapObservable(t()))}},ko.bindingHandlers.csstext={init:function(t,s){var o=e("../Common/Utils.js");t&&t.styleSheet&&!o.isUnd(t.styleSheet.cssText)?t.styleSheet.cssText=ko.utils.unwrapObservable(s()):i(t).text(ko.utils.unwrapObservable(s()))},update:function(t,s){var o=e("../Common/Utils.js");t&&t.styleSheet&&!o.isUnd(t.styleSheet.cssText)?t.styleSheet.cssText=ko.utils.unwrapObservable(s()):i(t).text(ko.utils.unwrapObservable(s()))}},ko.bindingHandlers.resizecrop={init:function(e){i(e).addClass("resizecrop").resizecrop({width:"100",height:"100",wrapperCSS:{"border-radius":"10px"}})},update:function(e,t){t()(),i(e).resizecrop({width:"100",height:"100"})}},ko.bindingHandlers.onEnter={init:function(e,t,o,n){i(e).on("keypress",function(o){o&&13===s.parseInt(o.keyCode,10)&&(i(e).trigger("change"),t().call(n))})}},ko.bindingHandlers.onEsc={init:function(e,t,o,n){i(e).on("keypress",function(o){o&&27===s.parseInt(o.keyCode,10)&&(i(e).trigger("change"),t().call(n))})}},ko.bindingHandlers.clickOnTrue={update:function(e,t){ko.utils.unwrapObservable(t())&&i(e).click()}},ko.bindingHandlers.modal={init:function(t,s){var o=e("../Common/Globals.js"),n=e("../Common/Utils.js");i(t).toggleClass("fade",!o.bMobileDevice).modal({keyboard:!1,show:ko.utils.unwrapObservable(s())}).on("shown",function(){n.windowResize()}).find(".close").click(function(){s()(!1)})},update:function(e,t){i(e).modal(ko.utils.unwrapObservable(t())?"show":"hide")}},ko.bindingHandlers.i18nInit={init:function(t){var s=e("../Common/Utils.js");s.i18nToNode(t)}},ko.bindingHandlers.i18nUpdate={update:function(t,s){var o=e("../Common/Utils.js");ko.utils.unwrapObservable(s()),o.i18nToNode(t)}},ko.bindingHandlers.link={update:function(e,t){i(e).attr("href",ko.utils.unwrapObservable(t()))}},ko.bindingHandlers.title={update:function(e,t){i(e).attr("title",ko.utils.unwrapObservable(t()))}},ko.bindingHandlers.textF={init:function(e,t){i(e).text(ko.utils.unwrapObservable(t()))}},ko.bindingHandlers.initDom={init:function(e,t){t()(e)}},ko.bindingHandlers.initResizeTrigger={init:function(e,t){var s=ko.utils.unwrapObservable(t());i(e).css({height:s[1],"min-height":s[1]})},update:function(t,s){var o=e("../Common/Utils.js"),r=ko.utils.unwrapObservable(s()),a=o.pInt(r[1]),l=0,c=i(t).offset().top;c>0&&(c+=o.pInt(r[2]),l=n.height()-c,l>a&&(a=l),i(t).css({height:a,"min-height":a}))}},ko.bindingHandlers.appendDom={update:function(e,t){i(e).hide().empty().append(ko.utils.unwrapObservable(t())).show()}},ko.bindingHandlers.draggable={init:function(t,o,n){var r=e("../Common/Globals.js"),a=e("../Common/Utils.js");if(!r.bMobileDevice){var l=100,c=3,u=n(),d=u&&u.droppableSelector?u.droppableSelector:"",p={distance:20,handle:".dragHandle",cursorAt:{top:22,left:3},refreshPositions:!0,scroll:!0};d&&(p.drag=function(e){i(d).each(function(){var t=null,o=null,n=i(this),r=n.offset(),u=r.top+n.height();s.clearInterval(n.data("timerScroll")),n.data("timerScroll",!1),e.pageX>=r.left&&e.pageX<=r.left+n.width()&&(e.pageY>=u-l&&e.pageY<=u&&(t=function(){n.scrollTop(n.scrollTop()+c),a.windowResize()},n.data("timerScroll",s.setInterval(t,10)),t()),e.pageY>=r.top&&e.pageY<=r.top+l&&(o=function(){n.scrollTop(n.scrollTop()-c),a.windowResize()},n.data("timerScroll",s.setInterval(o,10)),o()))})},p.stop=function(){i(d).each(function(){s.clearInterval(i(this).data("timerScroll")),i(this).data("timerScroll",!1)})}),p.helper=function(e){return o()(e&&e.target?ko.dataFor(e.target):null)},i(t).draggable(p).on("mousedown",function(){a.removeInFocus()})}}},ko.bindingHandlers.droppable={init:function(t,s,o){var n=e("../Common/Globals.js");if(!n.bMobileDevice){var r=s(),a=o(),l=a&&a.droppableOver?a.droppableOver:null,c=a&&a.droppableOut?a.droppableOut:null,u={tolerance:"pointer",hoverClass:"droppableHover"};r&&(u.drop=function(e,t){r(e,t)},l&&(u.over=function(e,t){l(e,t)}),c&&(u.out=function(e,t){c(e,t)}),i(t).droppable(u))}}},ko.bindingHandlers.nano={init:function(t){var s=e("../Common/Globals.js");s.bDisableNanoScroll||i(t).addClass("nano").nanoScroller({iOSNativeScrolling:!1,preventPageScrolling:!0})}},ko.bindingHandlers.saveTrigger={init:function(e){var t=i(e);t.data("save-trigger-type",t.is("input[type=text],input[type=email],input[type=password],select,textarea")?"input":"custom"),"custom"===t.data("save-trigger-type")?t.append(' ').addClass("settings-saved-trigger"):t.addClass("settings-saved-trigger-input")},update:function(e,t){var s=ko.utils.unwrapObservable(t()),o=i(e);if("custom"===o.data("save-trigger-type"))switch(s.toString()){case"1":o.find(".animated,.error").hide().removeClass("visible").end().find(".success").show().addClass("visible");break;case"0":o.find(".animated,.success").hide().removeClass("visible").end().find(".error").show().addClass("visible");break;case"-2":o.find(".error,.success").hide().removeClass("visible").end().find(".animated").show().addClass("visible");break;default:o.find(".animated").hide().end().find(".error,.success").removeClass("visible")}else switch(s.toString()){case"1":o.addClass("success").removeClass("error");break;case"0":o.addClass("error").removeClass("success");break;case"-2":break;default:o.removeClass("error success")}}},ko.bindingHandlers.emailsTags={init:function(t,s){var n=e("../Common/Utils.js"),r=i(t),a=s(),l=function(e){a&&a.focusTrigger&&a.focusTrigger(e)};r.inputosaurus({parseOnBlur:!0,allowDragAndDrop:!0,focusCallback:l,inputDelimiters:[",",";"],autoCompleteSource:function(e,t){RL.getAutocomplete(e.term,function(e){t(o.map(e,function(e){return e.toLine(!1)}))})},parseHook:function(e){return o.map(e,function(e){var t=n.trim(e),s=null;return""!==t?(s=new EmailModel,s.mailsoParse(t),s.clearDuplicateName(),[s.toLine(!1),s]):[t,null]})},change:o.bind(function(e){r.data("EmailsTagsValue",e.target.value),a(e.target.value)},this)})},update:function(e,t,s){var o=i(e),n=s(),r=n.emailsTagsFilter||null,a=ko.utils.unwrapObservable(t());o.data("EmailsTagsValue")!==a&&(o.val(a),o.data("EmailsTagsValue",a),o.inputosaurus("refresh")),r&&ko.utils.unwrapObservable(r)&&o.inputosaurus("focus")}},ko.bindingHandlers.contactTags={init:function(t,s){var n=e("../Common/Utils.js"),r=i(t),a=s(),l=function(e){a&&a.focusTrigger&&a.focusTrigger(e)};r.inputosaurus({parseOnBlur:!0,allowDragAndDrop:!1,focusCallback:l,inputDelimiters:[",",";"],outputDelimiter:",",autoCompleteSource:function(e,t){RL.getContactTagsAutocomplete(e.term,function(e){t(o.map(e,function(e){return e.toLine(!1)}))})},parseHook:function(e){return o.map(e,function(e){var t=n.trim(e),s=null;return""!==t?(s=new ContactTagModel,s.name(t),[s.toLine(!1),s]):[t,null]})},change:o.bind(function(e){r.data("ContactTagsValue",e.target.value),a(e.target.value)},this)})},update:function(e,t,s){var o=i(e),n=s(),r=n.contactTagsFilter||null,a=ko.utils.unwrapObservable(t());o.data("ContactTagsValue")!==a&&(o.val(a),o.data("ContactTagsValue",a),o.inputosaurus("refresh")),r&&ko.utils.unwrapObservable(r)&&o.inputosaurus("focus")}},ko.bindingHandlers.command={init:function(e,t,s,o){var n=i(e),r=t();if(!r||!r.enabled||!r.canExecute)throw new Error("You are not using command function");n.addClass("command"),ko.bindingHandlers[n.is("form")?"submit":"click"].init.apply(o,arguments)},update:function(e,t){var s=!0,o=i(e),n=t();s=n.enabled(),o.toggleClass("command-not-enabled",!s),s&&(s=n.canExecute(),o.toggleClass("command-can-not-be-execute",!s)),o.toggleClass("command-disabled disable disabled",!s).toggleClass("no-disabled",!!s),(o.is("input")||o.is("button"))&&o.prop("disabled",!s)}},ko.extenders.trimmer=function(t){var s=e("../Common/Utils.js"),o=ko.computed({read:t,write:function(e){t(s.trim(e.toString()))},owner:this});return o(t()),o},ko.extenders.posInterer=function(t,s){var o=e("../Common/Utils.js"),i=ko.computed({read:t,write:function(e){var i=o.pInt(e.toString(),s);0>=i&&(i=s),i===t()&&""+i!=""+e&&t(i+1),t(i)}});return i(t()),i},ko.extenders.reversible=function(e){var t=e();return e.commit=function(){t=e()},e.reverse=function(){e(t)},e.commitedValue=function(){return t},e},ko.extenders.toggleSubscribe=function(e,t){return e.subscribe(t[1],t[0],"beforeChange"),e.subscribe(t[2],t[0]),e},ko.extenders.falseTimeout=function(t,o){var i=e("../Common/Utils.js");return t.iTimeout=0,t.subscribe(function(e){e&&(s.clearTimeout(t.iTimeout),t.iTimeout=s.setTimeout(function(){t(!1),t.iTimeout=0},i.pInt(o)))}),t},ko.observable.fn.validateNone=function(){return this.hasError=ko.observable(!1),this},ko.observable.fn.validateEmail=function(){var t=e("../Common/Utils.js");return this.hasError=ko.observable(!1),this.subscribe(function(e){e=t.trim(e),this.hasError(""!==e&&!/^[^@\s]+@[^@\s]+$/.test(e))},this),this.valueHasMutated(),this},ko.observable.fn.validateSimpleEmail=function(){var t=e("../Common/Utils.js");return this.hasError=ko.observable(!1),this.subscribe(function(e){e=t.trim(e),this.hasError(""!==e&&!/^.+@.+$/.test(e))},this),this.valueHasMutated(),this},ko.observable.fn.validateFunc=function(t){var s=e("../Common/Utils.js");return this.hasFuncError=ko.observable(!1),s.isFunc(t)&&(this.subscribe(function(e){this.hasFuncError(!t(e))},this),this.valueHasMutated()),this},t.exports=ko}(t)},{"../Common/Globals.js":9,"../Common/Utils.js":14,"./$doc.js":16,"./$window.js":18,"./jquery.js":26,"./underscore.js":31,"./window.js":32}],29:[function(e,t){"use strict";t.exports=moment},{}],30:[function(e,t){"use strict";t.exports=ssm},{}],31:[function(e,t){"use strict";t.exports=_},{}],32:[function(e,t){"use strict";t.exports=window},{}],33:[function(e,t){!function(t){"use strict";function s(){this.sDefaultScreenName="",this.oScreens={},this.oCurrentScreen=null}var o=e("../External/jquery.js"),i=e("../External/underscore.js"),n=e("../External/ko.js"),r=e("../External/hasher.js"),a=e("../External/crossroads.js"),l=e("../External/$html.js"),c=e("../Common/Globals.js"),u=e("../Common/Plugins.js"),d=e("../Common/Utils.js"),p=e("../Knoin/KnoinAbstractViewModel.js");s.prototype.sDefaultScreenName="",s.prototype.oScreens={},s.prototype.oCurrentScreen=null,s.prototype.hideLoading=function(){o("#rl-loading").hide()},s.prototype.constructorEnd=function(e){d.isFunc(e.__constructor_end)&&e.__constructor_end.call(e)},s.prototype.extendAsViewModel=function(e,t,s){t&&(s||(s=p),t.__name=e,u.regViewModelHook(e,t),i.extend(t.prototype,s.prototype))},s.prototype.addSettingsViewModel=function(e,t,s,o,i){e.__rlSettingsData={Label:s,Template:t,Route:o,IsDefault:!!i},c.aViewModels.settings.push(e)},s.prototype.removeSettingsViewModel=function(e){c.aViewModels["settings-removed"].push(e)},s.prototype.disableSettingsViewModel=function(e){c.aViewModels["settings-disabled"].push(e)},s.prototype.routeOff=function(){r.changed.active=!1},s.prototype.routeOn=function(){r.changed.active=!0},s.prototype.screen=function(e){return""===e||d.isUnd(this.oScreens[e])?null:this.oScreens[e]},s.prototype.buildViewModel=function(e,t){if(e&&!e.__builded){var s=this,r=new e(t),a=r.viewModelPosition(),l=o("#rl-content #rl-"+a.toLowerCase()),p=null;e.__builded=!0,e.__vm=r,r.viewModelName=e.__name,l&&1===l.length?(p=o("").addClass("rl-view-model").addClass("RL-"+r.viewModelTemplate()).hide(),p.appendTo(l),r.viewModelDom=p,e.__dom=p,"Popups"===a&&(r.cancelCommand=r.closeCommand=d.createCommand(r,function(){s.hideScreenPopup(e)}),r.modalVisibility.subscribe(function(e){var t=this;e?(this.viewModelDom.show(),this.storeAndSetKeyScope(),c.popupVisibilityNames.push(this.viewModelName),r.viewModelDom.css("z-index",3e3+c.popupVisibilityNames().length+10),d.delegateRun(this,"onFocus",[],500)):(d.delegateRun(this,"onHide"),this.restoreKeyScope(),c.popupVisibilityNames.remove(this.viewModelName),r.viewModelDom.css("z-index",2e3),c.tooltipTrigger(!c.tooltipTrigger()),i.delay(function(){t.viewModelDom.hide()},300))},r)),u.runHook("view-model-pre-build",[e.__name,r,p]),n.applyBindingAccessorsToNode(p[0],{i18nInit:!0,template:function(){return{name:r.viewModelTemplate()}}},r),d.delegateRun(r,"onBuild",[p]),r&&"Popups"===a&&r.registerPopupKeyDown(),u.runHook("view-model-post-build",[e.__name,r,p])):d.log("Cannot find view model position: "+a)}return e?e.__vm:null},s.prototype.applyExternal=function(e,t){e&&t&&n.applyBindings(e,t)},s.prototype.hideScreenPopup=function(e){e&&e.__vm&&e.__dom&&(e.__vm.modalVisibility(!1),u.runHook("view-model-on-hide",[e.__name,e.__vm]))},s.prototype.showScreenPopup=function(e,t){e&&(this.buildViewModel(e),e.__vm&&e.__dom&&(e.__vm.modalVisibility(!0),d.delegateRun(e.__vm,"onShow",t||[]),u.runHook("view-model-on-show",[e.__name,e.__vm,t||[]])))},s.prototype.isPopupVisible=function(e){return e&&e.__vm?e.__vm.modalVisibility():!1},s.prototype.screenOnRoute=function(e,t){var s=this,o=null,n=null;""===d.pString(e)&&(e=this.sDefaultScreenName),""!==e&&(o=this.screen(e),o||(o=this.screen(this.sDefaultScreenName),o&&(t=e+"/"+t,e=this.sDefaultScreenName)),o&&o.__started&&(o.__builded||(o.__builded=!0,d.isNonEmptyArray(o.viewModels())&&i.each(o.viewModels(),function(e){this.buildViewModel(e,o)},this),d.delegateRun(o,"onBuild")),i.defer(function(){s.oCurrentScreen&&(d.delegateRun(s.oCurrentScreen,"onHide"),d.isNonEmptyArray(s.oCurrentScreen.viewModels())&&i.each(s.oCurrentScreen.viewModels(),function(e){e.__vm&&e.__dom&&"Popups"!==e.__vm.viewModelPosition()&&(e.__dom.hide(),e.__vm.viewModelVisibility(!1),d.delegateRun(e.__vm,"onHide"))})),s.oCurrentScreen=o,s.oCurrentScreen&&(d.delegateRun(s.oCurrentScreen,"onShow"),u.runHook("screen-on-show",[s.oCurrentScreen.screenName(),s.oCurrentScreen]),d.isNonEmptyArray(s.oCurrentScreen.viewModels())&&i.each(s.oCurrentScreen.viewModels(),function(e){e.__vm&&e.__dom&&"Popups"!==e.__vm.viewModelPosition()&&(e.__dom.show(),e.__vm.viewModelVisibility(!0),d.delegateRun(e.__vm,"onShow"),d.delegateRun(e.__vm,"onFocus",[],200),u.runHook("view-model-on-show",[e.__name,e.__vm]))},s)),n=o.__cross(),n&&n.parse(t)})))},s.prototype.startScreens=function(e){o("#rl-content").css({visibility:"hidden"}),i.each(e,function(e){var t=new e,s=t?t.screenName():"";t&&""!==s&&(""===this.sDefaultScreenName&&(this.sDefaultScreenName=s),this.oScreens[s]=t)
+},this),i.each(this.oScreens,function(e){e&&!e.__started&&e.__start&&(e.__started=!0,e.__start(),u.runHook("screen-pre-start",[e.screenName(),e]),d.delegateRun(e,"onStart"),u.runHook("screen-post-start",[e.screenName(),e]))},this);var t=a.create();t.addRoute(/^([a-zA-Z0-9\-]*)\/?(.*)$/,i.bind(this.screenOnRoute,this)),r.initialized.add(t.parse,t),r.changed.add(t.parse,t),r.init(),o("#rl-content").css({visibility:"visible"}),i.delay(function(){l.removeClass("rl-started-trigger").addClass("rl-started")},50)},s.prototype.setHash=function(e,t,s){e="#"===e.substr(0,1)?e.substr(1):e,e="/"===e.substr(0,1)?e.substr(1):e,s=d.isUnd(s)?!1:!!s,(d.isUnd(t)?1:!t)?(r.changed.active=!0,r[s?"replaceHash":"setHash"](e),r.setHash(e)):(r.changed.active=!1,r[s?"replaceHash":"setHash"](e),r.changed.active=!0)},t.exports=new s}(t)},{"../Common/Globals.js":9,"../Common/Plugins.js":12,"../Common/Utils.js":14,"../External/$html.js":17,"../External/crossroads.js":23,"../External/hasher.js":24,"../External/jquery.js":26,"../External/ko.js":28,"../External/underscore.js":31,"../Knoin/KnoinAbstractViewModel.js":36}],34:[function(e,t){!function(e){"use strict";function t(){}t.prototype.bootstart=function(){},e.exports=t}(t)},{}],35:[function(e,t){!function(t){"use strict";function s(e,t){this.sScreenName=e,this.aViewModels=i.isArray(t)?t:[]}var o=e("../External/crossroads.js"),i=e("../Common/Utils.js");s.prototype.oCross=null,s.prototype.sScreenName="",s.prototype.aViewModels=[],s.prototype.viewModels=function(){return this.aViewModels},s.prototype.screenName=function(){return this.sScreenName},s.prototype.routes=function(){return null},s.prototype.__cross=function(){return this.oCross},s.prototype.__start=function(){var e=this.routes(),t=null,s=null;i.isNonEmptyArray(e)&&(s=_.bind(this.onRoute||i.emptyFunction,this),t=o.create(),_.each(e,function(e){t.addRoute(e[0],s).rules=e[1]}),this.oCross=t)},t.exports=s}(t)},{"../Common/Utils.js":14,"../External/crossroads.js":23}],36:[function(e,t){!function(t){"use strict";function s(e,t){this.bDisabeCloseOnEsc=!1,this.sPosition=n.pString(e),this.sTemplate=n.pString(t),this.sDefaultKeyScope=r.KeyState.None,this.sCurrentKeyScope=this.sDefaultKeyScope,this.viewModelName="",this.viewModelVisibility=o.observable(!1),this.modalVisibility=o.observable(!1).extend({rateLimit:0}),this.viewModelDom=null}var o=e("../External/ko.js"),i=e("../External/$window.js"),n=e("../Common/Utils.js"),r=e("../Common/Enums.js"),a=e("../Common/Globals.js");s.prototype.sPosition="",s.prototype.sTemplate="",s.prototype.viewModelName="",s.prototype.viewModelDom=null,s.prototype.viewModelTemplate=function(){return this.sTemplate},s.prototype.viewModelPosition=function(){return this.sPosition},s.prototype.cancelCommand=s.prototype.closeCommand=function(){},s.prototype.storeAndSetKeyScope=function(){this.sCurrentKeyScope=a.keyScope(),a.keyScope(this.sDefaultKeyScope)},s.prototype.restoreKeyScope=function(){a.keyScope(this.sCurrentKeyScope)},s.prototype.registerPopupKeyDown=function(){var e=this;i.on("keydown",function(t){if(t&&e.modalVisibility&&e.modalVisibility()){if(!this.bDisabeCloseOnEsc&&r.EventKeyCode.Esc===t.keyCode)return n.delegateRun(e,"cancelCommand"),!1;if(r.EventKeyCode.Backspace===t.keyCode&&!n.inFocus())return!1}return!0})},t.exports=s}(t)},{"../Common/Enums.js":7,"../Common/Globals.js":9,"../Common/Utils.js":14,"../External/$window.js":18,"../External/ko.js":28}],37:[function(e,t){!function(t){"use strict";function s(){this.mimeType="",this.fileName="",this.estimatedSize=0,this.friendlySize="",this.isInline=!1,this.isLinked=!1,this.cid="",this.cidWithOutTags="",this.contentLocation="",this.download="",this.folder="",this.uid="",this.mimeIndex=""}var o=e("../External/window.js"),i=e("../Common/Globals.js"),n=e("../Common/Utils.js"),r=e("../Common/LinkBuilder.js");s.newInstanceFromJson=function(e){var t=new s;return t.initByJson(e)?t:null},s.prototype.mimeType="",s.prototype.fileName="",s.prototype.estimatedSize=0,s.prototype.friendlySize="",s.prototype.isInline=!1,s.prototype.isLinked=!1,s.prototype.cid="",s.prototype.cidWithOutTags="",s.prototype.contentLocation="",s.prototype.download="",s.prototype.folder="",s.prototype.uid="",s.prototype.mimeIndex="",s.prototype.initByJson=function(e){var t=!1;return e&&"Object/Attachment"===e["@Object"]&&(this.mimeType=(e.MimeType||"").toLowerCase(),this.fileName=e.FileName,this.estimatedSize=n.pInt(e.EstimatedSize),this.isInline=!!e.IsInline,this.isLinked=!!e.IsLinked,this.cid=e.CID,this.contentLocation=e.ContentLocation,this.download=e.Download,this.folder=e.Folder,this.uid=e.Uid,this.mimeIndex=e.MimeIndex,this.friendlySize=n.friendlySize(this.estimatedSize),this.cidWithOutTags=this.cid.replace(/^<+/,"").replace(/>+$/,""),t=!0),t},s.prototype.isImage=function(){return-1,]+)>?,? ?/g,s=t.exec(e);s?(this.name=s[1]||"",this.email=s[2]||"",this.clearDuplicateName()):/^[^@]+@[^@]+$/.test(e)&&(this.name="",this.email=e)},s.prototype.initByJson=function(e){var t=!1;return e&&"Object/Email"===e["@Object"]&&(this.name=i.trim(e.Name),this.email=i.trim(e.Email),t=""!==this.email,this.clearDuplicateName()),t},s.prototype.toLine=function(e,t,s){var o="";return""!==this.email&&(t=i.isUnd(t)?!1:!!t,s=i.isUnd(s)?!1:!!s,e&&""!==this.name?o=t?'")+'" target="_blank" tabindex="-1">'+i.encodeHtml(this.name)+"":s?i.encodeHtml(this.name):this.name:(o=this.email,""!==this.name?t?o=i.encodeHtml('"'+this.name+'" <')+'")+'" target="_blank" tabindex="-1">'+i.encodeHtml(o)+""+i.encodeHtml(">"):(o='"'+this.name+'" <'+o+">",s&&(o=i.encodeHtml(o))):t&&(o=''+i.encodeHtml(this.email)+""))),o},s.prototype.mailsoParse=function(e){if(e=i.trim(e),""===e)return!1;for(var t=function(e,t,s){e+="";var o=e.length;return 0>t&&(t+=o),o="undefined"==typeof s?o:0>s?s+o:s+t,t>=e.length||0>t||t>o?!1:e.slice(t,o)},s=function(e,t,s,o){return 0>s&&(s+=e.length),o=void 0!==o?o:e.length,0>o&&(o=o+e.length-s),e.slice(0,s)+t.substr(0,o)+t.slice(o)+e.slice(s+o)},o="",n="",r="",a=!1,l=!1,c=!1,u=null,d=0,p=0,h=0;h0&&0===o.length&&(o=t(e,0,h)),l=!0,d=h);break;case">":l&&(p=h,n=t(e,d+1,p-d-1),e=s(e,"",d,p-d+1),p=0,h=0,d=0,l=!1);break;case"(":a||l||c||(c=!0,d=h);break;case")":c&&(p=h,r=t(e,d+1,p-d-1),e=s(e,"",d,p-d+1),p=0,h=0,d=0,c=!1);break;case"\\":h++}h++}return 0===n.length&&(u=e.match(/[^@\s]+@\S+/i),u&&u[0]?n=u[0]:o=e),n.length>0&&0===o.length&&0===r.length&&(o=e.replace(n,"")),n=i.trim(n).replace(/^[<]+/,"").replace(/[>]+$/,""),o=i.trim(o).replace(/^["']+/,"").replace(/["']+$/,""),r=i.trim(r).replace(/^[(]+/,"").replace(/[)]+$/,""),o=o.replace(/\\\\(.)/,"$1"),r=r.replace(/\\\\(.)/,"$1"),this.name=o,this.email=n,this.clearDuplicateName(),!0},s.prototype.inputoTagLine=function(){return 00){if(r.FolderType.Draft===s)return""+e;if(t>0&&r.FolderType.Trash!==s&&r.FolderType.Archive!==s&&r.FolderType.SentItems!==s)return""+t}return""},this),this.canBeDeleted=i.computed(function(){var e=this.isSystemFolder();return!e&&0===this.subFolders().length&&"INBOX"!==this.fullNameRaw},this),this.canBeSubScribed=i.computed(function(){return!this.isSystemFolder()&&this.selectable&&"INBOX"!==this.fullNameRaw},this),this.visible.subscribe(function(){l.timeOutAction("folder-list-folder-visibility-change",function(){n.trigger("folder-list-folder-visibility-change")},100)}),this.localName=i.computed(function(){a.langChangeTrigger();var e=this.type(),t=this.name();if(this.isSystemFolder())switch(e){case r.FolderType.Inbox:t=l.i18n("FOLDER_LIST/INBOX_NAME");break;case r.FolderType.SentItems:t=l.i18n("FOLDER_LIST/SENT_NAME");break;case r.FolderType.Draft:t=l.i18n("FOLDER_LIST/DRAFTS_NAME");break;case r.FolderType.Spam:t=l.i18n("FOLDER_LIST/SPAM_NAME");break;case r.FolderType.Trash:t=l.i18n("FOLDER_LIST/TRASH_NAME");break;case r.FolderType.Archive:t=l.i18n("FOLDER_LIST/ARCHIVE_NAME")}return t},this),this.manageFolderSystemName=i.computed(function(){a.langChangeTrigger();var e="",t=this.type(),s=this.name();if(this.isSystemFolder())switch(t){case r.FolderType.Inbox:e="("+l.i18n("FOLDER_LIST/INBOX_NAME")+")";break;case r.FolderType.SentItems:e="("+l.i18n("FOLDER_LIST/SENT_NAME")+")";break;case r.FolderType.Draft:e="("+l.i18n("FOLDER_LIST/DRAFTS_NAME")+")";break;case r.FolderType.Spam:e="("+l.i18n("FOLDER_LIST/SPAM_NAME")+")";break;case r.FolderType.Trash:e="("+l.i18n("FOLDER_LIST/TRASH_NAME")+")";break;case r.FolderType.Archive:e="("+l.i18n("FOLDER_LIST/ARCHIVE_NAME")+")"}return(""!==e&&"("+s+")"===e||"(inbox)"===e.toLowerCase())&&(e=""),e},this),this.collapsed=i.computed({read:function(){return!this.hidden()&&this.collapsedPrivate()},write:function(e){this.collapsedPrivate(e)},owner:this}),this.hasUnreadMessages=i.computed(function(){return 0t?t:e))},this),this.body=null,this.plainRaw="",this.isHtml=r.observable(!1),this.hasImages=r.observable(!1),this.attachments=r.observableArray([]),this.isPgpSigned=r.observable(!1),this.isPgpEncrypted=r.observable(!1),this.pgpSignedVerifyStatus=r.observable(u.SignedVerifyStatus.None),this.pgpSignedVerifyUser=r.observable(""),this.priority=r.observable(u.MessagePriority.Normal),this.readReceipt=r.observable(""),this.aDraftInfo=[],this.sMessageId="",this.sInReplyTo="",this.sReferences="",this.parentUid=r.observable(0),this.threads=r.observableArray([]),this.threadsLen=r.observable(0),this.hasUnseenSubMessage=r.observable(!1),this.hasFlaggedSubMessage=r.observable(!1),this.lastInCollapsedThread=r.observable(!1),this.lastInCollapsedThreadLoading=r.observable(!1),this.threadsLenResult=r.computed(function(){var e=this.threadsLen();return 0===this.parentUid()&&e>0?e+1:""},this)}var o=e("../External/window.js"),i=e("../External/jquery.js"),n=e("../External/underscore.js"),r=e("../External/ko.js"),a=e("../External/moment.js"),l=e("../External/$window.js"),c=e("../External/$div.js"),u=e("../Common/Enums.js"),d=e("../Common/Utils.js"),p=e("../Common/LinkBuilder.js"),h=e("../Storages/WebMailDataStorage.js"),m=e("./EmailModel.js"),g=e("./AttachmentModel.js");s.newInstanceFromJson=function(e){var t=new s;return t.initByJson(e)?t:null},s.calculateFullFromatDateValue=function(e){return e>0?a.unix(e).format("LLL"):""},s.emailsToLine=function(e,t,s){var o=[],i=0,n=0;if(d.isNonEmptyArray(e))for(i=0,n=e.length;n>i;i++)o.push(e[i].toLine(t,s));return o.join(", ")},s.emailsToLineClear=function(e){var t=[],s=0,o=0;if(d.isNonEmptyArray(e))for(s=0,o=e.length;o>s;s++)e[s]&&e[s].email&&""!==e[s].name&&t.push(e[s].email);return t.join(", ")},s.initEmailsFromJson=function(e){var t=0,s=0,o=null,i=[];if(d.isNonEmptyArray(e))for(t=0,s=e.length;s>t;t++)o=m.newInstanceFromJson(e[t]),o&&i.push(o);return i},s.replyHelper=function(e,t,s){if(e&&0o;o++)d.isUnd(t[e[o].email])&&(t[e[o].email]=!0,s.push(e[o]))},s.prototype.clear=function(){this.folderFullNameRaw="",this.uid="",this.hash="",this.requestHash="",this.subject(""),this.subjectPrefix(""),this.subjectSuffix(""),this.size(0),this.dateTimeStampInUTC(0),this.priority(u.MessagePriority.Normal),this.proxy=!1,this.fromEmailString(""),this.fromClearEmailString(""),this.toEmailsString(""),this.toClearEmailsString(""),this.senderEmailsString(""),this.senderClearEmailsString(""),this.emails=[],this.from=[],this.to=[],this.cc=[],this.bcc=[],this.replyTo=[],this.deliveredTo=[],this.newForAnimation(!1),this.deleted(!1),this.unseen(!1),this.flagged(!1),this.answered(!1),this.forwarded(!1),this.isReadReceipt(!1),this.selected(!1),this.checked(!1),this.hasAttachments(!1),this.attachmentsMainType(""),this.body=null,this.isHtml(!1),this.hasImages(!1),this.attachments([]),this.isPgpSigned(!1),this.isPgpEncrypted(!1),this.pgpSignedVerifyStatus(u.SignedVerifyStatus.None),this.pgpSignedVerifyUser(""),this.priority(u.MessagePriority.Normal),this.readReceipt(""),this.aDraftInfo=[],this.sMessageId="",this.sInReplyTo="",this.sReferences="",this.parentUid(0),this.threads([]),this.threadsLen(0),this.hasUnseenSubMessage(!1),this.hasFlaggedSubMessage(!1),this.lastInCollapsedThread(!1),this.lastInCollapsedThreadLoading(!1)},s.prototype.computeSenderEmail=function(){var e=h.sentFolder(),t=h.draftFolder();this.senderEmailsString(this.folderFullNameRaw===e||this.folderFullNameRaw===t?this.toEmailsString():this.fromEmailString()),this.senderClearEmailsString(this.folderFullNameRaw===e||this.folderFullNameRaw===t?this.toClearEmailsString():this.fromClearEmailString())},s.prototype.initByJson=function(e){var t=!1;return e&&"Object/Message"===e["@Object"]&&(this.folderFullNameRaw=e.Folder,this.uid=e.Uid,this.hash=e.Hash,this.requestHash=e.RequestHash,this.proxy=!!e.ExternalProxy,this.size(d.pInt(e.Size)),this.from=s.initEmailsFromJson(e.From),this.to=s.initEmailsFromJson(e.To),this.cc=s.initEmailsFromJson(e.Cc),this.bcc=s.initEmailsFromJson(e.Bcc),this.replyTo=s.initEmailsFromJson(e.ReplyTo),this.deliveredTo=s.initEmailsFromJson(e.DeliveredTo),this.subject(e.Subject),d.isArray(e.SubjectParts)?(this.subjectPrefix(e.SubjectParts[0]),this.subjectSuffix(e.SubjectParts[1])):(this.subjectPrefix(""),this.subjectSuffix(this.subject())),this.dateTimeStampInUTC(d.pInt(e.DateTimeStampInUTC)),this.hasAttachments(!!e.HasAttachments),this.attachmentsMainType(e.AttachmentsMainType),this.fromEmailString(s.emailsToLine(this.from,!0)),this.fromClearEmailString(s.emailsToLineClear(this.from)),this.toEmailsString(s.emailsToLine(this.to,!0)),this.toClearEmailsString(s.emailsToLineClear(this.to)),this.parentUid(d.pInt(e.ParentThread)),this.threads(d.isArray(e.Threads)?e.Threads:[]),this.threadsLen(d.pInt(e.ThreadsLen)),this.initFlagsByJson(e),this.computeSenderEmail(),t=!0),t},s.prototype.initUpdateByMessageJson=function(e){var t=!1,s=u.MessagePriority.Normal;return e&&"Object/Message"===e["@Object"]&&(s=d.pInt(e.Priority),this.priority(-1t;t++)o=g.newInstanceFromJson(e["@Collection"][t]),o&&(""!==o.cidWithOutTags&&0 +$/,""),t=n.find(s,function(t){return e===t.cidWithOutTags})),t||null},s.prototype.findAttachmentByContentLocation=function(e){var t=null,s=this.attachments();return d.isNonEmptyArray(s)&&(t=n.find(s,function(t){return e===t.contentLocation})),t||null},s.prototype.messageId=function(){return this.sMessageId},s.prototype.inReplyTo=function(){return this.sInReplyTo},s.prototype.references=function(){return this.sReferences},s.prototype.fromAsSingleEmail=function(){return d.isArray(this.from)&&this.from[0]?this.from[0].email:""},s.prototype.viewLink=function(){return p.messageViewLink(this.requestHash)},s.prototype.downloadLink=function(){return p.messageDownloadLink(this.requestHash)},s.prototype.replyEmails=function(e){var t=[],o=d.isUnd(e)?{}:e;return s.replyHelper(this.replyTo,o,t),0===t.length&&s.replyHelper(this.from,o,t),t},s.prototype.replyAllEmails=function(e){var t=[],o=[],i=d.isUnd(e)?{}:e;return s.replyHelper(this.replyTo,i,t),0===t.length&&s.replyHelper(this.from,i,t),s.replyHelper(this.to,i,t),s.replyHelper(this.cc,i,o),[t,o]},s.prototype.textBodyToString=function(){return this.body?this.body.html():""},s.prototype.attachmentsToStringLine=function(){var e=n.map(this.attachments(),function(e){return e.fileName+" ("+e.friendlySize+")"});return e&&0=0&&o&&!n&&s.attr("src",o)}),e&&o.setTimeout(function(){t.print()},100))})},s.prototype.printMessage=function(){this.viewPopupMessage(!0)},s.prototype.generateUid=function(){return this.folderFullNameRaw+"/"+this.uid},s.prototype.populateByMessageListItem=function(e){return this.folderFullNameRaw=e.folderFullNameRaw,this.uid=e.uid,this.hash=e.hash,this.requestHash=e.requestHash,this.subject(e.subject()),this.subjectPrefix(this.subjectPrefix()),this.subjectSuffix(this.subjectSuffix()),this.size(e.size()),this.dateTimeStampInUTC(e.dateTimeStampInUTC()),this.priority(e.priority()),this.proxy=e.proxy,this.fromEmailString(e.fromEmailString()),this.fromClearEmailString(e.fromClearEmailString()),this.toEmailsString(e.toEmailsString()),this.toClearEmailsString(e.toClearEmailsString()),this.emails=e.emails,this.from=e.from,this.to=e.to,this.cc=e.cc,this.bcc=e.bcc,this.replyTo=e.replyTo,this.deliveredTo=e.deliveredTo,this.unseen(e.unseen()),this.flagged(e.flagged()),this.answered(e.answered()),this.forwarded(e.forwarded()),this.isReadReceipt(e.isReadReceipt()),this.selected(e.selected()),this.checked(e.checked()),this.hasAttachments(e.hasAttachments()),this.attachmentsMainType(e.attachmentsMainType()),this.moment(e.moment()),this.body=null,this.priority(u.MessagePriority.Normal),this.aDraftInfo=[],this.sMessageId="",this.sInReplyTo="",this.sReferences="",this.parentUid(e.parentUid()),this.threads(e.threads()),this.threadsLen(e.threadsLen()),this.computeSenderEmail(),this},s.prototype.showExternalImages=function(e){if(this.body&&this.body.data("rl-has-images")){var t="";e=d.isUnd(e)?!1:e,this.hasImages(!1),this.body.data("rl-has-images",!1),t=this.proxy?"data-x-additional-src":"data-x-src",i("["+t+"]",this.body).each(function(){e&&i(this).is("img")?i(this).addClass("lazy").attr("data-original",i(this).attr(t)).removeAttr(t):i(this).attr("src",i(this).attr(t)).removeAttr(t)}),t=this.proxy?"data-x-additional-style-url":"data-x-style-url",i("["+t+"]",this.body).each(function(){var e=d.trim(i(this).attr("style"));e=""===e?"":";"===e.substr(-1)?e+" ":e+"; ",i(this).attr("style",e+i(this).attr(t)).removeAttr(t)}),e&&(i("img.lazy",this.body).addClass("lazy-inited").lazyload({threshold:400,effect:"fadeIn",skip_invisible:!1,container:i(".RL-MailMessageView .messageView .messageItem .content")[0]}),l.resize()),d.windowResize(500)}},s.prototype.showInternalImages=function(e){if(this.body&&!this.body.data("rl-init-internal-images")){this.body.data("rl-init-internal-images",!0),e=d.isUnd(e)?!1:e;var t=this;i("[data-x-src-cid]",this.body).each(function(){var s=t.findAttachmentByCid(i(this).attr("data-x-src-cid"));s&&s.download&&(e&&i(this).is("img")?i(this).addClass("lazy").attr("data-original",s.linkPreview()):i(this).attr("src",s.linkPreview()))}),i("[data-x-src-location]",this.body).each(function(){var s=t.findAttachmentByContentLocation(i(this).attr("data-x-src-location"));s||(s=t.findAttachmentByCid(i(this).attr("data-x-src-location"))),s&&s.download&&(e&&i(this).is("img")?i(this).addClass("lazy").attr("data-original",s.linkPreview()):i(this).attr("src",s.linkPreview()))}),i("[data-x-style-cid]",this.body).each(function(){var e="",s="",o=t.findAttachmentByCid(i(this).attr("data-x-style-cid"));o&&o.linkPreview&&(s=i(this).attr("data-x-style-cid-name"),""!==s&&(e=d.trim(i(this).attr("style")),e=""===e?"":";"===e.substr(-1)?e+" ":e+"; ",i(this).attr("style",e+s+": url('"+o.linkPreview()+"')")))}),e&&!function(e,t){n.delay(function(){e.addClass("lazy-inited").lazyload({threshold:400,effect:"fadeIn",skip_invisible:!1,container:t})},300)}(i("img.lazy",t.body),i(".RL-MailMessageView .messageView .messageItem .content")[0]),d.windowResize(500)}},s.prototype.storeDataToDom=function(){this.body&&(this.body.data("rl-is-html",!!this.isHtml()),this.body.data("rl-has-images",!!this.hasImages()),this.body.data("rl-plain-raw",this.plainRaw),h.capaOpenPGP()&&(this.body.data("rl-plain-pgp-signed",!!this.isPgpSigned()),this.body.data("rl-plain-pgp-encrypted",!!this.isPgpEncrypted()),this.body.data("rl-pgp-verify-status",this.pgpSignedVerifyStatus()),this.body.data("rl-pgp-verify-user",this.pgpSignedVerifyUser())))
+},s.prototype.storePgpVerifyDataToDom=function(){this.body&&h.capaOpenPGP()&&(this.body.data("rl-pgp-verify-status",this.pgpSignedVerifyStatus()),this.body.data("rl-pgp-verify-user",this.pgpSignedVerifyUser()))},s.prototype.fetchDataToDom=function(){this.body&&(this.isHtml(!!this.body.data("rl-is-html")),this.hasImages(!!this.body.data("rl-has-images")),this.plainRaw=d.pString(this.body.data("rl-plain-raw")),h.capaOpenPGP()?(this.isPgpSigned(!!this.body.data("rl-plain-pgp-signed")),this.isPgpEncrypted(!!this.body.data("rl-plain-pgp-encrypted")),this.pgpSignedVerifyStatus(this.body.data("rl-pgp-verify-status")),this.pgpSignedVerifyUser(this.body.data("rl-pgp-verify-user"))):(this.isPgpSigned(!1),this.isPgpEncrypted(!1),this.pgpSignedVerifyStatus(u.SignedVerifyStatus.None),this.pgpSignedVerifyUser("")))},s.prototype.verifyPgpSignedClearMessage=function(){if(this.isPgpSigned()){var e=[],t=null,s=this.from&&this.from[0]&&this.from[0].email?this.from[0].email:"",r=h.findPublicKeysByEmail(s),a=null,l=null,d="";this.pgpSignedVerifyStatus(u.SignedVerifyStatus.Error),this.pgpSignedVerifyUser("");try{t=o.openpgp.cleartext.readArmored(this.plainRaw),t&&t.getText&&(this.pgpSignedVerifyStatus(r.length?u.SignedVerifyStatus.Unverified:u.SignedVerifyStatus.UnknownPublicKeys),e=t.verify(r),e&&0').text(d)).html(),c.empty(),this.replacePlaneTextBody(d)))))}catch(p){}this.storePgpVerifyDataToDom()}},s.prototype.decryptPgpEncryptedMessage=function(e){if(this.isPgpEncrypted()){var t=[],s=null,r=null,a=this.from&&this.from[0]&&this.from[0].email?this.from[0].email:"",l=h.findPublicKeysByEmail(a),d=h.findSelfPrivateKey(e),p=null,m=null,g="";this.pgpSignedVerifyStatus(u.SignedVerifyStatus.Error),this.pgpSignedVerifyUser(""),d||this.pgpSignedVerifyStatus(u.SignedVerifyStatus.UnknownPrivateKey);try{s=o.openpgp.message.readArmored(this.plainRaw),s&&d&&s.decrypt&&(this.pgpSignedVerifyStatus(u.SignedVerifyStatus.Unverified),r=s.decrypt(d),r&&(t=r.verify(l),t&&0').text(g)).html(),c.empty(),this.replacePlaneTextBody(g)))}catch(f){}this.storePgpVerifyDataToDom()}},s.prototype.replacePlaneTextBody=function(e){this.body&&this.body.html(e).addClass("b-text-part plain")},s.prototype.flagHash=function(){return[this.deleted(),this.unseen(),this.flagged(),this.answered(),this.forwarded(),this.isReadReceipt()].join("")},t.exports=s}(t)},{"../Common/Enums.js":7,"../Common/LinkBuilder.js":10,"../Common/Utils.js":14,"../External/$div.js":15,"../External/$window.js":18,"../External/jquery.js":26,"../External/ko.js":28,"../External/moment.js":29,"../External/underscore.js":31,"../External/window.js":32,"../Storages/WebMailDataStorage.js":65,"./AttachmentModel.js":37,"./EmailModel.js":38}],41:[function(e,t){!function(t){"use strict";function s(e){u.call(this,"settings",e),this.menu=n.observableArray([]),this.oCurrentSubScreen=null,this.oViewModelPlace=null}var o=e("../External/jquery.js"),i=e("../External/underscore.js"),n=e("../External/ko.js"),r=e("../Common/Globals.js"),a=e("../Common/Utils.js"),l=e("../Common/LinkBuilder.js"),c=e("../Knoin/Knoin.js"),u=e("../Knoin/KnoinAbstractScreen.js");i.extend(s.prototype,u.prototype),s.prototype.onRoute=function(e){var t=this,s=null,u=null,d=null,p=null;u=i.find(r.aViewModels.settings,function(t){return t&&t.__rlSettingsData&&e===t.__rlSettingsData.Route}),u&&(i.find(r.aViewModels["settings-removed"],function(e){return e&&e===u})&&(u=null),u&&i.find(r.aViewModels["settings-disabled"],function(e){return e&&e===u})&&(u=null)),u?(u.__builded&&u.__vm?s=u.__vm:(d=this.oViewModelPlace,d&&1===d.length?(u=u,s=new u,p=o("").addClass("rl-settings-view-model").hide(),p.appendTo(d),s.viewModelDom=p,s.__rlSettingsData=u.__rlSettingsData,u.__dom=p,u.__builded=!0,u.__vm=s,n.applyBindingAccessorsToNode(p[0],{i18nInit:!0,template:function(){return{name:u.__rlSettingsData.Template}}},s),a.delegateRun(s,"onBuild",[p])):a.log("Cannot find sub settings view model position: SettingsSubScreen")),s&&i.defer(function(){t.oCurrentSubScreen&&(a.delegateRun(t.oCurrentSubScreen,"onHide"),t.oCurrentSubScreen.viewModelDom.hide()),t.oCurrentSubScreen=s,t.oCurrentSubScreen&&(t.oCurrentSubScreen.viewModelDom.show(),a.delegateRun(t.oCurrentSubScreen,"onShow"),a.delegateRun(t.oCurrentSubScreen,"onFocus",[],200),i.each(t.menu(),function(e){e.selected(s&&s.__rlSettingsData&&e.route===s.__rlSettingsData.Route)}),o("#rl-content .b-settings .b-content .content").scrollTop(0)),a.windowResize()})):c.setHash(l.settings(),!1,!0)},s.prototype.onHide=function(){this.oCurrentSubScreen&&this.oCurrentSubScreen.viewModelDom&&(a.delegateRun(this.oCurrentSubScreen,"onHide"),this.oCurrentSubScreen.viewModelDom.hide())},s.prototype.onBuild=function(){i.each(r.aViewModels.settings,function(e){e&&e.__rlSettingsData&&!i.find(r.aViewModels["settings-removed"],function(t){return t&&t===e})&&this.menu.push({route:e.__rlSettingsData.Route,label:e.__rlSettingsData.Label,selected:n.observable(!1),disabled:!!i.find(r.aViewModels["settings-disabled"],function(t){return t&&t===e})})},this),this.oViewModelPlace=o("#rl-content #rl-settings-subscreen")},s.prototype.routes=function(){var e=i.find(r.aViewModels.settings,function(e){return e&&e.__rlSettingsData&&e.__rlSettingsData.IsDefault}),t=e?e.__rlSettingsData.Route:"general",s={subname:/^(.*)$/,normalize_:function(e,s){return s.subname=a.isUnd(s.subname)?t:a.pString(s.subname),[s.subname]}};return[["{subname}/",s],["{subname}",s],["",s]]},t.exports=s}(t)},{"../Common/Globals.js":9,"../Common/LinkBuilder.js":10,"../Common/Utils.js":14,"../External/jquery.js":26,"../External/ko.js":28,"../External/underscore.js":31,"../Knoin/Knoin.js":33,"../Knoin/KnoinAbstractScreen.js":35}],42:[function(e,t){!function(t){"use strict";function s(){var t=e("../ViewModels/LoginViewModel.js");n.call(this,"login",[t])}var o=e("../External/underscore.js"),i=e("../Boots/RainLoopApp.js"),n=e("../Knoin/KnoinAbstractScreen.js");o.extend(s.prototype,n.prototype),s.prototype.onShow=function(){i.setTitle("")},t.exports=s}(t)},{"../Boots/RainLoopApp.js":4,"../External/underscore.js":31,"../Knoin/KnoinAbstractScreen.js":35,"../ViewModels/LoginViewModel.js":67}],43:[function(e,t){!function(t){"use strict";function s(){var t=e("../ViewModels/MailBoxSystemDropDownViewModel.js"),s=e("../ViewModels/MailBoxFolderListViewModel.js"),o=e("../ViewModels/MailBoxMessageListViewModel.js"),i=e("../ViewModels/MailBoxMessageViewViewModel.js");l.call(this,"mailbox",[t,s,o,i]),this.oLastRoute={}}var o=e("../External/underscore.js"),i=e("../External/$html.js"),n=e("../Common/Enums.js"),r=e("../Common/Globals.js"),a=e("../Common/Utils.js"),l=e("../Knoin/KnoinAbstractScreen.js"),c=e("../Storages/AppSettings.js"),u=e("../Storages/WebMailDataStorage.js"),d=e("../Storages/WebMailCacheStorage.js"),p=e("../Storages/WebMailAjaxRemoteStorage.js"),h=e("../Boots/RainLoopApp.js");o.extend(s.prototype,l.prototype),s.prototype.oLastRoute={},s.prototype.setNewTitle=function(){var e=u.accountEmail(),t=u.foldersInboxUnreadCount();h.setTitle((""===e?"":(t>0?"("+t+") ":" ")+e+" - ")+a.i18n("TITLES/MAILBOX"))},s.prototype.onShow=function(){this.setNewTitle(),r.keyScope(n.KeyState.MessageList)},s.prototype.onRoute=function(e,t,s,o){if(a.isUnd(o)?1:!o){var i=d.getFolderFullNameRaw(e),r=d.getFolderFromCacheList(i);r&&(u.currentFolder(r).messageListPage(t).messageListSearch(s),n.Layout.NoPreview===u.layout()&&u.message()&&u.message(null),h.reloadMessageList())}else n.Layout.NoPreview!==u.layout()||u.message()||h.historyBack()},s.prototype.onStart=function(){var e=function(){a.windowResize()};(c.capa(n.Capa.AdditionalAccounts)||c.capa(n.Capa.AdditionalIdentities))&&h.accountsAndIdentities(),o.delay(function(){"INBOX"!==u.currentFolderFullNameRaw()&&h.folderInformation("INBOX")},1e3),o.delay(function(){h.quota()},5e3),o.delay(function(){p.appDelayStart(a.emptyFunction)},35e3),i.toggleClass("rl-no-preview-pane",n.Layout.NoPreview===u.layout()),u.folderList.subscribe(e),u.messageList.subscribe(e),u.message.subscribe(e),u.layout.subscribe(function(e){i.toggleClass("rl-no-preview-pane",n.Layout.NoPreview===e)}),u.foldersInboxUnreadCount.subscribe(function(){this.setNewTitle()},this)},s.prototype.routes=function(){var e=function(){return["Inbox",1,"",!0]},t=function(e,t){return t[0]=a.pString(t[0]),t[1]=a.pInt(t[1]),t[1]=0>=t[1]?1:t[1],t[2]=a.pString(t[2]),""===e&&(t[0]="Inbox",t[1]=1),[decodeURI(t[0]),t[1],decodeURI(t[2]),!1]},s=function(e,t){return t[0]=a.pString(t[0]),t[1]=a.pString(t[1]),""===e&&(t[0]="Inbox"),[decodeURI(t[0]),1,decodeURI(t[1]),!1]};return[[/^([a-zA-Z0-9]+)\/p([1-9][0-9]*)\/(.+)\/?$/,{normalize_:t}],[/^([a-zA-Z0-9]+)\/p([1-9][0-9]*)$/,{normalize_:t}],[/^([a-zA-Z0-9]+)\/(.+)\/?$/,{normalize_:s}],[/^message-preview$/,{normalize_:e}],[/^([^\/]*)$/,{normalize_:t}]]},t.exports=s}(t)},{"../Boots/RainLoopApp.js":4,"../Common/Enums.js":7,"../Common/Globals.js":9,"../Common/Utils.js":14,"../External/$html.js":17,"../External/underscore.js":31,"../Knoin/KnoinAbstractScreen.js":35,"../Storages/AppSettings.js":59,"../Storages/WebMailAjaxRemoteStorage.js":63,"../Storages/WebMailCacheStorage.js":64,"../Storages/WebMailDataStorage.js":65,"../ViewModels/MailBoxFolderListViewModel.js":68,"../ViewModels/MailBoxMessageListViewModel.js":69,"../ViewModels/MailBoxMessageViewViewModel.js":70,"../ViewModels/MailBoxSystemDropDownViewModel.js":71}],44:[function(e,t){!function(t){"use strict";function s(){var t=e("../ViewModels/SettingsSystemDropDownViewModel.js"),s=e("../ViewModels/SettingsMenuViewModel.js"),o=e("../ViewModels/SettingsPaneViewModel.js");l.call(this,[t,s,o]),n.initOnStartOrLangChange(function(){this.sSettingsTitle=n.i18n("TITLES/SETTINGS")},this,function(){a.setTitle(this.sSettingsTitle)})}var o=e("../External/underscore.js"),i=e("../Common/Enums.js"),n=e("../Common/Utils.js"),r=e("../Common/Globals.js"),a=e("../Boots/RainLoopApp.js"),l=e("./AbstractSettings.js");o.extend(s.prototype,l.prototype),s.prototype.onShow=function(){a.setTitle(this.sSettingsTitle),r.keyScope(i.KeyState.Settings)},t.exports=s}(t)},{"../Boots/RainLoopApp.js":4,"../Common/Enums.js":7,"../Common/Globals.js":9,"../Common/Utils.js":14,"../External/underscore.js":31,"../ViewModels/SettingsMenuViewModel.js":85,"../ViewModels/SettingsPaneViewModel.js":86,"../ViewModels/SettingsSystemDropDownViewModel.js":87,"./AbstractSettings.js":41}],45:[function(e,t){!function(t){"use strict";function s(){this.accounts=c.accounts,this.processText=n.computed(function(){return c.accountsLoading()?a.i18n("SETTINGS_ACCOUNTS/LOADING_PROCESS"):""},this),this.visibility=n.computed(function(){return""===this.processText()?"hidden":"visible"},this),this.accountForDeletion=n.observable(null).extend({falseTimeout:3e3}).extend({toggleSubscribe:[this,function(e){e&&e.deleteAccess(!1)},function(e){e&&e.deleteAccess(!0)}]})}var o=e("../External/window.js"),i=e("../External/underscore.js"),n=e("../External/ko.js"),r=e("../Common/Enums.js"),a=e("../Common/Utils.js"),l=e("../Common/LinkBuilder.js"),c=e("../Storages/WebMailDataStorage.js"),u=e("../Storages/WebMailAjaxRemoteStorage.js"),d=e("../Boots/RainLoopApp.js"),p=e("../Knoin/Knoin.js"),h=e("../ViewModels/Popups/PopupsAddAccountViewModel.js");s.prototype.addNewAccount=function(){p.showScreenPopup(h)},s.prototype.deleteAccount=function(e){if(e&&e.deleteAccess()){this.accountForDeletion(null);var t=function(t){return e===t};e&&(this.accounts.remove(t),u.accountDelete(function(e,t){r.StorageResultType.Success===e&&t&&t.Result&&t.Reload?(p.routeOff(),p.setHash(l.root(),!0),p.routeOff(),i.defer(function(){o.location.reload()})):d.accountsAndIdentities()},e.email))}},t.exports=s}(t)},{"../Boots/RainLoopApp.js":4,"../Common/Enums.js":7,"../Common/LinkBuilder.js":10,"../Common/Utils.js":14,"../External/ko.js":28,"../External/underscore.js":31,"../External/window.js":32,"../Knoin/Knoin.js":33,"../Storages/WebMailAjaxRemoteStorage.js":63,"../Storages/WebMailDataStorage.js":65,"../ViewModels/Popups/PopupsAddAccountViewModel.js":72}],46:[function(e,t){!function(t){"use strict";function s(){this.changeProcess=i.observable(!1),this.errorDescription=i.observable(""),this.passwordMismatch=i.observable(!1),this.passwordUpdateError=i.observable(!1),this.passwordUpdateSuccess=i.observable(!1),this.currentPassword=i.observable(""),this.currentPassword.error=i.observable(!1),this.newPassword=i.observable(""),this.newPassword2=i.observable(""),this.currentPassword.subscribe(function(){this.passwordUpdateError(!1),this.passwordUpdateSuccess(!1),this.currentPassword.error(!1)},this),this.newPassword.subscribe(function(){this.passwordUpdateError(!1),this.passwordUpdateSuccess(!1),this.passwordMismatch(!1)},this),this.newPassword2.subscribe(function(){this.passwordUpdateError(!1),this.passwordUpdateSuccess(!1),this.passwordMismatch(!1)},this),this.saveNewPasswordCommand=r.createCommand(this,function(){this.newPassword()!==this.newPassword2()?(this.passwordMismatch(!0),this.errorDescription(r.i18n("SETTINGS_CHANGE_PASSWORD/ERROR_PASSWORD_MISMATCH"))):(this.changeProcess(!0),this.passwordUpdateError(!1),this.passwordUpdateSuccess(!1),this.currentPassword.error(!1),this.passwordMismatch(!1),this.errorDescription(""),a.changePassword(this.onChangePasswordResponse,this.currentPassword(),this.newPassword()))},function(){return!this.changeProcess()&&""!==this.currentPassword()&&""!==this.newPassword()&&""!==this.newPassword2()}),this.onChangePasswordResponse=o.bind(this.onChangePasswordResponse,this)}var o=e("../External/underscore.js"),i=e("../External/ko.js"),n=e("../Common/Enums.js"),r=e("../Common/Utils.js"),a=e("../Storages/WebMailAjaxRemoteStorage.js");s.prototype.onHide=function(){this.changeProcess(!1),this.currentPassword(""),this.newPassword(""),this.newPassword2(""),this.errorDescription(""),this.passwordMismatch(!1),this.currentPassword.error(!1)},s.prototype.onChangePasswordResponse=function(e,t){this.changeProcess(!1),this.passwordMismatch(!1),this.errorDescription(""),this.currentPassword.error(!1),n.StorageResultType.Success===e&&t&&t.Result?(this.currentPassword(""),this.newPassword(""),this.newPassword2(""),this.passwordUpdateSuccess(!0),this.currentPassword.error(!1)):(t&&n.Notification.CurrentPasswordIncorrect===t.ErrorCode&&this.currentPassword.error(!0),this.passwordUpdateError(!0),this.errorDescription(r.getNotification(t&&t.ErrorCode?t.ErrorCode:n.Notification.CouldNotSaveNewPassword)))},t.exports=s}(t)},{"../Common/Enums.js":7,"../Common/Utils.js":14,"../External/ko.js":28,"../External/underscore.js":31,"../Storages/WebMailAjaxRemoteStorage.js":63}],47:[function(e,t){!function(t){"use strict";function s(){this.contactsAutosave=r.contactsAutosave,this.allowContactsSync=r.allowContactsSync,this.enableContactsSync=r.enableContactsSync,this.contactsSyncUrl=r.contactsSyncUrl,this.contactsSyncUser=r.contactsSyncUser,this.contactsSyncPass=r.contactsSyncPass,this.saveTrigger=o.computed(function(){return[this.enableContactsSync()?"1":"0",this.contactsSyncUrl(),this.contactsSyncUser(),this.contactsSyncPass()].join("|")},this).extend({throttle:500}),this.saveTrigger.subscribe(function(){n.saveContactsSyncData(null,this.enableContactsSync(),this.contactsSyncUrl(),this.contactsSyncUser(),this.contactsSyncPass())},this)}var o=e("../External/ko.js"),i=e("../Common/Utils.js"),n=e("../Storages/WebMailAjaxRemoteStorage.js"),r=e("../Storages/WebMailDataStorage.js");s.prototype.onBuild=function(){r.contactsAutosave.subscribe(function(e){n.saveSettings(i.emptyFunction,{ContactsAutosave:e?"1":"0"})})},t.exports=s}(t)},{"../Common/Utils.js":14,"../External/ko.js":28,"../Storages/WebMailAjaxRemoteStorage.js":63,"../Storages/WebMailDataStorage.js":65}],48:[function(e,t){!function(t){"use strict";function s(){this.filters=o.observableArray([]),this.filters.loading=o.observable(!1),this.filters.subscribe(function(){i.windowResize()})}var o=e("../External/ko.js"),i=e("../Common/Utils.js"),n=e("../Knoin/Knoin.js"),r=e("../ViewModels/Popups/PopupsFilterViewModel.js");s.prototype.deleteFilter=function(e){this.filters.remove(e)},s.prototype.addFilter=function(){n.showScreenPopup(r,[new FilterModel])},t.exports=s}(t)},{"../Common/Utils.js":14,"../External/ko.js":28,"../Knoin/Knoin.js":33,"../ViewModels/Popups/PopupsFilterViewModel.js":76}],49:[function(e,t){!function(t){"use strict";function s(){this.foldersListError=c.foldersListError,this.folderList=c.folderList,this.processText=o.computed(function(){var e=c.foldersLoading(),t=c.foldersCreating(),s=c.foldersDeleting(),o=c.foldersRenaming();return t?n.i18n("SETTINGS_FOLDERS/CREATING_PROCESS"):s?n.i18n("SETTINGS_FOLDERS/DELETING_PROCESS"):o?n.i18n("SETTINGS_FOLDERS/RENAMING_PROCESS"):e?n.i18n("SETTINGS_FOLDERS/LOADING_PROCESS"):""},this),this.visibility=o.computed(function(){return""===this.processText()?"hidden":"visible"},this),this.folderForDeletion=o.observable(null).extend({falseTimeout:3e3}).extend({toggleSubscribe:[this,function(e){e&&e.deleteAccess(!1)},function(e){e&&e.deleteAccess(!0)}]}),this.folderForEdit=o.observable(null).extend({toggleSubscribe:[this,function(e){e&&e.edited(!1)},function(e){e&&e.canBeEdited()&&e.edited(!0)}]}),this.useImapSubscribe=!!a.settingsGet("UseImapSubscribe")}var o=e("../External/ko.js"),i=e("../Common/Enums.js"),n=e("../Common/Utils.js"),r=e("../Knoin/Knoin.js"),a=e("../Storages/AppSettings.js"),l=e("../Storages/LocalStorage.js"),c=e("../Storages/WebMailDataStorage.js"),u=e("../Storages/WebMailCacheStorage.js"),d=e("../Storages/WebMailAjaxRemoteStorage.js"),p=e("../Boots/RainLoopApp.js"),h=e("../ViewModels/Popups/PopupsFolderCreateViewModel.js"),m=e("../ViewModels/Popups/PopupsFolderSystemViewModel.js");s.prototype.folderEditOnEnter=function(e){var t=e?n.trim(e.nameForEdit()):"";""!==t&&e.name()!==t&&(l.set(i.ClientSideKeyName.FoldersLashHash,""),c.foldersRenaming(!0),d.folderRename(function(e,t){c.foldersRenaming(!1),i.StorageResultType.Success===e&&t&&t.Result||c.foldersListError(t&&t.ErrorCode?n.getNotification(t.ErrorCode):n.i18n("NOTIFICATIONS/CANT_RENAME_FOLDER")),p.folders()},e.fullNameRaw,t),u.removeFolderFromCacheList(e.fullNameRaw),e.name(t)),e.edited(!1)},s.prototype.folderEditOnEsc=function(e){e&&e.edited(!1)},s.prototype.onShow=function(){c.foldersListError("")},s.prototype.createFolder=function(){r.showScreenPopup(h)},s.prototype.systemFolder=function(){r.showScreenPopup(m)},s.prototype.deleteFolder=function(e){if(e&&e.canBeDeleted()&&e.deleteAccess()&&0===e.privateMessageCountAll()){this.folderForDeletion(null);var t=function(s){return e===s?!0:(s.subFolders.remove(t),!1)};e&&(l.set(i.ClientSideKeyName.FoldersLashHash,""),c.folderList.remove(t),c.foldersDeleting(!0),d.folderDelete(function(e,t){c.foldersDeleting(!1),i.StorageResultType.Success===e&&t&&t.Result||c.foldersListError(t&&t.ErrorCode?n.getNotification(t.ErrorCode):n.i18n("NOTIFICATIONS/CANT_DELETE_FOLDER")),p.folders()},e.fullNameRaw),u.removeFolderFromCacheList(e.fullNameRaw))}else 0"},s.prototype.addNewIdentity=function(){u.showScreenPopup(d)},s.prototype.editIdentity=function(e){u.showScreenPopup(d,[e])},s.prototype.deleteIdentity=function(e){if(e&&e.deleteAccess()){this.identityForDeletion(null);var t=function(t){return e===t};e&&(this.identities.remove(t),l.identityDelete(function(){c.accountsAndIdentities()},e.id))}},s.prototype.onFocus=function(){if(!this.editor&&this.signatureDom()){var e=this,t=a.signature();this.editor=new r(e.signatureDom(),function(){a.signature((e.editor.isHtml()?":HTML:":"")+e.editor.getData())},function(){":HTML:"===t.substr(0,6)?e.editor.setHtml(t.substr(6),!1):e.editor.setPlain(t,!1)})}},s.prototype.onBuild=function(e){var t=this;e.on("click",".identity-item .e-action",function(){var e=o.dataFor(this);e&&t.editIdentity(e)}),_.delay(function(){var e=n.settingsSaveHelperSimpleFunction(t.displayNameTrigger,t),s=n.settingsSaveHelperSimpleFunction(t.replyTrigger,t),o=n.settingsSaveHelperSimpleFunction(t.signatureTrigger,t),i=n.settingsSaveHelperSimpleFunction(t.defaultIdentityIDTrigger,t);a.defaultIdentityID.subscribe(function(e){l.saveSettings(i,{DefaultIdentityID:e})}),a.displayName.subscribe(function(t){l.saveSettings(e,{DisplayName:t})}),a.replyTo.subscribe(function(e){l.saveSettings(s,{ReplyTo:e})}),a.signature.subscribe(function(e){l.saveSettings(o,{Signature:e})}),a.signatureToAll.subscribe(function(e){l.saveSettings(null,{SignatureToAll:e?"1":"0"})})},50)},t.exports=s}(t)},{"../Boots/RainLoopApp.js":4,"../Common/Enums.js":7,"../Common/NewHtmlEditorWrapper.js":11,"../Common/Utils.js":14,"../External/ko.js":28,"../Knoin/Knoin.js":33,"../Storages/WebMailAjaxRemoteStorage.js":63,"../Storages/WebMailDataStorage.js":65,"../ViewModels/Popups/PopupsIdentityViewModel.js":80}],52:[function(e,t){!function(t){"use strict";function s(){this.editor=null,this.displayName=a.displayName,this.signature=a.signature,this.signatureToAll=a.signatureToAll,this.replyTo=a.replyTo,this.signatureDom=o.observable(null),this.displayNameTrigger=o.observable(i.SaveSettingsStep.Idle),this.replyTrigger=o.observable(i.SaveSettingsStep.Idle),this.signatureTrigger=o.observable(i.SaveSettingsStep.Idle)}var o=e("../External/ko.js"),i=e("../Common/Enums.js"),n=e("../Common/Utils.js"),r=e("../Common/NewHtmlEditorWrapper.js"),a=e("../Storages/WebMailDataStorage.js"),l=e("../Storages/WebMailAjaxRemoteStorage.js");s.prototype.onFocus=function(){if(!this.editor&&this.signatureDom()){var e=this,t=a.signature();this.editor=new r(e.signatureDom(),function(){a.signature((e.editor.isHtml()?":HTML:":"")+e.editor.getData())},function(){":HTML:"===t.substr(0,6)?e.editor.setHtml(t.substr(6),!1):e.editor.setPlain(t,!1)})}},s.prototype.onBuild=function(){var e=this;_.delay(function(){var t=n.settingsSaveHelperSimpleFunction(e.displayNameTrigger,e),s=n.settingsSaveHelperSimpleFunction(e.replyTrigger,e),o=n.settingsSaveHelperSimpleFunction(e.signatureTrigger,e);a.displayName.subscribe(function(e){l.saveSettings(t,{DisplayName:e})}),a.replyTo.subscribe(function(e){l.saveSettings(s,{ReplyTo:e})}),a.signature.subscribe(function(e){l.saveSettings(o,{Signature:e})}),a.signatureToAll.subscribe(function(e){l.saveSettings(null,{SignatureToAll:e?"1":"0"})})},50)},t.exports=s}(t)},{"../Common/Enums.js":7,"../Common/NewHtmlEditorWrapper.js":11,"../Common/Utils.js":14,"../External/ko.js":28,"../Storages/WebMailAjaxRemoteStorage.js":63,"../Storages/WebMailDataStorage.js":65}],53:[function(e,t){!function(t){"use strict";function s(){this.openpgpkeys=n.openpgpkeys,this.openpgpkeysPublic=n.openpgpkeysPublic,this.openpgpkeysPrivate=n.openpgpkeysPrivate,this.openPgpKeyForDeletion=o.observable(null).extend({falseTimeout:3e3}).extend({toggleSubscribe:[this,function(e){e&&e.deleteAccess(!1)},function(e){e&&e.deleteAccess(!0)}]})}var o=e("../External/ko.js"),i=e("../Knoin/Knoin.js"),n=e("../Storages/WebMailDataStorage.js"),r=e("../Boots/RainLoopApp.js"),a=e("../ViewModels/Popups/PopupsAddOpenPgpKeyViewModel.js"),l=e("../ViewModels/Popups/PopupsGenerateNewOpenPgpKeyViewModel.js"),c=e("../ViewModels/Popups/PopupsViewOpenPgpKeyViewModel.js");s.prototype.addOpenPgpKey=function(){i.showScreenPopup(a)},s.prototype.generateOpenPgpKey=function(){i.showScreenPopup(l)},s.prototype.viewOpenPgpKey=function(e){e&&i.showScreenPopup(c,[e])},s.prototype.deleteOpenPgpKey=function(e){e&&e.deleteAccess()&&(this.openPgpKeyForDeletion(null),e&&n.openpgpKeyring&&(this.openpgpkeys.remove(function(t){return e===t}),n.openpgpKeyring[e.isPrivate?"privateKeys":"publicKeys"].removeForId(e.guid),n.openpgpKeyring.store(),r.reloadOpenPgpKeys()))},t.exports=s}(t)},{"../Boots/RainLoopApp.js":4,"../External/ko.js":28,"../Knoin/Knoin.js":33,"../Storages/WebMailDataStorage.js":65,"../ViewModels/Popups/PopupsAddOpenPgpKeyViewModel.js":73,"../ViewModels/Popups/PopupsGenerateNewOpenPgpKeyViewModel.js":79,"../ViewModels/Popups/PopupsViewOpenPgpKeyViewModel.js":84}],54:[function(e,t){!function(t){"use strict";function s(){this.processing=o.observable(!1),this.clearing=o.observable(!1),this.secreting=o.observable(!1),this.viewUser=o.observable(""),this.viewEnable=o.observable(!1),this.viewEnable.subs=!0,this.twoFactorStatus=o.observable(!1),this.viewSecret=o.observable(""),this.viewBackupCodes=o.observable(""),this.viewUrl=o.observable(""),this.bFirst=!0,this.viewTwoFactorStatus=o.computed(function(){return n.langChangeTrigger(),r.i18n(this.twoFactorStatus()?"SETTINGS_SECURITY/TWO_FACTOR_SECRET_CONFIGURED_DESC":"SETTINGS_SECURITY/TWO_FACTOR_SECRET_NOT_CONFIGURED_DESC")},this),this.onResult=_.bind(this.onResult,this),this.onSecretResult=_.bind(this.onSecretResult,this)}var o=e("../External/ko.js"),i=e("../Common/Utils.js"),n=e("../Common/Globals.js"),r=e("../Common/Utils.js"),a=e("../Storages/WebMailAjaxRemoteStorage.js"),l=e("../Knoin/Knoin.js"),c=e("../ViewModels/Popups/PopupsTwoFactorTestViewModel.js");s.prototype.showSecret=function(){this.secreting(!0),a.showTwoFactorSecret(this.onSecretResult)},s.prototype.hideSecret=function(){this.viewSecret(""),this.viewBackupCodes(""),this.viewUrl("")
+},s.prototype.createTwoFactor=function(){this.processing(!0),a.createTwoFactor(this.onResult)},s.prototype.enableTwoFactor=function(){this.processing(!0),a.enableTwoFactor(this.onResult,this.viewEnable())},s.prototype.testTwoFactor=function(){l.showScreenPopup(c)},s.prototype.clearTwoFactor=function(){this.viewSecret(""),this.viewBackupCodes(""),this.viewUrl(""),this.clearing(!0),a.clearTwoFactor(this.onResult)},s.prototype.onShow=function(){this.viewSecret(""),this.viewBackupCodes(""),this.viewUrl("")},s.prototype.onResult=function(e,t){if(this.processing(!1),this.clearing(!1),i.StorageResultType.Success===e&&t&&t.Result?(this.viewUser(r.pString(t.Result.User)),this.viewEnable(!!t.Result.Enable),this.twoFactorStatus(!!t.Result.IsSet),this.viewSecret(r.pString(t.Result.Secret)),this.viewBackupCodes(r.pString(t.Result.BackupCodes).replace(/[\s]+/g," ")),this.viewUrl(r.pString(t.Result.Url))):(this.viewUser(""),this.viewEnable(!1),this.twoFactorStatus(!1),this.viewSecret(""),this.viewBackupCodes(""),this.viewUrl("")),this.bFirst){this.bFirst=!1;var s=this;this.viewEnable.subscribe(function(e){this.viewEnable.subs&&a.enableTwoFactor(function(e,t){i.StorageResultType.Success===e&&t&&t.Result||(s.viewEnable.subs=!1,s.viewEnable(!1),s.viewEnable.subs=!0)},e)},this)}},s.prototype.onSecretResult=function(e,t){this.secreting(!1),i.StorageResultType.Success===e&&t&&t.Result?(this.viewSecret(r.pString(t.Result.Secret)),this.viewUrl(r.pString(t.Result.Url))):(this.viewSecret(""),this.viewUrl(""))},s.prototype.onBuild=function(){this.processing(!0),a.getTwoFactor(this.onResult)},t.exports=s}(t)},{"../Common/Globals.js":9,"../Common/Utils.js":14,"../External/ko.js":28,"../Knoin/Knoin.js":33,"../Storages/WebMailAjaxRemoteStorage.js":63,"../ViewModels/Popups/PopupsTwoFactorTestViewModel.js":83}],55:[function(e,t){!function(t){"use strict";function s(){this.googleEnable=i.googleEnable,this.googleActions=i.googleActions,this.googleLoggined=i.googleLoggined,this.googleUserName=i.googleUserName,this.facebookEnable=i.facebookEnable,this.facebookActions=i.facebookActions,this.facebookLoggined=i.facebookLoggined,this.facebookUserName=i.facebookUserName,this.twitterEnable=i.twitterEnable,this.twitterActions=i.twitterActions,this.twitterLoggined=i.twitterLoggined,this.twitterUserName=i.twitterUserName,this.connectGoogle=o.createCommand(this,function(){this.googleLoggined()||n.googleConnect()},function(){return!this.googleLoggined()&&!this.googleActions()}),this.disconnectGoogle=o.createCommand(this,function(){n.googleDisconnect()}),this.connectFacebook=o.createCommand(this,function(){this.facebookLoggined()||n.facebookConnect()},function(){return!this.facebookLoggined()&&!this.facebookActions()}),this.disconnectFacebook=o.createCommand(this,function(){n.facebookDisconnect()}),this.connectTwitter=o.createCommand(this,function(){this.twitterLoggined()||n.twitterConnect()},function(){return!this.twitterLoggined()&&!this.twitterActions()}),this.disconnectTwitter=o.createCommand(this,function(){n.twitterDisconnect()})}var o=e("../Common/Utils.js"),i=e("../Storages/WebMailDataStorage.js"),n=e("../Boots/RainLoopApp.js");t.exports=s}(t)},{"../Boots/RainLoopApp.js":4,"../Common/Utils.js":14,"../Storages/WebMailDataStorage.js":65}],56:[function(e,t){!function(t){"use strict";function s(){var e=this;this.mainTheme=c.mainTheme,this.themesObjects=n.observableArray([]),this.themeTrigger=n.observable(r.SaveSettingsStep.Idle).extend({throttle:100}),this.oLastAjax=null,this.iTimer=0,c.theme.subscribe(function(t){_.each(this.themesObjects(),function(e){e.selected(t===e.name)});var s=i("#rlThemeLink"),n=i("#rlThemeStyle"),l=s.attr("href");l||(l=n.attr("data-href")),l&&(l=l.toString().replace(/\/-\/[^\/]+\/\-\//,"/-/"+t+"/-/"),l=l.toString().replace(/\/Css\/[^\/]+\/User\//,"/Css/0/User/"),"Json/"!==l.substring(l.length-5,l.length)&&(l+="Json/"),o.clearTimeout(e.iTimer),e.themeTrigger(r.SaveSettingsStep.Animate),this.oLastAjax&&this.oLastAjax.abort&&this.oLastAjax.abort(),this.oLastAjax=i.ajax({url:l,dataType:"json"}).done(function(t){t&&a.isArray(t)&&2===t.length&&(!s||!s[0]||n&&n[0]||(n=i(''),s.after(n),s.remove()),n&&n[0]&&(n.attr("data-href",l).attr("data-theme",t[0]),n&&n[0]&&n[0].styleSheet&&!a.isUnd(n[0].styleSheet.cssText)?n[0].styleSheet.cssText=t[1]:n.text(t[1])),e.themeTrigger(r.SaveSettingsStep.TrueResult))}).always(function(){e.iTimer=o.setTimeout(function(){e.themeTrigger(r.SaveSettingsStep.Idle)},1e3),e.oLastAjax=null})),u.saveSettings(null,{Theme:t})},this)}var o=e("../External/window.js"),i=e("../External/jquery.js"),n=e("../External/ko.js"),r=e("../Common/Enums.js"),a=e("../Common/Utils.js"),l=e("../Common/LinkBuilder.js"),c=e("../Storages/WebMailDataStorage.js"),u=e("../Storages/WebMailAjaxRemoteStorage.js");s.prototype.onBuild=function(){var e=c.theme();this.themesObjects(_.map(c.themes(),function(t){return{name:t,nameDisplay:a.convertThemeName(t),selected:n.observable(t===e),themePreviewSrc:l.themePreviewLink(t)}}))},t.exports=s}(t)},{"../Common/Enums.js":7,"../Common/LinkBuilder.js":10,"../Common/Utils.js":14,"../External/jquery.js":26,"../External/ko.js":28,"../External/window.js":32,"../Storages/WebMailAjaxRemoteStorage.js":63,"../Storages/WebMailDataStorage.js":65}],57:[function(e,t){!function(t){"use strict";function s(){this.oRequests={}}var o=e("../External/window.js"),i=e("../External/jquery.js"),n=e("../Common/Consts.js"),r=e("../Common/Enums.js"),a=e("../Common/Globals.js"),l=e("../Common/Utils.js"),c=e("../Common/Plugins.js"),u=e("../Common/LinkBuilder.js"),d=e("./AppSettings.js");s.prototype.oRequests={},s.prototype.defaultResponse=function(e,t,s,i,u,d){var p=function(){r.StorageResultType.Success!==s&&a.bUnload&&(s=r.StorageResultType.Unload),r.StorageResultType.Success===s&&i&&!i.Result?(i&&-1(new o.Date).getTime()-h),g&&a.oRequests[g]&&(a.oRequests[g].__aborted&&(i="abort"),a.oRequests[g]=null),a.defaultResponse(e,g,i,s,n,t)}),g&&00?(this.defaultRequest(e,"Message",{},null,"Message/"+r.urlsafe_encode([t,s,c.projectHash(),c.threading()&&c.useThreads()?"1":"0"].join(String.fromCharCode(0))),["Message"]),!0):!1},s.prototype.composeUploadExternals=function(e,t){this.defaultRequest(e,"ComposeUploadExternals",{Externals:t},999e3)},s.prototype.composeUploadDrive=function(e,t,s){this.defaultRequest(e,"ComposeUploadDrive",{AccessToken:s,Url:t},999e3)},s.prototype.folderInformation=function(e,t,s){var n=!0,r=[];i.isArray(s)&&0=e?1:e},this),this.mainMessageListSearch=r.computed({read:this.messageListSearch,write:function(e){y.setHash(m.mailBox(this.currentFolderFullNameHash(),1,h.trim(e.toString())))
+},owner:this}),this.messageListError=r.observable(""),this.messageListLoading=r.observable(!1),this.messageListIsNotCompleted=r.observable(!1),this.messageListCompleteLoadingThrottle=r.observable(!1).extend({throttle:200}),this.messageListCompleteLoading=r.computed(function(){var e=this.messageListLoading(),t=this.messageListIsNotCompleted();return e||t},this),this.messageListCompleteLoading.subscribe(function(e){this.messageListCompleteLoadingThrottle(e)},this),this.messageList.subscribe(n.debounce(function(e){n.each(e,function(e){e.newForAnimation()&&e.newForAnimation(!1)})},500)),this.staticMessageList=new C,this.message=r.observable(null),this.messageLoading=r.observable(!1),this.messageLoadingThrottle=r.observable(!1).extend({throttle:50}),this.message.focused=r.observable(!1),this.message.subscribe(function(e){e?d.Layout.NoPreview===this.layout()&&this.message.focused(!0):(this.message.focused(!1),this.messageFullScreenMode(!1),this.hideMessageBodies(),d.Layout.NoPreview===b.layout()&&-10?o.Math.ceil(t/e*100):0},this),this.capaOpenPGP=r.observable(!1),this.openpgpkeys=r.observableArray([]),this.openpgpKeyring=null,this.openpgpkeysPublic=this.openpgpkeys.filter(function(e){return!(!e||e.isPrivate)}),this.openpgpkeysPrivate=this.openpgpkeys.filter(function(e){return!(!e||!e.isPrivate)}),this.googleActions=r.observable(!1),this.googleLoggined=r.observable(!1),this.googleUserName=r.observable(""),this.facebookActions=r.observable(!1),this.facebookLoggined=r.observable(!1),this.facebookUserName=r.observable(""),this.twitterActions=r.observable(!1),this.twitterLoggined=r.observable(!1),this.twitterUserName=r.observable(""),this.customThemeType=r.observable(d.CustomThemeType.Light),this.purgeMessageBodyCacheThrottle=n.throttle(this.purgeMessageBodyCache,3e4)}var o=e("../External/window.js"),i=e("../External/jquery.js"),n=e("../External/underscore.js"),r=e("../External/ko.js"),a=e("../External/moment.js"),l=e("../External/$div.js"),c=e("../External/NotificationClass.js"),u=e("../Common/Consts.js"),d=e("../Common/Enums.js"),p=e("../Common/Globals.js"),h=e("../Common/Utils.js"),m=e("../Common/LinkBuilder.js"),g=e("./AppSettings.js"),f=e("./WebMailCacheStorage.js"),b=e("./WebMailDataStorage.js"),S=e("./WebMailAjaxRemoteStorage.js"),y=e("../Knoin/Knoin.js"),C=e("../Models/MessageModel.js"),v=e("../Models/FolderModel.js"),w=e("./LocalStorage.js"),E=e("./AbstractData.js");n.extend(s.prototype,E.prototype),s.prototype.purgeMessageBodyCache=function(){var e=0,t=null,s=p.iMessageBodyCacheCount-u.Values.MessageBodyCacheLimit;s>0&&(t=this.messagesBodiesDom(),t&&(t.find(".rl-cache-class").each(function(){var t=i(this);s>t.data("rl-cache-count")&&(t.addClass("rl-cache-purge"),e++)}),e>0&&n.delay(function(){t.find(".rl-cache-purge").remove()},300)))},s.prototype.populateDataOnStart=function(){E.prototype.populateDataOnStart.call(this),this.accountEmail(g.settingsGet("Email")),this.accountIncLogin(g.settingsGet("IncLogin")),this.accountOutLogin(g.settingsGet("OutLogin")),this.projectHash(g.settingsGet("ProjectHash")),this.defaultIdentityID(g.settingsGet("DefaultIdentityID")),this.displayName(g.settingsGet("DisplayName")),this.replyTo(g.settingsGet("ReplyTo")),this.signature(g.settingsGet("Signature")),this.signatureToAll(!!g.settingsGet("SignatureToAll")),this.enableTwoFactor(!!g.settingsGet("EnableTwoFactor")),this.lastFoldersHash=w.get(d.ClientSideKeyName.FoldersLashHash)||"",this.remoteSuggestions=!!g.settingsGet("RemoteSuggestions"),this.devEmail=g.settingsGet("DevEmail"),this.devPassword=g.settingsGet("DevPassword")},s.prototype.initUidNextAndNewMessages=function(e,t,s){if("INBOX"===e&&h.isNormal(t)&&""!==t){if(h.isArray(s)&&03)a(m.notificationMailIcon(),b.accountEmail(),h.i18n("MESSAGE_LIST/NEW_MESSAGE_NOTIFICATION",{COUNT:r}));else for(;r>i;i++)a(m.notificationMailIcon(),C.emailsToLine(C.initEmailsFromJson(s[i].From),!1),s[i].Subject)}f.setFolderUidNext(e,t)}},s.prototype.folderResponseParseRec=function(e,t){var s=0,o=0,i=null,n=null,r="",a=[],l=[];for(s=0,o=t.length;o>s;s++)i=t[s],i&&(r=i.FullNameRaw,n=f.getFolderFromCacheList(r),n||(n=v.newInstanceFromJson(i),n&&(f.setFolderToCacheList(r,n),f.setFolderFullNameRaw(n.fullNameHash,r))),n&&(n.collapsed(!h.isFolderExpanded(n.fullNameHash)),i.Extended&&(i.Extended.Hash&&f.setFolderHash(n.fullNameRaw,i.Extended.Hash),h.isNormal(i.Extended.MessageCount)&&n.messageCountAll(i.Extended.MessageCount),h.isNormal(i.Extended.MessageUnseenCount)&&n.messageCountUnread(i.Extended.MessageUnseenCount)),a=i.SubFolders,a&&"Collection/FolderCollection"===a["@Object"]&&a["@Collection"]&&h.isArray(a["@Collection"])&&n.subFolders(this.folderResponseParseRec(e,a["@Collection"])),l.push(n)));return l},s.prototype.setFolders=function(e){var t=[],s=!1,o=function(e){return""===e||u.Values.UnuseOptionValue===e||null!==f.getFolderFromCacheList(e)?e:""};e&&e.Result&&"Collection/FolderCollection"===e.Result["@Object"]&&e.Result["@Collection"]&&h.isArray(e.Result["@Collection"])&&(h.isUnd(e.Result.Namespace)||(b.namespace=e.Result.Namespace),this.threading(!!g.settingsGet("UseImapThread")&&e.Result.IsThreadsSupported&&!0),t=this.folderResponseParseRec(b.namespace,e.Result["@Collection"]),b.folderList(t),e.Result.SystemFolders&&""==""+g.settingsGet("SentFolder")+g.settingsGet("DraftFolder")+g.settingsGet("SpamFolder")+g.settingsGet("TrashFolder")+g.settingsGet("ArchiveFolder")+g.settingsGet("NullFolder")&&(g.settingsSet("SentFolder",e.Result.SystemFolders[2]||null),g.settingsSet("DraftFolder",e.Result.SystemFolders[3]||null),g.settingsSet("SpamFolder",e.Result.SystemFolders[4]||null),g.settingsSet("TrashFolder",e.Result.SystemFolders[5]||null),g.settingsSet("ArchiveFolder",e.Result.SystemFolders[12]||null),s=!0),b.sentFolder(o(g.settingsGet("SentFolder"))),b.draftFolder(o(g.settingsGet("DraftFolder"))),b.spamFolder(o(g.settingsGet("SpamFolder"))),b.trashFolder(o(g.settingsGet("TrashFolder"))),b.archiveFolder(o(g.settingsGet("ArchiveFolder"))),s&&S.saveSystemFolders(h.emptyFunction,{SentFolder:b.sentFolder(),DraftFolder:b.draftFolder(),SpamFolder:b.spamFolder(),TrashFolder:b.trashFolder(),ArchiveFolder:b.archiveFolder(),NullFolder:"NullFolder"}),w.set(d.ClientSideKeyName.FoldersLashHash,e.Result.FoldersHash))},s.prototype.hideMessageBodies=function(){var e=this.messagesBodiesDom();e&&e.find(".b-text-part").hide()},s.prototype.getNextFolderNames=function(e){e=h.isUnd(e)?!1:!!e;var t=[],s=10,o=a().unix(),i=o-300,r=[],l=function(t){n.each(t,function(t){t&&"INBOX"!==t.fullNameRaw&&t.selectable&&t.existen&&i>t.interval&&(!e||t.subScribed())&&r.push([t.interval,t.fullNameRaw]),t&&0t[0]?1:0}),n.find(r,function(e){var i=f.getFolderFromCacheList(e[1]);return i&&(i.interval=o,t.push(e[1])),s<=t.length}),n.uniq(t)},s.prototype.removeMessagesFromList=function(e,t,s,o){s=h.isNormal(s)?s:"",o=h.isUnd(o)?!1:!!o,t=n.map(t,function(e){return h.pInt(e)});var i=0,r=b.messageList(),a=f.getFolderFromCacheList(e),l=""===s?null:f.getFolderFromCacheList(s||""),c=b.currentFolderFullNameRaw(),u=b.message(),d=c===e?n.filter(r,function(e){return e&&-10&&a.messageCountUnread(0<=a.messageCountUnread()-i?a.messageCountUnread()-i:0)),l&&(l.messageCountAll(l.messageCountAll()+t.length),i>0&&l.messageCountUnread(l.messageCountUnread()+i),l.actionBlink(!0)),0 ').hide().addClass("rl-cache-class"),r.data("rl-cache-count",++p.iMessageBodyCacheCount),h.isNormal(e.Result.Html)&&""!==e.Result.Html?(s=!0,u=e.Result.Html.toString()):h.isNormal(e.Result.Plain)&&""!==e.Result.Plain?(s=!1,u=h.plainToHtml(e.Result.Plain.toString(),!1),(y.isPgpSigned()||y.isPgpEncrypted())&&b.capaOpenPGP()&&(y.plainRaw=h.pString(e.Result.Plain),g=/---BEGIN PGP MESSAGE---/.test(y.plainRaw),g||(m=/-----BEGIN PGP SIGNED MESSAGE-----/.test(y.plainRaw)&&/-----BEGIN PGP SIGNATURE-----/.test(y.plainRaw)),l.empty(),m&&y.isPgpSigned()?u=l.append(i('').text(y.plainRaw)).html():g&&y.isPgpEncrypted()&&(u=l.append(i('').text(y.plainRaw)).html()),l.empty(),y.isPgpSigned(m),y.isPgpEncrypted(g))):s=!1,r.html(h.linkify(u)).addClass("b-text-part "+(s?"html":"plain")),y.isHtml(!!s),y.hasImages(!!o),y.pgpSignedVerifyStatus(d.SignedVerifyStatus.None),y.pgpSignedVerifyUser(""),y.body=r,y.body&&S.append(y.body),y.storeDataToDom(),n&&y.showInternalImages(!0),y.hasImages()&&this.showImages()&&y.showExternalImages(!0),this.purgeMessageBodyCacheThrottle()),this.messageActiveDom(y.body),this.hideMessageBodies(),y.body.show(),r&&h.initBlockquoteSwitcher(r)),f.initMessageFlagsFromCache(y),y.unseen()&&RL.setMessageSeen(y),h.windowResize())},s.prototype.calculateMessageListHash=function(e){return n.map(e,function(e){return""+e.hash+"_"+e.threadsLen()+"_"+e.flagHash()}).join("|")},s.prototype.setMessageList=function(e,t){if(e&&e.Result&&"Collection/MessageCollection"===e.Result["@Object"]&&e.Result["@Collection"]&&h.isArray(e.Result["@Collection"])){var s=null,i=0,n=0,r=0,l=0,c=[],u=a().unix(),p=b.staticMessageList,m=null,g=null,S=null,y=0,v=!1;for(r=h.pInt(e.Result.MessageResultCount),l=h.pInt(e.Result.Offset),h.isNonEmptyArray(e.Result.LastCollapsedThreadUids)&&(s=e.Result.LastCollapsedThreadUids),S=f.getFolderFromCacheList(h.isNormal(e.Result.Folder)?e.Result.Folder:""),S&&!t&&(S.interval=u,f.setFolderHash(e.Result.Folder,e.Result.FolderHash),h.isNormal(e.Result.MessageCount)&&S.messageCountAll(e.Result.MessageCount),h.isNormal(e.Result.MessageUnseenCount)&&(h.pInt(S.messageCountUnread())!==h.pInt(e.Result.MessageUnseenCount)&&(v=!0),S.messageCountUnread(e.Result.MessageUnseenCount)),this.initUidNextAndNewMessages(S.fullNameRaw,e.Result.UidNext,e.Result.NewMessages)),v&&S&&f.clearMessageFlagsFromCacheByFolder(S.fullNameRaw),i=0,n=e.Result["@Collection"].length;n>i;i++)m=e.Result["@Collection"][i],m&&"Object/Message"===m["@Object"]&&(g=p[i],g&&g.initByJson(m)||(g=C.newInstanceFromJson(m)),g&&(f.hasNewMessageAndRemoveFromCache(g.folderFullNameRaw,g.uid)&&5>=y&&(y++,g.newForAnimation(!0)),g.deleted(!1),t?f.initMessageFlagsFromCache(g):f.storeMessageFlagsToCache(g),g.lastInCollapsedThread(s&&-1-1&&a.eq(n).removeClass("focused"),38===r&&n>0?n--:40===r&&no)?(this.oContentScrollable.scrollTop(s.top<0?this.oContentScrollable.scrollTop()+s.top-e:this.oContentScrollable.scrollTop()+s.top-o+n+e),!0):!1},s.prototype.messagesDrop=function(e,t){if(e&&t&&t.helper){var s=t.helper.data("rl-folder"),o=a.hasClass("rl-ctrl-key-pressed"),i=t.helper.data("rl-uids");l.isNormal(s)&&""!==s&&l.isArray(i)&&g.moveMessagesToFolder(s,i,e.fullNameRaw,o)}},s.prototype.composeClick=function(){f.showScreenPopup(PopupsComposeViewModel)},s.prototype.createFolder=function(){f.showScreenPopup(PopupsFolderCreateViewModel)},s.prototype.configureFolders=function(){f.setHash(d.settings("folders"))},s.prototype.contactsClick=function(){this.allowContacts&&f.showScreenPopup(PopupsContactsViewModel)},t.exports=new s}(t)},{"../Boots/RainLoopApp.js":4,"../Common/Enums.js":7,"../Common/Globals.js":9,"../Common/LinkBuilder.js":10,"../Common/Utils.js":14,"../External/$html.js":17,"../External/jquery.js":26,"../External/key.js":27,"../External/ko.js":28,"../External/window.js":32,"../Knoin/Knoin.js":33,"../Knoin/KnoinAbstractViewModel.js":36,"../Storages/AppSettings.js":59,"../Storages/WebMailCacheStorage.js":64,"../Storages/WebMailDataStorage.js":65}],69:[function(e,t){!function(t){"use strict";function s(){w.call(this,"Right","MailMessageList"),this.sLastUid=null,this.bPrefetch=!1,this.emptySubjectValue="",this.hideDangerousActions=!!f.settingsGet("HideDangerousActions"),this.popupVisibility=p.popupVisibility,this.message=S.message,this.messageList=S.messageList,this.folderList=S.folderList,this.currentMessage=S.currentMessage,this.isMessageSelected=S.isMessageSelected,this.messageListSearch=S.messageListSearch,this.messageListError=S.messageListError,this.folderMenuForMove=S.folderMenuForMove,this.useCheckboxesInList=S.useCheckboxesInList,this.mainMessageListSearch=S.mainMessageListSearch,this.messageListEndFolder=S.messageListEndFolder,this.messageListChecked=S.messageListChecked,this.messageListCheckedOrSelected=S.messageListCheckedOrSelected,this.messageListCheckedOrSelectedUidsWithSubMails=S.messageListCheckedOrSelectedUidsWithSubMails,this.messageListCompleteLoadingThrottle=S.messageListCompleteLoadingThrottle,c.initOnStartOrLangChange(function(){this.emptySubjectValue=c.i18n("MESSAGE_LIST/EMPTY_SUBJECT_TEXT")},this),this.userQuota=S.userQuota,this.userUsageSize=S.userUsageSize,this.userUsageProc=S.userUsageProc,this.moveDropdownTrigger=n.observable(!1),this.moreDropdownTrigger=n.observable(!1),this.dragOver=n.observable(!1).extend({throttle:1}),this.dragOverEnter=n.observable(!1).extend({throttle:1}),this.dragOverArea=n.observable(null),this.dragOverBodyArea=n.observable(null),this.messageListItemTemplate=n.computed(function(){return u.Layout.NoPreview!==S.layout()?"MailMessageListItem":"MailMessageListItemNoPreviewPane"}),this.messageListSearchDesc=n.computed(function(){var e=S.messageListEndSearch();return""===e?"":c.i18n("MESSAGE_LIST/SEARCH_RESULT_FOR",{SEARCH:e})}),this.messageListPagenator=n.computed(c.computedPagenatorHelper(S.messageListPage,S.messageListPageCount)),this.checkAll=n.computed({read:function(){return 00&&t>0&&e>t},this),this.hasMessages=n.computed(function(){return 01?" ("+(100>e?e:"99+")+")":""},s.prototype.cancelSearch=function(){this.mainMessageListSearch(""),this.inputMessageListSearchFocus(!1)},s.prototype.moveSelectedMessagesToFolder=function(e,t){return this.canBeMoved()&&C.moveMessagesToFolder(S.currentFolderFullNameRaw(),S.messageListCheckedOrSelectedUidsWithSubMails(),e,t),!1},s.prototype.dragAndDronHelper=function(e){e&&e.checked(!0);var t=c.draggeblePlace(),s=S.messageListCheckedOrSelectedUidsWithSubMails();return t.data("rl-folder",S.currentFolderFullNameRaw()),t.data("rl-uids",s),t.find(".text").text(""+s.length),i.defer(function(){var e=S.messageListCheckedOrSelectedUidsWithSubMails();t.data("rl-uids",e),t.find(".text").text(""+e.length)}),t},s.prototype.onMessageResponse=function(e,t,s){S.hideMessageBodies(),S.messageLoading(!1),u.StorageResultType.Success===e&&t&&t.Result?S.setMessage(t,s):u.StorageResultType.Unload===e?(S.message(null),S.messageError("")):u.StorageResultType.Abort!==e&&(S.message(null),S.messageError(c.getNotification(t&&t.ErrorCode?t.ErrorCode:u.Notification.UnknownError)))},s.prototype.populateMessageBody=function(e){e&&(y.message(this.onMessageResponse,e.folderFullNameRaw,e.uid)?S.messageLoading(!0):c.log("Error: Unknown message request: "+e.folderFullNameRaw+" ~ "+e.uid+" [e-101]"))},s.prototype.setAction=function(e,t,s){var o=[],n=null,r=0;if(c.isUnd(s)&&(s=S.messageListChecked()),o=i.map(s,function(e){return e.uid}),""!==e&&00?100>e?e:"99+":""},s.prototype.verifyPgpSignedClearMessage=function(e){e&&e.verifyPgpSignedClearMessage()},s.prototype.decryptPgpEncryptedMessage=function(e){e&&e.decryptPgpEncryptedMessage(this.viewPgpPassword())},s.prototype.readReceipt=function(e){e&&""!==e.readReceipt()&&(m.sendReadReceiptMessage(u.emptyFunction,e.folderFullNameRaw,e.uid,e.readReceipt(),u.i18n("READ_RECEIPT/SUBJECT",{SUBJECT:e.subject()}),u.i18n("READ_RECEIPT/BODY",{"READ-RECEIPT":h.accountEmail()})),e.isReadReceipt(!0),p.storeMessageFlagsToCache(e),g.reloadFlagsCurrentMessageListAndMessageFromCache())},t.exports=s}(t)},{"../Boots/RainLoopApp.js":4,"../Common/Consts.js":6,"../Common/Enums.js":7,"../Common/Events.js":8,"../Common/Globals.js":9,"../Common/Utils.js":14,"../External/$html.js":17,"../External/jquery.js":26,"../External/key.js":27,"../External/ko.js":28,"../Knoin/Knoin.js":33,"../Knoin/KnoinAbstractViewModel.js":36,"../Storages/WebMailAjaxRemoteStorage.js":63,"../Storages/WebMailCacheStorage.js":64,"../Storages/WebMailDataStorage.js":65}],71:[function(e,t){!function(t){"use strict";function s(){i.call(this),o.constructorEnd(this)}var o=(e("../Common/Utils.js"),e("../Knoin/Knoin.js")),i=e("./AbstractSystemDropDownViewModel.js");o.extendAsViewModel("MailBoxSystemDropDownViewModel",s,i),t.exports=s}(t)},{"../Common/Utils.js":14,"../Knoin/Knoin.js":33,"./AbstractSystemDropDownViewModel.js":66}],72:[function(e,t){!function(t){"use strict";function s(){c.call(this,"Popups","PopupsAddAccount"),this.email=o.observable(""),this.password=o.observable(""),this.emailError=o.observable(!1),this.passwordError=o.observable(!1),this.email.subscribe(function(){this.emailError(!1)},this),this.password.subscribe(function(){this.passwordError(!1)},this),this.submitRequest=o.observable(!1),this.submitError=o.observable(""),this.emailFocus=o.observable(!1),this.addAccountCommand=n.createCommand(this,function(){return this.emailError(""===n.trim(this.email())),this.passwordError(""===n.trim(this.password())),this.emailError()||this.passwordError()?!1:(this.submitRequest(!0),r.accountAdd(_.bind(function(e,t){this.submitRequest(!1),i.StorageResultType.Success===e&&t&&"AccountAdd"===t.Action?t.Result?(a.accountsAndIdentities(),this.cancelCommand()):t.ErrorCode&&this.submitError(n.getNotification(t.ErrorCode)):this.submitError(n.getNotification(i.Notification.UnknownError))},this),this.email(),"",this.password()),!0)},function(){return!this.submitRequest()}),l.constructorEnd(this)}var o=e("../../External/ko.js"),i=e("../../Common/Enums.js"),n=e("../../Common/Utils.js"),r=e("../../Storages/WebMailAjaxRemoteStorage.js"),a=e("../../Boots/RainLoopApp.js"),l=e("../../Knoin/Knoin.js"),c=e("../../Knoin/KnoinAbstractViewModel.js");l.extendAsViewModel("PopupsAddAccountViewModel",s),s.prototype.clearPopup=function(){this.email(""),this.password(""),this.emailError(!1),this.passwordError(!1),this.submitRequest(!1),this.submitError("")},s.prototype.onShow=function(){this.clearPopup()},s.prototype.onFocus=function(){this.emailFocus(!0)},t.exports=new s}(t)},{"../../Boots/RainLoopApp.js":4,"../../Common/Enums.js":7,"../../Common/Utils.js":14,"../../External/ko.js":28,"../../Knoin/Knoin.js":33,"../../Knoin/KnoinAbstractViewModel.js":36,"../../Storages/WebMailAjaxRemoteStorage.js":63}],73:[function(e,t){!function(t){"use strict";function s(){l.call(this,"Popups","PopupsAddOpenPgpKey"),this.key=o.observable(""),this.key.error=o.observable(!1),this.key.focus=o.observable(!1),this.key.subscribe(function(){this.key.error(!1)},this),this.addOpenPgpKeyCommand=i.createCommand(this,function(){var e=30,t=null,s=i.trim(this.key()),o=/[\-]{3,6}BEGIN[\s]PGP[\s](PRIVATE|PUBLIC)[\s]KEY[\s]BLOCK[\-]{3,6}[\s\S]+?[\-]{3,6}END[\s]PGP[\s](PRIVATE|PUBLIC)[\s]KEY[\s]BLOCK[\-]{3,6}/gi,a=n.openpgpKeyring;if(s=s.replace(/[\r\n]([a-zA-Z0-9]{2,}:[^\r\n]+)[\r\n]+([a-zA-Z0-9\/\\+=]{10,})/g,"\n$1!-!N!-!$2").replace(/[\n\r]+/g,"\n").replace(/!-!N!-!/g,"\n\n"),this.key.error(""===s),!a||this.key.error())return!1;for(;;){if(t=o.exec(s),!t||0>e)break;t[0]&&t[1]&&t[2]&&t[1]===t[2]&&("PRIVATE"===t[1]?a.privateKeys.importKey(t[0]):"PUBLIC"===t[1]&&a.publicKeys.importKey(t[0])),e--}return a.store(),r.reloadOpenPgpKeys(),i.delegateRun(this,"cancelCommand"),!0}),a.constructorEnd(this)}var o=e("../../External/ko.js"),i=e("../../Common/Utils.js"),n=e("../../Storages/WebMailDataStorage.js"),r=e("../../Boots/RainLoopApp.js"),a=e("../../Knoin/Knoin.js"),l=e("../../Knoin/KnoinAbstractViewModel.js");a.extendAsViewModel("PopupsAddOpenPgpKeyViewModel",s),s.prototype.clearPopup=function(){this.key(""),this.key.error(!1)},s.prototype.onShow=function(){this.clearPopup()},s.prototype.onFocus=function(){this.key.focus(!0)},t.exports=new s}(t)},{"../../Boots/RainLoopApp.js":4,"../../Common/Utils.js":14,"../../External/ko.js":28,"../../Knoin/Knoin.js":33,"../../Knoin/KnoinAbstractViewModel.js":36,"../../Storages/WebMailDataStorage.js":65}],74:[function(e,t){!function(t){"use strict";function s(){l.call(this,"Popups","PopupsAsk"),this.askDesc=o.observable(""),this.yesButton=o.observable(""),this.noButton=o.observable(""),this.yesFocus=o.observable(!1),this.noFocus=o.observable(!1),this.fYesAction=null,this.fNoAction=null,this.bDisabeCloseOnEsc=!0,this.sDefaultKeyScope=n.KeyState.PopupAsk,a.constructorEnd(this)}var o=e("../../External/ko.js"),i=e("../../External/key.js"),n=e("../../Common/Enums.js"),r=e("../../Common/Utils.js"),a=e("../../Knoin/Knoin.js"),l=e("../../Knoin/KnoinAbstractViewModel.js");a.extendAsViewModel("PopupsAskViewModel",s),s.prototype.clearPopup=function(){this.askDesc(""),this.yesButton(r.i18n("POPUPS_ASK/BUTTON_YES")),this.noButton(r.i18n("POPUPS_ASK/BUTTON_NO")),this.yesFocus(!1),this.noFocus(!1),this.fYesAction=null,this.fNoAction=null},s.prototype.yesClick=function(){this.cancelCommand(),r.isFunc(this.fYesAction)&&this.fYesAction.call(null)},s.prototype.noClick=function(){this.cancelCommand(),r.isFunc(this.fNoAction)&&this.fNoAction.call(null)},s.prototype.onShow=function(e,t,s,o,i){this.clearPopup(),this.fYesAction=t||null,this.fNoAction=s||null,this.askDesc(e||""),o&&this.yesButton(o),o&&this.yesButton(i)},s.prototype.onFocus=function(){this.yesFocus(!0)},s.prototype.onBuild=function(){i("tab, shift+tab, right, left",n.KeyState.PopupAsk,_.bind(function(){return this.yesFocus()?this.noFocus(!0):this.yesFocus(!0),!1},this)),i("esc",n.KeyState.PopupAsk,_.bind(function(){return this.noClick(),!1},this))},t.exports=new s}(t)},{"../../Common/Enums.js":7,"../../Common/Utils.js":14,"../../External/key.js":27,"../../External/ko.js":28,"../../Knoin/Knoin.js":33,"../../Knoin/KnoinAbstractViewModel.js":36}],75:[function(e,t){!function(t){"use strict";
+function s(){y.call(this,"Popups","PopupsCompose"),this.oEditor=null,this.aDraftInfo=null,this.sInReplyTo="",this.bFromDraft=!1,this.bSkipNext=!1,this.sReferences="",this.bCapaAdditionalIdentities=h.capa(a.Capa.AdditionalIdentities);var e=this,t=function(t){!1===e.showCcAndBcc()&&0"},s.prototype.sendMessageResponse=function(e,t){var s=!1,o="";this.sending(!1),a.StorageResultType.Success===e&&t&&t.Result&&(s=!0,this.modalVisibility()&&c.delegateRun(this,"closeCommand")),this.modalVisibility()&&!s&&(t&&a.Notification.CantSaveMessage===t.ErrorCode?(this.sendSuccessButSaveError(!0),window.alert(c.trim(c.i18n("COMPOSE/SAVED_ERROR_ON_SEND")))):(o=c.getNotification(t&&t.ErrorCode?t.ErrorCode:a.Notification.CantSendMessage,t&&t.ErrorMessage?t.ErrorMessage:""),this.sendError(!0),window.alert(o||c.getNotification(a.Notification.CantSendMessage)))),this.reloadDraftFolder()},s.prototype.saveMessageResponse=function(e,t){var s=!1,o=null;this.saving(!1),a.StorageResultType.Success===e&&t&&t.Result&&t.Result.NewFolder&&t.Result.NewUid&&(this.bFromDraft&&(o=m.message(),o&&this.draftFolder()===o.folderFullNameRaw&&this.draftUid()===o.uid&&m.message(null)),this.draftFolder(t.Result.NewFolder),this.draftUid(t.Result.NewUid),this.modalVisibility()&&(this.savedTime(window.Math.round((new window.Date).getTime()/1e3)),this.savedOrSendingText(0 "+e;break;default:e=e+"
"+s}return e},s.prototype.editor=function(e){if(e){var t=this;!this.oEditor&&this.composeEditorArea()?i.delay(function(){t.oEditor=new p(t.composeEditorArea(),null,function(){e(t.oEditor)},function(e){t.isHtml(!!e)})},300):this.oEditor&&e(this.oEditor)}},s.prototype.onShow=function(e,t,s,n,r){S.routeOff();var l=this,u="",d="",p="",h="",g="",b=null,y=null,C="",v="",w=[],E={},A=m.accountEmail(),F=m.signature(),T=m.signatureToAll(),j=[],M=null,R=null,N=e||a.ComposeType.Empty,L=function(e,t){for(var s=0,o=e.length,i=[];o>s;s++)i.push(e[s].toLine(!!t));return i.join(", ")};if(t=t||null,t&&c.isNormal(t)&&(R=c.isArray(t)&&1===t.length?t[0]:c.isArray(t)?null:t),null!==A&&(E[A]=!0),this.currentIdentityID(this.findIdentityIdByMessage(N,R)),this.reset(),c.isNonEmptyArray(s)&&this.to(L(s)),""!==N&&R){switch(h=R.fullFormatDateValue(),g=R.subject(),M=R.aDraftInfo,b=o(R.body).clone(),c.removeBlockquoteSwitcher(b),y=b.find("[data-html-editor-font-wrapper=true]"),C=y&&y[0]?y.html():b.html(),N){case a.ComposeType.Empty:break;case a.ComposeType.Reply:this.to(L(R.replyEmails(E))),this.subject(c.replySubjectAdd("Re",g)),this.prepearMessageAttachments(R,N),this.aDraftInfo=["reply",R.uid,R.folderFullNameRaw],this.sInReplyTo=R.sMessageId,this.sReferences=c.trim(this.sInReplyTo+" "+R.sReferences);break;case a.ComposeType.ReplyAll:w=R.replyAllEmails(E),this.to(L(w[0])),this.cc(L(w[1])),this.subject(c.replySubjectAdd("Re",g)),this.prepearMessageAttachments(R,N),this.aDraftInfo=["reply",R.uid,R.folderFullNameRaw],this.sInReplyTo=R.sMessageId,this.sReferences=c.trim(this.sInReplyTo+" "+R.references());break;case a.ComposeType.Forward:this.subject(c.replySubjectAdd("Fwd",g)),this.prepearMessageAttachments(R,N),this.aDraftInfo=["forward",R.uid,R.folderFullNameRaw],this.sInReplyTo=R.sMessageId,this.sReferences=c.trim(this.sInReplyTo+" "+R.sReferences);break;case a.ComposeType.ForwardAsAttachment:this.subject(c.replySubjectAdd("Fwd",g)),this.prepearMessageAttachments(R,N),this.aDraftInfo=["forward",R.uid,R.folderFullNameRaw],this.sInReplyTo=R.sMessageId,this.sReferences=c.trim(this.sInReplyTo+" "+R.sReferences);break;case a.ComposeType.Draft:this.to(L(R.to)),this.cc(L(R.cc)),this.bcc(L(R.bcc)),this.bFromDraft=!0,this.draftFolder(R.folderFullNameRaw),this.draftUid(R.uid),this.subject(g),this.prepearMessageAttachments(R,N),this.aDraftInfo=c.isNonEmptyArray(M)&&3===M.length?M:null,this.sInReplyTo=R.sInReplyTo,this.sReferences=R.sReferences;break;case a.ComposeType.EditAsNew:this.to(L(R.to)),this.cc(L(R.cc)),this.bcc(L(R.bcc)),this.subject(g),this.prepearMessageAttachments(R,N),this.aDraftInfo=c.isNonEmptyArray(M)&&3===M.length?M:null,this.sInReplyTo=R.sInReplyTo,this.sReferences=R.sReferences}switch(N){case a.ComposeType.Reply:case a.ComposeType.ReplyAll:u=R.fromToLine(!1,!0),v=c.i18n("COMPOSE/REPLY_MESSAGE_TITLE",{DATETIME:h,EMAIL:u}),C="
"+v+":"+C+"
";break;case a.ComposeType.Forward:u=R.fromToLine(!1,!0),d=R.toToLine(!1,!0),p=R.ccToLine(!1,!0),C="
"+c.i18n("COMPOSE/FORWARD_MESSAGE_TOP_TITLE")+"
"+c.i18n("COMPOSE/FORWARD_MESSAGE_TOP_FROM")+": "+u+"
"+c.i18n("COMPOSE/FORWARD_MESSAGE_TOP_TO")+": "+d+(0 "+c.i18n("COMPOSE/FORWARD_MESSAGE_TOP_CC")+": "+p:"")+"
"+c.i18n("COMPOSE/FORWARD_MESSAGE_TOP_SENT")+": "+c.encodeHtml(h)+"
"+c.i18n("COMPOSE/FORWARD_MESSAGE_TOP_SUBJECT")+": "+c.encodeHtml(g)+"
"+C;break;case a.ComposeType.ForwardAsAttachment:C=""}T&&""!==F&&a.ComposeType.EditAsNew!==N&&a.ComposeType.Draft!==N&&(C=this.convertSignature(F,L(R.from,!0),C,N)),this.editor(function(e){e.setHtml(C,!1),R.isHtml()||e.modeToggle(!1)})}else a.ComposeType.Empty===N?(this.subject(c.isNormal(n)?""+n:""),C=c.isNormal(r)?""+r:"",T&&""!==F&&(C=this.convertSignature(F,"",c.convertPlainTextToHtml(C),N)),this.editor(function(e){e.setHtml(C,!1),a.EditorDefaultType.Html!==m.editorDefaultType()&&e.modeToggle(!1)})):c.isNonEmptyArray(t)&&i.each(t,function(e){l.addMessageAsAttachment(e)});j=this.getAttachmentsDownloadsForUpload(),c.isNonEmptyArray(j)&&f.messageUploadAttachments(function(e,t){if(a.StorageResultType.Success===e&&t&&t.Result){var s=null,o="";if(!l.viewModelVisibility())for(o in t.Result)t.Result.hasOwnProperty(o)&&(s=l.getAttachmentById(t.Result[o]),s&&s.tempName(o))}else l.setMessageAttachmentFailedDowbloadText()},j),this.triggerForResize()},s.prototype.onFocus=function(){""===this.to()?this.to.focusTrigger(!this.to.focusTrigger()):this.oEditor&&this.oEditor.focus(),this.triggerForResize()},s.prototype.editorResize=function(){this.oEditor&&this.oEditor.resize()},s.prototype.tryToClosePopup=function(){var e=this;S.isPopupVisible(PopupsAskViewModel)||S.showScreenPopup(PopupsAskViewModel,[c.i18n("POPUPS_ASK/DESC_WANT_CLOSE_THIS_WINDOW"),function(){e.modalVisibility()&&c.delegateRun(e,"closeCommand")}])},s.prototype.onBuild=function(){this.initUploader();var e=this,t=null;key("ctrl+q, command+q",a.KeyState.Compose,function(){return e.identitiesDropdownTrigger(!0),!1}),key("ctrl+s, command+s",a.KeyState.Compose,function(){return e.saveCommand(),!1}),key("ctrl+enter, command+enter",a.KeyState.Compose,function(){return e.sendCommand(),!1}),key("esc",a.KeyState.Compose,function(){return e.modalVisibility()&&e.tryToClosePopup(),!1}),$window.on("resize",function(){e.triggerForResize()}),this.dropboxEnabled()&&(t=document.createElement("script"),t.type="text/javascript",t.src="https://www.dropbox.com/static/api/1/dropins.js",o(t).attr("id","dropboxjs").attr("data-app-key",h.settingsGet("DropboxApiKey")),document.body.appendChild(t)),this.driveEnabled()&&o.getScript("https://apis.google.com/js/api.js",function(){window.gapi&&e.driveVisible(!0)})},s.prototype.driveCallback=function(e,t){if(t&&window.XMLHttpRequest&&window.google&&t[window.google.picker.Response.ACTION]===window.google.picker.Action.PICKED&&t[window.google.picker.Response.DOCUMENTS]&&t[window.google.picker.Response.DOCUMENTS][0]&&t[window.google.picker.Response.DOCUMENTS][0].id){var s=this,o=new window.XMLHttpRequest;o.open("GET","https://www.googleapis.com/drive/v2/files/"+t[window.google.picker.Response.DOCUMENTS][0].id),o.setRequestHeader("Authorization","Bearer "+e),o.addEventListener("load",function(){if(o&&o.responseText){var t=JSON.parse(o.responseText),i=function(e,t,s){e&&e.exportLinks&&(e.exportLinks[t]?(e.downloadUrl=e.exportLinks[t],e.title=e.title+"."+s,e.mimeType=t):e.exportLinks["application/pdf"]&&(e.downloadUrl=e.exportLinks["application/pdf"],e.title=e.title+".pdf",e.mimeType="application/pdf"))};if(t&&!t.downloadUrl&&t.mimeType&&t.exportLinks)switch(t.mimeType.toString().toLowerCase()){case"application/vnd.google-apps.document":i(t,"application/vnd.openxmlformats-officedocument.wordprocessingml.document","docx");break;case"application/vnd.google-apps.spreadsheet":i(t,"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","xlsx");break;case"application/vnd.google-apps.drawing":i(t,"image/png","png");break;case"application/vnd.google-apps.presentation":i(t,"application/vnd.openxmlformats-officedocument.presentationml.presentation","pptx");break;default:i(t,"application/pdf","pdf")}t&&t.downloadUrl&&s.addDriveAttachment(t,e)}}),o.send()}},s.prototype.driveCreatePiker=function(e){if(window.gapi&&e&&e.access_token){var t=this;window.gapi.load("picker",{callback:function(){if(window.google&&window.google.picker){var s=(new window.google.picker.PickerBuilder).addView((new window.google.picker.DocsView).setIncludeFolders(!0)).setAppId(h.settingsGet("GoogleClientID")).setOAuthToken(e.access_token).setCallback(i.bind(t.driveCallback,t,e.access_token)).enableFeature(window.google.picker.Feature.NAV_HIDDEN).build();s.setVisible(!0)}}})}},s.prototype.driveOpenPopup=function(){if(window.gapi){var e=this;window.gapi.load("auth",{callback:function(){var t=window.gapi.auth.getToken();t?e.driveCreatePiker(t):window.gapi.auth.authorize({client_id:h.settingsGet("GoogleClientID"),scope:"https://www.googleapis.com/auth/drive.readonly",immediate:!0},function(t){if(t&&!t.error){var s=window.gapi.auth.getToken();s&&e.driveCreatePiker(s)}else window.gapi.auth.authorize({client_id:h.settingsGet("GoogleClientID"),scope:"https://www.googleapis.com/auth/drive.readonly",immediate:!1},function(t){if(t&&!t.error){var s=window.gapi.auth.getToken();s&&e.driveCreatePiker(s)}})})}})}},s.prototype.getAttachmentById=function(e){for(var t=this.attachments(),s=0,o=t.length;o>s;s++)if(t[s]&&e===t[s].id)return t[s];return null},s.prototype.initUploader=function(){if(this.composeUploaderButton()){var e={},t=c.pInt(h.settingsGet("AttachmentLimit")),s=new Jua({action:u.upload(),name:"uploader",queueSize:2,multipleSizeLimit:50,disableFolderDragAndDrop:!1,clickElement:this.composeUploaderButton(),dragAndDropElement:this.composeUploaderDropPlace()});s?(s.on("onDragEnter",i.bind(function(){this.dragAndDropOver(!0)},this)).on("onDragLeave",i.bind(function(){this.dragAndDropOver(!1)},this)).on("onBodyDragEnter",i.bind(function(){this.dragAndDropVisible(!0)},this)).on("onBodyDragLeave",i.bind(function(){this.dragAndDropVisible(!1)},this)).on("onProgress",i.bind(function(t,s,o){var i=null;c.isUnd(e[t])?(i=this.getAttachmentById(t),i&&(e[t]=i)):i=e[t],i&&i.progress(" - "+Math.floor(s/o*100)+"%")},this)).on("onSelect",i.bind(function(e,o){this.dragAndDropOver(!1);var i=this,n=c.isUnd(o.FileName)?"":o.FileName.toString(),r=c.isNormal(o.Size)?c.pInt(o.Size):null,a=new ComposeAttachmentModel(e,n,r);return a.cancel=function(e){return function(){i.attachments.remove(function(t){return t&&t.id===e}),s&&s.cancel(e)}}(e),this.attachments.push(a),r>0&&t>0&&r>t?(a.error(c.i18n("UPLOAD/ERROR_FILE_IS_TOO_BIG")),!1):!0},this)).on("onStart",i.bind(function(t){var s=null;c.isUnd(e[t])?(s=this.getAttachmentById(t),s&&(e[t]=s)):s=e[t],s&&(s.waiting(!1),s.uploading(!0))},this)).on("onComplete",i.bind(function(t,s,o){var i="",n=null,r=null,a=this.getAttachmentById(t);r=s&&o&&o.Result&&o.Result.Attachment?o.Result.Attachment:null,n=o&&o.Result&&o.Result.ErrorCode?o.Result.ErrorCode:null,null!==n?i=c.getUploadErrorDescByCode(n):r||(i=c.i18n("UPLOAD/ERROR_UNKNOWN")),a&&(""!==i&&00&&i>0&&n>i?(s.uploading(!1),s.error(c.i18n("UPLOAD/ERROR_FILE_IS_TOO_BIG")),!1):(f.composeUploadExternals(function(e,t){var o=!1;s.uploading(!1),a.StorageResultType.Success===e&&t&&t.Result&&t.Result[s.id]&&(o=!0,s.tempName(t.Result[s.id])),o||s.error(c.getUploadErrorDescByCode(a.UploadErrorCode.FileNoUploaded))},[e.link]),!0)},s.prototype.addDriveAttachment=function(e,t){var s=this,o=function(e){return function(){s.attachments.remove(function(t){return t&&t.id===e})}},i=c.pInt(h.settingsGet("AttachmentLimit")),n=null,r=e.fileSize?c.pInt(e.fileSize):0;return n=new ComposeAttachmentModel(e.downloadUrl,e.title,r),n.fromMessage=!1,n.cancel=o(e.downloadUrl),n.waiting(!1).uploading(!0),this.attachments.push(n),r>0&&i>0&&r>i?(n.uploading(!1),n.error(c.i18n("UPLOAD/ERROR_FILE_IS_TOO_BIG")),!1):(f.composeUploadDrive(function(e,t){var s=!1;n.uploading(!1),a.StorageResultType.Success===e&&t&&t.Result&&t.Result[n.id]&&(s=!0,n.tempName(t.Result[n.id][0]),n.size(c.pInt(t.Result[n.id][1]))),s||n.error(c.getUploadErrorDescByCode(a.UploadErrorCode.FileNoUploaded))},e.downloadUrl,t),!0)},s.prototype.prepearMessageAttachments=function(e,t){if(e){var s=this,o=c.isNonEmptyArray(e.attachments())?e.attachments():[],i=0,n=o.length,r=null,l=null,u=!1,d=function(e){return function(){s.attachments.remove(function(t){return t&&t.id===e})}};if(a.ComposeType.ForwardAsAttachment===t)this.addMessageAsAttachment(e);else for(;n>i;i++){switch(l=o[i],u=!1,t){case a.ComposeType.Reply:case a.ComposeType.ReplyAll:u=l.isLinked;break;case a.ComposeType.Forward:case a.ComposeType.Draft:case a.ComposeType.EditAsNew:u=!0}u&&(r=new ComposeAttachmentModel(l.download,l.fileName,l.estimatedSize,l.isInline,l.isLinked,l.cid,l.contentLocation),r.fromMessage=!0,r.cancel=d(l.download),r.waiting(!1).uploading(!0),this.attachments.push(r))}}},s.prototype.removeLinkedAttachments=function(){this.attachments.remove(function(e){return e&&e.isLinked})},s.prototype.setMessageAttachmentFailedDowbloadText=function(){i.each(this.attachments(),function(e){e&&e.fromMessage&&e.waiting(!1).uploading(!1).error(c.getUploadErrorDescByCode(a.UploadErrorCode.FileNoUploaded))},this)},s.prototype.isEmptyForm=function(e){e=c.isUnd(e)?!0:!!e;var t=e?0===this.attachments().length:0===this.attachmentsInReady().length;return 0===this.to().length&&0===this.cc().length&&0===this.bcc().length&&0===this.subject().length&&t&&(!this.oEditor||""===this.oEditor.getData())},s.prototype.reset=function(){this.to(""),this.cc(""),this.bcc(""),this.replyTo(""),this.subject(""),this.requestReadReceipt(!1),this.aDraftInfo=null,this.sInReplyTo="",this.bFromDraft=!1,this.sReferences="",this.sendError(!1),this.sendSuccessButSaveError(!1),this.savedError(!1),this.savedTime(0),this.savedOrSendingText(""),this.emptyToError(!1),this.attachmentsInProcessError(!1),this.showCcAndBcc(!1),this.attachments([]),this.dragAndDropOver(!1),this.dragAndDropVisible(!1),this.draftFolder(""),this.draftUid(""),this.sending(!1),this.saving(!1),this.oEditor&&this.oEditor.clear(!1)},s.prototype.getAttachmentsDownloadsForUpload=function(){return i.map(i.filter(this.attachments(),function(e){return e&&""===e.tempName()}),function(e){return e.id})},s.prototype.triggerForResize=function(){this.resizer(!this.resizer()),this.editorResizeThrottle()},t.exports=new s}(t)},{"../../Boots/RainLoopApp.js":4,"../../Common/Consts.js":6,"../../Common/Enums.js":7,"../../Common/Events.js":8,"../../Common/LinkBuilder.js":10,"../../Common/NewHtmlEditorWrapper.js":11,"../../Common/Utils.js":14,"../../External/jquery.js":26,"../../External/ko.js":28,"../../External/moment.js":29,"../../External/underscore.js":31,"../../Knoin/Knoin.js":33,"../../Knoin/KnoinAbstractViewModel.js":36,"../../Storages/AppSettings.js":59,"../../Storages/WebMailAjaxRemoteStorage.js":63,"../../Storages/WebMailCacheStorage.js":64,"../../Storages/WebMailDataStorage.js":65}],76:[function(e,t){!function(t){"use strict";function s(){l.call(this,"Popups","PopupsFilter"),this.filter=o.observable(null),this.selectedFolderValue=o.observable(i.Values.UnuseOptionValue),this.folderSelectList=r.folderMenuForMove,this.defautOptionsAfterRender=n.defautOptionsAfterRender,a.constructorEnd(this)}var o=e("../../External/ko.js"),i=e("../../Common/Consts.js"),n=e("../../Common/Utils.js"),r=e("../../Storages/WebMailDataStorage.js"),a=e("../../Knoin/Knoin.js"),l=e("../../Knoin/KnoinAbstractViewModel.js");a.extendAsViewModel("PopupsFilterViewModel",s),s.prototype.clearPopup=function(){},s.prototype.onShow=function(e){this.clearPopup(),this.filter(e)},t.exports=new s}(t)},{"../../Common/Consts.js":6,"../../Common/Utils.js":14,"../../External/ko.js":28,"../../Knoin/Knoin.js":33,"../../Knoin/KnoinAbstractViewModel.js":36,"../../Storages/WebMailDataStorage.js":65}],77:[function(e,t){!function(t){"use strict";function s(){d.call(this,"Popups","PopupsFolderCreate"),r.initOnStartOrLangChange(function(){this.sNoParentText=r.i18n("POPUPS_CREATE_FOLDER/SELECT_NO_PARENT")},this),this.folderName=o.observable(""),this.folderName.focused=o.observable(!1),this.selectedParentValue=o.observable(n.Values.UnuseOptionValue),this.parentFolderSelectList=o.computed(function(){var e=[],t=null,s=null,o=a.folderList(),i=function(e){return e?e.isSystemFolder()?e.name()+" "+e.manageFolderSystemName():e.name():""};return e.push(["",this.sNoParentText]),""!==a.namespace&&(t=function(e){return a.namespace!==e.fullNameRaw.substr(0,a.namespace.length)}),r.folderListOptionsBuilder([],o,[],e,null,t,s,i)},this),this.createFolder=r.createCommand(this,function(){var e=this.selectedParentValue();""===e&&1"),this.submitRequest(!0),_.delay(function(){s=o.openpgp.generateKeyPair({userId:t,numBits:n.pInt(e.keyBitLength()),passphrase:n.trim(e.password())}),s&&s.privateKeyArmored&&(i.privateKeys.importKey(s.privateKeyArmored),i.publicKeys.importKey(s.publicKeyArmored),i.store(),a.reloadOpenPgpKeys(),n.delegateRun(e,"cancelCommand")),e.submitRequest(!1)},100),!0)}),l.constructorEnd(this)}var o=e("../../External/window.js"),i=e("../../External/ko.js"),n=e("../../Common/Utils.js"),r=e("../../Storages/WebMailDataStorage.js"),a=e("../../Boots/RainLoopApp.js"),l=e("../../Knoin/Knoin.js"),c=e("../../Knoin/KnoinAbstractViewModel.js");l.extendAsViewModel("PopupsGenerateNewOpenPgpKeyViewModel",s),s.prototype.clearPopup=function(){this.name(""),this.password(""),this.email(""),this.email.error(!1),this.keyBitLength(2048)},s.prototype.onShow=function(){this.clearPopup()},s.prototype.onFocus=function(){this.email.focus(!0)},t.exports=new s}(t)},{"../../Boots/RainLoopApp.js":4,"../../Common/Utils.js":14,"../../External/ko.js":28,"../../External/window.js":32,"../../Knoin/Knoin.js":33,"../../Knoin/KnoinAbstractViewModel.js":36,"../../Storages/WebMailDataStorage.js":65}],80:[function(e,t){!function(t){"use strict";function s(){u.call(this,"Popups","PopupsIdentity"),this.id="",this.edit=o.observable(!1),this.owner=o.observable(!1),this.email=o.observable("").validateEmail(),this.email.focused=o.observable(!1),this.name=o.observable(""),this.name.focused=o.observable(!1),this.replyTo=o.observable("").validateSimpleEmail(),this.replyTo.focused=o.observable(!1),this.bcc=o.observable("").validateSimpleEmail(),this.bcc.focused=o.observable(!1),this.submitRequest=o.observable(!1),this.submitError=o.observable(""),this.addOrEditIdentityCommand=n.createCommand(this,function(){return this.email.hasError()||this.email.hasError(""===n.trim(this.email())),this.email.hasError()?(this.owner()||this.email.focused(!0),!1):this.replyTo.hasError()?(this.replyTo.focused(!0),!1):this.bcc.hasError()?(this.bcc.focused(!0),!1):(this.submitRequest(!0),a.identityUpdate(_.bind(function(e,t){this.submitRequest(!1),i.StorageResultType.Success===e&&t?t.Result?(c.accountsAndIdentities(),this.cancelCommand()):t.ErrorCode&&this.submitError(n.getNotification(t.ErrorCode)):this.submitError(n.getNotification(i.Notification.UnknownError))},this),this.id,this.email(),this.name(),this.replyTo(),this.bcc()),!0)},function(){return!this.submitRequest()}),this.label=o.computed(function(){return n.i18n("POPUPS_IDENTITIES/"+(this.edit()?"TITLE_UPDATE_IDENTITY":"TITLE_ADD_IDENTITY"))},this),this.button=o.computed(function(){return n.i18n("POPUPS_IDENTITIES/"+(this.edit()?"BUTTON_UPDATE_IDENTITY":"BUTTON_ADD_IDENTITY"))},this),r.constructorEnd(this)}var o=e("../../External/ko.js"),i=e("../../Common/Enums.js"),n=e("../../Common/Utils.js"),r=e("../../Knoin/Knoin.js"),a=e("../../Storages/WebMailAjaxRemoteStorage.js"),l=e("../../Storages/WebMailDataStorage.js"),c=e("../../Boots/RainLoopApp.js"),u=e("../../Knoin/KnoinAbstractViewModel.js");r.extendAsViewModel("PopupsIdentityViewModel",s),s.prototype.clearPopup=function(){this.id="",this.edit(!1),this.owner(!1),this.name(""),this.email(""),this.replyTo(""),this.bcc(""),this.email.hasError(!1),this.replyTo.hasError(!1),this.bcc.hasError(!1),this.submitRequest(!1),this.submitError("")},s.prototype.onShow=function(e){this.clearPopup(),e&&(this.edit(!0),this.id=e.id,this.name(e.name()),this.email(e.email()),this.replyTo(e.replyTo()),this.bcc(e.bcc()),this.owner(this.id===l.accountEmail()))},s.prototype.onFocus=function(){this.owner()||this.email.focused(!0)},t.exports=new s}(t)},{"../../Boots/RainLoopApp.js":4,"../../Common/Enums.js":7,"../../Common/Utils.js":14,"../../External/ko.js":28,"../../Knoin/Knoin.js":33,"../../Knoin/KnoinAbstractViewModel.js":36,"../../Storages/WebMailAjaxRemoteStorage.js":63,"../../Storages/WebMailDataStorage.js":65}],81:[function(e,t){!function(t){"use strict";function s(){a.call(this,"Popups","PopupsKeyboardShortcutsHelp"),this.sDefaultKeyScope=n.KeyState.PopupKeyboardShortcutsHelp,r.constructorEnd(this)}var o=e("../../External/underscore.js"),i=e("../../External/key.js"),n=e("../../Common/Enums.js"),r=(e("../../Common/Utils.js"),e("../../Knoin/Knoin.js")),a=e("../../Knoin/KnoinAbstractViewModel.js");r.extendAsViewModel("PopupsKeyboardShortcutsHelpViewModel",s),s.prototype.onBuild=function(e){i("tab, shift+tab, left, right",n.KeyState.PopupKeyboardShortcutsHelp,o.bind(function(t,s){if(t&&s){var o=e.find(".nav.nav-tabs > li"),i=s&&("tab"===s.shortcut||"right"===s.shortcut),n=o.index(o.filter(".active"));return!i&&n>0?n--:i&&n').appendTo('body');
-
- $window.on('error', function (oEvent) {
- if (oEvent && oEvent.originalEvent && oEvent.originalEvent.message &&
- -1 === Utils.inArray(oEvent.originalEvent.message, [
- 'Script error.', 'Uncaught Error: Error calling method on NPObject.'
- ]))
- {
- Remote().jsError(
- Utils.emptyFunction,
- oEvent.originalEvent.message,
- oEvent.originalEvent.filename,
- oEvent.originalEvent.lineno,
- window.location && window.location.toString ? window.location.toString() : '',
- $html.attr('class'),
- Utils.microtime() - Globals.now
- );
- }
- });
-
- $doc.on('keydown', function (oEvent) {
- if (oEvent && oEvent.ctrlKey)
- {
- $html.addClass('rl-ctrl-key-pressed');
- }
- }).on('keyup', function (oEvent) {
- if (oEvent && !oEvent.ctrlKey)
- {
- $html.removeClass('rl-ctrl-key-pressed');
- }
- });
- }
-
- _.extend(AbstractApp.prototype, KnoinAbstractBoot.prototype);
-
- AbstractApp.prototype.oSettings = null;
- AbstractApp.prototype.oPlugins = null;
- AbstractApp.prototype.oLocal = null;
- AbstractApp.prototype.oLink = null;
- AbstractApp.prototype.oSubs = {};
-
- /**
- * @param {string} sLink
- * @return {boolean}
- */
- AbstractApp.prototype.download = function (sLink)
- {
- var
- oE = null,
- oLink = null,
- sUserAgent = window.navigator.userAgent.toLowerCase()
- ;
-
- if (sUserAgent && (sUserAgent.indexOf('chrome') > -1 || sUserAgent.indexOf('chrome') > -1))
- {
- oLink = window.document.createElement('a');
- oLink['href'] = sLink;
-
- if (window.document['createEvent'])
- {
- oE = window.document['createEvent']('MouseEvents');
- if (oE && oE['initEvent'] && oLink['dispatchEvent'])
- {
- oE['initEvent']('click', true, true);
- oLink['dispatchEvent'](oE);
- return true;
- }
- }
- }
-
- if (Globals.bMobileDevice)
- {
- window.open(sLink, '_self');
- window.focus();
- }
- else
- {
- this.iframe.attr('src', sLink);
- // window.document.location.href = sLink;
- }
-
- return true;
- };
-
- /**
- * @param {string} sName
- * @return {?}
- */
- AbstractApp.prototype.settingsGet = function (sName)
- {
- if (null === this.oSettings)
- {
- this.oSettings = Utils.isNormal(AppData) ? AppData : {};
- }
-
- return Utils.isUnd(this.oSettings[sName]) ? null : this.oSettings[sName];
- };
-
- /**
- * @param {string} sName
- * @param {?} mValue
- */
- AbstractApp.prototype.settingsSet = function (sName, mValue)
- {
- if (null === this.oSettings)
- {
- this.oSettings = Utils.isNormal(AppData) ? AppData : {};
- }
-
- this.oSettings[sName] = mValue;
- };
-
- AbstractApp.prototype.setTitle = function (sTitle)
- {
- sTitle = ((Utils.isNormal(sTitle) && 0 < sTitle.length) ? sTitle + ' - ' : '') +
- this.settingsGet('Title') || '';
-
- window.document.title = '_';
- window.document.title = sTitle;
- };
-
- /**
- * @param {boolean=} bLogout = false
- * @param {boolean=} bClose = false
- */
- AbstractApp.prototype.loginAndLogoutReload = function (bLogout, bClose)
- {
- var
- sCustomLogoutLink = Utils.pString(this.settingsGet('CustomLogoutLink')),
- bInIframe = !!this.settingsGet('InIframe')
- ;
-
- bLogout = Utils.isUnd(bLogout) ? false : !!bLogout;
- bClose = Utils.isUnd(bClose) ? false : !!bClose;
-
- if (bLogout && bClose && window.close)
- {
- window.close();
- }
-
- if (bLogout && '' !== sCustomLogoutLink && window.location.href !== sCustomLogoutLink)
- {
- _.delay(function () {
- if (bInIframe && window.parent)
- {
- window.parent.location.href = sCustomLogoutLink;
- }
- else
- {
- window.location.href = sCustomLogoutLink;
- }
- }, 100);
- }
- else
- {
- kn.routeOff();
- kn.setHash(LinkBuilder.root(), true);
- kn.routeOff();
-
- _.delay(function () {
- if (bInIframe && window.parent)
- {
- window.parent.location.reload();
- }
- else
- {
- window.location.reload();
- }
- }, 100);
- }
- };
-
- AbstractApp.prototype.historyBack = function ()
- {
- window.history.back();
- };
-
- /**
- * @param {string} sQuery
- * @param {Function} fCallback
- */
- AbstractApp.prototype.getAutocomplete = function (sQuery, fCallback)
- {
- fCallback([], sQuery);
- };
-
- /**
- * @param {string} sName
- * @param {Function} fFunc
- * @param {Object=} oContext
- * @return {AbstractApp}
- */
- AbstractApp.prototype.sub = function (sName, fFunc, oContext)
- {
- if (Utils.isUnd(this.oSubs[sName]))
- {
- this.oSubs[sName] = [];
- }
-
- this.oSubs[sName].push([fFunc, oContext]);
-
- return this;
- };
-
- /**
- * @param {string} sName
- * @param {Array=} aArgs
- * @return {AbstractApp}
- */
- AbstractApp.prototype.pub = function (sName, aArgs)
- {
- Plugins.runHook('rl-pub', [sName, aArgs]);
- if (!Utils.isUnd(this.oSubs[sName]))
- {
- _.each(this.oSubs[sName], function (aItem) {
- if (aItem[0])
- {
- aItem[0].apply(aItem[1] || null, aArgs || []);
- }
- });
- }
-
- return this;
- };
-
- /**
- * @param {string} sName
- * @return {boolean}
- */
- AbstractApp.prototype.capa = function (sName)
- {
- var mCapa = this.settingsGet('Capa');
- return Utils.isArray(mCapa) && Utils.isNormal(sName) && -1 < Utils.inArray(sName, mCapa);
- };
-
- AbstractApp.prototype.bootstart = function ()
- {
- var
- self = this,
- ssm = require('../External/ssm.js')
- ;
-
- Utils.initOnStartOrLangChange(function () {
- Utils.initNotificationLanguage();
- }, null);
-
- _.delay(function () {
- Utils.windowResize();
- }, 1000);
-
- ssm.addState({
- 'id': 'mobile',
- 'maxWidth': 767,
- 'onEnter': function() {
- $html.addClass('ssm-state-mobile');
- self.pub('ssm.mobile-enter');
- },
- 'onLeave': function() {
- $html.removeClass('ssm-state-mobile');
- self.pub('ssm.mobile-leave');
- }
- });
-
- ssm.addState({
- 'id': 'tablet',
- 'minWidth': 768,
- 'maxWidth': 999,
- 'onEnter': function() {
- $html.addClass('ssm-state-tablet');
- },
- 'onLeave': function() {
- $html.removeClass('ssm-state-tablet');
- }
- });
-
- ssm.addState({
- 'id': 'desktop',
- 'minWidth': 1000,
- 'maxWidth': 1400,
- 'onEnter': function() {
- $html.addClass('ssm-state-desktop');
- },
- 'onLeave': function() {
- $html.removeClass('ssm-state-desktop');
- }
- });
-
- ssm.addState({
- 'id': 'desktop-large',
- 'minWidth': 1400,
- 'onEnter': function() {
- $html.addClass('ssm-state-desktop-large');
- },
- 'onLeave': function() {
- $html.removeClass('ssm-state-desktop-large');
- }
- });
-
- this.sub('ssm.mobile-enter', function () {
- RL.data().leftPanelDisabled(true); // TODO cjs
- });
-
- this.sub('ssm.mobile-leave', function () {
- RL.data().leftPanelDisabled(false); // TODO cjs
- });
-
- RL.data().leftPanelDisabled.subscribe(function (bValue) { // TODO cjs
- $html.toggleClass('rl-left-panel-disabled', bValue);
- });
-
- ssm.ready();
- };
-
- module.exports = AbstractApp;
-
-}(module));
-},{"../Common/Globals.js":6,"../Common/LinkBuilder.js":7,"../Common/Plugins.js":8,"../Common/Utils.js":9,"../External/$doc.js":11,"../External/$html.js":12,"../External/$window.js":13,"../External/AppData.js":14,"../External/jquery.js":19,"../External/ko.js":21,"../External/ssm.js":23,"../External/underscore.js":24,"../External/window.js":25,"../Knoin/Knoin.js":26,"../Knoin/KnoinAbstractBoot.js":27,"../Remote.js":33}],3:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-(function (module) {
-
- 'use strict';
-
- var
- window = require('../External/window.js'),
- $ = require('../External/jquery.js'),
- _ = require('../External/underscore.js'),
- moment = require('../External/moment.js'),
-
- Enums = require('../Common/Enums.js'),
- Globals = require('../Common/Globals.js'),
- Consts = require('../Common/Consts.js'),
- Plugins = require('../Common/Plugins.js'),
- Utils = require('../Common/Utils.js'),
- LinkBuilder = require('../Common/LinkBuilder.js'),
-
- kn = require('../Knoin/Knoin.js'),
-
- Data = require('../Storages/WebMailDataStorage.js'),
- Cache = require('../Storages/WebMailCacheStorage.js'),
- Remote = require('../Storages/WebMailAjaxRemoteStorage.js'),
-
- PopupsFolderSystemViewModel = require('../ViewModels/Popups/PopupsAskViewModel.js'),
- PopupsAskViewModel = require('../ViewModels/Popups/PopupsAskViewModel.js'),
-
- AbstractApp = require('./AbstractApp.js')
- ;
-
- /**
- * @constructor
- * @extends AbstractApp
- */
- function RainLoopApp()
- {
- AbstractApp.call(this);
-
- this.oData = null;
- this.oRemote = null;
- this.oCache = null;
- this.oMoveCache = {};
-
- this.quotaDebounce = _.debounce(this.quota, 1000 * 30);
- this.moveOrDeleteResponseHelper = _.bind(this.moveOrDeleteResponseHelper, this);
-
- this.messagesMoveTrigger = _.debounce(this.messagesMoveTrigger, 500);
-
- window.setInterval(function () {
- RL.pub('interval.30s');
- }, 30000);
-
- window.setInterval(function () {
- RL.pub('interval.1m');
- }, 60000);
-
- window.setInterval(function () {
- RL.pub('interval.2m');
- }, 60000 * 2);
-
- window.setInterval(function () {
- RL.pub('interval.3m');
- }, 60000 * 3);
-
- window.setInterval(function () {
- RL.pub('interval.5m');
- }, 60000 * 5);
-
- window.setInterval(function () {
- RL.pub('interval.10m');
- }, 60000 * 10);
-
- window.setTimeout(function () {
- window.setInterval(function () {
- RL.pub('interval.10m-after5m');
- }, 60000 * 10);
- }, 60000 * 5);
-
- $.wakeUp(function () {
- Remote.jsVersion(function (sResult, oData) {
- if (Enums.StorageResultType.Success === sResult && oData && !oData.Result)
- {
- if (window.parent && !!RL.settingsGet('InIframe'))
- {
- window.parent.location.reload();
- }
- else
- {
- window.location.reload();
- }
- }
- }, RL.settingsGet('Version'));
- }, {}, 60 * 60 * 1000);
- }
-
- _.extend(RainLoopApp.prototype, AbstractApp.prototype);
-
- RainLoopApp.prototype.oData = null;
- RainLoopApp.prototype.oRemote = null;
- RainLoopApp.prototype.oCache = null;
-
- /**
- * @return {WebMailDataStorage}
- */
- RainLoopApp.prototype.data = function ()
- {
- if (null === this.oData)
- {
- this.oData = new WebMailDataStorage();
- }
-
- return this.oData;
- };
-
- /**
- * @return {WebMailAjaxRemoteStorage}
- */
- RainLoopApp.prototype.remote = function ()
- {
- if (null === this.oRemote)
- {
- this.oRemote = new WebMailAjaxRemoteStorage();
- }
-
- return this.oRemote;
- };
-
- RainLoopApp.prototype.reloadFlagsCurrentMessageListAndMessageFromCache = function ()
- {
- _.each(Data.messageList(), function (oMessage) {
- Cache.initMessageFlagsFromCache(oMessage);
- });
-
- Cache.initMessageFlagsFromCache(Data.message());
- };
-
- /**
- * @param {boolean=} bDropPagePosition = false
- * @param {boolean=} bDropCurrenFolderCache = false
- */
- RainLoopApp.prototype.reloadMessageList = function (bDropPagePosition, bDropCurrenFolderCache)
- {
- var
- iOffset = (Data.messageListPage() - 1) * Data.messagesPerPage()
- ;
-
- if (Utils.isUnd(bDropCurrenFolderCache) ? false : !!bDropCurrenFolderCache)
- {
- Cache.setFolderHash(Data.currentFolderFullNameRaw(), '');
- }
-
- if (Utils.isUnd(bDropPagePosition) ? false : !!bDropPagePosition)
- {
- Data.messageListPage(1);
- iOffset = 0;
- }
-
- Data.messageListLoading(true);
- Remote.messageList(function (sResult, oData, bCached) {
-
- if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
- {
- Data.messageListError('');
- Data.messageListLoading(false);
- Data.setMessageList(oData, bCached);
- }
- else if (Enums.StorageResultType.Unload === sResult)
- {
- Data.messageListError('');
- Data.messageListLoading(false);
- }
- else if (Enums.StorageResultType.Abort !== sResult)
- {
- Data.messageList([]);
- Data.messageListLoading(false);
- Data.messageListError(oData && oData.ErrorCode ?
- Utils.getNotification(oData.ErrorCode) : Utils.i18n('NOTIFICATIONS/CANT_GET_MESSAGE_LIST')
- );
- }
-
- }, Data.currentFolderFullNameRaw(), iOffset, Data.messagesPerPage(), Data.messageListSearch());
- };
-
- RainLoopApp.prototype.recacheInboxMessageList = function ()
- {
- Remote.messageList(Utils.emptyFunction, 'INBOX', 0, Data.messagesPerPage(), '', true);
- };
-
- RainLoopApp.prototype.reloadMessageListHelper = function (bEmptyList)
- {
- RL.reloadMessageList(bEmptyList);
- };
-
- /**
- * @param {Function} fResultFunc
- * @returns {boolean}
- */
- RainLoopApp.prototype.contactsSync = function (fResultFunc)
- {
- var oContacts = Data.contacts;
- if (oContacts.importing() || oContacts.syncing() || !Data.enableContactsSync() || !Data.allowContactsSync())
- {
- return false;
- }
-
- oContacts.syncing(true);
-
- Remote.contactsSync(function (sResult, oData) {
-
- oContacts.syncing(false);
-
- if (fResultFunc)
- {
- fResultFunc(sResult, oData);
- }
- });
-
- return true;
- };
-
- RainLoopApp.prototype.messagesMoveTrigger = function ()
- {
- var
- self = this,
- sSpamFolder = Data.spamFolder()
- ;
-
- _.each(this.oMoveCache, function (oItem) {
-
- var
- bSpam = sSpamFolder === oItem['To'],
- bHam = !bSpam && sSpamFolder === oItem['From'] && 'INBOX' === oItem['To']
- ;
-
- Remote.messagesMove(self.moveOrDeleteResponseHelper, oItem['From'], oItem['To'], oItem['Uid'],
- bSpam ? 'SPAM' : (bHam ? 'HAM' : ''));
- });
-
- this.oMoveCache = {};
- };
-
- RainLoopApp.prototype.messagesMoveHelper = function (sFromFolderFullNameRaw, sToFolderFullNameRaw, aUidForMove)
- {
- var sH = '$$' + sFromFolderFullNameRaw + '$$' + sToFolderFullNameRaw + '$$';
- if (!this.oMoveCache[sH])
- {
- this.oMoveCache[sH] = {
- 'From': sFromFolderFullNameRaw,
- 'To': sToFolderFullNameRaw,
- 'Uid': []
- };
- }
-
- this.oMoveCache[sH]['Uid'] = _.union(this.oMoveCache[sH]['Uid'], aUidForMove);
- this.messagesMoveTrigger();
- };
-
- RainLoopApp.prototype.messagesCopyHelper = function (sFromFolderFullNameRaw, sToFolderFullNameRaw, aUidForCopy)
- {
- Remote.messagesCopy(
- this.moveOrDeleteResponseHelper,
- sFromFolderFullNameRaw,
- sToFolderFullNameRaw,
- aUidForCopy
- );
- };
-
- RainLoopApp.prototype.messagesDeleteHelper = function (sFromFolderFullNameRaw, aUidForRemove)
- {
- Remote.messagesDelete(
- this.moveOrDeleteResponseHelper,
- sFromFolderFullNameRaw,
- aUidForRemove
- );
- };
-
- RainLoopApp.prototype.moveOrDeleteResponseHelper = function (sResult, oData)
- {
- if (Enums.StorageResultType.Success === sResult && Data.currentFolder())
- {
- if (oData && Utils.isArray(oData.Result) && 2 === oData.Result.length)
- {
- Cache.setFolderHash(oData.Result[0], oData.Result[1]);
- }
- else
- {
- Cache.setFolderHash(Data.currentFolderFullNameRaw(), '');
-
- if (oData && -1 < Utils.inArray(oData.ErrorCode,
- [Enums.Notification.CantMoveMessage, Enums.Notification.CantCopyMessage]))
- {
- window.alert(Utils.getNotification(oData.ErrorCode));
- }
- }
-
- RL.reloadMessageListHelper(0 === Data.messageList().length);
- RL.quotaDebounce();
- }
- };
-
- /**
- * @param {string} sFromFolderFullNameRaw
- * @param {Array} aUidForRemove
- */
- RainLoopApp.prototype.deleteMessagesFromFolderWithoutCheck = function (sFromFolderFullNameRaw, aUidForRemove)
- {
- this.messagesDeleteHelper(sFromFolderFullNameRaw, aUidForRemove);
- Data.removeMessagesFromList(sFromFolderFullNameRaw, aUidForRemove);
- };
-
- /**
- * @param {number} iDeleteType
- * @param {string} sFromFolderFullNameRaw
- * @param {Array} aUidForRemove
- * @param {boolean=} bUseFolder = true
- */
- RainLoopApp.prototype.deleteMessagesFromFolder = function (iDeleteType, sFromFolderFullNameRaw, aUidForRemove, bUseFolder)
- {
- var
- self = this,
- oMoveFolder = null,
- nSetSystemFoldersNotification = null
- ;
-
- switch (iDeleteType)
- {
- case Enums.FolderType.Spam:
- oMoveFolder = Cache.getFolderFromCacheList(Data.spamFolder());
- nSetSystemFoldersNotification = Enums.SetSystemFoldersNotification.Spam;
- break;
- case Enums.FolderType.NotSpam:
- oMoveFolder = Cache.getFolderFromCacheList('INBOX');
- break;
- case Enums.FolderType.Trash:
- oMoveFolder = Cache.getFolderFromCacheList(Data.trashFolder());
- nSetSystemFoldersNotification = Enums.SetSystemFoldersNotification.Trash;
- break;
- case Enums.FolderType.Archive:
- oMoveFolder = Cache.getFolderFromCacheList(Data.archiveFolder());
- nSetSystemFoldersNotification = Enums.SetSystemFoldersNotification.Archive;
- break;
- }
-
- bUseFolder = Utils.isUnd(bUseFolder) ? true : !!bUseFolder;
- if (bUseFolder)
- {
- if ((Enums.FolderType.Spam === iDeleteType && Consts.Values.UnuseOptionValue === Data.spamFolder()) ||
- (Enums.FolderType.Trash === iDeleteType && Consts.Values.UnuseOptionValue === Data.trashFolder()) ||
- (Enums.FolderType.Archive === iDeleteType && Consts.Values.UnuseOptionValue === Data.archiveFolder()))
- {
- bUseFolder = false;
- }
- }
-
- if (!oMoveFolder && bUseFolder)
- {
- kn.showScreenPopup(PopupsFolderSystemViewModel, [nSetSystemFoldersNotification]);
- }
- else if (!bUseFolder || (Enums.FolderType.Trash === iDeleteType &&
- (sFromFolderFullNameRaw === Data.spamFolder() || sFromFolderFullNameRaw === Data.trashFolder())))
- {
- kn.showScreenPopup(PopupsAskViewModel, [Utils.i18n('POPUPS_ASK/DESC_WANT_DELETE_MESSAGES'), function () {
-
- self.messagesDeleteHelper(sFromFolderFullNameRaw, aUidForRemove);
- Data.removeMessagesFromList(sFromFolderFullNameRaw, aUidForRemove);
-
- }]);
- }
- else if (oMoveFolder)
- {
- this.messagesMoveHelper(sFromFolderFullNameRaw, oMoveFolder.fullNameRaw, aUidForRemove);
- Data.removeMessagesFromList(sFromFolderFullNameRaw, aUidForRemove, oMoveFolder.fullNameRaw);
- }
- };
-
- /**
- * @param {string} sFromFolderFullNameRaw
- * @param {Array} aUidForMove
- * @param {string} sToFolderFullNameRaw
- * @param {boolean=} bCopy = false
- */
- RainLoopApp.prototype.moveMessagesToFolder = function (sFromFolderFullNameRaw, aUidForMove, sToFolderFullNameRaw, bCopy)
- {
- if (sFromFolderFullNameRaw !== sToFolderFullNameRaw && Utils.isArray(aUidForMove) && 0 < aUidForMove.length)
- {
- var
- oFromFolder = Cache.getFolderFromCacheList(sFromFolderFullNameRaw),
- oToFolder = Cache.getFolderFromCacheList(sToFolderFullNameRaw)
- ;
-
- if (oFromFolder && oToFolder)
- {
- if (Utils.isUnd(bCopy) ? false : !!bCopy)
- {
- this.messagesCopyHelper(oFromFolder.fullNameRaw, oToFolder.fullNameRaw, aUidForMove);
- }
- else
- {
- this.messagesMoveHelper(oFromFolder.fullNameRaw, oToFolder.fullNameRaw, aUidForMove);
- }
-
- Data.removeMessagesFromList(oFromFolder.fullNameRaw, aUidForMove, oToFolder.fullNameRaw, bCopy);
- return true;
- }
- }
-
- return false;
- };
-
- /**
- * @param {Function=} fCallback
- */
- RainLoopApp.prototype.folders = function (fCallback)
- {
- this.data().foldersLoading(true);
- this.remote().folders(_.bind(function (sResult, oData) {
-
- Data.foldersLoading(false);
- if (Enums.StorageResultType.Success === sResult)
- {
- this.data().setFolders(oData);
- if (fCallback)
- {
- fCallback(true);
- }
- }
- else
- {
- if (fCallback)
- {
- fCallback(false);
- }
- }
- }, this));
- };
-
- RainLoopApp.prototype.reloadOpenPgpKeys = function ()
- {
- if (Data.capaOpenPGP())
- {
- var
- aKeys = [],
- oEmail = new EmailModel(),
- oOpenpgpKeyring = Data.openpgpKeyring,
- oOpenpgpKeys = oOpenpgpKeyring ? oOpenpgpKeyring.getAllKeys() : []
- ;
-
- _.each(oOpenpgpKeys, function (oItem, iIndex) {
- if (oItem && oItem.primaryKey)
- {
- var
-
- oPrimaryUser = oItem.getPrimaryUser(),
- sUser = (oPrimaryUser && oPrimaryUser.user) ? oPrimaryUser.user.userId.userid
- : (oItem.users && oItem.users[0] ? oItem.users[0].userId.userid : '')
- ;
-
- oEmail.clear();
- oEmail.mailsoParse(sUser);
-
- if (oEmail.validate())
- {
- aKeys.push(new OpenPgpKeyModel(
- iIndex,
- oItem.primaryKey.getFingerprint(),
- oItem.primaryKey.getKeyId().toHex().toLowerCase(),
- sUser,
- oEmail.email,
- oItem.isPrivate(),
- oItem.armor())
- );
- }
- }
- });
-
- Data.openpgpkeys(aKeys);
- }
- };
-
- RainLoopApp.prototype.accountsAndIdentities = function ()
- {
- Data.accountsLoading(true);
- Data.identitiesLoading(true);
-
- Remote.accountsAndIdentities(function (sResult, oData) {
-
- Data.accountsLoading(false);
- Data.identitiesLoading(false);
-
- if (Enums.StorageResultType.Success === sResult && oData.Result)
- {
- var
- sParentEmail = RL.settingsGet('ParentEmail'),
- sAccountEmail = Data.accountEmail()
- ;
-
- sParentEmail = '' === sParentEmail ? sAccountEmail : sParentEmail;
-
- if (Utils.isArray(oData.Result['Accounts']))
- {
- Data.accounts(_.map(oData.Result['Accounts'], function (sValue) {
- return new AccountModel(sValue, sValue !== sParentEmail);
- }));
- }
-
- if (Utils.isArray(oData.Result['Identities']))
- {
- Data.identities(_.map(oData.Result['Identities'], function (oIdentityData) {
-
- var
- sId = Utils.pString(oIdentityData['Id']),
- sEmail = Utils.pString(oIdentityData['Email']),
- oIdentity = new IdentityModel(sId, sEmail, sId !== sAccountEmail)
- ;
-
- oIdentity.name(Utils.pString(oIdentityData['Name']));
- oIdentity.replyTo(Utils.pString(oIdentityData['ReplyTo']));
- oIdentity.bcc(Utils.pString(oIdentityData['Bcc']));
-
- return oIdentity;
- }));
- }
- }
- });
- };
-
- RainLoopApp.prototype.quota = function ()
- {
- this.remote().quota(function (sResult, oData) {
- if (Enums.StorageResultType.Success === sResult && oData && oData.Result &&
- Utils.isArray(oData.Result) && 1 < oData.Result.length &&
- Utils.isPosNumeric(oData.Result[0], true) && Utils.isPosNumeric(oData.Result[1], true))
- {
- Data.userQuota(Utils.pInt(oData.Result[1]) * 1024);
- Data.userUsageSize(Utils.pInt(oData.Result[0]) * 1024);
- }
- });
- };
-
- /**
- * @param {string} sFolder
- * @param {Array=} aList = []
- */
- RainLoopApp.prototype.folderInformation = function (sFolder, aList)
- {
- if ('' !== Utils.trim(sFolder))
- {
- this.remote().folderInformation(function (sResult, oData) {
- if (Enums.StorageResultType.Success === sResult)
- {
- if (oData && oData.Result && oData.Result.Hash && oData.Result.Folder)
- {
- var
- iUtc = moment().unix(),
- sHash = Cache.getFolderHash(oData.Result.Folder),
- oFolder = Cache.getFolderFromCacheList(oData.Result.Folder),
- bCheck = false,
- sUid = '',
- aList = [],
- bUnreadCountChange = false,
- oFlags = null
- ;
-
- if (oFolder)
- {
- oFolder.interval = iUtc;
-
- if (oData.Result.Hash)
- {
- Cache.setFolderHash(oData.Result.Folder, oData.Result.Hash);
- }
-
- if (Utils.isNormal(oData.Result.MessageCount))
- {
- oFolder.messageCountAll(oData.Result.MessageCount);
- }
-
- if (Utils.isNormal(oData.Result.MessageUnseenCount))
- {
- if (Utils.pInt(oFolder.messageCountUnread()) !== Utils.pInt(oData.Result.MessageUnseenCount))
- {
- bUnreadCountChange = true;
- }
-
- oFolder.messageCountUnread(oData.Result.MessageUnseenCount);
- }
-
- if (bUnreadCountChange)
- {
- Cache.clearMessageFlagsFromCacheByFolder(oFolder.fullNameRaw);
- }
-
- if (oData.Result.Flags)
- {
- for (sUid in oData.Result.Flags)
- {
- if (oData.Result.Flags.hasOwnProperty(sUid))
- {
- bCheck = true;
- oFlags = oData.Result.Flags[sUid];
- Cache.storeMessageFlagsToCacheByFolderAndUid(oFolder.fullNameRaw, sUid.toString(), [
- !oFlags['IsSeen'], !!oFlags['IsFlagged'], !!oFlags['IsAnswered'], !!oFlags['IsForwarded'], !!oFlags['IsReadReceipt']
- ]);
- }
- }
-
- if (bCheck)
- {
- RL.reloadFlagsCurrentMessageListAndMessageFromCache();
- }
- }
-
- Data.initUidNextAndNewMessages(oFolder.fullNameRaw, oData.Result.UidNext, oData.Result.NewMessages);
-
- if (oData.Result.Hash !== sHash || '' === sHash)
- {
- if (oFolder.fullNameRaw === Data.currentFolderFullNameRaw())
- {
- RL.reloadMessageList();
- }
- else if ('INBOX' === oFolder.fullNameRaw)
- {
- RL.recacheInboxMessageList();
- }
- }
- else if (bUnreadCountChange)
- {
- if (oFolder.fullNameRaw === Data.currentFolderFullNameRaw())
- {
- aList = Data.messageList();
- if (Utils.isNonEmptyArray(aList))
- {
- RL.folderInformation(oFolder.fullNameRaw, aList);
- }
- }
- }
- }
- }
- }
- }, sFolder, aList);
- }
- };
-
- /**
- * @param {boolean=} bBoot = false
- */
- RainLoopApp.prototype.folderInformationMultiply = function (bBoot)
- {
- bBoot = Utils.isUnd(bBoot) ? false : !!bBoot;
-
- var
- iUtc = moment().unix(),
- aFolders = Data.getNextFolderNames(bBoot)
- ;
-
- if (Utils.isNonEmptyArray(aFolders))
- {
- this.remote().folderInformationMultiply(function (sResult, oData) {
- if (Enums.StorageResultType.Success === sResult)
- {
- if (oData && oData.Result && oData.Result.List && Utils.isNonEmptyArray(oData.Result.List))
- {
- _.each(oData.Result.List, function (oItem) {
-
- var
- aList = [],
- sHash = Cache.getFolderHash(oItem.Folder),
- oFolder = Cache.getFolderFromCacheList(oItem.Folder),
- bUnreadCountChange = false
- ;
-
- if (oFolder)
- {
- oFolder.interval = iUtc;
-
- if (oItem.Hash)
- {
- Cache.setFolderHash(oItem.Folder, oItem.Hash);
- }
-
- if (Utils.isNormal(oItem.MessageCount))
- {
- oFolder.messageCountAll(oItem.MessageCount);
- }
-
- if (Utils.isNormal(oItem.MessageUnseenCount))
- {
- if (Utils.pInt(oFolder.messageCountUnread()) !== Utils.pInt(oItem.MessageUnseenCount))
- {
- bUnreadCountChange = true;
- }
-
- oFolder.messageCountUnread(oItem.MessageUnseenCount);
- }
-
- if (bUnreadCountChange)
- {
- Cache.clearMessageFlagsFromCacheByFolder(oFolder.fullNameRaw);
- }
-
- if (oItem.Hash !== sHash || '' === sHash)
- {
- if (oFolder.fullNameRaw === Data.currentFolderFullNameRaw())
- {
- RL.reloadMessageList();
- }
- }
- else if (bUnreadCountChange)
- {
- if (oFolder.fullNameRaw === Data.currentFolderFullNameRaw())
- {
- aList = Data.messageList();
- if (Utils.isNonEmptyArray(aList))
- {
- RL.folderInformation(oFolder.fullNameRaw, aList);
- }
- }
- }
- }
- });
-
- if (bBoot)
- {
- RL.folderInformationMultiply(true);
- }
- }
- }
- }, aFolders);
- }
- };
-
- RainLoopApp.prototype.setMessageSeen = function (oMessage)
- {
- if (oMessage.unseen())
- {
- oMessage.unseen(false);
-
- var oFolder = Cache.getFolderFromCacheList(oMessage.folderFullNameRaw);
- if (oFolder)
- {
- oFolder.messageCountUnread(0 <= oFolder.messageCountUnread() - 1 ?
- oFolder.messageCountUnread() - 1 : 0);
- }
-
- Cache.storeMessageFlagsToCache(oMessage);
- RL.reloadFlagsCurrentMessageListAndMessageFromCache();
- }
-
- Remote.messageSetSeen(Utils.emptyFunction, oMessage.folderFullNameRaw, [oMessage.uid], true);
- };
-
- RainLoopApp.prototype.googleConnect = function ()
- {
- window.open(LinkBuilder.socialGoogle(), 'Google', 'left=200,top=100,width=650,height=600,menubar=no,status=no,resizable=yes,scrollbars=yes');
- };
-
- RainLoopApp.prototype.twitterConnect = function ()
- {
- window.open(LinkBuilder.socialTwitter(), 'Twitter', 'left=200,top=100,width=650,height=350,menubar=no,status=no,resizable=yes,scrollbars=yes');
- };
-
- RainLoopApp.prototype.facebookConnect = function ()
- {
- window.open(LinkBuilder.socialFacebook(), 'Facebook', 'left=200,top=100,width=650,height=335,menubar=no,status=no,resizable=yes,scrollbars=yes');
- };
-
- /**
- * @param {boolean=} bFireAllActions
- */
- RainLoopApp.prototype.socialUsers = function (bFireAllActions)
- {
- if (bFireAllActions)
- {
- Data.googleActions(true);
- Data.facebookActions(true);
- Data.twitterActions(true);
- }
-
- Remote.socialUsers(function (sResult, oData) {
-
- if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
- {
- Data.googleUserName(oData.Result['Google'] || '');
- Data.facebookUserName(oData.Result['Facebook'] || '');
- Data.twitterUserName(oData.Result['Twitter'] || '');
- }
- else
- {
- Data.googleUserName('');
- Data.facebookUserName('');
- Data.twitterUserName('');
- }
-
- Data.googleLoggined('' !== Data.googleUserName());
- Data.facebookLoggined('' !== Data.facebookUserName());
- Data.twitterLoggined('' !== Data.twitterUserName());
-
- Data.googleActions(false);
- Data.facebookActions(false);
- Data.twitterActions(false);
- });
- };
-
- RainLoopApp.prototype.googleDisconnect = function ()
- {
- Data.googleActions(true);
- Remote.googleDisconnect(function () {
- RL.socialUsers();
- });
- };
-
- RainLoopApp.prototype.facebookDisconnect = function ()
- {
- Data.facebookActions(true);
- Remote.facebookDisconnect(function () {
- RL.socialUsers();
- });
- };
-
- RainLoopApp.prototype.twitterDisconnect = function ()
- {
- Data.twitterActions(true);
- Remote.twitterDisconnect(function () {
- RL.socialUsers();
- });
- };
-
- /**
- * @param {Array} aSystem
- * @param {Array} aList
- * @param {Array=} aDisabled
- * @param {Array=} aHeaderLines
- * @param {?number=} iUnDeep
- * @param {Function=} fDisableCallback
- * @param {Function=} fVisibleCallback
- * @param {Function=} fRenameCallback
- * @param {boolean=} bSystem
- * @param {boolean=} bBuildUnvisible
- * @return {Array}
- */
- RainLoopApp.prototype.folderListOptionsBuilder = function (aSystem, aList, aDisabled, aHeaderLines, iUnDeep, fDisableCallback, fVisibleCallback, fRenameCallback, bSystem, bBuildUnvisible)
- {
- var
- iIndex = 0,
- iLen = 0,
- /**
- * @type {?FolderModel}
- */
- oItem = null,
- bSep = false,
- sDeepPrefix = '\u00A0\u00A0\u00A0',
- aResult = []
- ;
-
- bSystem = !Utils.isNormal(bSystem) ? 0 < aSystem.length : bSystem;
- bBuildUnvisible = Utils.isUnd(bBuildUnvisible) ? false : !!bBuildUnvisible;
- iUnDeep = !Utils.isNormal(iUnDeep) ? 0 : iUnDeep;
- fDisableCallback = Utils.isNormal(fDisableCallback) ? fDisableCallback : null;
- fVisibleCallback = Utils.isNormal(fVisibleCallback) ? fVisibleCallback : null;
- fRenameCallback = Utils.isNormal(fRenameCallback) ? fRenameCallback : null;
-
- if (!Utils.isArray(aDisabled))
- {
- aDisabled = [];
- }
-
- if (!Utils.isArray(aHeaderLines))
- {
- aHeaderLines = [];
- }
-
- for (iIndex = 0, iLen = aHeaderLines.length; iIndex < iLen; iIndex++)
- {
- aResult.push({
- 'id': aHeaderLines[iIndex][0],
- 'name': aHeaderLines[iIndex][1],
- 'system': false,
- 'seporator': false,
- 'disabled': false
- });
- }
-
- bSep = true;
- for (iIndex = 0, iLen = aSystem.length; iIndex < iLen; iIndex++)
- {
- oItem = aSystem[iIndex];
- if (fVisibleCallback ? fVisibleCallback.call(null, oItem) : true)
- {
- if (bSep && 0 < aResult.length)
- {
- aResult.push({
- 'id': '---',
- 'name': '---',
- 'system': false,
- 'seporator': true,
- 'disabled': true
- });
- }
-
- bSep = false;
- aResult.push({
- 'id': oItem.fullNameRaw,
- 'name': fRenameCallback ? fRenameCallback.call(null, oItem) : oItem.name(),
- 'system': true,
- 'seporator': false,
- 'disabled': !oItem.selectable || -1 < Utils.inArray(oItem.fullNameRaw, aDisabled) ||
- (fDisableCallback ? fDisableCallback.call(null, oItem) : false)
- });
- }
- }
-
- bSep = true;
- for (iIndex = 0, iLen = aList.length; iIndex < iLen; iIndex++)
- {
- oItem = aList[iIndex];
- if (oItem.subScribed() || !oItem.existen)
- {
- if (fVisibleCallback ? fVisibleCallback.call(null, oItem) : true)
- {
- if (Enums.FolderType.User === oItem.type() || !bSystem || 0 < oItem.subFolders().length)
- {
- if (bSep && 0 < aResult.length)
- {
- aResult.push({
- 'id': '---',
- 'name': '---',
- 'system': false,
- 'seporator': true,
- 'disabled': true
- });
- }
-
- bSep = false;
- aResult.push({
- 'id': oItem.fullNameRaw,
- 'name': (new window.Array(oItem.deep + 1 - iUnDeep)).join(sDeepPrefix) +
- (fRenameCallback ? fRenameCallback.call(null, oItem) : oItem.name()),
- 'system': false,
- 'seporator': false,
- 'disabled': !oItem.selectable || -1 < Utils.inArray(oItem.fullNameRaw, aDisabled) ||
- (fDisableCallback ? fDisableCallback.call(null, oItem) : false)
- });
- }
- }
- }
-
- if (oItem.subScribed() && 0 < oItem.subFolders().length)
- {
- aResult = aResult.concat(RL.folderListOptionsBuilder([], oItem.subFolders(), aDisabled, [],
- iUnDeep, fDisableCallback, fVisibleCallback, fRenameCallback, bSystem, bBuildUnvisible));
- }
- }
-
- return aResult;
- };
-
- /**
- * @param {string} sQuery
- * @param {Function} fCallback
- */
- RainLoopApp.prototype.getAutocomplete = function (sQuery, fCallback)
- {
- var
- aData = []
- ;
-
- Remote.suggestions(function (sResult, oData) {
- if (Enums.StorageResultType.Success === sResult && oData && Utils.isArray(oData.Result))
- {
- aData = _.map(oData.Result, function (aItem) {
- return aItem && aItem[0] ? new EmailModel(aItem[0], aItem[1]) : null;
- });
-
- fCallback(_.compact(aData));
- }
- else if (Enums.StorageResultType.Abort !== sResult)
- {
- fCallback([]);
- }
-
- }, sQuery);
- };
-
- /**
- * @param {string} sQuery
- * @param {Function} fCallback
- */
- RainLoopApp.prototype.getContactTagsAutocomplete = function (sQuery, fCallback)
- {
- fCallback(_.filter(Data.contactTags(), function (oContactTag) {
- return oContactTag && oContactTag.filterHelper(sQuery);
- }));
- };
-
- /**
- * @param {string} sMailToUrl
- * @returns {boolean}
- */
- RainLoopApp.prototype.mailToHelper = function (sMailToUrl)
- {
- if (sMailToUrl && 'mailto:' === sMailToUrl.toString().substr(0, 7).toLowerCase())
- {
- sMailToUrl = sMailToUrl.toString().substr(7);
-
- var
- oParams = {},
- oEmailModel = null,
- sEmail = sMailToUrl.replace(/\?.+$/, ''),
- sQueryString = sMailToUrl.replace(/^[^\?]*\?/, '')
- ;
-
- oEmailModel = new EmailModel();
- oEmailModel.parse(window.decodeURIComponent(sEmail));
-
- if (oEmailModel && oEmailModel.email)
- {
- oParams = Utils.simpleQueryParser(sQueryString);
- kn.showScreenPopup(PopupsComposeViewModel, [Enums.ComposeType.Empty, null, [oEmailModel],
- Utils.isUnd(oParams.subject) ? null : Utils.pString(oParams.subject),
- Utils.isUnd(oParams.body) ? null : Utils.plainToHtml(Utils.pString(oParams.body))
- ]);
- }
-
- return true;
- }
-
- return false;
- };
-
- RainLoopApp.prototype.bootstart = function ()
- {
- RL.pub('rl.bootstart');
- AbstractApp.prototype.bootstart.call(this);
-
- Data.populateDataOnStart();
-
- var
- sCustomLoginLink = '',
- sJsHash = RL.settingsGet('JsHash'),
- iContactsSyncInterval = Utils.pInt(RL.settingsGet('ContactsSyncInterval')),
- bGoogle = RL.settingsGet('AllowGoogleSocial'),
- bFacebook = RL.settingsGet('AllowFacebookSocial'),
- bTwitter = RL.settingsGet('AllowTwitterSocial')
- ;
-
- if (!RL.settingsGet('ChangePasswordIsAllowed'))
- {
- kn.removeSettingsViewModel(SettingsChangePasswordScreen);
- }
-
- if (!RL.settingsGet('ContactsIsAllowed'))
- {
- kn.removeSettingsViewModel(SettingsContacts);
- }
-
- if (!RL.capa(Enums.Capa.AdditionalAccounts))
- {
- kn.removeSettingsViewModel(SettingsAccounts);
- }
-
- if (RL.capa(Enums.Capa.AdditionalIdentities))
- {
- kn.removeSettingsViewModel(SettingsIdentity);
- }
- else
- {
- kn.removeSettingsViewModel(SettingsIdentities);
- }
-
- if (!RL.capa(Enums.Capa.OpenPGP))
- {
- kn.removeSettingsViewModel(SettingsOpenPGP);
- }
-
- if (!RL.capa(Enums.Capa.TwoFactor))
- {
- kn.removeSettingsViewModel(SettingsSecurity);
- }
-
- if (!RL.capa(Enums.Capa.Themes))
- {
- kn.removeSettingsViewModel(SettingsThemes);
- }
-
- if (!RL.capa(Enums.Capa.Filters))
- {
- kn.removeSettingsViewModel(SettingsFilters);
- }
-
- if (!bGoogle && !bFacebook && !bTwitter)
- {
- kn.removeSettingsViewModel(SettingsSocialScreen);
- }
-
- Utils.initOnStartOrLangChange(function () {
-
- $.extend(true, $.magnificPopup.defaults, {
- 'tClose': Utils.i18n('MAGNIFIC_POPUP/CLOSE'),
- 'tLoading': Utils.i18n('MAGNIFIC_POPUP/LOADING'),
- 'gallery': {
- 'tPrev': Utils.i18n('MAGNIFIC_POPUP/GALLERY_PREV'),
- 'tNext': Utils.i18n('MAGNIFIC_POPUP/GALLERY_NEXT'),
- 'tCounter': Utils.i18n('MAGNIFIC_POPUP/GALLERY_COUNTER')
- },
- 'image': {
- 'tError': Utils.i18n('MAGNIFIC_POPUP/IMAGE_ERROR')
- },
- 'ajax': {
- 'tError': Utils.i18n('MAGNIFIC_POPUP/AJAX_ERROR')
- }
- });
-
- }, this);
-
- if (window.SimplePace)
- {
- window.SimplePace.set(70);
- window.SimplePace.sleep();
- }
-
- if (!!RL.settingsGet('Auth'))
- {
- this.setTitle(Utils.i18n('TITLES/LOADING'));
-
- this.folders(_.bind(function (bValue) {
-
- kn.hideLoading();
-
- if (bValue)
- {
- if (window.$LAB && window.crypto && window.crypto.getRandomValues && RL.capa(Enums.Capa.OpenPGP))
- {
- window.$LAB.script(window.openpgp ? '' : LinkBuilder.openPgpJs()).wait(function () {
- if (window.openpgp)
- {
- Data.openpgpKeyring = new window.openpgp.Keyring();
- Data.capaOpenPGP(true);
-
- RL.pub('openpgp.init');
-
- RL.reloadOpenPgpKeys();
- }
- });
- }
- else
- {
- Data.capaOpenPGP(false);
- }
-
- kn.startScreens([MailBoxScreen, SettingsScreen]);
-
- if (bGoogle || bFacebook || bTwitter)
- {
- RL.socialUsers(true);
- }
-
- RL.sub('interval.2m', function () {
- RL.folderInformation('INBOX');
- });
-
- RL.sub('interval.2m', function () {
- var sF = Data.currentFolderFullNameRaw();
- if ('INBOX' !== sF)
- {
- RL.folderInformation(sF);
- }
- });
-
- RL.sub('interval.3m', function () {
- RL.folderInformationMultiply();
- });
-
- RL.sub('interval.5m', function () {
- RL.quota();
- });
-
- RL.sub('interval.10m', function () {
- RL.folders();
- });
-
- iContactsSyncInterval = 5 <= iContactsSyncInterval ? iContactsSyncInterval : 20;
- iContactsSyncInterval = 320 >= iContactsSyncInterval ? iContactsSyncInterval : 320;
-
- window.setInterval(function () {
- RL.contactsSync();
- }, iContactsSyncInterval * 60000 + 5000);
-
- _.delay(function () {
- RL.contactsSync();
- }, 5000);
-
- _.delay(function () {
- RL.folderInformationMultiply(true);
- }, 500);
-
- Plugins.runHook('rl-start-user-screens');
- RL.pub('rl.bootstart-user-screens');
-
- if (!!RL.settingsGet('AccountSignMe') && window.navigator.registerProtocolHandler)
- {
- _.delay(function () {
- try {
- window.navigator.registerProtocolHandler('mailto',
- window.location.protocol + '//' + window.location.host + window.location.pathname + '?mailto&to=%s',
- '' + (RL.settingsGet('Title') || 'RainLoop'));
- } catch(e) {}
-
- if (RL.settingsGet('MailToEmail'))
- {
- RL.mailToHelper(RL.settingsGet('MailToEmail'));
- }
- }, 500);
- }
- }
- else
- {
- kn.startScreens([LoginScreen]);
-
- Plugins.runHook('rl-start-login-screens');
- RL.pub('rl.bootstart-login-screens');
- }
-
- if (window.SimplePace)
- {
- window.SimplePace.set(100);
- }
-
- if (!Globals.bMobileDevice)
- {
- _.defer(function () {
- Utils.initLayoutResizer('#rl-left', '#rl-right', Enums.ClientSideKeyName.FolderListSize);
- });
- }
-
- }, this));
- }
- else
- {
- sCustomLoginLink = Utils.pString(RL.settingsGet('CustomLoginLink'));
- if (!sCustomLoginLink)
- {
- kn.hideLoading();
- kn.startScreens([LoginScreen]);
-
- Plugins.runHook('rl-start-login-screens');
- RL.pub('rl.bootstart-login-screens');
-
- if (window.SimplePace)
- {
- window.SimplePace.set(100);
- }
- }
- else
- {
- kn.routeOff();
- kn.setHash(LinkBuilder.root(), true);
- kn.routeOff();
-
- _.defer(function () {
- window.location.href = sCustomLoginLink;
- });
- }
- }
-
- if (bGoogle)
- {
- window['rl_' + sJsHash + '_google_service'] = function () {
- Data.googleActions(true);
- RL.socialUsers();
- };
- }
-
- if (bFacebook)
- {
- window['rl_' + sJsHash + '_facebook_service'] = function () {
- Data.facebookActions(true);
- RL.socialUsers();
- };
- }
-
- if (bTwitter)
- {
- window['rl_' + sJsHash + '_twitter_service'] = function () {
- Data.twitterActions(true);
- RL.socialUsers();
- };
- }
-
- RL.sub('interval.1m', function () {
- Globals.momentTrigger(!Globals.momentTrigger());
- });
-
- Plugins.runHook('rl-start-screens');
- RL.pub('rl.bootstart-end');
- };
-
- module.exports = new RainLoopApp();
-
-}(module));
-},{"../Common/Consts.js":4,"../Common/Enums.js":5,"../Common/Globals.js":6,"../Common/LinkBuilder.js":7,"../Common/Plugins.js":8,"../Common/Utils.js":9,"../External/jquery.js":19,"../External/moment.js":22,"../External/underscore.js":24,"../External/window.js":25,"../Knoin/Knoin.js":26,"../Storages/WebMailAjaxRemoteStorage.js":39,"../Storages/WebMailCacheStorage.js":40,"../Storages/WebMailDataStorage.js":41,"../ViewModels/Popups/PopupsAskViewModel.js":42,"./AbstractApp.js":2}],4:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-(function (module) {
-
- 'use strict';
-
- var Consts = {};
-
- Consts.Values = {};
- Consts.DataImages = {};
- Consts.Defaults = {};
-
- /**
- * @const
- * @type {number}
- */
- Consts.Defaults.MessagesPerPage = 20;
-
- /**
- * @const
- * @type {number}
- */
- Consts.Defaults.ContactsPerPage = 50;
-
- /**
- * @const
- * @type {Array}
- */
- Consts.Defaults.MessagesPerPageArray = [10, 20, 30, 50, 100/*, 150, 200, 300*/];
-
- /**
- * @const
- * @type {number}
- */
- Consts.Defaults.DefaultAjaxTimeout = 30000;
-
- /**
- * @const
- * @type {number}
- */
- Consts.Defaults.SearchAjaxTimeout = 300000;
-
- /**
- * @const
- * @type {number}
- */
- Consts.Defaults.SendMessageAjaxTimeout = 300000;
-
- /**
- * @const
- * @type {number}
- */
- Consts.Defaults.SaveMessageAjaxTimeout = 200000;
-
- /**
- * @const
- * @type {number}
- */
- Consts.Defaults.ContactsSyncAjaxTimeout = 200000;
-
- /**
- * @const
- * @type {string}
- */
- Consts.Values.UnuseOptionValue = '__UNUSE__';
-
- /**
- * @const
- * @type {string}
- */
- Consts.Values.ClientSideCookieIndexName = 'rlcsc';
-
- /**
- * @const
- * @type {number}
- */
- Consts.Values.ImapDefaulPort = 143;
-
- /**
- * @const
- * @type {number}
- */
- Consts.Values.ImapDefaulSecurePort = 993;
-
- /**
- * @const
- * @type {number}
- */
- Consts.Values.SmtpDefaulPort = 25;
-
- /**
- * @const
- * @type {number}
- */
- Consts.Values.SmtpDefaulSecurePort = 465;
-
- /**
- * @const
- * @type {number}
- */
- Consts.Values.MessageBodyCacheLimit = 15;
-
- /**
- * @const
- * @type {number}
- */
- Consts.Values.AjaxErrorLimit = 7;
-
- /**
- * @const
- * @type {number}
- */
- Consts.Values.TokenErrorLimit = 10;
-
- /**
- * @const
- * @type {string}
- */
- Consts.DataImages.UserDotPic = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQIW2P8DwQACgAD/il4QJ8AAAAASUVORK5CYII=';
-
- /**
- * @const
- * @type {string}
- */
- Consts.DataImages.TranspPic = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQIW2NkAAIAAAoAAggA9GkAAAAASUVORK5CYII=';
-
- module.exports = Consts;
-
-}(module));
-},{}],5:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-(function (module) {
-
- 'use strict';
-
- var Enums = {};
-
- /**
- * @enum {string}
- */
- Enums.StorageResultType = {
- 'Success': 'success',
- 'Abort': 'abort',
- 'Error': 'error',
- 'Unload': 'unload'
- };
-
- /**
- * @enum {number}
- */
- Enums.State = {
- 'Empty': 10,
- 'Login': 20,
- 'Auth': 30
- };
-
- /**
- * @enum {number}
- */
- Enums.StateType = {
- 'Webmail': 0,
- 'Admin': 1
- };
-
- /**
- * @enum {string}
- */
- Enums.Capa = {
- 'Prem': 'PREM',
- 'TwoFactor': 'TWO_FACTOR',
- 'OpenPGP': 'OPEN_PGP',
- 'Prefetch': 'PREFETCH',
- 'Gravatar': 'GRAVATAR',
- 'Themes': 'THEMES',
- 'Filters': 'FILTERS',
- 'AdditionalAccounts': 'ADDITIONAL_ACCOUNTS',
- 'AdditionalIdentities': 'ADDITIONAL_IDENTITIES'
- };
-
- /**
- * @enum {string}
- */
- Enums.KeyState = {
- 'All': 'all',
- 'None': 'none',
- 'ContactList': 'contact-list',
- 'MessageList': 'message-list',
- 'FolderList': 'folder-list',
- 'MessageView': 'message-view',
- 'Compose': 'compose',
- 'Settings': 'settings',
- 'Menu': 'menu',
- 'PopupComposeOpenPGP': 'compose-open-pgp',
- 'PopupKeyboardShortcutsHelp': 'popup-keyboard-shortcuts-help',
- 'PopupAsk': 'popup-ask'
- };
-
- /**
- * @enum {number}
- */
- Enums.FolderType = {
- 'Inbox': 10,
- 'SentItems': 11,
- 'Draft': 12,
- 'Trash': 13,
- 'Spam': 14,
- 'Archive': 15,
- 'NotSpam': 80,
- 'User': 99
- };
-
- /**
- * @enum {string}
- */
- Enums.LoginSignMeTypeAsString = {
- 'DefaultOff': 'defaultoff',
- 'DefaultOn': 'defaulton',
- 'Unused': 'unused'
- };
-
- /**
- * @enum {number}
- */
- Enums.LoginSignMeType = {
- 'DefaultOff': 0,
- 'DefaultOn': 1,
- 'Unused': 2
- };
-
- /**
- * @enum {string}
- */
- Enums.ComposeType = {
- 'Empty': 'empty',
- 'Reply': 'reply',
- 'ReplyAll': 'replyall',
- 'Forward': 'forward',
- 'ForwardAsAttachment': 'forward-as-attachment',
- 'Draft': 'draft',
- 'EditAsNew': 'editasnew'
- };
-
- /**
- * @enum {number}
- */
- Enums.UploadErrorCode = {
- 'Normal': 0,
- 'FileIsTooBig': 1,
- 'FilePartiallyUploaded': 2,
- 'FileNoUploaded': 3,
- 'MissingTempFolder': 4,
- 'FileOnSaveingError': 5,
- 'FileType': 98,
- 'Unknown': 99
- };
-
- /**
- * @enum {number}
- */
- Enums.SetSystemFoldersNotification = {
- 'None': 0,
- 'Sent': 1,
- 'Draft': 2,
- 'Spam': 3,
- 'Trash': 4,
- 'Archive': 5
- };
-
- /**
- * @enum {number}
- */
- Enums.ClientSideKeyName = {
- 'FoldersLashHash': 0,
- 'MessagesInboxLastHash': 1,
- 'MailBoxListSize': 2,
- 'ExpandedFolders': 3,
- 'FolderListSize': 4
- };
-
- /**
- * @enum {number}
- */
- Enums.EventKeyCode = {
- 'Backspace': 8,
- 'Tab': 9,
- 'Enter': 13,
- 'Esc': 27,
- 'PageUp': 33,
- 'PageDown': 34,
- 'Left': 37,
- 'Right': 39,
- 'Up': 38,
- 'Down': 40,
- 'End': 35,
- 'Home': 36,
- 'Space': 32,
- 'Insert': 45,
- 'Delete': 46,
- 'A': 65,
- 'S': 83
- };
-
- /**
- * @enum {number}
- */
- Enums.MessageSetAction = {
- 'SetSeen': 0,
- 'UnsetSeen': 1,
- 'SetFlag': 2,
- 'UnsetFlag': 3
- };
-
- /**
- * @enum {number}
- */
- Enums.MessageSelectAction = {
- 'All': 0,
- 'None': 1,
- 'Invert': 2,
- 'Unseen': 3,
- 'Seen': 4,
- 'Flagged': 5,
- 'Unflagged': 6
- };
-
- /**
- * @enum {number}
- */
- Enums.DesktopNotifications = {
- 'Allowed': 0,
- 'NotAllowed': 1,
- 'Denied': 2,
- 'NotSupported': 9
- };
-
- /**
- * @enum {number}
- */
- Enums.MessagePriority = {
- 'Low': 5,
- 'Normal': 3,
- 'High': 1
- };
-
- /**
- * @enum {string}
- */
- Enums.EditorDefaultType = {
- 'Html': 'Html',
- 'Plain': 'Plain'
- };
-
- /**
- * @enum {string}
- */
- Enums.CustomThemeType = {
- 'Light': 'Light',
- 'Dark': 'Dark'
- };
-
- /**
- * @enum {number}
- */
- Enums.ServerSecure = {
- 'None': 0,
- 'SSL': 1,
- 'TLS': 2
- };
-
- /**
- * @enum {number}
- */
- Enums.SearchDateType = {
- 'All': -1,
- 'Days3': 3,
- 'Days7': 7,
- 'Month': 30
- };
-
- /**
- * @enum {number}
- */
- Enums.EmailType = {
- 'Defailt': 0,
- 'Facebook': 1,
- 'Google': 2
- };
-
- /**
- * @enum {number}
- */
- Enums.SaveSettingsStep = {
- 'Animate': -2,
- 'Idle': -1,
- 'TrueResult': 1,
- 'FalseResult': 0
- };
-
- /**
- * @enum {string}
- */
- Enums.InterfaceAnimation = {
- 'None': 'None',
- 'Normal': 'Normal',
- 'Full': 'Full'
- };
-
- /**
- * @enum {number}
- */
- Enums.Layout = {
- 'NoPreview': 0,
- 'SidePreview': 1,
- 'BottomPreview': 2
- };
-
- /**
- * @enum {string}
- */
- Enums.FilterConditionField = {
- 'From': 'From',
- 'To': 'To',
- 'Recipient': 'Recipient',
- 'Subject': 'Subject'
- };
-
- /**
- * @enum {string}
- */
- Enums.FilterConditionType = {
- 'Contains': 'Contains',
- 'NotContains': 'NotContains',
- 'EqualTo': 'EqualTo',
- 'NotEqualTo': 'NotEqualTo'
- };
-
- /**
- * @enum {string}
- */
- Enums.FiltersAction = {
- 'None': 'None',
- 'Move': 'Move',
- 'Discard': 'Discard',
- 'Forward': 'Forward',
- };
-
- /**
- * @enum {string}
- */
- Enums.FilterRulesType = {
- 'And': 'And',
- 'Or': 'Or'
- };
-
- /**
- * @enum {number}
- */
- Enums.SignedVerifyStatus = {
- 'UnknownPublicKeys': -4,
- 'UnknownPrivateKey': -3,
- 'Unverified': -2,
- 'Error': -1,
- 'None': 0,
- 'Success': 1
- };
-
- /**
- * @enum {number}
- */
- Enums.ContactPropertyType = {
-
- 'Unknown': 0,
-
- 'FullName': 10,
-
- 'FirstName': 15,
- 'LastName': 16,
- 'MiddleName': 16,
- 'Nick': 18,
-
- 'NamePrefix': 20,
- 'NameSuffix': 21,
-
- 'Email': 30,
- 'Phone': 31,
- 'Web': 32,
-
- 'Birthday': 40,
-
- 'Facebook': 90,
- 'Skype': 91,
- 'GitHub': 92,
-
- 'Note': 110,
-
- 'Custom': 250
- };
-
- /**
- * @enum {number}
- */
- Enums.Notification = {
- 'InvalidToken': 101,
- 'AuthError': 102,
- 'AccessError': 103,
- 'ConnectionError': 104,
- 'CaptchaError': 105,
- 'SocialFacebookLoginAccessDisable': 106,
- 'SocialTwitterLoginAccessDisable': 107,
- 'SocialGoogleLoginAccessDisable': 108,
- 'DomainNotAllowed': 109,
- 'AccountNotAllowed': 110,
-
- 'AccountTwoFactorAuthRequired': 120,
- 'AccountTwoFactorAuthError': 121,
-
- 'CouldNotSaveNewPassword': 130,
- 'CurrentPasswordIncorrect': 131,
- 'NewPasswordShort': 132,
- 'NewPasswordWeak': 133,
- 'NewPasswordForbidden': 134,
-
- 'ContactsSyncError': 140,
-
- 'CantGetMessageList': 201,
- 'CantGetMessage': 202,
- 'CantDeleteMessage': 203,
- 'CantMoveMessage': 204,
- 'CantCopyMessage': 205,
-
- 'CantSaveMessage': 301,
- 'CantSendMessage': 302,
- 'InvalidRecipients': 303,
-
- 'CantCreateFolder': 400,
- 'CantRenameFolder': 401,
- 'CantDeleteFolder': 402,
- 'CantSubscribeFolder': 403,
- 'CantUnsubscribeFolder': 404,
- 'CantDeleteNonEmptyFolder': 405,
-
- 'CantSaveSettings': 501,
- 'CantSavePluginSettings': 502,
-
- 'DomainAlreadyExists': 601,
-
- 'CantInstallPackage': 701,
- 'CantDeletePackage': 702,
- 'InvalidPluginPackage': 703,
- 'UnsupportedPluginPackage': 704,
-
- 'LicensingServerIsUnavailable': 710,
- 'LicensingExpired': 711,
- 'LicensingBanned': 712,
-
- 'DemoSendMessageError': 750,
-
- 'AccountAlreadyExists': 801,
-
- 'MailServerError': 901,
- 'ClientViewError': 902,
- 'InvalidInputArgument': 903,
- 'UnknownNotification': 999,
- 'UnknownError': 999
- };
-
- module.exports = Enums;
-
-}(module));
-},{}],6:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-(function (module) {
-
- 'use strict';
-
- var
- Globals = {},
- window = require('../External/window.js'),
- ko = require('../External/ko.js'),
- $html = require('../External/$html.js')
- ;
-
- /**
- * @type {?}
- */
- Globals.now = (new window.Date()).getTime();
-
- /**
- * @type {?}
- */
- Globals.momentTrigger = ko.observable(true);
-
- /**
- * @type {?}
- */
- Globals.dropdownVisibility = ko.observable(false).extend({'rateLimit': 0});
-
- /**
- * @type {?}
- */
- Globals.tooltipTrigger = ko.observable(false).extend({'rateLimit': 0});
-
- /**
- * @type {?}
- */
- Globals.langChangeTrigger = ko.observable(true);
-
- /**
- * @type {number}
- */
- Globals.iAjaxErrorCount = 0;
-
- /**
- * @type {number}
- */
- Globals.iTokenErrorCount = 0;
-
- /**
- * @type {number}
- */
- Globals.iMessageBodyCacheCount = 0;
-
- /**
- * @type {boolean}
- */
- Globals.bUnload = false;
-
- /**
- * @type {string}
- */
- Globals.sUserAgent = (window.navigator.userAgent || '').toLowerCase();
-
- /**
- * @type {boolean}
- */
- Globals.bIsiOSDevice = -1 < Globals.sUserAgent.indexOf('iphone') || -1 < Globals.sUserAgent.indexOf('ipod') || -1 < Globals.sUserAgent.indexOf('ipad');
-
- /**
- * @type {boolean}
- */
- Globals.bIsAndroidDevice = -1 < Globals.sUserAgent.indexOf('android');
-
- /**
- * @type {boolean}
- */
- Globals.bMobileDevice = Globals.bIsiOSDevice || Globals.bIsAndroidDevice;
-
- /**
- * @type {boolean}
- */
- Globals.bDisableNanoScroll = Globals.bMobileDevice;
-
- /**
- * @type {boolean}
- */
- Globals.bAllowPdfPreview = !Globals.bMobileDevice;
-
- /**
- * @type {boolean}
- */
- Globals.bAnimationSupported = !Globals.bMobileDevice && $html.hasClass('csstransitions');
-
- /**
- * @type {boolean}
- */
- Globals.bXMLHttpRequestSupported = !!window.XMLHttpRequest;
-
- /**
- * @type {string}
- */
- Globals.sAnimationType = '';
-
- /**
- * @type {Object}
- */
- Globals.oHtmlEditorDefaultConfig = {
- 'title': false,
- 'stylesSet': false,
- 'customConfig': '',
- 'contentsCss': '',
- 'toolbarGroups': [
- {name: 'spec'},
- {name: 'styles'},
- {name: 'basicstyles', groups: ['basicstyles', 'cleanup']},
- {name: 'colors'},
- {name: 'paragraph', groups: ['list', 'indent', 'blocks', 'align']},
- {name: 'links'},
- {name: 'insert'},
- {name: 'others'}
- // {name: 'document', groups: ['mode', 'document', 'doctools']}
- ],
-
- 'removePlugins': 'contextmenu', //blockquote
- 'removeButtons': 'Format,Undo,Redo,Cut,Copy,Paste,Anchor,Strike,Subscript,Superscript,Image,SelectAll',
- 'removeDialogTabs': 'link:advanced;link:target;image:advanced;images:advanced',
-
- 'extraPlugins': 'plain',
-
- 'allowedContent': true,
- 'autoParagraph': false,
-
- 'font_defaultLabel': 'Arial',
- 'fontSize_defaultLabel': '13',
- 'fontSize_sizes': '10/10px;12/12px;13/13px;14/14px;16/16px;18/18px;20/20px;24/24px;28/28px;36/36px;48/48px'
- };
-
- /**
- * @type {Object}
- */
- Globals.oHtmlEditorLangsMap = {
- 'de': 'de',
- 'es': 'es',
- 'fr': 'fr',
- 'hu': 'hu',
- 'is': 'is',
- 'it': 'it',
- 'ko': 'ko',
- 'ko-kr': 'ko',
- 'lv': 'lv',
- 'nl': 'nl',
- 'no': 'no',
- 'pl': 'pl',
- 'pt': 'pt',
- 'pt-pt': 'pt',
- 'pt-br': 'pt-br',
- 'ru': 'ru',
- 'ro': 'ro',
- 'zh': 'zh',
- 'zh-cn': 'zh-cn'
- };
-
- if (Globals.bAllowPdfPreview && window.navigator && window.navigator.mimeTypes)
- {
- Globals.bAllowPdfPreview = !!_.find(window.navigator.mimeTypes, function (oType) {
- return oType && 'application/pdf' === oType.type;
- });
- }
-
- Globals.oI18N = {},
-
- Globals.oNotificationI18N = {},
-
- Globals.aBootstrapDropdowns = [],
-
- Globals.aViewModels = {
- 'settings': [],
- 'settings-removed': [],
- 'settings-disabled': []
- };
-
- module.exports = Globals;
-
-}(module));
-},{"../External/$html.js":12,"../External/ko.js":21,"../External/window.js":25}],7:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-(function (module) {
-
- 'use strict';
-
- var
- window = require('../External/window.js'),
- Utils = require('./Utils.js')
- ;
-
- /**
- * @constructor
- */
- function LinkBuilder()
- {
- this.sBase = '#/';
- this.sServer = './?';
- this.sVersion = RL.settingsGet('Version');
- this.sSpecSuffix = RL.settingsGet('AuthAccountHash') || '0';
- this.sStaticPrefix = RL.settingsGet('StaticPrefix') || 'rainloop/v/' + this.sVersion + '/static/';
- }
-
- /**
- * @return {string}
- */
- LinkBuilder.prototype.root = function ()
- {
- return this.sBase;
- };
-
- /**
- * @param {string} sDownload
- * @return {string}
- */
- LinkBuilder.prototype.attachmentDownload = function (sDownload)
- {
- return this.sServer + '/Raw/' + this.sSpecSuffix + '/Download/' + sDownload;
- };
-
- /**
- * @param {string} sDownload
- * @return {string}
- */
- LinkBuilder.prototype.attachmentPreview = function (sDownload)
- {
- return this.sServer + '/Raw/' + this.sSpecSuffix + '/View/' + sDownload;
- };
-
- /**
- * @param {string} sDownload
- * @return {string}
- */
- LinkBuilder.prototype.attachmentPreviewAsPlain = function (sDownload)
- {
- return this.sServer + '/Raw/' + this.sSpecSuffix + '/ViewAsPlain/' + sDownload;
- };
-
- /**
- * @return {string}
- */
- LinkBuilder.prototype.upload = function ()
- {
- return this.sServer + '/Upload/' + this.sSpecSuffix + '/';
- };
-
- /**
- * @return {string}
- */
- LinkBuilder.prototype.uploadContacts = function ()
- {
- return this.sServer + '/UploadContacts/' + this.sSpecSuffix + '/';
- };
-
- /**
- * @return {string}
- */
- LinkBuilder.prototype.uploadBackground = function ()
- {
- return this.sServer + '/UploadBackground/' + this.sSpecSuffix + '/';
- };
-
- /**
- * @return {string}
- */
- LinkBuilder.prototype.append = function ()
- {
- return this.sServer + '/Append/' + this.sSpecSuffix + '/';
- };
-
- /**
- * @param {string} sEmail
- * @return {string}
- */
- LinkBuilder.prototype.change = function (sEmail)
- {
- return this.sServer + '/Change/' + this.sSpecSuffix + '/' + window.encodeURIComponent(sEmail) + '/';
- };
-
- /**
- * @param {string=} sAdd
- * @return {string}
- */
- LinkBuilder.prototype.ajax = function (sAdd)
- {
- return this.sServer + '/Ajax/' + this.sSpecSuffix + '/' + sAdd;
- };
-
- /**
- * @param {string} sRequestHash
- * @return {string}
- */
- LinkBuilder.prototype.messageViewLink = function (sRequestHash)
- {
- return this.sServer + '/Raw/' + this.sSpecSuffix + '/ViewAsPlain/' + sRequestHash;
- };
-
- /**
- * @param {string} sRequestHash
- * @return {string}
- */
- LinkBuilder.prototype.messageDownloadLink = function (sRequestHash)
- {
- return this.sServer + '/Raw/' + this.sSpecSuffix + '/Download/' + sRequestHash;
- };
-
- /**
- * @param {string} sEmail
- * @return {string}
- */
- LinkBuilder.prototype.avatarLink = function (sEmail)
- {
- return this.sServer + '/Raw/0/Avatar/' + window.encodeURIComponent(sEmail) + '/';
- // return '//secure.gravatar.com/avatar/' + Utils.md5(sEmail.toLowerCase()) + '.jpg?s=80&d=mm';
- };
-
- /**
- * @return {string}
- */
- LinkBuilder.prototype.inbox = function ()
- {
- return this.sBase + 'mailbox/Inbox';
- };
-
- /**
- * @return {string}
- */
- LinkBuilder.prototype.messagePreview = function ()
- {
- return this.sBase + 'mailbox/message-preview';
- };
-
- /**
- * @param {string=} sScreenName
- * @return {string}
- */
- LinkBuilder.prototype.settings = function (sScreenName)
- {
- var sResult = this.sBase + 'settings';
- if (!Utils.isUnd(sScreenName) && '' !== sScreenName)
- {
- sResult += '/' + sScreenName;
- }
-
- return sResult;
- };
-
- /**
- * @param {string} sScreenName
- * @return {string}
- */
- LinkBuilder.prototype.admin = function (sScreenName)
- {
- var sResult = this.sBase;
- switch (sScreenName) {
- case 'AdminDomains':
- sResult += 'domains';
- break;
- case 'AdminSecurity':
- sResult += 'security';
- break;
- case 'AdminLicensing':
- sResult += 'licensing';
- break;
- }
-
- return sResult;
- };
-
- /**
- * @param {string} sFolder
- * @param {number=} iPage = 1
- * @param {string=} sSearch = ''
- * @return {string}
- */
- LinkBuilder.prototype.mailBox = function (sFolder, iPage, sSearch)
- {
- iPage = Utils.isNormal(iPage) ? Utils.pInt(iPage) : 1;
- sSearch = Utils.pString(sSearch);
-
- var sResult = this.sBase + 'mailbox/';
- if ('' !== sFolder)
- {
- sResult += encodeURI(sFolder);
- }
- if (1 < iPage)
- {
- sResult = sResult.replace(/[\/]+$/, '');
- sResult += '/p' + iPage;
- }
- if ('' !== sSearch)
- {
- sResult = sResult.replace(/[\/]+$/, '');
- sResult += '/' + encodeURI(sSearch);
- }
-
- return sResult;
- };
-
- /**
- * @return {string}
- */
- LinkBuilder.prototype.phpInfo = function ()
- {
- return this.sServer + 'Info';
- };
-
- /**
- * @param {string} sLang
- * @return {string}
- */
- LinkBuilder.prototype.langLink = function (sLang)
- {
- return this.sServer + '/Lang/0/' + encodeURI(sLang) + '/' + this.sVersion + '/';
- };
-
- /**
- * @return {string}
- */
- LinkBuilder.prototype.exportContactsVcf = function ()
- {
- return this.sServer + '/Raw/' + this.sSpecSuffix + '/ContactsVcf/';
- };
-
- /**
- * @return {string}
- */
- LinkBuilder.prototype.exportContactsCsv = function ()
- {
- return this.sServer + '/Raw/' + this.sSpecSuffix + '/ContactsCsv/';
- };
-
- /**
- * @return {string}
- */
- LinkBuilder.prototype.emptyContactPic = function ()
- {
- return this.sStaticPrefix + 'css/images/empty-contact.png';
- };
-
- /**
- * @param {string} sFileName
- * @return {string}
- */
- LinkBuilder.prototype.sound = function (sFileName)
- {
- return this.sStaticPrefix + 'sounds/' + sFileName;
- };
-
- /**
- * @param {string} sTheme
- * @return {string}
- */
- LinkBuilder.prototype.themePreviewLink = function (sTheme)
- {
- var sPrefix = 'rainloop/v/' + this.sVersion + '/';
- if ('@custom' === sTheme.substr(-7))
- {
- sTheme = Utils.trim(sTheme.substring(0, sTheme.length - 7));
- sPrefix = '';
- }
-
- return sPrefix + 'themes/' + encodeURI(sTheme) + '/images/preview.png';
- };
-
- /**
- * @return {string}
- */
- LinkBuilder.prototype.notificationMailIcon = function ()
- {
- return this.sStaticPrefix + 'css/images/icom-message-notification.png';
- };
-
- /**
- * @return {string}
- */
- LinkBuilder.prototype.openPgpJs = function ()
- {
- return this.sStaticPrefix + 'js/openpgp.min.js';
- };
-
- /**
- * @return {string}
- */
- LinkBuilder.prototype.socialGoogle = function ()
- {
- return this.sServer + 'SocialGoogle' + ('' !== this.sSpecSuffix ? '/' + this.sSpecSuffix + '/' : '');
- };
-
- /**
- * @return {string}
- */
- LinkBuilder.prototype.socialTwitter = function ()
- {
- return this.sServer + 'SocialTwitter' + ('' !== this.sSpecSuffix ? '/' + this.sSpecSuffix + '/' : '');
- };
-
- /**
- * @return {string}
- */
- LinkBuilder.prototype.socialFacebook = function ()
- {
- return this.sServer + 'SocialFacebook' + ('' !== this.sSpecSuffix ? '/' + this.sSpecSuffix + '/' : '');
- };
-
- module.exports = new LinkBuilder();
-
-}(module));
-},{"../External/window.js":25,"./Utils.js":9}],8:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-(function (module) {
-
- 'use strict';
-
- var
- Plugins = {},
- Utils = require('./Utils.js'),
- Remote = require('../Remote.js'),
- RL = require('../RL.js')
- ;
-
- /**
- * @type {Object}
- */
- Plugins.oViewModelsHooks = {};
-
- /**
- * @type {Object}
- */
- Plugins.oSimpleHooks = {};
-
- /**
- * @param {string} sName
- * @param {Function} ViewModel
- */
- Plugins.regViewModelHook = function (sName, ViewModel)
- {
- if (ViewModel)
- {
- ViewModel.__hookName = sName;
- }
- };
-
- /**
- * @param {string} sName
- * @param {Function} fCallback
- */
- Plugins.addHook = function (sName, fCallback)
- {
- if (Utils.isFunc(fCallback))
- {
- if (!Utils.isArray(Plugins.oSimpleHooks[sName]))
- {
- Plugins.oSimpleHooks[sName] = [];
- }
-
- Plugins.oSimpleHooks[sName].push(fCallback);
- }
- };
-
- /**
- * @param {string} sName
- * @param {Array=} aArguments
- */
- Plugins.runHook = function (sName, aArguments)
- {
- if (Utils.isArray(Plugins.oSimpleHooks[sName]))
- {
- aArguments = aArguments || [];
-
- _.each(Plugins.oSimpleHooks[sName], function (fCallback) {
- fCallback.apply(null, aArguments);
- });
- }
- };
-
- /**
- * @param {string} sName
- * @return {?}
- */
- Plugins.mainSettingsGet = function (sName)
- {
- return RL ? RL().settingsGet(sName) : null;
- };
-
- /**
- * @param {Function} fCallback
- * @param {string} sAction
- * @param {Object=} oParameters
- * @param {?number=} iTimeout
- * @param {string=} sGetAdd = ''
- * @param {Array=} aAbortActions = []
- */
- Plugins.remoteRequest = function (fCallback, sAction, oParameters, iTimeout, sGetAdd, aAbortActions)
- {
- if (Remote)
- {
- Remote().defaultRequest(fCallback, sAction, oParameters, iTimeout, sGetAdd, aAbortActions);
- }
- };
-
- /**
- * @param {string} sPluginSection
- * @param {string} sName
- * @return {?}
- */
- Plugins.settingsGet = function (sPluginSection, sName)
- {
- var oPlugin = Plugins.mainSettingsGet('Plugins');
- oPlugin = oPlugin && Utils.isUnd(oPlugin[sPluginSection]) ? null : oPlugin[sPluginSection];
- return oPlugin ? (Utils.isUnd(oPlugin[sName]) ? null : oPlugin[sName]) : null;
- };
-
- module.exports = Plugins;
-
-}(module));
-},{"../RL.js":32,"../Remote.js":33,"./Utils.js":9}],9:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-(function (module) {
-
- 'use strict';
-
- var
- Utils = {},
-
- $ = require('../External/jquery.js'),
- _ = require('../External/underscore.js'),
- ko = require('../External/ko.js'),
- key = require('../External/key.js'),
- window = require('../External/window.js'),
- $window = require('../External/$window.js'),
- $doc = require('../External/$doc.js'),
- NotificationClass = require('../External/NotificationClass.js'),
-
- LocalStorage = require('../Storages/LocalStorage.js'),
-
- kn = require('../Knoin/Knoin.js'),
-
- Enums = require('./Enums.js'),
- Globals = require('./Globals.js')
- ;
-
- Utils.trim = $.trim;
- Utils.inArray = $.inArray;
- Utils.isArray = _.isArray;
- Utils.isFunc = _.isFunction;
- Utils.isUnd = _.isUndefined;
- Utils.isNull = _.isNull;
- Utils.emptyFunction = function () {};
-
- /**
- * @param {*} oValue
- * @return {boolean}
- */
- Utils.isNormal = function (oValue)
- {
- return !Utils.isUnd(oValue) && !Utils.isNull(oValue);
- };
-
- Utils.windowResize = _.debounce(function (iTimeout) {
- if (Utils.isUnd(iTimeout))
- {
- $window.resize();
- }
- else
- {
- window.setTimeout(function () {
- $window.resize();
- }, iTimeout);
- }
- }, 50);
-
- /**
- * @param {(string|number)} mValue
- * @param {boolean=} bIncludeZero
- * @return {boolean}
- */
- Utils.isPosNumeric = function (mValue, bIncludeZero)
- {
- return Utils.isNormal(mValue) ?
- ((Utils.isUnd(bIncludeZero) ? true : !!bIncludeZero) ?
- (/^[0-9]*$/).test(mValue.toString()) :
- (/^[1-9]+[0-9]*$/).test(mValue.toString())) :
- false;
- };
-
- /**
- * @param {*} iValue
- * @param {number=} iDefault = 0
- * @return {number}
- */
- Utils.pInt = function (iValue, iDefault)
- {
- var iResult = Utils.isNormal(iValue) && '' !== iValue ? window.parseInt(iValue, 10) : (iDefault || 0);
- return window.isNaN(iResult) ? (iDefault || 0) : iResult;
- };
-
- /**
- * @param {*} mValue
- * @return {string}
- */
- Utils.pString = function (mValue)
- {
- return Utils.isNormal(mValue) ? '' + mValue : '';
- };
-
- /**
- * @param {*} aValue
- * @return {boolean}
- */
- Utils.isNonEmptyArray = function (aValue)
- {
- return Utils.isArray(aValue) && 0 < aValue.length;
- };
-
- /**
- * @param {string} sQueryString
- * @return {Object}
- */
- Utils.simpleQueryParser = function (sQueryString)
- {
- var
- oParams = {},
- aQueries = [],
- aTemp = [],
- iIndex = 0,
- iLen = 0
- ;
-
- aQueries = sQueryString.split('&');
- for (iIndex = 0, iLen = aQueries.length; iIndex < iLen; iIndex++)
- {
- aTemp = aQueries[iIndex].split('=');
- oParams[window.decodeURIComponent(aTemp[0])] = window.decodeURIComponent(aTemp[1]);
- }
-
- return oParams;
- };
-
- /**
- * @param {string} aValue
- * @param {string} sKey
- * @param {string} sLongKey
- * @return {string|boolean}
- */
- Utils.rsaEncode = function (sValue, sHash, sKey, sLongKey)
- {
- if (window.crypto && window.crypto.getRandomValues && window.RSAKey && sHash && sKey && sLongKey)
- {
- var oRsa = new window.RSAKey();
- oRsa.setPublic(sLongKey, sKey);
-
- sValue = oRsa.encrypt(Utils.fakeMd5() + ':' + sValue + ':' + Utils.fakeMd5());
- if (false !== sValue)
- {
- return 'rsa:' + sHash + ':' + sValue;
- }
- }
-
- return false;
- };
-
- Utils.rsaEncode.supported = !!(window.crypto && window.crypto.getRandomValues && window.RSAKey);
-
- /**
- * @param {string} sPath
- * @param {*=} oObject
- * @param {Object=} oObjectToExportTo
- */
- Utils.exportPath = function (sPath, oObject, oObjectToExportTo)
- {
- var
- part = null,
- parts = sPath.split('.'),
- cur = oObjectToExportTo || window
- ;
-
- for (; parts.length && (part = parts.shift());)
- {
- if (!parts.length && !Utils.isUnd(oObject))
- {
- cur[part] = oObject;
- }
- else if (cur[part])
- {
- cur = cur[part];
- }
- else
- {
- cur = cur[part] = {};
- }
- }
- };
-
- /**
- * @param {Object} oObject
- * @param {string} sName
- * @param {*} mValue
- */
- Utils.pImport = function (oObject, sName, mValue)
- {
- oObject[sName] = mValue;
- };
-
- /**
- * @param {Object} oObject
- * @param {string} sName
- * @param {*} mDefault
- * @return {*}
- */
- Utils.pExport = function (oObject, sName, mDefault)
- {
- return Utils.isUnd(oObject[sName]) ? mDefault : oObject[sName];
- };
-
- /**
- * @param {string} sText
- * @return {string}
- */
- Utils.encodeHtml = function (sText)
- {
- return Utils.isNormal(sText) ? sText.toString()
- .replace(/&/g, '&').replace(//g, '>')
- .replace(/"/g, '"').replace(/'/g, ''') : '';
- };
-
- /**
- * @param {string} sText
- * @param {number=} iLen
- * @return {string}
- */
- Utils.splitPlainText = function (sText, iLen)
- {
- var
- sPrefix = '',
- sSubText = '',
- sResult = sText,
- iSpacePos = 0,
- iNewLinePos = 0
- ;
-
- iLen = Utils.isUnd(iLen) ? 100 : iLen;
-
- while (sResult.length > iLen)
- {
- sSubText = sResult.substring(0, iLen);
- iSpacePos = sSubText.lastIndexOf(' ');
- iNewLinePos = sSubText.lastIndexOf('\n');
-
- if (-1 !== iNewLinePos)
- {
- iSpacePos = iNewLinePos;
- }
-
- if (-1 === iSpacePos)
- {
- iSpacePos = iLen;
- }
-
- sPrefix += sSubText.substring(0, iSpacePos) + '\n';
- sResult = sResult.substring(iSpacePos + 1);
- }
-
- return sPrefix + sResult;
- };
-
- Utils.timeOutAction = (function () {
-
- var
- oTimeOuts = {}
- ;
-
- return function (sAction, fFunction, iTimeOut)
- {
- if (Utils.isUnd(oTimeOuts[sAction]))
- {
- oTimeOuts[sAction] = 0;
- }
-
- window.clearTimeout(oTimeOuts[sAction]);
- oTimeOuts[sAction] = window.setTimeout(fFunction, iTimeOut);
- };
- }());
-
- Utils.timeOutActionSecond = (function () {
-
- var
- oTimeOuts = {}
- ;
-
- return function (sAction, fFunction, iTimeOut)
- {
- if (!oTimeOuts[sAction])
- {
- oTimeOuts[sAction] = window.setTimeout(function () {
- fFunction();
- oTimeOuts[sAction] = 0;
- }, iTimeOut);
- }
- };
- }());
-
- Utils.audio = (function () {
-
- var
- oAudio = false
- ;
-
- return function (sMp3File, sOggFile) {
-
- if (false === oAudio)
- {
- if (Globals.bIsiOSDevice)
- {
- oAudio = null;
- }
- else
- {
- var
- bCanPlayMp3 = false,
- bCanPlayOgg = false,
- oAudioLocal = window.Audio ? new window.Audio() : null
- ;
-
- if (oAudioLocal && oAudioLocal.canPlayType && oAudioLocal.play)
- {
- bCanPlayMp3 = '' !== oAudioLocal.canPlayType('audio/mpeg; codecs="mp3"');
- if (!bCanPlayMp3)
- {
- bCanPlayOgg = '' !== oAudioLocal.canPlayType('audio/ogg; codecs="vorbis"');
- }
-
- if (bCanPlayMp3 || bCanPlayOgg)
- {
- oAudio = oAudioLocal;
- oAudio.preload = 'none';
- oAudio.loop = false;
- oAudio.autoplay = false;
- oAudio.muted = false;
- oAudio.src = bCanPlayMp3 ? sMp3File : sOggFile;
- }
- else
- {
- oAudio = null;
- }
- }
- else
- {
- oAudio = null;
- }
- }
- }
-
- return oAudio;
- };
- }());
-
- /**
- * @param {(Object|null|undefined)} oObject
- * @param {string} sProp
- * @return {boolean}
- */
- Utils.hos = function (oObject, sProp)
- {
- return oObject && window.Object && window.Object.hasOwnProperty ? window.Object.hasOwnProperty.call(oObject, sProp) : false;
- };
-
- /**
- * @param {string} sKey
- * @param {Object=} oValueList
- * @param {string=} sDefaulValue
- * @return {string}
- */
- Utils.i18n = function (sKey, oValueList, sDefaulValue)
- {
- var
- sValueName = '',
- sResult = Utils.isUnd(Globals.oI18N[sKey]) ? (Utils.isUnd(sDefaulValue) ? sKey : sDefaulValue) : Globals.oI18N[sKey]
- ;
-
- if (!Utils.isUnd(oValueList) && !Utils.isNull(oValueList))
- {
- for (sValueName in oValueList)
- {
- if (Utils.hos(oValueList, sValueName))
- {
- sResult = sResult.replace('%' + sValueName + '%', oValueList[sValueName]);
- }
- }
- }
-
- return sResult;
- };
-
- /**
- * @param {Object} oElement
- */
- Utils.i18nToNode = function (oElement)
- {
- _.defer(function () {
- $('.i18n', oElement).each(function () {
- var
- jqThis = $(this),
- sKey = ''
- ;
-
- sKey = jqThis.data('i18n-text');
- if (sKey)
- {
- jqThis.text(Utils.i18n(sKey));
- }
- else
- {
- sKey = jqThis.data('i18n-html');
- if (sKey)
- {
- jqThis.html(Utils.i18n(sKey));
- }
-
- sKey = jqThis.data('i18n-placeholder');
- if (sKey)
- {
- jqThis.attr('placeholder', Utils.i18n(sKey));
- }
-
- sKey = jqThis.data('i18n-title');
- if (sKey)
- {
- jqThis.attr('title', Utils.i18n(sKey));
- }
- }
- });
- });
- };
-
- Utils.i18nReload = function ()
- {
- if (window['rainloopI18N'])
- {
- Globals.oI18N = window['rainloopI18N'] || {};
-
- Utils.i18nToNode($doc);
-
- Globals.langChangeTrigger(!Globals.langChangeTrigger());
- }
-
- window['rainloopI18N'] = null;
- };
-
- /**
- * @param {Function} fCallback
- * @param {Object} oScope
- * @param {Function=} fLangCallback
- */
- Utils.initOnStartOrLangChange = function (fCallback, oScope, fLangCallback)
- {
- if (fCallback)
- {
- fCallback.call(oScope);
- }
-
- if (fLangCallback)
- {
- Globals.langChangeTrigger.subscribe(function () {
- if (fCallback)
- {
- fCallback.call(oScope);
- }
-
- fLangCallback.call(oScope);
- });
- }
- else if (fCallback)
- {
- Globals.langChangeTrigger.subscribe(fCallback, oScope);
- }
- };
-
- /**
- * @return {boolean}
- */
- Utils.inFocus = function ()
- {
- if (document.activeElement)
- {
- if (Utils.isUnd(document.activeElement.__inFocusCache))
- {
- document.activeElement.__inFocusCache = $(document.activeElement).is('input,textarea,iframe,.cke_editable');
- }
-
- return !!document.activeElement.__inFocusCache;
- }
-
- return false;
- };
-
- Utils.removeInFocus = function ()
- {
- if (document && document.activeElement && document.activeElement.blur)
- {
- var oA = $(document.activeElement);
- if (oA.is('input,textarea'))
- {
- document.activeElement.blur();
- }
- }
- };
-
- Utils.removeSelection = function ()
- {
- if (window && window.getSelection)
- {
- var oSel = window.getSelection();
- if (oSel && oSel.removeAllRanges)
- {
- oSel.removeAllRanges();
- }
- }
- else if (document && document.selection && document.selection.empty)
- {
- document.selection.empty();
- }
- };
-
- /**
- * @param {string} sPrefix
- * @param {string} sSubject
- * @return {string}
- */
- Utils.replySubjectAdd = function (sPrefix, sSubject)
- {
- sPrefix = Utils.trim(sPrefix.toUpperCase());
- sSubject = Utils.trim(sSubject.replace(/[\s]+/, ' '));
-
- var
- iIndex = 0,
- sResult = '',
- bDrop = false,
- sTrimmedPart = '',
- aSubject = [],
- aParts = [],
- bRe = 'RE' === sPrefix,
- bFwd = 'FWD' === sPrefix,
- bPrefixIsRe = !bFwd
- ;
-
- if ('' !== sSubject)
- {
- bDrop = false;
-
- aParts = sSubject.split(':');
- for (iIndex = 0; iIndex < aParts.length; iIndex++)
- {
- sTrimmedPart = Utils.trim(aParts[iIndex]);
- if (!bDrop &&
- (/^(RE|FWD)$/i.test(sTrimmedPart) || /^(RE|FWD)[\[\(][\d]+[\]\)]$/i.test(sTrimmedPart))
- )
- {
- if (!bRe)
- {
- bRe = !!(/^RE/i.test(sTrimmedPart));
- }
-
- if (!bFwd)
- {
- bFwd = !!(/^FWD/i.test(sTrimmedPart));
- }
- }
- else
- {
- aSubject.push(aParts[iIndex]);
- bDrop = true;
- }
- }
-
- if (0 < aSubject.length)
- {
- sResult = Utils.trim(aSubject.join(':'));
- }
- }
-
- if (bPrefixIsRe)
- {
- bRe = false;
- }
- else
- {
- bFwd = false;
- }
-
- return Utils.trim(
- (bPrefixIsRe ? 'Re: ' : 'Fwd: ') +
- (bRe ? 'Re: ' : '') +
- (bFwd ? 'Fwd: ' : '') +
- sResult
- );
- };
-
-
- /**
- * @param {string} sSubject
- * @return {string}
- */
- Utils.fixLongSubject = function (sSubject)
- {
- var
- iLimit = 30,
- mReg = /^Re([\[\(]([\d]+)[\]\)]|):[\s]{0,3}Re([\[\(]([\d]+)[\]\)]|):/ig,
- oMatch = null
- ;
-
- sSubject = Utils.trim(sSubject.replace(/[\s]+/, ' '));
-
- do
- {
- iLimit--;
-
- oMatch = mReg.exec(sSubject);
- if (!oMatch || Utils.isUnd(oMatch[0]))
- {
- oMatch = null;
- }
-
- if (oMatch)
- {
- sSubject = sSubject.replace(mReg, 'Re:');
- }
- }
- while (oMatch || 0 < iLimit);
-
- return sSubject.replace(/[\s]+/, ' ');
- };
-
- /**
- * @deprecated
- * @param {string} sPrefix
- * @param {string} sSubject
- * @param {boolean=} bFixLongSubject = true
- * @return {string}
- */
- Utils._replySubjectAdd_ = function (sPrefix, sSubject, bFixLongSubject)
- {
- var
- oMatch = null,
- sResult = Utils.trim(sSubject)
- ;
-
- if (null !== (oMatch = (new window.RegExp('^' + sPrefix + '[\\s]?\\:(.*)$', 'gi')).exec(sSubject)) && !Utils.isUnd(oMatch[1]))
- {
- sResult = sPrefix + '[2]: ' + oMatch[1];
- }
- else if (null !== (oMatch = (new window.RegExp('^(' + sPrefix + '[\\s]?[\\[\\(]?)([\\d]+)([\\]\\)]?[\\s]?\\:.*)$', 'gi')).exec(sSubject)) &&
- !Utils.isUnd(oMatch[1]) && !Utils.isUnd(oMatch[2]) && !Utils.isUnd(oMatch[3]))
- {
- sResult = oMatch[1] + (Utils.pInt(oMatch[2]) + 1) + oMatch[3];
- }
- else
- {
- sResult = sPrefix + ': ' + sSubject;
- }
-
- sResult = sResult.replace(/[\s]+/g, ' ');
- sResult = (Utils.isUnd(bFixLongSubject) ? true : bFixLongSubject) ? Utils.fixLongSubject(sResult) : sResult;
- // sResult = sResult.replace(/^(Re|Fwd)[\s]?\[[\d]+\]:/ig, '$1:');
- return sResult;
- };
-
- /**
- * @deprecated
- * @param {string} sSubject
- * @return {string}
- */
- Utils._fixLongSubject_ = function (sSubject)
- {
- var
- iCounter = 0,
- oMatch = null
- ;
-
- sSubject = Utils.trim(sSubject.replace(/[\s]+/, ' '));
-
- do
- {
- oMatch = /^Re(\[([\d]+)\]|):[\s]{0,3}Re(\[([\d]+)\]|):/ig.exec(sSubject);
- if (!oMatch || Utils.isUnd(oMatch[0]))
- {
- oMatch = null;
- }
-
- if (oMatch)
- {
- iCounter = 0;
- iCounter += Utils.isUnd(oMatch[2]) ? 1 : 0 + Utils.pInt(oMatch[2]);
- iCounter += Utils.isUnd(oMatch[4]) ? 1 : 0 + Utils.pInt(oMatch[4]);
-
- sSubject = sSubject.replace(/^Re(\[[\d]+\]|):[\s]{0,3}Re(\[[\d]+\]|):/gi, 'Re' + (0 < iCounter ? '[' + iCounter + ']' : '') + ':');
- }
-
- }
- while (oMatch);
-
- sSubject = sSubject.replace(/[\s]+/, ' ');
- return sSubject;
- };
-
- /**
- * @param {number} iNum
- * @param {number} iDec
- * @return {number}
- */
- Utils.roundNumber = function (iNum, iDec)
- {
- return Math.round(iNum * Math.pow(10, iDec)) / Math.pow(10, iDec);
- };
-
- /**
- * @param {(number|string)} iSizeInBytes
- * @return {string}
- */
- Utils.friendlySize = function (iSizeInBytes)
- {
- iSizeInBytes = Utils.pInt(iSizeInBytes);
-
- if (iSizeInBytes >= 1073741824)
- {
- return Utils.roundNumber(iSizeInBytes / 1073741824, 1) + 'GB';
- }
- else if (iSizeInBytes >= 1048576)
- {
- return Utils.roundNumber(iSizeInBytes / 1048576, 1) + 'MB';
- }
- else if (iSizeInBytes >= 1024)
- {
- return Utils.roundNumber(iSizeInBytes / 1024, 0) + 'KB';
- }
-
- return iSizeInBytes + 'B';
- };
-
- /**
- * @param {string} sDesc
- */
- Utils.log = function (sDesc)
- {
- if (window.console && window.console.log)
- {
- window.console.log(sDesc);
- }
- };
-
- /**
- * @param {number} iCode
- * @param {*=} mMessage = ''
- * @return {string}
- */
- Utils.getNotification = function (iCode, mMessage)
- {
- iCode = Utils.pInt(iCode);
- if (Enums.Notification.ClientViewError === iCode && mMessage)
- {
- return mMessage;
- }
-
- return Utils.isUnd(Globals.oNotificationI18N[iCode]) ? '' : Globals.oNotificationI18N[iCode];
- };
-
- Utils.initNotificationLanguage = function ()
- {
- var oN = Globals.oNotificationI18N || {};
- oN[Enums.Notification.InvalidToken] = Utils.i18n('NOTIFICATIONS/INVALID_TOKEN');
- oN[Enums.Notification.AuthError] = Utils.i18n('NOTIFICATIONS/AUTH_ERROR');
- oN[Enums.Notification.AccessError] = Utils.i18n('NOTIFICATIONS/ACCESS_ERROR');
- oN[Enums.Notification.ConnectionError] = Utils.i18n('NOTIFICATIONS/CONNECTION_ERROR');
- oN[Enums.Notification.CaptchaError] = Utils.i18n('NOTIFICATIONS/CAPTCHA_ERROR');
- oN[Enums.Notification.SocialFacebookLoginAccessDisable] = Utils.i18n('NOTIFICATIONS/SOCIAL_FACEBOOK_LOGIN_ACCESS_DISABLE');
- oN[Enums.Notification.SocialTwitterLoginAccessDisable] = Utils.i18n('NOTIFICATIONS/SOCIAL_TWITTER_LOGIN_ACCESS_DISABLE');
- oN[Enums.Notification.SocialGoogleLoginAccessDisable] = Utils.i18n('NOTIFICATIONS/SOCIAL_GOOGLE_LOGIN_ACCESS_DISABLE');
- oN[Enums.Notification.DomainNotAllowed] = Utils.i18n('NOTIFICATIONS/DOMAIN_NOT_ALLOWED');
- oN[Enums.Notification.AccountNotAllowed] = Utils.i18n('NOTIFICATIONS/ACCOUNT_NOT_ALLOWED');
-
- oN[Enums.Notification.AccountTwoFactorAuthRequired] = Utils.i18n('NOTIFICATIONS/ACCOUNT_TWO_FACTOR_AUTH_REQUIRED');
- oN[Enums.Notification.AccountTwoFactorAuthError] = Utils.i18n('NOTIFICATIONS/ACCOUNT_TWO_FACTOR_AUTH_ERROR');
-
- oN[Enums.Notification.CouldNotSaveNewPassword] = Utils.i18n('NOTIFICATIONS/COULD_NOT_SAVE_NEW_PASSWORD');
- oN[Enums.Notification.CurrentPasswordIncorrect] = Utils.i18n('NOTIFICATIONS/CURRENT_PASSWORD_INCORRECT');
- oN[Enums.Notification.NewPasswordShort] = Utils.i18n('NOTIFICATIONS/NEW_PASSWORD_SHORT');
- oN[Enums.Notification.NewPasswordWeak] = Utils.i18n('NOTIFICATIONS/NEW_PASSWORD_WEAK');
- oN[Enums.Notification.NewPasswordForbidden] = Utils.i18n('NOTIFICATIONS/NEW_PASSWORD_FORBIDDENT');
-
- oN[Enums.Notification.ContactsSyncError] = Utils.i18n('NOTIFICATIONS/CONTACTS_SYNC_ERROR');
-
- oN[Enums.Notification.CantGetMessageList] = Utils.i18n('NOTIFICATIONS/CANT_GET_MESSAGE_LIST');
- oN[Enums.Notification.CantGetMessage] = Utils.i18n('NOTIFICATIONS/CANT_GET_MESSAGE');
- oN[Enums.Notification.CantDeleteMessage] = Utils.i18n('NOTIFICATIONS/CANT_DELETE_MESSAGE');
- oN[Enums.Notification.CantMoveMessage] = Utils.i18n('NOTIFICATIONS/CANT_MOVE_MESSAGE');
- oN[Enums.Notification.CantCopyMessage] = Utils.i18n('NOTIFICATIONS/CANT_MOVE_MESSAGE');
-
- oN[Enums.Notification.CantSaveMessage] = Utils.i18n('NOTIFICATIONS/CANT_SAVE_MESSAGE');
- oN[Enums.Notification.CantSendMessage] = Utils.i18n('NOTIFICATIONS/CANT_SEND_MESSAGE');
- oN[Enums.Notification.InvalidRecipients] = Utils.i18n('NOTIFICATIONS/INVALID_RECIPIENTS');
-
- oN[Enums.Notification.CantCreateFolder] = Utils.i18n('NOTIFICATIONS/CANT_CREATE_FOLDER');
- oN[Enums.Notification.CantRenameFolder] = Utils.i18n('NOTIFICATIONS/CANT_RENAME_FOLDER');
- oN[Enums.Notification.CantDeleteFolder] = Utils.i18n('NOTIFICATIONS/CANT_DELETE_FOLDER');
- oN[Enums.Notification.CantDeleteNonEmptyFolder] = Utils.i18n('NOTIFICATIONS/CANT_DELETE_NON_EMPTY_FOLDER');
- oN[Enums.Notification.CantSubscribeFolder] = Utils.i18n('NOTIFICATIONS/CANT_SUBSCRIBE_FOLDER');
- oN[Enums.Notification.CantUnsubscribeFolder] = Utils.i18n('NOTIFICATIONS/CANT_UNSUBSCRIBE_FOLDER');
-
- oN[Enums.Notification.CantSaveSettings] = Utils.i18n('NOTIFICATIONS/CANT_SAVE_SETTINGS');
- oN[Enums.Notification.CantSavePluginSettings] = Utils.i18n('NOTIFICATIONS/CANT_SAVE_PLUGIN_SETTINGS');
-
- oN[Enums.Notification.DomainAlreadyExists] = Utils.i18n('NOTIFICATIONS/DOMAIN_ALREADY_EXISTS');
-
- oN[Enums.Notification.CantInstallPackage] = Utils.i18n('NOTIFICATIONS/CANT_INSTALL_PACKAGE');
- oN[Enums.Notification.CantDeletePackage] = Utils.i18n('NOTIFICATIONS/CANT_DELETE_PACKAGE');
- oN[Enums.Notification.InvalidPluginPackage] = Utils.i18n('NOTIFICATIONS/INVALID_PLUGIN_PACKAGE');
- oN[Enums.Notification.UnsupportedPluginPackage] = Utils.i18n('NOTIFICATIONS/UNSUPPORTED_PLUGIN_PACKAGE');
-
- oN[Enums.Notification.LicensingServerIsUnavailable] = Utils.i18n('NOTIFICATIONS/LICENSING_SERVER_IS_UNAVAILABLE');
- oN[Enums.Notification.LicensingExpired] = Utils.i18n('NOTIFICATIONS/LICENSING_EXPIRED');
- oN[Enums.Notification.LicensingBanned] = Utils.i18n('NOTIFICATIONS/LICENSING_BANNED');
-
- oN[Enums.Notification.DemoSendMessageError] = Utils.i18n('NOTIFICATIONS/DEMO_SEND_MESSAGE_ERROR');
-
- oN[Enums.Notification.AccountAlreadyExists] = Utils.i18n('NOTIFICATIONS/ACCOUNT_ALREADY_EXISTS');
-
- oN[Enums.Notification.MailServerError] = Utils.i18n('NOTIFICATIONS/MAIL_SERVER_ERROR');
- oN[Enums.Notification.InvalidInputArgument] = Utils.i18n('NOTIFICATIONS/INVALID_INPUT_ARGUMENT');
- oN[Enums.Notification.UnknownNotification] = Utils.i18n('NOTIFICATIONS/UNKNOWN_ERROR');
- oN[Enums.Notification.UnknownError] = Utils.i18n('NOTIFICATIONS/UNKNOWN_ERROR');
- };
-
- /**
- * @param {*} mCode
- * @return {string}
- */
- Utils.getUploadErrorDescByCode = function (mCode)
- {
- var sResult = '';
- switch (Utils.pInt(mCode)) {
- case Enums.UploadErrorCode.FileIsTooBig:
- sResult = Utils.i18n('UPLOAD/ERROR_FILE_IS_TOO_BIG');
- break;
- case Enums.UploadErrorCode.FilePartiallyUploaded:
- sResult = Utils.i18n('UPLOAD/ERROR_FILE_PARTIALLY_UPLOADED');
- break;
- case Enums.UploadErrorCode.FileNoUploaded:
- sResult = Utils.i18n('UPLOAD/ERROR_NO_FILE_UPLOADED');
- break;
- case Enums.UploadErrorCode.MissingTempFolder:
- sResult = Utils.i18n('UPLOAD/ERROR_MISSING_TEMP_FOLDER');
- break;
- case Enums.UploadErrorCode.FileOnSaveingError:
- sResult = Utils.i18n('UPLOAD/ERROR_ON_SAVING_FILE');
- break;
- case Enums.UploadErrorCode.FileType:
- sResult = Utils.i18n('UPLOAD/ERROR_FILE_TYPE');
- break;
- default:
- sResult = Utils.i18n('UPLOAD/ERROR_UNKNOWN');
- break;
- }
-
- return sResult;
- };
-
- /**
- * @param {?} oObject
- * @param {string} sMethodName
- * @param {Array=} aParameters
- * @param {number=} nDelay
- */
- Utils.delegateRun = function (oObject, sMethodName, aParameters, nDelay)
- {
- if (oObject && oObject[sMethodName])
- {
- nDelay = Utils.pInt(nDelay);
- if (0 >= nDelay)
- {
- oObject[sMethodName].apply(oObject, Utils.isArray(aParameters) ? aParameters : []);
- }
- else
- {
- _.delay(function () {
- oObject[sMethodName].apply(oObject, Utils.isArray(aParameters) ? aParameters : []);
- }, nDelay);
- }
- }
- };
-
- /**
- * @param {?} oEvent
- */
- Utils.killCtrlAandS = function (oEvent)
- {
- oEvent = oEvent || window.event;
- if (oEvent && oEvent.ctrlKey && !oEvent.shiftKey && !oEvent.altKey)
- {
- var
- oSender = oEvent.target || oEvent.srcElement,
- iKey = oEvent.keyCode || oEvent.which
- ;
-
- if (iKey === Enums.EventKeyCode.S)
- {
- oEvent.preventDefault();
- return;
- }
-
- if (oSender && oSender.tagName && oSender.tagName.match(/INPUT|TEXTAREA/i))
- {
- return;
- }
-
- if (iKey === Enums.EventKeyCode.A)
- {
- if (window.getSelection)
- {
- window.getSelection().removeAllRanges();
- }
- else if (window.document.selection && window.document.selection.clear)
- {
- window.document.selection.clear();
- }
-
- oEvent.preventDefault();
- }
- }
- };
-
- /**
- * @param {(Object|null|undefined)} oContext
- * @param {Function} fExecute
- * @param {(Function|boolean|null)=} fCanExecute
- * @return {Function}
- */
- Utils.createCommand = function (oContext, fExecute, fCanExecute)
- {
- var
- fResult = fExecute ? function () {
- if (fResult.canExecute && fResult.canExecute())
- {
- fExecute.apply(oContext, Array.prototype.slice.call(arguments));
- }
- return false;
- } : function () {}
- ;
-
- fResult.enabled = ko.observable(true);
-
- fCanExecute = Utils.isUnd(fCanExecute) ? true : fCanExecute;
- if (Utils.isFunc(fCanExecute))
- {
- fResult.canExecute = ko.computed(function () {
- return fResult.enabled() && fCanExecute.call(oContext);
- });
- }
- else
- {
- fResult.canExecute = ko.computed(function () {
- return fResult.enabled() && !!fCanExecute;
- });
- }
-
- return fResult;
- };
-
- /**
- * @param {Object} oData
- */
- Utils.initDataConstructorBySettings = function (oData)
- {
- oData.editorDefaultType = ko.observable(Enums.EditorDefaultType.Html);
- oData.showImages = ko.observable(false);
- oData.interfaceAnimation = ko.observable(Enums.InterfaceAnimation.Full);
- oData.contactsAutosave = ko.observable(false);
-
- Globals.sAnimationType = Enums.InterfaceAnimation.Full;
-
- oData.capaThemes = ko.observable(false);
- oData.allowLanguagesOnSettings = ko.observable(true);
- oData.allowLanguagesOnLogin = ko.observable(true);
-
- oData.useLocalProxyForExternalImages = ko.observable(false);
-
- oData.desktopNotifications = ko.observable(false);
- oData.useThreads = ko.observable(true);
- oData.replySameFolder = ko.observable(true);
- oData.useCheckboxesInList = ko.observable(true);
-
- oData.layout = ko.observable(Enums.Layout.SidePreview);
- oData.usePreviewPane = ko.computed(function () {
- return Enums.Layout.NoPreview !== oData.layout();
- });
-
- oData.interfaceAnimation.subscribe(function (sValue) {
- if (Globals.bMobileDevice || sValue === Enums.InterfaceAnimation.None)
- {
- $html.removeClass('rl-anim rl-anim-full').addClass('no-rl-anim');
-
- Globals.sAnimationType = Enums.InterfaceAnimation.None;
- }
- else
- {
- switch (sValue)
- {
- case Enums.InterfaceAnimation.Full:
- $html.removeClass('no-rl-anim').addClass('rl-anim rl-anim-full');
- Globals.sAnimationType = sValue;
- break;
- case Enums.InterfaceAnimation.Normal:
- $html.removeClass('no-rl-anim rl-anim-full').addClass('rl-anim');
- Globals.sAnimationType = sValue;
- break;
- }
- }
- });
-
- oData.interfaceAnimation.valueHasMutated();
-
- oData.desktopNotificationsPermisions = ko.computed(function () {
- oData.desktopNotifications();
- var iResult = Enums.DesktopNotifications.NotSupported;
- if (NotificationClass && NotificationClass.permission)
- {
- switch (NotificationClass.permission.toLowerCase())
- {
- case 'granted':
- iResult = Enums.DesktopNotifications.Allowed;
- break;
- case 'denied':
- iResult = Enums.DesktopNotifications.Denied;
- break;
- case 'default':
- iResult = Enums.DesktopNotifications.NotAllowed;
- break;
- }
- }
- else if (window.webkitNotifications && window.webkitNotifications.checkPermission)
- {
- iResult = window.webkitNotifications.checkPermission();
- }
-
- return iResult;
- });
-
- oData.useDesktopNotifications = ko.computed({
- 'read': function () {
- return oData.desktopNotifications() &&
- Enums.DesktopNotifications.Allowed === oData.desktopNotificationsPermisions();
- },
- 'write': function (bValue) {
- if (bValue)
- {
- var iPermission = oData.desktopNotificationsPermisions();
- if (Enums.DesktopNotifications.Allowed === iPermission)
- {
- oData.desktopNotifications(true);
- }
- else if (Enums.DesktopNotifications.NotAllowed === iPermission)
- {
- NotificationClass.requestPermission(function () {
- oData.desktopNotifications.valueHasMutated();
- if (Enums.DesktopNotifications.Allowed === oData.desktopNotificationsPermisions())
- {
- if (oData.desktopNotifications())
- {
- oData.desktopNotifications.valueHasMutated();
- }
- else
- {
- oData.desktopNotifications(true);
- }
- }
- else
- {
- if (oData.desktopNotifications())
- {
- oData.desktopNotifications(false);
- }
- else
- {
- oData.desktopNotifications.valueHasMutated();
- }
- }
- });
- }
- else
- {
- oData.desktopNotifications(false);
- }
- }
- else
- {
- oData.desktopNotifications(false);
- }
- }
- });
-
- oData.language = ko.observable('');
- oData.languages = ko.observableArray([]);
-
- oData.mainLanguage = ko.computed({
- 'read': oData.language,
- 'write': function (sValue) {
- if (sValue !== oData.language())
- {
- if (-1 < Utils.inArray(sValue, oData.languages()))
- {
- oData.language(sValue);
- }
- else if (0 < oData.languages().length)
- {
- oData.language(oData.languages()[0]);
- }
- }
- else
- {
- oData.language.valueHasMutated();
- }
- }
- });
-
- oData.theme = ko.observable('');
- oData.themes = ko.observableArray([]);
-
- oData.mainTheme = ko.computed({
- 'read': oData.theme,
- 'write': function (sValue) {
- if (sValue !== oData.theme())
- {
- var aThemes = oData.themes();
- if (-1 < Utils.inArray(sValue, aThemes))
- {
- oData.theme(sValue);
- }
- else if (0 < aThemes.length)
- {
- oData.theme(aThemes[0]);
- }
- }
- else
- {
- oData.theme.valueHasMutated();
- }
- }
- });
-
- oData.capaAdditionalAccounts = ko.observable(false);
- oData.capaAdditionalIdentities = ko.observable(false);
- oData.capaGravatar = ko.observable(false);
- oData.determineUserLanguage = ko.observable(false);
- oData.determineUserDomain = ko.observable(false);
-
- oData.messagesPerPage = ko.observable(Consts.Defaults.MessagesPerPage);//.extend({'throttle': 200});
-
- oData.mainMessagesPerPage = oData.messagesPerPage;
- oData.mainMessagesPerPage = ko.computed({
- 'read': oData.messagesPerPage,
- 'write': function (iValue) {
- if (-1 < Utils.inArray(Utils.pInt(iValue), Consts.Defaults.MessagesPerPageArray))
- {
- if (iValue !== oData.messagesPerPage())
- {
- oData.messagesPerPage(iValue);
- }
- }
- else
- {
- oData.messagesPerPage.valueHasMutated();
- }
- }
- });
-
- oData.facebookSupported = ko.observable(false);
- oData.facebookEnable = ko.observable(false);
- oData.facebookAppID = ko.observable('');
- oData.facebookAppSecret = ko.observable('');
-
- oData.twitterEnable = ko.observable(false);
- oData.twitterConsumerKey = ko.observable('');
- oData.twitterConsumerSecret = ko.observable('');
-
- oData.googleEnable = ko.observable(false);
- oData.googleClientID = ko.observable('');
- oData.googleClientSecret = ko.observable('');
- oData.googleApiKey = ko.observable('');
-
- oData.dropboxEnable = ko.observable(false);
- oData.dropboxApiKey = ko.observable('');
-
- oData.contactsIsAllowed = ko.observable(false);
- };
-
- /**
- * @param {{moment:Function}} oObject
- */
- Utils.createMomentDate = function (oObject)
- {
- if (Utils.isUnd(oObject.moment))
- {
- oObject.moment = ko.observable(moment());
- }
-
- return ko.computed(function () {
- Globals.momentTrigger();
- var oMoment = this.moment();
- return 1970 === oMoment.year() ? '' : oMoment.fromNow();
- }, oObject);
- };
-
- /**
- * @param {{moment:Function, momentDate:Function}} oObject
- */
- Utils.createMomentShortDate = function (oObject)
- {
- return ko.computed(function () {
-
- var
- sResult = '',
- oMomentNow = moment(),
- oMoment = this.moment(),
- sMomentDate = this.momentDate()
- ;
-
- if (1970 === oMoment.year())
- {
- sResult = '';
- }
- else if (4 >= oMomentNow.diff(oMoment, 'hours'))
- {
- sResult = sMomentDate;
- }
- else if (oMomentNow.format('L') === oMoment.format('L'))
- {
- sResult = Utils.i18n('MESSAGE_LIST/TODAY_AT', {
- 'TIME': oMoment.format('LT')
- });
- }
- else if (oMomentNow.clone().subtract('days', 1).format('L') === oMoment.format('L'))
- {
- sResult = Utils.i18n('MESSAGE_LIST/YESTERDAY_AT', {
- 'TIME': oMoment.format('LT')
- });
- }
- else if (oMomentNow.year() === oMoment.year())
- {
- sResult = oMoment.format('D MMM.');
- }
- else
- {
- sResult = oMoment.format('LL');
- }
-
- return sResult;
-
- }, oObject);
- };
-
- /**
- * @param {string} sFullNameHash
- * @return {boolean}
- */
- Utils.isFolderExpanded = function (sFullNameHash)
- {
- var aExpandedList = /** @type {Array|null} */ LocalStorage.get(Enums.ClientSideKeyName.ExpandedFolders);
- return _.isArray(aExpandedList) && -1 !== _.indexOf(aExpandedList, sFullNameHash);
- };
-
- /**
- * @param {string} sFullNameHash
- * @param {boolean} bExpanded
- */
- Utils.setExpandedFolder = function (sFullNameHash, bExpanded)
- {
- var aExpandedList = /** @type {Array|null} */ LocalStorage.get(Enums.ClientSideKeyName.ExpandedFolders);
- if (!_.isArray(aExpandedList))
- {
- aExpandedList = [];
- }
-
- if (bExpanded)
- {
- aExpandedList.push(sFullNameHash);
- aExpandedList = _.uniq(aExpandedList);
- }
- else
- {
- aExpandedList = _.without(aExpandedList, sFullNameHash);
- }
-
- LocalStorage.set(Enums.ClientSideKeyName.ExpandedFolders, aExpandedList);
- };
-
- Utils.initLayoutResizer = function (sLeft, sRight, sClientSideKeyName)
- {
- var
- iDisabledWidth = 60,
- iMinWidth = 155,
- oLeft = $(sLeft),
- oRight = $(sRight),
-
- mLeftWidth = LocalStorage.get(sClientSideKeyName) || null,
-
- fSetWidth = function (iWidth) {
- if (iWidth)
- {
- oLeft.css({
- 'width': '' + iWidth + 'px'
- });
-
- oRight.css({
- 'left': '' + iWidth + 'px'
- });
- }
- },
-
- fDisable = function (bDisable) {
- if (bDisable)
- {
- oLeft.resizable('disable');
- fSetWidth(iDisabledWidth);
- }
- else
- {
- oLeft.resizable('enable');
- var iWidth = Utils.pInt(LocalStorage.get(sClientSideKeyName)) || iMinWidth;
- fSetWidth(iWidth > iMinWidth ? iWidth : iMinWidth);
- }
- },
-
- fResizeFunction = function (oEvent, oObject) {
- if (oObject && oObject.size && oObject.size.width)
- {
- LocalStorage.set(sClientSideKeyName, oObject.size.width);
-
- oRight.css({
- 'left': '' + oObject.size.width + 'px'
- });
- }
- }
- ;
-
- if (null !== mLeftWidth)
- {
- fSetWidth(mLeftWidth > iMinWidth ? mLeftWidth : iMinWidth);
- }
-
- oLeft.resizable({
- 'helper': 'ui-resizable-helper',
- 'minWidth': iMinWidth,
- 'maxWidth': 350,
- 'handles': 'e',
- 'stop': fResizeFunction
- });
-
- RL.sub('left-panel.off', function () {
- fDisable(true);
- });
-
- RL.sub('left-panel.on', function () {
- fDisable(false);
- });
- };
-
- /**
- * @param {Object} oMessageTextBody
- */
- Utils.initBlockquoteSwitcher = function (oMessageTextBody)
- {
- if (oMessageTextBody)
- {
- var $oList = $('blockquote:not(.rl-bq-switcher)', oMessageTextBody).filter(function () {
- return 0 === $(this).parent().closest('blockquote', oMessageTextBody).length;
- });
-
- if ($oList && 0 < $oList.length)
- {
- $oList.each(function () {
- var $self = $(this), iH = $self.height();
- if (0 === iH || 100 < iH)
- {
- $self.addClass('rl-bq-switcher hidden-bq');
- $('')
- .insertBefore($self)
- .click(function () {
- $self.toggleClass('hidden-bq');
- Utils.windowResize();
- })
- .after('
')
- .before('
')
- ;
- }
- });
- }
- }
- };
-
- /**
- * @param {Object} oMessageTextBody
- */
- Utils.removeBlockquoteSwitcher = function (oMessageTextBody)
- {
- if (oMessageTextBody)
- {
- $(oMessageTextBody).find('blockquote.rl-bq-switcher').each(function () {
- $(this).removeClass('rl-bq-switcher hidden-bq');
- });
-
- $(oMessageTextBody).find('.rlBlockquoteSwitcher').each(function () {
- $(this).remove();
- });
- }
- };
-
- /**
- * @param {Object} oMessageTextBody
- */
- Utils.toggleMessageBlockquote = function (oMessageTextBody)
- {
- if (oMessageTextBody)
- {
- oMessageTextBody.find('.rlBlockquoteSwitcher').click();
- }
- };
-
- Utils.convertThemeName = function (sTheme)
- {
- if ('@custom' === sTheme.substr(-7))
- {
- sTheme = Utils.trim(sTheme.substring(0, sTheme.length - 7));
- }
-
- return Utils.trim(sTheme.replace(/[^a-zA-Z]+/g, ' ').replace(/([A-Z])/g, ' $1').replace(/[\s]+/g, ' '));
- };
-
- /**
- * @param {string} sName
- * @return {string}
- */
- Utils.quoteName = function (sName)
- {
- return sName.replace(/["]/g, '\\"');
- };
-
- /**
- * @return {number}
- */
- Utils.microtime = function ()
- {
- return (new Date()).getTime();
- };
-
- /**
- *
- * @param {string} sLanguage
- * @param {boolean=} bEng = false
- * @return {string}
- */
- Utils.convertLangName = function (sLanguage, bEng)
- {
- return Utils.i18n('LANGS_NAMES' + (true === bEng ? '_EN' : '') + '/LANG_' +
- sLanguage.toUpperCase().replace(/[^a-zA-Z0-9]+/, '_'), null, sLanguage);
- };
-
- /**
- * @param {number=} iLen
- * @return {string}
- */
- Utils.fakeMd5 = function(iLen)
- {
- var
- sResult = '',
- sLine = '0123456789abcdefghijklmnopqrstuvwxyz'
- ;
-
- iLen = Utils.isUnd(iLen) ? 32 : Utils.pInt(iLen);
-
- while (sResult.length < iLen)
- {
- sResult += sLine.substr(window.Math.round(window.Math.random() * sLine.length), 1);
- }
-
- return sResult;
- };
-
- /* jshint ignore:start */
-
- /**
- * @param {string} s
- * @return {string}
- */
- Utils.md5 = function(s){function L(k,d){return(k<>>(32-d))}function K(G,k){var I,d,F,H,x;F=(G&2147483648);H=(k&2147483648);I=(G&1073741824);d=(k&1073741824);x=(G&1073741823)+(k&1073741823);if(I&d){return(x^2147483648^F^H)}if(I|d){if(x&1073741824){return(x^3221225472^F^H)}else{return(x^1073741824^F^H)}}else{return(x^F^H)}}function r(d,F,k){return(d&F)|((~d)&k)}function q(d,F,k){return(d&k)|(F&(~k))}function p(d,F,k){return(d^F^k)}function n(d,F,k){return(F^(d|(~k)))}function u(G,F,aa,Z,k,H,I){G=K(G,K(K(r(F,aa,Z),k),I));return K(L(G,H),F)}function f(G,F,aa,Z,k,H,I){G=K(G,K(K(q(F,aa,Z),k),I));return K(L(G,H),F)}function D(G,F,aa,Z,k,H,I){G=K(G,K(K(p(F,aa,Z),k),I));return K(L(G,H),F)}function t(G,F,aa,Z,k,H,I){G=K(G,K(K(n(F,aa,Z),k),I));return K(L(G,H),F)}function e(G){var Z;var F=G.length;var x=F+8;var k=(x-(x%64))/64;var I=(k+1)*16;var aa=Array(I-1);var d=0;var H=0;while(H>>29;return aa}function B(x){var k="",F="",G,d;for(d=0;d<=3;d++){G=(x>>>(d*8))&255;F="0"+G.toString(16);k=k+F.substr(F.length-2,2)}return k}function J(k){k=k.replace(/rn/g,"n");var d="";for(var F=0;F127)&&(x<2048)){d+=String.fromCharCode((x>>6)|192);d+=String.fromCharCode((x&63)|128)}else{d+=String.fromCharCode((x>>12)|224);d+=String.fromCharCode(((x>>6)&63)|128);d+=String.fromCharCode((x&63)|128)}}}return d}var C=Array();var P,h,E,v,g,Y,X,W,V;var S=7,Q=12,N=17,M=22;var A=5,z=9,y=14,w=20;var o=4,m=11,l=16,j=23;var U=6,T=10,R=15,O=21;s=J(s);C=e(s);Y=1732584193;X=4023233417;W=2562383102;V=271733878;for(P=0;P /g, '>').replace(/');
- };
-
- Utils.draggeblePlace = function ()
- {
- return $(' ').appendTo('#rl-hidden');
- };
-
- Utils.defautOptionsAfterRender = function (oOption, oItem)
- {
- if (oItem && !Utils.isUnd(oItem.disabled) && oOption)
- {
- $(oOption)
- .toggleClass('disabled', oItem.disabled)
- .prop('disabled', oItem.disabled)
- ;
- }
- };
-
- /**
- * @param {Object} oViewModel
- * @param {string} sTemplateID
- * @param {string} sTitle
- * @param {Function=} fCallback
- */
- Utils.windowPopupKnockout = function (oViewModel, sTemplateID, sTitle, fCallback)
- {
- var
- oScript = null,
- oWin = window.open(''),
- sFunc = '__OpenerApplyBindingsUid' + Utils.fakeMd5() + '__',
- oTemplate = $('#' + sTemplateID)
- ;
-
- window[sFunc] = function () {
-
- if (oWin && oWin.document.body && oTemplate && oTemplate[0])
- {
- var oBody = $(oWin.document.body);
-
- $('#rl-content', oBody).html(oTemplate.html());
- $('html', oWin.document).addClass('external ' + $('html').attr('class'));
-
- Utils.i18nToNode(oBody);
-
- kn.applyExternal(oViewModel, $('#rl-content', oBody)[0]);
-
- window[sFunc] = null;
-
- fCallback(oWin);
- }
- };
-
- oWin.document.open();
- oWin.document.write('' +
- '' +
- '' +
- '' +
- '' +
- '' +
- '' + Utils.encodeHtml(sTitle) + ' ' +
- '');
- oWin.document.close();
-
- oScript = oWin.document.createElement('script');
- oScript.type = 'text/javascript';
- oScript.innerHTML = 'if(window&&window.opener&&window.opener[\'' + sFunc + '\']){window.opener[\'' + sFunc + '\']();window.opener[\'' + sFunc + '\']=null}';
- oWin.document.getElementsByTagName('head')[0].appendChild(oScript);
- };
-
- Utils.settingsSaveHelperFunction = function (fCallback, koTrigger, oContext, iTimer)
- {
- oContext = oContext || null;
- iTimer = Utils.isUnd(iTimer) ? 1000 : Utils.pInt(iTimer);
- return function (sType, mData, bCached, sRequestAction, oRequestParameters) {
- koTrigger.call(oContext, mData && mData['Result'] ? Enums.SaveSettingsStep.TrueResult : Enums.SaveSettingsStep.FalseResult);
- if (fCallback)
- {
- fCallback.call(oContext, sType, mData, bCached, sRequestAction, oRequestParameters);
- }
- _.delay(function () {
- koTrigger.call(oContext, Enums.SaveSettingsStep.Idle);
- }, iTimer);
- };
- };
-
- Utils.settingsSaveHelperSimpleFunction = function (koTrigger, oContext)
- {
- return Utils.settingsSaveHelperFunction(null, koTrigger, oContext, 1000);
- };
-
- Utils.$div = $('');
-
- /**
- * @param {string} sHtml
- * @return {string}
- */
- Utils.htmlToPlain = function (sHtml)
- {
- var
- iPos = 0,
- iP1 = 0,
- iP2 = 0,
- iP3 = 0,
- iLimit = 0,
-
- sText = '',
-
- splitPlainText = function (sText)
- {
- var
- iLen = 100,
- sPrefix = '',
- sSubText = '',
- sResult = sText,
- iSpacePos = 0,
- iNewLinePos = 0
- ;
-
- while (sResult.length > iLen)
- {
- sSubText = sResult.substring(0, iLen);
- iSpacePos = sSubText.lastIndexOf(' ');
- iNewLinePos = sSubText.lastIndexOf('\n');
-
- if (-1 !== iNewLinePos)
- {
- iSpacePos = iNewLinePos;
- }
-
- if (-1 === iSpacePos)
- {
- iSpacePos = iLen;
- }
-
- sPrefix += sSubText.substring(0, iSpacePos) + '\n';
- sResult = sResult.substring(iSpacePos + 1);
- }
-
- return sPrefix + sResult;
- },
-
- convertBlockquote = function (sText) {
- sText = splitPlainText($.trim(sText));
- sText = '> ' + sText.replace(/\n/gm, '\n> ');
- return sText.replace(/(^|\n)([> ]+)/gm, function () {
- return (arguments && 2 < arguments.length) ? arguments[1] + $.trim(arguments[2].replace(/[\s]/, '')) + ' ' : '';
- });
- },
-
- convertDivs = function () {
- if (arguments && 1 < arguments.length)
- {
- var sText = $.trim(arguments[1]);
- if (0 < sText.length)
- {
- sText = sText.replace(/]*>([\s\S\r\n]*)<\/div>/gmi, convertDivs);
- sText = '\n' + $.trim(sText) + '\n';
- }
-
- return sText;
- }
-
- return '';
- },
-
- convertPre = function () {
- return (arguments && 1 < arguments.length) ? arguments[1].toString().replace(/[\n]/gm, '
') : '';
- },
-
- fixAttibuteValue = function () {
- return (arguments && 1 < arguments.length) ?
- '' + arguments[1] + arguments[2].replace(//g, '>') : '';
- },
-
- convertLinks = function () {
- return (arguments && 1 < arguments.length) ? $.trim(arguments[1]) : '';
- }
- ;
-
- sText = sHtml
- .replace(/]*>([\s\S\r\n]*)<\/pre>/gmi, convertPre)
- .replace(/[\s]+/gm, ' ')
- .replace(/((?:href|data)\s?=\s?)("[^"]+?"|'[^']+?')/gmi, fixAttibuteValue)
- .replace(/
]*>/gmi, '\n')
- .replace(/<\/h[\d]>/gi, '\n')
- .replace(/<\/p>/gi, '\n\n')
- .replace(/<\/li>/gi, '\n')
- .replace(/<\/td>/gi, '\n')
- .replace(/<\/tr>/gi, '\n')
- .replace(/
]*>/gmi, '\n_______________________________\n\n')
- .replace(/]*>([\s\S\r\n]*)<\/div>/gmi, convertDivs)
- .replace(/]*>/gmi, '\n__bq__start__\n')
- .replace(/<\/blockquote>/gmi, '\n__bq__end__\n')
- .replace(/]*>([\s\S\r\n]*?)<\/a>/gmi, convertLinks)
- .replace(/<\/div>/gi, '\n')
- .replace(/ /gi, ' ')
- .replace(/"/gi, '"')
- .replace(/<[^>]*>/gm, '')
- ;
-
- sText = Utils.$div.html(sText).text();
-
- sText = sText
- .replace(/\n[ \t]+/gm, '\n')
- .replace(/[\n]{3,}/gm, '\n\n')
- .replace(/>/gi, '>')
- .replace(/</gi, '<')
- .replace(/&/gi, '&')
- ;
-
- iPos = 0;
- iLimit = 100;
-
- while (0 < iLimit)
- {
- iLimit--;
- iP1 = sText.indexOf('__bq__start__', iPos);
- if (-1 < iP1)
- {
- iP2 = sText.indexOf('__bq__start__', iP1 + 5);
- iP3 = sText.indexOf('__bq__end__', iP1 + 5);
-
- if ((-1 === iP2 || iP3 < iP2) && iP1 < iP3)
- {
- sText = sText.substring(0, iP1) +
- convertBlockquote(sText.substring(iP1 + 13, iP3)) +
- sText.substring(iP3 + 11);
-
- iPos = 0;
- }
- else if (-1 < iP2 && iP2 < iP3)
- {
- iPos = iP2 - 1;
- }
- else
- {
- iPos = 0;
- }
- }
- else
- {
- break;
- }
- }
-
- sText = sText
- .replace(/__bq__start__/gm, '')
- .replace(/__bq__end__/gm, '')
- ;
-
- return sText;
- };
-
- /**
- * @param {string} sPlain
- * @param {boolean} bLinkify = false
- * @return {string}
- */
- Utils.plainToHtml = function (sPlain, bLinkify)
- {
- sPlain = sPlain.toString().replace(/\r/g, '');
-
- var
- bIn = false,
- bDo = true,
- bStart = true,
- aNextText = [],
- sLine = '',
- iIndex = 0,
- aText = sPlain.split("\n")
- ;
-
- do
- {
- bDo = false;
- aNextText = [];
- for (iIndex = 0; iIndex < aText.length; iIndex++)
- {
- sLine = aText[iIndex];
- bStart = '>' === sLine.substr(0, 1);
- if (bStart && !bIn)
- {
- bDo = true;
- bIn = true;
- aNextText.push('~~~blockquote~~~');
- aNextText.push(sLine.substr(1));
- }
- else if (!bStart && bIn)
- {
- bIn = false;
- aNextText.push('~~~/blockquote~~~');
- aNextText.push(sLine);
- }
- else if (bStart && bIn)
- {
- aNextText.push(sLine.substr(1));
- }
- else
- {
- aNextText.push(sLine);
- }
- }
-
- if (bIn)
- {
- bIn = false;
- aNextText.push('~~~/blockquote~~~');
- }
-
- aText = aNextText;
- }
- while (bDo);
-
- sPlain = aText.join("\n");
-
- sPlain = sPlain
- .replace(/&/g, '&')
- .replace(/>/g, '>').replace(/')
- .replace(/[\s]*~~~\/blockquote~~~/g, '
')
- .replace(/[\-_~]{10,}/g, '
')
- .replace(/\n/g, '
');
-
- return bLinkify ? Utils.linkify(sPlain) : sPlain;
- };
-
- window.rainloop_Utils_htmlToPlain = Utils.htmlToPlain;
- window.rainloop_Utils_plainToHtml = Utils.plainToHtml;
-
- /**
- * @param {string} sHtml
- * @return {string}
- */
- Utils.linkify = function (sHtml)
- {
- if ($.fn && $.fn.linkify)
- {
- sHtml = Utils.$div.html(sHtml.replace(/&/ig, 'amp_amp_12345_amp_amp'))
- .linkify()
- .find('.linkified').removeClass('linkified').end()
- .html()
- .replace(/amp_amp_12345_amp_amp/g, '&')
- ;
- }
-
- return sHtml;
- };
-
- Utils.resizeAndCrop = function (sUrl, iValue, fCallback)
- {
- var oTempImg = new window.Image();
- oTempImg.onload = function() {
-
- var
- aDiff = [0, 0],
- oCanvas = document.createElement('canvas'),
- oCtx = oCanvas.getContext('2d')
- ;
-
- oCanvas.width = iValue;
- oCanvas.height = iValue;
-
- if (this.width > this.height)
- {
- aDiff = [this.width - this.height, 0];
- }
- else
- {
- aDiff = [0, this.height - this.width];
- }
-
- oCtx.fillStyle = '#fff';
- oCtx.fillRect(0, 0, iValue, iValue);
- oCtx.drawImage(this, aDiff[0] / 2, aDiff[1] / 2, this.width - aDiff[0], this.height - aDiff[1], 0, 0, iValue, iValue);
-
- fCallback(oCanvas.toDataURL('image/jpeg'));
- };
-
- oTempImg.src = sUrl;
- };
-
- Utils.computedPagenatorHelper = function (koCurrentPage, koPageCount)
- {
- return function() {
- var
- iPrev = 0,
- iNext = 0,
- iLimit = 2,
- aResult = [],
- iCurrentPage = koCurrentPage(),
- iPageCount = koPageCount(),
-
- /**
- * @param {number} iIndex
- * @param {boolean=} bPush
- * @param {string=} sCustomName
- */
- fAdd = function (iIndex, bPush, sCustomName) {
-
- var oData = {
- 'current': iIndex === iCurrentPage,
- 'name': Utils.isUnd(sCustomName) ? iIndex.toString() : sCustomName.toString(),
- 'custom': Utils.isUnd(sCustomName) ? false : true,
- 'title': Utils.isUnd(sCustomName) ? '' : iIndex.toString(),
- 'value': iIndex.toString()
- };
-
- if (Utils.isUnd(bPush) ? true : !!bPush)
- {
- aResult.push(oData);
- }
- else
- {
- aResult.unshift(oData);
- }
- }
- ;
-
- if (1 < iPageCount || (0 < iPageCount && iPageCount < iCurrentPage))
- // if (0 < iPageCount && 0 < iCurrentPage)
- {
- if (iPageCount < iCurrentPage)
- {
- fAdd(iPageCount);
- iPrev = iPageCount;
- iNext = iPageCount;
- }
- else
- {
- if (3 >= iCurrentPage || iPageCount - 2 <= iCurrentPage)
- {
- iLimit += 2;
- }
-
- fAdd(iCurrentPage);
- iPrev = iCurrentPage;
- iNext = iCurrentPage;
- }
-
- while (0 < iLimit) {
-
- iPrev -= 1;
- iNext += 1;
-
- if (0 < iPrev)
- {
- fAdd(iPrev, false);
- iLimit--;
- }
-
- if (iPageCount >= iNext)
- {
- fAdd(iNext, true);
- iLimit--;
- }
- else if (0 >= iPrev)
- {
- break;
- }
- }
-
- if (3 === iPrev)
- {
- fAdd(2, false);
- }
- else if (3 < iPrev)
- {
- fAdd(Math.round((iPrev - 1) / 2), false, '...');
- }
-
- if (iPageCount - 2 === iNext)
- {
- fAdd(iPageCount - 1, true);
- }
- else if (iPageCount - 2 > iNext)
- {
- fAdd(Math.round((iPageCount + iNext) / 2), true, '...');
- }
-
- // first and last
- if (1 < iPrev)
- {
- fAdd(1, false);
- }
-
- if (iPageCount > iNext)
- {
- fAdd(iPageCount, true);
- }
- }
-
- return aResult;
- };
- };
-
- Utils.selectElement = function (element)
- {
- /* jshint onevar: false */
- if (window.getSelection)
- {
- var sel = window.getSelection();
- sel.removeAllRanges();
- var range = document.createRange();
- range.selectNodeContents(element);
- sel.addRange(range);
- }
- else if (document.selection)
- {
- var textRange = document.body.createTextRange();
- textRange.moveToElementText(element);
- textRange.select();
- }
- /* jshint onevar: true */
- };
-
- Utils.disableKeyFilter = function ()
- {
- if (window.key)
- {
- key.filter = function () {
- return RL.data().useKeyboardShortcuts();
- };
- }
- };
-
- Utils.restoreKeyFilter = function ()
- {
- if (window.key)
- {
- key.filter = function (event) {
-
- if (RL.data().useKeyboardShortcuts())
- {
- var
- element = event.target || event.srcElement,
- tagName = element ? element.tagName : ''
- ;
-
- tagName = tagName.toUpperCase();
- return !(tagName === 'INPUT' || tagName === 'SELECT' || tagName === 'TEXTAREA' ||
- (element && tagName === 'DIV' && 'editorHtmlArea' === element.className && element.contentEditable)
- );
- }
-
- return false;
- };
- }
- };
-
- Utils.detectDropdownVisibility = _.debounce(function () {
- Globals.dropdownVisibility(!!_.find(Globals.aBootstrapDropdowns, function (oItem) {
- return oItem.hasClass('open');
- }));
- }, 50);
-
- Utils.triggerAutocompleteInputChange = function (bDelay) {
-
- var fFunc = function () {
- $('.checkAutocomplete').trigger('change');
- };
-
- if (bDelay)
- {
- _.delay(fFunc, 100);
- }
- else
- {
- fFunc();
- }
- };
-
- module.exports = Utils;
-
-}(module));
-},{"../External/$doc.js":11,"../External/$window.js":13,"../External/NotificationClass.js":16,"../External/jquery.js":19,"../External/key.js":20,"../External/ko.js":21,"../External/underscore.js":24,"../External/window.js":25,"../Knoin/Knoin.js":26,"../Storages/LocalStorage.js":36,"./Enums.js":5,"./Globals.js":6}],10:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-'use strict';
-
-module.exports = require('./jquery.js')('');
-
-},{"./jquery.js":19}],11:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-'use strict';
-
-module.exports = require('./jquery.js')(window.document);
-
-},{"./jquery.js":19}],12:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-'use strict';
-
-module.exports = require('./jquery.js')('html');
-
-},{"./jquery.js":19}],13:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-'use strict';
-
-module.exports = require('./jquery.js')(window);
-
-},{"./jquery.js":19}],14:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-'use strict';
-
-module.exports = require('./window.js')['rainloopAppData'] || {};
-},{"./window.js":25}],15:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-'use strict';
-
-module.exports = JSON;
-},{}],16:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-'use strict';
-
-var
- window = require('./window.js')
-;
-
-module.exports = window.Notification && window.Notification.requestPermission ? window.Notification : null;
-},{"./window.js":25}],17:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-'use strict';
-
-module.exports = crossroads;
-},{}],18:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-'use strict';
-
-module.exports = hasher;
-},{}],19:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-'use strict';
-
-module.exports = $;
-},{}],20:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-'use strict';
-
-module.exports = key;
-},{}],21:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-(function (module) {
-
- 'use strict';
-
- var
- $ = require('./jquery.js'),
- _ = require('./underscore.js'),
- window = require('./window.js'),
- $window = require('./$window.js'),
- $doc = require('./$doc.js'),
-
- Globals = require('../Common/Globals.js'),
- Utils = require('../Common/Utils.js'),
-
- RL = require('../RL.js')
- ;
-
- ko.bindingHandlers.tooltip = {
- 'init': function (oElement, fValueAccessor) {
- if (!Globals.bMobileDevice)
- {
- var
- $oEl = $(oElement),
- sClass = $oEl.data('tooltip-class') || '',
- sPlacement = $oEl.data('tooltip-placement') || 'top'
- ;
-
- $oEl.tooltip({
- 'delay': {
- 'show': 500,
- 'hide': 100
- },
- 'html': true,
- 'container': 'body',
- 'placement': sPlacement,
- 'trigger': 'hover',
- 'title': function () {
- return $oEl.is('.disabled') || Globals.dropdownVisibility() ? '' : '' +
- Utils.i18n(ko.utils.unwrapObservable(fValueAccessor())) + '';
- }
- }).click(function () {
- $oEl.tooltip('hide');
- });
-
- Globals.tooltipTrigger.subscribe(function () {
- $oEl.tooltip('hide');
- });
- }
- }
- };
-
- ko.bindingHandlers.tooltip2 = {
- 'init': function (oElement, fValueAccessor) {
- var
- $oEl = $(oElement),
- sClass = $oEl.data('tooltip-class') || '',
- sPlacement = $oEl.data('tooltip-placement') || 'top'
- ;
-
- $oEl.tooltip({
- 'delay': {
- 'show': 500,
- 'hide': 100
- },
- 'html': true,
- 'container': 'body',
- 'placement': sPlacement,
- 'title': function () {
- return $oEl.is('.disabled') || Globals.dropdownVisibility() ? '' :
- '' + fValueAccessor()() + '';
- }
- }).click(function () {
- $oEl.tooltip('hide');
- });
-
- Globals.tooltipTrigger.subscribe(function () {
- $oEl.tooltip('hide');
- });
- }
- };
-
- ko.bindingHandlers.tooltip3 = {
- 'init': function (oElement) {
-
- var $oEl = $(oElement);
-
- $oEl.tooltip({
- 'container': 'body',
- 'trigger': 'hover manual',
- 'title': function () {
- return $oEl.data('tooltip3-data') || '';
- }
- });
-
- $doc.click(function () {
- $oEl.tooltip('hide');
- });
-
- Globals.tooltipTrigger.subscribe(function () {
- $oEl.tooltip('hide');
- });
- },
- 'update': function (oElement, fValueAccessor) {
- var sValue = ko.utils.unwrapObservable(fValueAccessor());
- if ('' === sValue)
- {
- $(oElement).data('tooltip3-data', '').tooltip('hide');
- }
- else
- {
- $(oElement).data('tooltip3-data', sValue).tooltip('show');
- }
- }
- };
-
- ko.bindingHandlers.registrateBootstrapDropdown = {
- 'init': function (oElement) {
- Globals.aBootstrapDropdowns.push($(oElement));
- }
- };
-
- ko.bindingHandlers.openDropdownTrigger = {
- 'update': function (oElement, fValueAccessor) {
- if (ko.utils.unwrapObservable(fValueAccessor()))
- {
- var $el = $(oElement);
- if (!$el.hasClass('open'))
- {
- $el.find('.dropdown-toggle').dropdown('toggle');
- Utils.detectDropdownVisibility();
- }
-
- fValueAccessor()(false);
- }
- }
- };
-
- ko.bindingHandlers.dropdownCloser = {
- 'init': function (oElement) {
- $(oElement).closest('.dropdown').on('click', '.e-item', function () {
- $(oElement).dropdown('toggle');
- });
- }
- };
-
- ko.bindingHandlers.popover = {
- 'init': function (oElement, fValueAccessor) {
- $(oElement).popover(ko.utils.unwrapObservable(fValueAccessor()));
- }
- };
-
- ko.bindingHandlers.csstext = {
- 'init': function (oElement, fValueAccessor) {
- if (oElement && oElement.styleSheet && !Utils.isUnd(oElement.styleSheet.cssText))
- {
- oElement.styleSheet.cssText = ko.utils.unwrapObservable(fValueAccessor());
- }
- else
- {
- $(oElement).text(ko.utils.unwrapObservable(fValueAccessor()));
- }
- },
- 'update': function (oElement, fValueAccessor) {
- if (oElement && oElement.styleSheet && !Utils.isUnd(oElement.styleSheet.cssText))
- {
- oElement.styleSheet.cssText = ko.utils.unwrapObservable(fValueAccessor());
- }
- else
- {
- $(oElement).text(ko.utils.unwrapObservable(fValueAccessor()));
- }
- }
- };
-
- ko.bindingHandlers.resizecrop = {
- 'init': function (oElement) {
- $(oElement).addClass('resizecrop').resizecrop({
- 'width': '100',
- 'height': '100',
- 'wrapperCSS': {
- 'border-radius': '10px'
- }
- });
- },
- 'update': function (oElement, fValueAccessor) {
- fValueAccessor()();
- $(oElement).resizecrop({
- 'width': '100',
- 'height': '100'
- });
- }
- };
-
- ko.bindingHandlers.onEnter = {
- 'init': function (oElement, fValueAccessor, fAllBindingsAccessor, oViewModel) {
- $(oElement).on('keypress', function (oEvent) {
- if (oEvent && 13 === window.parseInt(oEvent.keyCode, 10))
- {
- $(oElement).trigger('change');
- fValueAccessor().call(oViewModel);
- }
- });
- }
- };
-
- ko.bindingHandlers.onEsc = {
- 'init': function (oElement, fValueAccessor, fAllBindingsAccessor, oViewModel) {
- $(oElement).on('keypress', function (oEvent) {
- if (oEvent && 27 === window.parseInt(oEvent.keyCode, 10))
- {
- $(oElement).trigger('change');
- fValueAccessor().call(oViewModel);
- }
- });
- }
- };
-
- ko.bindingHandlers.clickOnTrue = {
- 'update': function (oElement, fValueAccessor) {
- if (ko.utils.unwrapObservable(fValueAccessor()))
- {
- $(oElement).click();
- }
- }
- };
-
- ko.bindingHandlers.modal = {
- 'init': function (oElement, fValueAccessor) {
-
- $(oElement).toggleClass('fade', !Globals.bMobileDevice).modal({
- 'keyboard': false,
- 'show': ko.utils.unwrapObservable(fValueAccessor())
- })
- .on('shown', function () {
- Utils.windowResize();
- })
- .find('.close').click(function () {
- fValueAccessor()(false);
- });
- },
- 'update': function (oElement, fValueAccessor) {
- $(oElement).modal(ko.utils.unwrapObservable(fValueAccessor()) ? 'show' : 'hide');
- }
- };
-
- ko.bindingHandlers.i18nInit = {
- 'init': function (oElement) {
- Utils.i18nToNode(oElement);
- }
- };
-
- ko.bindingHandlers.i18nUpdate = {
- 'update': function (oElement, fValueAccessor) {
- ko.utils.unwrapObservable(fValueAccessor());
- Utils.i18nToNode(oElement);
- }
- };
-
- ko.bindingHandlers.link = {
- 'update': function (oElement, fValueAccessor) {
- $(oElement).attr('href', ko.utils.unwrapObservable(fValueAccessor()));
- }
- };
-
- ko.bindingHandlers.title = {
- 'update': function (oElement, fValueAccessor) {
- $(oElement).attr('title', ko.utils.unwrapObservable(fValueAccessor()));
- }
- };
-
- ko.bindingHandlers.textF = {
- 'init': function (oElement, fValueAccessor) {
- $(oElement).text(ko.utils.unwrapObservable(fValueAccessor()));
- }
- };
-
- ko.bindingHandlers.initDom = {
- 'init': function (oElement, fValueAccessor) {
- fValueAccessor()(oElement);
- }
- };
-
- ko.bindingHandlers.initResizeTrigger = {
- 'init': function (oElement, fValueAccessor) {
- var aValues = ko.utils.unwrapObservable(fValueAccessor());
- $(oElement).css({
- 'height': aValues[1],
- 'min-height': aValues[1]
- });
- },
- 'update': function (oElement, fValueAccessor) {
- var
- aValues = ko.utils.unwrapObservable(fValueAccessor()),
- iValue = Utils.pInt(aValues[1]),
- iSize = 0,
- iOffset = $(oElement).offset().top
- ;
-
- if (0 < iOffset)
- {
- iOffset += Utils.pInt(aValues[2]);
- iSize = $window.height() - iOffset;
-
- if (iValue < iSize)
- {
- iValue = iSize;
- }
-
- $(oElement).css({
- 'height': iValue,
- 'min-height': iValue
- });
- }
- }
- };
-
- ko.bindingHandlers.appendDom = {
- 'update': function (oElement, fValueAccessor) {
- $(oElement).hide().empty().append(ko.utils.unwrapObservable(fValueAccessor())).show();
- }
- };
-
- ko.bindingHandlers.draggable = {
- 'init': function (oElement, fValueAccessor, fAllBindingsAccessor) {
-
- if (!Globals.bMobileDevice)
- {
- var
- iTriggerZone = 100,
- iScrollSpeed = 3,
- fAllValueFunc = fAllBindingsAccessor(),
- sDroppableSelector = fAllValueFunc && fAllValueFunc['droppableSelector'] ? fAllValueFunc['droppableSelector'] : '',
- oConf = {
- 'distance': 20,
- 'handle': '.dragHandle',
- 'cursorAt': {'top': 22, 'left': 3},
- 'refreshPositions': true,
- 'scroll': true
- }
- ;
-
- if (sDroppableSelector)
- {
- oConf['drag'] = function (oEvent) {
-
- $(sDroppableSelector).each(function () {
- var
- moveUp = null,
- moveDown = null,
- $this = $(this),
- oOffset = $this.offset(),
- bottomPos = oOffset.top + $this.height()
- ;
-
- window.clearInterval($this.data('timerScroll'));
- $this.data('timerScroll', false);
-
- if (oEvent.pageX >= oOffset.left && oEvent.pageX <= oOffset.left + $this.width())
- {
- if (oEvent.pageY >= bottomPos - iTriggerZone && oEvent.pageY <= bottomPos)
- {
- moveUp = function() {
- $this.scrollTop($this.scrollTop() + iScrollSpeed);
- Utils.windowResize();
- };
-
- $this.data('timerScroll', window.setInterval(moveUp, 10));
- moveUp();
- }
-
- if (oEvent.pageY >= oOffset.top && oEvent.pageY <= oOffset.top + iTriggerZone)
- {
- moveDown = function() {
- $this.scrollTop($this.scrollTop() - iScrollSpeed);
- Utils.windowResize();
- };
-
- $this.data('timerScroll', window.setInterval(moveDown, 10));
- moveDown();
- }
- }
- });
- };
-
- oConf['stop'] = function() {
- $(sDroppableSelector).each(function () {
- window.clearInterval($(this).data('timerScroll'));
- $(this).data('timerScroll', false);
- });
- };
- }
-
- oConf['helper'] = function (oEvent) {
- return fValueAccessor()(oEvent && oEvent.target ? ko.dataFor(oEvent.target) : null);
- };
-
- $(oElement).draggable(oConf).on('mousedown', function () {
- Utils.removeInFocus();
- });
- }
- }
- };
-
- ko.bindingHandlers.droppable = {
- 'init': function (oElement, fValueAccessor, fAllBindingsAccessor) {
-
- if (!Globals.bMobileDevice)
- {
- var
- fValueFunc = fValueAccessor(),
- fAllValueFunc = fAllBindingsAccessor(),
- fOverCallback = fAllValueFunc && fAllValueFunc['droppableOver'] ? fAllValueFunc['droppableOver'] : null,
- fOutCallback = fAllValueFunc && fAllValueFunc['droppableOut'] ? fAllValueFunc['droppableOut'] : null,
- oConf = {
- 'tolerance': 'pointer',
- 'hoverClass': 'droppableHover'
- }
- ;
-
- if (fValueFunc)
- {
- oConf['drop'] = function (oEvent, oUi) {
- fValueFunc(oEvent, oUi);
- };
-
- if (fOverCallback)
- {
- oConf['over'] = function (oEvent, oUi) {
- fOverCallback(oEvent, oUi);
- };
- }
-
- if (fOutCallback)
- {
- oConf['out'] = function (oEvent, oUi) {
- fOutCallback(oEvent, oUi);
- };
- }
-
- $(oElement).droppable(oConf);
- }
- }
- }
- };
-
- ko.bindingHandlers.nano = {
- 'init': function (oElement) {
- if (!Globals.bDisableNanoScroll)
- {
- $(oElement)
- .addClass('nano')
- .nanoScroller({
- 'iOSNativeScrolling': false,
- 'preventPageScrolling': true
- })
- ;
- }
- }
- };
-
- ko.bindingHandlers.saveTrigger = {
- 'init': function (oElement) {
-
- var $oEl = $(oElement);
-
- $oEl.data('save-trigger-type', $oEl.is('input[type=text],input[type=email],input[type=password],select,textarea') ? 'input' : 'custom');
-
- if ('custom' === $oEl.data('save-trigger-type'))
- {
- $oEl.append(
- ' '
- ).addClass('settings-saved-trigger');
- }
- else
- {
- $oEl.addClass('settings-saved-trigger-input');
- }
- },
- 'update': function (oElement, fValueAccessor) {
- var
- mValue = ko.utils.unwrapObservable(fValueAccessor()),
- $oEl = $(oElement)
- ;
-
- if ('custom' === $oEl.data('save-trigger-type'))
- {
- switch (mValue.toString())
- {
- case '1':
- $oEl
- .find('.animated,.error').hide().removeClass('visible')
- .end()
- .find('.success').show().addClass('visible')
- ;
- break;
- case '0':
- $oEl
- .find('.animated,.success').hide().removeClass('visible')
- .end()
- .find('.error').show().addClass('visible')
- ;
- break;
- case '-2':
- $oEl
- .find('.error,.success').hide().removeClass('visible')
- .end()
- .find('.animated').show().addClass('visible')
- ;
- break;
- default:
- $oEl
- .find('.animated').hide()
- .end()
- .find('.error,.success').removeClass('visible')
- ;
- break;
- }
- }
- else
- {
- switch (mValue.toString())
- {
- case '1':
- $oEl.addClass('success').removeClass('error');
- break;
- case '0':
- $oEl.addClass('error').removeClass('success');
- break;
- case '-2':
- // $oEl;
- break;
- default:
- $oEl.removeClass('error success');
- break;
- }
- }
- }
- };
-
- ko.bindingHandlers.emailsTags = {
- 'init': function(oElement, fValueAccessor) {
- var
- $oEl = $(oElement),
- fValue = fValueAccessor(),
- fFocusCallback = function (bValue) {
- if (fValue && fValue.focusTrigger)
- {
- fValue.focusTrigger(bValue);
- }
- }
- ;
-
- $oEl.inputosaurus({
- 'parseOnBlur': true,
- 'allowDragAndDrop': true,
- 'focusCallback': fFocusCallback,
- 'inputDelimiters': [',', ';'],
- 'autoCompleteSource': function (oData, fResponse) {
- RL().getAutocomplete(oData.term, function (aData) {
- fResponse(_.map(aData, function (oEmailItem) {
- return oEmailItem.toLine(false);
- }));
- });
- },
- 'parseHook': function (aInput) {
- return _.map(aInput, function (sInputValue) {
-
- var
- sValue = Utils.trim(sInputValue),
- oEmail = null
- ;
-
- if ('' !== sValue)
- {
- oEmail = new EmailModel();
- oEmail.mailsoParse(sValue);
- oEmail.clearDuplicateName();
- return [oEmail.toLine(false), oEmail];
- }
-
- return [sValue, null];
-
- });
- },
- 'change': _.bind(function (oEvent) {
- $oEl.data('EmailsTagsValue', oEvent.target.value);
- fValue(oEvent.target.value);
- }, this)
- });
- },
- 'update': function (oElement, fValueAccessor, fAllBindingsAccessor) {
-
- var
- $oEl = $(oElement),
- fAllValueFunc = fAllBindingsAccessor(),
- fEmailsTagsFilter = fAllValueFunc['emailsTagsFilter'] || null,
- sValue = ko.utils.unwrapObservable(fValueAccessor())
- ;
-
- if ($oEl.data('EmailsTagsValue') !== sValue)
- {
- $oEl.val(sValue);
- $oEl.data('EmailsTagsValue', sValue);
- $oEl.inputosaurus('refresh');
- }
-
- if (fEmailsTagsFilter && ko.utils.unwrapObservable(fEmailsTagsFilter))
- {
- $oEl.inputosaurus('focus');
- }
- }
- };
-
- ko.bindingHandlers.contactTags = {
- 'init': function(oElement, fValueAccessor) {
- var
- $oEl = $(oElement),
- fValue = fValueAccessor(),
- fFocusCallback = function (bValue) {
- if (fValue && fValue.focusTrigger)
- {
- fValue.focusTrigger(bValue);
- }
- }
- ;
-
- $oEl.inputosaurus({
- 'parseOnBlur': true,
- 'allowDragAndDrop': false,
- 'focusCallback': fFocusCallback,
- 'inputDelimiters': [',', ';'],
- 'outputDelimiter': ',',
- 'autoCompleteSource': function (oData, fResponse) {
- RL().getContactTagsAutocomplete(oData.term, function (aData) {
- fResponse(_.map(aData, function (oTagItem) {
- return oTagItem.toLine(false);
- }));
- });
- },
- 'parseHook': function (aInput) {
- return _.map(aInput, function (sInputValue) {
-
- var
- sValue = Utils.trim(sInputValue),
- oTag = null
- ;
-
- if ('' !== sValue)
- {
- oTag = new ContactTagModel();
- oTag.name(sValue);
- return [oTag.toLine(false), oTag];
- }
-
- return [sValue, null];
-
- });
- },
- 'change': _.bind(function (oEvent) {
- $oEl.data('ContactTagsValue', oEvent.target.value);
- fValue(oEvent.target.value);
- }, this)
- });
- },
- 'update': function (oElement, fValueAccessor, fAllBindingsAccessor) {
-
- var
- $oEl = $(oElement),
- fAllValueFunc = fAllBindingsAccessor(),
- fContactTagsFilter = fAllValueFunc['contactTagsFilter'] || null,
- sValue = ko.utils.unwrapObservable(fValueAccessor())
- ;
-
- if ($oEl.data('ContactTagsValue') !== sValue)
- {
- $oEl.val(sValue);
- $oEl.data('ContactTagsValue', sValue);
- $oEl.inputosaurus('refresh');
- }
-
- if (fContactTagsFilter && ko.utils.unwrapObservable(fContactTagsFilter))
- {
- $oEl.inputosaurus('focus');
- }
- }
- };
-
- ko.bindingHandlers.command = {
- 'init': function (oElement, fValueAccessor, fAllBindingsAccessor, oViewModel) {
- var
- jqElement = $(oElement),
- oCommand = fValueAccessor()
- ;
-
- if (!oCommand || !oCommand.enabled || !oCommand.canExecute)
- {
- throw new Error('You are not using command function');
- }
-
- jqElement.addClass('command');
- ko.bindingHandlers[jqElement.is('form') ? 'submit' : 'click'].init.apply(oViewModel, arguments);
- },
-
- 'update': function (oElement, fValueAccessor) {
-
- var
- bResult = true,
- jqElement = $(oElement),
- oCommand = fValueAccessor()
- ;
-
- bResult = oCommand.enabled();
- jqElement.toggleClass('command-not-enabled', !bResult);
-
- if (bResult)
- {
- bResult = oCommand.canExecute();
- jqElement.toggleClass('command-can-not-be-execute', !bResult);
- }
-
- jqElement.toggleClass('command-disabled disable disabled', !bResult).toggleClass('no-disabled', !!bResult);
-
- if (jqElement.is('input') || jqElement.is('button'))
- {
- jqElement.prop('disabled', !bResult);
- }
- }
- };
-
- ko.extenders.trimmer = function (oTarget)
- {
- var oResult = ko.computed({
- 'read': oTarget,
- 'write': function (sNewValue) {
- oTarget(Utils.trim(sNewValue.toString()));
- },
- 'owner': this
- });
-
- oResult(oTarget());
- return oResult;
- };
-
- ko.extenders.posInterer = function (oTarget, iDefault)
- {
- var oResult = ko.computed({
- 'read': oTarget,
- 'write': function (sNewValue) {
- var iNew = Utils.pInt(sNewValue.toString(), iDefault);
- if (0 >= iNew)
- {
- iNew = iDefault;
- }
-
- if (iNew === oTarget() && '' + iNew !== '' + sNewValue)
- {
- oTarget(iNew + 1);
- }
-
- oTarget(iNew);
- }
- });
-
- oResult(oTarget());
- return oResult;
- };
-
- ko.extenders.reversible = function (oTarget)
- {
- var mValue = oTarget();
-
- oTarget.commit = function ()
- {
- mValue = oTarget();
- };
-
- oTarget.reverse = function ()
- {
- oTarget(mValue);
- };
-
- oTarget.commitedValue = function ()
- {
- return mValue;
- };
-
- return oTarget;
- };
-
- ko.extenders.toggleSubscribe = function (oTarget, oOptions)
- {
- oTarget.subscribe(oOptions[1], oOptions[0], 'beforeChange');
- oTarget.subscribe(oOptions[2], oOptions[0]);
-
- return oTarget;
- };
-
- ko.extenders.falseTimeout = function (oTarget, iOption)
- {
- oTarget.iTimeout = 0;
- oTarget.subscribe(function (bValue) {
- if (bValue)
- {
- window.clearTimeout(oTarget.iTimeout);
- oTarget.iTimeout = window.setTimeout(function () {
- oTarget(false);
- oTarget.iTimeout = 0;
- }, Utils.pInt(iOption));
- }
- });
-
- return oTarget;
- };
-
- ko.observable.fn.validateNone = function ()
- {
- this.hasError = ko.observable(false);
- return this;
- };
-
- ko.observable.fn.validateEmail = function ()
- {
- this.hasError = ko.observable(false);
-
- this.subscribe(function (sValue) {
- sValue = Utils.trim(sValue);
- this.hasError('' !== sValue && !(/^[^@\s]+@[^@\s]+$/.test(sValue)));
- }, this);
-
- this.valueHasMutated();
- return this;
- };
-
- ko.observable.fn.validateSimpleEmail = function ()
- {
- this.hasError = ko.observable(false);
-
- this.subscribe(function (sValue) {
- sValue = Utils.trim(sValue);
- this.hasError('' !== sValue && !(/^.+@.+$/.test(sValue)));
- }, this);
-
- this.valueHasMutated();
- return this;
- };
-
- ko.observable.fn.validateFunc = function (fFunc)
- {
- this.hasFuncError = ko.observable(false);
-
- if (Utils.isFunc(fFunc))
- {
- this.subscribe(function (sValue) {
- this.hasFuncError(!fFunc(sValue));
- }, this);
-
- this.valueHasMutated();
- }
-
- return this;
- };
-
- module.exports = ko;
-
-}(module));
-},{"../Common/Globals.js":6,"../Common/Utils.js":9,"../RL.js":32,"./$doc.js":11,"./$window.js":13,"./jquery.js":19,"./underscore.js":24,"./window.js":25}],22:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-'use strict';
-
-module.exports = moment;
-},{}],23:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-'use strict';
-
-module.exports = ssm;
-},{}],24:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-'use strict';
-
-module.exports = window;
-},{}],25:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-'use strict';
-
-module.exports = window;
-
-},{}],26:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-(function (module) {
-
- 'use strict';
-
- var
- $ = require('../External/jquery.js'),
- _ = require('../External/underscore.js'),
- ko = require('../External/ko.js'),
- hasher = require('../External/hasher.js'),
- crossroads = require('../External/crossroads.js'),
- $html = require('../External/$html.js'),
- Globals = require('../Common/Globals.js'),
- Enums = require('../Common/Enums.js'),
- Plugins = require('../Common/Plugins.js'),
- Utils = require('../Common/Utils.js'),
- KnoinAbstractViewModel = require('../Knoin/KnoinAbstractViewModel.js')
- ;
-
- /**
- * @constructor
- */
- function Knoin()
- {
- this.sDefaultScreenName = '';
- this.oScreens = {};
- this.oBoot = null;
- this.oCurrentScreen = null;
- }
-
- /**
- * @param {Object} thisObject
- */
- Knoin.constructorEnd = function (thisObject)
- {
- if (Utils.isFunc(thisObject['__constructor_end']))
- {
- thisObject['__constructor_end'].call(thisObject);
- }
- };
-
- Knoin.prototype.sDefaultScreenName = '';
- Knoin.prototype.oScreens = {};
- Knoin.prototype.oBoot = null;
- Knoin.prototype.oCurrentScreen = null;
-
- Knoin.prototype.hideLoading = function ()
- {
- $('#rl-loading').hide();
- };
-
- Knoin.prototype.rl = function ()
- {
- return this.oBoot;
- };
-
- Knoin.prototype.remote = function ()
- {
- return this.oRemote;
- };
-
- /**
- * @param {Object} thisObject
- */
- Knoin.prototype.constructorEnd = function (thisObject)
- {
- if (Utils.isFunc(thisObject['__constructor_end']))
- {
- thisObject['__constructor_end'].call(thisObject);
- }
- };
-
- /**
- * @param {string} sName
- * @param {Function} ViewModelClass
- * @param {Function=} AbstractViewModel = KnoinAbstractViewModel
- */
- Knoin.prototype.extendAsViewModel = function (sName, ViewModelClass, AbstractViewModel)
- {
- if (ViewModelClass)
- {
- if (!AbstractViewModel)
- {
- AbstractViewModel = KnoinAbstractViewModel;
- }
-
- ViewModelClass.__name = sName;
- Plugins.regViewModelHook(sName, ViewModelClass);
- _.extend(ViewModelClass.prototype, AbstractViewModel.prototype);
- }
- };
-
- /**
- * @param {Function} SettingsViewModelClass
- * @param {string} sLabelName
- * @param {string} sTemplate
- * @param {string} sRoute
- * @param {boolean=} bDefault
- */
- Knoin.prototype.addSettingsViewModel = function (SettingsViewModelClass, sTemplate, sLabelName, sRoute, bDefault)
- {
- SettingsViewModelClass.__rlSettingsData = {
- 'Label': sLabelName,
- 'Template': sTemplate,
- 'Route': sRoute,
- 'IsDefault': !!bDefault
- };
-
- Globals.aViewModels['settings'].push(SettingsViewModelClass);
- };
-
- /**
- * @param {Function} SettingsViewModelClass
- */
- Knoin.prototype.removeSettingsViewModel = function (SettingsViewModelClass)
- {
- Globals.aViewModels['settings-removed'].push(SettingsViewModelClass);
- };
-
- /**
- * @param {Function} SettingsViewModelClass
- */
- Knoin.prototype.disableSettingsViewModel = function (SettingsViewModelClass)
- {
- Globals.aViewModels['settings-disabled'].push(SettingsViewModelClass);
- };
-
- Knoin.prototype.routeOff = function ()
- {
- hasher.changed.active = false;
- };
-
- Knoin.prototype.routeOn = function ()
- {
- hasher.changed.active = true;
- };
-
- /**
- * @param {string} sScreenName
- * @return {?Object}
- */
- Knoin.prototype.screen = function (sScreenName)
- {
- return ('' !== sScreenName && !Utils.isUnd(this.oScreens[sScreenName])) ? this.oScreens[sScreenName] : null;
- };
-
- /**
- * @param {Function} ViewModelClass
- * @param {Object=} oScreen
- */
- Knoin.prototype.buildViewModel = function (ViewModelClass, oScreen)
- {
- if (ViewModelClass && !ViewModelClass.__builded)
- {
- var
- oViewModel = new ViewModelClass(oScreen),
- sPosition = oViewModel.viewModelPosition(),
- oViewModelPlace = $('#rl-content #rl-' + sPosition.toLowerCase()),
- oViewModelDom = null
- ;
-
- ViewModelClass.__builded = true;
- ViewModelClass.__vm = oViewModel;
- oViewModel.data = RL.data(); // TODO cjs
-
- oViewModel.viewModelName = ViewModelClass.__name;
-
- if (oViewModelPlace && 1 === oViewModelPlace.length)
- {
- oViewModelDom = $('').addClass('rl-view-model').addClass('RL-' + oViewModel.viewModelTemplate()).hide();
- oViewModelDom.appendTo(oViewModelPlace);
-
- oViewModel.viewModelDom = oViewModelDom;
- ViewModelClass.__dom = oViewModelDom;
-
- if ('Popups' === sPosition)
- {
- oViewModel.cancelCommand = oViewModel.closeCommand = Utils.createCommand(oViewModel, function () {
- kn.hideScreenPopup(ViewModelClass); // TODO cjs
- });
-
- oViewModel.modalVisibility.subscribe(function (bValue) {
-
- var self = this;
- if (bValue)
- {
- this.viewModelDom.show();
- this.storeAndSetKeyScope();
-
- RL.popupVisibilityNames.push(this.viewModelName); // TODO cjs
- oViewModel.viewModelDom.css('z-index', 3000 + RL.popupVisibilityNames().length + 10); // TODO cjs
-
- Utils.delegateRun(this, 'onFocus', [], 500);
- }
- else
- {
- Utils.delegateRun(this, 'onHide');
- this.restoreKeyScope();
-
- RL.popupVisibilityNames.remove(this.viewModelName); // TODO cjs
- oViewModel.viewModelDom.css('z-index', 2000);
-
- Globals.tooltipTrigger(!Globals.tooltipTrigger());
-
- _.delay(function () {
- self.viewModelDom.hide();
- }, 300);
- }
-
- }, oViewModel);
- }
-
- Plugins.runHook('view-model-pre-build', [ViewModelClass.__name, oViewModel, oViewModelDom]); // TODO cjs
-
- ko.applyBindingAccessorsToNode(oViewModelDom[0], {
- 'i18nInit': true,
- 'template': function () { return {'name': oViewModel.viewModelTemplate()};}
- }, oViewModel);
-
- Utils.delegateRun(oViewModel, 'onBuild', [oViewModelDom]);
- if (oViewModel && 'Popups' === sPosition)
- {
- oViewModel.registerPopupKeyDown();
- }
-
- Plugins.runHook('view-model-post-build', [ViewModelClass.__name, oViewModel, oViewModelDom]); // TODO cjs
- }
- else
- {
- Utils.log('Cannot find view model position: ' + sPosition);
- }
- }
-
- return ViewModelClass ? ViewModelClass.__vm : null;
- };
-
- /**
- * @param {Object} oViewModel
- * @param {Object} oViewModelDom
- */
- Knoin.prototype.applyExternal = function (oViewModel, oViewModelDom)
- {
- if (oViewModel && oViewModelDom)
- {
- ko.applyBindings(oViewModel, oViewModelDom);
- }
- };
-
- /**
- * @param {Function} ViewModelClassToHide
- */
- Knoin.prototype.hideScreenPopup = function (ViewModelClassToHide)
- {
- if (ViewModelClassToHide && ViewModelClassToHide.__vm && ViewModelClassToHide.__dom)
- {
- ViewModelClassToHide.__vm.modalVisibility(false);
- Plugins.runHook('view-model-on-hide', [ViewModelClassToHide.__name, ViewModelClassToHide.__vm]); // TODO cjs
- }
- };
-
- /**
- * @param {Function} ViewModelClassToShow
- * @param {Array=} aParameters
- */
- Knoin.prototype.showScreenPopup = function (ViewModelClassToShow, aParameters)
- {
- if (ViewModelClassToShow)
- {
- this.buildViewModel(ViewModelClassToShow);
-
- if (ViewModelClassToShow.__vm && ViewModelClassToShow.__dom)
- {
- ViewModelClassToShow.__vm.modalVisibility(true);
- Utils.delegateRun(ViewModelClassToShow.__vm, 'onShow', aParameters || []);
- Plugins.runHook('view-model-on-show', [ViewModelClassToShow.__name, ViewModelClassToShow.__vm, aParameters || []]); // TODO cjs
- }
- }
- };
-
- /**
- * @param {Function} ViewModelClassToShow
- * @return {boolean}
- */
- Knoin.prototype.isPopupVisible = function (ViewModelClassToShow)
- {
- return ViewModelClassToShow && ViewModelClassToShow.__vm ? ViewModelClassToShow.__vm.modalVisibility() : false;
- };
-
- /**
- * @param {string} sScreenName
- * @param {string} sSubPart
- */
- Knoin.prototype.screenOnRoute = function (sScreenName, sSubPart)
- {
- var
- self = this,
- oScreen = null,
- oCross = null
- ;
-
- if ('' === Utils.pString(sScreenName))
- {
- sScreenName = this.sDefaultScreenName;
- }
-
- if ('' !== sScreenName)
- {
- oScreen = this.screen(sScreenName);
- if (!oScreen)
- {
- oScreen = this.screen(this.sDefaultScreenName);
- if (oScreen)
- {
- sSubPart = sScreenName + '/' + sSubPart;
- sScreenName = this.sDefaultScreenName;
- }
- }
-
- if (oScreen && oScreen.__started)
- {
- if (!oScreen.__builded)
- {
- oScreen.__builded = true;
-
- if (Utils.isNonEmptyArray(oScreen.viewModels()))
- {
- _.each(oScreen.viewModels(), function (ViewModelClass) {
- this.buildViewModel(ViewModelClass, oScreen);
- }, this);
- }
-
- Utils.delegateRun(oScreen, 'onBuild');
- }
-
- _.defer(function () {
-
- // hide screen
- if (self.oCurrentScreen)
- {
- Utils.delegateRun(self.oCurrentScreen, 'onHide');
-
- if (Utils.isNonEmptyArray(self.oCurrentScreen.viewModels()))
- {
- _.each(self.oCurrentScreen.viewModels(), function (ViewModelClass) {
-
- if (ViewModelClass.__vm && ViewModelClass.__dom &&
- 'Popups' !== ViewModelClass.__vm.viewModelPosition())
- {
- ViewModelClass.__dom.hide();
- ViewModelClass.__vm.viewModelVisibility(false);
- Utils.delegateRun(ViewModelClass.__vm, 'onHide');
- }
-
- });
- }
- }
- // --
-
- self.oCurrentScreen = oScreen;
-
- // show screen
- if (self.oCurrentScreen)
- {
- Utils.delegateRun(self.oCurrentScreen, 'onShow');
-
- Plugins.runHook('screen-on-show', [self.oCurrentScreen.screenName(), self.oCurrentScreen]); // TODO cjs
-
- if (Utils.isNonEmptyArray(self.oCurrentScreen.viewModels()))
- {
- _.each(self.oCurrentScreen.viewModels(), function (ViewModelClass) {
-
- if (ViewModelClass.__vm && ViewModelClass.__dom &&
- 'Popups' !== ViewModelClass.__vm.viewModelPosition())
- {
- ViewModelClass.__dom.show();
- ViewModelClass.__vm.viewModelVisibility(true);
- Utils.delegateRun(ViewModelClass.__vm, 'onShow');
- Utils.delegateRun(ViewModelClass.__vm, 'onFocus', [], 200);
-
- Plugins.runHook('view-model-on-show', [ViewModelClass.__name, ViewModelClass.__vm]); // TODO cjs
- }
-
- }, self);
- }
- }
- // --
-
- oCross = oScreen.__cross();
- if (oCross)
- {
- oCross.parse(sSubPart);
- }
- });
- }
- }
- };
-
- /**
- * @param {Array} aScreensClasses
- */
- Knoin.prototype.startScreens = function (aScreensClasses)
- {
- $('#rl-content').css({
- 'visibility': 'hidden'
- });
-
- _.each(aScreensClasses, function (CScreen) {
-
- var
- oScreen = new CScreen(),
- sScreenName = oScreen ? oScreen.screenName() : ''
- ;
-
- if (oScreen && '' !== sScreenName)
- {
- if ('' === this.sDefaultScreenName)
- {
- this.sDefaultScreenName = sScreenName;
- }
-
- this.oScreens[sScreenName] = oScreen;
- }
-
- }, this);
-
-
- _.each(this.oScreens, function (oScreen) {
- if (oScreen && !oScreen.__started && oScreen.__start)
- {
- oScreen.__started = true;
- oScreen.__start();
-
- Plugins.runHook('screen-pre-start', [oScreen.screenName(), oScreen]); // TODO cjs
- Utils.delegateRun(oScreen, 'onStart');
- Plugins.runHook('screen-post-start', [oScreen.screenName(), oScreen]); // TODO cjs
- }
- }, this);
-
- var oCross = crossroads.create();
- oCross.addRoute(/^([a-zA-Z0-9\-]*)\/?(.*)$/, _.bind(this.screenOnRoute, this));
-
- hasher.initialized.add(oCross.parse, oCross);
- hasher.changed.add(oCross.parse, oCross);
- hasher.init();
-
- $('#rl-content').css({
- 'visibility': 'visible'
- });
-
- _.delay(function () {
- $html.removeClass('rl-started-trigger').addClass('rl-started');
- }, 50);
- };
-
- /**
- * @param {string} sHash
- * @param {boolean=} bSilence = false
- * @param {boolean=} bReplace = false
- */
- Knoin.prototype.setHash = function (sHash, bSilence, bReplace)
- {
- sHash = '#' === sHash.substr(0, 1) ? sHash.substr(1) : sHash;
- sHash = '/' === sHash.substr(0, 1) ? sHash.substr(1) : sHash;
-
- bReplace = Utils.isUnd(bReplace) ? false : !!bReplace;
-
- if (Utils.isUnd(bSilence) ? false : !!bSilence)
- {
- hasher.changed.active = false;
- hasher[bReplace ? 'replaceHash' : 'setHash'](sHash);
- hasher.changed.active = true;
- }
- else
- {
- hasher.changed.active = true;
- hasher[bReplace ? 'replaceHash' : 'setHash'](sHash);
- hasher.setHash(sHash);
- }
- };
-
- /**
- * @return {Knoin}
- */
- Knoin.prototype.bootstart = function (RL, Remote)
- {
- this.oBoot = RL;
- this.oRemote = Remote;
-
- var
- window = require('../External/window.js'),
- $window = require('../External/$window.js'),
- $html = require('../External/$html.js'),
- Plugins = require('../Common/Plugins.js'),
- EmailModel = require('../Models/EmailModel.js')
- ;
-
- $html.addClass(Globals.bMobileDevice ? 'mobile' : 'no-mobile');
-
- $window.keydown(Utils.killCtrlAandS).keyup(Utils.killCtrlAandS);
- $window.unload(function () {
- Globals.bUnload = true;
- });
-
- $html.on('click.dropdown.data-api', function () {
- Utils.detectDropdownVisibility();
- });
-
- // export
- window['rl'] = window['rl'] || {};
- window['rl']['addHook'] = Plugins.addHook;
- window['rl']['settingsGet'] = Plugins.mainSettingsGet;
- window['rl']['remoteRequest'] = Plugins.remoteRequest;
- window['rl']['pluginSettingsGet'] = Plugins.settingsGet;
- window['rl']['addSettingsViewModel'] = _.bind(this.addSettingsViewModel, this);
- window['rl']['createCommand'] = Utils.createCommand;
-
- window['rl']['EmailModel'] = EmailModel;
- window['rl']['Enums'] = Enums;
-
- window['__RLBOOT'] = function (fCall) {
-
- // boot
- $(function () {
-
- if (window['rainloopTEMPLATES'] && window['rainloopTEMPLATES'][0])
- {
- $('#rl-templates').html(window['rainloopTEMPLATES'][0]);
-
- _.delay(function () {
-
- RL.bootstart();
-
- $html.removeClass('no-js rl-booted-trigger').addClass('rl-booted');
- }, 50);
- }
- else
- {
- fCall(false);
- }
-
- window['__RLBOOT'] = null;
- });
- };
- };
-
- module.exports = new Knoin();
-
-}(module));
-},{"../Common/Enums.js":5,"../Common/Globals.js":6,"../Common/Plugins.js":8,"../Common/Utils.js":9,"../External/$html.js":12,"../External/$window.js":13,"../External/crossroads.js":17,"../External/hasher.js":18,"../External/jquery.js":19,"../External/ko.js":21,"../External/underscore.js":24,"../External/window.js":25,"../Knoin/KnoinAbstractViewModel.js":28,"../Models/EmailModel.js":30}],27:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-(function (module) {
-
- 'use strict';
-
- /**
- * @constructor
- */
- function KnoinAbstractBoot()
- {
-
- }
-
- KnoinAbstractBoot.prototype.bootstart = function ()
- {
-
- };
-
- module.exports = KnoinAbstractBoot;
-
-}(module));
-},{}],28:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-(function (module) {
-
- 'use strict';
-
- var
- ko = require('../External/ko.js'),
- $window = require('../External/$window.js'),
- Utils = require('../Common/Utils.js'),
- Enums = require('../Common/Enums.js')
- ;
-
- /**
- * @param {string=} sPosition = ''
- * @param {string=} sTemplate = ''
- * @constructor
- */
- function KnoinAbstractViewModel(sPosition, sTemplate)
- {
- this.bDisabeCloseOnEsc = false;
- this.sPosition = Utils.pString(sPosition);
- this.sTemplate = Utils.pString(sTemplate);
-
- this.sDefaultKeyScope = Enums.KeyState.None;
- this.sCurrentKeyScope = this.sDefaultKeyScope;
-
- this.viewModelName = '';
- this.viewModelVisibility = ko.observable(false);
- this.modalVisibility = ko.observable(false).extend({'rateLimit': 0});
-
- this.viewModelDom = null;
- }
-
- /**
- * @type {string}
- */
- KnoinAbstractViewModel.prototype.sPosition = '';
-
- /**
- * @type {string}
- */
- KnoinAbstractViewModel.prototype.sTemplate = '';
-
- /**
- * @type {string}
- */
- KnoinAbstractViewModel.prototype.viewModelName = '';
-
- /**
- * @type {?}
- */
- KnoinAbstractViewModel.prototype.viewModelDom = null;
-
- /**
- * @return {string}
- */
- KnoinAbstractViewModel.prototype.viewModelTemplate = function ()
- {
- return this.sTemplate;
- };
-
- /**
- * @return {string}
- */
- KnoinAbstractViewModel.prototype.viewModelPosition = function ()
- {
- return this.sPosition;
- };
-
- KnoinAbstractViewModel.prototype.cancelCommand = KnoinAbstractViewModel.prototype.closeCommand = function ()
- {
- };
-
- KnoinAbstractViewModel.prototype.storeAndSetKeyScope = function ()
- {
- this.sCurrentKeyScope = RL.data().keyScope(); // TODO cjs
- RL.data().keyScope(this.sDefaultKeyScope); // TODO cjs
- };
-
- KnoinAbstractViewModel.prototype.restoreKeyScope = function ()
- {
- RL.data().keyScope(this.sCurrentKeyScope); // TODO cjs
- };
-
- KnoinAbstractViewModel.prototype.registerPopupKeyDown = function ()
- {
- var self = this;
- $window.on('keydown', function (oEvent) {
- if (oEvent && self.modalVisibility && self.modalVisibility())
- {
- if (!this.bDisabeCloseOnEsc && Enums.EventKeyCode.Esc === oEvent.keyCode)
- {
- Utils.delegateRun(self, 'cancelCommand');
- return false;
- }
- else if (Enums.EventKeyCode.Backspace === oEvent.keyCode && !Utils.inFocus())
- {
- return false;
- }
- }
-
- return true;
- });
- };
-
- module.exports = KnoinAbstractViewModel;
-
-}(module));
-},{"../Common/Enums.js":5,"../Common/Utils.js":9,"../External/$window.js":13,"../External/ko.js":21}],29:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-(function (module) {
-
- 'use strict';
-
- var
- window = require('../External/window.js'),
- Globals = require('../Common/Globals.js'),
- Utils = require('../Common/Utils.js'),
- LinkBuilder = require('../Common/LinkBuilder.js')
- ;
-
- /**
- * @constructor
- */
- function AttachmentModel()
- {
- this.mimeType = '';
- this.fileName = '';
- this.estimatedSize = 0;
- this.friendlySize = '';
- this.isInline = false;
- this.isLinked = false;
- this.cid = '';
- this.cidWithOutTags = '';
- this.contentLocation = '';
- this.download = '';
- this.folder = '';
- this.uid = '';
- this.mimeIndex = '';
- }
-
- /**
- * @static
- * @param {AjaxJsonAttachment} oJsonAttachment
- * @return {?AttachmentModel}
- */
- AttachmentModel.newInstanceFromJson = function (oJsonAttachment)
- {
- var oAttachmentModel = new AttachmentModel();
- return oAttachmentModel.initByJson(oJsonAttachment) ? oAttachmentModel : null;
- };
-
- AttachmentModel.prototype.mimeType = '';
- AttachmentModel.prototype.fileName = '';
- AttachmentModel.prototype.estimatedSize = 0;
- AttachmentModel.prototype.friendlySize = '';
- AttachmentModel.prototype.isInline = false;
- AttachmentModel.prototype.isLinked = false;
- AttachmentModel.prototype.cid = '';
- AttachmentModel.prototype.cidWithOutTags = '';
- AttachmentModel.prototype.contentLocation = '';
- AttachmentModel.prototype.download = '';
- AttachmentModel.prototype.folder = '';
- AttachmentModel.prototype.uid = '';
- AttachmentModel.prototype.mimeIndex = '';
-
- /**
- * @param {AjaxJsonAttachment} oJsonAttachment
- */
- AttachmentModel.prototype.initByJson = function (oJsonAttachment)
- {
- var bResult = false;
- if (oJsonAttachment && 'Object/Attachment' === oJsonAttachment['@Object'])
- {
- this.mimeType = (oJsonAttachment.MimeType || '').toLowerCase();
- this.fileName = oJsonAttachment.FileName;
- this.estimatedSize = Utils.pInt(oJsonAttachment.EstimatedSize);
- this.isInline = !!oJsonAttachment.IsInline;
- this.isLinked = !!oJsonAttachment.IsLinked;
- this.cid = oJsonAttachment.CID;
- this.contentLocation = oJsonAttachment.ContentLocation;
- this.download = oJsonAttachment.Download;
-
- this.folder = oJsonAttachment.Folder;
- this.uid = oJsonAttachment.Uid;
- this.mimeIndex = oJsonAttachment.MimeIndex;
-
- this.friendlySize = Utils.friendlySize(this.estimatedSize);
- this.cidWithOutTags = this.cid.replace(/^<+/, '').replace(/>+$/, '');
-
- bResult = true;
- }
-
- return bResult;
- };
-
- /**
- * @return {boolean}
- */
- AttachmentModel.prototype.isImage = function ()
- {
- return -1 < Utils.inArray(this.mimeType.toLowerCase(),
- ['image/png', 'image/jpg', 'image/jpeg', 'image/gif']
- );
- };
-
- /**
- * @return {boolean}
- */
- AttachmentModel.prototype.isText = function ()
- {
- return 'text/' === this.mimeType.substr(0, 5) &&
- -1 === Utils.inArray(this.mimeType, ['text/html']);
- };
-
- /**
- * @return {boolean}
- */
- AttachmentModel.prototype.isPdf = function ()
- {
- return Globals.bAllowPdfPreview && 'application/pdf' === this.mimeType;
- };
-
- /**
- * @return {string}
- */
- AttachmentModel.prototype.linkDownload = function ()
- {
- return LinkBuilder.attachmentDownload(this.download); // TODO cjs
- };
-
- /**
- * @return {string}
- */
- AttachmentModel.prototype.linkPreview = function ()
- {
- return LinkBuilder.attachmentPreview(this.download); // TODO cjs
- };
-
- /**
- * @return {string}
- */
- AttachmentModel.prototype.linkPreviewAsPlain = function ()
- {
- return LinkBuilder.attachmentPreviewAsPlain(this.download);
- };
-
- /**
- * @return {string}
- */
- AttachmentModel.prototype.generateTransferDownloadUrl = function ()
- {
- var sLink = this.linkDownload();
- if ('http' !== sLink.substr(0, 4))
- {
- sLink = window.location.protocol + '//' + window.location.host + window.location.pathname + sLink;
- }
-
- return this.mimeType + ':' + this.fileName + ':' + sLink;
- };
-
- /**
- * @param {AttachmentModel} oAttachment
- * @param {*} oEvent
- * @return {boolean}
- */
- AttachmentModel.prototype.eventDragStart = function (oAttachment, oEvent)
- {
- var oLocalEvent = oEvent.originalEvent || oEvent;
- if (oAttachment && oLocalEvent && oLocalEvent.dataTransfer && oLocalEvent.dataTransfer.setData)
- {
- oLocalEvent.dataTransfer.setData('DownloadURL', this.generateTransferDownloadUrl());
- }
-
- return true;
- };
-
- AttachmentModel.prototype.iconClass = function ()
- {
- var
- aParts = this.mimeType.toLocaleString().split('/'),
- sClass = 'icon-file'
- ;
-
- if (aParts && aParts[1])
- {
- if ('image' === aParts[0])
- {
- sClass = 'icon-file-image';
- }
- else if ('text' === aParts[0])
- {
- sClass = 'icon-file-text';
- }
- else if ('audio' === aParts[0])
- {
- sClass = 'icon-file-music';
- }
- else if ('video' === aParts[0])
- {
- sClass = 'icon-file-movie';
- }
- else if (-1 < Utils.inArray(aParts[1],
- ['zip', '7z', 'tar', 'rar', 'gzip', 'bzip', 'bzip2', 'x-zip', 'x-7z', 'x-rar', 'x-tar', 'x-gzip', 'x-bzip', 'x-bzip2', 'x-zip-compressed', 'x-7z-compressed', 'x-rar-compressed']))
- {
- sClass = 'icon-file-zip';
- }
- // else if (-1 < Utils.inArray(aParts[1],
- // ['pdf', 'x-pdf']))
- // {
- // sClass = 'icon-file-pdf';
- // }
- // else if (-1 < Utils.inArray(aParts[1], [
- // 'exe', 'x-exe', 'x-winexe', 'bat'
- // ]))
- // {
- // sClass = 'icon-console';
- // }
- else if (-1 < Utils.inArray(aParts[1], [
- 'rtf', 'msword', 'vnd.msword', 'vnd.openxmlformats-officedocument.wordprocessingml.document',
- 'vnd.openxmlformats-officedocument.wordprocessingml.template',
- 'vnd.ms-word.document.macroEnabled.12',
- 'vnd.ms-word.template.macroEnabled.12'
- ]))
- {
- sClass = 'icon-file-text';
- }
- else if (-1 < Utils.inArray(aParts[1], [
- 'excel', 'ms-excel', 'vnd.ms-excel',
- 'vnd.openxmlformats-officedocument.spreadsheetml.sheet',
- 'vnd.openxmlformats-officedocument.spreadsheetml.template',
- 'vnd.ms-excel.sheet.macroEnabled.12',
- 'vnd.ms-excel.template.macroEnabled.12',
- 'vnd.ms-excel.addin.macroEnabled.12',
- 'vnd.ms-excel.sheet.binary.macroEnabled.12'
- ]))
- {
- sClass = 'icon-file-excel';
- }
- else if (-1 < Utils.inArray(aParts[1], [
- 'powerpoint', 'ms-powerpoint', 'vnd.ms-powerpoint',
- 'vnd.openxmlformats-officedocument.presentationml.presentation',
- 'vnd.openxmlformats-officedocument.presentationml.template',
- 'vnd.openxmlformats-officedocument.presentationml.slideshow',
- 'vnd.ms-powerpoint.addin.macroEnabled.12',
- 'vnd.ms-powerpoint.presentation.macroEnabled.12',
- 'vnd.ms-powerpoint.template.macroEnabled.12',
- 'vnd.ms-powerpoint.slideshow.macroEnabled.12'
- ]))
- {
- sClass = 'icon-file-chart-graph';
- }
- }
-
- return sClass;
- };
-
- module.exports = AttachmentModel;
-
-}(module));
-},{"../Common/Globals.js":6,"../Common/LinkBuilder.js":7,"../Common/Utils.js":9,"../External/window.js":25}],30:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-(function (module) {
-
- 'use strict';
-
- var
- Enums = require('../Common/Enums.js'),
- Utils = require('../Common/Utils.js')
- ;
-
- /**
- * @param {string=} sEmail
- * @param {string=} sName
- *
- * @constructor
- */
- function EmailModel(sEmail, sName)
- {
- this.email = sEmail || '';
- this.name = sName || '';
- this.privateType = null;
-
- this.clearDuplicateName();
- }
-
- /**
- * @static
- * @param {AjaxJsonEmail} oJsonEmail
- * @return {?EmailModel}
- */
- EmailModel.newInstanceFromJson = function (oJsonEmail)
- {
- var oEmailModel = new EmailModel();
- return oEmailModel.initByJson(oJsonEmail) ? oEmailModel : null;
- };
-
- /**
- * @type {string}
- */
- EmailModel.prototype.name = '';
-
- /**
- * @type {string}
- */
- EmailModel.prototype.email = '';
-
- /**
- * @type {(number|null)}
- */
- EmailModel.prototype.privateType = null;
-
- EmailModel.prototype.clear = function ()
- {
- this.email = '';
- this.name = '';
- this.privateType = null;
- };
-
- /**
- * @returns {boolean}
- */
- EmailModel.prototype.validate = function ()
- {
- return '' !== this.name || '' !== this.email;
- };
-
- /**
- * @param {boolean} bWithoutName = false
- * @return {string}
- */
- EmailModel.prototype.hash = function (bWithoutName)
- {
- return '#' + (bWithoutName ? '' : this.name) + '#' + this.email + '#';
- };
-
- EmailModel.prototype.clearDuplicateName = function ()
- {
- if (this.name === this.email)
- {
- this.name = '';
- }
- };
-
- /**
- * @return {number}
- */
- EmailModel.prototype.type = function ()
- {
- if (null === this.privateType)
- {
- if (this.email && '@facebook.com' === this.email.substr(-13))
- {
- this.privateType = Enums.EmailType.Facebook;
- }
-
- if (null === this.privateType)
- {
- this.privateType = Enums.EmailType.Default;
- }
- }
-
- return this.privateType;
- };
-
- /**
- * @param {string} sQuery
- * @return {boolean}
- */
- EmailModel.prototype.search = function (sQuery)
- {
- return -1 < (this.name + ' ' + this.email).toLowerCase().indexOf(sQuery.toLowerCase());
- };
-
- /**
- * @param {string} sString
- */
- EmailModel.prototype.parse = function (sString)
- {
- this.clear();
-
- sString = Utils.trim(sString);
-
- var
- mRegex = /(?:"([^"]+)")? ?(.*?@[^>,]+)>?,? ?/g,
- mMatch = mRegex.exec(sString)
- ;
-
- if (mMatch)
- {
- this.name = mMatch[1] || '';
- this.email = mMatch[2] || '';
-
- this.clearDuplicateName();
- }
- else if ((/^[^@]+@[^@]+$/).test(sString))
- {
- this.name = '';
- this.email = sString;
- }
- };
-
- /**
- * @param {AjaxJsonEmail} oJsonEmail
- * @return {boolean}
- */
- EmailModel.prototype.initByJson = function (oJsonEmail)
- {
- var bResult = false;
- if (oJsonEmail && 'Object/Email' === oJsonEmail['@Object'])
- {
- this.name = Utils.trim(oJsonEmail.Name);
- this.email = Utils.trim(oJsonEmail.Email);
-
- bResult = '' !== this.email;
- this.clearDuplicateName();
- }
-
- return bResult;
- };
-
- /**
- * @param {boolean} bFriendlyView
- * @param {boolean=} bWrapWithLink = false
- * @param {boolean=} bEncodeHtml = false
- * @return {string}
- */
- EmailModel.prototype.toLine = function (bFriendlyView, bWrapWithLink, bEncodeHtml)
- {
- var sResult = '';
- if ('' !== this.email)
- {
- bWrapWithLink = Utils.isUnd(bWrapWithLink) ? false : !!bWrapWithLink;
- bEncodeHtml = Utils.isUnd(bEncodeHtml) ? false : !!bEncodeHtml;
-
- if (bFriendlyView && '' !== this.name)
- {
- sResult = bWrapWithLink ? '') +
- '" target="_blank" tabindex="-1">' + Utils.encodeHtml(this.name) + '' :
- (bEncodeHtml ? Utils.encodeHtml(this.name) : this.name);
- }
- else
- {
- sResult = this.email;
- if ('' !== this.name)
- {
- if (bWrapWithLink)
- {
- sResult = Utils.encodeHtml('"' + this.name + '" <') +
- '') + '" target="_blank" tabindex="-1">' + Utils.encodeHtml(sResult) + '' + Utils.encodeHtml('>');
- }
- else
- {
- sResult = '"' + this.name + '" <' + sResult + '>';
- if (bEncodeHtml)
- {
- sResult = Utils.encodeHtml(sResult);
- }
- }
- }
- else if (bWrapWithLink)
- {
- sResult = '' + Utils.encodeHtml(this.email) + '';
- }
- }
- }
-
- return sResult;
- };
-
- /**
- * @param {string} $sEmailAddress
- * @return {boolean}
- */
- EmailModel.prototype.mailsoParse = function ($sEmailAddress)
- {
- $sEmailAddress = Utils.trim($sEmailAddress);
- if ('' === $sEmailAddress)
- {
- return false;
- }
-
- var
- substr = function (str, start, len) {
- str += '';
- var end = str.length;
-
- if (start < 0) {
- start += end;
- }
-
- end = typeof len === 'undefined' ? end : (len < 0 ? len + end : len + start);
-
- return start >= str.length || start < 0 || start > end ? false : str.slice(start, end);
- },
-
- substr_replace = function (str, replace, start, length) {
- if (start < 0) {
- start = start + str.length;
- }
- length = length !== undefined ? length : str.length;
- if (length < 0) {
- length = length + str.length - start;
- }
- return str.slice(0, start) + replace.substr(0, length) + replace.slice(length) + str.slice(start + length);
- },
-
- $sName = '',
- $sEmail = '',
- $sComment = '',
-
- $bInName = false,
- $bInAddress = false,
- $bInComment = false,
-
- $aRegs = null,
-
- $iStartIndex = 0,
- $iEndIndex = 0,
- $iCurrentIndex = 0
- ;
-
- while ($iCurrentIndex < $sEmailAddress.length)
- {
- switch ($sEmailAddress.substr($iCurrentIndex, 1))
- {
- case '"':
- if ((!$bInName) && (!$bInAddress) && (!$bInComment))
- {
- $bInName = true;
- $iStartIndex = $iCurrentIndex;
- }
- else if ((!$bInAddress) && (!$bInComment))
- {
- $iEndIndex = $iCurrentIndex;
- $sName = substr($sEmailAddress, $iStartIndex + 1, $iEndIndex - $iStartIndex - 1);
- $sEmailAddress = substr_replace($sEmailAddress, '', $iStartIndex, $iEndIndex - $iStartIndex + 1);
- $iEndIndex = 0;
- $iCurrentIndex = 0;
- $iStartIndex = 0;
- $bInName = false;
- }
- break;
- case '<':
- if ((!$bInName) && (!$bInAddress) && (!$bInComment))
- {
- if ($iCurrentIndex > 0 && $sName.length === 0)
- {
- $sName = substr($sEmailAddress, 0, $iCurrentIndex);
- }
-
- $bInAddress = true;
- $iStartIndex = $iCurrentIndex;
- }
- break;
- case '>':
- if ($bInAddress)
- {
- $iEndIndex = $iCurrentIndex;
- $sEmail = substr($sEmailAddress, $iStartIndex + 1, $iEndIndex - $iStartIndex - 1);
- $sEmailAddress = substr_replace($sEmailAddress, '', $iStartIndex, $iEndIndex - $iStartIndex + 1);
- $iEndIndex = 0;
- $iCurrentIndex = 0;
- $iStartIndex = 0;
- $bInAddress = false;
- }
- break;
- case '(':
- if ((!$bInName) && (!$bInAddress) && (!$bInComment))
- {
- $bInComment = true;
- $iStartIndex = $iCurrentIndex;
- }
- break;
- case ')':
- if ($bInComment)
- {
- $iEndIndex = $iCurrentIndex;
- $sComment = substr($sEmailAddress, $iStartIndex + 1, $iEndIndex - $iStartIndex - 1);
- $sEmailAddress = substr_replace($sEmailAddress, '', $iStartIndex, $iEndIndex - $iStartIndex + 1);
- $iEndIndex = 0;
- $iCurrentIndex = 0;
- $iStartIndex = 0;
- $bInComment = false;
- }
- break;
- case '\\':
- $iCurrentIndex++;
- break;
- }
-
- $iCurrentIndex++;
- }
-
- if ($sEmail.length === 0)
- {
- $aRegs = $sEmailAddress.match(/[^@\s]+@\S+/i);
- if ($aRegs && $aRegs[0])
- {
- $sEmail = $aRegs[0];
- }
- else
- {
- $sName = $sEmailAddress;
- }
- }
-
- if ($sEmail.length > 0 && $sName.length === 0 && $sComment.length === 0)
- {
- $sName = $sEmailAddress.replace($sEmail, '');
- }
-
- $sEmail = Utils.trim($sEmail).replace(/^[<]+/, '').replace(/[>]+$/, '');
- $sName = Utils.trim($sName).replace(/^["']+/, '').replace(/["']+$/, '');
- $sComment = Utils.trim($sComment).replace(/^[(]+/, '').replace(/[)]+$/, '');
-
- // Remove backslash
- $sName = $sName.replace(/\\\\(.)/, '$1');
- $sComment = $sComment.replace(/\\\\(.)/, '$1');
-
- this.name = $sName;
- this.email = $sEmail;
-
- this.clearDuplicateName();
- return true;
- };
-
- /**
- * @return {string}
- */
- EmailModel.prototype.inputoTagLine = function ()
- {
- return 0 < this.name.length ? this.name + ' (' + this.email + ')' : this.email;
- };
-
- module.exports = EmailModel;
-
-}(module));
-},{"../Common/Enums.js":5,"../Common/Utils.js":9}],31:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-(function (module) {
-
- 'use strict';
-
- var
- window = require('../External/window.js'),
- $ = require('../External/jquery.js'),
- _ = require('../External/underscore.js'),
- ko = require('../External/ko.js'),
- moment = require('../External/moment.js'),
- $window = require('../External/$window.js'),
- $div = require('../External/$div.js'),
-
- Enums = require('../Common/Enums.js'),
- Utils = require('../Common/Utils.js'),
- LinkBuilder = require('../Common/LinkBuilder.js'),
-
- EmailModel = require('./EmailModel.js'),
- AttachmentModel = require('./AttachmentModel.js')
- ;
-
- /**
- * @constructor
- */
- function MessageModel()
- {
- this.folderFullNameRaw = '';
- this.uid = '';
- this.hash = '';
- this.requestHash = '';
- this.subject = ko.observable('');
- this.subjectPrefix = ko.observable('');
- this.subjectSuffix = ko.observable('');
- this.size = ko.observable(0);
- this.dateTimeStampInUTC = ko.observable(0);
- this.priority = ko.observable(Enums.MessagePriority.Normal);
-
- this.proxy = false;
-
- this.fromEmailString = ko.observable('');
- this.fromClearEmailString = ko.observable('');
- this.toEmailsString = ko.observable('');
- this.toClearEmailsString = ko.observable('');
-
- this.senderEmailsString = ko.observable('');
- this.senderClearEmailsString = ko.observable('');
-
- this.emails = [];
-
- this.from = [];
- this.to = [];
- this.cc = [];
- this.bcc = [];
- this.replyTo = [];
- this.deliveredTo = [];
-
- this.newForAnimation = ko.observable(false);
-
- this.deleted = ko.observable(false);
- this.unseen = ko.observable(false);
- this.flagged = ko.observable(false);
- this.answered = ko.observable(false);
- this.forwarded = ko.observable(false);
- this.isReadReceipt = ko.observable(false);
-
- this.focused = ko.observable(false);
- this.selected = ko.observable(false);
- this.checked = ko.observable(false);
- this.hasAttachments = ko.observable(false);
- this.attachmentsMainType = ko.observable('');
-
- this.moment = ko.observable(moment(moment.unix(0)));
-
- this.attachmentIconClass = ko.computed(function () {
- var sClass = '';
- if (this.hasAttachments())
- {
- sClass = 'icon-attachment';
- switch (this.attachmentsMainType())
- {
- case 'image':
- sClass = 'icon-image';
- break;
- case 'archive':
- sClass = 'icon-file-zip';
- break;
- case 'doc':
- sClass = 'icon-file-text';
- break;
- // case 'pdf':
- // sClass = 'icon-file-pdf';
- // break;
- }
- }
- return sClass;
- }, this);
-
- this.fullFormatDateValue = ko.computed(function () {
- return MessageModel.calculateFullFromatDateValue(this.dateTimeStampInUTC());
- }, this);
-
- this.momentDate = Utils.createMomentDate(this);
- this.momentShortDate = Utils.createMomentShortDate(this);
-
- this.dateTimeStampInUTC.subscribe(function (iValue) {
- var iNow = moment().unix();
- this.moment(moment.unix(iNow < iValue ? iNow : iValue));
- }, this);
-
- this.body = null;
- this.plainRaw = '';
- this.isHtml = ko.observable(false);
- this.hasImages = ko.observable(false);
- this.attachments = ko.observableArray([]);
-
- this.isPgpSigned = ko.observable(false);
- this.isPgpEncrypted = ko.observable(false);
- this.pgpSignedVerifyStatus = ko.observable(Enums.SignedVerifyStatus.None);
- this.pgpSignedVerifyUser = ko.observable('');
-
- this.priority = ko.observable(Enums.MessagePriority.Normal);
- this.readReceipt = ko.observable('');
-
- this.aDraftInfo = [];
- this.sMessageId = '';
- this.sInReplyTo = '';
- this.sReferences = '';
-
- this.parentUid = ko.observable(0);
- this.threads = ko.observableArray([]);
- this.threadsLen = ko.observable(0);
- this.hasUnseenSubMessage = ko.observable(false);
- this.hasFlaggedSubMessage = ko.observable(false);
-
- this.lastInCollapsedThread = ko.observable(false);
- this.lastInCollapsedThreadLoading = ko.observable(false);
-
- this.threadsLenResult = ko.computed(function () {
- var iCount = this.threadsLen();
- return 0 === this.parentUid() && 0 < iCount ? iCount + 1 : '';
- }, this);
- }
-
- /**
- * @static
- * @param {AjaxJsonMessage} oJsonMessage
- * @return {?MessageModel}
- */
- MessageModel.newInstanceFromJson = function (oJsonMessage)
- {
- var oMessageModel = new MessageModel();
- return oMessageModel.initByJson(oJsonMessage) ? oMessageModel : null;
- };
-
- /**
- * @static
- * @param {number} iTimeStampInUTC
- * @return {string}
- */
- MessageModel.calculateFullFromatDateValue = function (iTimeStampInUTC)
- {
- return 0 < iTimeStampInUTC ? moment.unix(iTimeStampInUTC).format('LLL') : '';
- };
-
- /**
- * @static
- * @param {Array} aEmail
- * @param {boolean=} bFriendlyView
- * @param {boolean=} bWrapWithLink = false
- * @return {string}
- */
- MessageModel.emailsToLine = function (aEmail, bFriendlyView, bWrapWithLink)
- {
- var
- aResult = [],
- iIndex = 0,
- iLen = 0
- ;
-
- if (Utils.isNonEmptyArray(aEmail))
- {
- for (iIndex = 0, iLen = aEmail.length; iIndex < iLen; iIndex++)
- {
- aResult.push(aEmail[iIndex].toLine(bFriendlyView, bWrapWithLink));
- }
- }
-
- return aResult.join(', ');
- };
-
- /**
- * @static
- * @param {Array} aEmail
- * @return {string}
- */
- MessageModel.emailsToLineClear = function (aEmail)
- {
- var
- aResult = [],
- iIndex = 0,
- iLen = 0
- ;
-
- if (Utils.isNonEmptyArray(aEmail))
- {
- for (iIndex = 0, iLen = aEmail.length; iIndex < iLen; iIndex++)
- {
- if (aEmail[iIndex] && aEmail[iIndex].email && '' !== aEmail[iIndex].name)
- {
- aResult.push(aEmail[iIndex].email);
- }
- }
- }
-
- return aResult.join(', ');
- };
-
- /**
- * @static
- * @param {?Array} aJsonEmails
- * @return {Array.}
- */
- MessageModel.initEmailsFromJson = function (aJsonEmails)
- {
- var
- iIndex = 0,
- iLen = 0,
- oEmailModel = null,
- aResult = []
- ;
-
- if (Utils.isNonEmptyArray(aJsonEmails))
- {
- for (iIndex = 0, iLen = aJsonEmails.length; iIndex < iLen; iIndex++)
- {
- oEmailModel = EmailModel.newInstanceFromJson(aJsonEmails[iIndex]);
- if (oEmailModel)
- {
- aResult.push(oEmailModel);
- }
- }
- }
-
- return aResult;
- };
-
- /**
- * @static
- * @param {Array.} aMessageEmails
- * @param {Object} oLocalUnic
- * @param {Array} aLocalEmails
- */
- MessageModel.replyHelper = function (aMessageEmails, oLocalUnic, aLocalEmails)
- {
- if (aMessageEmails && 0 < aMessageEmails.length)
- {
- var
- iIndex = 0,
- iLen = aMessageEmails.length
- ;
-
- for (; iIndex < iLen; iIndex++)
- {
- if (Utils.isUnd(oLocalUnic[aMessageEmails[iIndex].email]))
- {
- oLocalUnic[aMessageEmails[iIndex].email] = true;
- aLocalEmails.push(aMessageEmails[iIndex]);
- }
- }
- }
- };
-
- MessageModel.prototype.clear = function ()
- {
- this.folderFullNameRaw = '';
- this.uid = '';
- this.hash = '';
- this.requestHash = '';
- this.subject('');
- this.subjectPrefix('');
- this.subjectSuffix('');
- this.size(0);
- this.dateTimeStampInUTC(0);
- this.priority(Enums.MessagePriority.Normal);
-
- this.proxy = false;
-
- this.fromEmailString('');
- this.fromClearEmailString('');
- this.toEmailsString('');
- this.toClearEmailsString('');
- this.senderEmailsString('');
- this.senderClearEmailsString('');
-
- this.emails = [];
-
- this.from = [];
- this.to = [];
- this.cc = [];
- this.bcc = [];
- this.replyTo = [];
- this.deliveredTo = [];
-
- this.newForAnimation(false);
-
- this.deleted(false);
- this.unseen(false);
- this.flagged(false);
- this.answered(false);
- this.forwarded(false);
- this.isReadReceipt(false);
-
- this.selected(false);
- this.checked(false);
- this.hasAttachments(false);
- this.attachmentsMainType('');
-
- this.body = null;
- this.isHtml(false);
- this.hasImages(false);
- this.attachments([]);
-
- this.isPgpSigned(false);
- this.isPgpEncrypted(false);
- this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.None);
- this.pgpSignedVerifyUser('');
-
- this.priority(Enums.MessagePriority.Normal);
- this.readReceipt('');
- this.aDraftInfo = [];
- this.sMessageId = '';
- this.sInReplyTo = '';
- this.sReferences = '';
-
- this.parentUid(0);
- this.threads([]);
- this.threadsLen(0);
- this.hasUnseenSubMessage(false);
- this.hasFlaggedSubMessage(false);
-
- this.lastInCollapsedThread(false);
- this.lastInCollapsedThreadLoading(false);
- };
-
- MessageModel.prototype.computeSenderEmail = function ()
- {
- var
- sSent = RL.data().sentFolder(),
- sDraft = RL.data().draftFolder()
- ;
-
- this.senderEmailsString(this.folderFullNameRaw === sSent || this.folderFullNameRaw === sDraft ?
- this.toEmailsString() : this.fromEmailString());
-
- this.senderClearEmailsString(this.folderFullNameRaw === sSent || this.folderFullNameRaw === sDraft ?
- this.toClearEmailsString() : this.fromClearEmailString());
- };
-
- /**
- * @param {AjaxJsonMessage} oJsonMessage
- * @return {boolean}
- */
- MessageModel.prototype.initByJson = function (oJsonMessage)
- {
- var bResult = false;
- if (oJsonMessage && 'Object/Message' === oJsonMessage['@Object'])
- {
- this.folderFullNameRaw = oJsonMessage.Folder;
- this.uid = oJsonMessage.Uid;
- this.hash = oJsonMessage.Hash;
- this.requestHash = oJsonMessage.RequestHash;
-
- this.proxy = !!oJsonMessage.ExternalProxy;
-
- this.size(Utils.pInt(oJsonMessage.Size));
-
- this.from = MessageModel.initEmailsFromJson(oJsonMessage.From);
- this.to = MessageModel.initEmailsFromJson(oJsonMessage.To);
- this.cc = MessageModel.initEmailsFromJson(oJsonMessage.Cc);
- this.bcc = MessageModel.initEmailsFromJson(oJsonMessage.Bcc);
- this.replyTo = MessageModel.initEmailsFromJson(oJsonMessage.ReplyTo);
- this.deliveredTo = MessageModel.initEmailsFromJson(oJsonMessage.DeliveredTo);
-
- this.subject(oJsonMessage.Subject);
- if (Utils.isArray(oJsonMessage.SubjectParts))
- {
- this.subjectPrefix(oJsonMessage.SubjectParts[0]);
- this.subjectSuffix(oJsonMessage.SubjectParts[1]);
- }
- else
- {
- this.subjectPrefix('');
- this.subjectSuffix(this.subject());
- }
-
- this.dateTimeStampInUTC(Utils.pInt(oJsonMessage.DateTimeStampInUTC));
- this.hasAttachments(!!oJsonMessage.HasAttachments);
- this.attachmentsMainType(oJsonMessage.AttachmentsMainType);
-
- this.fromEmailString(MessageModel.emailsToLine(this.from, true));
- this.fromClearEmailString(MessageModel.emailsToLineClear(this.from));
- this.toEmailsString(MessageModel.emailsToLine(this.to, true));
- this.toClearEmailsString(MessageModel.emailsToLineClear(this.to));
-
- this.parentUid(Utils.pInt(oJsonMessage.ParentThread));
- this.threads(Utils.isArray(oJsonMessage.Threads) ? oJsonMessage.Threads : []);
- this.threadsLen(Utils.pInt(oJsonMessage.ThreadsLen));
-
- this.initFlagsByJson(oJsonMessage);
- this.computeSenderEmail();
-
- bResult = true;
- }
-
- return bResult;
- };
-
- /**
- * @param {AjaxJsonMessage} oJsonMessage
- * @return {boolean}
- */
- MessageModel.prototype.initUpdateByMessageJson = function (oJsonMessage)
- {
- var
- bResult = false,
- iPriority = Enums.MessagePriority.Normal
- ;
-
- if (oJsonMessage && 'Object/Message' === oJsonMessage['@Object'])
- {
- iPriority = Utils.pInt(oJsonMessage.Priority);
- this.priority(-1 < Utils.inArray(iPriority, [Enums.MessagePriority.High, Enums.MessagePriority.Low]) ?
- iPriority : Enums.MessagePriority.Normal);
-
- this.aDraftInfo = oJsonMessage.DraftInfo;
-
- this.sMessageId = oJsonMessage.MessageId;
- this.sInReplyTo = oJsonMessage.InReplyTo;
- this.sReferences = oJsonMessage.References;
-
- this.proxy = !!oJsonMessage.ExternalProxy;
-
- if (RL.data().capaOpenPGP()) // TODO cjs
- {
- this.isPgpSigned(!!oJsonMessage.PgpSigned);
- this.isPgpEncrypted(!!oJsonMessage.PgpEncrypted);
- }
-
- this.hasAttachments(!!oJsonMessage.HasAttachments);
- this.attachmentsMainType(oJsonMessage.AttachmentsMainType);
-
- this.foundedCIDs = Utils.isArray(oJsonMessage.FoundedCIDs) ? oJsonMessage.FoundedCIDs : [];
- this.attachments(this.initAttachmentsFromJson(oJsonMessage.Attachments));
-
- this.readReceipt(oJsonMessage.ReadReceipt || '');
-
- this.computeSenderEmail();
-
- bResult = true;
- }
-
- return bResult;
- };
-
- /**
- * @param {(AjaxJsonAttachment|null)} oJsonAttachments
- * @return {Array}
- */
- MessageModel.prototype.initAttachmentsFromJson = function (oJsonAttachments)
- {
- var
- iIndex = 0,
- iLen = 0,
- oAttachmentModel = null,
- aResult = []
- ;
-
- if (oJsonAttachments && 'Collection/AttachmentCollection' === oJsonAttachments['@Object'] &&
- Utils.isNonEmptyArray(oJsonAttachments['@Collection']))
- {
- for (iIndex = 0, iLen = oJsonAttachments['@Collection'].length; iIndex < iLen; iIndex++)
- {
- oAttachmentModel = AttachmentModel.newInstanceFromJson(oJsonAttachments['@Collection'][iIndex]);
- if (oAttachmentModel)
- {
- if ('' !== oAttachmentModel.cidWithOutTags && 0 < this.foundedCIDs.length &&
- 0 <= Utils.inArray(oAttachmentModel.cidWithOutTags, this.foundedCIDs))
- {
- oAttachmentModel.isLinked = true;
- }
-
- aResult.push(oAttachmentModel);
- }
- }
- }
-
- return aResult;
- };
-
- /**
- * @param {AjaxJsonMessage} oJsonMessage
- * @return {boolean}
- */
- MessageModel.prototype.initFlagsByJson = function (oJsonMessage)
- {
- var bResult = false;
-
- if (oJsonMessage && 'Object/Message' === oJsonMessage['@Object'])
- {
- this.unseen(!oJsonMessage.IsSeen);
- this.flagged(!!oJsonMessage.IsFlagged);
- this.answered(!!oJsonMessage.IsAnswered);
- this.forwarded(!!oJsonMessage.IsForwarded);
- this.isReadReceipt(!!oJsonMessage.IsReadReceipt);
-
- bResult = true;
- }
-
- return bResult;
- };
-
- /**
- * @param {boolean} bFriendlyView
- * @param {boolean=} bWrapWithLink = false
- * @return {string}
- */
- MessageModel.prototype.fromToLine = function (bFriendlyView, bWrapWithLink)
- {
- return MessageModel.emailsToLine(this.from, bFriendlyView, bWrapWithLink);
- };
-
- /**
- * @param {boolean} bFriendlyView
- * @param {boolean=} bWrapWithLink = false
- * @return {string}
- */
- MessageModel.prototype.toToLine = function (bFriendlyView, bWrapWithLink)
- {
- return MessageModel.emailsToLine(this.to, bFriendlyView, bWrapWithLink);
- };
-
- /**
- * @param {boolean} bFriendlyView
- * @param {boolean=} bWrapWithLink = false
- * @return {string}
- */
- MessageModel.prototype.ccToLine = function (bFriendlyView, bWrapWithLink)
- {
- return MessageModel.emailsToLine(this.cc, bFriendlyView, bWrapWithLink);
- };
-
- /**
- * @param {boolean} bFriendlyView
- * @param {boolean=} bWrapWithLink = false
- * @return {string}
- */
- MessageModel.prototype.bccToLine = function (bFriendlyView, bWrapWithLink)
- {
- return MessageModel.emailsToLine(this.bcc, bFriendlyView, bWrapWithLink);
- };
-
- /**
- * @return string
- */
- MessageModel.prototype.lineAsCcc = function ()
- {
- var aResult = [];
- if (this.deleted())
- {
- aResult.push('deleted');
- }
- if (this.selected())
- {
- aResult.push('selected');
- }
- if (this.checked())
- {
- aResult.push('checked');
- }
- if (this.flagged())
- {
- aResult.push('flagged');
- }
- if (this.unseen())
- {
- aResult.push('unseen');
- }
- if (this.answered())
- {
- aResult.push('answered');
- }
- if (this.forwarded())
- {
- aResult.push('forwarded');
- }
- if (this.focused())
- {
- aResult.push('focused');
- }
- if (this.hasAttachments())
- {
- aResult.push('withAttachments');
- switch (this.attachmentsMainType())
- {
- case 'image':
- aResult.push('imageOnlyAttachments');
- break;
- case 'archive':
- aResult.push('archiveOnlyAttachments');
- break;
- }
- }
- if (this.newForAnimation())
- {
- aResult.push('new');
- }
- if ('' === this.subject())
- {
- aResult.push('emptySubject');
- }
- if (0 < this.parentUid())
- {
- aResult.push('hasParentMessage');
- }
- if (0 < this.threadsLen() && 0 === this.parentUid())
- {
- aResult.push('hasChildrenMessage');
- }
- if (this.hasUnseenSubMessage())
- {
- aResult.push('hasUnseenSubMessage');
- }
- if (this.hasFlaggedSubMessage())
- {
- aResult.push('hasFlaggedSubMessage');
- }
-
- return aResult.join(' ');
- };
-
- /**
- * @return {boolean}
- */
- MessageModel.prototype.hasVisibleAttachments = function ()
- {
- return !!_.find(this.attachments(), function (oAttachment) {
- return !oAttachment.isLinked;
- });
- };
-
- /**
- * @param {string} sCid
- * @return {*}
- */
- MessageModel.prototype.findAttachmentByCid = function (sCid)
- {
- var
- oResult = null,
- aAttachments = this.attachments()
- ;
-
- if (Utils.isNonEmptyArray(aAttachments))
- {
- sCid = sCid.replace(/^<+/, '').replace(/>+$/, '');
- oResult = _.find(aAttachments, function (oAttachment) {
- return sCid === oAttachment.cidWithOutTags;
- });
- }
-
- return oResult || null;
- };
-
- /**
- * @param {string} sContentLocation
- * @return {*}
- */
- MessageModel.prototype.findAttachmentByContentLocation = function (sContentLocation)
- {
- var
- oResult = null,
- aAttachments = this.attachments()
- ;
-
- if (Utils.isNonEmptyArray(aAttachments))
- {
- oResult = _.find(aAttachments, function (oAttachment) {
- return sContentLocation === oAttachment.contentLocation;
- });
- }
-
- return oResult || null;
- };
-
-
- /**
- * @return {string}
- */
- MessageModel.prototype.messageId = function ()
- {
- return this.sMessageId;
- };
-
- /**
- * @return {string}
- */
- MessageModel.prototype.inReplyTo = function ()
- {
- return this.sInReplyTo;
- };
-
- /**
- * @return {string}
- */
- MessageModel.prototype.references = function ()
- {
- return this.sReferences;
- };
-
- /**
- * @return {string}
- */
- MessageModel.prototype.fromAsSingleEmail = function ()
- {
- return Utils.isArray(this.from) && this.from[0] ? this.from[0].email : '';
- };
-
- /**
- * @return {string}
- */
- MessageModel.prototype.viewLink = function ()
- {
- return LinkBuilder.messageViewLink(this.requestHash);// TODO cjs
- };
-
- /**
- * @return {string}
- */
- MessageModel.prototype.downloadLink = function ()
- {
- return LinkBuilder.messageDownloadLink(this.requestHash);// TODO cjs
- };
-
- /**
- * @param {Object} oExcludeEmails
- * @return {Array}
- */
- MessageModel.prototype.replyEmails = function (oExcludeEmails)
- {
- var
- aResult = [],
- oUnic = Utils.isUnd(oExcludeEmails) ? {} : oExcludeEmails
- ;
-
- MessageModel.replyHelper(this.replyTo, oUnic, aResult);
- if (0 === aResult.length)
- {
- MessageModel.replyHelper(this.from, oUnic, aResult);
- }
-
- return aResult;
- };
-
- /**
- * @param {Object} oExcludeEmails
- * @return {Array.}
- */
- MessageModel.prototype.replyAllEmails = function (oExcludeEmails)
- {
- var
- aToResult = [],
- aCcResult = [],
- oUnic = Utils.isUnd(oExcludeEmails) ? {} : oExcludeEmails
- ;
-
- MessageModel.replyHelper(this.replyTo, oUnic, aToResult);
- if (0 === aToResult.length)
- {
- MessageModel.replyHelper(this.from, oUnic, aToResult);
- }
-
- MessageModel.replyHelper(this.to, oUnic, aToResult);
- MessageModel.replyHelper(this.cc, oUnic, aCcResult);
-
- return [aToResult, aCcResult];
- };
-
- /**
- * @return {string}
- */
- MessageModel.prototype.textBodyToString = function ()
- {
- return this.body ? this.body.html() : '';
- };
-
- /**
- * @return {string}
- */
- MessageModel.prototype.attachmentsToStringLine = function ()
- {
- var aAttachLines = _.map(this.attachments(), function (oItem) {
- return oItem.fileName + ' (' + oItem.friendlySize + ')';
- });
-
- return aAttachLines && 0 < aAttachLines.length ? aAttachLines.join(', ') : '';
- };
-
- /**
- * @return {Object}
- */
- MessageModel.prototype.getDataForWindowPopup = function ()
- {
- return {
- 'popupFrom': this.fromToLine(false),
- 'popupTo': this.toToLine(false),
- 'popupCc': this.ccToLine(false),
- 'popupBcc': this.bccToLine(false),
- 'popupSubject': this.subject(),
- 'popupDate': this.fullFormatDateValue(),
- 'popupAttachments': this.attachmentsToStringLine(),
- 'popupBody': this.textBodyToString()
- };
- };
-
- /**
- * @param {boolean=} bPrint = false
- */
- MessageModel.prototype.viewPopupMessage = function (bPrint)
- {
- Utils.windowPopupKnockout(this.getDataForWindowPopup(), 'PopupsWindowSimpleMessage', this.subject(), function (oPopupWin) {
- if (oPopupWin && oPopupWin.document && oPopupWin.document.body)
- {
- $('img.lazy', oPopupWin.document.body).each(function (iIndex, oImg) {
-
- var
- $oImg = $(oImg),
- sOrig = $oImg.data('original'),
- sSrc = $oImg.attr('src')
- ;
-
- if (0 <= iIndex && sOrig && !sSrc)
- {
- $oImg.attr('src', sOrig);
- }
- });
-
- if (bPrint)
- {
- window.setTimeout(function () {
- oPopupWin.print();
- }, 100);
- }
- }
- });
- };
-
- MessageModel.prototype.printMessage = function ()
- {
- this.viewPopupMessage(true);
- };
-
- /**
- * @returns {string}
- */
- MessageModel.prototype.generateUid = function ()
- {
- return this.folderFullNameRaw + '/' + this.uid;
- };
-
- /**
- * @param {MessageModel} oMessage
- * @return {MessageModel}
- */
- MessageModel.prototype.populateByMessageListItem = function (oMessage)
- {
- this.folderFullNameRaw = oMessage.folderFullNameRaw;
- this.uid = oMessage.uid;
- this.hash = oMessage.hash;
- this.requestHash = oMessage.requestHash;
- this.subject(oMessage.subject());
- this.subjectPrefix(this.subjectPrefix());
- this.subjectSuffix(this.subjectSuffix());
-
- this.size(oMessage.size());
- this.dateTimeStampInUTC(oMessage.dateTimeStampInUTC());
- this.priority(oMessage.priority());
-
- this.proxy = oMessage.proxy;
-
- this.fromEmailString(oMessage.fromEmailString());
- this.fromClearEmailString(oMessage.fromClearEmailString());
- this.toEmailsString(oMessage.toEmailsString());
- this.toClearEmailsString(oMessage.toClearEmailsString());
-
- this.emails = oMessage.emails;
-
- this.from = oMessage.from;
- this.to = oMessage.to;
- this.cc = oMessage.cc;
- this.bcc = oMessage.bcc;
- this.replyTo = oMessage.replyTo;
- this.deliveredTo = oMessage.deliveredTo;
-
- this.unseen(oMessage.unseen());
- this.flagged(oMessage.flagged());
- this.answered(oMessage.answered());
- this.forwarded(oMessage.forwarded());
- this.isReadReceipt(oMessage.isReadReceipt());
-
- this.selected(oMessage.selected());
- this.checked(oMessage.checked());
- this.hasAttachments(oMessage.hasAttachments());
- this.attachmentsMainType(oMessage.attachmentsMainType());
-
- this.moment(oMessage.moment());
-
- this.body = null;
-
- this.priority(Enums.MessagePriority.Normal);
- this.aDraftInfo = [];
- this.sMessageId = '';
- this.sInReplyTo = '';
- this.sReferences = '';
-
- this.parentUid(oMessage.parentUid());
- this.threads(oMessage.threads());
- this.threadsLen(oMessage.threadsLen());
-
- this.computeSenderEmail();
-
- return this;
- };
-
- MessageModel.prototype.showExternalImages = function (bLazy)
- {
- if (this.body && this.body.data('rl-has-images'))
- {
- var sAttr = '';
- bLazy = Utils.isUnd(bLazy) ? false : bLazy;
-
- this.hasImages(false);
- this.body.data('rl-has-images', false);
-
- sAttr = this.proxy ? 'data-x-additional-src' : 'data-x-src';
- $('[' + sAttr + ']', this.body).each(function () {
- if (bLazy && $(this).is('img'))
- {
- $(this)
- .addClass('lazy')
- .attr('data-original', $(this).attr(sAttr))
- .removeAttr(sAttr)
- ;
- }
- else
- {
- $(this).attr('src', $(this).attr(sAttr)).removeAttr(sAttr);
- }
- });
-
- sAttr = this.proxy ? 'data-x-additional-style-url' : 'data-x-style-url';
- $('[' + sAttr + ']', this.body).each(function () {
- var sStyle = Utils.trim($(this).attr('style'));
- sStyle = '' === sStyle ? '' : (';' === sStyle.substr(-1) ? sStyle + ' ' : sStyle + '; ');
- $(this).attr('style', sStyle + $(this).attr(sAttr)).removeAttr(sAttr);
- });
-
- if (bLazy)
- {
- $('img.lazy', this.body).addClass('lazy-inited').lazyload({
- 'threshold' : 400,
- 'effect' : 'fadeIn',
- 'skip_invisible' : false,
- 'container': $('.RL-MailMessageView .messageView .messageItem .content')[0]
- });
-
- $window.resize();
- }
-
- Utils.windowResize(500);
- }
- };
-
- MessageModel.prototype.showInternalImages = function (bLazy)
- {
- if (this.body && !this.body.data('rl-init-internal-images'))
- {
- this.body.data('rl-init-internal-images', true);
-
- bLazy = Utils.isUnd(bLazy) ? false : bLazy;
-
- var self = this;
-
- $('[data-x-src-cid]', this.body).each(function () {
-
- var oAttachment = self.findAttachmentByCid($(this).attr('data-x-src-cid'));
- if (oAttachment && oAttachment.download)
- {
- if (bLazy && $(this).is('img'))
- {
- $(this)
- .addClass('lazy')
- .attr('data-original', oAttachment.linkPreview());
- }
- else
- {
- $(this).attr('src', oAttachment.linkPreview());
- }
- }
- });
-
- $('[data-x-src-location]', this.body).each(function () {
-
- var oAttachment = self.findAttachmentByContentLocation($(this).attr('data-x-src-location'));
- if (!oAttachment)
- {
- oAttachment = self.findAttachmentByCid($(this).attr('data-x-src-location'));
- }
-
- if (oAttachment && oAttachment.download)
- {
- if (bLazy && $(this).is('img'))
- {
- $(this)
- .addClass('lazy')
- .attr('data-original', oAttachment.linkPreview());
- }
- else
- {
- $(this).attr('src', oAttachment.linkPreview());
- }
- }
- });
-
- $('[data-x-style-cid]', this.body).each(function () {
-
- var
- sStyle = '',
- sName = '',
- oAttachment = self.findAttachmentByCid($(this).attr('data-x-style-cid'))
- ;
-
- if (oAttachment && oAttachment.linkPreview)
- {
- sName = $(this).attr('data-x-style-cid-name');
- if ('' !== sName)
- {
- sStyle = Utils.trim($(this).attr('style'));
- sStyle = '' === sStyle ? '' : (';' === sStyle.substr(-1) ? sStyle + ' ' : sStyle + '; ');
- $(this).attr('style', sStyle + sName + ': url(\'' + oAttachment.linkPreview() + '\')');
- }
- }
- });
-
- if (bLazy)
- {
- (function ($oImg, oContainer) {
- _.delay(function () {
- $oImg.addClass('lazy-inited').lazyload({
- 'threshold' : 400,
- 'effect' : 'fadeIn',
- 'skip_invisible' : false,
- 'container': oContainer
- });
- }, 300);
- }($('img.lazy', self.body), $('.RL-MailMessageView .messageView .messageItem .content')[0]));
- }
-
- Utils.windowResize(500);
- }
- };
-
- MessageModel.prototype.storeDataToDom = function ()
- {
- if (this.body)
- {
- this.body.data('rl-is-html', !!this.isHtml());
- this.body.data('rl-has-images', !!this.hasImages());
-
- this.body.data('rl-plain-raw', this.plainRaw);
-
- if (RL.data().capaOpenPGP()) // TODO cjs
- {
- this.body.data('rl-plain-pgp-signed', !!this.isPgpSigned());
- this.body.data('rl-plain-pgp-encrypted', !!this.isPgpEncrypted());
- this.body.data('rl-pgp-verify-status', this.pgpSignedVerifyStatus());
- this.body.data('rl-pgp-verify-user', this.pgpSignedVerifyUser());
- }
- }
- };
-
- MessageModel.prototype.storePgpVerifyDataToDom = function ()
- {
- if (this.body && RL.data().capaOpenPGP()) // TODO cjs
- {
- this.body.data('rl-pgp-verify-status', this.pgpSignedVerifyStatus());
- this.body.data('rl-pgp-verify-user', this.pgpSignedVerifyUser());
- }
- };
-
- MessageModel.prototype.fetchDataToDom = function ()
- {
- if (this.body)
- {
- this.isHtml(!!this.body.data('rl-is-html'));
- this.hasImages(!!this.body.data('rl-has-images'));
-
- this.plainRaw = Utils.pString(this.body.data('rl-plain-raw'));
-
- if (RL.data().capaOpenPGP()) // TODO cjs
- {
- this.isPgpSigned(!!this.body.data('rl-plain-pgp-signed'));
- this.isPgpEncrypted(!!this.body.data('rl-plain-pgp-encrypted'));
- this.pgpSignedVerifyStatus(this.body.data('rl-pgp-verify-status'));
- this.pgpSignedVerifyUser(this.body.data('rl-pgp-verify-user'));
- }
- else
- {
- this.isPgpSigned(false);
- this.isPgpEncrypted(false);
- this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.None);
- this.pgpSignedVerifyUser('');
- }
- }
- };
-
- MessageModel.prototype.verifyPgpSignedClearMessage = function ()
- {
- if (this.isPgpSigned())
- {
- var
- aRes = [],
- mPgpMessage = null,
- sFrom = this.from && this.from[0] && this.from[0].email ? this.from[0].email : '',
- aPublicKeys = RL.data().findPublicKeysByEmail(sFrom), // TODO cjs
- oValidKey = null,
- oValidSysKey = null,
- sPlain = ''
- ;
-
- this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.Error);
- this.pgpSignedVerifyUser('');
-
- try
- {
- mPgpMessage = window.openpgp.cleartext.readArmored(this.plainRaw);
- if (mPgpMessage && mPgpMessage.getText)
- {
- this.pgpSignedVerifyStatus(
- aPublicKeys.length ? Enums.SignedVerifyStatus.Unverified : Enums.SignedVerifyStatus.UnknownPublicKeys);
-
- aRes = mPgpMessage.verify(aPublicKeys);
- if (aRes && 0 < aRes.length)
- {
- oValidKey = _.find(aRes, function (oItem) {
- return oItem && oItem.keyid && oItem.valid;
- });
-
- if (oValidKey)
- {
- oValidSysKey = RL.data().findPublicKeyByHex(oValidKey.keyid.toHex()); // TODO cjs
- if (oValidSysKey)
- {
- sPlain = mPgpMessage.getText();
-
- this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.Success);
- this.pgpSignedVerifyUser(oValidSysKey.user);
-
- sPlain =
- $div.empty().append(
- $('').text(sPlain)
- ).html()
- ;
-
- $div.empty();
-
- this.replacePlaneTextBody(sPlain);
- }
- }
- }
- }
- }
- catch (oExc) {}
-
- this.storePgpVerifyDataToDom();
- }
- };
-
- MessageModel.prototype.decryptPgpEncryptedMessage = function (sPassword)
- {
- if (this.isPgpEncrypted())
- {
- var
- aRes = [],
- mPgpMessage = null,
- mPgpMessageDecrypted = null,
- sFrom = this.from && this.from[0] && this.from[0].email ? this.from[0].email : '',
- aPublicKey = RL.data().findPublicKeysByEmail(sFrom), // TODO cjs
- oPrivateKey = RL.data().findSelfPrivateKey(sPassword), // TODO cjs
- oValidKey = null,
- oValidSysKey = null,
- sPlain = ''
- ;
-
- this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.Error);
- this.pgpSignedVerifyUser('');
-
- if (!oPrivateKey)
- {
- this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.UnknownPrivateKey);
- }
-
- try
- {
- mPgpMessage = window.openpgp.message.readArmored(this.plainRaw);
- if (mPgpMessage && oPrivateKey && mPgpMessage.decrypt)
- {
- this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.Unverified);
-
- mPgpMessageDecrypted = mPgpMessage.decrypt(oPrivateKey);
- if (mPgpMessageDecrypted)
- {
- aRes = mPgpMessageDecrypted.verify(aPublicKey);
- if (aRes && 0 < aRes.length)
- {
- oValidKey = _.find(aRes, function (oItem) {
- return oItem && oItem.keyid && oItem.valid;
- });
-
- if (oValidKey)
- {
- oValidSysKey = RL.data().findPublicKeyByHex(oValidKey.keyid.toHex()); // TODO cjs
- if (oValidSysKey)
- {
- this.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.Success);
- this.pgpSignedVerifyUser(oValidSysKey.user);
- }
- }
- }
-
- sPlain = mPgpMessageDecrypted.getText();
-
- sPlain =
- $div.empty().append(
- $('').text(sPlain)
- ).html()
- ;
-
- $div.empty();
-
- this.replacePlaneTextBody(sPlain);
- }
- }
- }
- catch (oExc) {}
-
- this.storePgpVerifyDataToDom();
- }
- };
-
- MessageModel.prototype.replacePlaneTextBody = function (sPlain)
- {
- if (this.body)
- {
- this.body.html(sPlain).addClass('b-text-part plain');
- }
- };
-
- /**
- * @return {string}
- */
- MessageModel.prototype.flagHash = function ()
- {
- return [this.deleted(), this.unseen(), this.flagged(), this.answered(), this.forwarded(),
- this.isReadReceipt()].join('');
- };
-
- module.exports = MessageModel;
-
-}(module));
-},{"../Common/Enums.js":5,"../Common/LinkBuilder.js":7,"../Common/Utils.js":9,"../External/$div.js":10,"../External/$window.js":13,"../External/jquery.js":19,"../External/ko.js":21,"../External/moment.js":22,"../External/underscore.js":24,"../External/window.js":25,"./AttachmentModel.js":29,"./EmailModel.js":30}],32:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-'use strict';
-
-module.exports = function () {
- return require('./Knoin/Knoin.js').rl();
-};
-},{"./Knoin/Knoin.js":26}],33:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-'use strict';
-
-module.exports = function () {
- return require('./Knoin/Knoin.js').remote();
-};
-},{"./Knoin/Knoin.js":26}],34:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-(function (module) {
-
- 'use strict';
-
- var
- window = require('../External/window.js'),
- $ = require('../External/jquery.js'),
-
- Consts = require('../Common/Consts.js'),
- Enums = require('../Common/Enums.js'),
- Globals = require('../Common/Globals.js'),
- Utils = require('../Common/Utils.js'),
- Plugins = require('../Common/Plugins.js'),
- LinkBuilder = require('../Common/LinkBuilder.js'),
-
- RL = require('../RL.js')
- ;
-
- /**
- * @constructor
- */
- function AbstractAjaxRemoteStorage()
- {
- this.oRequests = {};
- }
-
- AbstractAjaxRemoteStorage.prototype.oRequests = {};
-
- /**
- * @param {?Function} fCallback
- * @param {string} sRequestAction
- * @param {string} sType
- * @param {?AjaxJsonDefaultResponse} oData
- * @param {boolean} bCached
- * @param {*=} oRequestParameters
- */
- AbstractAjaxRemoteStorage.prototype.defaultResponse = function (fCallback, sRequestAction, sType, oData, bCached, oRequestParameters)
- {
- var
- fCall = function () {
- if (Enums.StorageResultType.Success !== sType && Globals.bUnload)
- {
- sType = Enums.StorageResultType.Unload;
- }
-
- if (Enums.StorageResultType.Success === sType && oData && !oData.Result)
- {
- if (oData && -1 < Utils.inArray(oData.ErrorCode, [
- Enums.Notification.AuthError, Enums.Notification.AccessError,
- Enums.Notification.ConnectionError, Enums.Notification.DomainNotAllowed, Enums.Notification.AccountNotAllowed,
- Enums.Notification.MailServerError, Enums.Notification.UnknownNotification, Enums.Notification.UnknownError
- ]))
- {
- Globals.iAjaxErrorCount++;
- }
-
- if (oData && Enums.Notification.InvalidToken === oData.ErrorCode)
- {
- Globals.iTokenErrorCount++;
- }
-
- if (Consts.Values.TokenErrorLimit < Globals.iTokenErrorCount)
- {
- RL().loginAndLogoutReload(true);
- }
-
- if (oData.Logout || Consts.Values.AjaxErrorLimit < Globals.iAjaxErrorCount)
- {
- if (window.__rlah_clear)
- {
- window.__rlah_clear();
- }
-
- RL().loginAndLogoutReload(true);
- }
- }
- else if (Enums.StorageResultType.Success === sType && oData && oData.Result)
- {
- Globals.iAjaxErrorCount = 0;
- Globals.iTokenErrorCount = 0;
- }
-
- if (fCallback)
- {
- Plugins.runHook('ajax-default-response', [sRequestAction, Enums.StorageResultType.Success === sType ? oData : null, sType, bCached, oRequestParameters]);
-
- fCallback(
- sType,
- Enums.StorageResultType.Success === sType ? oData : null,
- bCached,
- sRequestAction,
- oRequestParameters
- );
- }
- }
- ;
-
- switch (sType)
- {
- case 'success':
- sType = Enums.StorageResultType.Success;
- break;
- case 'abort':
- sType = Enums.StorageResultType.Abort;
- break;
- default:
- sType = Enums.StorageResultType.Error;
- break;
- }
-
- if (Enums.StorageResultType.Error === sType)
- {
- _.delay(fCall, 300);
- }
- else
- {
- fCall();
- }
- };
-
- /**
- * @param {?Function} fResultCallback
- * @param {Object} oParameters
- * @param {?number=} iTimeOut = 20000
- * @param {string=} sGetAdd = ''
- * @param {Array=} aAbortActions = []
- * @return {jQuery.jqXHR}
- */
- AbstractAjaxRemoteStorage.prototype.ajaxRequest = function (fResultCallback, oParameters, iTimeOut, sGetAdd, aAbortActions)
- {
- var
- self = this,
- bPost = '' === sGetAdd,
- oHeaders = {},
- iStart = (new window.Date()).getTime(),
- oDefAjax = null,
- sAction = ''
- ;
-
- oParameters = oParameters || {};
- iTimeOut = Utils.isNormal(iTimeOut) ? iTimeOut : 20000;
- sGetAdd = Utils.isUnd(sGetAdd) ? '' : Utils.pString(sGetAdd);
- aAbortActions = Utils.isArray(aAbortActions) ? aAbortActions : [];
-
- sAction = oParameters.Action || '';
-
- if (sAction && 0 < aAbortActions.length)
- {
- _.each(aAbortActions, function (sActionToAbort) {
- if (self.oRequests[sActionToAbort])
- {
- self.oRequests[sActionToAbort].__aborted = true;
- if (self.oRequests[sActionToAbort].abort)
- {
- self.oRequests[sActionToAbort].abort();
- }
- self.oRequests[sActionToAbort] = null;
- }
- });
- }
-
- if (bPost)
- {
- oParameters['XToken'] = RL.settingsGet('Token'); // TODO cjs
- }
-
- oDefAjax = $.ajax({
- 'type': bPost ? 'POST' : 'GET',
- 'url': LinkBuilder.ajax(sGetAdd),
- 'async': true,
- 'dataType': 'json',
- 'data': bPost ? oParameters : {},
- 'headers': oHeaders,
- 'timeout': iTimeOut,
- 'global': true
- });
-
- oDefAjax.always(function (oData, sType) {
-
- var bCached = false;
- if (oData && oData['Time'])
- {
- bCached = Utils.pInt(oData['Time']) > (new window.Date()).getTime() - iStart;
- }
-
- if (sAction && self.oRequests[sAction])
- {
- if (self.oRequests[sAction].__aborted)
- {
- sType = 'abort';
- }
-
- self.oRequests[sAction] = null;
- }
-
- self.defaultResponse(fResultCallback, sAction, sType, oData, bCached, oParameters);
- });
-
- if (sAction && 0 < aAbortActions.length && -1 < Utils.inArray(sAction, aAbortActions))
- {
- if (this.oRequests[sAction])
- {
- this.oRequests[sAction].__aborted = true;
- if (this.oRequests[sAction].abort)
- {
- this.oRequests[sAction].abort();
- }
- this.oRequests[sAction] = null;
- }
-
- this.oRequests[sAction] = oDefAjax;
- }
-
- return oDefAjax;
- };
-
- /**
- * @param {?Function} fCallback
- * @param {string} sAction
- * @param {Object=} oParameters
- * @param {?number=} iTimeout
- * @param {string=} sGetAdd = ''
- * @param {Array=} aAbortActions = []
- */
- AbstractAjaxRemoteStorage.prototype.defaultRequest = function (fCallback, sAction, oParameters, iTimeout, sGetAdd, aAbortActions)
- {
- oParameters = oParameters || {};
- oParameters.Action = sAction;
-
- sGetAdd = Utils.pString(sGetAdd);
-
- Plugins.runHook('ajax-default-request', [sAction, oParameters, sGetAdd]);
-
- this.ajaxRequest(fCallback, oParameters,
- Utils.isUnd(iTimeout) ? Consts.Defaults.DefaultAjaxTimeout : Utils.pInt(iTimeout), sGetAdd, aAbortActions);
- };
-
- /**
- * @param {?Function} fCallback
- */
- AbstractAjaxRemoteStorage.prototype.noop = function (fCallback)
- {
- this.defaultRequest(fCallback, 'Noop');
- };
-
- /**
- * @param {?Function} fCallback
- * @param {string} sMessage
- * @param {string} sFileName
- * @param {number} iLineNo
- * @param {string} sLocation
- * @param {string} sHtmlCapa
- * @param {number} iTime
- */
- AbstractAjaxRemoteStorage.prototype.jsError = function (fCallback, sMessage, sFileName, iLineNo, sLocation, sHtmlCapa, iTime)
- {
- this.defaultRequest(fCallback, 'JsError', {
- 'Message': sMessage,
- 'FileName': sFileName,
- 'LineNo': iLineNo,
- 'Location': sLocation,
- 'HtmlCapa': sHtmlCapa,
- 'TimeOnPage': iTime
- });
- };
-
- /**
- * @param {?Function} fCallback
- * @param {string} sType
- * @param {Array=} mData = null
- * @param {boolean=} bIsError = false
- */
- AbstractAjaxRemoteStorage.prototype.jsInfo = function (fCallback, sType, mData, bIsError)
- {
- this.defaultRequest(fCallback, 'JsInfo', {
- 'Type': sType,
- 'Data': mData,
- 'IsError': (Utils.isUnd(bIsError) ? false : !!bIsError) ? '1' : '0'
- });
- };
-
- /**
- * @param {?Function} fCallback
- */
- AbstractAjaxRemoteStorage.prototype.getPublicKey = function (fCallback)
- {
- this.defaultRequest(fCallback, 'GetPublicKey');
- };
-
- /**
- * @param {?Function} fCallback
- * @param {string} sVersion
- */
- AbstractAjaxRemoteStorage.prototype.jsVersion = function (fCallback, sVersion)
- {
- this.defaultRequest(fCallback, 'Version', {
- 'Version': sVersion
- });
- };
-
- module.exports = AbstractAjaxRemoteStorage;
-
-}(module));
-},{"../Common/Consts.js":4,"../Common/Enums.js":5,"../Common/Globals.js":6,"../Common/LinkBuilder.js":7,"../Common/Plugins.js":8,"../Common/Utils.js":9,"../External/jquery.js":19,"../External/window.js":25,"../RL.js":32}],35:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-(function (module) {
-
- 'use strict';
-
- var
- ko = require('../External/ko.js'),
- key = require('../External/key.js'),
- Enums = require('../Common/Enums.js'),
- Globals = require('../Common/Globals.js'),
- Utils = require('../Common/Utils.js')
- ;
-
- /**
- * @constructor
- */
- function AbstractData()
- {
- this.leftPanelDisabled = ko.observable(false);
- this.useKeyboardShortcuts = ko.observable(true);
-
- this.keyScopeReal = ko.observable(Enums.KeyState.All);
- this.keyScopeFake = ko.observable(Enums.KeyState.All);
-
- this.keyScope = ko.computed({
- 'owner': this,
- 'read': function () {
- return this.keyScopeFake();
- },
- 'write': function (sValue) {
-
- if (Enums.KeyState.Menu !== sValue)
- {
- if (Enums.KeyState.Compose === sValue)
- {
- Utils.disableKeyFilter();
- }
- else
- {
- Utils.restoreKeyFilter();
- }
-
- this.keyScopeFake(sValue);
- if (Globals.dropdownVisibility())
- {
- sValue = Enums.KeyState.Menu;
- }
- }
-
- this.keyScopeReal(sValue);
- }
- });
-
- this.keyScopeReal.subscribe(function (sValue) {
- // window.console.log(sValue);
- key.setScope(sValue);
- });
-
- this.leftPanelDisabled.subscribe(function (bValue) {
- RL.pub('left-panel.' + (bValue ? 'off' : 'on')); // TODO cjs
- });
-
- Globals.dropdownVisibility.subscribe(function (bValue) {
- if (bValue)
- {
- Globals.tooltipTrigger(!Globals.tooltipTrigger());
- this.keyScope(Enums.KeyState.Menu);
- }
- else if (Enums.KeyState.Menu === key.getScope())
- {
- this.keyScope(this.keyScopeFake());
- }
- }, this);
-
- Utils.initDataConstructorBySettings(this);
- }
-
- AbstractData.prototype.populateDataOnStart = function()
- {
- var
- mLayout = Utils.pInt(RL.settingsGet('Layout')), // TODO cjs
- aLanguages = RL.settingsGet('Languages'),
- aThemes = RL.settingsGet('Themes')
- ;
-
- if (Utils.isArray(aLanguages))
- {
- this.languages(aLanguages);
- }
-
- if (Utils.isArray(aThemes))
- {
- this.themes(aThemes);
- }
-
- this.mainLanguage(RL.settingsGet('Language'));
- this.mainTheme(RL.settingsGet('Theme'));
-
- this.capaAdditionalAccounts(RL.capa(Enums.Capa.AdditionalAccounts));
- this.capaAdditionalIdentities(RL.capa(Enums.Capa.AdditionalIdentities));
- this.capaGravatar(RL.capa(Enums.Capa.Gravatar));
- this.determineUserLanguage(!!RL.settingsGet('DetermineUserLanguage'));
- this.determineUserDomain(!!RL.settingsGet('DetermineUserDomain'));
-
- this.capaThemes(RL.capa(Enums.Capa.Themes));
- this.allowLanguagesOnLogin(!!RL.settingsGet('AllowLanguagesOnLogin'));
- this.allowLanguagesOnSettings(!!RL.settingsGet('AllowLanguagesOnSettings'));
- this.useLocalProxyForExternalImages(!!RL.settingsGet('UseLocalProxyForExternalImages'));
-
- this.editorDefaultType(RL.settingsGet('EditorDefaultType'));
- this.showImages(!!RL.settingsGet('ShowImages'));
- this.contactsAutosave(!!RL.settingsGet('ContactsAutosave'));
- this.interfaceAnimation(RL.settingsGet('InterfaceAnimation'));
-
- this.mainMessagesPerPage(RL.settingsGet('MPP'));
-
- this.desktopNotifications(!!RL.settingsGet('DesktopNotifications'));
- this.useThreads(!!RL.settingsGet('UseThreads'));
- this.replySameFolder(!!RL.settingsGet('ReplySameFolder'));
- this.useCheckboxesInList(!!RL.settingsGet('UseCheckboxesInList'));
-
- this.layout(Enums.Layout.SidePreview);
- if (-1 < Utils.inArray(mLayout, [Enums.Layout.NoPreview, Enums.Layout.SidePreview, Enums.Layout.BottomPreview]))
- {
- this.layout(mLayout);
- }
- this.facebookSupported(!!RL.settingsGet('SupportedFacebookSocial'));
- this.facebookEnable(!!RL.settingsGet('AllowFacebookSocial'));
- this.facebookAppID(RL.settingsGet('FacebookAppID'));
- this.facebookAppSecret(RL.settingsGet('FacebookAppSecret'));
-
- this.twitterEnable(!!RL.settingsGet('AllowTwitterSocial'));
- this.twitterConsumerKey(RL.settingsGet('TwitterConsumerKey'));
- this.twitterConsumerSecret(RL.settingsGet('TwitterConsumerSecret'));
-
- this.googleEnable(!!RL.settingsGet('AllowGoogleSocial'));
- this.googleClientID(RL.settingsGet('GoogleClientID'));
- this.googleClientSecret(RL.settingsGet('GoogleClientSecret'));
- this.googleApiKey(RL.settingsGet('GoogleApiKey'));
-
- this.dropboxEnable(!!RL.settingsGet('AllowDropboxSocial'));
- this.dropboxApiKey(RL.settingsGet('DropboxApiKey'));
-
- this.contactsIsAllowed(!!RL.settingsGet('ContactsIsAllowed'));
- };
-
- module.exports = AbstractData;
-
-}(module));
-},{"../Common/Enums.js":5,"../Common/Globals.js":6,"../Common/Utils.js":9,"../External/key.js":20,"../External/ko.js":21}],36:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-(function (module) {
-
- 'use strict';
-
- var
- _ = require('../External/underscore.js'),
- CookieDriver = require('./LocalStorages/CookieDriver.js'),
- LocalStorageDriver = require('./LocalStorages/LocalStorageDriver.js')
- ;
-
- /**
- * @constructor
- */
- function LocalStorage()
- {
- var
- NextStorageDriver = _.find([LocalStorageDriver, CookieDriver], function (NextStorageDriver) {
- return NextStorageDriver.supported();
- })
- ;
-
- if (NextStorageDriver)
- {
- NextStorageDriver = /** @type {?Function} */ NextStorageDriver;
- this.oDriver = new NextStorageDriver();
- }
- }
-
- LocalStorage.prototype.oDriver = null;
-
- /**
- * @param {number} iKey
- * @param {*} mData
- * @return {boolean}
- */
- LocalStorage.prototype.set = function (iKey, mData)
- {
- return this.oDriver ? this.oDriver.set('p' + iKey, mData) : false;
- };
-
- /**
- * @param {number} iKey
- * @return {*}
- */
- LocalStorage.prototype.get = function (iKey)
- {
- return this.oDriver ? this.oDriver.get('p' + iKey) : null;
- };
-
- module.exports = new LocalStorage();
-
-}(module));
-},{"../External/underscore.js":24,"./LocalStorages/CookieDriver.js":37,"./LocalStorages/LocalStorageDriver.js":38}],37:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-(function (module) {
-
- 'use strict';
-
- var
- $ = require('../../External/jquery.js'),
- JSON = require('../../External/JSON.js'),
- Consts = require('../../Common/Consts.js'),
- Utils = require('../../Common/Utils.js')
- ;
-
- /**
- * @constructor
- */
- function CookieDriver()
- {
-
- }
-
- CookieDriver.supported = function ()
- {
- return true;
- };
-
- /**
- * @param {string} sKey
- * @param {*} mData
- * @returns {boolean}
- */
- CookieDriver.prototype.set = function (sKey, mData)
- {
- var
- mCokieValue = $.cookie(Consts.Values.ClientSideCookieIndexName),
- bResult = false,
- mResult = null
- ;
-
- try
- {
- mResult = null === mCokieValue ? null : JSON.parse(mCokieValue);
- if (!mResult)
- {
- mResult = {};
- }
-
- mResult[sKey] = mData;
- $.cookie(Consts.Values.ClientSideCookieIndexName, JSON.stringify(mResult), {
- 'expires': 30
- });
-
- bResult = true;
- }
- catch (oException) {}
-
- return bResult;
- };
-
- /**
- * @param {string} sKey
- * @returns {*}
- */
- CookieDriver.prototype.get = function (sKey)
- {
- var
- mCokieValue = $.cookie(Consts.Values.ClientSideCookieIndexName),
- mResult = null
- ;
-
- try
- {
- mResult = null === mCokieValue ? null : JSON.parse(mCokieValue);
- if (mResult && !Utils.isUnd(mResult[sKey]))
- {
- mResult = mResult[sKey];
- }
- else
- {
- mResult = null;
- }
- }
- catch (oException) {}
-
- return mResult;
- };
-
- module.exports = CookieDriver;
-
-}(module));
-},{"../../Common/Consts.js":4,"../../Common/Utils.js":9,"../../External/JSON.js":15,"../../External/jquery.js":19}],38:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-(function (module) {
-
- 'use strict';
-
- var
- window = require('../../External/window.js'),
- JSON = require('../../External/JSON.js'),
- Consts = require('../../Common/Consts.js'),
- Utils = require('../../Common/Utils.js')
- ;
-
- /**
- * @constructor
- */
- function LocalStorageDriver()
- {
- }
-
- LocalStorageDriver.supported = function ()
- {
- return !!window.localStorage;
- };
-
- /**
- * @param {string} sKey
- * @param {*} mData
- * @returns {boolean}
- */
- LocalStorageDriver.prototype.set = function (sKey, mData)
- {
- var
- mCookieValue = window.localStorage[Consts.Values.ClientSideCookieIndexName] || null,
- bResult = false,
- mResult = null
- ;
-
- try
- {
- mResult = null === mCookieValue ? null : JSON.parse(mCookieValue);
- if (!mResult)
- {
- mResult = {};
- }
-
- mResult[sKey] = mData;
- window.localStorage[Consts.Values.ClientSideCookieIndexName] = JSON.stringify(mResult);
-
- bResult = true;
- }
- catch (oException) {}
-
- return bResult;
- };
-
- /**
- * @param {string} sKey
- * @returns {*}
- */
- LocalStorageDriver.prototype.get = function (sKey)
- {
- var
- mCokieValue = window.localStorage[Consts.Values.ClientSideCookieIndexName] || null,
- mResult = null
- ;
-
- try
- {
- mResult = null === mCokieValue ? null : JSON.parse(mCokieValue);
- if (mResult && !Utils.isUnd(mResult[sKey]))
- {
- mResult = mResult[sKey];
- }
- else
- {
- mResult = null;
- }
- }
- catch (oException) {}
-
- return mResult;
- };
-
- module.exports = LocalStorageDriver;
-
-}(module));
-},{"../../Common/Consts.js":4,"../../Common/Utils.js":9,"../../External/JSON.js":15,"../../External/window.js":25}],39:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-(function (module) {
-
- 'use strict';
-
- var
- _ = require('../External/underscore.js'),
-
- Utils = require('../Common/Utils.js'),
-
- Cache = require('../Storages/WebMailCacheStorage.js'),
-
- AbstractAjaxRemoteStorage = require('./AbstractAjaxRemoteStorage.js')
- ;
-
- /**
- * @constructor
- * @extends AbstractAjaxRemoteStorage
- */
- function WebMailAjaxRemoteStorage()
- {
- AbstractAjaxRemoteStorage.call(this);
-
- this.oRequests = {};
- }
-
- _.extend(WebMailAjaxRemoteStorage.prototype, AbstractAjaxRemoteStorage.prototype);
-
- /**
- * @param {?Function} fCallback
- */
- WebMailAjaxRemoteStorage.prototype.folders = function (fCallback)
- {
- this.defaultRequest(fCallback, 'Folders', {
- 'SentFolder': RL.settingsGet('SentFolder'),
- 'DraftFolder': RL.settingsGet('DraftFolder'),
- 'SpamFolder': RL.settingsGet('SpamFolder'),
- 'TrashFolder': RL.settingsGet('TrashFolder'),
- 'ArchiveFolder': RL.settingsGet('ArchiveFolder')
- }, null, '', ['Folders']);
- };
-
- /**
- * @param {?Function} fCallback
- * @param {string} sEmail
- * @param {string} sLogin
- * @param {string} sPassword
- * @param {boolean} bSignMe
- * @param {string=} sLanguage
- * @param {string=} sAdditionalCode
- * @param {boolean=} bAdditionalCodeSignMe
- */
- WebMailAjaxRemoteStorage.prototype.login = function (fCallback, sEmail, sLogin, sPassword, bSignMe, sLanguage, sAdditionalCode, bAdditionalCodeSignMe)
- {
- this.defaultRequest(fCallback, 'Login', {
- 'Email': sEmail,
- 'Login': sLogin,
- 'Password': sPassword,
- 'Language': sLanguage || '',
- 'AdditionalCode': sAdditionalCode || '',
- 'AdditionalCodeSignMe': bAdditionalCodeSignMe ? '1' : '0',
- 'SignMe': bSignMe ? '1' : '0'
- });
- };
-
- /**
- * @param {?Function} fCallback
- */
- WebMailAjaxRemoteStorage.prototype.getTwoFactor = function (fCallback)
- {
- this.defaultRequest(fCallback, 'GetTwoFactorInfo');
- };
-
- /**
- * @param {?Function} fCallback
- */
- WebMailAjaxRemoteStorage.prototype.createTwoFactor = function (fCallback)
- {
- this.defaultRequest(fCallback, 'CreateTwoFactorSecret');
- };
-
- /**
- * @param {?Function} fCallback
- */
- WebMailAjaxRemoteStorage.prototype.clearTwoFactor = function (fCallback)
- {
- this.defaultRequest(fCallback, 'ClearTwoFactorInfo');
- };
-
- /**
- * @param {?Function} fCallback
- */
- WebMailAjaxRemoteStorage.prototype.showTwoFactorSecret = function (fCallback)
- {
- this.defaultRequest(fCallback, 'ShowTwoFactorSecret');
- };
-
- /**
- * @param {?Function} fCallback
- * @param {string} sCode
- */
- WebMailAjaxRemoteStorage.prototype.testTwoFactor = function (fCallback, sCode)
- {
- this.defaultRequest(fCallback, 'TestTwoFactorInfo', {
- 'Code': sCode
- });
- };
-
- /**
- * @param {?Function} fCallback
- * @param {boolean} bEnable
- */
- WebMailAjaxRemoteStorage.prototype.enableTwoFactor = function (fCallback, bEnable)
- {
- this.defaultRequest(fCallback, 'EnableTwoFactor', {
- 'Enable': bEnable ? '1' : '0'
- });
- };
-
- /**
- * @param {?Function} fCallback
- */
- WebMailAjaxRemoteStorage.prototype.clearTwoFactorInfo = function (fCallback)
- {
- this.defaultRequest(fCallback, 'ClearTwoFactorInfo');
- };
-
- /**
- * @param {?Function} fCallback
- */
- WebMailAjaxRemoteStorage.prototype.contactsSync = function (fCallback)
- {
- this.defaultRequest(fCallback, 'ContactsSync', null, Consts.Defaults.ContactsSyncAjaxTimeout);
- };
-
- /**
- * @param {?Function} fCallback
- * @param {boolean} bEnable
- * @param {string} sUrl
- * @param {string} sUser
- * @param {string} sPassword
- */
- WebMailAjaxRemoteStorage.prototype.saveContactsSyncData = function (fCallback, bEnable, sUrl, sUser, sPassword)
- {
- this.defaultRequest(fCallback, 'SaveContactsSyncData', {
- 'Enable': bEnable ? '1' : '0',
- 'Url': sUrl,
- 'User': sUser,
- 'Password': sPassword
- });
- };
-
- /**
- * @param {?Function} fCallback
- * @param {string} sEmail
- * @param {string} sLogin
- * @param {string} sPassword
- */
- WebMailAjaxRemoteStorage.prototype.accountAdd = function (fCallback, sEmail, sLogin, sPassword)
- {
- this.defaultRequest(fCallback, 'AccountAdd', {
- 'Email': sEmail,
- 'Login': sLogin,
- 'Password': sPassword
- });
- };
-
- /**
- * @param {?Function} fCallback
- * @param {string} sEmailToDelete
- */
- WebMailAjaxRemoteStorage.prototype.accountDelete = function (fCallback, sEmailToDelete)
- {
- this.defaultRequest(fCallback, 'AccountDelete', {
- 'EmailToDelete': sEmailToDelete
- });
- };
-
- /**
- * @param {?Function} fCallback
- * @param {string} sId
- * @param {string} sEmail
- * @param {string} sName
- * @param {string} sReplyTo
- * @param {string} sBcc
- */
- WebMailAjaxRemoteStorage.prototype.identityUpdate = function (fCallback, sId, sEmail, sName, sReplyTo, sBcc)
- {
- this.defaultRequest(fCallback, 'IdentityUpdate', {
- 'Id': sId,
- 'Email': sEmail,
- 'Name': sName,
- 'ReplyTo': sReplyTo,
- 'Bcc': sBcc
- });
- };
-
- /**
- * @param {?Function} fCallback
- * @param {string} sIdToDelete
- */
- WebMailAjaxRemoteStorage.prototype.identityDelete = function (fCallback, sIdToDelete)
- {
- this.defaultRequest(fCallback, 'IdentityDelete', {
- 'IdToDelete': sIdToDelete
- });
- };
-
- /**
- * @param {?Function} fCallback
- */
- WebMailAjaxRemoteStorage.prototype.accountsAndIdentities = function (fCallback)
- {
- this.defaultRequest(fCallback, 'AccountsAndIdentities');
- };
-
- /**
- * @param {?Function} fCallback
- * @param {string} sFolderFullNameRaw
- * @param {number=} iOffset = 0
- * @param {number=} iLimit = 20
- * @param {string=} sSearch = ''
- * @param {boolean=} bSilent = false
- */
- WebMailAjaxRemoteStorage.prototype.messageList = function (fCallback, sFolderFullNameRaw, iOffset, iLimit, sSearch, bSilent)
- {
- sFolderFullNameRaw = Utils.pString(sFolderFullNameRaw);
-
- var
- oData = RL.data(),
- sFolderHash = Cache.getFolderHash(sFolderFullNameRaw)
- ;
-
- bSilent = Utils.isUnd(bSilent) ? false : !!bSilent;
- iOffset = Utils.isUnd(iOffset) ? 0 : Utils.pInt(iOffset);
- iLimit = Utils.isUnd(iOffset) ? 20 : Utils.pInt(iLimit);
- sSearch = Utils.pString(sSearch);
-
- if ('' !== sFolderHash && ('' === sSearch || -1 === sSearch.indexOf('is:')))
- {
- this.defaultRequest(fCallback, 'MessageList', {},
- '' === sSearch ? Consts.Defaults.DefaultAjaxTimeout : Consts.Defaults.SearchAjaxTimeout,
- 'MessageList/' + Base64.urlsafe_encode([
- sFolderFullNameRaw,
- iOffset,
- iLimit,
- sSearch,
- oData.projectHash(),
- sFolderHash,
- 'INBOX' === sFolderFullNameRaw ? Cache.getFolderUidNext(sFolderFullNameRaw) : '',
- oData.threading() && oData.useThreads() ? '1' : '0',
- oData.threading() && sFolderFullNameRaw === oData.messageListThreadFolder() ? oData.messageListThreadUids().join(',') : ''
- ].join(String.fromCharCode(0))), bSilent ? [] : ['MessageList']);
- }
- else
- {
- this.defaultRequest(fCallback, 'MessageList', {
- 'Folder': sFolderFullNameRaw,
- 'Offset': iOffset,
- 'Limit': iLimit,
- 'Search': sSearch,
- 'UidNext': 'INBOX' === sFolderFullNameRaw ? Cache.getFolderUidNext(sFolderFullNameRaw) : '',
- 'UseThreads': RL.data().threading() && RL.data().useThreads() ? '1' : '0',
- 'ExpandedThreadUid': oData.threading() && sFolderFullNameRaw === oData.messageListThreadFolder() ? oData.messageListThreadUids().join(',') : ''
- }, '' === sSearch ? Consts.Defaults.DefaultAjaxTimeout : Consts.Defaults.SearchAjaxTimeout, '', bSilent ? [] : ['MessageList']);
- }
- };
-
- /**
- * @param {?Function} fCallback
- * @param {Array} aDownloads
- */
- WebMailAjaxRemoteStorage.prototype.messageUploadAttachments = function (fCallback, aDownloads)
- {
- this.defaultRequest(fCallback, 'MessageUploadAttachments', {
- 'Attachments': aDownloads
- }, 999000);
- };
-
- /**
- * @param {?Function} fCallback
- * @param {string} sFolderFullNameRaw
- * @param {number} iUid
- * @return {boolean}
- */
- WebMailAjaxRemoteStorage.prototype.message = function (fCallback, sFolderFullNameRaw, iUid)
- {
- sFolderFullNameRaw = Utils.pString(sFolderFullNameRaw);
- iUid = Utils.pInt(iUid);
-
- if (Cache.getFolderFromCacheList(sFolderFullNameRaw) && 0 < iUid)
- {
- this.defaultRequest(fCallback, 'Message', {}, null,
- 'Message/' + Base64.urlsafe_encode([
- sFolderFullNameRaw,
- iUid,
- RL.data().projectHash(),
- RL.data().threading() && RL.data().useThreads() ? '1' : '0'
- ].join(String.fromCharCode(0))), ['Message']);
-
- return true;
- }
-
- return false;
- };
-
- /**
- * @param {?Function} fCallback
- * @param {Array} aExternals
- */
- WebMailAjaxRemoteStorage.prototype.composeUploadExternals = function (fCallback, aExternals)
- {
- this.defaultRequest(fCallback, 'ComposeUploadExternals', {
- 'Externals': aExternals
- }, 999000);
- };
-
- /**
- * @param {?Function} fCallback
- * @param {string} sUrl
- * @param {string} sAccessToken
- */
- WebMailAjaxRemoteStorage.prototype.composeUploadDrive = function (fCallback, sUrl, sAccessToken)
- {
- this.defaultRequest(fCallback, 'ComposeUploadDrive', {
- 'AccessToken': sAccessToken,
- 'Url': sUrl
- }, 999000);
- };
-
- /**
- * @param {?Function} fCallback
- * @param {string} sFolder
- * @param {Array=} aList = []
- */
- WebMailAjaxRemoteStorage.prototype.folderInformation = function (fCallback, sFolder, aList)
- {
- var
- bRequest = true,
- aUids = []
- ;
-
- if (Utils.isArray(aList) && 0 < aList.length)
- {
- bRequest = false;
- _.each(aList, function (oMessageListItem) {
- if (!Cache.getMessageFlagsFromCache(oMessageListItem.folderFullNameRaw, oMessageListItem.uid))
- {
- aUids.push(oMessageListItem.uid);
- }
-
- if (0 < oMessageListItem.threads().length)
- {
- _.each(oMessageListItem.threads(), function (sUid) {
- if (!Cache.getMessageFlagsFromCache(oMessageListItem.folderFullNameRaw, sUid))
- {
- aUids.push(sUid);
- }
- });
- }
- });
-
- if (0 < aUids.length)
- {
- bRequest = true;
- }
- }
-
- if (bRequest)
- {
- this.defaultRequest(fCallback, 'FolderInformation', {
- 'Folder': sFolder,
- 'FlagsUids': Utils.isArray(aUids) ? aUids.join(',') : '',
- 'UidNext': 'INBOX' === sFolder ? Cache.getFolderUidNext(sFolder) : ''
- });
- }
- else if (RL.data().useThreads())
- {
- RL.reloadFlagsCurrentMessageListAndMessageFromCache();
- }
- };
-
- /**
- * @param {?Function} fCallback
- * @param {Array} aFolders
- */
- WebMailAjaxRemoteStorage.prototype.folderInformationMultiply = function (fCallback, aFolders)
- {
- this.defaultRequest(fCallback, 'FolderInformationMultiply', {
- 'Folders': aFolders
- });
- };
-
- /**
- * @param {?Function} fCallback
- */
- WebMailAjaxRemoteStorage.prototype.logout = function (fCallback)
- {
- this.defaultRequest(fCallback, 'Logout');
- };
-
- /**
- * @param {?Function} fCallback
- * @param {string} sFolderFullNameRaw
- * @param {Array} aUids
- * @param {boolean} bSetFlagged
- */
- WebMailAjaxRemoteStorage.prototype.messageSetFlagged = function (fCallback, sFolderFullNameRaw, aUids, bSetFlagged)
- {
- this.defaultRequest(fCallback, 'MessageSetFlagged', {
- 'Folder': sFolderFullNameRaw,
- 'Uids': aUids.join(','),
- 'SetAction': bSetFlagged ? '1' : '0'
- });
- };
-
- /**
- * @param {?Function} fCallback
- * @param {string} sFolderFullNameRaw
- * @param {Array} aUids
- * @param {boolean} bSetSeen
- */
- WebMailAjaxRemoteStorage.prototype.messageSetSeen = function (fCallback, sFolderFullNameRaw, aUids, bSetSeen)
- {
- this.defaultRequest(fCallback, 'MessageSetSeen', {
- 'Folder': sFolderFullNameRaw,
- 'Uids': aUids.join(','),
- 'SetAction': bSetSeen ? '1' : '0'
- });
- };
-
- /**
- * @param {?Function} fCallback
- * @param {string} sFolderFullNameRaw
- * @param {boolean} bSetSeen
- */
- WebMailAjaxRemoteStorage.prototype.messageSetSeenToAll = function (fCallback, sFolderFullNameRaw, bSetSeen)
- {
- this.defaultRequest(fCallback, 'MessageSetSeenToAll', {
- 'Folder': sFolderFullNameRaw,
- 'SetAction': bSetSeen ? '1' : '0'
- });
- };
-
- /**
- * @param {?Function} fCallback
- * @param {string} sMessageFolder
- * @param {string} sMessageUid
- * @param {string} sDraftFolder
- * @param {string} sFrom
- * @param {string} sTo
- * @param {string} sCc
- * @param {string} sBcc
- * @param {string} sSubject
- * @param {boolean} bTextIsHtml
- * @param {string} sText
- * @param {Array} aAttachments
- * @param {(Array|null)} aDraftInfo
- * @param {string} sInReplyTo
- * @param {string} sReferences
- */
- WebMailAjaxRemoteStorage.prototype.saveMessage = function (fCallback, sMessageFolder, sMessageUid, sDraftFolder,
- sFrom, sTo, sCc, sBcc, sSubject, bTextIsHtml, sText, aAttachments, aDraftInfo, sInReplyTo, sReferences)
- {
- this.defaultRequest(fCallback, 'SaveMessage', {
- 'MessageFolder': sMessageFolder,
- 'MessageUid': sMessageUid,
- 'DraftFolder': sDraftFolder,
- 'From': sFrom,
- 'To': sTo,
- 'Cc': sCc,
- 'Bcc': sBcc,
- 'Subject': sSubject,
- 'TextIsHtml': bTextIsHtml ? '1' : '0',
- 'Text': sText,
- 'DraftInfo': aDraftInfo,
- 'InReplyTo': sInReplyTo,
- 'References': sReferences,
- 'Attachments': aAttachments
- }, Consts.Defaults.SaveMessageAjaxTimeout);
- };
-
-
- /**
- * @param {?Function} fCallback
- * @param {string} sMessageFolder
- * @param {string} sMessageUid
- * @param {string} sReadReceipt
- * @param {string} sSubject
- * @param {string} sText
- */
- WebMailAjaxRemoteStorage.prototype.sendReadReceiptMessage = function (fCallback, sMessageFolder, sMessageUid, sReadReceipt, sSubject, sText)
- {
- this.defaultRequest(fCallback, 'SendReadReceiptMessage', {
- 'MessageFolder': sMessageFolder,
- 'MessageUid': sMessageUid,
- 'ReadReceipt': sReadReceipt,
- 'Subject': sSubject,
- 'Text': sText
- });
- };
-
- /**
- * @param {?Function} fCallback
- * @param {string} sMessageFolder
- * @param {string} sMessageUid
- * @param {string} sSentFolder
- * @param {string} sFrom
- * @param {string} sTo
- * @param {string} sCc
- * @param {string} sBcc
- * @param {string} sSubject
- * @param {boolean} bTextIsHtml
- * @param {string} sText
- * @param {Array} aAttachments
- * @param {(Array|null)} aDraftInfo
- * @param {string} sInReplyTo
- * @param {string} sReferences
- * @param {boolean} bRequestReadReceipt
- */
- WebMailAjaxRemoteStorage.prototype.sendMessage = function (fCallback, sMessageFolder, sMessageUid, sSentFolder,
- sFrom, sTo, sCc, sBcc, sSubject, bTextIsHtml, sText, aAttachments, aDraftInfo, sInReplyTo, sReferences, bRequestReadReceipt)
- {
- this.defaultRequest(fCallback, 'SendMessage', {
- 'MessageFolder': sMessageFolder,
- 'MessageUid': sMessageUid,
- 'SentFolder': sSentFolder,
- 'From': sFrom,
- 'To': sTo,
- 'Cc': sCc,
- 'Bcc': sBcc,
- 'Subject': sSubject,
- 'TextIsHtml': bTextIsHtml ? '1' : '0',
- 'Text': sText,
- 'DraftInfo': aDraftInfo,
- 'InReplyTo': sInReplyTo,
- 'References': sReferences,
- 'ReadReceiptRequest': bRequestReadReceipt ? '1' : '0',
- 'Attachments': aAttachments
- }, Consts.Defaults.SendMessageAjaxTimeout);
- };
-
- /**
- * @param {?Function} fCallback
- * @param {Object} oData
- */
- WebMailAjaxRemoteStorage.prototype.saveSystemFolders = function (fCallback, oData)
- {
- this.defaultRequest(fCallback, 'SystemFoldersUpdate', oData);
- };
-
- /**
- * @param {?Function} fCallback
- * @param {Object} oData
- */
- WebMailAjaxRemoteStorage.prototype.saveSettings = function (fCallback, oData)
- {
- this.defaultRequest(fCallback, 'SettingsUpdate', oData);
- };
-
- /**
- * @param {?Function} fCallback
- * @param {string} sPrevPassword
- * @param {string} sNewPassword
- */
- WebMailAjaxRemoteStorage.prototype.changePassword = function (fCallback, sPrevPassword, sNewPassword)
- {
- this.defaultRequest(fCallback, 'ChangePassword', {
- 'PrevPassword': sPrevPassword,
- 'NewPassword': sNewPassword
- });
- };
-
- /**
- * @param {?Function} fCallback
- * @param {string} sNewFolderName
- * @param {string} sParentName
- */
- WebMailAjaxRemoteStorage.prototype.folderCreate = function (fCallback, sNewFolderName, sParentName)
- {
- this.defaultRequest(fCallback, 'FolderCreate', {
- 'Folder': sNewFolderName,
- 'Parent': sParentName
- }, null, '', ['Folders']);
- };
-
- /**
- * @param {?Function} fCallback
- * @param {string} sFolderFullNameRaw
- */
- WebMailAjaxRemoteStorage.prototype.folderDelete = function (fCallback, sFolderFullNameRaw)
- {
- this.defaultRequest(fCallback, 'FolderDelete', {
- 'Folder': sFolderFullNameRaw
- }, null, '', ['Folders']);
- };
-
- /**
- * @param {?Function} fCallback
- * @param {string} sPrevFolderFullNameRaw
- * @param {string} sNewFolderName
- */
- WebMailAjaxRemoteStorage.prototype.folderRename = function (fCallback, sPrevFolderFullNameRaw, sNewFolderName)
- {
- this.defaultRequest(fCallback, 'FolderRename', {
- 'Folder': sPrevFolderFullNameRaw,
- 'NewFolderName': sNewFolderName
- }, null, '', ['Folders']);
- };
-
- /**
- * @param {?Function} fCallback
- * @param {string} sFolderFullNameRaw
- */
- WebMailAjaxRemoteStorage.prototype.folderClear = function (fCallback, sFolderFullNameRaw)
- {
- this.defaultRequest(fCallback, 'FolderClear', {
- 'Folder': sFolderFullNameRaw
- });
- };
-
- /**
- * @param {?Function} fCallback
- * @param {string} sFolderFullNameRaw
- * @param {boolean} bSubscribe
- */
- WebMailAjaxRemoteStorage.prototype.folderSetSubscribe = function (fCallback, sFolderFullNameRaw, bSubscribe)
- {
- this.defaultRequest(fCallback, 'FolderSubscribe', {
- 'Folder': sFolderFullNameRaw,
- 'Subscribe': bSubscribe ? '1' : '0'
- });
- };
-
- /**
- * @param {?Function} fCallback
- * @param {string} sFolder
- * @param {string} sToFolder
- * @param {Array} aUids
- * @param {string=} sLearning
- */
- WebMailAjaxRemoteStorage.prototype.messagesMove = function (fCallback, sFolder, sToFolder, aUids, sLearning)
- {
- this.defaultRequest(fCallback, 'MessageMove', {
- 'FromFolder': sFolder,
- 'ToFolder': sToFolder,
- 'Uids': aUids.join(','),
- 'Learning': sLearning || ''
- }, null, '', ['MessageList']);
- };
-
- /**
- * @param {?Function} fCallback
- * @param {string} sFolder
- * @param {string} sToFolder
- * @param {Array} aUids
- */
- WebMailAjaxRemoteStorage.prototype.messagesCopy = function (fCallback, sFolder, sToFolder, aUids)
- {
- this.defaultRequest(fCallback, 'MessageCopy', {
- 'FromFolder': sFolder,
- 'ToFolder': sToFolder,
- 'Uids': aUids.join(',')
- });
- };
-
- /**
- * @param {?Function} fCallback
- * @param {string} sFolder
- * @param {Array} aUids
- */
- WebMailAjaxRemoteStorage.prototype.messagesDelete = function (fCallback, sFolder, aUids)
- {
- this.defaultRequest(fCallback, 'MessageDelete', {
- 'Folder': sFolder,
- 'Uids': aUids.join(',')
- }, null, '', ['MessageList']);
- };
-
- /**
- * @param {?Function} fCallback
- */
- WebMailAjaxRemoteStorage.prototype.appDelayStart = function (fCallback)
- {
- this.defaultRequest(fCallback, 'AppDelayStart');
- };
-
- /**
- * @param {?Function} fCallback
- */
- WebMailAjaxRemoteStorage.prototype.quota = function (fCallback)
- {
- this.defaultRequest(fCallback, 'Quota');
- };
-
- /**
- * @param {?Function} fCallback
- * @param {number} iOffset
- * @param {number} iLimit
- * @param {string} sSearch
- */
- WebMailAjaxRemoteStorage.prototype.contacts = function (fCallback, iOffset, iLimit, sSearch)
- {
- this.defaultRequest(fCallback, 'Contacts', {
- 'Offset': iOffset,
- 'Limit': iLimit,
- 'Search': sSearch
- }, null, '', ['Contacts']);
- };
-
- /**
- * @param {?Function} fCallback
- */
- WebMailAjaxRemoteStorage.prototype.contactSave = function (fCallback, sRequestUid, sUid, sTags, aProperties)
- {
- this.defaultRequest(fCallback, 'ContactSave', {
- 'RequestUid': sRequestUid,
- 'Uid': Utils.trim(sUid),
- 'Tags': Utils.trim(sTags),
- 'Properties': aProperties
- });
- };
-
- /**
- * @param {?Function} fCallback
- * @param {Array} aUids
- */
- WebMailAjaxRemoteStorage.prototype.contactsDelete = function (fCallback, aUids)
- {
- this.defaultRequest(fCallback, 'ContactsDelete', {
- 'Uids': aUids.join(',')
- });
- };
-
- /**
- * @param {?Function} fCallback
- * @param {string} sQuery
- * @param {number} iPage
- */
- WebMailAjaxRemoteStorage.prototype.suggestions = function (fCallback, sQuery, iPage)
- {
- this.defaultRequest(fCallback, 'Suggestions', {
- 'Query': sQuery,
- 'Page': iPage
- }, null, '', ['Suggestions']);
- };
-
- /**
- * @param {?Function} fCallback
- */
- WebMailAjaxRemoteStorage.prototype.facebookUser = function (fCallback)
- {
- this.defaultRequest(fCallback, 'SocialFacebookUserInformation');
- };
-
- /**
- * @param {?Function} fCallback
- */
- WebMailAjaxRemoteStorage.prototype.facebookDisconnect = function (fCallback)
- {
- this.defaultRequest(fCallback, 'SocialFacebookDisconnect');
- };
-
- /**
- * @param {?Function} fCallback
- */
- WebMailAjaxRemoteStorage.prototype.twitterUser = function (fCallback)
- {
- this.defaultRequest(fCallback, 'SocialTwitterUserInformation');
- };
-
- /**
- * @param {?Function} fCallback
- */
- WebMailAjaxRemoteStorage.prototype.twitterDisconnect = function (fCallback)
- {
- this.defaultRequest(fCallback, 'SocialTwitterDisconnect');
- };
-
- /**
- * @param {?Function} fCallback
- */
- WebMailAjaxRemoteStorage.prototype.googleUser = function (fCallback)
- {
- this.defaultRequest(fCallback, 'SocialGoogleUserInformation');
- };
-
- /**
- * @param {?Function} fCallback
- */
- WebMailAjaxRemoteStorage.prototype.googleDisconnect = function (fCallback)
- {
- this.defaultRequest(fCallback, 'SocialGoogleDisconnect');
- };
-
- /**
- * @param {?Function} fCallback
- */
- WebMailAjaxRemoteStorage.prototype.socialUsers = function (fCallback)
- {
- this.defaultRequest(fCallback, 'SocialUsers');
- };
-
- module.exports = new WebMailAjaxRemoteStorage();
-
-}(module));
-},{"../Common/Utils.js":9,"../External/underscore.js":24,"../Storages/WebMailCacheStorage.js":40,"./AbstractAjaxRemoteStorage.js":34}],40:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-(function (module) {
-
- 'use strict';
-
- var
- _ = require('../External/underscore.js'),
-
- Enums = require('../Common/Enums.js'),
- Utils = require('../Common/Utils.js'),
- LinkBuilder = require('../Common/LinkBuilder.js'),
-
- RL = require('../RL.js')
- ;
-
- /**
- * @constructor
- */
- function WebMailCacheStorage()
- {
- this.oFoldersCache = {};
- this.oFoldersNamesCache = {};
- this.oFolderHashCache = {};
- this.oFolderUidNextCache = {};
- this.oMessageListHashCache = {};
- this.oMessageFlagsCache = {};
- this.oNewMessage = {};
- this.oRequestedMessage = {};
-
- this.bCapaGravatar = RL().capa(Enums.Capa.Gravatar);
- }
-
- /**
- * @type {boolean}
- */
- WebMailCacheStorage.prototype.bCapaGravatar = false;
-
- /**
- * @type {Object}
- */
- WebMailCacheStorage.prototype.oFoldersCache = {};
-
- /**
- * @type {Object}
- */
- WebMailCacheStorage.prototype.oFoldersNamesCache = {};
-
- /**
- * @type {Object}
- */
- WebMailCacheStorage.prototype.oFolderHashCache = {};
-
- /**
- * @type {Object}
- */
- WebMailCacheStorage.prototype.oFolderUidNextCache = {};
-
- /**
- * @type {Object}
- */
- WebMailCacheStorage.prototype.oMessageListHashCache = {};
-
- /**
- * @type {Object}
- */
- WebMailCacheStorage.prototype.oMessageFlagsCache = {};
-
- /**
- * @type {Object}
- */
- WebMailCacheStorage.prototype.oBodies = {};
-
- /**
- * @type {Object}
- */
- WebMailCacheStorage.prototype.oNewMessage = {};
-
- /**
- * @type {Object}
- */
- WebMailCacheStorage.prototype.oRequestedMessage = {};
-
- WebMailCacheStorage.prototype.clear = function ()
- {
- this.oFoldersCache = {};
- this.oFoldersNamesCache = {};
- this.oFolderHashCache = {};
- this.oFolderUidNextCache = {};
- this.oMessageListHashCache = {};
- this.oMessageFlagsCache = {};
- this.oBodies = {};
- };
-
-
- /**
- * @param {string} sEmail
- * @param {Function} fCallback
- * @return {string}
- */
- WebMailCacheStorage.prototype.getUserPic = function (sEmail, fCallback)
- {
- sEmail = Utils.trim(sEmail);
- fCallback(this.bCapaGravatar && '' !== sEmail ? LinkBuilder.avatarLink(sEmail) : '', sEmail);
- };
-
- /**
- * @param {string} sFolderFullNameRaw
- * @param {string} sUid
- * @return {string}
- */
- WebMailCacheStorage.prototype.getMessageKey = function (sFolderFullNameRaw, sUid)
- {
- return sFolderFullNameRaw + '#' + sUid;
- };
-
- /**
- * @param {string} sFolder
- * @param {string} sUid
- */
- WebMailCacheStorage.prototype.addRequestedMessage = function (sFolder, sUid)
- {
- this.oRequestedMessage[this.getMessageKey(sFolder, sUid)] = true;
- };
-
- /**
- * @param {string} sFolder
- * @param {string} sUid
- * @return {boolean}
- */
- WebMailCacheStorage.prototype.hasRequestedMessage = function (sFolder, sUid)
- {
- return true === this.oRequestedMessage[this.getMessageKey(sFolder, sUid)];
- };
-
- /**
- * @param {string} sFolderFullNameRaw
- * @param {string} sUid
- */
- WebMailCacheStorage.prototype.addNewMessageCache = function (sFolderFullNameRaw, sUid)
- {
- this.oNewMessage[this.getMessageKey(sFolderFullNameRaw, sUid)] = true;
- };
-
- /**
- * @param {string} sFolderFullNameRaw
- * @param {string} sUid
- */
- WebMailCacheStorage.prototype.hasNewMessageAndRemoveFromCache = function (sFolderFullNameRaw, sUid)
- {
- if (this.oNewMessage[this.getMessageKey(sFolderFullNameRaw, sUid)])
- {
- this.oNewMessage[this.getMessageKey(sFolderFullNameRaw, sUid)] = null;
- return true;
- }
-
- return false;
- };
-
- WebMailCacheStorage.prototype.clearNewMessageCache = function ()
- {
- this.oNewMessage = {};
- };
-
- /**
- * @param {string} sFolderHash
- * @return {string}
- */
- WebMailCacheStorage.prototype.getFolderFullNameRaw = function (sFolderHash)
- {
- return '' !== sFolderHash && this.oFoldersNamesCache[sFolderHash] ? this.oFoldersNamesCache[sFolderHash] : '';
- };
-
- /**
- * @param {string} sFolderHash
- * @param {string} sFolderFullNameRaw
- */
- WebMailCacheStorage.prototype.setFolderFullNameRaw = function (sFolderHash, sFolderFullNameRaw)
- {
- this.oFoldersNamesCache[sFolderHash] = sFolderFullNameRaw;
- };
-
- /**
- * @param {string} sFolderFullNameRaw
- * @return {string}
- */
- WebMailCacheStorage.prototype.getFolderHash = function (sFolderFullNameRaw)
- {
- return '' !== sFolderFullNameRaw && this.oFolderHashCache[sFolderFullNameRaw] ? this.oFolderHashCache[sFolderFullNameRaw] : '';
- };
-
- /**
- * @param {string} sFolderFullNameRaw
- * @param {string} sFolderHash
- */
- WebMailCacheStorage.prototype.setFolderHash = function (sFolderFullNameRaw, sFolderHash)
- {
- this.oFolderHashCache[sFolderFullNameRaw] = sFolderHash;
- };
-
- /**
- * @param {string} sFolderFullNameRaw
- * @return {string}
- */
- WebMailCacheStorage.prototype.getFolderUidNext = function (sFolderFullNameRaw)
- {
- return '' !== sFolderFullNameRaw && this.oFolderUidNextCache[sFolderFullNameRaw] ? this.oFolderUidNextCache[sFolderFullNameRaw] : '';
- };
-
- /**
- * @param {string} sFolderFullNameRaw
- * @param {string} sUidNext
- */
- WebMailCacheStorage.prototype.setFolderUidNext = function (sFolderFullNameRaw, sUidNext)
- {
- this.oFolderUidNextCache[sFolderFullNameRaw] = sUidNext;
- };
-
- /**
- * @param {string} sFolderFullNameRaw
- * @return {?FolderModel}
- */
- WebMailCacheStorage.prototype.getFolderFromCacheList = function (sFolderFullNameRaw)
- {
- return '' !== sFolderFullNameRaw && this.oFoldersCache[sFolderFullNameRaw] ? this.oFoldersCache[sFolderFullNameRaw] : null;
- };
-
- /**
- * @param {string} sFolderFullNameRaw
- * @param {?FolderModel} oFolder
- */
- WebMailCacheStorage.prototype.setFolderToCacheList = function (sFolderFullNameRaw, oFolder)
- {
- this.oFoldersCache[sFolderFullNameRaw] = oFolder;
- };
-
- /**
- * @param {string} sFolderFullNameRaw
- */
- WebMailCacheStorage.prototype.removeFolderFromCacheList = function (sFolderFullNameRaw)
- {
- this.setFolderToCacheList(sFolderFullNameRaw, null);
- };
-
- /**
- * @param {string} sFolderFullName
- * @param {string} sUid
- * @return {?Array}
- */
- WebMailCacheStorage.prototype.getMessageFlagsFromCache = function (sFolderFullName, sUid)
- {
- return this.oMessageFlagsCache[sFolderFullName] && this.oMessageFlagsCache[sFolderFullName][sUid] ?
- this.oMessageFlagsCache[sFolderFullName][sUid] : null;
- };
-
- /**
- * @param {string} sFolderFullName
- * @param {string} sUid
- * @param {Array} aFlagsCache
- */
- WebMailCacheStorage.prototype.setMessageFlagsToCache = function (sFolderFullName, sUid, aFlagsCache)
- {
- if (!this.oMessageFlagsCache[sFolderFullName])
- {
- this.oMessageFlagsCache[sFolderFullName] = {};
- }
-
- this.oMessageFlagsCache[sFolderFullName][sUid] = aFlagsCache;
- };
-
- /**
- * @param {string} sFolderFullName
- */
- WebMailCacheStorage.prototype.clearMessageFlagsFromCacheByFolder = function (sFolderFullName)
- {
- this.oMessageFlagsCache[sFolderFullName] = {};
- };
-
- /**
- * @param {(MessageModel|null)} oMessage
- */
- WebMailCacheStorage.prototype.initMessageFlagsFromCache = function (oMessage)
- {
- if (oMessage)
- {
- var
- self = this,
- aFlags = this.getMessageFlagsFromCache(oMessage.folderFullNameRaw, oMessage.uid),
- mUnseenSubUid = null,
- mFlaggedSubUid = null
- ;
-
- if (aFlags && 0 < aFlags.length)
- {
- oMessage.unseen(!!aFlags[0]);
- oMessage.flagged(!!aFlags[1]);
- oMessage.answered(!!aFlags[2]);
- oMessage.forwarded(!!aFlags[3]);
- oMessage.isReadReceipt(!!aFlags[4]);
- }
-
- if (0 < oMessage.threads().length)
- {
- mUnseenSubUid = _.find(oMessage.threads(), function (iSubUid) {
- var aFlags = self.getMessageFlagsFromCache(oMessage.folderFullNameRaw, iSubUid);
- return aFlags && 0 < aFlags.length && !!aFlags[0];
- });
-
- mFlaggedSubUid = _.find(oMessage.threads(), function (iSubUid) {
- var aFlags = self.getMessageFlagsFromCache(oMessage.folderFullNameRaw, iSubUid);
- return aFlags && 0 < aFlags.length && !!aFlags[1];
- });
-
- oMessage.hasUnseenSubMessage(mUnseenSubUid && 0 < Utils.pInt(mUnseenSubUid));
- oMessage.hasFlaggedSubMessage(mFlaggedSubUid && 0 < Utils.pInt(mFlaggedSubUid));
- }
- }
- };
-
- /**
- * @param {(MessageModel|null)} oMessage
- */
- WebMailCacheStorage.prototype.storeMessageFlagsToCache = function (oMessage)
- {
- if (oMessage)
- {
- this.setMessageFlagsToCache(
- oMessage.folderFullNameRaw,
- oMessage.uid,
- [oMessage.unseen(), oMessage.flagged(), oMessage.answered(), oMessage.forwarded(), oMessage.isReadReceipt()]
- );
- }
- };
- /**
- * @param {string} sFolder
- * @param {string} sUid
- * @param {Array} aFlags
- */
- WebMailCacheStorage.prototype.storeMessageFlagsToCacheByFolderAndUid = function (sFolder, sUid, aFlags)
- {
- if (Utils.isArray(aFlags) && 0 < aFlags.length)
- {
- this.setMessageFlagsToCache(sFolder, sUid, aFlags);
- }
- };
-
- module.exports = new WebMailCacheStorage();
-
-}(module));
-},{"../Common/Enums.js":5,"../Common/LinkBuilder.js":7,"../Common/Utils.js":9,"../External/underscore.js":24,"../RL.js":32}],41:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-(function (module) {
-
- 'use strict';
-
- var
- window = require('../External/window.js'),
- $ = require('../External/jquery.js'),
- _ = require('../External/underscore.js'),
- ko = require('../External/ko.js'),
- moment = require('../External/moment.js'),
- $div = require('../External/$div.js'),
- NotificationClass = require('../External/NotificationClass.js'),
-
- Consts = require('../Common/Consts.js'),
- Enums = require('../Common/Enums.js'),
- Globals = require('../Common/Globals.js'),
- Utils = require('../Common/Utils.js'),
- LinkBuilder = require('../Common/LinkBuilder.js'),
-
- Cache = require('../Storages/WebMailCacheStorage.js'),
- Remote = require('../Storages/WebMailAjaxRemoteStorage.js'),
-
- kn = require('../Knoin/Knoin.js'),
-
- MessageModel = require('../Models/MessageModel.js'),
-
- LocalStorage = require('./LocalStorage.js'),
- AbstractData = require('./AbstractData.js')
- ;
-
- /**
- * @constructor
- * @extends AbstractData
- */
- function WebMailDataStorage()
- {
- AbstractData.call(this);
-
- var
- fRemoveSystemFolderType = function (observable) {
- return function () {
- var oFolder = Cache.getFolderFromCacheList(observable()); // TODO cjs
- if (oFolder)
- {
- oFolder.type(Enums.FolderType.User);
- }
- };
- },
- fSetSystemFolderType = function (iType) {
- return function (sValue) {
- var oFolder = Cache.getFolderFromCacheList(sValue); // TODO cjs
- if (oFolder)
- {
- oFolder.type(iType);
- }
- };
- }
- ;
-
- this.devEmail = '';
- this.devPassword = '';
-
- this.accountEmail = ko.observable('');
- this.accountIncLogin = ko.observable('');
- this.accountOutLogin = ko.observable('');
- this.projectHash = ko.observable('');
- this.threading = ko.observable(false);
-
- this.lastFoldersHash = '';
- this.remoteSuggestions = false;
-
- // system folders
- this.sentFolder = ko.observable('');
- this.draftFolder = ko.observable('');
- this.spamFolder = ko.observable('');
- this.trashFolder = ko.observable('');
- this.archiveFolder = ko.observable('');
-
- this.sentFolder.subscribe(fRemoveSystemFolderType(this.sentFolder), this, 'beforeChange');
- this.draftFolder.subscribe(fRemoveSystemFolderType(this.draftFolder), this, 'beforeChange');
- this.spamFolder.subscribe(fRemoveSystemFolderType(this.spamFolder), this, 'beforeChange');
- this.trashFolder.subscribe(fRemoveSystemFolderType(this.trashFolder), this, 'beforeChange');
- this.archiveFolder.subscribe(fRemoveSystemFolderType(this.archiveFolder), this, 'beforeChange');
-
- this.sentFolder.subscribe(fSetSystemFolderType(Enums.FolderType.SentItems), this);
- this.draftFolder.subscribe(fSetSystemFolderType(Enums.FolderType.Draft), this);
- this.spamFolder.subscribe(fSetSystemFolderType(Enums.FolderType.Spam), this);
- this.trashFolder.subscribe(fSetSystemFolderType(Enums.FolderType.Trash), this);
- this.archiveFolder.subscribe(fSetSystemFolderType(Enums.FolderType.Archive), this);
-
- this.draftFolderNotEnabled = ko.computed(function () {
- return '' === this.draftFolder() || Consts.Values.UnuseOptionValue === this.draftFolder();
- }, this);
-
- // personal
- this.displayName = ko.observable('');
- this.signature = ko.observable('');
- this.signatureToAll = ko.observable(false);
- this.replyTo = ko.observable('');
-
- // security
- this.enableTwoFactor = ko.observable(false);
-
- // accounts
- this.accounts = ko.observableArray([]);
- this.accountsLoading = ko.observable(false).extend({'throttle': 100});
-
- // identities
- this.defaultIdentityID = ko.observable('');
- this.identities = ko.observableArray([]);
- this.identitiesLoading = ko.observable(false).extend({'throttle': 100});
-
- // contacts
- this.contactTags = ko.observableArray([]);
- this.contacts = ko.observableArray([]);
- this.contacts.loading = ko.observable(false).extend({'throttle': 200});
- this.contacts.importing = ko.observable(false).extend({'throttle': 200});
- this.contacts.syncing = ko.observable(false).extend({'throttle': 200});
- this.contacts.exportingVcf = ko.observable(false).extend({'throttle': 200});
- this.contacts.exportingCsv = ko.observable(false).extend({'throttle': 200});
-
- this.allowContactsSync = ko.observable(false);
- this.enableContactsSync = ko.observable(false);
- this.contactsSyncUrl = ko.observable('');
- this.contactsSyncUser = ko.observable('');
- this.contactsSyncPass = ko.observable('');
-
- this.allowContactsSync = ko.observable(!!RL.settingsGet('ContactsSyncIsAllowed')); // TODO cjs
- this.enableContactsSync = ko.observable(!!RL.settingsGet('EnableContactsSync'));
- this.contactsSyncUrl = ko.observable(RL.settingsGet('ContactsSyncUrl'));
- this.contactsSyncUser = ko.observable(RL.settingsGet('ContactsSyncUser'));
- this.contactsSyncPass = ko.observable(RL.settingsGet('ContactsSyncPassword'));
-
- // folders
- this.namespace = '';
- this.folderList = ko.observableArray([]);
- this.folderList.focused = ko.observable(false);
-
- this.foldersListError = ko.observable('');
-
- this.foldersLoading = ko.observable(false);
- this.foldersCreating = ko.observable(false);
- this.foldersDeleting = ko.observable(false);
- this.foldersRenaming = ko.observable(false);
-
- this.foldersChanging = ko.computed(function () {
- var
- bLoading = this.foldersLoading(),
- bCreating = this.foldersCreating(),
- bDeleting = this.foldersDeleting(),
- bRenaming = this.foldersRenaming()
- ;
- return bLoading || bCreating || bDeleting || bRenaming;
- }, this);
-
- this.foldersInboxUnreadCount = ko.observable(0);
-
- this.currentFolder = ko.observable(null).extend({'toggleSubscribe': [null,
- function (oPrev) {
- if (oPrev)
- {
- oPrev.selected(false);
- }
- }, function (oNext) {
- if (oNext)
- {
- oNext.selected(true);
- }
- }
- ]});
-
- this.currentFolderFullNameRaw = ko.computed(function () {
- return this.currentFolder() ? this.currentFolder().fullNameRaw : '';
- }, this);
-
- this.currentFolderFullName = ko.computed(function () {
- return this.currentFolder() ? this.currentFolder().fullName : '';
- }, this);
-
- this.currentFolderFullNameHash = ko.computed(function () {
- return this.currentFolder() ? this.currentFolder().fullNameHash : '';
- }, this);
-
- this.currentFolderName = ko.computed(function () {
- return this.currentFolder() ? this.currentFolder().name() : '';
- }, this);
-
- this.folderListSystemNames = ko.computed(function () {
-
- var
- aList = ['INBOX'],
- aFolders = this.folderList(),
- sSentFolder = this.sentFolder(),
- sDraftFolder = this.draftFolder(),
- sSpamFolder = this.spamFolder(),
- sTrashFolder = this.trashFolder(),
- sArchiveFolder = this.archiveFolder()
- ;
-
- if (Utils.isArray(aFolders) && 0 < aFolders.length)
- {
- if ('' !== sSentFolder && Consts.Values.UnuseOptionValue !== sSentFolder)
- {
- aList.push(sSentFolder);
- }
- if ('' !== sDraftFolder && Consts.Values.UnuseOptionValue !== sDraftFolder)
- {
- aList.push(sDraftFolder);
- }
- if ('' !== sSpamFolder && Consts.Values.UnuseOptionValue !== sSpamFolder)
- {
- aList.push(sSpamFolder);
- }
- if ('' !== sTrashFolder && Consts.Values.UnuseOptionValue !== sTrashFolder)
- {
- aList.push(sTrashFolder);
- }
- if ('' !== sArchiveFolder && Consts.Values.UnuseOptionValue !== sArchiveFolder)
- {
- aList.push(sArchiveFolder);
- }
- }
-
- return aList;
-
- }, this);
-
- this.folderListSystem = ko.computed(function () {
- return _.compact(_.map(this.folderListSystemNames(), function (sName) {
- return Cache.getFolderFromCacheList(sName); // TODO cjs
- }));
- }, this);
-
- this.folderMenuForMove = ko.computed(function () {
- return RL.folderListOptionsBuilder(this.folderListSystem(), this.folderList(), [// TODO cjs
- this.currentFolderFullNameRaw()
- ], null, null, null, null, function (oItem) {
- return oItem ? oItem.localName() : '';
- });
- }, this);
-
- // message list
- this.staticMessageList = [];
-
- this.messageList = ko.observableArray([]).extend({'rateLimit': 0});
-
- this.messageListCount = ko.observable(0);
- this.messageListSearch = ko.observable('');
- this.messageListPage = ko.observable(1);
-
- this.messageListThreadFolder = ko.observable('');
- this.messageListThreadUids = ko.observableArray([]);
-
- this.messageListThreadFolder.subscribe(function () {
- this.messageListThreadUids([]);
- }, this);
-
- this.messageListEndFolder = ko.observable('');
- this.messageListEndSearch = ko.observable('');
- this.messageListEndPage = ko.observable(1);
-
- this.messageListEndHash = ko.computed(function () {
- return this.messageListEndFolder() + '|' + this.messageListEndSearch() + '|' + this.messageListEndPage();
- }, this);
-
- this.messageListPageCount = ko.computed(function () {
- var iPage = window.Math.ceil(this.messageListCount() / this.messagesPerPage());
- return 0 >= iPage ? 1 : iPage;
- }, this);
-
- this.mainMessageListSearch = ko.computed({
- 'read': this.messageListSearch,
- 'write': function (sValue) {
- kn.setHash(LinkBuilder.mailBox( // TODO cjs
- this.currentFolderFullNameHash(), 1, Utils.trim(sValue.toString())
- ));
- },
- 'owner': this
- });
-
- this.messageListError = ko.observable('');
-
- this.messageListLoading = ko.observable(false);
- this.messageListIsNotCompleted = ko.observable(false);
- this.messageListCompleteLoadingThrottle = ko.observable(false).extend({'throttle': 200});
-
- this.messageListCompleteLoading = ko.computed(function () {
- var
- bOne = this.messageListLoading(),
- bTwo = this.messageListIsNotCompleted()
- ;
- return bOne || bTwo;
- }, this);
-
- this.messageListCompleteLoading.subscribe(function (bValue) {
- this.messageListCompleteLoadingThrottle(bValue);
- }, this);
-
- this.messageList.subscribe(_.debounce(function (aList) {
- _.each(aList, function (oItem) {
- if (oItem.newForAnimation())
- {
- oItem.newForAnimation(false);
- }
- });
- }, 500));
-
- // message preview
- this.staticMessageList = new MessageModel();// TODO cjs
- this.message = ko.observable(null);
- this.messageLoading = ko.observable(false);
- this.messageLoadingThrottle = ko.observable(false).extend({'throttle': 50});
-
- this.message.focused = ko.observable(false);
-
- this.message.subscribe(function (oMessage) {
- if (!oMessage)
- {
- this.message.focused(false);
- this.messageFullScreenMode(false);
- this.hideMessageBodies();
-
- if (Enums.Layout.NoPreview === RL.data().layout() &&// TODO cjs
- -1 < window.location.hash.indexOf('message-preview'))
- {
- RL.historyBack();// TODO cjs
- }
- }
- else if (Enums.Layout.NoPreview === this.layout())
- {
- this.message.focused(true);
- }
- }, this);
-
- this.message.focused.subscribe(function (bValue) {
- if (bValue)
- {
- this.folderList.focused(false);
- this.keyScope(Enums.KeyState.MessageView);
- }
- else if (Enums.KeyState.MessageView === RL.data().keyScope())// TODO cjs
- {
- if (Enums.Layout.NoPreview === RL.data().layout() && this.message())// TODO cjs
- {
- this.keyScope(Enums.KeyState.MessageView);
- }
- else
- {
- this.keyScope(Enums.KeyState.MessageList);
- }
- }
- }, this);
-
- this.folderList.focused.subscribe(function (bValue) {
- if (bValue)
- {
- RL.data().keyScope(Enums.KeyState.FolderList);// TODO cjs
- }
- else if (Enums.KeyState.FolderList === RL.data().keyScope())// TODO cjs
- {
- RL.data().keyScope(Enums.KeyState.MessageList);// TODO cjs
- }
- });
-
- this.messageLoading.subscribe(function (bValue) {
- this.messageLoadingThrottle(bValue);
- }, this);
-
- this.messageFullScreenMode = ko.observable(false);
-
- this.messageError = ko.observable('');
-
- this.messagesBodiesDom = ko.observable(null);
-
- this.messagesBodiesDom.subscribe(function (oDom) {
- if (oDom && !(oDom instanceof $))
- {
- this.messagesBodiesDom($(oDom));
- }
- }, this);
-
- this.messageActiveDom = ko.observable(null);
-
- this.isMessageSelected = ko.computed(function () {
- return null !== this.message();
- }, this);
-
- this.currentMessage = ko.observable(null);
-
- this.messageListChecked = ko.computed(function () {
- return _.filter(this.messageList(), function (oItem) {
- return oItem.checked();
- });
- }, this).extend({'rateLimit': 0});
-
- this.hasCheckedMessages = ko.computed(function () {
- return 0 < this.messageListChecked().length;
- }, this).extend({'rateLimit': 0});
-
- this.messageListCheckedOrSelected = ko.computed(function () {
-
- var
- aChecked = this.messageListChecked(),
- oSelectedMessage = this.currentMessage()
- ;
-
- return _.union(aChecked, oSelectedMessage ? [oSelectedMessage] : []);
-
- }, this);
-
- this.messageListCheckedOrSelectedUidsWithSubMails = ko.computed(function () {
- var aList = [];
- _.each(this.messageListCheckedOrSelected(), function (oMessage) {
- if (oMessage)
- {
- aList.push(oMessage.uid);
- if (0 < oMessage.threadsLen() && 0 === oMessage.parentUid() && oMessage.lastInCollapsedThread())
- {
- aList = _.union(aList, oMessage.threads());
- }
- }
- });
- return aList;
- }, this);
-
- // quota
- this.userQuota = ko.observable(0);
- this.userUsageSize = ko.observable(0);
- this.userUsageProc = ko.computed(function () {
-
- var
- iQuota = this.userQuota(),
- iUsed = this.userUsageSize()
- ;
-
- return 0 < iQuota ? window.Math.ceil((iUsed / iQuota) * 100) : 0;
-
- }, this);
-
- // other
- this.capaOpenPGP = ko.observable(false);
- this.openpgpkeys = ko.observableArray([]);
- this.openpgpKeyring = null;
-
- this.openpgpkeysPublic = this.openpgpkeys.filter(function (oItem) {
- return !!(oItem && !oItem.isPrivate);
- });
-
- this.openpgpkeysPrivate = this.openpgpkeys.filter(function (oItem) {
- return !!(oItem && oItem.isPrivate);
- });
-
- // google
- this.googleActions = ko.observable(false);
- this.googleLoggined = ko.observable(false);
- this.googleUserName = ko.observable('');
-
- // facebook
- this.facebookActions = ko.observable(false);
- this.facebookLoggined = ko.observable(false);
- this.facebookUserName = ko.observable('');
-
- // twitter
- this.twitterActions = ko.observable(false);
- this.twitterLoggined = ko.observable(false);
- this.twitterUserName = ko.observable('');
-
- this.customThemeType = ko.observable(Enums.CustomThemeType.Light);
-
- this.purgeMessageBodyCacheThrottle = _.throttle(this.purgeMessageBodyCache, 1000 * 30);
- }
-
- _.extend(WebMailDataStorage.prototype, AbstractData.prototype);
-
- WebMailDataStorage.prototype.purgeMessageBodyCache = function()
- {
- var
- iCount = 0,
- oMessagesBodiesDom = null,
- iEnd = Globals.iMessageBodyCacheCount - Consts.Values.MessageBodyCacheLimit
- ;
-
- if (0 < iEnd)
- {
- oMessagesBodiesDom = this.messagesBodiesDom();
- if (oMessagesBodiesDom)
- {
- oMessagesBodiesDom.find('.rl-cache-class').each(function () {
- var oItem = $(this);
- if (iEnd > oItem.data('rl-cache-count'))
- {
- oItem.addClass('rl-cache-purge');
- iCount++;
- }
- });
-
- if (0 < iCount)
- {
- _.delay(function () {
- oMessagesBodiesDom.find('.rl-cache-purge').remove();
- }, 300);
- }
- }
- }
- };
-
- WebMailDataStorage.prototype.populateDataOnStart = function()
- {
- AbstractData.prototype.populateDataOnStart.call(this);
-
- this.accountEmail(RL.settingsGet('Email'));// TODO cjs
- this.accountIncLogin(RL.settingsGet('IncLogin'));
- this.accountOutLogin(RL.settingsGet('OutLogin'));
- this.projectHash(RL.settingsGet('ProjectHash'));
-
- this.defaultIdentityID(RL.settingsGet('DefaultIdentityID'));
-
- this.displayName(RL.settingsGet('DisplayName'));
- this.replyTo(RL.settingsGet('ReplyTo'));
- this.signature(RL.settingsGet('Signature'));
- this.signatureToAll(!!RL.settingsGet('SignatureToAll'));
- this.enableTwoFactor(!!RL.settingsGet('EnableTwoFactor'));
-
- this.lastFoldersHash = LocalStorage.get(Enums.ClientSideKeyName.FoldersLashHash) || '';
-
- this.remoteSuggestions = !!RL.settingsGet('RemoteSuggestions');
-
- this.devEmail = RL.settingsGet('DevEmail');
- this.devPassword = RL.settingsGet('DevPassword');
- };
-
- WebMailDataStorage.prototype.initUidNextAndNewMessages = function (sFolder, sUidNext, aNewMessages)
- {
- if ('INBOX' === sFolder && Utils.isNormal(sUidNext) && sUidNext !== '')
- {
- if (Utils.isArray(aNewMessages) && 0 < aNewMessages.length)
- {
- var
- iIndex = 0,
- iLen = aNewMessages.length,
- fNotificationHelper = function (sImageSrc, sTitle, sText)
- {
- var oNotification = null;
- if (NotificationClass && RL.data().useDesktopNotifications())
- {
- oNotification = new NotificationClass(sTitle, {
- 'body': sText,
- 'icon': sImageSrc
- });
-
- if (oNotification)
- {
- if (oNotification.show)
- {
- oNotification.show();
- }
-
- window.setTimeout((function (oLocalNotifications) {
- return function () {
- if (oLocalNotifications.cancel)
- {
- oLocalNotifications.cancel();
- }
- else if (oLocalNotifications.close)
- {
- oLocalNotifications.close();
- }
- };
- }(oNotification)), 7000);
- }
- }
- }
- ;
-
- _.each(aNewMessages, function (oItem) {
- Cache.addNewMessageCache(sFolder, oItem.Uid);
- });
-
- if (3 < iLen)
- {
- fNotificationHelper(
- LinkBuilder.notificationMailIcon(),
- RL.data().accountEmail(),
- Utils.i18n('MESSAGE_LIST/NEW_MESSAGE_NOTIFICATION', {
- 'COUNT': iLen
- })
- );
- }
- else
- {
- for (; iIndex < iLen; iIndex++)
- {
- fNotificationHelper(
- LinkBuilder.notificationMailIcon(),
- MessageModel.emailsToLine(MessageModel.initEmailsFromJson(aNewMessages[iIndex].From), false),
- aNewMessages[iIndex].Subject
- );
- }
- }
- }
-
- Cache.setFolderUidNext(sFolder, sUidNext);
- }
- };
-
- /**
- * @param {string} sNamespace
- * @param {Array} aFolders
- * @return {Array}
- */
- WebMailDataStorage.prototype.folderResponseParseRec = function (sNamespace, aFolders)
- {
- var
- iIndex = 0,
- iLen = 0,
- oFolder = null,
- oCacheFolder = null,
- sFolderFullNameRaw = '',
- aSubFolders = [],
- aList = []
- ;
-
- for (iIndex = 0, iLen = aFolders.length; iIndex < iLen; iIndex++)
- {
- oFolder = aFolders[iIndex];
- if (oFolder)
- {
- sFolderFullNameRaw = oFolder.FullNameRaw;
-
- oCacheFolder = Cache.getFolderFromCacheList(sFolderFullNameRaw);// TODO cjs
- if (!oCacheFolder)
- {
- oCacheFolder = FolderModel.newInstanceFromJson(oFolder);// TODO cjs
- if (oCacheFolder)
- {
- Cache.setFolderToCacheList(sFolderFullNameRaw, oCacheFolder);// TODO cjs
- Cache.setFolderFullNameRaw(oCacheFolder.fullNameHash, sFolderFullNameRaw);// TODO cjs
- }
- }
-
- if (oCacheFolder)
- {
- oCacheFolder.collapsed(!Utils.isFolderExpanded(oCacheFolder.fullNameHash));
-
- if (oFolder.Extended)
- {
- if (oFolder.Extended.Hash)
- {
- Cache.setFolderHash(oCacheFolder.fullNameRaw, oFolder.Extended.Hash);// TODO cjs
- }
-
- if (Utils.isNormal(oFolder.Extended.MessageCount))
- {
- oCacheFolder.messageCountAll(oFolder.Extended.MessageCount);
- }
-
- if (Utils.isNormal(oFolder.Extended.MessageUnseenCount))
- {
- oCacheFolder.messageCountUnread(oFolder.Extended.MessageUnseenCount);
- }
- }
-
- aSubFolders = oFolder['SubFolders'];
- if (aSubFolders && 'Collection/FolderCollection' === aSubFolders['@Object'] &&
- aSubFolders['@Collection'] && Utils.isArray(aSubFolders['@Collection']))
- {
- oCacheFolder.subFolders(
- this.folderResponseParseRec(sNamespace, aSubFolders['@Collection']));
- }
-
- aList.push(oCacheFolder);
- }
- }
- }
-
- return aList;
- };
-
- /**
- * @param {*} oData
- */
- WebMailDataStorage.prototype.setFolders = function (oData)
- {
- var
- aList = [],
- bUpdate = false,
- oRLData = RL.data(),// TODO cjs
- fNormalizeFolder = function (sFolderFullNameRaw) {
- return ('' === sFolderFullNameRaw || Consts.Values.UnuseOptionValue === sFolderFullNameRaw ||
- null !== Cache.getFolderFromCacheList(sFolderFullNameRaw)) ? sFolderFullNameRaw : '';// TODO cjs
- }
- ;
-
- if (oData && oData.Result && 'Collection/FolderCollection' === oData.Result['@Object'] &&
- oData.Result['@Collection'] && Utils.isArray(oData.Result['@Collection']))
- {
- if (!Utils.isUnd(oData.Result.Namespace))
- {
- oRLData.namespace = oData.Result.Namespace;
- }
-
- this.threading(!!RL.settingsGet('UseImapThread') && oData.Result.IsThreadsSupported && true);// TODO cjs
-
- aList = this.folderResponseParseRec(oRLData.namespace, oData.Result['@Collection']);
- oRLData.folderList(aList);
-
- // TODO cjs
- if (oData.Result['SystemFolders'] &&
- '' === '' + RL.settingsGet('SentFolder') + RL.settingsGet('DraftFolder') +
- RL.settingsGet('SpamFolder') + RL.settingsGet('TrashFolder') + RL.settingsGet('ArchiveFolder') +
- RL.settingsGet('NullFolder'))
- {
- // TODO Magic Numbers
- RL.settingsSet('SentFolder', oData.Result['SystemFolders'][2] || null);
- RL.settingsSet('DraftFolder', oData.Result['SystemFolders'][3] || null);
- RL.settingsSet('SpamFolder', oData.Result['SystemFolders'][4] || null);
- RL.settingsSet('TrashFolder', oData.Result['SystemFolders'][5] || null);
- RL.settingsSet('ArchiveFolder', oData.Result['SystemFolders'][12] || null);
-
- bUpdate = true;
- }
-
- // TODO cjs
- oRLData.sentFolder(fNormalizeFolder(RL.settingsGet('SentFolder')));
- oRLData.draftFolder(fNormalizeFolder(RL.settingsGet('DraftFolder')));
- oRLData.spamFolder(fNormalizeFolder(RL.settingsGet('SpamFolder')));
- oRLData.trashFolder(fNormalizeFolder(RL.settingsGet('TrashFolder')));
- oRLData.archiveFolder(fNormalizeFolder(RL.settingsGet('ArchiveFolder')));
-
- if (bUpdate)
- {
- Remote.saveSystemFolders(Utils.emptyFunction, {
- 'SentFolder': oRLData.sentFolder(),
- 'DraftFolder': oRLData.draftFolder(),
- 'SpamFolder': oRLData.spamFolder(),
- 'TrashFolder': oRLData.trashFolder(),
- 'ArchiveFolder': oRLData.archiveFolder(),
- 'NullFolder': 'NullFolder'
- });
- }
-
- LocalStorage.set(Enums.ClientSideKeyName.FoldersLashHash, oData.Result.FoldersHash);
- }
- };
-
- WebMailDataStorage.prototype.hideMessageBodies = function ()
- {
- var oMessagesBodiesDom = this.messagesBodiesDom();
- if (oMessagesBodiesDom)
- {
- oMessagesBodiesDom.find('.b-text-part').hide();
- }
- };
-
- /**
- * @param {boolean=} bBoot = false
- * @returns {Array}
- */
- WebMailDataStorage.prototype.getNextFolderNames = function (bBoot)
- {
- bBoot = Utils.isUnd(bBoot) ? false : !!bBoot;
-
- var
- aResult = [],
- iLimit = 10,
- iUtc = moment().unix(),
- iTimeout = iUtc - 60 * 5,
- aTimeouts = [],
- fSearchFunction = function (aList) {
- _.each(aList, function (oFolder) {
- if (oFolder && 'INBOX' !== oFolder.fullNameRaw &&
- oFolder.selectable && oFolder.existen &&
- iTimeout > oFolder.interval &&
- (!bBoot || oFolder.subScribed()))
- {
- aTimeouts.push([oFolder.interval, oFolder.fullNameRaw]);
- }
-
- if (oFolder && 0 < oFolder.subFolders().length)
- {
- fSearchFunction(oFolder.subFolders());
- }
- });
- }
- ;
-
- fSearchFunction(this.folderList());
-
- aTimeouts.sort(function(a, b) {
- if (a[0] < b[0])
- {
- return -1;
- }
- else if (a[0] > b[0])
- {
- return 1;
- }
-
- return 0;
- });
-
- _.find(aTimeouts, function (aItem) {
- var oFolder = Cache.getFolderFromCacheList(aItem[1]);// TODO cjs
- if (oFolder)
- {
- oFolder.interval = iUtc;
- aResult.push(aItem[1]);
- }
-
- return iLimit <= aResult.length;
- });
-
- return _.uniq(aResult);
- };
-
- /**
- * @param {string} sFromFolderFullNameRaw
- * @param {Array} aUidForRemove
- * @param {string=} sToFolderFullNameRaw = ''
- * @param {bCopy=} bCopy = false
- */
- WebMailDataStorage.prototype.removeMessagesFromList = function (
- sFromFolderFullNameRaw, aUidForRemove, sToFolderFullNameRaw, bCopy)
- {
- sToFolderFullNameRaw = Utils.isNormal(sToFolderFullNameRaw) ? sToFolderFullNameRaw : '';
- bCopy = Utils.isUnd(bCopy) ? false : !!bCopy;
-
- aUidForRemove = _.map(aUidForRemove, function (mValue) {
- return Utils.pInt(mValue);
- });
-
- var
- iUnseenCount = 0,
- oData = RL.data(),// TODO cjs
- aMessageList = oData.messageList(),
- oFromFolder = Cache.getFolderFromCacheList(sFromFolderFullNameRaw),
- oToFolder = '' === sToFolderFullNameRaw ? null : Cache.getFolderFromCacheList(sToFolderFullNameRaw || ''),
- sCurrentFolderFullNameRaw = oData.currentFolderFullNameRaw(),
- oCurrentMessage = oData.message(),
- aMessages = sCurrentFolderFullNameRaw === sFromFolderFullNameRaw ? _.filter(aMessageList, function (oMessage) {
- return oMessage && -1 < Utils.inArray(Utils.pInt(oMessage.uid), aUidForRemove);
- }) : []
- ;
-
- _.each(aMessages, function (oMessage) {
- if (oMessage && oMessage.unseen())
- {
- iUnseenCount++;
- }
- });
-
- if (oFromFolder && !bCopy)
- {
- oFromFolder.messageCountAll(0 <= oFromFolder.messageCountAll() - aUidForRemove.length ?
- oFromFolder.messageCountAll() - aUidForRemove.length : 0);
-
- if (0 < iUnseenCount)
- {
- oFromFolder.messageCountUnread(0 <= oFromFolder.messageCountUnread() - iUnseenCount ?
- oFromFolder.messageCountUnread() - iUnseenCount : 0);
- }
- }
-
- if (oToFolder)
- {
- oToFolder.messageCountAll(oToFolder.messageCountAll() + aUidForRemove.length);
- if (0 < iUnseenCount)
- {
- oToFolder.messageCountUnread(oToFolder.messageCountUnread() + iUnseenCount);
- }
-
- oToFolder.actionBlink(true);
- }
-
- if (0 < aMessages.length)
- {
- if (bCopy)
- {
- _.each(aMessages, function (oMessage) {
- oMessage.checked(false);
- });
- }
- else
- {
- oData.messageListIsNotCompleted(true);
-
- _.each(aMessages, function (oMessage) {
- if (oCurrentMessage && oCurrentMessage.hash === oMessage.hash)
- {
- oCurrentMessage = null;
- oData.message(null);
- }
-
- oMessage.deleted(true);
- });
-
- _.delay(function () {
- _.each(aMessages, function (oMessage) {
- oData.messageList.remove(oMessage);
- });
- }, 400);
- }
- }
-
- if ('' !== sFromFolderFullNameRaw)
- {
- Cache.setFolderHash(sFromFolderFullNameRaw, '');
- }
-
- if ('' !== sToFolderFullNameRaw)
- {
- Cache.setFolderHash(sToFolderFullNameRaw, '');
- }
- };
-
- WebMailDataStorage.prototype.setMessage = function (oData, bCached)
- {
- var
- bIsHtml = false,
- bHasExternals = false,
- bHasInternals = false,
- oBody = null,
- oTextBody = null,
- sId = '',
- sResultHtml = '',
- bPgpSigned = false,
- bPgpEncrypted = false,
- oMessagesBodiesDom = this.messagesBodiesDom(),
- oMessage = this.message()
- ;
-
- if (oData && oMessage && oData.Result && 'Object/Message' === oData.Result['@Object'] &&
- oMessage.folderFullNameRaw === oData.Result.Folder && oMessage.uid === oData.Result.Uid)
- {
- this.messageError('');
-
- oMessage.initUpdateByMessageJson(oData.Result);
- Cache.addRequestedMessage(oMessage.folderFullNameRaw, oMessage.uid);// TODO cjs
-
- if (!bCached)
- {
- oMessage.initFlagsByJson(oData.Result);
- }
-
- oMessagesBodiesDom = oMessagesBodiesDom && oMessagesBodiesDom[0] ? oMessagesBodiesDom : null;
- if (oMessagesBodiesDom)
- {
- sId = 'rl-mgs-' + oMessage.hash.replace(/[^a-zA-Z0-9]/g, '');
- oTextBody = oMessagesBodiesDom.find('#' + sId);
- if (!oTextBody || !oTextBody[0])
- {
- bHasExternals = !!oData.Result.HasExternals;
- bHasInternals = !!oData.Result.HasInternals;
-
- oBody = $('').hide().addClass('rl-cache-class');
- oBody.data('rl-cache-count', ++Globals.iMessageBodyCacheCount);
-
- if (Utils.isNormal(oData.Result.Html) && '' !== oData.Result.Html)
- {
- bIsHtml = true;
- sResultHtml = oData.Result.Html.toString();
- }
- else if (Utils.isNormal(oData.Result.Plain) && '' !== oData.Result.Plain)
- {
- bIsHtml = false;
- sResultHtml = Utils.plainToHtml(oData.Result.Plain.toString(), false);
-
- if ((oMessage.isPgpSigned() || oMessage.isPgpEncrypted()) && RL.data().capaOpenPGP())
- {
- oMessage.plainRaw = Utils.pString(oData.Result.Plain);
-
- bPgpEncrypted = /---BEGIN PGP MESSAGE---/.test(oMessage.plainRaw);
- if (!bPgpEncrypted)
- {
- bPgpSigned = /-----BEGIN PGP SIGNED MESSAGE-----/.test(oMessage.plainRaw) &&
- /-----BEGIN PGP SIGNATURE-----/.test(oMessage.plainRaw);
- }
-
- $div.empty();
- if (bPgpSigned && oMessage.isPgpSigned())
- {
- sResultHtml =
- $div.append(
- $('').text(oMessage.plainRaw)
- ).html()
- ;
- }
- else if (bPgpEncrypted && oMessage.isPgpEncrypted())
- {
- sResultHtml =
- $div.append(
- $('').text(oMessage.plainRaw)
- ).html()
- ;
- }
-
- $div.empty();
-
- oMessage.isPgpSigned(bPgpSigned);
- oMessage.isPgpEncrypted(bPgpEncrypted);
- }
- }
- else
- {
- bIsHtml = false;
- }
-
- oBody
- .html(Utils.linkify(sResultHtml))
- .addClass('b-text-part ' + (bIsHtml ? 'html' : 'plain'))
- ;
-
- oMessage.isHtml(!!bIsHtml);
- oMessage.hasImages(!!bHasExternals);
- oMessage.pgpSignedVerifyStatus(Enums.SignedVerifyStatus.None);
- oMessage.pgpSignedVerifyUser('');
-
- oMessage.body = oBody;
- if (oMessage.body)
- {
- oMessagesBodiesDom.append(oMessage.body);
- }
-
- oMessage.storeDataToDom();
-
- if (bHasInternals)
- {
- oMessage.showInternalImages(true);
- }
-
- if (oMessage.hasImages() && this.showImages())
- {
- oMessage.showExternalImages(true);
- }
-
- this.purgeMessageBodyCacheThrottle();
- }
- else
- {
- oMessage.body = oTextBody;
- if (oMessage.body)
- {
- oMessage.body.data('rl-cache-count', ++Globals.iMessageBodyCacheCount);
- oMessage.fetchDataToDom();
- }
- }
-
- this.messageActiveDom(oMessage.body);
-
- this.hideMessageBodies();
- oMessage.body.show();
-
- if (oBody)
- {
- Utils.initBlockquoteSwitcher(oBody);
- }
- }
-
- Cache.initMessageFlagsFromCache(oMessage);
- if (oMessage.unseen())
- {
- RL.setMessageSeen(oMessage);
- }
-
- Utils.windowResize();
- }
- };
-
- /**
- * @param {Array} aList
- * @returns {string}
- */
- WebMailDataStorage.prototype.calculateMessageListHash = function (aList)
- {
- return _.map(aList, function (oMessage) {
- return '' + oMessage.hash + '_' + oMessage.threadsLen() + '_' + oMessage.flagHash();
- }).join('|');
- };
-
- WebMailDataStorage.prototype.setMessageList = function (oData, bCached)
- {
- if (oData && oData.Result && 'Collection/MessageCollection' === oData.Result['@Object'] &&
- oData.Result['@Collection'] && Utils.isArray(oData.Result['@Collection']))
- {
- var
- oRainLoopData = RL.data(),
- mLastCollapsedThreadUids = null,
- iIndex = 0,
- iLen = 0,
- iCount = 0,
- iOffset = 0,
- aList = [],
- iUtc = moment().unix(),
- aStaticList = oRainLoopData.staticMessageList,
- oJsonMessage = null,
- oMessage = null,
- oFolder = null,
- iNewCount = 0,
- bUnreadCountChange = false
- ;
-
- iCount = Utils.pInt(oData.Result.MessageResultCount);
- iOffset = Utils.pInt(oData.Result.Offset);
-
- if (Utils.isNonEmptyArray(oData.Result.LastCollapsedThreadUids))
- {
- mLastCollapsedThreadUids = oData.Result.LastCollapsedThreadUids;
- }
-
- oFolder = Cache.getFolderFromCacheList(
- Utils.isNormal(oData.Result.Folder) ? oData.Result.Folder : '');
-
- if (oFolder && !bCached)
- {
- oFolder.interval = iUtc;
-
- Cache.setFolderHash(oData.Result.Folder, oData.Result.FolderHash);
-
- if (Utils.isNormal(oData.Result.MessageCount))
- {
- oFolder.messageCountAll(oData.Result.MessageCount);
- }
-
- if (Utils.isNormal(oData.Result.MessageUnseenCount))
- {
- if (Utils.pInt(oFolder.messageCountUnread()) !== Utils.pInt(oData.Result.MessageUnseenCount))
- {
- bUnreadCountChange = true;
- }
-
- oFolder.messageCountUnread(oData.Result.MessageUnseenCount);
- }
-
- this.initUidNextAndNewMessages(oFolder.fullNameRaw, oData.Result.UidNext, oData.Result.NewMessages);
- }
-
- if (bUnreadCountChange && oFolder)
- {
- Cache.clearMessageFlagsFromCacheByFolder(oFolder.fullNameRaw);
- }
-
- for (iIndex = 0, iLen = oData.Result['@Collection'].length; iIndex < iLen; iIndex++)
- {
- oJsonMessage = oData.Result['@Collection'][iIndex];
- if (oJsonMessage && 'Object/Message' === oJsonMessage['@Object'])
- {
- oMessage = aStaticList[iIndex];
- if (!oMessage || !oMessage.initByJson(oJsonMessage))
- {
- oMessage = MessageModel.newInstanceFromJson(oJsonMessage);
- }
-
- if (oMessage)
- {
- if (Cache.hasNewMessageAndRemoveFromCache(oMessage.folderFullNameRaw, oMessage.uid) && 5 >= iNewCount)
- {
- iNewCount++;
- oMessage.newForAnimation(true);
- }
-
- oMessage.deleted(false);
-
- if (bCached)
- {
- Cache.initMessageFlagsFromCache(oMessage);
- }
- else
- {
- Cache.storeMessageFlagsToCache(oMessage);
- }
-
- oMessage.lastInCollapsedThread(mLastCollapsedThreadUids && -1 < Utils.inArray(Utils.pInt(oMessage.uid), mLastCollapsedThreadUids) ? true : false);
-
- aList.push(oMessage);
- }
- }
- }
-
- oRainLoopData.messageListCount(iCount);
- oRainLoopData.messageListSearch(Utils.isNormal(oData.Result.Search) ? oData.Result.Search : '');
- oRainLoopData.messageListPage(Math.ceil((iOffset / oRainLoopData.messagesPerPage()) + 1));
- oRainLoopData.messageListEndFolder(Utils.isNormal(oData.Result.Folder) ? oData.Result.Folder : '');
- oRainLoopData.messageListEndSearch(Utils.isNormal(oData.Result.Search) ? oData.Result.Search : '');
- oRainLoopData.messageListEndPage(oRainLoopData.messageListPage());
-
- oRainLoopData.messageList(aList);
- oRainLoopData.messageListIsNotCompleted(false);
-
- if (aStaticList.length < aList.length)
- {
- oRainLoopData.staticMessageList = aList;
- }
-
- Cache.clearNewMessageCache();
-
- if (oFolder && (bCached || bUnreadCountChange || RL.data().useThreads()))
- {
- RL.folderInformation(oFolder.fullNameRaw, aList);
- }
- }
- else
- {
- RL.data().messageListCount(0);
- RL.data().messageList([]);
- RL.data().messageListError(Utils.getNotification(
- oData && oData.ErrorCode ? oData.ErrorCode : Enums.Notification.CantGetMessageList
- ));
- }
- };
-
- WebMailDataStorage.prototype.findPublicKeyByHex = function (sHash)
- {
- return _.find(this.openpgpkeysPublic(), function (oItem) {
- return oItem && sHash === oItem.id;
- });
- };
-
- WebMailDataStorage.prototype.findPublicKeysByEmail = function (sEmail)
- {
- return _.compact(_.map(this.openpgpkeysPublic(), function (oItem) {
-
- var oKey = null;
- if (oItem && sEmail === oItem.email)
- {
- try
- {
- oKey = window.openpgp.key.readArmored(oItem.armor);
- if (oKey && !oKey.err && oKey.keys && oKey.keys[0])
- {
- return oKey.keys[0];
- }
- }
- catch (e) {}
- }
-
- return null;
-
- }));
- };
-
- /**
- * @param {string} sEmail
- * @param {string=} sPassword
- * @returns {?}
- */
- WebMailDataStorage.prototype.findPrivateKeyByEmail = function (sEmail, sPassword)
- {
- var
- oPrivateKey = null,
- oKey = _.find(this.openpgpkeysPrivate(), function (oItem) {
- return oItem && sEmail === oItem.email;
- })
- ;
-
- if (oKey)
- {
- try
- {
- oPrivateKey = window.openpgp.key.readArmored(oKey.armor);
- if (oPrivateKey && !oPrivateKey.err && oPrivateKey.keys && oPrivateKey.keys[0])
- {
- oPrivateKey = oPrivateKey.keys[0];
- oPrivateKey.decrypt(Utils.pString(sPassword));
- }
- else
- {
- oPrivateKey = null;
- }
- }
- catch (e)
- {
- oPrivateKey = null;
- }
- }
-
- return oPrivateKey;
- };
-
- /**
- * @param {string=} sPassword
- * @returns {?}
- */
- WebMailDataStorage.prototype.findSelfPrivateKey = function (sPassword)
- {
- return this.findPrivateKeyByEmail(this.accountEmail(), sPassword);
- };
-
- module.exports = new WebMailDataStorage();
-
-}(module));
-
-},{"../Common/Consts.js":4,"../Common/Enums.js":5,"../Common/Globals.js":6,"../Common/LinkBuilder.js":7,"../Common/Utils.js":9,"../External/$div.js":10,"../External/NotificationClass.js":16,"../External/jquery.js":19,"../External/ko.js":21,"../External/moment.js":22,"../External/underscore.js":24,"../External/window.js":25,"../Knoin/Knoin.js":26,"../Models/MessageModel.js":31,"../Storages/WebMailAjaxRemoteStorage.js":39,"../Storages/WebMailCacheStorage.js":40,"./AbstractData.js":35,"./LocalStorage.js":36}],42:[function(require,module,exports){
-/* RainLoop Webmail (c) RainLoop Team | Licensed under CC BY-NC-SA 3.0 */
-
-(function (module) {
-
- 'use strict';
-
- var
- ko = require('../../External/ko.js'),
- key = require('../../External/key.js'),
- Enums = require('../../Common/Enums.js'),
- Utils = require('../../Common/Utils.js'),
- kn = require('../../Knoin/Knoin.js'),
- KnoinAbstractViewModel = require('../../Knoin/KnoinAbstractViewModel.js')
- ;
-
- /**
- * @constructor
- * @extends KnoinAbstractViewModel
- */
- function PopupsAskViewModel()
- {
- KnoinAbstractViewModel.call(this, 'Popups', 'PopupsAsk');
-
- this.askDesc = ko.observable('');
- this.yesButton = ko.observable('');
- this.noButton = ko.observable('');
-
- this.yesFocus = ko.observable(false);
- this.noFocus = ko.observable(false);
-
- this.fYesAction = null;
- this.fNoAction = null;
-
- this.bDisabeCloseOnEsc = true;
- this.sDefaultKeyScope = Enums.KeyState.PopupAsk;
-
- kn.constructorEnd(this);
- }
-
- kn.extendAsViewModel('PopupsAskViewModel', PopupsAskViewModel);
-
- PopupsAskViewModel.prototype.clearPopup = function ()
- {
- this.askDesc('');
- this.yesButton(Utils.i18n('POPUPS_ASK/BUTTON_YES'));
- this.noButton(Utils.i18n('POPUPS_ASK/BUTTON_NO'));
-
- this.yesFocus(false);
- this.noFocus(false);
-
- this.fYesAction = null;
- this.fNoAction = null;
- };
-
- PopupsAskViewModel.prototype.yesClick = function ()
- {
- this.cancelCommand();
-
- if (Utils.isFunc(this.fYesAction))
- {
- this.fYesAction.call(null);
- }
- };
-
- PopupsAskViewModel.prototype.noClick = function ()
- {
- this.cancelCommand();
-
- if (Utils.isFunc(this.fNoAction))
- {
- this.fNoAction.call(null);
- }
- };
-
- /**
- * @param {string} sAskDesc
- * @param {Function=} fYesFunc
- * @param {Function=} fNoFunc
- * @param {string=} sYesButton
- * @param {string=} sNoButton
- */
- PopupsAskViewModel.prototype.onShow = function (sAskDesc, fYesFunc, fNoFunc, sYesButton, sNoButton)
- {
- this.clearPopup();
-
- this.fYesAction = fYesFunc || null;
- this.fNoAction = fNoFunc || null;
-
- this.askDesc(sAskDesc || '');
- if (sYesButton)
- {
- this.yesButton(sYesButton);
- }
-
- if (sYesButton)
- {
- this.yesButton(sNoButton);
- }
- };
-
- PopupsAskViewModel.prototype.onFocus = function ()
- {
- this.yesFocus(true);
- };
-
- PopupsAskViewModel.prototype.onBuild = function ()
- {
- key('tab, shift+tab, right, left', Enums.KeyState.PopupAsk, _.bind(function () {
- if (this.yesFocus())
- {
- this.noFocus(true);
- }
- else
- {
- this.yesFocus(true);
- }
- return false;
- }, this));
-
- key('esc', Enums.KeyState.PopupAsk, _.bind(function () {
- this.noClick();
- return false;
- }, this));
- };
-
- module.exports = new PopupsAskViewModel();
-
-}(module));
-},{"../../Common/Enums.js":5,"../../Common/Utils.js":9,"../../External/key.js":20,"../../External/ko.js":21,"../../Knoin/Knoin.js":26,"../../Knoin/KnoinAbstractViewModel.js":28}]},{},[1]);