eslint (additional rules)

This commit is contained in:
RainLoop Team 2016-06-30 03:02:45 +03:00
parent 77a1d3f3df
commit 8e8a041032
150 changed files with 21911 additions and 23106 deletions

168
.eslintrc
View file

@ -1,168 +0,0 @@
{
"ecmaFeatures": {
"modules": true
},
"env": {
"node": true,
"commonjs": true,
"es6": true,
"browser": true
},
"globals": {
"RL_COMMUNITY" : true,
"ko" : true,
"ssm" : true,
"moment" : true,
"ifvisible" : true,
"crossroads" : true,
"hasher" : true,
"key" : true,
"Jua" : true,
"_" : true,
"$" : true,
"Dropbox" : true
},
"rules": {
"comma-dangle": [2, "never"],
"no-cond-assign": 2,
"no-console": 2,
"no-constant-condition": 2,
"no-control-regex": 2,
"no-debugger": 2,
"no-dupe-keys": 2,
"no-empty": 2,
"no-empty-character-class": 2,
"no-ex-assign": 2,
"no-extra-boolean-cast": 2,
"no-extra-parens": 0,
"no-extra-semi": 2,
"no-func-assign": 2,
"no-inner-declarations": 2,
"no-invalid-regexp": 2,
"no-irregular-whitespace": 2,
"no-negated-in-lhs": 2,
"no-obj-calls": 2,
"no-regex-spaces": 2,
"no-reserved-keys": 0,
"no-sparse-arrays": 2,
"no-unreachable": 2,
"use-isnan": 2,
"valid-jsdoc": 0,
"valid-typeof": 2,
// Best Practices
"block-scoped-var": 2,
"complexity": 0,
"consistent-return": 2,
"curly": 2,
// "default-case": 2,
"dot-notation": 2,
"eqeqeq": 2,
"guard-for-in": 2,
"no-alert": 2,
"no-caller": 2,
"no-div-regex": 2,
"no-else-return": 2,
"no-eq-null": 2,
"no-eval": 2,
"no-extend-native": 2,
"no-extra-bind": 2,
"no-fallthrough": 2,
"no-floating-decimal": 2,
"no-implied-eval": 2,
"no-iterator": 2,
"no-labels": 2,
"no-lone-blocks": 2,
"no-loop-func": 2,
"no-multi-spaces": 2,
"no-multi-str": 0,
"no-native-reassign": 2,
"no-new": 2,
"no-new-func": 2,
"no-new-wrappers": 2,
"no-octal": 2,
"no-octal-escape": 2,
"no-process-env": 2,
"no-proto": 2,
"no-redeclare": 2,
"no-return-assign": 2,
"no-script-url": 2,
"no-self-compare": 2,
"no-sequences": 2,
"no-unused-expressions": 2,
"no-void": 0,
"no-warning-comments": 2,
"no-with": 2,
"radix": 2,
"vars-on-top": 0,
"wrap-iife": 2,
"yoda": 0,
// Strict Mode
"strict": 0,
// Variables
"no-catch-shadow": 2,
"no-delete-var": 2,
"no-label-var": 2,
"no-shadow": 2,
"no-shadow-restricted-names": 2,
"no-undef": 2,
"no-undef-init": 2,
"no-undefined": 2,
"no-unused-vars": 2,
"no-use-before-define": 2,
// Stylistic Issues
// "indent": [2, "tab", {
// "SwitchCase": 1,
// "VariableDeclarator": 1
// }],
"camelcase": 0,
"comma-spacing": 2,
"comma-style": 2,
"consistent-this": 0,
"eol-last": 2,
"func-names": 0,
"func-style": 0,
"key-spacing": [2, {
"beforeColon": false,
"afterColon": true
}],
"max-nested-callbacks": 0,
"new-cap": 2,
"new-parens": 2,
"no-array-constructor": 2,
"no-inline-comments": 0,
// "no-lonely-if": 2,
"no-mixed-spaces-and-tabs": 2,
// "no-nested-ternary": 2,
"no-new-object": 2,
"semi-spacing": [2, {
"before": false,
"after": true
}],
"no-spaced-func": 2,
"no-ternary": 0,
"no-trailing-spaces": 2,
"no-multiple-empty-lines": 2,
"no-underscore-dangle": 0,
"one-var": 0,
"operator-assignment": [2, "always"],
"padded-blocks": 0,
"quotes": [2, "single"],
"quote-props": 0,
"semi": [2, "always"],
// "sort-vars": [2, {"ignoreCase": true}],
"space-before-blocks": 2,
"object-curly-spacing": [2, "never"],
"array-bracket-spacing": [2, "never"],
"space-in-parens": 2,
"space-infix-ops": 2,
"space-unary-ops": 2,
"spaced-comment": 2,
"wrap-regex": 0,
"max-depth": 0,
"max-len": [2, 200],
"max-params": 0,
"max-statements": 0,
"no-plusplus": 0
}
}

237
.eslintrc.js Normal file
View file

@ -0,0 +1,237 @@
module.exports = {
"extends": "eslint:recommended",
"ecmaFeatures": {
"modules": true
},
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module"
},
"env": {
"node": true,
"commonjs": true,
"es6": true,
"browser": true
},
"globals": {
"RL_COMMUNITY": true,
"ko": true,
"ssm": true,
"moment": true,
"ifvisible": true,
"crossroads": true,
"hasher": true,
"key": true,
"Jua": true,
"_": true,
"$": true,
"Dropbox": true
},
"rules": {
"strict": 2, // require or disallow strict mode directives
// errors
"comma-dangle": [2, "never"], // disallow or enforce trailing commas
"no-cond-assign": [2, "always"], // disallow assignment in conditional expressions
"no-console": 1, // disallow use of console (off by default in the node environment)
"no-constant-condition": 2, // disallow use of constant expressions in conditions
"no-control-regex": 2, // disallow control characters in regular expressions
"no-debugger": 2, // disallow use of debugger
"no-dupe-args": 2, // disallow duplicate arguments in functions
"no-dupe-keys": 2, // disallow duplicate keys when creating object literals
"no-duplicate-case": 2, // disallow a duplicate case label.
"no-empty": 2, // disallow empty statements
"no-empty-character-class": 2, // disallow the use of empty character classes in regular expressions
"no-ex-assign": 2, // disallow assigning to the exception in a catch block
"no-extra-boolean-cast": 2, // disallow double-negation boolean casts in a boolean context
"no-extra-parens": 0, // disallow unnecessary parentheses (off by default)
"no-extra-semi": 2, // disallow unnecessary semicolons
"no-func-assign": 2, // disallow overwriting functions written as function declarations
"no-inner-declarations": 2, // disallow function or variable declarations in nested blocks
"no-invalid-regexp": 2, // disallow invalid regular expression strings in the RegExp constructor
"no-irregular-whitespace": 2, // disallow irregular whitespace outside of strings and comments
"no-negated-in-lhs": 2, // disallow negation of the left operand of an in expression
"no-obj-calls": 2, // disallow the use of object properties of the global object (Math and JSON) as functions
"no-regex-spaces": 2, // disallow multiple spaces in a regular expression literal
"no-sparse-arrays": 2, // disallow sparse arrays
"no-unexpected-multiline": 2, // disallow confusing multiline expressions
"no-unreachable": 2, // disallow unreachable statements after a return, throw, continue, or break statement
"use-isnan": 2, // disallow comparisons with the value NaN
"valid-typeof": 2, // Ensure that the results of typeof are compared against a valid string
// "valid-jsdoc": [2, { // Ensure JSDoc comments are valid (off by default)
// "requireParamDescription": false,
// "requireReturnDescription": false
// }],
// best practices
"accessor-pairs": 2, // enforce getter and setter pairs in objects
"block-scoped-var": 2, // treat var statements as if they were block scoped (off by default). 0: deep destructuring is not compatible https://github.com/eslint/eslint/issues/1863
// "complexity": 0, // specify the maximum cyclomatic complexity allowed in a program (off by default)
"consistent-return": 2, // require return statements to either always or never specify values
"curly": 2, // specify curly brace conventions for all control statements
"default-case": 2, // require default case in switch statements (off by default)
"dot-location": [2, "property"], // enforce consistent newlines before and after dots
"dot-notation": 2, // encourages use of dot notation whenever possible
"eqeqeq": 2, // require the use of === and !==
"guard-for-in": 2, // make sure for-in loops have an if statement (off by default)
"no-alert": 2, // disallow the use of alert, confirm, and prompt
"no-caller": 2, // disallow use of arguments.caller or arguments.callee
"no-div-regex": 2, // disallow division operators explicitly at beginning of regular expression (off by default)
"no-else-return": 2, // disallow else after a return in an if (off by default)
"no-empty-label": 2, // disallow use of labels for anything other then loops and switches
"no-eq-null": 2, // disallow comparisons to null without a type-checking operator (off by default)
"no-eval": 2, // disallow use of eval()
"no-extend-native": 2, // disallow adding to native types
"no-extra-bind": 2, // disallow unnecessary function binding
"no-fallthrough": 2, // disallow fallthrough of case statements
"no-floating-decimal": 2, // disallow the use of leading or trailing decimal points in numeric literals (off by default)
"no-implied-eval": 2, // disallow use of eval()-like methods
"no-iterator": 2, // disallow usage of __iterator__ property
"no-labels": 2, // disallow use of labeled statements
"no-lone-blocks": 2, // disallow unnecessary nested blocks
"no-loop-func": 2, // disallow creation of functions within loops
"no-multi-spaces": 2, // disallow use of multiple spaces
"no-multi-str": 2, // disallow use of multiline strings
"no-native-reassign": 2, // disallow reassignments of native objects
"no-new": 2, // disallow use of new operator when not part of the assignment or comparison
"no-new-func": 2, // disallow use of new operator for Function object
"no-new-wrappers": 2, // disallows creating new instances of String,Number, and Boolean
"no-octal": 2, // disallow use of octal literals
"no-octal-escape": 2, // disallow use of octal escape sequences in string literals, such as var foo = "Copyright \251";
// "no-param-reassign": 2, // disallow reassignment of function parameters (off by default)
"no-process-env": 2, // disallow use of process.env (off by default)
"no-proto": 2, // disallow usage of __proto__ property
"no-redeclare": 2, // disallow declaring the same variable more then once
"no-return-assign": 2, // disallow use of assignment in return statement
"no-script-url": 2, // disallow use of javascript: urls.
"no-self-compare": 2, // disallow comparisons where both sides are exactly the same (off by default)
"no-sequences": 2, // disallow use of comma operator
"no-throw-literal": 2, // restrict what can be thrown as an exception (off by default)
"no-unused-expressions": 2, // disallow usage of expressions in statement position
"no-void": 2, // disallow use of void operator (off by default)
"no-warning-comments": 1, // disallow usage of configurable warning terms in comments": 2, // e.g. TODO or FIXME (off by default)
"no-with": 2, // disallow use of the with statement
"radix": 2, // require use of the second argument for parseInt() (off by default)
// "vars-on-top": 2, // requires to declare all vars on top of their containing scope (off by default)
"wrap-iife": 2, // require immediate function invocation to be wrapped in parentheses (off by default)
"yoda": [2, "always"], // require or disallow Yoda conditions
// variables
"no-catch-shadow": 2, // disallow the catch clause parameter name being the same as a variable in the outer scope (off by default in the node environment)
"no-delete-var": 2, // disallow deletion of variables
"no-label-var": 2, // disallow labels that share a name with a variable
"no-shadow": 2, // disallow declaration of variables already declared in the outer scope
"no-shadow-restricted-names": 2, // disallow shadowing of names such as arguments
"no-undef": 2, // disallow use of undeclared variables unless mentioned in a /*global */ block
"no-undef-init": 2, // disallow use of undefined when initializing variables
"no-undefined": 2, // disallow use of undefined variable (off by default)
"no-unused-vars": 2, // disallow declaration of variables that are not used in the code
"no-use-before-define": 2, // disallow use of variables before they are defined
// stylistic issues
"array-bracket-spacing": 1, // enforce consistent spacing inside array brackets
"block-spacing": [1, "never"], // enforce consistent spacing inside single-line blocks
// "brace-style": [1, "1tbs"], // enforce consistent brace style for blocks
// "camelcase": 1, // enforce camelcase naming convention
"comma-spacing": 1, // enforce consistent spacing before and after commas
"comma-style": 1, // enforce consistent comma style
"computed-property-spacing": 1, // enforce consistent spacing inside computed property brackets
"consistent-this": [1, "self"], // enforce consistent naming when capturing the current execution context
"eol-last": 1, // enforce at least one newline at the end of files
"id-match": 1, // require identifiers to match a specified regular expression
"indent": [1, "tab", { // enforce consistent indentation
"SwitchCase": 1,
"VariableDeclarator": {
"var": 1,
"let": 1,
"const": 1
}
}],
"key-spacing": 1, // enforce consistent spacing between keys and values in object literal properties
"linebreak-style": [1, "windows"], // enforce consistent linebreak style
"lines-around-comment": 0, // require empty lines around comments
"max-depth": 0, // enforce a maximum depth that blocks can be nested
"max-len": [1, 200], // enforce a maximum line length
"max-lines": 0, // enforce a maximum file length
"max-nested-callbacks": [1, 5], // enforce a maximum depth that callbacks can be nested
"max-params": 0, // enforce a maximum number of parameters in function definitions
"max-statements": 0, // enforce a maximum number of statements allowed in function blocks
"max-statements-per-line": 0, // enforce a maximum number of statements allowed per line
"new-cap": 1, // require constructor function names to begin with a capital letter
"new-parens": 1, // require parentheses when invoking a constructor with no arguments
"newline-after-var": 0, // require or disallow an empty line after var declarations
"newline-before-return": 0, // require an empty line before return statements
"newline-per-chained-call": 0, // require a newline after each call in a method chain
"no-array-constructor": 1, // disallow Array constructors
"no-bitwise": 1, // disallow bitwise operators
"no-continue": 1, // disallow continue statements
"no-inline-comments": 0, // disallow inline comments after code
"no-lonely-if": 0, // disallow if statements as the only statement in else blocks
"no-mixed-operators": 0, // disallow mixes of different operators
"no-mixed-spaces-and-tabs": 2, // disallow mixed spaces and tabs for indentation
"no-multiple-empty-lines": 2, // disallow multiple empty lines
"no-negated-condition": 0, // disallow negated conditions
"no-nested-ternary": 0, // disallow nested ternary expressions
"no-new-object": 2, // disallow Object constructors
"no-plusplus": [1, { // disallow the unary operators ++ and --
"allowForLoopAfterthoughts": true
}],
"no-restricted-syntax": 1, // disallow specified syntax
"no-spaced-func": 1, // disallow spacing between function identifiers and their applications
"no-ternary": 0, // disallow ternary operators
"no-trailing-spaces": 1, // disallow trailing whitespace at the end of lines
"no-underscore-dangle": 0, // disallow dangling underscores in identifiers
"no-unneeded-ternary": 1, // disallow ternary operators when simpler alternatives exist
"no-whitespace-before-property": 0, // disallow whitespace before properties
"object-curly-newline": 0, // enforce consistent line breaks inside braces
"object-curly-spacing": [1, "never"], // enforce consistent spacing inside braces
"object-property-newline": [0, { // enforce placing object properties on separate lines
"allowMultiplePropertiesPerLine": false
}],
// "one-var": [2, { // enforce variables to be declared either together or separately in functions
// "var": "always",
// "let": "always",
// "const": "never"
// }],
"one-var-declaration-per-line": [0, "always"], // require or disallow newlines around var declarations
"operator-assignment": 1, // require or disallow assignment operator shorthand where possible
"operator-linebreak": [1, "after"], // enforce consistent linebreak style for operators
"padded-blocks": [0, "never"], // require or disallow padding within blocks
"quote-props": [0, "as-needed"], // require quotes around object literal property names
"quotes": [2, "single"], // enforce the consistent use of either backticks, double, or single quotes
"require-jsdoc": 1, // require JSDoc comments
"semi": [1, "always"], // require or disallow semicolons instead of ASI
"semi-spacing": 1, // enforce consistent spacing before and after semicolons
"sort-vars": 0, // require variables within the same declaration block to be sorted
"space-before-blocks": 1, // enforce consistent spacing before blocks
"space-before-function-paren": [1, "never"], // enforce consistent spacing before function definition opening parenthesis
"space-in-parens": 1, // enforce consistent spacing inside parentheses
"space-infix-ops": 1, // require spacing around operators
"space-unary-ops": 1, // enforce consistent spacing before or after unary operators
"spaced-comment": 1, // enforce consistent spacing after the // or /* in a comment
// "unicode-bom": [1, "never"], // require or disallow the Unicode BOM
"wrap-regex": 1, // require parenthesis around regex literals
// es6
"constructor-super": 2, // require super() calls in constructors
"no-class-assign": 2, // disallow reassigning class members
"no-const-assign": 2, // disallow reassigning const variables
"no-dupe-class-members": 2, // disallow duplicate class members
"no-this-before-super": 2, // disallow this/super before calling super() in constructors
"prefer-const": 2 // require const declarations for variables that are never reassigned after declared
}
};

View file

@ -19,6 +19,7 @@ import {AbstractBoot} from 'Knoin/AbstractBoot';
class AbstractApp extends AbstractBoot class AbstractApp extends AbstractBoot
{ {
/** /**
* @constructor
* @param {RemoteStorage|AdminRemoteStorage} Remote * @param {RemoteStorage|AdminRemoteStorage} Remote
*/ */
constructor(Remote) constructor(Remote)
@ -58,16 +59,15 @@ class AbstractApp extends AbstractBoot
} }
}); });
$win.on('resize', function () { $win.on('resize', function() {
Events.pub('window.resize'); Events.pub('window.resize');
}); });
Events.sub('window.resize', _.throttle(function () { Events.sub('window.resize', _.throttle(function() {
var var
iH = $win.height(), iH = $win.height(),
iW = $win.height() iW = $win.height();
;
if ($win.__sizes[0] !== iH || $win.__sizes[1] !== iW) if ($win.__sizes[0] !== iH || $win.__sizes[1] !== iW)
{ {
@ -81,31 +81,31 @@ class AbstractApp extends AbstractBoot
// DEBUG // DEBUG
// Events.sub({ // Events.sub({
// 'window.resize': function () { // 'window.resize': function() {
// window.console.log('window.resize'); // window.console.log('window.resize');
// }, // },
// 'window.resize.real': function () { // 'window.resize.real': function() {
// window.console.log('window.resize.real'); // window.console.log('window.resize.real');
// } // }
// }); // });
$doc.on('keydown', function (oEvent) { $doc.on('keydown', function(oEvent) {
if (oEvent && oEvent.ctrlKey) if (oEvent && oEvent.ctrlKey)
{ {
$html.addClass('rl-ctrl-key-pressed'); $html.addClass('rl-ctrl-key-pressed');
} }
}).on('keyup', function (oEvent) { }).on('keyup', function(oEvent) {
if (oEvent && !oEvent.ctrlKey) if (oEvent && !oEvent.ctrlKey)
{ {
$html.removeClass('rl-ctrl-key-pressed'); $html.removeClass('rl-ctrl-key-pressed');
} }
}); });
$doc.on('mousemove keypress click', _.debounce(function () { $doc.on('mousemove keypress click', _.debounce(function() {
Events.pub('rl.auto-logout-refresh'); Events.pub('rl.auto-logout-refresh');
}, 5000)); }, 5000));
key('esc, enter', KeyState.All, _.bind(function () { key('esc, enter', KeyState.All, _.bind(function() {
detectDropdownVisibility(); detectDropdownVisibility();
}, this)); }, this));
} }
@ -124,11 +124,11 @@ class AbstractApp extends AbstractBoot
/** /**
* @param {string} link * @param {string} link
* @return {boolean} * @returns {boolean}
*/ */
download(link) { download(link) {
if (sUserAgent && (sUserAgent.indexOf('chrome') > -1 || sUserAgent.indexOf('chrome') > -1)) if (sUserAgent && (-1 < sUserAgent.indexOf('chrome') || -1 < sUserAgent.indexOf('chrome')))
{ {
const oLink = window.document.createElement('a'); const oLink = window.document.createElement('a');
oLink.href = link; oLink.href = link;
@ -160,7 +160,7 @@ class AbstractApp extends AbstractBoot
} }
/** /**
* @return {boolean} * @returns {boolean}
*/ */
googlePreviewSupported() { googlePreviewSupported() {
if (null === this.googlePreviewSupportedCache) if (null === this.googlePreviewSupportedCache)
@ -220,8 +220,7 @@ class AbstractApp extends AbstractBoot
const const
kn = require('Knoin/Knoin'), kn = require('Knoin/Knoin'),
mobile = Settings.appSettingsGet('mobile'), mobile = Settings.appSettingsGet('mobile'),
inIframe = !!Settings.appSettingsGet('inIframe') inIframe = !!Settings.appSettingsGet('inIframe');
;
let customLogoutLink = pString(Settings.appSettingsGet('customLogoutLink')); let customLogoutLink = pString(Settings.appSettingsGet('customLogoutLink'));
@ -282,8 +281,7 @@ class AbstractApp extends AbstractBoot
const const
mobile = Settings.appSettingsGet('mobile'), mobile = Settings.appSettingsGet('mobile'),
ssm = require('ssm'), ssm = require('ssm'),
ko = require('ko') ko = require('ko');
;
ko.components.register('SaveTrigger', require('Component/SaveTrigger')); ko.components.register('SaveTrigger', require('Component/SaveTrigger'));
ko.components.register('Input', require('Component/Input')); ko.components.register('Input', require('Component/Input'));

View file

@ -78,10 +78,8 @@ class AdminApp extends AbstractApp
PackageStore.packagesReal(!!data.Result.Real); PackageStore.packagesReal(!!data.Result.Real);
PackageStore.packagesMainUpdatable(!!data.Result.MainUpdatable); PackageStore.packagesMainUpdatable(!!data.Result.MainUpdatable);
let let list = [];
list = [], const loading = {};
loading = {}
;
_.each(PackageStore.packages(), (item) => { _.each(PackageStore.packages(), (item) => {
if (item && item.loading()) if (item && item.loading())

View file

@ -110,8 +110,7 @@ class AppUser extends AbstractApp
centeredX: true, centeredX: true,
centeredY: true centeredY: true
}) })
.removeAttr('style') .removeAttr('style');
;
}, 1000); }, 1000);
} }
@ -147,8 +146,7 @@ class AppUser extends AbstractApp
reloadMessageList(bDropPagePosition = false, bDropCurrenFolderCache = false) { reloadMessageList(bDropPagePosition = false, bDropCurrenFolderCache = false) {
let let
iOffset = (MessageStore.messageListPage() - 1) * SettingsStore.messagesPerPage() iOffset = (MessageStore.messageListPage() - 1) * SettingsStore.messagesPerPage();
;
if (bDropCurrenFolderCache) if (bDropCurrenFolderCache)
{ {
@ -203,7 +201,7 @@ class AppUser extends AbstractApp
/** /**
* @param {Function} fResultFunc * @param {Function} fResultFunc
* @return {boolean} * @returns {boolean}
*/ */
contactsSync(fResultFunc) { contactsSync(fResultFunc) {
@ -232,16 +230,14 @@ class AppUser extends AbstractApp
const const
sTrashFolder = FolderStore.trashFolder(), sTrashFolder = FolderStore.trashFolder(),
sSpamFolder = FolderStore.spamFolder() sSpamFolder = FolderStore.spamFolder();
;
_.each(this.moveCache, (oItem) => { _.each(this.moveCache, (oItem) => {
var var
bSpam = sSpamFolder === oItem.To, bSpam = sSpamFolder === oItem.To,
bTrash = sTrashFolder === oItem.To, bTrash = sTrashFolder === oItem.To,
bHam = !bSpam && sSpamFolder === oItem.From && Cache.getFolderInboxName() === oItem.To bHam = !bSpam && sSpamFolder === oItem.From && Cache.getFolderInboxName() === oItem.To;
;
Remote.messagesMove(this.moveOrDeleteResponseHelper, oItem.From, oItem.To, oItem.Uid, Remote.messagesMove(this.moveOrDeleteResponseHelper, oItem.From, oItem.To, oItem.Uid,
bSpam ? 'SPAM' : (bHam ? 'HAM' : ''), bSpam || bTrash); bSpam ? 'SPAM' : (bHam ? 'HAM' : ''), bSpam || bTrash);
@ -326,8 +322,7 @@ class AppUser extends AbstractApp
let let
oMoveFolder = null, oMoveFolder = null,
nSetSystemFoldersNotification = null nSetSystemFoldersNotification = null;
;
switch (iDeleteType) switch (iDeleteType)
{ {
@ -346,6 +341,7 @@ class AppUser extends AbstractApp
oMoveFolder = Cache.getFolderFromCacheList(FolderStore.archiveFolder()); oMoveFolder = Cache.getFolderFromCacheList(FolderStore.archiveFolder());
nSetSystemFoldersNotification = SetSystemFoldersNotification.Archive; nSetSystemFoldersNotification = SetSystemFoldersNotification.Archive;
break; break;
// no default
} }
bUseFolder = isUnd(bUseFolder) ? true : !!bUseFolder; bUseFolder = isUnd(bUseFolder) ? true : !!bUseFolder;
@ -390,8 +386,7 @@ class AppUser extends AbstractApp
{ {
const const
oFromFolder = Cache.getFolderFromCacheList(sFromFolderFullNameRaw), oFromFolder = Cache.getFolderFromCacheList(sFromFolderFullNameRaw),
oToFolder = Cache.getFolderFromCacheList(sToFolderFullNameRaw) oToFolder = Cache.getFolderFromCacheList(sToFolderFullNameRaw);
;
if (oFromFolder && oToFolder) if (oFromFolder && oToFolder)
{ {
@ -441,8 +436,7 @@ class AppUser extends AbstractApp
}, (errorCode) => { }, (errorCode) => {
FolderStore.folderList.error(getNotification(errorCode, '', errorDefCode)); FolderStore.folderList.error(getNotification(errorCode, '', errorDefCode));
Promises.foldersReloadWithTimeout(FolderStore.foldersLoading); Promises.foldersReloadWithTimeout(FolderStore.foldersLoading);
}) });
;
} }
reloadOpenPgpKeys() { reloadOpenPgpKeys() {
@ -453,8 +447,7 @@ class AppUser extends AbstractApp
aKeys = [], aKeys = [],
oEmail = new EmailModel(), oEmail = new EmailModel(),
oOpenpgpKeyring = PgpStore.openpgpKeyring, oOpenpgpKeyring = PgpStore.openpgpKeyring,
oOpenpgpKeys = oOpenpgpKeyring ? oOpenpgpKeyring.getAllKeys() : [] oOpenpgpKeys = oOpenpgpKeyring ? oOpenpgpKeyring.getAllKeys() : [];
;
_.each(oOpenpgpKeys, (oItem, iIndex) => { _.each(oOpenpgpKeys, (oItem, iIndex) => {
if (oItem && oItem.primaryKey) if (oItem && oItem.primaryKey)
@ -463,9 +456,8 @@ class AppUser extends AbstractApp
aEmails = [], aEmails = [],
aUsers = [], aUsers = [],
oPrimaryUser = oItem.getPrimaryUser(), oPrimaryUser = oItem.getPrimaryUser(),
sUser = (oPrimaryUser && oPrimaryUser.user) ? oPrimaryUser.user.userId.userid sUser = (oPrimaryUser && oPrimaryUser.user) ? oPrimaryUser.user.userId.userid :
: (oItem.users && oItem.users[0] ? oItem.users[0].userId.userid : '') (oItem.users && oItem.users[0] ? oItem.users[0].userId.userid : '');
;
if (oItem.users) if (oItem.users)
{ {
@ -550,8 +542,7 @@ class AppUser extends AbstractApp
var var
aCounts = {}, aCounts = {},
sParentEmail = Settings.settingsGet('ParentEmail'), sParentEmail = Settings.settingsGet('ParentEmail'),
sAccountEmail = AccountStore.email() sAccountEmail = AccountStore.email();
;
sParentEmail = '' === sParentEmail ? sAccountEmail : sParentEmail; sParentEmail = '' === sParentEmail ? sAccountEmail : sParentEmail;
@ -582,8 +573,7 @@ class AppUser extends AbstractApp
const const
sId = pString(oIdentityData.Id), sId = pString(oIdentityData.Id),
sEmail = pString(oIdentityData.Email), sEmail = pString(oIdentityData.Email),
oIdentity = new IdentityModel(sId, sEmail) oIdentity = new IdentityModel(sId, sEmail);
;
oIdentity.name(pString(oIdentityData.Name)); oIdentity.name(pString(oIdentityData.Name));
oIdentity.replyTo(pString(oIdentityData.ReplyTo)); oIdentity.replyTo(pString(oIdentityData.ReplyTo));
@ -646,8 +636,7 @@ class AppUser extends AbstractApp
let let
uid = '', uid = '',
check = false, check = false,
unreadCountChange = false unreadCountChange = false;
;
const folderFromCache = Cache.getFolderFromCacheList(data.Result.Folder); const folderFromCache = Cache.getFolderFromCacheList(data.Result.Folder);
if (folderFromCache) if (folderFromCache)
@ -739,8 +728,7 @@ class AppUser extends AbstractApp
var var
sHash = Cache.getFolderHash(oItem.Folder), sHash = Cache.getFolderHash(oItem.Folder),
oFolder = Cache.getFolderFromCacheList(oItem.Folder), oFolder = Cache.getFolderFromCacheList(oItem.Folder),
bUnreadCountChange = false bUnreadCountChange = false;
;
if (oFolder) if (oFolder)
{ {
@ -813,8 +801,7 @@ class AppUser extends AbstractApp
var var
oFolder = null, oFolder = null,
aRootUids = [], aRootUids = [],
iAlreadyUnread = 0 iAlreadyUnread = 0;
;
if (isUnd(aMessages)) if (isUnd(aMessages))
{ {
@ -825,7 +812,8 @@ class AppUser extends AbstractApp
if ('' !== sFolderFullNameRaw && 0 < aRootUids.length) if ('' !== sFolderFullNameRaw && 0 < aRootUids.length)
{ {
switch (iSetAction) { switch (iSetAction)
{
case MessageSetAction.SetSeen: case MessageSetAction.SetSeen:
_.each(aRootUids, (sSubUid) => { _.each(aRootUids, (sSubUid) => {
@ -877,6 +865,7 @@ class AppUser extends AbstractApp
Remote.messageSetFlagged(noop, sFolderFullNameRaw, aRootUids, false); Remote.messageSetFlagged(noop, sFolderFullNameRaw, aRootUids, false);
break; break;
// no default
} }
this.reloadFlagsCurrentMessageListAndMessageFromCache(); this.reloadFlagsCurrentMessageListAndMessageFromCache();
@ -1019,8 +1008,7 @@ class AppUser extends AbstractApp
}) })
.on('mouseup', () => { .on('mouseup', () => {
$html.removeClass('rl-resizer'); $html.removeClass('rl-resizer');
}) });
;
} }
}, },
@ -1062,8 +1050,7 @@ class AppUser extends AbstractApp
{ {
oTop oTop
.resizable('destroy') .resizable('destroy')
.removeAttr('style') .removeAttr('style');
;
} }
if (oBottom) if (oBottom)
@ -1084,8 +1071,7 @@ class AppUser extends AbstractApp
const iHeight = pInt(Local.get(sClientSideKeyName)) || 300; const iHeight = pInt(Local.get(sClientSideKeyName)) || 300;
fSetHeight(iHeight > iMinHeight ? iHeight : iMinHeight); fSetHeight(iHeight > iMinHeight ? iHeight : iMinHeight);
} }
} };
;
fDisable(false); fDisable(false);
@ -1144,8 +1130,7 @@ class AppUser extends AbstractApp
}) })
.on('mouseup', () => { .on('mouseup', () => {
$html.removeClass('rl-resizer'); $html.removeClass('rl-resizer');
}) });
;
} }
}, },
fResizeResizeFunction = _.debounce(() => { fResizeResizeFunction = _.debounce(() => {
@ -1173,8 +1158,7 @@ class AppUser extends AbstractApp
height: '' height: ''
}); });
} }
} };
;
if (null !== mLeftWidth) if (null !== mLeftWidth)
{ {
@ -1236,7 +1220,7 @@ class AppUser extends AbstractApp
kn.setHash(Links.root(), true); kn.setHash(Links.root(), true);
kn.routeOff(); kn.routeOff();
_.defer(function () { _.defer(function() {
window.location.href = customLoginLink; window.location.href = customLoginLink;
}); });
} }
@ -1271,8 +1255,7 @@ class AppUser extends AbstractApp
iContactsSyncInterval = pInt(Settings.settingsGet('ContactsSyncInterval')), iContactsSyncInterval = pInt(Settings.settingsGet('ContactsSyncInterval')),
bGoogle = Settings.settingsGet('AllowGoogleSocial'), bGoogle = Settings.settingsGet('AllowGoogleSocial'),
bFacebook = Settings.settingsGet('AllowFacebookSocial'), bFacebook = Settings.settingsGet('AllowFacebookSocial'),
bTwitter = Settings.settingsGet('AllowTwitterSocial') bTwitter = Settings.settingsGet('AllowTwitterSocial');
;
if (progressJs) if (progressJs)
{ {
@ -1423,7 +1406,8 @@ class AppUser extends AbstractApp
window.navigator.registerProtocolHandler('mailto', window.navigator.registerProtocolHandler('mailto',
window.location.protocol + '//' + window.location.host + window.location.pathname + '?mailto&to=%s', window.location.protocol + '//' + window.location.host + window.location.pathname + '?mailto&to=%s',
'' + (Settings.settingsGet('Title') || 'RainLoop')); '' + (Settings.settingsGet('Title') || 'RainLoop'));
} catch (e) {/* eslint-disable-line no-empty */} }
catch (e) {/* eslint-disable-line no-empty */}
if (Settings.settingsGet('MailToEmail')) if (Settings.settingsGet('MailToEmail'))
{ {

View file

@ -17,8 +17,7 @@ const Base64 = {
let let
output = '', output = '',
chr1, chr2, chr3, enc1, enc2, enc3, enc4, chr1, chr2, chr3, enc1, enc2, enc3, enc4,
i = 0 i = 0;
;
input = Base64._utf8_encode(input); input = Base64._utf8_encode(input);
@ -56,8 +55,7 @@ const Base64 = {
let let
output = '', output = '',
chr1, chr2, chr3, enc1, enc2, enc3, enc4, chr1, chr2, chr3, enc1, enc2, enc3, enc4,
i = 0 i = 0;
;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ''); input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
@ -97,8 +95,7 @@ const Base64 = {
utftext = '', utftext = '',
n = 0, n = 0,
l = string.length, l = string.length,
c = 0 c = 0;
;
for (; n < l; n++) { for (; n < l; n++) {
@ -132,8 +129,7 @@ const Base64 = {
i = 0, i = 0,
c = 0, c = 0,
c2 = 0, c2 = 0,
c3 = 0 c3 = 0;
;
while ( i < utftext.length ) while ( i < utftext.length )
{ {

View file

@ -14,6 +14,11 @@ window.__rlah_set = () => setHash();
window.__rlah_clear = () => clearHash(); window.__rlah_clear = () => clearHash();
window.__rlah_data = () => RL_APP_DATA_STORAGE; window.__rlah_data = () => RL_APP_DATA_STORAGE;
/**
* @param {string} id
* @param {string} name
* @returns {string}
*/
function getComputedStyle(id, name) function getComputedStyle(id, name)
{ {
var element = window.document.getElementById(id); var element = window.document.getElementById(id);
@ -21,16 +26,27 @@ function getComputedStyle(id, name)
(window.getComputedStyle ? window.getComputedStyle(element, null).getPropertyValue(name) : null); (window.getComputedStyle ? window.getComputedStyle(element, null).getPropertyValue(name) : null);
} }
/**
* @param {string} styles
* @returns {void}
*/
function includeStyle(styles) function includeStyle(styles)
{ {
window.document.write(unescape('%3Csty' + 'le%3E' + styles + '"%3E%3C/' + 'sty' + 'le%3E')); window.document.write(unescape('%3Csty' + 'le%3E' + styles + '"%3E%3C/' + 'sty' + 'le%3E'));
} }
/**
* @param {string} src
* @returns {void}
*/
function includeScr(src) function includeScr(src)
{ {
window.document.write(unescape('%3Csc' + 'ript type="text/jav' + 'ascr' + 'ipt" data-cfasync="false" sr' + 'c="' + src + '"%3E%3C/' + 'scr' + 'ipt%3E')); window.document.write(unescape('%3Csc' + 'ript type="text/jav' + 'ascr' + 'ipt" data-cfasync="false" sr' + 'c="' + src + '"%3E%3C/' + 'scr' + 'ipt%3E'));
} }
/**
* @returns {boolean}
*/
function includeLayout() function includeLayout()
{ {
const app = window.document.getElementById('rl-app'); const app = window.document.getElementById('rl-app');
@ -49,18 +65,25 @@ function includeLayout()
return false; return false;
} }
function includeAppScr(data = {}) /**
* @param {mixed} data
* @returns {void}
*/
function includeAppScr({admin = false, mobile = false, mobileDevice = false})
{ {
let src = './?/'; let src = './?/';
src += data.admin ? 'Admin' : ''; src += admin ? 'Admin' : '';
src += 'AppData@'; src += 'AppData@';
src += data.mobile ? 'mobile' : 'no-mobile'; src += mobile ? 'mobile' : 'no-mobile';
src += data.mobileDevice ? '-1' : '-0'; src += mobileDevice ? '-1' : '-0';
src += '/'; src += '/';
includeScr(src + (window.__rlah ? window.__rlah() || '0' : '0') + '/' + window.Math.random().toString().substr(2) + '/'); includeScr(src + (window.__rlah ? window.__rlah() || '0' : '0') + '/' + window.Math.random().toString().substr(2) + '/');
} }
/**
* @returns {object}
*/
function getRainloopBootData() function getRainloopBootData()
{ {
let result = {}; let result = {};
@ -74,13 +97,16 @@ function getRainloopBootData()
return result; return result;
} }
/**
* @param {string} additionalError
* @returns {void}
*/
function showError(additionalError) function showError(additionalError)
{ {
const const
oR = window.document.getElementById('rl-loading'), oR = window.document.getElementById('rl-loading'),
oL = window.document.getElementById('rl-loading-error'), oL = window.document.getElementById('rl-loading-error'),
oLA = window.document.getElementById('rl-loading-error-additional') oLA = window.document.getElementById('rl-loading-error-additional');
;
if (oR) if (oR)
{ {
@ -104,12 +130,15 @@ function showError(additionalError)
} }
} }
/**
* @param {string} description
* @returns {void}
*/
function showDescriptionAndLoading(description) function showDescriptionAndLoading(description)
{ {
const const
oE = window.document.getElementById('rl-loading'), oE = window.document.getElementById('rl-loading'),
oElDesc = window.document.getElementById('rl-loading-desc') oElDesc = window.document.getElementById('rl-loading-desc');
;
if (oElDesc && description) if (oElDesc && description)
{ {
@ -125,6 +154,11 @@ function showDescriptionAndLoading(description)
} }
} }
/**
* @param {boolean} withError
* @param {string} additionalError
* @returns {void}
*/
function runMainBoot(withError, additionalError) function runMainBoot(withError, additionalError)
{ {
if (window.__APP_BOOT && !withError) if (window.__APP_BOOT && !withError)
@ -139,6 +173,9 @@ function runMainBoot(withError, additionalError)
} }
} }
/**
* @returns {void}
*/
function runApp() function runApp()
{ {
const appData = window.__rlah_data(); const appData = window.__rlah_data();
@ -162,16 +199,14 @@ function runApp()
window.$('#rl-bg').attr('style', 'background-image: none !important;') window.$('#rl-bg').attr('style', 'background-image: none !important;')
.backstretch(appData.IncludeBackground.replace('{{USER}}', .backstretch(appData.IncludeBackground.replace('{{USER}}',
(window.__rlah ? (window.__rlah() || '0') : '0')), {fade: 100, centeredX: true, centeredY: true}) (window.__rlah ? (window.__rlah() || '0') : '0')), {fade: 100, centeredX: true, centeredY: true})
.removeAttr('style') .removeAttr('style');
;
} }
} }
}), }),
common = window.Promise.all([ common = window.Promise.all([
window.jassl(appData.TemplatesLink), window.jassl(appData.TemplatesLink),
window.jassl(appData.LangLink) window.jassl(appData.LangLink)
]) ]);
;
window.Promise.all([libs, common]) window.Promise.all([libs, common])
.then(() => { .then(() => {
@ -193,8 +228,7 @@ function runApp()
window.__initEditor(); window.__initEditor();
window.__initEditor = null; window.__initEditor = null;
} }
}) });
;
} }
else else
{ {
@ -202,6 +236,10 @@ function runApp()
} }
} }
/**
* @param {mixed} data
* @returns {void}
*/
window.__initAppData = function(data) { window.__initAppData = function(data) {
RL_APP_DATA_STORAGE = data; RL_APP_DATA_STORAGE = data;
@ -226,6 +264,9 @@ window.__initAppData = function(data) {
runApp(); runApp();
}; };
/**
* @returns {void}
*/
window.__runBoot = function() { window.__runBoot = function() {
if (!window.navigator || !window.navigator.cookieEnabled) if (!window.navigator || !window.navigator.cookieEnabled)

View file

@ -5,18 +5,20 @@ import {trim, pInt, isArray} from 'Common/Utils';
import * as Links from 'Common/Links'; import * as Links from 'Common/Links';
import * as Settings from 'Storage/Settings'; import * as Settings from 'Storage/Settings';
let FOLDERS_CACHE = {}; let FOLDERS_CACHE = {},
let FOLDERS_NAME_CACHE = {}; FOLDERS_NAME_CACHE = {},
let FOLDERS_HASH_CACHE = {}; FOLDERS_HASH_CACHE = {},
let FOLDERS_UID_NEXT_CACHE = {}; FOLDERS_UID_NEXT_CACHE = {},
let MESSAGE_FLAGS_CACHE = {}; MESSAGE_FLAGS_CACHE = {},
NEW_MESSAGE_CACHE = {},
inboxFolderName = '';
let NEW_MESSAGE_CACHE = {}; const REQUESTED_MESSAGE_CACHE = {},
let REQUESTED_MESSAGE_CACHE = {}; capaGravatar = Settings.capa(Capa.Gravatar);
const capaGravatar = Settings.capa(Capa.Gravatar);
let inboxFolderName = '';
/**
* @returns {void}
*/
export function clear() export function clear()
{ {
FOLDERS_CACHE = {}; FOLDERS_CACHE = {};
@ -29,7 +31,7 @@ export function clear()
/** /**
* @param {string} email * @param {string} email
* @param {Function} callback * @param {Function} callback
* @return {string} * @returns {string}
*/ */
export function getUserPic(email, callback) export function getUserPic(email, callback)
{ {
@ -40,7 +42,7 @@ export function getUserPic(email, callback)
/** /**
* @param {string} folderFullNameRaw * @param {string} folderFullNameRaw
* @param {string} uid * @param {string} uid
* @return {string} * @returns {string}
*/ */
export function getMessageKey(folderFullNameRaw, uid) export function getMessageKey(folderFullNameRaw, uid)
{ {
@ -59,7 +61,7 @@ export function addRequestedMessage(folder, uid)
/** /**
* @param {string} folder * @param {string} folder
* @param {string} uid * @param {string} uid
* @return {boolean} * @returns {boolean}
*/ */
export function hasRequestedMessage(folder, uid) export function hasRequestedMessage(folder, uid)
{ {
@ -89,13 +91,16 @@ export function hasNewMessageAndRemoveFromCache(folderFullNameRaw, uid)
return false; return false;
} }
/**
* @returns {void}
*/
export function clearNewMessageCache() export function clearNewMessageCache()
{ {
NEW_MESSAGE_CACHE = {}; NEW_MESSAGE_CACHE = {};
} }
/** /**
* @return {string} * @returns {string}
*/ */
export function getFolderInboxName() export function getFolderInboxName()
{ {
@ -104,7 +109,7 @@ export function getFolderInboxName()
/** /**
* @param {string} folderHash * @param {string} folderHash
* @return {string} * @returns {string}
*/ */
export function getFolderFullNameRaw(folderHash) export function getFolderFullNameRaw(folderHash)
{ {
@ -126,7 +131,7 @@ export function setFolderFullNameRaw(folderHash, folderFullNameRaw)
/** /**
* @param {string} folderFullNameRaw * @param {string} folderFullNameRaw
* @return {string} * @returns {string}
*/ */
export function getFolderHash(folderFullNameRaw) export function getFolderHash(folderFullNameRaw)
{ {
@ -147,7 +152,7 @@ export function setFolderHash(folderFullNameRaw, folderHash)
/** /**
* @param {string} folderFullNameRaw * @param {string} folderFullNameRaw
* @return {string} * @returns {string}
*/ */
export function getFolderUidNext(folderFullNameRaw) export function getFolderUidNext(folderFullNameRaw)
{ {
@ -165,7 +170,7 @@ export function setFolderUidNext(folderFullNameRaw, uidNext)
/** /**
* @param {string} folderFullNameRaw * @param {string} folderFullNameRaw
* @return {?FolderModel} * @returns {?FolderModel}
*/ */
export function getFolderFromCacheList(folderFullNameRaw) export function getFolderFromCacheList(folderFullNameRaw)
{ {
@ -192,7 +197,7 @@ export function removeFolderFromCacheList(folderFullNameRaw)
/** /**
* @param {string} folderFullName * @param {string} folderFullName
* @param {string} uid * @param {string} uid
* @return {?Array} * @returns {?Array}
*/ */
export function getMessageFlagsFromCache(folderFullName, uid) export function getMessageFlagsFromCache(folderFullName, uid)
{ {
@ -233,14 +238,13 @@ export function initMessageFlagsFromCache(message)
{ {
const const
uid = message.uid, uid = message.uid,
flags = getMessageFlagsFromCache(message.folderFullNameRaw, uid) flags = getMessageFlagsFromCache(message.folderFullNameRaw, uid);
;
if (flags && 0 < flags.length) if (flags && 0 < flags.length)
{ {
message.flagged(!!flags[1]); message.flagged(!!flags[1]);
if (!message.__simple_message__) if (!message.isSimpleMessage)
{ {
message.unseen(!!flags[0]); message.unseen(!!flags[0]);
message.answered(!!flags[2]); message.answered(!!flags[2]);
@ -334,6 +338,7 @@ export function storeMessageFlagsToCacheBySetAction(folder, uid, setAction)
case MessageSetAction.UnsetFlag: case MessageSetAction.UnsetFlag:
flags[1] = false; flags[1] = false;
break; break;
// no default
} }
setMessageFlagsToCache(folder, uid, flags); setMessageFlagsToCache(folder, uid, flags);

View file

@ -8,14 +8,13 @@ class CookieDriver
/** /**
* @param {string} key * @param {string} key
* @param {*} data * @param {*} data
* @return {boolean} * @returns {boolean}
*/ */
set(key, data) { set(key, data) {
let let
result = false, result = false,
storageResult = null storageResult = null;
;
try try
{ {
@ -41,7 +40,7 @@ class CookieDriver
/** /**
* @param {string} key * @param {string} key
* @return {*} * @returns {*}
*/ */
get(key) { get(key) {
@ -51,8 +50,7 @@ class CookieDriver
{ {
const const
storageValue = $.cookie(CLIENT_SIDE_STORAGE_INDEX_NAME), storageValue = $.cookie(CLIENT_SIDE_STORAGE_INDEX_NAME),
storageResult = null === storageValue ? null : JSON.parse(storageValue) storageResult = null === storageValue ? null : JSON.parse(storageValue);
;
result = (storageResult && !isUnd(storageResult[key])) ? storageResult[key] : null; result = (storageResult && !isUnd(storageResult[key])) ? storageResult[key] : null;
} }
@ -62,7 +60,7 @@ class CookieDriver
} }
/** /**
* @return {boolean} * @returns {boolean}
*/ */
static supported() { static supported() {
return !!(window.navigator && window.navigator.cookieEnabled); return !!(window.navigator && window.navigator.cookieEnabled);

View file

@ -8,14 +8,13 @@ class LocalStorageDriver
/** /**
* @param {string} key * @param {string} key
* @param {*} data * @param {*} data
* @return {boolean} * @returns {boolean}
*/ */
set(key, data) { set(key, data) {
let let
result = false, result = false,
storageResult = null storageResult = null;
;
try try
{ {
@ -38,7 +37,7 @@ class LocalStorageDriver
/** /**
* @param {string} key * @param {string} key
* @return {*} * @returns {*}
*/ */
get(key) { get(key) {
@ -48,8 +47,7 @@ class LocalStorageDriver
{ {
const const
storageValue = window.localStorage[CLIENT_SIDE_STORAGE_INDEX_NAME] || null, storageValue = window.localStorage[CLIENT_SIDE_STORAGE_INDEX_NAME] || null,
storageResult = null === storageValue ? null : JSON.parse(storageValue) storageResult = null === storageValue ? null : JSON.parse(storageValue);
;
result = (storageResult && !isUnd(storageResult[key])) ? storageResult[key] : null; result = (storageResult && !isUnd(storageResult[key])) ? storageResult[key] : null;
} }
@ -59,7 +57,7 @@ class LocalStorageDriver
} }
/** /**
* @return {boolean} * @returns {boolean}
*/ */
static supported() { static supported() {
return !!window.localStorage; return !!window.localStorage;

View file

@ -43,41 +43,37 @@ export const sUserAgent = 'navigator' in window && 'userAgent' in window.navigat
/** /**
* @type {boolean} * @type {boolean}
*/ */
export const bIE = sUserAgent.indexOf('msie') > -1; export const bIE = -1 < sUserAgent.indexOf('msie');
/** /**
* @type {boolean} * @type {boolean}
*/ */
export const bChrome = sUserAgent.indexOf('chrome') > -1; export const bChrome = -1 < sUserAgent.indexOf('chrome');
/** /**
* @type {boolean} * @type {boolean}
*/ */
export const bSafari = !bChrome && sUserAgent.indexOf('safari') > -1; export const bSafari = !bChrome && -1 < sUserAgent.indexOf('safari');
/** /**
* @type {boolean} * @type {boolean}
*/ */
export const bMobileDevice = export const bMobileDevice =
/android/i.test(sUserAgent) || (/android/i).test(sUserAgent) ||
/iphone/i.test(sUserAgent) || (/iphone/i).test(sUserAgent) ||
/ipod/i.test(sUserAgent) || (/ipod/i).test(sUserAgent) ||
/ipad/i.test(sUserAgent) || (/ipad/i).test(sUserAgent) ||
/blackberry/i.test(sUserAgent) (/blackberry/i).test(sUserAgent);
;
/** /**
* @type {boolean} * @type {boolean}
*/ */
export let bDisableNanoScroll = bMobileDevice; export const bDisableNanoScroll = bMobileDevice;
/** /**
* @type {boolean} * @type {boolean}
*/ */
export let bAnimationSupported = !bMobileDevice && export const bAnimationSupported = !bMobileDevice && $html.hasClass('csstransitions') && $html.hasClass('cssanimations');
$html.hasClass('csstransitions') &&
$html.hasClass('cssanimations')
;
/** /**
* @type {boolean} * @type {boolean}
@ -161,13 +157,13 @@ let bAllowPdfPreview = !bMobileDevice;
if (bAllowPdfPreview && window.navigator && window.navigator.mimeTypes) if (bAllowPdfPreview && window.navigator && window.navigator.mimeTypes)
{ {
bAllowPdfPreview = !!_.find(window.navigator.mimeTypes, function (oType) { bAllowPdfPreview = !!_.find(window.navigator.mimeTypes, function(oType) {
return oType && 'application/pdf' === oType.type; return oType && 'application/pdf' === oType.type;
}); });
if (!bAllowPdfPreview) if (!bAllowPdfPreview)
{ {
bAllowPdfPreview = (typeof window.navigator.mimeTypes['application/pdf'] !== 'undefined'); bAllowPdfPreview = 'undefined' !== typeof window.navigator.mimeTypes['application/pdf'];
} }
} }
@ -203,32 +199,31 @@ export const keyScope = ko.computed({
read: () => { read: () => {
return keyScopeFake(); return keyScopeFake();
}, },
write: function (sValue) { write: function(sValue) {
if (KeyState.Menu !== sValue) if (KeyState.Menu !== sValue)
{ {
if (KeyState.Compose === sValue) if (KeyState.Compose === sValue)
{ {
// disableKeyFilter // disableKeyFilter
key.filter = function () { key.filter = function() {
return useKeyboardShortcuts(); return useKeyboardShortcuts();
}; };
} }
else else
{ {
// restoreKeyFilter // restoreKeyFilter
key.filter = function (event) { key.filter = function(event) {
if (useKeyboardShortcuts()) if (useKeyboardShortcuts())
{ {
var var
oElement = event.target || event.srcElement, oElement = event.target || event.srcElement,
sTagName = oElement ? oElement.tagName : '' sTagName = oElement ? oElement.tagName : '';
;
sTagName = sTagName.toUpperCase(); sTagName = sTagName.toUpperCase();
return !(sTagName === 'INPUT' || sTagName === 'SELECT' || sTagName === 'TEXTAREA' || return !('INPUT' === sTagName || 'SELECT' === sTagName || 'TEXTAREA' === sTagName ||
(oElement && sTagName === 'DIV' && ('editorHtmlArea' === oElement.className || 'true' === '' + oElement.contentEditable)) (oElement && 'DIV' === sTagName && ('editorHtmlArea' === oElement.className || 'true' === '' + oElement.contentEditable))
); );
} }
@ -247,12 +242,12 @@ export const keyScope = ko.computed({
} }
}); });
keyScopeReal.subscribe(function (sValue) { keyScopeReal.subscribe(function(sValue) {
// window.console.log('keyScope=' + sValue); // DEBUG // window.console.log('keyScope=' + sValue); // DEBUG
key.setScope(sValue); key.setScope(sValue);
}); });
dropdownVisibility.subscribe(function (bValue) { dropdownVisibility.subscribe(function(bValue) {
if (bValue) if (bValue)
{ {
keyScope(KeyState.Menu); keyScope(KeyState.Menu);

View file

@ -6,6 +6,7 @@ import * as Settings from 'Storage/Settings';
class HtmlEditor class HtmlEditor
{ {
/** /**
* @constructor
* @param {Object} element * @param {Object} element
* @param {Function=} onBlur * @param {Function=} onBlur
* @param {Function=} onReady * @param {Function=} onReady
@ -47,7 +48,7 @@ class HtmlEditor
} }
/** /**
* @return {boolean} * @returns {boolean}
*/ */
isHtml() { isHtml() {
return this.editor ? 'wysiwyg' === this.editor.mode : false; return this.editor ? 'wysiwyg' === this.editor.mode : false;
@ -70,7 +71,7 @@ class HtmlEditor
} }
/** /**
* @return {boolean} * @returns {boolean}
*/ */
checkDirty() { checkDirty() {
return this.editor ? this.editor.checkDirty() : false; return this.editor ? this.editor.checkDirty() : false;
@ -85,7 +86,7 @@ class HtmlEditor
/** /**
* @param {string} text * @param {string} text
* @return {string} * @returns {string}
*/ */
clearSignatureSigns(text) { clearSignatureSigns(text) {
return text.replace(/(\u200C|\u0002)/g, ''); return text.replace(/(\u200C|\u0002)/g, '');
@ -94,7 +95,7 @@ class HtmlEditor
/** /**
* @param {boolean=} wrapIsHtml = false * @param {boolean=} wrapIsHtml = false
* @param {boolean=} clearSignatureSigns = false * @param {boolean=} clearSignatureSigns = false
* @return {string} * @returns {string}
*/ */
getData(wrapIsHtml = false, clearSignatureSigns = false) { getData(wrapIsHtml = false, clearSignatureSigns = false) {
@ -113,7 +114,8 @@ class HtmlEditor
'<div data-html-editor-font-wrapper="true" style="font-family: arial, sans-serif; font-size: 13px;">' + '<div data-html-editor-font-wrapper="true" style="font-family: arial, sans-serif; font-size: 13px;">' +
this.editor.getData() + '</div>' : this.editor.getData(); this.editor.getData() + '</div>' : this.editor.getData();
} }
} catch (e) {/* eslint-disable-line no-empty */} }
catch (e) {/* eslint-disable-line no-empty */}
if (clearSignatureSigns) if (clearSignatureSigns)
{ {
@ -127,7 +129,7 @@ class HtmlEditor
/** /**
* @param {boolean=} wrapIsHtml = false * @param {boolean=} wrapIsHtml = false
* @param {boolean=} clearSignatureSigns = false * @param {boolean=} clearSignatureSigns = false
* @return {string} * @returns {string}
*/ */
getDataWithHtmlMark(wrapIsHtml = false, clearSignatureSigns = false) { getDataWithHtmlMark(wrapIsHtml = false, clearSignatureSigns = false) {
return (this.isHtml() ? ':HTML:' : '') + this.getData(wrapIsHtml, clearSignatureSigns); return (this.isHtml() ? ':HTML:' : '') + this.getData(wrapIsHtml, clearSignatureSigns);
@ -151,7 +153,8 @@ class HtmlEditor
this.editor.setMode('plain'); this.editor.setMode('plain');
} }
} }
} catch (e) {/* eslint-disable-line no-empty */} }
catch (e) {/* eslint-disable-line no-empty */}
if (resize) if (resize)
{ {
@ -180,7 +183,8 @@ class HtmlEditor
try { try {
this.editor.setData(html); this.editor.setData(html);
} catch (e) {/* eslint-disable-line no-empty */} }
catch (e) {/* eslint-disable-line no-empty */}
if (focus) if (focus)
{ {
@ -195,7 +199,8 @@ class HtmlEditor
try { try {
this.editor.setData( this.editor.setData(
this.editor.getData().replace(find, replaceHtml)); this.editor.getData().replace(find, replaceHtml));
} catch (e) {/* eslint-disable-line no-empty */} }
catch (e) {/* eslint-disable-line no-empty */}
} }
} }
@ -211,7 +216,8 @@ class HtmlEditor
{ {
try { try {
this.editor.setData(plain); this.editor.setData(plain);
} catch (e) {/* eslint-disable-line no-empty */} }
catch (e) {/* eslint-disable-line no-empty */}
} }
if (focus) if (focus)
@ -231,8 +237,7 @@ class HtmlEditor
config = oHtmlEditorDefaultConfig, config = oHtmlEditorDefaultConfig,
language = Settings.settingsGet('Language'), language = Settings.settingsGet('Language'),
allowSource = !!Settings.appSettingsGet('allowHtmlEditorSourceButton'), allowSource = !!Settings.appSettingsGet('allowHtmlEditorSourceButton'),
biti = !!Settings.appSettingsGet('allowHtmlEditorBitiButtons') biti = !!Settings.appSettingsGet('allowHtmlEditorBitiButtons');
;
if ((allowSource || !biti) && !config.toolbarGroups.__cfgInited) if ((allowSource || !biti) && !config.toolbarGroups.__cfgInited)
{ {
@ -295,8 +300,7 @@ class HtmlEditor
var var
id = event.data.dataTransfer.id, id = event.data.dataTransfer.id,
imageId = `[img=${id}]`, imageId = `[img=${id}]`,
reader = new window.FileReader() reader = new window.FileReader();
;
reader.onloadend = () => { reader.onloadend = () => {
if (reader.result) if (reader.result)
@ -333,8 +337,7 @@ class HtmlEditor
} }
}); });
} };
;
if (window.CKEDITOR) if (window.CKEDITOR)
{ {
@ -352,7 +355,8 @@ class HtmlEditor
{ {
try { try {
this.editor.focus(); this.editor.focus();
} catch (e) {/* eslint-disable-line no-empty */} }
catch (e) {/* eslint-disable-line no-empty */}
} }
} }
@ -361,7 +365,8 @@ class HtmlEditor
{ {
try { try {
return !!this.editor.focusManager.hasFocus; return !!this.editor.focusManager.hasFocus;
} catch (e) {/* eslint-disable-line no-empty */} }
catch (e) {/* eslint-disable-line no-empty */}
} }
return false; return false;
@ -372,7 +377,8 @@ class HtmlEditor
{ {
try { try {
this.editor.focusManager.blur(true); this.editor.focusManager.blur(true);
} catch (e) {/* eslint-disable-line no-empty */} }
catch (e) {/* eslint-disable-line no-empty */}
} }
} }
@ -381,7 +387,8 @@ class HtmlEditor
{ {
try { try {
this.editor.resize(this.$element.width(), this.$element.innerHeight()); this.editor.resize(this.$element.width(), this.$element.innerHeight());
} catch (e) {/* eslint-disable-line no-empty */} }
catch (e) {/* eslint-disable-line no-empty */}
} }
} }
@ -390,7 +397,8 @@ class HtmlEditor
{ {
try { try {
this.editor.setReadOnly(!!value); this.editor.setReadOnly(!!value);
} catch (e) {/* eslint-disable-line no-empty */} }
catch (e) {/* eslint-disable-line no-empty */}
} }
} }

View file

@ -3,29 +3,33 @@ import {window} from 'common';
import {pString, pInt, isUnd, isNormal, trim, encodeURIComponent} from 'Common/Utils'; import {pString, pInt, isUnd, isNormal, trim, encodeURIComponent} from 'Common/Utils';
import * as Settings from 'Storage/Settings'; import * as Settings from 'Storage/Settings';
const ROOT = './'; const
const HASH_PREFIX = '#/'; ROOT = './',
const SERVER_PREFIX = './?'; HASH_PREFIX = '#/',
const SUB_QUERY_PREFIX = '&q[]='; SERVER_PREFIX = './?',
SUB_QUERY_PREFIX = '&q[]=',
const VERSION = Settings.appSettingsGet('version'); VERSION = Settings.appSettingsGet('version'),
const WEB_PREFIX = Settings.appSettingsGet('webPath') || ''; WEB_PREFIX = Settings.appSettingsGet('webPath') || '',
const VERSION_PREFIX = Settings.appSettingsGet('webVersionPath') || 'rainloop/v/' + VERSION + '/'; VERSION_PREFIX = Settings.appSettingsGet('webVersionPath') || 'rainloop/v/' + VERSION + '/',
const STATIC_PREFIX = VERSION_PREFIX + 'static/'; STATIC_PREFIX = VERSION_PREFIX + 'static/',
const ADMIN_HOST_USE = !!Settings.appSettingsGet('adminHostUse'); ADMIN_HOST_USE = !!Settings.appSettingsGet('adminHostUse'),
const ADMIN_PATH = Settings.appSettingsGet('adminPath') || 'admin'; ADMIN_PATH = Settings.appSettingsGet('adminPath') || 'admin';
let AUTH_PREFIX = Settings.settingsGet('AuthAccountHash') || '0'; let AUTH_PREFIX = Settings.settingsGet('AuthAccountHash') || '0';
/**
* @returns {void}
*/
export function populateAuthSuffix() export function populateAuthSuffix()
{ {
AUTH_PREFIX = Settings.settingsGet('AuthAccountHash') || '0'; AUTH_PREFIX = Settings.settingsGet('AuthAccountHash') || '0';
} }
/** /**
* @return {string} * @returns {string}
*/ */
export function subQueryPrefix() export function subQueryPrefix()
{ {
@ -34,7 +38,7 @@ export function subQueryPrefix()
/** /**
* @param {string=} startupUrl * @param {string=} startupUrl
* @return {string} * @returns {string}
*/ */
export function root(startupUrl = '') export function root(startupUrl = '')
{ {
@ -42,7 +46,7 @@ export function root(startupUrl = '')
} }
/** /**
* @return {string} * @returns {string}
*/ */
export function rootAdmin() export function rootAdmin()
{ {
@ -51,7 +55,7 @@ export function rootAdmin()
/** /**
* @param {boolean=} mobile = false * @param {boolean=} mobile = false
* @return {string} * @returns {string}
*/ */
export function rootUser(mobile = false) export function rootUser(mobile = false)
{ {
@ -62,7 +66,7 @@ export function rootUser(mobile = false)
* @param {string} type * @param {string} type
* @param {string} download * @param {string} download
* @param {string=} customSpecSuffix * @param {string=} customSpecSuffix
* @return {string} * @returns {string}
*/ */
export function attachmentRaw(type, download, customSpecSuffix) export function attachmentRaw(type, download, customSpecSuffix)
{ {
@ -73,7 +77,7 @@ export function attachmentRaw(type, download, customSpecSuffix)
/** /**
* @param {string} download * @param {string} download
* @param {string=} customSpecSuffix * @param {string=} customSpecSuffix
* @return {string} * @returns {string}
*/ */
export function attachmentDownload(download, customSpecSuffix) export function attachmentDownload(download, customSpecSuffix)
{ {
@ -83,7 +87,7 @@ export function attachmentDownload(download, customSpecSuffix)
/** /**
* @param {string} download * @param {string} download
* @param {string=} customSpecSuffix * @param {string=} customSpecSuffix
* @return {string} * @returns {string}
*/ */
export function attachmentPreview(download, customSpecSuffix) export function attachmentPreview(download, customSpecSuffix)
{ {
@ -93,7 +97,7 @@ export function attachmentPreview(download, customSpecSuffix)
/** /**
* @param {string} download * @param {string} download
* @param {string=} customSpecSuffix * @param {string=} customSpecSuffix
* @return {string} * @returns {string}
*/ */
export function attachmentThumbnailPreview(download, customSpecSuffix) export function attachmentThumbnailPreview(download, customSpecSuffix)
{ {
@ -103,7 +107,7 @@ export function attachmentThumbnailPreview(download, customSpecSuffix)
/** /**
* @param {string} download * @param {string} download
* @param {string=} customSpecSuffix * @param {string=} customSpecSuffix
* @return {string} * @returns {string}
*/ */
export function attachmentPreviewAsPlain(download, customSpecSuffix) export function attachmentPreviewAsPlain(download, customSpecSuffix)
{ {
@ -113,7 +117,7 @@ export function attachmentPreviewAsPlain(download, customSpecSuffix)
/** /**
* @param {string} download * @param {string} download
* @param {string=} customSpecSuffix * @param {string=} customSpecSuffix
* @return {string} * @returns {string}
*/ */
export function attachmentFramed(download, customSpecSuffix) export function attachmentFramed(download, customSpecSuffix)
{ {
@ -122,7 +126,7 @@ export function attachmentFramed(download, customSpecSuffix)
/** /**
* @param {string} type * @param {string} type
* @return {string} * @returns {string}
*/ */
export function serverRequest(type) export function serverRequest(type)
{ {
@ -130,7 +134,7 @@ export function serverRequest(type)
} }
/** /**
* @return {string} * @returns {string}
*/ */
export function upload() export function upload()
{ {
@ -138,7 +142,7 @@ export function upload()
} }
/** /**
* @return {string} * @returns {string}
*/ */
export function uploadContacts() export function uploadContacts()
{ {
@ -146,7 +150,7 @@ export function uploadContacts()
} }
/** /**
* @return {string} * @returns {string}
*/ */
export function uploadBackground() export function uploadBackground()
{ {
@ -154,7 +158,7 @@ export function uploadBackground()
} }
/** /**
* @return {string} * @returns {string}
*/ */
export function append() export function append()
{ {
@ -163,7 +167,7 @@ export function append()
/** /**
* @param {string} email * @param {string} email
* @return {string} * @returns {string}
*/ */
export function change(email) export function change(email)
{ {
@ -172,7 +176,7 @@ export function change(email)
/** /**
* @param {string} add * @param {string} add
* @return {string} * @returns {string}
*/ */
export function ajax(add) export function ajax(add)
{ {
@ -181,7 +185,7 @@ export function ajax(add)
/** /**
* @param {string} requestHash * @param {string} requestHash
* @return {string} * @returns {string}
*/ */
export function messageViewLink(requestHash) export function messageViewLink(requestHash)
{ {
@ -190,7 +194,7 @@ export function messageViewLink(requestHash)
/** /**
* @param {string} requestHash * @param {string} requestHash
* @return {string} * @returns {string}
*/ */
export function messageDownloadLink(requestHash) export function messageDownloadLink(requestHash)
{ {
@ -199,7 +203,7 @@ export function messageDownloadLink(requestHash)
/** /**
* @param {string} email * @param {string} email
* @return {string} * @returns {string}
*/ */
export function avatarLink(email) export function avatarLink(email)
{ {
@ -208,7 +212,7 @@ export function avatarLink(email)
/** /**
* @param {string} hash * @param {string} hash
* @return {string} * @returns {string}
*/ */
export function publicLink(hash) export function publicLink(hash)
{ {
@ -217,7 +221,7 @@ export function publicLink(hash)
/** /**
* @param {string} hash * @param {string} hash
* @return {string} * @returns {string}
*/ */
export function userBackground(hash) export function userBackground(hash)
{ {
@ -225,7 +229,7 @@ export function userBackground(hash)
} }
/** /**
* @return {string} * @returns {string}
*/ */
export function phpInfo() export function phpInfo()
{ {
@ -235,7 +239,7 @@ export function phpInfo()
/** /**
* @param {string} lang * @param {string} lang
* @param {boolean} isAdmin * @param {boolean} isAdmin
* @return {string} * @returns {string}
*/ */
export function langLink(lang, isAdmin) export function langLink(lang, isAdmin)
{ {
@ -243,7 +247,7 @@ export function langLink(lang, isAdmin)
} }
/** /**
* @return {string} * @returns {string}
*/ */
export function exportContactsVcf() export function exportContactsVcf()
{ {
@ -251,7 +255,7 @@ export function exportContactsVcf()
} }
/** /**
* @return {string} * @returns {string}
*/ */
export function exportContactsCsv() export function exportContactsCsv()
{ {
@ -260,7 +264,7 @@ export function exportContactsCsv()
/** /**
* @param {boolean} xauth = false * @param {boolean} xauth = false
* @return {string} * @returns {string}
*/ */
export function socialGoogle(xauth = false) export function socialGoogle(xauth = false)
{ {
@ -269,7 +273,7 @@ export function socialGoogle(xauth = false)
} }
/** /**
* @return {string} * @returns {string}
*/ */
export function socialTwitter() export function socialTwitter()
{ {
@ -278,7 +282,7 @@ export function socialTwitter()
} }
/** /**
* @return {string} * @returns {string}
*/ */
export function socialFacebook() export function socialFacebook()
{ {
@ -288,7 +292,7 @@ export function socialFacebook()
/** /**
* @param {string} path * @param {string} path
* @return {string} * @returns {string}
*/ */
export function staticPrefix(path) export function staticPrefix(path)
{ {
@ -296,7 +300,7 @@ export function staticPrefix(path)
} }
/** /**
* @return {string} * @returns {string}
*/ */
export function emptyContactPic() export function emptyContactPic()
{ {
@ -305,7 +309,7 @@ export function emptyContactPic()
/** /**
* @param {string} fileName * @param {string} fileName
* @return {string} * @returns {string}
*/ */
export function sound(fileName) export function sound(fileName)
{ {
@ -313,7 +317,7 @@ export function sound(fileName)
} }
/** /**
* @return {string} * @returns {string}
*/ */
export function notificationMailIcon() export function notificationMailIcon()
{ {
@ -321,7 +325,7 @@ export function notificationMailIcon()
} }
/** /**
* @return {string} * @returns {string}
*/ */
export function openPgpJs() export function openPgpJs()
{ {
@ -329,7 +333,7 @@ export function openPgpJs()
} }
/** /**
* @return {string} * @returns {string}
*/ */
export function openPgpWorkerJs() export function openPgpWorkerJs()
{ {
@ -337,7 +341,7 @@ export function openPgpWorkerJs()
} }
/** /**
* @return {string} * @returns {string}
*/ */
export function openPgpWorkerPath() export function openPgpWorkerPath()
{ {
@ -346,7 +350,7 @@ export function openPgpWorkerPath()
/** /**
* @param {string} theme * @param {string} theme
* @return {string} * @returns {string}
*/ */
export function themePreviewLink(theme) export function themePreviewLink(theme)
{ {
@ -362,7 +366,7 @@ export function themePreviewLink(theme)
/** /**
* @param {string} inboxFolderName = 'INBOX' * @param {string} inboxFolderName = 'INBOX'
* @return {string} * @returns {string}
*/ */
export function inbox(inboxFolderName = 'INBOX') export function inbox(inboxFolderName = 'INBOX')
{ {
@ -371,7 +375,7 @@ export function inbox(inboxFolderName = 'INBOX')
/** /**
* @param {string=} screenName = '' * @param {string=} screenName = ''
* @return {string} * @returns {string}
*/ */
export function settings(screenName = '') export function settings(screenName = '')
{ {
@ -379,7 +383,7 @@ export function settings(screenName = '')
} }
/** /**
* @return {string} * @returns {string}
*/ */
export function about() export function about()
{ {
@ -388,12 +392,13 @@ export function about()
/** /**
* @param {string} screenName * @param {string} screenName
* @return {string} * @returns {string}
*/ */
export function admin(screenName) export function admin(screenName)
{ {
let result = HASH_PREFIX; let result = HASH_PREFIX;
switch (screenName) { switch (screenName)
{
case 'AdminDomains': case 'AdminDomains':
result += 'domains'; result += 'domains';
break; break;
@ -403,6 +408,7 @@ export function admin(screenName)
case 'AdminLicensing': case 'AdminLicensing':
result += 'licensing'; result += 'licensing';
break; break;
// no default
} }
return result; return result;
@ -413,7 +419,7 @@ export function admin(screenName)
* @param {number=} page = 1 * @param {number=} page = 1
* @param {string=} search = '' * @param {string=} search = ''
* @param {string=} threadUid = '' * @param {string=} threadUid = ''
* @return {string} * @returns {string}
*/ */
export function mailBox(folder, page = 1, search = '', threadUid = '') export function mailBox(folder, page = 1, search = '', threadUid = '')
{ {

View file

@ -13,12 +13,18 @@ const updateMomentNowUnix = _.debounce(() => {
_momentNow = moment().unix(); _momentNow = moment().unix();
}, 500, true); }, 500, true);
/**
* @returns {moment}
*/
export function momentNow() export function momentNow()
{ {
updateMomentNow(); updateMomentNow();
return _moment || moment(); return _moment || moment();
} }
/**
* @returns {number}
*/
export function momentNowUnix() export function momentNowUnix()
{ {
updateMomentNowUnix(); updateMomentNowUnix();
@ -27,7 +33,7 @@ export function momentNowUnix()
/** /**
* @param {number} date * @param {number} date
* @return {string} * @returns {string}
*/ */
export function searchSubtractFormatDateHelper(date) export function searchSubtractFormatDateHelper(date)
{ {
@ -36,14 +42,14 @@ export function searchSubtractFormatDateHelper(date)
/** /**
* @param {Object} m * @param {Object} m
* @return {string} * @returns {string}
*/ */
function formatCustomShortDate(m) function formatCustomShortDate(m)
{ {
const now = momentNow(); const now = momentNow();
if (m && now) if (m && now)
{ {
switch(true) switch (true)
{ {
case 4 >= now.diff(m, 'hours'): case 4 >= now.diff(m, 'hours'):
return m.fromNow(); return m.fromNow();
@ -57,6 +63,7 @@ function formatCustomShortDate(m)
}); });
case now.year() === m.year(): case now.year() === m.year():
return m.format('D MMM.'); return m.format('D MMM.');
// no default
} }
} }
@ -66,15 +73,14 @@ function formatCustomShortDate(m)
/** /**
* @param {number} timeStampInUTC * @param {number} timeStampInUTC
* @param {string} formatStr * @param {string} formatStr
* @return {string} * @returns {string}
*/ */
export function format(timeStampInUTC, formatStr) export function format(timeStampInUTC, formatStr)
{ {
let let
m = null, m = null,
result = '' result = '';
;
const now = momentNowUnix(); const now = momentNowUnix();
@ -112,14 +118,14 @@ export function format(timeStampInUTC, formatStr)
/** /**
* @param {Object} element * @param {Object} element
* @returns {void}
*/ */
export function momentToNode(element) export function momentToNode(element)
{ {
var var
key = '', key = '',
time = 0, time = 0,
$el = $(element) $el = $(element);
;
time = $el.data('moment-time'); time = $el.data('moment-time');
if (time) if (time)
@ -138,6 +144,9 @@ export function momentToNode(element)
} }
} }
/**
* @returns {void}
*/
export function reload() export function reload()
{ {
_.defer(() => { _.defer(() => {

View file

@ -41,7 +41,7 @@ export function runHook(name, args = [])
/** /**
* @param {string} name * @param {string} name
* @return {?} * @returns {?}
*/ */
export function mainSettingsGet(name) export function mainSettingsGet(name)
{ {
@ -98,7 +98,7 @@ export function runSettingsViewModelHooks(admin)
/** /**
* @param {string} pluginSection * @param {string} pluginSection
* @param {string} name * @param {string} name
* @return {?} * @returns {?}
*/ */
export function settingsGet(pluginSection, name) export function settingsGet(pluginSection, name)
{ {

View file

@ -129,8 +129,7 @@ class Selector
aCache = [], aCache = [],
aCheckedCache = [], aCheckedCache = [],
mFocused = null, mFocused = null,
mSelected = null mSelected = null;
;
this.list.subscribe((items) => { this.list.subscribe((items) => {
@ -168,8 +167,7 @@ class Selector
mNextFocused = mFocused, mNextFocused = mFocused,
bChecked = false, bChecked = false,
bSelected = false, bSelected = false,
iLen = 0 iLen = 0;
;
this.selectedItemUseCallback = false; this.selectedItemUseCallback = false;
@ -195,7 +193,7 @@ class Selector
{ {
bChecked = true; bChecked = true;
oItem.checked(true); oItem.checked(true);
iLen--; iLen -= 1;
} }
if (!bChecked && null !== mSelected && mSelected === sUid) if (!bChecked && null !== mSelected && mSelected === sUid)
@ -350,8 +348,7 @@ class Selector
item.checked(!item.checked()); item.checked(!item.checked());
} }
} }
}) });
;
key('enter', keyScope, () => { key('enter', keyScope, () => {
if (this.focusedItem() && !this.focusedItem().selected()) if (this.focusedItem() && !this.focusedItem().selected())
@ -397,6 +394,7 @@ class Selector
case 'pagedown': case 'pagedown':
eventKey = EventKeyCode.PageDown; eventKey = EventKeyCode.PageDown;
break; break;
// no default
} }
if (0 < eventKey) if (0 < eventKey)
@ -410,7 +408,7 @@ class Selector
} }
/** /**
* @return {boolean} * @returns {boolean}
*/ */
autoSelect() { autoSelect() {
return !!(this.oCallbacks.onAutoSelect || noopTrue)(); return !!(this.oCallbacks.onAutoSelect || noopTrue)();
@ -425,7 +423,7 @@ class Selector
/** /**
* @param {Object} oItem * @param {Object} oItem
* @return {string} * @returns {string}
*/ */
getItemUid(item) { getItemUid(item) {
@ -455,8 +453,7 @@ class Selector
oResult = null, oResult = null,
aList = this.list(), aList = this.list(),
iListLen = aList ? aList.length : 0, iListLen = aList ? aList.length : 0,
oFocused = this.focusedItem() oFocused = this.focusedItem();
;
if (0 < iListLen) if (0 < iListLen)
{ {
@ -482,29 +479,31 @@ class Selector
_.each(aList, (item) => { _.each(aList, (item) => {
if (!bStop) if (!bStop)
{ {
switch (iEventKeyCode) { switch (iEventKeyCode)
case EventKeyCode.Up: {
if (oFocused === item) case EventKeyCode.Up:
{ if (oFocused === item)
bStop = true; {
} bStop = true;
else }
{ else
oResult = item; {
} oResult = item;
break; }
case EventKeyCode.Down: break;
case EventKeyCode.Insert: case EventKeyCode.Down:
if (bNext) case EventKeyCode.Insert:
{ if (bNext)
oResult = item; {
bStop = true; oResult = item;
} bStop = true;
else if (oFocused === item) }
{ else if (oFocused === item)
bNext = true; {
} bNext = true;
break; }
break;
// no default
} }
} }
}); });
@ -540,7 +539,7 @@ class Selector
} }
else if (EventKeyCode.PageUp === iEventKeyCode) else if (EventKeyCode.PageUp === iEventKeyCode)
{ {
for (iIndex = iListLen; iIndex >= 0; iIndex--) for (iIndex = iListLen; 0 <= iIndex; iIndex--)
{ {
if (oFocused === aList[iIndex]) if (oFocused === aList[iIndex])
{ {
@ -597,7 +596,7 @@ class Selector
} }
/** /**
* @return {boolean} * @returns {boolean}
*/ */
scrollToFocused() { scrollToFocused() {
@ -612,17 +611,16 @@ class Selector
$focused = $(this.sItemFocusedSelector, this.oContentScrollable), $focused = $(this.sItemFocusedSelector, this.oContentScrollable),
pos = $focused.position(), pos = $focused.position(),
visibleHeight = this.oContentVisible.height(), visibleHeight = this.oContentVisible.height(),
focusedHeight = $focused.outerHeight() focusedHeight = $focused.outerHeight();
;
if (list && list[0] && list[0].focused()) if (list && list[0] && list[0].focused())
{ {
this.oContentScrollable.scrollTop(0); this.oContentScrollable.scrollTop(0);
return true; return true;
} }
else if (pos && (pos.top < 0 || pos.top + focusedHeight > visibleHeight)) else if (pos && (0 > pos.top || pos.top + focusedHeight > visibleHeight))
{ {
this.oContentScrollable.scrollTop(pos.top < 0 ? this.oContentScrollable.scrollTop(0 > pos.top ?
this.oContentScrollable.scrollTop() + pos.top - offset : this.oContentScrollable.scrollTop() + pos.top - offset :
this.oContentScrollable.scrollTop() + pos.top - visibleHeight + focusedHeight + offset this.oContentScrollable.scrollTop() + pos.top - visibleHeight + focusedHeight + offset
); );
@ -635,7 +633,7 @@ class Selector
/** /**
* @param {boolean=} fast = false * @param {boolean=} fast = false
* @return {boolean} * @returns {boolean}
*/ */
scrollToTop(fast = false) { scrollToTop(fast = false) {
@ -666,8 +664,7 @@ class Selector
list = [], list = [],
checked = false, checked = false,
listItem = null, listItem = null,
lineUid = '' lineUid = '';
;
const uid = this.getItemUid(item); const uid = this.getItemUid(item);
if (event && event.shiftKey) if (event && event.shiftKey)

View file

@ -88,14 +88,13 @@ export const trigger = ko.observable(false);
* @param {string} key * @param {string} key
* @param {Object=} valueList * @param {Object=} valueList
* @param {string=} defaulValue * @param {string=} defaulValue
* @return {string} * @returns {string}
*/ */
export function i18n(key, valueList, defaulValue) export function i18n(key, valueList, defaulValue)
{ {
let let
valueName = '', valueName = '',
result = I18N_DATA[key] result = I18N_DATA[key];
;
if (isUnd(result)) if (isUnd(result))
{ {
@ -120,8 +119,7 @@ const i18nToNode = (element) => {
const const
$el = $(element), $el = $(element),
key = $el.data('i18n') key = $el.data('i18n');
;
if (key) if (key)
{ {
@ -138,6 +136,7 @@ const i18nToNode = (element) => {
case '[title': case '[title':
$el.attr('title', i18n(key.substr(7))); $el.attr('title', i18n(key.substr(7)));
break; break;
// no default
} }
} }
else else
@ -187,6 +186,9 @@ const reloadData = () => {
window.rainloopI18N = null; window.rainloopI18N = null;
}; };
/**
* @returns {void}
*/
export function initNotificationLanguage() export function initNotificationLanguage()
{ {
I18N_NOTIFICATION_MAP.forEach((item) => { I18N_NOTIFICATION_MAP.forEach((item) => {
@ -227,7 +229,7 @@ export function initOnStartOrLangChange(callback, scope, langCallback = null)
* @param {number} code * @param {number} code
* @param {*=} message = '' * @param {*=} message = ''
* @param {*=} defCode = null * @param {*=} defCode = null
* @return {string} * @returns {string}
*/ */
export function getNotification(code, message = '', defCode = null) export function getNotification(code, message = '', defCode = null)
{ {
@ -246,7 +248,7 @@ export function getNotification(code, message = '', defCode = null)
/** /**
* @param {object} response * @param {object} response
* @param {number} defCode = Notification.UnknownNotification * @param {number} defCode = Notification.UnknownNotification
* @return {string} * @returns {string}
*/ */
export function getNotificationFromResponse(response, defCode = Notification.UnknownNotification) export function getNotificationFromResponse(response, defCode = Notification.UnknownNotification)
{ {
@ -256,7 +258,7 @@ export function getNotificationFromResponse(response, defCode = Notification.Unk
/** /**
* @param {*} code * @param {*} code
* @return {string} * @returns {string}
*/ */
export function getUploadErrorDescByCode(code) export function getUploadErrorDescByCode(code)
{ {
@ -314,9 +316,8 @@ export function reload(admin, language)
$html $html
.removeClass('rl-changing-language') .removeClass('rl-changing-language')
.removeClass('rl-rtl rl-ltr') .removeClass('rl-rtl rl-ltr')
.addClass(isRtl ? 'rl-rtl' : 'rl-ltr')
// .attr('dir', isRtl ? 'rtl' : 'ltr') // .attr('dir', isRtl ? 'rtl' : 'ltr')
; .addClass(isRtl ? 'rl-rtl' : 'rl-ltr');
resolve(); resolve();

View file

@ -32,12 +32,13 @@ export function silentTryCatch(callback)
{ {
try { try {
callback(); callback();
} catch (e) {/* eslint-disable-line no-empty */} }
catch (e) {/* eslint-disable-line no-empty */}
} }
/** /**
* @param {*} value * @param {*} value
* @return {boolean} * @returns {boolean}
*/ */
export function isNormal(value) export function isNormal(value)
{ {
@ -47,7 +48,7 @@ export function isNormal(value)
/** /**
* @param {(string|number)} value * @param {(string|number)} value
* @param {boolean=} includeZero = true * @param {boolean=} includeZero = true
* @return {boolean} * @returns {boolean}
*/ */
export function isPosNumeric(value, includeZero = true) export function isPosNumeric(value, includeZero = true)
{ {
@ -58,7 +59,7 @@ export function isPosNumeric(value, includeZero = true)
/** /**
* @param {*} value * @param {*} value
* @param {number=} defaultValur = 0 * @param {number=} defaultValur = 0
* @return {number} * @returns {number}
*/ */
export function pInt(value, defaultValur = 0) export function pInt(value, defaultValur = 0)
{ {
@ -68,7 +69,7 @@ export function pInt(value, defaultValur = 0)
/** /**
* @param {*} value * @param {*} value
* @return {string} * @returns {string}
*/ */
export function pString(value) export function pString(value)
{ {
@ -77,7 +78,7 @@ export function pString(value)
/** /**
* @param {*} value * @param {*} value
* @return {boolean} * @returns {boolean}
*/ */
export function pBool(value) export function pBool(value)
{ {
@ -86,7 +87,7 @@ export function pBool(value)
/** /**
* @param {*} values * @param {*} values
* @return {boolean} * @returns {boolean}
*/ */
export function isNonEmptyArray(values) export function isNonEmptyArray(values)
{ {
@ -95,7 +96,7 @@ export function isNonEmptyArray(values)
/** /**
* @param {string} component * @param {string} component
* @return {string} * @returns {string}
*/ */
export function encodeURIComponent(component) export function encodeURIComponent(component)
{ {
@ -104,7 +105,7 @@ export function encodeURIComponent(component)
/** /**
* @param {string} component * @param {string} component
* @return {string} * @returns {string}
*/ */
export function decodeURIComponent(component) export function decodeURIComponent(component)
{ {
@ -113,20 +114,17 @@ export function decodeURIComponent(component)
/** /**
* @param {string} queryString * @param {string} queryString
* @return {Object} * @returns {Object}
*/ */
export function simpleQueryParser(queryString) export function simpleQueryParser(queryString)
{ {
let let index = 0, len = 0, temp = null;
params = {},
queries = [],
temp = [],
index = 0,
len = 0
;
queries = queryString.split('&'); const
for (index = 0, len = queries.length; index < len; index++) queries = queryString.split('&'),
params = {};
for (len = queries.length; index < len; index++)
{ {
temp = queries[index].split('='); temp = queries[index].split('=');
params[decodeURIComponent(temp[0])] = decodeURIComponent(temp[1]); params[decodeURIComponent(temp[0])] = decodeURIComponent(temp[1]);
@ -137,14 +135,13 @@ export function simpleQueryParser(queryString)
/** /**
* @param {number=} len = 32 * @param {number=} len = 32
* @return {string} * @returns {string}
*/ */
export function fakeMd5(len = 32) export function fakeMd5(len = 32)
{ {
const const
line = '0123456789abcdefghijklmnopqrstuvwxyz', line = '0123456789abcdefghijklmnopqrstuvwxyz',
lineLen = line.length lineLen = line.length;
;
len = pInt(len); len = pInt(len);
@ -162,7 +159,7 @@ let encryptObject = null;
/** /**
* @param {constructor} JSEncryptClass * @param {constructor} JSEncryptClass
* @param {string} publicKey * @param {string} publicKey
* @return {JSEncrypt|boolean} * @returns {JSEncrypt|boolean}
*/ */
const rsaObject = (JSEncryptClass, publicKey) => { const rsaObject = (JSEncryptClass, publicKey) => {
@ -184,16 +181,14 @@ const rsaObject = (JSEncryptClass, publicKey) => {
/** /**
* @param {string} value * @param {string} value
* @param {string} publicKey * @param {string} publicKey
* @return {string} * @returns {string}
*/ */
const rsaEncode = (value, publicKey) => { const rsaEncode = (value, publicKey) => {
if (window.crypto && window.crypto.getRandomValues && publicKey) if (window.crypto && window.crypto.getRandomValues && publicKey)
{ {
let let resultValue = false;
resultValue = false, const encrypt = rsaObject(JSEncrypt, publicKey);
encrypt = rsaObject(JSEncrypt, publicKey)
;
if (encrypt) if (encrypt)
{ {
@ -214,7 +209,7 @@ export {rsaEncode};
/** /**
* @param {string} text * @param {string} text
* @return {string} * @returns {string}
*/ */
export function encodeHtml(text) export function encodeHtml(text)
{ {
@ -224,7 +219,7 @@ export function encodeHtml(text)
/** /**
* @param {string} text * @param {string} text
* @param {number=} iLen = 100 * @param {number=} iLen = 100
* @return {string} * @returns {string}
*/ */
export function splitPlainText(text, len = 100) export function splitPlainText(text, len = 100)
{ {
@ -233,8 +228,7 @@ export function splitPlainText(text, len = 100)
subText = '', subText = '',
result = text, result = text,
spacePos = 0, spacePos = 0,
newLinePos = 0 newLinePos = 0;
;
while (result.length > len) while (result.length > len)
{ {
@ -259,8 +253,8 @@ export function splitPlainText(text, len = 100)
return prefix + result; return prefix + result;
} }
const timeOutAction = (function () { const timeOutAction = (function() {
let timeOuts = {}; const timeOuts = {};
return (action, fFunction, timeOut) => { return (action, fFunction, timeOut) => {
timeOuts[action] = isUnd(timeOuts[action]) ? 0 : timeOuts[action]; timeOuts[action] = isUnd(timeOuts[action]) ? 0 : timeOuts[action];
window.clearTimeout(timeOuts[action]); window.clearTimeout(timeOuts[action]);
@ -268,8 +262,8 @@ const timeOutAction = (function () {
}; };
}()); }());
const timeOutActionSecond = (function () { const timeOutActionSecond = (function() {
let timeOuts = {}; const timeOuts = {};
return (action, fFunction, timeOut) => { return (action, fFunction, timeOut) => {
if (!timeOuts[action]) if (!timeOuts[action])
{ {
@ -284,7 +278,7 @@ const timeOutActionSecond = (function () {
export {timeOutAction, timeOutActionSecond}; export {timeOutAction, timeOutActionSecond};
/** /**
* @return {boolean} * @returns {boolean}
*/ */
export function inFocus() export function inFocus()
{ {
@ -301,6 +295,10 @@ export function inFocus()
return false; return false;
} }
/**
* @param {boolean} force
* @returns {void}
*/
export function removeInFocus(force) export function removeInFocus(force)
{ {
if (window.document && window.document.activeElement && window.document.activeElement.blur) if (window.document && window.document.activeElement && window.document.activeElement.blur)
@ -313,12 +311,16 @@ export function removeInFocus(force)
} }
else if (force) else if (force)
{ {
window.document.activeElement.blur(); window.document.activeElement.blur();
} }
} catch (e) {/* eslint-disable-line no-empty */} }
catch (e) {/* eslint-disable-line no-empty */}
} }
} }
/**
* @returns {void}
*/
export function removeSelection() export function removeSelection()
{ {
try { try {
@ -334,41 +336,42 @@ export function removeSelection()
{ {
window.document.selection.empty(); window.document.selection.empty();
} }
} catch (e) {/* eslint-disable-line no-empty */} }
catch (e) {/* eslint-disable-line no-empty */}
} }
/** /**
* @param {string} prefix * @param {string} prefix
* @param {string} subject * @param {string} subject
* @return {string} * @returns {string}
*/ */
export function replySubjectAdd(prefix, subject) export function replySubjectAdd(prefix, subject)
{ {
prefix = trim(prefix.toUpperCase()); prefix = trim(prefix.toUpperCase());
subject = trim(subject.replace(/[\s]+/g, ' ')); subject = trim(subject.replace(/[\s]+/g, ' '));
let let drop = false,
drop = false,
parts = [],
re = 'RE' === prefix, re = 'RE' === prefix,
fwd = 'FWD' === prefix, fwd = 'FWD' === prefix;
prefixIsRe = !fwd
; const
parts = [],
prefixIsRe = !fwd;
if ('' !== subject) if ('' !== subject)
{ {
_.each(subject.split(':'), (part) => { _.each(subject.split(':'), (part) => {
const trimmedPart = trim(part); const trimmedPart = trim(part);
if (!drop && (/^(RE|FWD)$/i.test(trimmedPart) || /^(RE|FWD)[\[\(][\d]+[\]\)]$/i.test(trimmedPart))) if (!drop && ((/^(RE|FWD)$/i).test(trimmedPart) || (/^(RE|FWD)[\[\(][\d]+[\]\)]$/i).test(trimmedPart)))
{ {
if (!re) if (!re)
{ {
re = !!(/^RE/i.test(trimmedPart)); re = !!(/^RE/i).test(trimmedPart);
} }
if (!fwd) if (!fwd)
{ {
fwd = !!(/^FWD/i.test(trimmedPart)); fwd = !!(/^FWD/i).test(trimmedPart);
} }
} }
else else
@ -399,7 +402,7 @@ export function replySubjectAdd(prefix, subject)
/** /**
* @param {number} num * @param {number} num
* @param {number} dec * @param {number} dec
* @return {number} * @returns {number}
*/ */
export function roundNumber(num, dec) export function roundNumber(num, dec)
{ {
@ -408,23 +411,21 @@ export function roundNumber(num, dec)
/** /**
* @param {(number|string)} sizeInBytes * @param {(number|string)} sizeInBytes
* @return {string} * @returns {string}
*/ */
export function friendlySize(sizeInBytes) export function friendlySize(sizeInBytes)
{ {
sizeInBytes = pInt(sizeInBytes); sizeInBytes = pInt(sizeInBytes);
if (sizeInBytes >= 1073741824) switch (true)
{ {
return roundNumber(sizeInBytes / 1073741824, 1) + 'GB'; case 1073741824 <= sizeInBytes:
} return roundNumber(sizeInBytes / 1073741824, 1) + 'GB';
else if (sizeInBytes >= 1048576) case 1048576 <= sizeInBytes:
{ return roundNumber(sizeInBytes / 1048576, 1) + 'MB';
return roundNumber(sizeInBytes / 1048576, 1) + 'MB'; case 1024 <= sizeInBytes:
} return roundNumber(sizeInBytes / 1024, 0) + 'KB';
else if (sizeInBytes >= 1024) // no default
{
return roundNumber(sizeInBytes / 1024, 0) + 'KB';
} }
return sizeInBytes + 'B'; return sizeInBytes + 'B';
@ -506,21 +507,19 @@ export function kill_CtrlA_CtrlS(event)
* @param {(Object|null|undefined)} context * @param {(Object|null|undefined)} context
* @param {Function} fExecute * @param {Function} fExecute
* @param {(Function|boolean|null)=} fCanExecute = true * @param {(Function|boolean|null)=} fCanExecute = true
* @return {Function} * @returns {Function}
*/ */
export function createCommand(context, fExecute, fCanExecute = true) export function createCommand(context, fExecute, fCanExecute = true)
{ {
let let fResult = null;
fResult = null, const fNonEmpty = (...args) => {
fNonEmpty = (...args) => { if (fResult && fResult.canExecute && fResult.canExecute())
if (fResult && fResult.canExecute && fResult.canExecute()) {
{ fExecute.apply(context, args);
fExecute.apply(context, args);
}
return false;
} }
; return false;
};
fResult = fExecute ? fNonEmpty : noop; fResult = fExecute ? fNonEmpty : noop;
fResult.enabled = ko.observable(true); fResult.enabled = ko.observable(true);
@ -543,7 +542,7 @@ export function createCommand(context, fExecute, fCanExecute = true)
/** /**
* @param {string} theme * @param {string} theme
* @return {string} * @returns {string}
*/ */
export const convertThemeName = _.memoize((theme) => { export const convertThemeName = _.memoize((theme) => {
@ -557,7 +556,7 @@ export const convertThemeName = _.memoize((theme) => {
/** /**
* @param {string} name * @param {string} name
* @return {string} * @returns {string}
*/ */
export function quoteName(name) export function quoteName(name)
{ {
@ -565,7 +564,7 @@ export function quoteName(name)
} }
/** /**
* @return {number} * @returns {number}
*/ */
export function microtime() export function microtime()
{ {
@ -573,7 +572,7 @@ export function microtime()
} }
/** /**
* @return {number} * @returns {number}
*/ */
export function timestamp() export function timestamp()
{ {
@ -584,7 +583,7 @@ export function timestamp()
* *
* @param {string} language * @param {string} language
* @param {boolean=} isEng = false * @param {boolean=} isEng = false
* @return {string} * @returns {string}
*/ */
export function convertLangName(language, isEng = false) export function convertLangName(language, isEng = false)
{ {
@ -592,6 +591,9 @@ export function convertLangName(language, isEng = false)
language.toUpperCase().replace(/[^a-zA-Z0-9]+/g, '_'), null, language); language.toUpperCase().replace(/[^a-zA-Z0-9]+/g, '_'), null, language);
} }
/**
* @returns {object}
*/
export function draggablePlace() export function draggablePlace()
{ {
return $('<div class="draggablePlace">' + return $('<div class="draggablePlace">' +
@ -602,14 +604,18 @@ export function draggablePlace()
).appendTo('#rl-hidden'); ).appendTo('#rl-hidden');
} }
export function defautOptionsAfterRender(domOption, item) /**
* @param {object} domOption
* @param {object} item
* @returns {void}
*/
export function defautOptionsAfterRender(domItem, item)
{ {
if (item && !isUnd(item.disabled) && domOption) if (item && !isUnd(item.disabled) && domItem)
{ {
$(domOption) $(domItem)
.toggleClass('disabled', item.disabled) .toggleClass('disabled', item.disabled)
.prop('disabled', item.disabled) .prop('disabled', item.disabled);
;
} }
} }
@ -638,8 +644,7 @@ export function previewMessage(title, body, isHtml, print)
win = window.open(''), win = window.open(''),
doc = win.document, doc = win.document,
bodyClone = body.clone(), bodyClone = body.clone(),
bodyClass = isHtml ? 'html' : 'plain' bodyClass = isHtml ? 'html' : 'plain';
;
clearBqSwitcher(bodyClone); clearBqSwitcher(bodyClone);
@ -734,7 +739,7 @@ body.plain blockquote blockquote blockquote {
* @param {?} koTrigger * @param {?} koTrigger
* @param {?} context = null * @param {?} context = null
* @param {number=} timer = 1000 * @param {number=} timer = 1000
* @return {Function} * @returns {Function}
*/ */
export function settingsSaveHelperFunction(fCallback, koTrigger, context = null, timer = 1000) export function settingsSaveHelperFunction(fCallback, koTrigger, context = null, timer = 1000)
{ {
@ -751,11 +756,23 @@ export function settingsSaveHelperFunction(fCallback, koTrigger, context = null,
}; };
} }
/**
* @param {object} koTrigger
* @param {mixed} context
* @returns {mixed}
*/
export function settingsSaveHelperSimpleFunction(koTrigger, context) export function settingsSaveHelperSimpleFunction(koTrigger, context)
{ {
return settingsSaveHelperFunction(null, koTrigger, context, 1000); return settingsSaveHelperFunction(null, koTrigger, context, 1000);
} }
/**
* @param {object} remote
* @param {string} settingName
* @param {string} type
* @param {function} fTriggerFunction
* @returns {function}
*/
export function settingsSaveHelperSubscribeFunction(remote, settingName, type, fTriggerFunction) export function settingsSaveHelperSubscribeFunction(remote, settingName, type, fTriggerFunction)
{ {
return (value) => { return (value) => {
@ -764,9 +781,6 @@ export function settingsSaveHelperSubscribeFunction(remote, settingName, type, f
{ {
switch (type) switch (type)
{ {
default:
value = pString(value);
break;
case 'bool': case 'bool':
case 'boolean': case 'boolean':
value = value ? '1' : '0'; value = value ? '1' : '0';
@ -779,9 +793,12 @@ export function settingsSaveHelperSubscribeFunction(remote, settingName, type, f
case 'trim': case 'trim':
value = trim(value); value = trim(value);
break; break;
default:
value = pString(value);
break;
} }
let data = {}; const data = {};
data[settingName] = value; data[settingName] = value;
if (remote.saveAdminConfig) if (remote.saveAdminConfig)
@ -798,7 +815,7 @@ export function settingsSaveHelperSubscribeFunction(remote, settingName, type, f
/** /**
* @param {string} html * @param {string} html
* @return {string} * @returns {string}
*/ */
export function findEmailAndLinks(html) export function findEmailAndLinks(html)
{ {
@ -809,7 +826,7 @@ export function findEmailAndLinks(html)
urls: true, urls: true,
email: true, email: true,
twitter: false, twitter: false,
replaceFn: function (autolinker, match) { replaceFn: function(autolinker, match) {
return !(autolinker && match && 'url' === match.getType() && match.matchedText && 0 !== match.matchedText.indexOf('http')); return !(autolinker && match && 'url' === match.getType() && match.matchedText && 0 !== match.matchedText.indexOf('http'));
} }
}); });
@ -817,7 +834,7 @@ export function findEmailAndLinks(html)
/** /**
* @param {string} html * @param {string} html
* @return {string} * @returns {string}
*/ */
export function htmlToPlain(html) export function htmlToPlain(html)
{ {
@ -828,8 +845,7 @@ export function htmlToPlain(html)
iP2 = 0, iP2 = 0,
iP3 = 0, iP3 = 0,
text = '' text = '';
;
const const
@ -867,8 +883,7 @@ export function htmlToPlain(html)
convertLinks = (...args) => { convertLinks = (...args) => {
return (args && 1 < args.length) ? trim(args[1]) : ''; return (args && 1 < args.length) ? trim(args[1]) : '';
} };
;
text = html text = html
.replace(/\u0002([\s\S]*)\u0002/gm, '\u200C$1\u200C') .replace(/\u0002([\s\S]*)\u0002/gm, '\u200C$1\u200C')
@ -893,8 +908,7 @@ export function htmlToPlain(html)
.replace(/<\/div>/gi, '\n') .replace(/<\/div>/gi, '\n')
.replace(/&nbsp;/gi, ' ') .replace(/&nbsp;/gi, ' ')
.replace(/&quot;/gi, '"') .replace(/&quot;/gi, '"')
.replace(/<[^>]*>/gm, '') .replace(/<[^>]*>/gm, '');
;
text = $div.html(text).text(); text = $div.html(text).text();
@ -903,8 +917,7 @@ export function htmlToPlain(html)
.replace(/[\n]{3,}/gm, '\n\n') .replace(/[\n]{3,}/gm, '\n\n')
.replace(/&gt;/gi, '>') .replace(/&gt;/gi, '>')
.replace(/&lt;/gi, '<') .replace(/&lt;/gi, '<')
.replace(/&amp;/gi, '&') .replace(/&amp;/gi, '&');
;
text = splitPlainText(trim(text)); text = splitPlainText(trim(text));
@ -913,7 +926,7 @@ export function htmlToPlain(html)
while (0 < limit) while (0 < limit)
{ {
limit--; limit -= 1;
iP1 = text.indexOf('__bq__start__', pos); iP1 = text.indexOf('__bq__start__', pos);
if (-1 < iP1) if (-1 < iP1)
{ {
@ -945,8 +958,7 @@ export function htmlToPlain(html)
text = text text = text
.replace(/__bq__start__/gm, '') .replace(/__bq__start__/gm, '')
.replace(/__bq__end__/gm, '') .replace(/__bq__end__/gm, '');
;
return text; return text;
} }
@ -954,7 +966,7 @@ export function htmlToPlain(html)
/** /**
* @param {string} plain * @param {string} plain
* @param {boolean} findEmailAndLinksInText = false * @param {boolean} findEmailAndLinksInText = false
* @return {string} * @returns {string}
*/ */
export function plainToHtml(plain, findEmailAndLinksInText = false) export function plainToHtml(plain, findEmailAndLinksInText = false)
{ {
@ -971,8 +983,7 @@ export function plainToHtml(plain, findEmailAndLinksInText = false)
aNextText = [], aNextText = [],
sLine = '', sLine = '',
iIndex = 0, iIndex = 0,
aText = plain.split('\n') aText = plain.split('\n');
;
do do
{ {
@ -1031,8 +1042,7 @@ export function plainToHtml(plain, findEmailAndLinksInText = false)
.replace(/~~~blockquote~~~[\s]*/g, '<blockquote>') .replace(/~~~blockquote~~~[\s]*/g, '<blockquote>')
.replace(/[\s]*~~~\/blockquote~~~/g, '</blockquote>') .replace(/[\s]*~~~\/blockquote~~~/g, '</blockquote>')
.replace(/\u200C([\s\S]*)\u200C/g, '\u0002$1\u0002') .replace(/\u200C([\s\S]*)\u200C/g, '\u0002$1\u0002')
.replace(/\n/g, '<br />') .replace(/\n/g, '<br />');
;
return findEmailAndLinksInText ? findEmailAndLinks(plain) : plain; return findEmailAndLinksInText ? findEmailAndLinks(plain) : plain;
} }
@ -1051,7 +1061,7 @@ window.rainloop_Utils_plainToHtml = plainToHtml;
* @param {Function=} fRenameCallback * @param {Function=} fRenameCallback
* @param {boolean=} bSystem * @param {boolean=} bSystem
* @param {boolean=} bBuildUnvisible * @param {boolean=} bBuildUnvisible
* @return {Array} * @returns {Array}
*/ */
export function folderListOptionsBuilder(aSystem, aList, aDisabled, aHeaderLines, export function folderListOptionsBuilder(aSystem, aList, aDisabled, aHeaderLines,
iUnDeep, fDisableCallback, fVisibleCallback, fRenameCallback, bSystem, bBuildUnvisible) iUnDeep, fDisableCallback, fVisibleCallback, fRenameCallback, bSystem, bBuildUnvisible)
@ -1064,9 +1074,9 @@ export function folderListOptionsBuilder(aSystem, aList, aDisabled, aHeaderLines
bSep = false, bSep = false,
iIndex = 0, iIndex = 0,
iLen = 0, iLen = 0,
sDeepPrefix = '\u00A0\u00A0\u00A0', aResult = [];
aResult = []
; const sDeepPrefix = '\u00A0\u00A0\u00A0';
bBuildUnvisible = isUnd(bBuildUnvisible) ? false : !!bBuildUnvisible; bBuildUnvisible = isUnd(bBuildUnvisible) ? false : !!bBuildUnvisible;
bSystem = !isNormal(bSystem) ? 0 < aSystem.length : bSystem; bSystem = !isNormal(bSystem) ? 0 < aSystem.length : bSystem;
@ -1171,6 +1181,10 @@ export function folderListOptionsBuilder(aSystem, aList, aDisabled, aHeaderLines
return aResult; return aResult;
} }
/**
* @param {object} element
* @returns {void}
*/
export function selectElement(element) export function selectElement(element)
{ {
let sel, range; let sel, range;
@ -1215,26 +1229,26 @@ export function triggerAutocompleteInputChange(delay = false) {
} }
} }
let configurationScriptTagCache = {}; const configurationScriptTagCache = {};
/** /**
* @param {string} configuration * @param {string} configuration
* @return {object} * @returns {object}
*/ */
export function getConfigurationFromScriptTag(configuration) export function getConfigurationFromScriptTag(configuration)
{ {
let result = {};
if (!configurationScriptTagCache[configuration]) if (!configurationScriptTagCache[configuration])
{ {
configurationScriptTagCache[configuration] = $('script[type="application/json"][data-configuration="' + configuration + '"]'); configurationScriptTagCache[configuration] = $('script[type="application/json"][data-configuration="' + configuration + '"]');
} }
try { try
result = JSON.parse(configurationScriptTagCache[configuration].text()); {
} catch (e) {/* eslint-disable-line no-empty */} return JSON.parse(configurationScriptTagCache[configuration].text());
}
catch (e) {/* eslint-disable-line no-empty */}
return result; return {};
} }
/** /**
@ -1244,7 +1258,7 @@ export function getConfigurationFromScriptTag(configuration)
export function disposeOne(propOrValue, value) export function disposeOne(propOrValue, value)
{ {
const disposable = value || propOrValue; const disposable = value || propOrValue;
if (disposable && typeof disposable.dispose === 'function') if (disposable && 'function' === typeof disposable.dispose)
{ {
disposable.dispose(); disposable.dispose();
} }
@ -1268,6 +1282,7 @@ export function disposeObject(object)
/** /**
* @param {Object|Array} objectOrObjects * @param {Object|Array} objectOrObjects
* @returns {void}
*/ */
export function delegateRunOnDestroy(objectOrObjects) export function delegateRunOnDestroy(objectOrObjects)
{ {
@ -1286,6 +1301,11 @@ export function delegateRunOnDestroy(objectOrObjects)
} }
} }
/**
* @param {object} $styleTag
* @param {string} css
* @returns {boolean}
*/
export function appendStyles($styleTag, css) export function appendStyles($styleTag, css)
{ {
if ($styleTag && $styleTag[0]) if ($styleTag && $styleTag[0])
@ -1307,20 +1327,25 @@ export function appendStyles($styleTag, css)
let let
__themeTimer = 0, __themeTimer = 0,
__themeAjax = null __themeAjax = null;
;
/**
* @param {string} value
* @param {function} themeTrigger
* @returns {void}
*/
export function changeTheme(value, themeTrigger) export function changeTheme(value, themeTrigger)
{ {
let const
themeLink = $('#app-theme-link'), themeLink = $('#app-theme-link'),
themeStyle = $('#app-theme-style'),
url = themeLink.attr('href'),
clearTimer = () => { clearTimer = () => {
__themeTimer = window.setTimeout(() => themeTrigger(SaveSettingsStep.Idle), 1000); __themeTimer = window.setTimeout(() => themeTrigger(SaveSettingsStep.Idle), 1000);
__themeAjax = null; __themeAjax = null;
} };
;
let
themeStyle = $('#app-theme-style'),
url = themeLink.attr('href');
if (!url) if (!url)
{ {
@ -1375,6 +1400,9 @@ export function changeTheme(value, themeTrigger)
} }
} }
/**
* @returns {function}
*/
export function computedPagenatorHelper(koCurrentPage, koPageCount) export function computedPagenatorHelper(koCurrentPage, koPageCount)
{ {
return () => { return () => {
@ -1388,7 +1416,7 @@ export function computedPagenatorHelper(koCurrentPage, koPageCount)
const data = { const data = {
current: index === currentPage, current: index === currentPage,
name: '' === customName ? index.toString() : customName.toString(), name: '' === customName ? index.toString() : customName.toString(),
custom: '' === customName ? false : true, custom: '' !== customName,
title: '' === customName ? '' : index.toString(), title: '' === customName ? '' : index.toString(),
value: index.toString() value: index.toString()
}; };
@ -1401,14 +1429,12 @@ export function computedPagenatorHelper(koCurrentPage, koPageCount)
{ {
result.unshift(data); result.unshift(data);
} }
} };
;
let let
prev = 0, prev = 0,
next = 0, next = 0,
limit = 2 limit = 2;
;
if (1 < pageCount || (0 < pageCount && pageCount < currentPage)) if (1 < pageCount || (0 < pageCount && pageCount < currentPage))
{ {
@ -1438,13 +1464,13 @@ export function computedPagenatorHelper(koCurrentPage, koPageCount)
if (0 < prev) if (0 < prev)
{ {
fAdd(prev, false); fAdd(prev, false);
limit--; limit -= 1;
} }
if (pageCount >= next) if (pageCount >= next)
{ {
fAdd(next, true); fAdd(next, true);
limit--; limit -= 1;
} }
else if (0 >= prev) else if (0 >= prev)
{ {
@ -1488,7 +1514,7 @@ export function computedPagenatorHelper(koCurrentPage, koPageCount)
/** /**
* @param {string} fileName * @param {string} fileName
* @return {string} * @returns {string}
*/ */
export function getFileExtension(fileName) export function getFileExtension(fileName)
{ {
@ -1500,14 +1526,13 @@ export function getFileExtension(fileName)
/** /**
* @param {string} fileName * @param {string} fileName
* @return {string} * @returns {string}
*/ */
export function mimeContentType(fileName) export function mimeContentType(fileName)
{ {
let let
ext = '', ext = '',
result = 'application/octet-stream' result = 'application/octet-stream';
;
fileName = trim(fileName).toLowerCase(); fileName = trim(fileName).toLowerCase();
@ -1536,13 +1561,11 @@ export function resizeAndCrop(url, value, fCallback)
img.onload = function() { img.onload = function() {
let let
diff = [0, 0] diff = [0, 0];
;
const const
canvas = window.document.createElement('canvas'), canvas = window.document.createElement('canvas'),
ctx = canvas.getContext('2d') ctx = canvas.getContext('2d');
;
canvas.width = value; canvas.width = value;
canvas.height = value; canvas.height = value;
@ -1569,7 +1592,7 @@ export function resizeAndCrop(url, value, fCallback)
/** /**
* @param {string} mailToUrl * @param {string} mailToUrl
* @param {Function} PopupComposeVoreModel * @param {Function} PopupComposeVoreModel
* @return {boolean} * @returns {boolean}
*/ */
export function mailToHelper(mailToUrl, PopupComposeVoreModel) export function mailToHelper(mailToUrl, PopupComposeVoreModel)
{ {
@ -1586,22 +1609,22 @@ export function mailToHelper(mailToUrl, PopupComposeVoreModel)
to = [], to = [],
cc = null, cc = null,
bcc = null, bcc = null,
params = {}, params = {};
EmailModel = require('Model/Email'),
const
email = mailToUrl.replace(/\?.+$/, ''), email = mailToUrl.replace(/\?.+$/, ''),
queryString = mailToUrl.replace(/^[^\?]*\?/, ''), query = mailToUrl.replace(/^[^\?]*\?/, ''),
EmailModel = require('Model/Email'),
fParseEmailLine = (line) => { fParseEmailLine = (line) => {
return line ? _.compact(_.map(decodeURIComponent(line).split(/[,]/), (item) => { return line ? _.compact(_.map(decodeURIComponent(line).split(/[,]/), (item) => {
const emailObj = new EmailModel(); const emailObj = new EmailModel();
emailObj.mailsoParse(item); emailObj.mailsoParse(item);
return '' !== emailObj.email ? emailObj : null; return '' !== emailObj.email ? emailObj : null;
})) : null; })) : null;
} };
;
to = fParseEmailLine(email); to = fParseEmailLine(email);
params = simpleQueryParser(query);
params = simpleQueryParser(queryString);
if (!isUnd(params.cc)) if (!isUnd(params.cc))
{ {
@ -1638,16 +1661,19 @@ export const windowResize = _.debounce((timeout) => {
} }
}, 50); }, 50);
/**
* @returns {void}
*/
export function windowResizeCallback() export function windowResizeCallback()
{ {
windowResize(); windowResize();
} }
let substr = window.String.substr; let substr = window.String.substr;
if ('ab'.substr(-1) !== 'b') if ('b' !== 'ab'.substr(-1))
{ {
substr = (str, start, length) => { substr = (str, start, length) => {
start = start < 0 ? str.length + start : start; start = 0 > start ? str.length + start : start;
return str.substr(start, length); return str.substr(start, length);
}; };

View file

@ -6,6 +6,7 @@ import {AbstractComponent} from 'Component/Abstract';
class AbstracCheckbox extends AbstractComponent class AbstracCheckbox extends AbstractComponent
{ {
/** /**
* @constructor
* @param {Object} params = {} * @param {Object} params = {}
*/ */
constructor(params = {}) { constructor(params = {}) {

View file

@ -7,6 +7,7 @@ import {AbstractComponent} from 'Component/Abstract';
class AbstracRadio extends AbstractComponent class AbstracRadio extends AbstractComponent
{ {
/** /**
* @constructor
* @param {Object} params * @param {Object} params
*/ */
constructor(params) { constructor(params) {

View file

@ -22,7 +22,7 @@ class AbstractComponent
/** /**
* @param {*} ClassObject * @param {*} ClassObject
* @param {string} templateID = '' * @param {string} templateID = ''
* @return {Object} * @returns {Object}
*/ */
const componentExportHelper = (ClassObject, templateID = '') => { const componentExportHelper = (ClassObject, templateID = '') => {
return { return {

View file

@ -7,6 +7,7 @@ import {AbstractComponent} from 'Component/Abstract';
class AbstractInput extends AbstractComponent class AbstractInput extends AbstractComponent
{ {
/** /**
* @constructor
* @param {Object} params * @param {Object} params
*/ */
constructor(params) { constructor(params) {
@ -32,10 +33,9 @@ class AbstractInput extends AbstractComponent
var var
size = ko.unwrap(this.size), size = ko.unwrap(this.size),
suffixValue = this.trigger ? suffixValue = this.trigger ?
' ' + trim('settings-saved-trigger-input ' + this.classForTrigger()) : '' ' ' + trim('settings-saved-trigger-input ' + this.classForTrigger()) : '';
;
return (size > 0 ? 'span' + size : '') + suffixValue; return (0 < size ? 'span' + size : '') + suffixValue;
}, this); }, this);

View file

@ -7,6 +7,7 @@ import {AbstracCheckbox} from 'Component/AbstracCheckbox';
class CheckboxMaterialDesignComponent extends AbstracCheckbox class CheckboxMaterialDesignComponent extends AbstracCheckbox
{ {
/** /**
* @constructor
* @param {Object} params * @param {Object} params
*/ */
constructor(params) { constructor(params) {
@ -38,7 +39,8 @@ class CheckboxMaterialDesignComponent extends AbstracCheckbox
if (box) { if (box) {
this.animationBoxSetTrue(); this.animationBoxSetTrue();
_.delay(this.animationCheckmarkSetTrue, 200); _.delay(this.animationCheckmarkSetTrue, 200);
} else { }
else {
this.animationCheckmarkSetTrue(); this.animationCheckmarkSetTrue();
_.delay(this.animationBoxSetTrue, 200); _.delay(this.animationBoxSetTrue, 200);
} }

View file

@ -6,6 +6,7 @@ import {AbstractComponent, componentExportHelper} from 'Component/Abstract';
class SaveTriggerComponent extends AbstractComponent class SaveTriggerComponent extends AbstractComponent
{ {
/** /**
* @constructor
* @param {Object} params * @param {Object} params
*/ */
constructor(params) { constructor(params) {
@ -47,30 +48,26 @@ class SaveTriggerComponent extends AbstractComponent
this.element this.element
.find('.animated,.error').hide().removeClass('visible') .find('.animated,.error').hide().removeClass('visible')
.end() .end()
.find('.success').show().addClass('visible') .find('.success').show().addClass('visible');
;
break; break;
case SaveSettingsStep.FalseResult: case SaveSettingsStep.FalseResult:
this.element this.element
.find('.animated,.success').hide().removeClass('visible') .find('.animated,.success').hide().removeClass('visible')
.end() .end()
.find('.error').show().addClass('visible') .find('.error').show().addClass('visible');
;
break; break;
case SaveSettingsStep.Animate: case SaveSettingsStep.Animate:
this.element this.element
.find('.error,.success').hide().removeClass('visible') .find('.error,.success').hide().removeClass('visible')
.end() .end()
.find('.animated').show().addClass('visible') .find('.animated').show().addClass('visible');
;
break; break;
default:
case SaveSettingsStep.Idle: case SaveSettingsStep.Idle:
default:
this.element this.element
.find('.animated').hide() .find('.animated').hide()
.end() .end()
.find('.error,.success').removeClass('visible') .find('.error,.success').removeClass('visible');
;
break; break;
} }
} }

View file

@ -5,6 +5,7 @@ import {AbstractComponent, componentExportHelper} from 'Component/Abstract';
class ScriptComponent extends AbstractComponent class ScriptComponent extends AbstractComponent
{ {
/** /**
* @constructor
* @param {Object} params * @param {Object} params
*/ */
constructor(params) { constructor(params) {
@ -17,8 +18,7 @@ class ScriptComponent extends AbstractComponent
let script = params.element[0].outerHTML; let script = params.element[0].outerHTML;
script = !script ? '' : script script = !script ? '' : script
.replace(/<x-script/i, '<script') .replace(/<x-script/i, '<script')
.replace(/<b><\/b><\/x-script>/i, '</script>') .replace(/<b><\/b><\/x-script>/i, '</script>');
;
if (script) if (script)
{ {

View file

@ -7,6 +7,7 @@ import {AbstractInput} from 'Component/AbstractInput';
class SelectComponent extends AbstractInput class SelectComponent extends AbstractInput
{ {
/** /**
* @constructor
* @param {Object} params * @param {Object} params
*/ */
constructor(params) { constructor(params) {

View file

@ -1,28 +1,25 @@
import {$} from 'common'; import {$} from 'common';
let let cachedUrl = null;
cachedUrl = null, const getUrl = () => {
getUtl = () => { if (!cachedUrl)
if (!cachedUrl) {
{ const version = $('#rlAppVersion').attr('content') || '0.0.0';
const version = $('#rlAppVersion').attr('content') || '0.0.0'; cachedUrl = `rainloop/v/${version}/static/css/svg/icons.svg`;
cachedUrl = `rainloop/v/${version}/static/css/svg/icons.svg`;
}
return cachedUrl;
} }
;
return cachedUrl;
};
module.exports = { module.exports = {
template: '<b></b>', template: '<b></b>',
viewModel: { viewModel: {
createViewModel: (params, componentInfo) => { createViewModel: ({icon = 'null'}, componentInfo) => {
if (componentInfo && componentInfo.element) if (componentInfo && componentInfo.element)
{ {
const icon = params.icon || 'null';
$(componentInfo.element).replaceWith( $(componentInfo.element).replaceWith(
`<svg class="svg-icon svg-icon-${icon}"><use xlink:href="${getUtl()}#svg-icon-${icon}"></use></svg>` `<svg class="svg-icon svg-icon-${icon}"><use xlink:href="${getUrl()}#svg-icon-${icon}"></use></svg>`
); );
} }
} }

View file

@ -6,6 +6,7 @@ import {AbstractInput} from 'Component/AbstractInput';
class TextAreaComponent extends AbstractInput class TextAreaComponent extends AbstractInput
{ {
/** /**
* @constructor
* @param {Object} params * @param {Object} params
*/ */
constructor(params) { constructor(params) {

View file

@ -1,51 +1,44 @@
(function () { var
window = require('window'),
Opentip = window.Opentip;
'use strict'; Opentip.styles.rainloop = {
var 'extends': 'standard',
window = require('window'),
Opentip = window.Opentip
;
Opentip.styles.rainloop = { 'fixed': true,
'target': true,
'extends': 'standard', 'delay': 0.2,
'hideDelay': 0,
'fixed': true, 'hideEffect': 'fade',
'target': true, 'hideEffectDuration': 0.2,
'delay': 0.2, 'showEffect': 'fade',
'hideDelay': 0, 'showEffectDuration': 0.2,
'hideEffect': 'fade', 'showOn': 'mouseover click',
'hideEffectDuration': 0.2, 'removeElementsOnHide': true,
'showEffect': 'fade', 'background': '#fff',
'showEffectDuration': 0.2, 'shadow': false,
'showOn': 'mouseover click', 'borderColor': '#999',
'removeElementsOnHide': true, 'borderRadius': 2,
'borderWidth': 1
};
'background': '#fff', Opentip.styles.rainloopTip = {
'shadow': false, 'extends': 'rainloop',
'delay': 0.4,
'group': 'rainloopTips'
};
'borderColor': '#999', Opentip.styles.rainloopErrorTip = {
'borderRadius': 2, 'extends': 'rainloop',
'borderWidth': 1 'className': 'rainloopErrorTip'
}; };
Opentip.styles.rainloopTip = { module.exports = Opentip;
'extends': 'rainloop',
'delay': 0.4,
'group': 'rainloopTips'
};
Opentip.styles.rainloopErrorTip = {
'extends': 'rainloop',
'className': 'rainloopErrorTip'
};
module.exports = Opentip;
}());

2237
dev/External/ko.js vendored

File diff suppressed because it is too large Load diff

View file

@ -4,25 +4,25 @@ import EmailModel from 'Model/Email';
class MessageHelper class MessageHelper
{ {
/**
* @constructor
*/
constructor() {} constructor() {}
/** /**
* @param {Array.<EmailModel>} emails * @param {Array.<EmailModel>} emails
* @param {boolean=} friendlyView = false * @param {boolean=} friendlyView = false
* @param {boolean=} wrapWithLink = false * @param {boolean=} wrapWithLink = false
* @return {string} * @returns {string}
*/ */
emailArrayToString(emails, friendlyView = false, wrapWithLink = false) { emailArrayToString(emails, friendlyView = false, wrapWithLink = false) {
let let index = 0, len = 0;
result = [], const result = [];
index = 0,
len = 0
;
if (isNonEmptyArray(emails)) if (isNonEmptyArray(emails))
{ {
for (index = 0, len = emails.length; index < len; index++) for (len = emails.length; index < len; index++)
{ {
result.push(emails[index].toLine(friendlyView, wrapWithLink)); result.push(emails[index].toLine(friendlyView, wrapWithLink));
} }
@ -33,19 +33,16 @@ class MessageHelper
/** /**
* @param {Array.<EmailModel>} emails * @param {Array.<EmailModel>} emails
* @return {string} * @returns {string}
*/ */
emailArrayToStringClear(emails) { emailArrayToStringClear(emails) {
let let index = 0, len = 0;
result = [], const result = [];
index = 0,
len = 0
;
if (isNonEmptyArray(emails)) if (isNonEmptyArray(emails))
{ {
for (index = 0, len = emails.length; index < len; index++) for (len = emails.length; index < len; index++)
{ {
if (emails[index] && emails[index].email && '' !== emails[index].name) if (emails[index] && emails[index].email && '' !== emails[index].name)
{ {
@ -59,16 +56,12 @@ class MessageHelper
/** /**
* @param {?Array} json * @param {?Array} json
* @return {Array.<EmailModel>} * @returns {Array.<EmailModel>}
*/ */
emailArrayFromJson(json) { emailArrayFromJson(json) {
let let index = 0, len = 0, email = null;
index = 0, const result = [];
len = 0,
email = null,
result = []
;
if (isNonEmptyArray(json)) if (isNonEmptyArray(json))
{ {

View file

@ -1,48 +1,41 @@
(function () { var
_ = require('_'),
'use strict'; Utils = require('Common/Utils');
var /**
_ = require('_'), * @constructor
*
* @param {string} sModelName
*/
function AbstractModel(sModelName)
{
this.sModelName = sModelName || '';
this.disposables = [];
}
Utils = require('Common/Utils') /**
; * @param {Array|Object} mInputValue
*/
/** AbstractModel.prototype.regDisposables = function(mInputValue)
* @constructor {
* if (Utils.isArray(mInputValue))
* @param {string} sModelName
*/
function AbstractModel(sModelName)
{ {
this.sModelName = sModelName || ''; _.each(mInputValue, function(mValue) {
this.disposables = []; this.disposables.push(mValue);
}, this);
}
else if (mInputValue)
{
this.disposables.push(mInputValue);
} }
/** };
* @param {Array|Object} mInputValue
*/
AbstractModel.prototype.regDisposables = function (mInputValue)
{
if (Utils.isArray(mInputValue))
{
_.each(mInputValue, function (mValue) {
this.disposables.push(mValue);
}, this);
}
else if (mInputValue)
{
this.disposables.push(mInputValue);
}
}; AbstractModel.prototype.onDestroy = function()
{
Utils.disposeObject(this);
};
AbstractModel.prototype.onDestroy = function () module.exports = AbstractModel;
{
Utils.disposeObject(this);
};
module.exports = AbstractModel;
}());

View file

@ -1,91 +1,83 @@
(function () { var
_ = require('_'),
crossroads = require('crossroads'),
'use strict'; Utils = require('Common/Utils');
/**
* @param {string} sScreenName
* @param {?=} aViewModels = []
* @constructor
*/
function AbstractScreen(sScreenName, aViewModels)
{
this.sScreenName = sScreenName;
this.aViewModels = Utils.isArray(aViewModels) ? aViewModels : [];
}
/**
* @type {Array}
*/
AbstractScreen.prototype.oCross = null;
/**
* @type {string}
*/
AbstractScreen.prototype.sScreenName = '';
/**
* @type {Array}
*/
AbstractScreen.prototype.aViewModels = [];
/**
* @returns {Array}
*/
AbstractScreen.prototype.viewModels = function()
{
return this.aViewModels;
};
/**
* @returns {string}
*/
AbstractScreen.prototype.screenName = function()
{
return this.sScreenName;
};
AbstractScreen.prototype.routes = function()
{
return null;
};
/**
* @returns {?Object}
*/
AbstractScreen.prototype.__cross = function()
{
return this.oCross;
};
AbstractScreen.prototype.__start = function()
{
var var
_ = require('_'), aRoutes = this.routes(),
crossroads = require('crossroads'), oRoute = null,
fMatcher = null;
Utils = require('Common/Utils') if (Utils.isNonEmptyArray(aRoutes))
;
/**
* @param {string} sScreenName
* @param {?=} aViewModels = []
* @constructor
*/
function AbstractScreen(sScreenName, aViewModels)
{ {
this.sScreenName = sScreenName; fMatcher = _.bind(this.onRoute || Utils.noop, this);
this.aViewModels = Utils.isArray(aViewModels) ? aViewModels : []; oRoute = crossroads.create();
_.each(aRoutes, function(aItem) {
oRoute.addRoute(aItem[0], fMatcher).rules = aItem[1];
});
this.oCross = oRoute;
} }
};
/** module.exports = AbstractScreen;
* @type {Array}
*/
AbstractScreen.prototype.oCross = null;
/**
* @type {string}
*/
AbstractScreen.prototype.sScreenName = '';
/**
* @type {Array}
*/
AbstractScreen.prototype.aViewModels = [];
/**
* @return {Array}
*/
AbstractScreen.prototype.viewModels = function ()
{
return this.aViewModels;
};
/**
* @return {string}
*/
AbstractScreen.prototype.screenName = function ()
{
return this.sScreenName;
};
AbstractScreen.prototype.routes = function ()
{
return null;
};
/**
* @return {?Object}
*/
AbstractScreen.prototype.__cross = function ()
{
return this.oCross;
};
AbstractScreen.prototype.__start = function ()
{
var
aRoutes = this.routes(),
oRoute = null,
fMatcher = null
;
if (Utils.isNonEmptyArray(aRoutes))
{
fMatcher = _.bind(this.onRoute || Utils.noop, this);
oRoute = crossroads.create();
_.each(aRoutes, function (aItem) {
oRoute.addRoute(aItem[0], fMatcher).rules = aItem[1];
});
this.oCross = oRoute;
}
};
module.exports = AbstractScreen;
}());

View file

@ -1,130 +1,123 @@
(function () { var
ko = require('ko'),
'use strict'; Enums = require('Common/Enums'),
Utils = require('Common/Utils'),
Globals = require('Common/Globals');
var /**
ko = require('ko'), * @constructor
* @param {string=} sPosition = ''
* @param {string=} sTemplate = ''
*/
function AbstractView(sPosition, sTemplate)
{
this.bDisabeCloseOnEsc = false;
this.sPosition = Utils.pString(sPosition);
this.sTemplate = Utils.pString(sTemplate);
Enums = require('Common/Enums'), this.sDefaultKeyScope = Enums.KeyState.None;
Utils = require('Common/Utils'), this.sCurrentKeyScope = this.sDefaultKeyScope;
Globals = require('Common/Globals')
;
/** this.viewModelVisibility = ko.observable(false);
* @constructor this.modalVisibility = ko.observable(false).extend({'rateLimit': 0});
* @param {string=} sPosition = ''
* @param {string=} sTemplate = ''
*/
function AbstractView(sPosition, sTemplate)
{
this.bDisabeCloseOnEsc = false;
this.sPosition = Utils.pString(sPosition);
this.sTemplate = Utils.pString(sTemplate);
this.sDefaultKeyScope = Enums.KeyState.None; this.viewModelName = '';
this.sCurrentKeyScope = this.sDefaultKeyScope; this.viewModelNames = [];
this.viewModelDom = null;
}
this.viewModelVisibility = ko.observable(false); /**
this.modalVisibility = ko.observable(false).extend({'rateLimit': 0}); * @type {boolean}
*/
AbstractView.prototype.bDisabeCloseOnEsc = false;
this.viewModelName = ''; /**
this.viewModelNames = []; * @type {string}
this.viewModelDom = null; */
} AbstractView.prototype.sPosition = '';
/** /**
* @type {boolean} * @type {string}
*/ */
AbstractView.prototype.bDisabeCloseOnEsc = false; AbstractView.prototype.sTemplate = '';
/** /**
* @type {string} * @type {string}
*/ */
AbstractView.prototype.sPosition = ''; AbstractView.prototype.sDefaultKeyScope = Enums.KeyState.None;
/** /**
* @type {string} * @type {string}
*/ */
AbstractView.prototype.sTemplate = ''; AbstractView.prototype.sCurrentKeyScope = Enums.KeyState.None;
/** /**
* @type {string} * @type {string}
*/ */
AbstractView.prototype.sDefaultKeyScope = Enums.KeyState.None; AbstractView.prototype.viewModelName = '';
/** /**
* @type {string} * @type {Array}
*/ */
AbstractView.prototype.sCurrentKeyScope = Enums.KeyState.None; AbstractView.prototype.viewModelNames = [];
/** /**
* @type {string} * @type {?}
*/ */
AbstractView.prototype.viewModelName = ''; AbstractView.prototype.viewModelDom = null;
/** /**
* @type {Array} * @returns {string}
*/ */
AbstractView.prototype.viewModelNames = []; AbstractView.prototype.viewModelTemplate = function()
{
return this.sTemplate;
};
/** /**
* @type {?} * @returns {string}
*/ */
AbstractView.prototype.viewModelDom = null; AbstractView.prototype.viewModelPosition = function()
{
return this.sPosition;
};
/** AbstractView.prototype.cancelCommand = function() {};
* @return {string} AbstractView.prototype.closeCommand = function() {};
*/
AbstractView.prototype.viewModelTemplate = function ()
{
return this.sTemplate;
};
/** AbstractView.prototype.storeAndSetKeyScope = function()
* @return {string} {
*/ this.sCurrentKeyScope = Globals.keyScope();
AbstractView.prototype.viewModelPosition = function () Globals.keyScope(this.sDefaultKeyScope);
{ };
return this.sPosition;
};
AbstractView.prototype.cancelCommand = function () {}; AbstractView.prototype.restoreKeyScope = function()
AbstractView.prototype.closeCommand = function () {}; {
Globals.keyScope(this.sCurrentKeyScope);
};
AbstractView.prototype.storeAndSetKeyScope = function () AbstractView.prototype.registerPopupKeyDown = function()
{ {
this.sCurrentKeyScope = Globals.keyScope(); var self = this;
Globals.keyScope(this.sDefaultKeyScope);
};
AbstractView.prototype.restoreKeyScope = function () Globals.$win.on('keydown', function(oEvent) {
{ if (oEvent && self.modalVisibility && self.modalVisibility())
Globals.keyScope(this.sCurrentKeyScope); {
}; if (!this.bDisabeCloseOnEsc && Enums.EventKeyCode.Esc === oEvent.keyCode)
AbstractView.prototype.registerPopupKeyDown = function ()
{
var self = this;
Globals.$win.on('keydown', function (oEvent) {
if (oEvent && self.modalVisibility && self.modalVisibility())
{ {
if (!this.bDisabeCloseOnEsc && Enums.EventKeyCode.Esc === oEvent.keyCode) Utils.delegateRun(self, 'cancelCommand');
{ return false;
Utils.delegateRun(self, 'cancelCommand');
return false;
}
else if (Enums.EventKeyCode.Backspace === oEvent.keyCode && !Utils.inFocus())
{
return false;
}
} }
else if (Enums.EventKeyCode.Backspace === oEvent.keyCode && !Utils.inFocus())
{
return false;
}
}
return true; return true;
}); });
}; };
module.exports = AbstractView; module.exports = AbstractView;
}());

View file

@ -1,512 +1,497 @@
(function () { var
_ = require('_'),
$ = require('$'),
ko = require('ko'),
hasher = require('hasher'),
crossroads = require('crossroads'),
'use strict'; Globals = require('Common/Globals'),
Plugins = require('Common/Plugins'),
Utils = require('Common/Utils');
var /**
_ = require('_'), * @constructor
$ = require('$'), */
ko = require('ko'), function Knoin()
hasher = require('hasher'), {
crossroads = require('crossroads'), this.oScreens = {};
this.sDefaultScreenName = '';
this.oCurrentScreen = null;
}
Globals = require('Common/Globals'), Knoin.prototype.oScreens = {};
Plugins = require('Common/Plugins'), Knoin.prototype.sDefaultScreenName = '';
Utils = require('Common/Utils') Knoin.prototype.oCurrentScreen = null;
;
/** Knoin.prototype.hideLoading = function()
* @constructor {
*/ $('#rl-content').addClass('rl-content-show');
function Knoin() $('#rl-loading').hide().remove();
};
/**
* @param {Object} context
*/
Knoin.prototype.constructorEnd = function(context)
{
if (Utils.isFunc(context.__constructor_end))
{ {
this.oScreens = {}; context.__constructor_end.call(context);
this.sDefaultScreenName = '';
this.oCurrentScreen = null;
} }
};
Knoin.prototype.oScreens = {}; /**
Knoin.prototype.sDefaultScreenName = ''; * @param {string|Array} mName
Knoin.prototype.oCurrentScreen = null; * @param {Function} ViewModelClass
*/
Knoin.prototype.hideLoading = function () Knoin.prototype.extendAsViewModel = function(mName, ViewModelClass)
{
if (ViewModelClass)
{ {
$('#rl-content').addClass('rl-content-show'); if (Utils.isArray(mName))
$('#rl-loading').hide().remove();
};
/**
* @param {Object} context
*/
Knoin.prototype.constructorEnd = function (context)
{
if (Utils.isFunc(context.__constructor_end))
{ {
context.__constructor_end.call(context); ViewModelClass.__names = mName;
}
};
/**
* @param {string|Array} mName
* @param {Function} ViewModelClass
*/
Knoin.prototype.extendAsViewModel = function (mName, ViewModelClass)
{
if (ViewModelClass)
{
if (Utils.isArray(mName))
{
ViewModelClass.__names = mName;
}
else
{
ViewModelClass.__names = [mName];
}
ViewModelClass.__name = ViewModelClass.__names[0];
}
};
/**
* @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.onShowTrigger = ko.observable(false);
oViewModel.onHideTrigger = ko.observable(false);
oViewModel.viewModelName = ViewModelClass.__name;
oViewModel.viewModelNames = ViewModelClass.__names;
if (oViewModelPlace && 1 === oViewModelPlace.length)
{
oViewModelDom = $('<div></div>').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();
Globals.popupVisibilityNames.push(this.viewModelName);
oViewModel.viewModelDom.css('z-index', 3000 + Globals.popupVisibilityNames().length + 10);
if (this.onShowTrigger)
{
this.onShowTrigger(!this.onShowTrigger());
}
Utils.delegateRun(this, 'onShowWithDelay', [], 500);
}
else
{
Utils.delegateRun(this, 'onHide');
Utils.delegateRun(this, 'onHideWithDelay', [], 500);
if (this.onHideTrigger)
{
this.onHideTrigger(!this.onHideTrigger());
}
this.restoreKeyScope();
_.each(this.viewModelNames, function (sName) {
Plugins.runHook('view-model-on-hide', [sName, self]);
});
Globals.popupVisibilityNames.remove(this.viewModelName);
oViewModel.viewModelDom.css('z-index', 2000);
_.delay(function () {
self.viewModelDom.hide();
}, 300);
}
}, oViewModel);
}
_.each(ViewModelClass.__names, function (sName) {
Plugins.runHook('view-model-pre-build', [sName, oViewModel, oViewModelDom]);
});
ko.applyBindingAccessorsToNode(oViewModelDom[0], {
'translatorInit': true,
'template': function () { return {'name': oViewModel.viewModelTemplate()};}
}, oViewModel);
Utils.delegateRun(oViewModel, 'onBuild', [oViewModelDom]);
if (oViewModel && 'Popups' === sPosition)
{
oViewModel.registerPopupKeyDown();
}
_.each(ViewModelClass.__names, function (sName) {
Plugins.runHook('view-model-post-build', [sName, 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);
}
};
/**
* @param {Function} ViewModelClassToShow
* @param {Array=} aParameters
*/
Knoin.prototype.showScreenPopup = function (ViewModelClassToShow, aParameters)
{
if (ViewModelClassToShow)
{
this.buildViewModel(ViewModelClassToShow);
if (ViewModelClassToShow.__vm && ViewModelClassToShow.__dom)
{
Utils.delegateRun(ViewModelClassToShow.__vm, 'onBeforeShow', aParameters || []);
ViewModelClassToShow.__vm.modalVisibility(true);
Utils.delegateRun(ViewModelClassToShow.__vm, 'onShow', aParameters || []);
_.each(ViewModelClassToShow.__names, function (sName) {
Plugins.runHook('view-model-on-show', [sName, 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,
bSameScreen = false,
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)
{
bSameScreen = this.oCurrentScreen && oScreen === this.oCurrentScreen;
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 && !bSameScreen)
{
Utils.delegateRun(self.oCurrentScreen, 'onHide');
Utils.delegateRun(self.oCurrentScreen, 'onHideWithDelay', [], 500);
if (self.oCurrentScreen.onHideTrigger)
{
self.oCurrentScreen.onHideTrigger(!self.oCurrentScreen.onHideTrigger());
}
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');
Utils.delegateRun(ViewModelClass.__vm, 'onHideWithDelay', [], 500);
if (ViewModelClass.__vm.onHideTrigger)
{
ViewModelClass.__vm.onHideTrigger(!ViewModelClass.__vm.onHideTrigger());
}
}
});
}
}
// --
self.oCurrentScreen = oScreen;
// show screen
if (self.oCurrentScreen && !bSameScreen)
{
Utils.delegateRun(self.oCurrentScreen, 'onShow');
if (self.oCurrentScreen.onShowTrigger)
{
self.oCurrentScreen.onShowTrigger(!self.oCurrentScreen.onShowTrigger());
}
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())
{
Utils.delegateRun(ViewModelClass.__vm, 'onBeforeShow');
ViewModelClass.__dom.show();
ViewModelClass.__vm.viewModelVisibility(true);
Utils.delegateRun(ViewModelClass.__vm, 'onShow');
if (ViewModelClass.__vm.onShowTrigger)
{
ViewModelClass.__vm.onShowTrigger(!ViewModelClass.__vm.onShowTrigger());
}
Utils.delegateRun(ViewModelClass.__vm, 'onShowWithDelay', [], 200);
_.each(ViewModelClass.__names, function (sName) {
Plugins.runHook('view-model-on-show', [sName, ViewModelClass.__vm]);
});
}
}, self);
}
}
// --
oCross = oScreen.__cross ? oScreen.__cross() : null;
if (oCross)
{
oCross.parse(sSubPart);
}
});
}
}
};
/**
* @param {Array} aScreensClasses
*/
Knoin.prototype.startScreens = function (aScreensClasses)
{
// $('#rl-content').css({
// 'visibility': 'hidden'
// });
_.each(aScreensClasses, function (CScreen) {
if (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 () {
Globals.$html.removeClass('rl-started-trigger').addClass('rl-started');
}, 100);
_.delay(function () {
Globals.$html.addClass('rl-started-delay');
}, 200);
};
/**
* @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 else
{ {
hasher.changed.active = true; ViewModelClass.__names = [mName];
hasher[bReplace ? 'replaceHash' : 'setHash'](sHash);
hasher.setHash(sHash);
} }
ViewModelClass.__name = ViewModelClass.__names[0];
}
};
/**
* @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
}; };
module.exports = new Knoin(); 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
* @returns {?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.onShowTrigger = ko.observable(false);
oViewModel.onHideTrigger = ko.observable(false);
oViewModel.viewModelName = ViewModelClass.__name;
oViewModel.viewModelNames = ViewModelClass.__names;
if (oViewModelPlace && 1 === oViewModelPlace.length)
{
oViewModelDom = $('<div></div>').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, _.bind(function() {
this.hideScreenPopup(ViewModelClass);
}, this));
oViewModel.modalVisibility.subscribe(function(bValue) {
var self = this;
if (bValue)
{
this.viewModelDom.show();
this.storeAndSetKeyScope();
Globals.popupVisibilityNames.push(this.viewModelName);
oViewModel.viewModelDom.css('z-index', 3000 + Globals.popupVisibilityNames().length + 10);
if (this.onShowTrigger)
{
this.onShowTrigger(!this.onShowTrigger());
}
Utils.delegateRun(this, 'onShowWithDelay', [], 500);
}
else
{
Utils.delegateRun(this, 'onHide');
Utils.delegateRun(this, 'onHideWithDelay', [], 500);
if (this.onHideTrigger)
{
this.onHideTrigger(!this.onHideTrigger());
}
this.restoreKeyScope();
_.each(this.viewModelNames, function(sName) {
Plugins.runHook('view-model-on-hide', [sName, self]);
});
Globals.popupVisibilityNames.remove(this.viewModelName);
oViewModel.viewModelDom.css('z-index', 2000);
_.delay(function() {
self.viewModelDom.hide();
}, 300);
}
}, oViewModel);
}
_.each(ViewModelClass.__names, function(sName) {
Plugins.runHook('view-model-pre-build', [sName, oViewModel, oViewModelDom]);
});
ko.applyBindingAccessorsToNode(oViewModelDom[0], {
translatorInit: true,
template: function() {
return {
name: oViewModel.viewModelTemplate()
};
}
}, oViewModel);
Utils.delegateRun(oViewModel, 'onBuild', [oViewModelDom]);
if (oViewModel && 'Popups' === sPosition)
{
oViewModel.registerPopupKeyDown();
}
_.each(ViewModelClass.__names, function(sName) {
Plugins.runHook('view-model-post-build', [sName, 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);
}
};
/**
* @param {Function} ViewModelClassToShow
* @param {Array=} aParameters
*/
Knoin.prototype.showScreenPopup = function(ViewModelClassToShow, aParameters)
{
if (ViewModelClassToShow)
{
this.buildViewModel(ViewModelClassToShow);
if (ViewModelClassToShow.__vm && ViewModelClassToShow.__dom)
{
Utils.delegateRun(ViewModelClassToShow.__vm, 'onBeforeShow', aParameters || []);
ViewModelClassToShow.__vm.modalVisibility(true);
Utils.delegateRun(ViewModelClassToShow.__vm, 'onShow', aParameters || []);
_.each(ViewModelClassToShow.__names, function(sName) {
Plugins.runHook('view-model-on-show', [sName, ViewModelClassToShow.__vm, aParameters || []]);
});
}
}
};
/**
* @param {Function} ViewModelClassToShow
* @returns {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,
bSameScreen = false,
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)
{
bSameScreen = this.oCurrentScreen && oScreen === this.oCurrentScreen;
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 && !bSameScreen)
{
Utils.delegateRun(self.oCurrentScreen, 'onHide');
Utils.delegateRun(self.oCurrentScreen, 'onHideWithDelay', [], 500);
if (self.oCurrentScreen.onHideTrigger)
{
self.oCurrentScreen.onHideTrigger(!self.oCurrentScreen.onHideTrigger());
}
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');
Utils.delegateRun(ViewModelClass.__vm, 'onHideWithDelay', [], 500);
if (ViewModelClass.__vm.onHideTrigger)
{
ViewModelClass.__vm.onHideTrigger(!ViewModelClass.__vm.onHideTrigger());
}
}
});
}
}
// --
self.oCurrentScreen = oScreen;
// show screen
if (self.oCurrentScreen && !bSameScreen)
{
Utils.delegateRun(self.oCurrentScreen, 'onShow');
if (self.oCurrentScreen.onShowTrigger)
{
self.oCurrentScreen.onShowTrigger(!self.oCurrentScreen.onShowTrigger());
}
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())
{
Utils.delegateRun(ViewModelClass.__vm, 'onBeforeShow');
ViewModelClass.__dom.show();
ViewModelClass.__vm.viewModelVisibility(true);
Utils.delegateRun(ViewModelClass.__vm, 'onShow');
if (ViewModelClass.__vm.onShowTrigger)
{
ViewModelClass.__vm.onShowTrigger(!ViewModelClass.__vm.onShowTrigger());
}
Utils.delegateRun(ViewModelClass.__vm, 'onShowWithDelay', [], 200);
_.each(ViewModelClass.__names, function(sName) {
Plugins.runHook('view-model-on-show', [sName, ViewModelClass.__vm]);
});
}
}, self);
}
}
// --
oCross = oScreen.__cross ? oScreen.__cross() : null;
if (oCross)
{
oCross.parse(sSubPart);
}
});
}
}
};
/**
* @param {Array} aScreensClasses
*/
Knoin.prototype.startScreens = function(aScreensClasses)
{
_.each(aScreensClasses, function(CScreen) {
if (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();
_.delay(function() {
Globals.$html.removeClass('rl-started-trigger').addClass('rl-started');
}, 100);
_.delay(function() {
Globals.$html.addClass('rl-started-delay');
}, 200);
};
/**
* @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);
}
};
module.exports = new Knoin();

View file

@ -1,52 +1,45 @@
(function () { var
_ = require('_'),
ko = require('ko'),
'use strict'; Utils = require('Common/Utils'),
var AbstractModel = require('Knoin/AbstractModel');
_ = require('_'),
ko = require('ko'),
Utils = require('Common/Utils'), /**
* @constructor
*
* @param {string} sEmail
* @param {boolean=} bCanBeDelete = true
* @param {number=} iCount = 0
*/
function AccountModel(sEmail, bCanBeDelete, iCount)
{
AbstractModel.call(this, 'AccountModel');
AbstractModel = require('Knoin/AbstractModel') this.email = sEmail;
;
/** this.count = ko.observable(iCount || 0);
* @constructor
*
* @param {string} sEmail
* @param {boolean=} bCanBeDelete = true
* @param {number=} iCount = 0
*/
function AccountModel(sEmail, bCanBeDelete, iCount)
{
AbstractModel.call(this, 'AccountModel');
this.email = sEmail; this.deleteAccess = ko.observable(false);
this.canBeDeleted = ko.observable(Utils.isUnd(bCanBeDelete) ? true : !!bCanBeDelete);
this.canBeEdit = this.canBeDeleted;
}
this.count = ko.observable(iCount || 0); _.extend(AccountModel.prototype, AbstractModel.prototype);
this.deleteAccess = ko.observable(false); /**
this.canBeDeleted = ko.observable(Utils.isUnd(bCanBeDelete) ? true : !!bCanBeDelete); * @type {string}
this.canBeEdit = this.canBeDeleted; */
} AccountModel.prototype.email = '';
_.extend(AccountModel.prototype, AbstractModel.prototype); /**
* @returns {string}
*/
AccountModel.prototype.changeAccountLink = function()
{
return require('Common/Links').change(this.email);
};
/** module.exports = AccountModel;
* @type {string}
*/
AccountModel.prototype.email = '';
/**
* @return {string}
*/
AccountModel.prototype.changeAccountLink = function ()
{
return require('Common/Links').change(this.email);
};
module.exports = AccountModel;
}());

File diff suppressed because it is too large Load diff

View file

@ -1,130 +1,123 @@
(function () { var
_ = require('_'),
ko = require('ko'),
'use strict'; Utils = require('Common/Utils'),
var AttachmentModel = require('Model/Attachment'),
_ = require('_'),
ko = require('ko'),
Utils = require('Common/Utils'), AbstractModel = require('Knoin/AbstractModel');
AttachmentModel = require('Model/Attachment'), /**
* @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)
{
AbstractModel.call(this, 'ComposeAttachmentModel');
AbstractModel = require('Knoin/AbstractModel') 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);
* @constructor this.size = ko.observable(Utils.isUnd(nSize) ? null : nSize);
* @param {string} sId this.tempName = ko.observable('');
* @param {string} sFileName
* @param {?number=} nSize this.progress = ko.observable(0);
* @param {boolean=} bInline this.error = ko.observable('');
* @param {boolean=} bLinked this.waiting = ko.observable(true);
* @param {string=} sCID this.uploading = ko.observable(false);
* @param {string=} sContentLocation this.enabled = ko.observable(true);
*/ this.complete = ko.observable(false);
function ComposeAttachmentModel(sId, sFileName, nSize, bInline, bLinked, sCID, sContentLocation)
this.progressText = ko.computed(function() {
var iP = this.progress();
return 0 === iP ? '' : '' + (98 < iP ? 100 : iP) + '%';
}, this);
this.progressStyle = ko.computed(function() {
var iP = this.progress();
return 0 === iP ? '' : 'width:' + (98 < iP ? 100 : iP) + '%';
}, this);
this.title = ko.computed(function() {
var sError = this.error();
return '' !== sError ? sError : this.fileName();
}, this);
this.friendlySize = ko.computed(function() {
var mSize = this.size();
return null === mSize ? '' : Utils.friendlySize(this.size());
}, this);
this.mimeType = ko.computed(function() {
return Utils.mimeContentType(this.fileName());
}, this);
this.fileExt = ko.computed(function() {
return Utils.getFileExtension(this.fileName());
}, this);
this.regDisposables([this.progressText, this.progressStyle, this.title, this.friendlySize, this.mimeType, this.fileExt]);
}
_.extend(ComposeAttachmentModel.prototype, AbstractModel.prototype);
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.noop;
/**
* @param {AjaxJsonComposeAttachment} oJsonAttachment
* @returns {boolean}
*/
ComposeAttachmentModel.prototype.initByUploadJson = function(oJsonAttachment)
{
var bResult = false;
if (oJsonAttachment)
{ {
AbstractModel.call(this, 'ComposeAttachmentModel'); 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;
this.id = sId; bResult = true;
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(0);
this.error = ko.observable('');
this.waiting = ko.observable(true);
this.uploading = ko.observable(false);
this.enabled = ko.observable(true);
this.complete = ko.observable(false);
this.progressText = ko.computed(function () {
var iP = this.progress();
return 0 === iP ? '' : '' + (98 < iP ? 100 : iP) + '%';
}, this);
this.progressStyle = ko.computed(function () {
var iP = this.progress();
return 0 === iP ? '' : 'width:' + (98 < iP ? 100 : iP) + '%';
}, this);
this.title = ko.computed(function () {
var sError = this.error();
return '' !== sError ? sError : this.fileName();
}, this);
this.friendlySize = ko.computed(function () {
var mSize = this.size();
return null === mSize ? '' : Utils.friendlySize(this.size());
}, this);
this.mimeType = ko.computed(function () {
return Utils.mimeContentType(this.fileName());
}, this);
this.fileExt = ko.computed(function () {
return Utils.getFileExtension(this.fileName());
}, this);
this.regDisposables([this.progressText, this.progressStyle, this.title, this.friendlySize, this.mimeType, this.fileExt]);
} }
_.extend(ComposeAttachmentModel.prototype, AbstractModel.prototype); return bResult;
};
ComposeAttachmentModel.prototype.id = ''; /**
ComposeAttachmentModel.prototype.isInline = false; * @returns {string}
ComposeAttachmentModel.prototype.isLinked = false; */
ComposeAttachmentModel.prototype.CID = ''; ComposeAttachmentModel.prototype.iconClass = function()
ComposeAttachmentModel.prototype.contentLocation = ''; {
ComposeAttachmentModel.prototype.fromMessage = false; return AttachmentModel.staticIconClass(
ComposeAttachmentModel.prototype.cancel = Utils.noop; AttachmentModel.staticFileType(this.fileExt(), this.mimeType()))[0];
};
/** /**
* @param {AjaxJsonComposeAttachment} oJsonAttachment * @returns {string}
* @return {boolean} */
*/ ComposeAttachmentModel.prototype.iconText = function()
ComposeAttachmentModel.prototype.initByUploadJson = function (oJsonAttachment) {
{ return AttachmentModel.staticIconClass(
var bResult = false; AttachmentModel.staticFileType(this.fileExt(), this.mimeType()))[1];
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; module.exports = ComposeAttachmentModel;
}
return bResult;
};
/**
* @return {string}
*/
ComposeAttachmentModel.prototype.iconClass = function ()
{
return AttachmentModel.staticIconClass(
AttachmentModel.staticFileType(this.fileExt(), this.mimeType()))[0];
};
/**
* @return {string}
*/
ComposeAttachmentModel.prototype.iconText = function ()
{
return AttachmentModel.staticIconClass(
AttachmentModel.staticFileType(this.fileExt(), this.mimeType()))[1];
};
module.exports = ComposeAttachmentModel;
}());

View file

@ -1,140 +1,132 @@
(function () { var
_ = require('_'),
ko = require('ko'),
'use strict'; Enums = require('Common/Enums'),
Utils = require('Common/Utils'),
Links = require('Common/Links'),
AbstractModel = require('Knoin/AbstractModel');
/**
* @constructor
*/
function ContactModel()
{
AbstractModel.call(this, 'ContactModel');
this.idContact = 0;
this.display = '';
this.properties = [];
this.readOnly = false;
this.focused = ko.observable(false);
this.selected = ko.observable(false);
this.checked = ko.observable(false);
this.deleted = ko.observable(false);
}
_.extend(ContactModel.prototype, AbstractModel.prototype);
/**
* @returns {Array|null}
*/
ContactModel.prototype.getNameAndEmailHelper = function()
{
var var
_ = require('_'), sName = '',
ko = require('ko'), sEmail = '';
Enums = require('Common/Enums'), if (Utils.isNonEmptyArray(this.properties))
Utils = require('Common/Utils'),
Links = require('Common/Links'),
AbstractModel = require('Knoin/AbstractModel')
;
/**
* @constructor
*/
function ContactModel()
{ {
AbstractModel.call(this, 'ContactModel'); _.each(this.properties, function(aProperty) {
if (aProperty)
this.idContact = 0; {
this.display = ''; if (Enums.ContactPropertyType.FirstName === aProperty[0])
this.properties = []; {
this.readOnly = false; sName = Utils.trim(aProperty[1] + ' ' + sName);
}
this.focused = ko.observable(false); else if (Enums.ContactPropertyType.LastName === aProperty[0])
this.selected = ko.observable(false); {
this.checked = ko.observable(false); sName = Utils.trim(sName + ' ' + aProperty[1]);
this.deleted = ko.observable(false); }
else if ('' === sEmail && Enums.ContactPropertyType.Email === aProperty[0])
{
sEmail = aProperty[1];
}
}
}, this);
} }
_.extend(ContactModel.prototype, AbstractModel.prototype); return '' === sEmail ? null : [sEmail, sName];
};
/** ContactModel.prototype.parse = function(oItem)
* @return {Array|null} {
*/ var bResult = false;
ContactModel.prototype.getNameAndEmailHelper = function () if (oItem && 'Object/Contact' === oItem['@Object'])
{ {
var this.idContact = Utils.pInt(oItem.IdContact);
sName = '', this.display = Utils.pString(oItem.Display);
sEmail = '' this.readOnly = !!oItem.ReadOnly;
;
if (Utils.isNonEmptyArray(this.properties)) if (Utils.isNonEmptyArray(oItem.Properties))
{ {
_.each(this.properties, function (aProperty) { _.each(oItem.Properties, function(oProperty) {
if (aProperty) if (oProperty && oProperty.Type && Utils.isNormal(oProperty.Value) && Utils.isNormal(oProperty.TypeStr))
{ {
if (Enums.ContactPropertyType.FirstName === aProperty[0]) this.properties.push([Utils.pInt(oProperty.Type), Utils.pString(oProperty.Value), Utils.pString(oProperty.TypeStr)]);
{
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); }, this);
} }
return '' === sEmail ? null : [sEmail, sName]; bResult = true;
}; }
ContactModel.prototype.parse = function (oItem) return bResult;
};
/**
* @returns {string}
*/
ContactModel.prototype.srcAttr = function()
{
return Links.emptyContactPic();
};
/**
* @returns {string}
*/
ContactModel.prototype.generateUid = function()
{
return '' + this.idContact;
};
/**
* @return string
*/
ContactModel.prototype.lineAsCss = function()
{
var aResult = [];
if (this.deleted())
{ {
var bResult = false; aResult.push('deleted');
if (oItem && 'Object/Contact' === oItem['@Object']) }
{ if (this.selected())
this.idContact = Utils.pInt(oItem.IdContact);
this.display = Utils.pString(oItem.Display);
this.readOnly = !!oItem.ReadOnly;
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);
}
bResult = true;
}
return bResult;
};
/**
* @return {string}
*/
ContactModel.prototype.srcAttr = function ()
{ {
return Links.emptyContactPic(); aResult.push('selected');
}; }
if (this.checked())
/**
* @return {string}
*/
ContactModel.prototype.generateUid = function ()
{ {
return '' + this.idContact; aResult.push('checked');
}; }
if (this.focused())
/**
* @return string
*/
ContactModel.prototype.lineAsCss = function ()
{ {
var aResult = []; aResult.push('focused');
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(' '); return aResult.join(' ');
}; };
module.exports = ContactModel; module.exports = ContactModel;
}());

View file

@ -1,52 +1,45 @@
(function () { var
_ = require('_'),
ko = require('ko'),
'use strict'; Enums = require('Common/Enums'),
Utils = require('Common/Utils'),
Translator = require('Common/Translator'),
var AbstractModel = require('Knoin/AbstractModel');
_ = require('_'),
ko = require('ko'),
Enums = require('Common/Enums'), /**
Utils = require('Common/Utils'), * @constructor
Translator = require('Common/Translator'), * @param {number=} iType = Enums.ContactPropertyType.Unknown
* @param {string=} sTypeStr = ''
* @param {string=} sValue = ''
* @param {boolean=} bFocused = false
* @param {string=} sPlaceholder = ''
*/
function ContactPropertyModel(iType, sTypeStr, sValue, bFocused, sPlaceholder)
{
AbstractModel.call(this, 'ContactPropertyModel');
AbstractModel = require('Knoin/AbstractModel') 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 || '');
* @constructor
* @param {number=} iType = Enums.ContactPropertyType.Unknown
* @param {string=} sTypeStr = ''
* @param {string=} sValue = ''
* @param {boolean=} bFocused = false
* @param {string=} sPlaceholder = ''
*/
function ContactPropertyModel(iType, sTypeStr, sValue, bFocused, sPlaceholder)
{
AbstractModel.call(this, 'ContactPropertyModel');
this.type = ko.observable(Utils.isUnd(iType) ? Enums.ContactPropertyType.Unknown : iType); this.placeholderValue = ko.computed(function() {
this.typeStr = ko.observable(Utils.isUnd(sTypeStr) ? '' : sTypeStr); var value = this.placeholder();
this.focused = ko.observable(Utils.isUnd(bFocused) ? false : !!bFocused); return value ? Translator.i18n(value) : '';
this.value = ko.observable(Utils.pString(sValue)); }, this);
this.placeholder = ko.observable(sPlaceholder || ''); this.largeValue = ko.computed(function() {
return Enums.ContactPropertyType.Note === this.type();
}, this);
this.placeholderValue = ko.computed(function () { this.regDisposables([this.placeholderValue, this.largeValue]);
var value = this.placeholder(); }
return value ? Translator.i18n(value) : '';
}, this);
this.largeValue = ko.computed(function () { _.extend(ContactPropertyModel.prototype, AbstractModel.prototype);
return Enums.ContactPropertyType.Note === this.type();
}, this);
this.regDisposables([this.placeholderValue, this.largeValue]); module.exports = ContactPropertyModel;
}
_.extend(ContactPropertyModel.prototype, AbstractModel.prototype);
module.exports = ContactPropertyModel;
}());

View file

@ -1,406 +1,396 @@
(function () { var Utils = require('Common/Utils');
'use strict'; /**
* @constructor
* @param {string=} sEmail
* @param {string=} sName
* @param {string=} sDkimStatus
* @param {string=} sDkimValue
*/
function EmailModel(sEmail, sName, sDkimStatus, sDkimValue)
{
this.email = sEmail || '';
this.name = sName || '';
this.dkimStatus = sDkimStatus || 'none';
this.dkimValue = sDkimValue || '';
this.clearDuplicateName();
}
/**
* @static
* @param {AjaxJsonEmail} oJsonEmail
* @returns {?EmailModel}
*/
EmailModel.newInstanceFromJson = function(oJsonEmail)
{
var oEmailModel = new EmailModel();
return oEmailModel.initByJson(oJsonEmail) ? oEmailModel : null;
};
/**
* @static
* @param {string} sLine
* @param {string=} sDelimiter = ';'
* @returns {Array}
*/
EmailModel.splitHelper = function(sLine, sDelimiter)
{
sDelimiter = sDelimiter || ';';
sLine = sLine.replace(/[\r\n]+/g, '; ').replace(/[\s]+/g, ' ');
var var
Utils = require('Common/Utils') iIndex = 0,
; iLen = sLine.length,
bAt = false,
sChar = '',
sResult = '';
/** for (; iIndex < iLen; iIndex++)
* @param {string=} sEmail
* @param {string=} sName
* @param {string=} sDkimStatus
* @param {string=} sDkimValue
*
* @constructor
*/
function EmailModel(sEmail, sName, sDkimStatus, sDkimValue)
{ {
this.email = sEmail || ''; sChar = sLine.charAt(iIndex);
this.name = sName || ''; switch (sChar)
this.dkimStatus = sDkimStatus || 'none'; {
this.dkimValue = sDkimValue || ''; case '@':
bAt = true;
break;
case ' ':
if (bAt)
{
bAt = false;
sResult += sDelimiter;
}
break;
// no default
}
sResult += sChar;
}
return sResult.split(sDelimiter);
};
/**
* @type {string}
*/
EmailModel.prototype.name = '';
/**
* @type {string}
*/
EmailModel.prototype.email = '';
/**
* @type {string}
*/
EmailModel.prototype.dkimStatus = 'none';
/**
* @type {string}
*/
EmailModel.prototype.dkimValue = '';
EmailModel.prototype.clear = function()
{
this.email = '';
this.name = '';
this.dkimStatus = 'none';
this.dkimValue = '';
};
/**
* @returns {boolean}
*/
EmailModel.prototype.validate = function()
{
return '' !== this.name || '' !== this.email;
};
/**
* @param {boolean} bWithoutName = false
* @returns {string}
*/
EmailModel.prototype.hash = function(bWithoutName)
{
return '#' + (bWithoutName ? '' : this.name) + '#' + this.email + '#';
};
EmailModel.prototype.clearDuplicateName = function()
{
if (this.name === this.email)
{
this.name = '';
}
};
/**
* @param {string} sQuery
* @returns {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(); this.clearDuplicateName();
} }
else if ((/^[^@]+@[^@]+$/).test(sString))
/**
* @static
* @param {AjaxJsonEmail} oJsonEmail
* @return {?EmailModel}
*/
EmailModel.newInstanceFromJson = function (oJsonEmail)
{ {
var oEmailModel = new EmailModel();
return oEmailModel.initByJson(oJsonEmail) ? oEmailModel : null;
};
/**
* @static
* @param {string} sLine
* @param {string=} sDelimiter = ';'
* @return {Array}
*/
EmailModel.splitHelper = function (sLine, sDelimiter)
{
sDelimiter = sDelimiter || ';';
sLine = sLine.replace(/[\r\n]+/g, '; ').replace(/[\s]+/g, ' ');
var
iIndex = 0,
iLen = sLine.length,
bAt = false,
sChar = '',
sResult = ''
;
for (; iIndex < iLen; iIndex++)
{
sChar = sLine.charAt(iIndex);
switch (sChar)
{
case '@':
bAt = true;
break;
case ' ':
if (bAt)
{
bAt = false;
sResult += sDelimiter;
}
break;
}
sResult += sChar;
}
return sResult.split(sDelimiter);
};
/**
* @type {string}
*/
EmailModel.prototype.name = '';
/**
* @type {string}
*/
EmailModel.prototype.email = '';
/**
* @type {string}
*/
EmailModel.prototype.dkimStatus = 'none';
/**
* @type {string}
*/
EmailModel.prototype.dkimValue = '';
EmailModel.prototype.clear = function ()
{
this.email = '';
this.name = ''; this.name = '';
this.email = sString;
}
};
this.dkimStatus = 'none'; /**
this.dkimValue = ''; * @param {AjaxJsonEmail} oJsonEmail
}; * @returns {boolean}
*/
/** EmailModel.prototype.initByJson = function(oJsonEmail)
* @return {boolean} {
*/ var bResult = false;
EmailModel.prototype.validate = function () if (oJsonEmail && 'Object/Email' === oJsonEmail['@Object'])
{ {
return '' !== this.name || '' !== this.email; this.name = Utils.trim(oJsonEmail.Name);
}; this.email = Utils.trim(oJsonEmail.Email);
this.dkimStatus = Utils.trim(oJsonEmail.DkimStatus || '');
/** this.dkimValue = Utils.trim(oJsonEmail.DkimValue || '');
* @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 = '';
}
};
/**
* @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);
this.dkimStatus = Utils.trim(oJsonEmail.DkimStatus || '');
this.dkimValue = Utils.trim(oJsonEmail.DkimValue || '');
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 ? '<a href="mailto:' + Utils.encodeHtml('"' + this.name + '" <' + this.email + '>') +
'" target="_blank" tabindex="-1">' + Utils.encodeHtml(this.name) + '</a>' :
(bEncodeHtml ? Utils.encodeHtml(this.name) : this.name);
}
else
{
sResult = this.email;
if ('' !== this.name)
{
if (bWrapWithLink)
{
sResult = Utils.encodeHtml('"' + this.name + '" <') + '<a href="mailto:' +
Utils.encodeHtml('"' + this.name + '" <' + this.email + '>') +
'" target="_blank" tabindex="-1">' +
Utils.encodeHtml(sResult) +
'</a>' +
Utils.encodeHtml('>');
}
else
{
sResult = '"' + this.name + '" <' + sResult + '>';
if (bEncodeHtml)
{
sResult = Utils.encodeHtml(sResult);
}
}
}
else if (bWrapWithLink)
{
sResult = '<a href="mailto:' + Utils.encodeHtml(this.email) + '" target="_blank" tabindex="-1">' + Utils.encodeHtml(this.email) + '</a>';
}
}
}
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 += str.length;
}
length = typeof 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(/\\\\(.)/g, '$1');
$sComment = $sComment.replace(/\\\\(.)/g, '$1');
this.name = $sName;
this.email = $sEmail;
bResult = '' !== this.email;
this.clearDuplicateName(); this.clearDuplicateName();
return true; }
};
module.exports = EmailModel; return bResult;
};
}()); /**
* @param {boolean} bFriendlyView
* @param {boolean=} bWrapWithLink = false
* @param {boolean=} bEncodeHtml = false
* @returns {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 ? '<a href="mailto:' + Utils.encodeHtml('"' + this.name + '" <' + this.email + '>') +
'" target="_blank" tabindex="-1">' + Utils.encodeHtml(this.name) + '</a>' :
(bEncodeHtml ? Utils.encodeHtml(this.name) : this.name);
}
else
{
sResult = this.email;
if ('' !== this.name)
{
if (bWrapWithLink)
{
sResult = Utils.encodeHtml('"' + this.name + '" <') + '<a href="mailto:' +
Utils.encodeHtml('"' + this.name + '" <' + this.email + '>') +
'" target="_blank" tabindex="-1">' +
Utils.encodeHtml(sResult) +
'</a>' +
Utils.encodeHtml('>');
}
else
{
sResult = '"' + this.name + '" <' + sResult + '>';
if (bEncodeHtml)
{
sResult = Utils.encodeHtml(sResult);
}
}
}
else if (bWrapWithLink)
{
sResult = '<a href="mailto:' + Utils.encodeHtml(this.email) + '" target="_blank" tabindex="-1">' + Utils.encodeHtml(this.email) + '</a>';
}
}
}
return sResult;
};
/**
* @param {string} $sEmailAddress
* @returns {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 (0 > start) {
start += end;
}
end = 'undefined' === typeof len ? end : (0 > len ? len + end : len + start);
return start >= str.length || 0 > start || start > end ? false : str.slice(start, end);
},
substrReplace = function(str, replace, start, length) {
if (0 > start) {
start += str.length;
}
length = 'undefined' === typeof length ? length : str.length;
if (0 > length) {
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 = substrReplace($sEmailAddress, '', $iStartIndex, $iEndIndex - $iStartIndex + 1);
$iEndIndex = 0;
$iCurrentIndex = 0;
$iStartIndex = 0;
$bInName = false;
}
break;
case '<':
if ((!$bInName) && (!$bInAddress) && (!$bInComment))
{
if (0 < $iCurrentIndex && 0 === $sName.length)
{
$sName = substr($sEmailAddress, 0, $iCurrentIndex);
}
$bInAddress = true;
$iStartIndex = $iCurrentIndex;
}
break;
case '>':
if ($bInAddress)
{
$iEndIndex = $iCurrentIndex;
$sEmail = substr($sEmailAddress, $iStartIndex + 1, $iEndIndex - $iStartIndex - 1);
$sEmailAddress = substrReplace($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 = substrReplace($sEmailAddress, '', $iStartIndex, $iEndIndex - $iStartIndex + 1);
$iEndIndex = 0;
$iCurrentIndex = 0;
$iStartIndex = 0;
$bInComment = false;
}
break;
case '\\':
$iCurrentIndex += 1;
break;
// no default
}
$iCurrentIndex += 1;
}
if (0 === $sEmail.length)
{
$aRegs = $sEmailAddress.match(/[^@\s]+@\S+/i);
if ($aRegs && $aRegs[0])
{
$sEmail = $aRegs[0];
}
else
{
$sName = $sEmailAddress;
}
}
if (0 < $sEmail.length && 0 === $sName.length && 0 === $sComment.length)
{
$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(/\\\\(.)/g, '$1');
$sComment = $sComment.replace(/\\\\(.)/g, '$1');
this.name = $sName;
this.email = $sEmail;
this.clearDuplicateName();
return true;
};
module.exports = EmailModel;

View file

@ -1,325 +1,318 @@
(function () { var
_ = require('_'),
ko = require('ko'),
'use strict'; Enums = require('Common/Enums'),
Utils = require('Common/Utils'),
Translator = require('Common/Translator'),
var Cache = require('Common/Cache'),
_ = require('_'),
ko = require('ko'),
Enums = require('Common/Enums'), FilterConditionModel = require('Model/FilterCondition'),
Utils = require('Common/Utils'),
Translator = require('Common/Translator'),
Cache = require('Common/Cache'), AbstractModel = require('Knoin/AbstractModel');
FilterConditionModel = require('Model/FilterCondition'), /**
* @constructor
*/
function FilterModel()
{
AbstractModel.call(this, 'FilterModel');
AbstractModel = require('Knoin/AbstractModel') this.enabled = ko.observable(true);
;
/** this.id = '';
* @constructor
*/
function FilterModel()
{
AbstractModel.call(this, 'FilterModel');
this.enabled = ko.observable(true); this.name = ko.observable('');
this.name.error = ko.observable(false);
this.name.focused = ko.observable(false);
this.id = ''; this.conditions = ko.observableArray([]);
this.conditionsType = ko.observable(Enums.FilterRulesType.Any);
this.name = ko.observable(''); // Actions
this.name.error = ko.observable(false); this.actionValue = ko.observable('');
this.name.focused = ko.observable(false); this.actionValue.error = ko.observable(false);
this.conditions = ko.observableArray([]); this.actionValueSecond = ko.observable('');
this.conditionsType = ko.observable(Enums.FilterRulesType.Any); this.actionValueThird = ko.observable('');
// Actions this.actionValueFourth = ko.observable('');
this.actionValue = ko.observable(''); this.actionValueFourth.error = ko.observable(false);
this.actionValue.error = ko.observable(false);
this.actionValueSecond = ko.observable(''); this.actionMarkAsRead = ko.observable(false);
this.actionValueThird = ko.observable('');
this.actionValueFourth = ko.observable(''); this.actionKeep = ko.observable(true);
this.actionValueFourth.error = ko.observable(false); this.actionNoStop = ko.observable(false);
this.actionMarkAsRead = ko.observable(false); this.actionType = ko.observable(Enums.FiltersAction.MoveTo);
this.actionKeep = ko.observable(true); this.actionType.subscribe(function() {
this.actionNoStop = ko.observable(false); this.actionValue('');
this.actionValue.error(false);
this.actionValueSecond('');
this.actionValueThird('');
this.actionValueFourth('');
this.actionValueFourth.error(false);
}, this);
this.actionType = ko.observable(Enums.FiltersAction.MoveTo); var fGetRealFolderName = function(sFolderFullNameRaw) {
var oFolder = Cache.getFolderFromCacheList(sFolderFullNameRaw);
this.actionType.subscribe(function () { return oFolder ? oFolder.fullName.replace(
this.actionValue(''); '.' === oFolder.delimiter ? /\./ : /[\\\/]+/, ' / ') : sFolderFullNameRaw;
this.actionValue.error(false);
this.actionValueSecond('');
this.actionValueThird('');
this.actionValueFourth('');
this.actionValueFourth.error(false);
}, this);
var fGetRealFolderName = function (sFolderFullNameRaw) {
var oFolder = Cache.getFolderFromCacheList(sFolderFullNameRaw);
return oFolder ? oFolder.fullName.replace(
'.' === oFolder.delimiter ? /\./ : /[\\\/]+/, ' / ') : sFolderFullNameRaw;
};
this.nameSub = ko.computed(function () {
var
sResult = '',
sActionValue = this.actionValue()
;
switch (this.actionType())
{
case Enums.FiltersAction.MoveTo:
sResult = Translator.i18n('SETTINGS_FILTERS/SUBNAME_MOVE_TO', {
FOLDER: fGetRealFolderName(sActionValue)
});
break;
case Enums.FiltersAction.Forward:
sResult = Translator.i18n('SETTINGS_FILTERS/SUBNAME_FORWARD_TO', {
EMAIL: sActionValue
});
break;
case Enums.FiltersAction.Vacation:
sResult = Translator.i18n('SETTINGS_FILTERS/SUBNAME_VACATION_MESSAGE');
break;
case Enums.FiltersAction.Reject:
sResult = Translator.i18n('SETTINGS_FILTERS/SUBNAME_REJECT');
break;
case Enums.FiltersAction.Discard:
sResult = Translator.i18n('SETTINGS_FILTERS/SUBNAME_DISCARD');
break;
}
return sResult ? '(' + sResult + ')' : '';
}, this);
this.actionTemplate = ko.computed(function () {
var sTemplate = '';
switch (this.actionType())
{
default:
case Enums.FiltersAction.MoveTo:
sTemplate = 'SettingsFiltersActionMoveToFolder';
break;
case Enums.FiltersAction.Forward:
sTemplate = 'SettingsFiltersActionForward';
break;
case Enums.FiltersAction.Vacation:
sTemplate = 'SettingsFiltersActionVacation';
break;
case Enums.FiltersAction.Reject:
sTemplate = 'SettingsFiltersActionReject';
break;
case Enums.FiltersAction.None:
sTemplate = 'SettingsFiltersActionNone';
break;
case Enums.FiltersAction.Discard:
sTemplate = 'SettingsFiltersActionDiscard';
break;
}
return sTemplate;
}, this);
this.regDisposables(this.conditions.subscribe(Utils.windowResizeCallback));
this.regDisposables(this.name.subscribe(function (sValue) {
this.name.error('' === sValue);
}, this));
this.regDisposables(this.actionValue.subscribe(function (sValue) {
this.actionValue.error('' === sValue);
}, this));
this.regDisposables([this.actionNoStop, this.actionTemplate]);
this.deleteAccess = ko.observable(false);
this.canBeDeleted = ko.observable(true);
}
_.extend(FilterModel.prototype, AbstractModel.prototype);
FilterModel.prototype.generateID = function ()
{
this.id = Utils.fakeMd5();
}; };
FilterModel.prototype.verify = function () this.nameSub = ko.computed(function() {
{
if ('' === this.name()) var
sResult = '',
sActionValue = this.actionValue();
switch (this.actionType())
{
case Enums.FiltersAction.MoveTo:
sResult = Translator.i18n('SETTINGS_FILTERS/SUBNAME_MOVE_TO', {
FOLDER: fGetRealFolderName(sActionValue)
});
break;
case Enums.FiltersAction.Forward:
sResult = Translator.i18n('SETTINGS_FILTERS/SUBNAME_FORWARD_TO', {
EMAIL: sActionValue
});
break;
case Enums.FiltersAction.Vacation:
sResult = Translator.i18n('SETTINGS_FILTERS/SUBNAME_VACATION_MESSAGE');
break;
case Enums.FiltersAction.Reject:
sResult = Translator.i18n('SETTINGS_FILTERS/SUBNAME_REJECT');
break;
case Enums.FiltersAction.Discard:
sResult = Translator.i18n('SETTINGS_FILTERS/SUBNAME_DISCARD');
break;
// no default
}
return sResult ? '(' + sResult + ')' : '';
}, this);
this.actionTemplate = ko.computed(function() {
var sTemplate = '';
switch (this.actionType())
{
case Enums.FiltersAction.Forward:
sTemplate = 'SettingsFiltersActionForward';
break;
case Enums.FiltersAction.Vacation:
sTemplate = 'SettingsFiltersActionVacation';
break;
case Enums.FiltersAction.Reject:
sTemplate = 'SettingsFiltersActionReject';
break;
case Enums.FiltersAction.None:
sTemplate = 'SettingsFiltersActionNone';
break;
case Enums.FiltersAction.Discard:
sTemplate = 'SettingsFiltersActionDiscard';
break;
case Enums.FiltersAction.MoveTo:
default:
sTemplate = 'SettingsFiltersActionMoveToFolder';
break;
}
return sTemplate;
}, this);
this.regDisposables(this.conditions.subscribe(Utils.windowResizeCallback));
this.regDisposables(this.name.subscribe(function(sValue) {
this.name.error('' === sValue);
}, this));
this.regDisposables(this.actionValue.subscribe(function(sValue) {
this.actionValue.error('' === sValue);
}, this));
this.regDisposables([this.actionNoStop, this.actionTemplate]);
this.deleteAccess = ko.observable(false);
this.canBeDeleted = ko.observable(true);
}
_.extend(FilterModel.prototype, AbstractModel.prototype);
FilterModel.prototype.generateID = function()
{
this.id = Utils.fakeMd5();
};
FilterModel.prototype.verify = function()
{
if ('' === this.name())
{
this.name.error(true);
return false;
}
if (0 < this.conditions().length)
{
if (_.find(this.conditions(), function(oCond) {
return oCond && !oCond.verify();
}))
{ {
this.name.error(true);
return false; return false;
} }
}
if (0 < this.conditions().length) if ('' === this.actionValue())
{ {
if (_.find(this.conditions(), function (oCond) { if (-1 < Utils.inArray(this.actionType(), [
return oCond && !oCond.verify(); Enums.FiltersAction.MoveTo,
})) Enums.FiltersAction.Forward,
{ Enums.FiltersAction.Reject,
return false; Enums.FiltersAction.Vacation
} ]))
}
if ('' === this.actionValue())
{
if (-1 < Utils.inArray(this.actionType(), [
Enums.FiltersAction.MoveTo,
Enums.FiltersAction.Forward,
Enums.FiltersAction.Reject,
Enums.FiltersAction.Vacation
]))
{
this.actionValue.error(true);
return false;
}
}
if (Enums.FiltersAction.Forward === this.actionType() &&
-1 === this.actionValue().indexOf('@'))
{ {
this.actionValue.error(true); this.actionValue.error(true);
return false; return false;
} }
}
if (Enums.FiltersAction.Vacation === this.actionType() && if (Enums.FiltersAction.Forward === this.actionType() &&
'' !== this.actionValueFourth() && -1 === this.actionValueFourth().indexOf('@') -1 === this.actionValue().indexOf('@'))
) {
this.actionValue.error(true);
return false;
}
if (Enums.FiltersAction.Vacation === this.actionType() &&
'' !== this.actionValueFourth() && -1 === this.actionValueFourth().indexOf('@')
)
{
this.actionValueFourth.error(true);
return false;
}
this.name.error(false);
this.actionValue.error(false);
return true;
};
FilterModel.prototype.toJson = function()
{
return {
ID: this.id,
Enabled: this.enabled() ? '1' : '0',
Name: this.name(),
ConditionsType: this.conditionsType(),
Conditions: _.map(this.conditions(), function(oItem) {
return oItem.toJson();
}),
ActionValue: this.actionValue(),
ActionValueSecond: this.actionValueSecond(),
ActionValueThird: this.actionValueThird(),
ActionValueFourth: this.actionValueFourth(),
ActionType: this.actionType(),
Stop: this.actionNoStop() ? '0' : '1',
Keep: this.actionKeep() ? '1' : '0',
MarkAsRead: this.actionMarkAsRead() ? '1' : '0'
};
};
FilterModel.prototype.addCondition = function()
{
this.conditions.push(new FilterConditionModel());
};
FilterModel.prototype.removeCondition = function(oConditionToDelete)
{
this.conditions.remove(oConditionToDelete);
Utils.delegateRunOnDestroy(oConditionToDelete);
};
FilterModel.prototype.setRecipients = function()
{
this.actionValueFourth(require('Stores/User/Account').accountsEmails().join(', '));
};
FilterModel.prototype.parse = function(oItem)
{
var bResult = false;
if (oItem && 'Object/Filter' === oItem['@Object'])
{
this.id = Utils.pString(oItem.ID);
this.name(Utils.pString(oItem.Name));
this.enabled(!!oItem.Enabled);
this.conditionsType(Utils.pString(oItem.ConditionsType));
this.conditions([]);
if (Utils.isNonEmptyArray(oItem.Conditions))
{ {
this.actionValueFourth.error(true); this.conditions(_.compact(_.map(oItem.Conditions, function(aData) {
return false; var oFilterCondition = new FilterConditionModel();
return oFilterCondition && oFilterCondition.parse(aData) ?
oFilterCondition : null;
})));
} }
this.name.error(false); this.actionType(Utils.pString(oItem.ActionType));
this.actionValue.error(false);
return true; this.actionValue(Utils.pString(oItem.ActionValue));
}; this.actionValueSecond(Utils.pString(oItem.ActionValueSecond));
this.actionValueThird(Utils.pString(oItem.ActionValueThird));
this.actionValueFourth(Utils.pString(oItem.ActionValueFourth));
FilterModel.prototype.toJson = function () this.actionNoStop(!oItem.Stop);
{ this.actionKeep(!!oItem.Keep);
return { this.actionMarkAsRead(!!oItem.MarkAsRead);
ID: this.id,
Enabled: this.enabled() ? '1' : '0',
Name: this.name(),
ConditionsType: this.conditionsType(),
Conditions: _.map(this.conditions(), function (oItem) {
return oItem.toJson();
}),
ActionValue: this.actionValue(), bResult = true;
ActionValueSecond: this.actionValueSecond(), }
ActionValueThird: this.actionValueThird(),
ActionValueFourth: this.actionValueFourth(),
ActionType: this.actionType(),
Stop: this.actionNoStop() ? '0' : '1', return bResult;
Keep: this.actionKeep() ? '1' : '0', };
MarkAsRead: this.actionMarkAsRead() ? '1' : '0'
};
};
FilterModel.prototype.addCondition = function () FilterModel.prototype.cloneSelf = function()
{ {
this.conditions.push(new FilterConditionModel()); var oClone = new FilterModel();
};
FilterModel.prototype.removeCondition = function (oConditionToDelete) oClone.id = this.id;
{
this.conditions.remove(oConditionToDelete);
Utils.delegateRunOnDestroy(oConditionToDelete);
};
FilterModel.prototype.setRecipients = function () oClone.enabled(this.enabled());
{
this.actionValueFourth(require('Stores/User/Account').accountsEmails().join(', '));
};
FilterModel.prototype.parse = function (oItem) oClone.name(this.name());
{ oClone.name.error(this.name.error());
var bResult = false;
if (oItem && 'Object/Filter' === oItem['@Object'])
{
this.id = Utils.pString(oItem.ID);
this.name(Utils.pString(oItem.Name));
this.enabled(!!oItem.Enabled);
this.conditionsType(Utils.pString(oItem.ConditionsType)); oClone.conditionsType(this.conditionsType());
this.conditions([]); oClone.actionMarkAsRead(this.actionMarkAsRead());
if (Utils.isNonEmptyArray(oItem.Conditions)) oClone.actionType(this.actionType());
{
this.conditions(_.compact(_.map(oItem.Conditions, function (aData) {
var oFilterCondition = new FilterConditionModel();
return oFilterCondition && oFilterCondition.parse(aData) ?
oFilterCondition : null;
})));
}
this.actionType(Utils.pString(oItem.ActionType)); oClone.actionValue(this.actionValue());
oClone.actionValue.error(this.actionValue.error());
this.actionValue(Utils.pString(oItem.ActionValue)); oClone.actionValueSecond(this.actionValueSecond());
this.actionValueSecond(Utils.pString(oItem.ActionValueSecond)); oClone.actionValueThird(this.actionValueThird());
this.actionValueThird(Utils.pString(oItem.ActionValueThird)); oClone.actionValueFourth(this.actionValueFourth());
this.actionValueFourth(Utils.pString(oItem.ActionValueFourth));
this.actionNoStop(!oItem.Stop); oClone.actionKeep(this.actionKeep());
this.actionKeep(!!oItem.Keep); oClone.actionNoStop(this.actionNoStop());
this.actionMarkAsRead(!!oItem.MarkAsRead);
bResult = true; oClone.conditions(_.map(this.conditions(), function(oCondition) {
} return oCondition.cloneSelf();
}));
return bResult; return oClone;
}; };
FilterModel.prototype.cloneSelf = function () module.exports = FilterModel;
{
var oClone = new FilterModel();
oClone.id = this.id;
oClone.enabled(this.enabled());
oClone.name(this.name());
oClone.name.error(this.name.error());
oClone.conditionsType(this.conditionsType());
oClone.actionMarkAsRead(this.actionMarkAsRead());
oClone.actionType(this.actionType());
oClone.actionValue(this.actionValue());
oClone.actionValue.error(this.actionValue.error());
oClone.actionValueSecond(this.actionValueSecond());
oClone.actionValueThird(this.actionValueThird());
oClone.actionValueFourth(this.actionValueFourth());
oClone.actionKeep(this.actionKeep());
oClone.actionNoStop(this.actionNoStop());
oClone.conditions(_.map(this.conditions(), function (oCondition) {
return oCondition.cloneSelf();
}));
return oClone;
};
module.exports = FilterModel;
}());

View file

@ -1,117 +1,110 @@
(function () { var
_ = require('_'),
ko = require('ko'),
'use strict'; Enums = require('Common/Enums'),
Utils = require('Common/Utils'),
var AbstractModel = require('Knoin/AbstractModel');
_ = require('_'),
ko = require('ko'),
Enums = require('Common/Enums'), /**
Utils = require('Common/Utils'), * @constructor
*/
function FilterConditionModel()
{
AbstractModel.call(this, 'FilterConditionModel');
AbstractModel = require('Knoin/AbstractModel') this.field = ko.observable(Enums.FilterConditionField.From);
; this.type = ko.observable(Enums.FilterConditionType.Contains);
this.value = ko.observable('');
this.value.error = ko.observable(false);
/** this.valueSecond = ko.observable('');
* @constructor this.valueSecond.error = ko.observable(false);
*/
function FilterConditionModel() this.template = ko.computed(function() {
var sTemplate = '';
switch (this.field())
{
case Enums.FilterConditionField.Size:
sTemplate = 'SettingsFiltersConditionSize';
break;
case Enums.FilterConditionField.Header:
sTemplate = 'SettingsFiltersConditionMore';
break;
default:
sTemplate = 'SettingsFiltersConditionDefault';
break;
}
return sTemplate;
}, this);
this.field.subscribe(function() {
this.value('');
this.valueSecond('');
}, this);
this.regDisposables([this.template]);
}
_.extend(FilterConditionModel.prototype, AbstractModel.prototype);
FilterConditionModel.prototype.verify = function()
{
if ('' === this.value())
{ {
AbstractModel.call(this, 'FilterConditionModel'); this.value.error(true);
return false;
this.field = ko.observable(Enums.FilterConditionField.From);
this.type = ko.observable(Enums.FilterConditionType.Contains);
this.value = ko.observable('');
this.value.error = ko.observable(false);
this.valueSecond = ko.observable('');
this.valueSecond.error = ko.observable(false);
this.template = ko.computed(function () {
var sTemplate = '';
switch (this.field())
{
case Enums.FilterConditionField.Size:
sTemplate = 'SettingsFiltersConditionSize';
break;
case Enums.FilterConditionField.Header:
sTemplate = 'SettingsFiltersConditionMore';
break;
default:
sTemplate = 'SettingsFiltersConditionDefault';
break;
}
return sTemplate;
}, this);
this.field.subscribe(function () {
this.value('');
this.valueSecond('');
}, this);
this.regDisposables([this.template]);
} }
_.extend(FilterConditionModel.prototype, AbstractModel.prototype); if (Enums.FilterConditionField.Header === this.field() && '' === this.valueSecond())
FilterConditionModel.prototype.verify = function ()
{ {
if ('' === this.value()) this.valueSecond.error(true);
{ return false;
this.value.error(true); }
return false;
}
if (Enums.FilterConditionField.Header === this.field() && '' === this.valueSecond()) return true;
{ };
this.valueSecond.error(true);
return false; FilterConditionModel.prototype.parse = function(oItem)
} {
if (oItem && oItem.Field && oItem.Type)
{
this.field(Utils.pString(oItem.Field));
this.type(Utils.pString(oItem.Type));
this.value(Utils.pString(oItem.Value));
this.valueSecond(Utils.pString(oItem.ValueSecond));
return true; return true;
}
return false;
};
FilterConditionModel.prototype.toJson = function()
{
return {
Field: this.field(),
Type: this.type(),
Value: this.value(),
ValueSecond: this.valueSecond()
}; };
};
FilterConditionModel.prototype.parse = function (oItem) FilterConditionModel.prototype.cloneSelf = function()
{ {
if (oItem && oItem.Field && oItem.Type) var oClone = new FilterConditionModel();
{
this.field(Utils.pString(oItem.Field));
this.type(Utils.pString(oItem.Type));
this.value(Utils.pString(oItem.Value));
this.valueSecond(Utils.pString(oItem.ValueSecond));
return true; oClone.field(this.field());
} oClone.type(this.type());
oClone.value(this.value());
oClone.valueSecond(this.valueSecond());
return false; return oClone;
}; };
FilterConditionModel.prototype.toJson = function () module.exports = FilterConditionModel;
{
return {
Field: this.field(),
Type: this.type(),
Value: this.value(),
ValueSecond: this.valueSecond()
};
};
FilterConditionModel.prototype.cloneSelf = function ()
{
var oClone = new FilterConditionModel();
oClone.field(this.field());
oClone.type(this.type());
oClone.value(this.value());
oClone.valueSecond(this.valueSecond());
return oClone;
};
module.exports = FilterConditionModel;
}());

View file

@ -1,379 +1,367 @@
(function () { var
_ = require('_'),
ko = require('ko'),
'use strict'; Enums = require('Common/Enums'),
Utils = require('Common/Utils'),
Events = require('Common/Events'),
Translator = require('Common/Translator'),
var Cache = require('Common/Cache'),
_ = require('_'),
ko = require('ko'),
Enums = require('Common/Enums'), AbstractModel = require('Knoin/AbstractModel');
Utils = require('Common/Utils'),
Events = require('Common/Events'),
Translator = require('Common/Translator'),
Cache = require('Common/Cache'), /**
* @constructor
*/
function FolderModel()
{
AbstractModel.call(this, 'FolderModel');
AbstractModel = require('Knoin/AbstractModel') this.name = ko.observable('');
; this.fullName = '';
this.fullNameRaw = '';
this.fullNameHash = '';
this.delimiter = '';
this.namespace = '';
this.deep = 0;
this.interval = 0;
/** this.selectable = false;
* @constructor this.existen = true;
*/
function FolderModel()
{
AbstractModel.call(this, 'FolderModel');
this.name = ko.observable(''); this.type = ko.observable(Enums.FolderType.User);
this.fullName = '';
this.fullNameRaw = '';
this.fullNameHash = '';
this.delimiter = '';
this.namespace = '';
this.deep = 0;
this.interval = 0;
this.selectable = false; this.focused = ko.observable(false);
this.existen = true; this.selected = ko.observable(false);
this.edited = ko.observable(false);
this.collapsed = ko.observable(true);
this.subScribed = ko.observable(true);
this.checkable = ko.observable(false);
this.subFolders = ko.observableArray([]);
this.deleteAccess = ko.observable(false);
this.actionBlink = ko.observable(false).extend({'falseTimeout': 1000});
this.type = ko.observable(Enums.FolderType.User); this.nameForEdit = ko.observable('');
this.focused = ko.observable(false); this.privateMessageCountAll = ko.observable(0);
this.selected = ko.observable(false); this.privateMessageCountUnread = ko.observable(0);
this.edited = ko.observable(false);
this.collapsed = ko.observable(true);
this.subScribed = ko.observable(true);
this.checkable = ko.observable(false);
this.subFolders = ko.observableArray([]);
this.deleteAccess = ko.observable(false);
this.actionBlink = ko.observable(false).extend({'falseTimeout': 1000});
this.nameForEdit = ko.observable(''); this.collapsedPrivate = ko.observable(true);
}
this.privateMessageCountAll = ko.observable(0); _.extend(FolderModel.prototype, AbstractModel.prototype);
this.privateMessageCountUnread = ko.observable(0);
this.collapsedPrivate = ko.observable(true); /**
} * @static
* @param {AjaxJsonFolder} oJsonFolder
* @returns {?FolderModel}
*/
FolderModel.newInstanceFromJson = function(oJsonFolder)
{
var oFolderModel = new FolderModel();
return oFolderModel.initByJson(oJsonFolder) ? oFolderModel.initComputed() : null;
};
_.extend(FolderModel.prototype, AbstractModel.prototype); /**
* @returns {FolderModel}
*/
FolderModel.prototype.initComputed = function()
{
var sInboxFolderName = Cache.getFolderInboxName();
/** this.isInbox = ko.computed(function() {
* @static return Enums.FolderType.Inbox === this.type();
* @param {AjaxJsonFolder} oJsonFolder }, this);
* @return {?FolderModel}
*/
FolderModel.newInstanceFromJson = function (oJsonFolder)
{
var oFolderModel = new FolderModel();
return oFolderModel.initByJson(oJsonFolder) ? oFolderModel.initComputed() : null;
};
/** this.hasSubScribedSubfolders = ko.computed(function() {
* @return {FolderModel} return !!_.find(this.subFolders(), function(oFolder) {
*/ return (oFolder.subScribed() || oFolder.hasSubScribedSubfolders()) && !oFolder.isSystemFolder();
FolderModel.prototype.initComputed = function () });
{ }, this);
var sInboxFolderName = Cache.getFolderInboxName();
this.isInbox = ko.computed(function () { this.canBeEdited = ko.computed(function() {
return Enums.FolderType.Inbox === this.type(); return Enums.FolderType.User === this.type() && this.existen && this.selectable;
}, this); }, this);
this.hasSubScribedSubfolders = ko.computed(function () { this.visible = ko.computed(function() {
return !!_.find(this.subFolders(), function (oFolder) {
return (oFolder.subScribed() || oFolder.hasSubScribedSubfolders()) && !oFolder.isSystemFolder();
});
}, this);
this.canBeEdited = ko.computed(function () { var
return Enums.FolderType.User === this.type() && this.existen && this.selectable; bSubScribed = this.subScribed(),
}, this); bSubFolders = this.hasSubScribedSubfolders();
this.visible = ko.computed(function () { return (bSubScribed || (bSubFolders && (!this.existen || !this.selectable)));
var }, this);
bSubScribed = this.subScribed(),
bSubFolders = this.hasSubScribedSubfolders()
;
return (bSubScribed || (bSubFolders && (!this.existen || !this.selectable))); this.isSystemFolder = ko.computed(function() {
return Enums.FolderType.User !== this.type();
}, this);
}, this); this.hidden = ko.computed(function() {
this.isSystemFolder = ko.computed(function () { var
return Enums.FolderType.User !== this.type(); bSystem = this.isSystemFolder(),
}, this); bSubFolders = this.hasSubScribedSubfolders();
this.hidden = ko.computed(function () { return (bSystem && !bSubFolders) || (!this.selectable && !bSubFolders);
var }, this);
bSystem = this.isSystemFolder(),
bSubFolders = this.hasSubScribedSubfolders()
;
return (bSystem && !bSubFolders) || (!this.selectable && !bSubFolders); this.selectableForFolderList = ko.computed(function() {
return !this.isSystemFolder() && this.selectable;
}, this);
}, this); this.messageCountAll = ko.computed({
'read': this.privateMessageCountAll,
this.selectableForFolderList = ko.computed(function () { 'write': function(iValue) {
return !this.isSystemFolder() && this.selectable; if (Utils.isPosNumeric(iValue, true))
}, 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
}).extend({'notify': 'always'});
this.messageCountUnread = ko.computed({
'read': this.privateMessageCountUnread,
'write': function (iValue) {
if (Utils.isPosNumeric(iValue, true))
{
this.privateMessageCountUnread(iValue);
}
else
{
this.privateMessageCountUnread.valueHasMutated();
}
},
'owner': this
}).extend({'notify': 'always'});
this.printableUnreadCount = ko.computed(function () {
var
iCount = this.messageCountAll(),
iUnread = this.messageCountUnread(),
iType = this.type()
;
if (0 < iCount)
{ {
if (Enums.FolderType.Draft === iType) this.privateMessageCountAll(iValue);
{
return '' + iCount;
}
else if (0 < iUnread && Enums.FolderType.Trash !== iType && Enums.FolderType.Archive !== iType && Enums.FolderType.SentItems !== iType)
{
return '' + iUnread;
}
} }
else
{
this.privateMessageCountAll.valueHasMutated();
}
},
'owner': this
}).extend({'notify': 'always'});
return ''; this.messageCountUnread = ko.computed({
'read': this.privateMessageCountUnread,
'write': function(iValue) {
if (Utils.isPosNumeric(iValue, true))
{
this.privateMessageCountUnread(iValue);
}
else
{
this.privateMessageCountUnread.valueHasMutated();
}
},
'owner': this
}).extend({'notify': 'always'});
}, this); this.printableUnreadCount = ko.computed(function() {
var
iCount = this.messageCountAll(),
iUnread = this.messageCountUnread(),
iType = this.type();
this.canBeDeleted = ko.computed(function () { if (0 < iCount)
var {
bSystem = this.isSystemFolder() if (Enums.FolderType.Draft === iType)
; {
return !bSystem && 0 === this.subFolders().length && sInboxFolderName !== this.fullNameRaw; return '' + iCount;
}, this); }
else if (0 < iUnread && Enums.FolderType.Trash !== iType && Enums.FolderType.Archive !== iType && Enums.FolderType.SentItems !== iType)
{
return '' + iUnread;
}
}
this.canBeSubScribed = ko.computed(function () { return '';
return !this.isSystemFolder() && this.selectable && sInboxFolderName !== this.fullNameRaw;
}, this);
this.canBeChecked = this.canBeSubScribed; }, this);
// this.visible.subscribe(function () { this.canBeDeleted = ko.computed(function() {
// Utils.timeOutAction('folder-list-folder-visibility-change', function () { var
bSystem = this.isSystemFolder();
return !bSystem && 0 === this.subFolders().length && sInboxFolderName !== this.fullNameRaw;
}, this);
this.canBeSubScribed = ko.computed(function() {
return !this.isSystemFolder() && this.selectable && sInboxFolderName !== this.fullNameRaw;
}, this);
this.canBeChecked = this.canBeSubScribed;
// this.visible.subscribe(function() {
// Utils.timeOutAction('folder-list-folder-visibility-change', function() {
// Globals.$win.trigger('folder-list-folder-visibility-change'); // Globals.$win.trigger('folder-list-folder-visibility-change');
// }, 100); // }, 100);
// }); // });
this.localName = ko.computed(function () { this.localName = ko.computed(function() {
Translator.trigger(); Translator.trigger();
var
iType = this.type(),
sName = this.name()
;
if (this.isSystemFolder())
{
switch (iType)
{
case Enums.FolderType.Inbox:
sName = Translator.i18n('FOLDER_LIST/INBOX_NAME');
break;
case Enums.FolderType.SentItems:
sName = Translator.i18n('FOLDER_LIST/SENT_NAME');
break;
case Enums.FolderType.Draft:
sName = Translator.i18n('FOLDER_LIST/DRAFTS_NAME');
break;
case Enums.FolderType.Spam:
sName = Translator.i18n('FOLDER_LIST/SPAM_NAME');
break;
case Enums.FolderType.Trash:
sName = Translator.i18n('FOLDER_LIST/TRASH_NAME');
break;
case Enums.FolderType.Archive:
sName = Translator.i18n('FOLDER_LIST/ARCHIVE_NAME');
break;
}
}
return sName;
}, this);
this.manageFolderSystemName = ko.computed(function () {
Translator.trigger();
var
sSuffix = '',
iType = this.type(),
sName = this.name()
;
if (this.isSystemFolder())
{
switch (iType)
{
case Enums.FolderType.Inbox:
sSuffix = '(' + Translator.i18n('FOLDER_LIST/INBOX_NAME') + ')';
break;
case Enums.FolderType.SentItems:
sSuffix = '(' + Translator.i18n('FOLDER_LIST/SENT_NAME') + ')';
break;
case Enums.FolderType.Draft:
sSuffix = '(' + Translator.i18n('FOLDER_LIST/DRAFTS_NAME') + ')';
break;
case Enums.FolderType.Spam:
sSuffix = '(' + Translator.i18n('FOLDER_LIST/SPAM_NAME') + ')';
break;
case Enums.FolderType.Trash:
sSuffix = '(' + Translator.i18n('FOLDER_LIST/TRASH_NAME') + ')';
break;
case Enums.FolderType.Archive:
sSuffix = '(' + Translator.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.printableUnreadCount();
}, 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 var
bResult = false, iType = this.type(),
sInboxFolderName = Cache.getFolderInboxName() sName = this.name();
;
if (oJsonFolder && 'Object/Folder' === oJsonFolder['@Object']) if (this.isSystemFolder())
{ {
this.name(oJsonFolder.Name); switch (iType)
this.delimiter = oJsonFolder.Delimiter; {
this.fullName = oJsonFolder.FullName; case Enums.FolderType.Inbox:
this.fullNameRaw = oJsonFolder.FullNameRaw; sName = Translator.i18n('FOLDER_LIST/INBOX_NAME');
this.fullNameHash = oJsonFolder.FullNameHash; break;
this.deep = oJsonFolder.FullNameRaw.split(this.delimiter).length - 1; case Enums.FolderType.SentItems:
this.selectable = !!oJsonFolder.IsSelectable; sName = Translator.i18n('FOLDER_LIST/SENT_NAME');
this.existen = !!oJsonFolder.IsExists; break;
case Enums.FolderType.Draft:
this.subScribed(!!oJsonFolder.IsSubscribed); sName = Translator.i18n('FOLDER_LIST/DRAFTS_NAME');
this.checkable(!!oJsonFolder.Checkable); break;
case Enums.FolderType.Spam:
this.type(sInboxFolderName === this.fullNameRaw ? Enums.FolderType.Inbox : Enums.FolderType.User); sName = Translator.i18n('FOLDER_LIST/SPAM_NAME');
break;
bResult = true; case Enums.FolderType.Trash:
sName = Translator.i18n('FOLDER_LIST/TRASH_NAME');
break;
case Enums.FolderType.Archive:
sName = Translator.i18n('FOLDER_LIST/ARCHIVE_NAME');
break;
// no default
}
} }
return bResult; return sName;
};
/** }, this);
* @return {string}
*/ this.manageFolderSystemName = ko.computed(function() {
FolderModel.prototype.printableFullName = function ()
Translator.trigger();
var
sSuffix = '',
iType = this.type(),
sName = this.name();
if (this.isSystemFolder())
{
switch (iType)
{
case Enums.FolderType.Inbox:
sSuffix = '(' + Translator.i18n('FOLDER_LIST/INBOX_NAME') + ')';
break;
case Enums.FolderType.SentItems:
sSuffix = '(' + Translator.i18n('FOLDER_LIST/SENT_NAME') + ')';
break;
case Enums.FolderType.Draft:
sSuffix = '(' + Translator.i18n('FOLDER_LIST/DRAFTS_NAME') + ')';
break;
case Enums.FolderType.Spam:
sSuffix = '(' + Translator.i18n('FOLDER_LIST/SPAM_NAME') + ')';
break;
case Enums.FolderType.Trash:
sSuffix = '(' + Translator.i18n('FOLDER_LIST/TRASH_NAME') + ')';
break;
case Enums.FolderType.Archive:
sSuffix = '(' + Translator.i18n('FOLDER_LIST/ARCHIVE_NAME') + ')';
break;
// no default
}
}
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.printableUnreadCount();
}, 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;
/**
* @returns {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
* @returns {boolean}
*/
FolderModel.prototype.initByJson = function(oJsonFolder)
{
var
bResult = false,
sInboxFolderName = Cache.getFolderInboxName();
if (oJsonFolder && 'Object/Folder' === oJsonFolder['@Object'])
{ {
return this.fullName.split(this.delimiter).join(' / '); 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;
module.exports = FolderModel; this.subScribed(!!oJsonFolder.IsSubscribed);
this.checkable(!!oJsonFolder.Checkable);
}()); this.type(sInboxFolderName === this.fullNameRaw ? Enums.FolderType.Inbox : Enums.FolderType.User);
bResult = true;
}
return bResult;
};
/**
* @returns {string}
*/
FolderModel.prototype.printableFullName = function()
{
return this.fullName.split(this.delimiter).join(' / ');
};
module.exports = FolderModel;

View file

@ -1,52 +1,44 @@
(function () { var
_ = require('_'),
ko = require('ko'),
'use strict'; AbstractModel = require('Knoin/AbstractModel');
/**
* @constructor
* @param {string} sId
* @param {string} sEmail
*/
function IdentityModel(sId, sEmail)
{
AbstractModel.call(this, 'IdentityModel');
this.id = ko.observable(sId || '');
this.email = ko.observable(sEmail);
this.name = ko.observable('');
this.replyTo = ko.observable('');
this.bcc = ko.observable('');
this.signature = ko.observable('');
this.signatureInsertBefore = ko.observable(false);
this.deleteAccess = ko.observable(false);
this.canBeDeleted = ko.computed(function() {
return '' !== this.id();
}, this);
}
_.extend(IdentityModel.prototype, AbstractModel.prototype);
IdentityModel.prototype.formattedName = function()
{
var var
_ = require('_'), sName = this.name(),
ko = require('ko'), sEmail = this.email();
AbstractModel = require('Knoin/AbstractModel') return ('' !== sName) ? sName + ' (' + sEmail + ')' : sEmail;
; };
/** module.exports = IdentityModel;
* @param {string} sId
* @param {string} sEmail
* @constructor
*/
function IdentityModel(sId, sEmail)
{
AbstractModel.call(this, 'IdentityModel');
this.id = ko.observable(sId || '');
this.email = ko.observable(sEmail);
this.name = ko.observable('');
this.replyTo = ko.observable('');
this.bcc = ko.observable('');
this.signature = ko.observable('');
this.signatureInsertBefore = ko.observable(false);
this.deleteAccess = ko.observable(false);
this.canBeDeleted = ko.computed(function () {
return '' !== this.id();
}, this);
}
_.extend(IdentityModel.prototype, AbstractModel.prototype);
IdentityModel.prototype.formattedName = function ()
{
var
sName = this.name(),
sEmail = this.email()
;
return ('' !== sName) ? sName + ' (' + sEmail + ')' : sEmail;
};
module.exports = IdentityModel;
}());

File diff suppressed because it is too large Load diff

View file

@ -1,89 +1,80 @@
(function () { var
_ = require('_'),
'use strict'; Enums = require('Common/Enums'),
Utils = require('Common/Utils'),
var MessageSimpleModel = require('Model/MessageSimple');
_ = require('_'),
Enums = require('Common/Enums'), /**
Utils = require('Common/Utils'), * @constructor
*/
function MessageFullModel()
{
MessageSimpleModel.call(this, 'MessageFullModel');
}
// MessageHelper = require('Helper/Message').default, _.extend(MessageFullModel.prototype, MessageSimpleModel.prototype);
MessageSimpleModel = require('Model/MessageSimple') MessageFullModel.prototype.priority = 0;
; MessageFullModel.prototype.hash = '';
MessageFullModel.prototype.requestHash = '';
MessageFullModel.prototype.proxy = false;
MessageFullModel.prototype.hasAttachments = false;
/** MessageFullModel.prototype.clear = function()
* @constructor {
*/ MessageSimpleModel.prototype.clear.call(this);
function MessageFullModel()
this.priority = 0;
this.hash = '';
this.requestHash = '';
this.proxy = false;
this.hasAttachments = false;
};
/**
* @param {AjaxJsonMessage} oJson
* @returns {boolean}
*/
MessageFullModel.prototype.initByJson = function(oJson)
{
var bResult = false;
if (oJson && 'Object/Message' === oJson['@Object'])
{ {
MessageSimpleModel.call(this, 'MessageFullModel'); if (MessageSimpleModel.prototype.initByJson.call(this, oJson))
{
this.priority = Utils.pInt(oJson.Priority);
this.priority = Utils.inArray(this.priority, [Enums.MessagePriority.High, Enums.MessagePriority.Low]) ?
this.priority : Enums.MessagePriority.Normal;
this.hash = Utils.pString(oJson.Hash);
this.requestHash = Utils.pString(oJson.RequestHash);
this.proxy = !!oJson.ExternalProxy;
this.hasAttachments = !!oJson.HasAttachments;
bResult = true;
}
} }
_.extend(MessageFullModel.prototype, MessageSimpleModel.prototype); return bResult;
};
MessageFullModel.prototype.priority = 0; /**
MessageFullModel.prototype.hash = ''; * @static
MessageFullModel.prototype.requestHash = ''; * @param {AjaxJsonMessage} oJson
MessageFullModel.prototype.proxy = false; * @returns {?MessageFullModel}
MessageFullModel.prototype.hasAttachments = false; */
MessageFullModel.newInstanceFromJson = function(oJson)
{
var oItem = oJson ? new MessageFullModel() : null;
return oItem && oItem.initByJson(oJson) ? oItem : null;
};
MessageFullModel.prototype.clear = function () module.exports = MessageFullModel;
{
MessageSimpleModel.prototype.clear.call(this);
this.priority = 0;
this.hash = '';
this.requestHash = '';
this.proxy = false;
this.hasAttachments = false;
};
/**
* @param {AjaxJsonMessage} oJson
* @return {boolean}
*/
MessageFullModel.prototype.initByJson = function (oJson)
{
var bResult = false;
if (oJson && 'Object/Message' === oJson['@Object'])
{
if (MessageSimpleModel.prototype.initByJson.call(this, oJson))
{
this.priority = Utils.pInt(oJson.Priority);
this.priority = Utils.inArray(this.priority, [Enums.MessagePriority.High, Enums.MessagePriority.Low]) ?
this.priority : Enums.MessagePriority.Normal;
this.hash = Utils.pString(oJson.Hash);
this.requestHash = Utils.pString(oJson.RequestHash);
this.proxy = !!oJson.ExternalProxy;
this.hasAttachments = !!oJson.HasAttachments;
bResult = true;
}
}
return bResult;
};
/**
* @static
* @param {AjaxJsonMessage} oJson
* @return {?MessageFullModel}
*/
MessageFullModel.newInstanceFromJson = function (oJson)
{
var oItem = oJson ? new MessageFullModel() : null;
return oItem && oItem.initByJson(oJson) ? oItem : null;
};
module.exports = MessageFullModel;
}());

View file

@ -1,174 +1,167 @@
(function () { var
_ = require('_'),
ko = require('ko'),
'use strict'; Utils = require('Common/Utils'),
var MessageHelper = require('Helper/Message').default,
_ = require('_'),
ko = require('ko'),
Utils = require('Common/Utils'), AbstractModel = require('Knoin/AbstractModel');
MessageHelper = require('Helper/Message').default, /**
* @constructor
* @param {string=} sSuperName
*/
function MessageSimpleModel(sSuperName)
{
AbstractModel.call(this, sSuperName || 'MessageSimpleModel');
AbstractModel = require('Knoin/AbstractModel') this.flagged = ko.observable(false);
; this.selected = ko.observable(false);
}
/** _.extend(MessageSimpleModel.prototype, AbstractModel.prototype);
* @param {string=} sSuperName
* @constructor MessageSimpleModel.prototype.isSimpleMessage = true;
*/
function MessageSimpleModel(sSuperName) MessageSimpleModel.prototype.folder = '';
MessageSimpleModel.prototype.folderFullNameRaw = '';
MessageSimpleModel.prototype.uid = '';
MessageSimpleModel.prototype.subject = '';
MessageSimpleModel.prototype.to = [];
MessageSimpleModel.prototype.from = [];
MessageSimpleModel.prototype.cc = [];
MessageSimpleModel.prototype.bcc = [];
MessageSimpleModel.prototype.replyTo = [];
MessageSimpleModel.prototype.deliveredTo = [];
MessageSimpleModel.prototype.fromAsString = '';
MessageSimpleModel.prototype.fromAsStringClear = '';
MessageSimpleModel.prototype.toAsString = '';
MessageSimpleModel.prototype.toAsStringClear = '';
MessageSimpleModel.prototype.senderAsString = '';
MessageSimpleModel.prototype.senderAsStringClear = '';
MessageSimpleModel.prototype.size = 0;
MessageSimpleModel.prototype.timestamp = 0;
MessageSimpleModel.prototype.clear = function()
{
this.folder = '';
this.folderFullNameRaw = '';
this.uid = '';
this.subject = '';
this.to = [];
this.from = [];
this.cc = [];
this.bcc = [];
this.replyTo = [];
this.deliveredTo = [];
this.fromAsString = '';
this.fromAsStringClear = '';
this.toAsString = '';
this.toAsStringClear = '';
this.senderAsString = '';
this.senderAsStringClear = '';
this.size = 0;
this.timestamp = 0;
this.flagged(false);
this.selected(false);
};
/**
* @param {Object} oJson
* @returns {boolean}
*/
MessageSimpleModel.prototype.initByJson = function(oJson)
{
var bResult = false;
if (oJson && 'Object/Message' === oJson['@Object'])
{ {
AbstractModel.call(this, sSuperName || 'MessageSimpleModel'); this.folder = Utils.pString(oJson.Folder);
this.folderFullNameRaw = this.folder;
this.flagged = ko.observable(false); this.uid = Utils.pString(oJson.Uid);
this.selected = ko.observable(false);
}
_.extend(MessageSimpleModel.prototype, AbstractModel.prototype); this.subject = Utils.pString(oJson.Subject);
MessageSimpleModel.prototype.__simple_message__ = true; if (Utils.isArray(oJson.SubjectParts))
{
this.subjectPrefix = Utils.pString(oJson.SubjectParts[0]);
this.subjectSuffix = Utils.pString(oJson.SubjectParts[1]);
}
else
{
this.subjectPrefix = '';
this.subjectSuffix = this.subject;
}
MessageSimpleModel.prototype.folder = ''; this.from = MessageHelper.emailArrayFromJson(oJson.From);
MessageSimpleModel.prototype.folderFullNameRaw = ''; this.to = MessageHelper.emailArrayFromJson(oJson.To);
this.cc = MessageHelper.emailArrayFromJson(oJson.Cc);
this.bcc = MessageHelper.emailArrayFromJson(oJson.Bcc);
this.replyTo = MessageHelper.emailArrayFromJson(oJson.ReplyTo);
this.deliveredTo = MessageHelper.emailArrayFromJson(oJson.DeliveredTo);
MessageSimpleModel.prototype.uid = ''; this.size = Utils.pInt(oJson.Size);
MessageSimpleModel.prototype.subject = ''; this.timestamp = Utils.pInt(oJson.DateTimeStampInUTC);
MessageSimpleModel.prototype.to = []; this.fromAsString = MessageHelper.emailArrayToString(this.from, true);
MessageSimpleModel.prototype.from = []; this.fromAsStringClear = MessageHelper.emailArrayToStringClear(this.from);
MessageSimpleModel.prototype.cc = [];
MessageSimpleModel.prototype.bcc = [];
MessageSimpleModel.prototype.replyTo = [];
MessageSimpleModel.prototype.deliveredTo = [];
MessageSimpleModel.prototype.fromAsString = ''; this.toAsString = MessageHelper.emailArrayToString(this.to, true);
MessageSimpleModel.prototype.fromAsStringClear = ''; this.toAsStringClear = MessageHelper.emailArrayToStringClear(this.to);
MessageSimpleModel.prototype.toAsString = '';
MessageSimpleModel.prototype.toAsStringClear = '';
MessageSimpleModel.prototype.senderAsString = '';
MessageSimpleModel.prototype.senderAsStringClear = '';
MessageSimpleModel.prototype.size = 0;
MessageSimpleModel.prototype.timestamp = 0;
MessageSimpleModel.prototype.clear = function ()
{
this.folder = '';
this.folderFullNameRaw = '';
this.uid = '';
this.subject = '';
this.to = [];
this.from = [];
this.cc = [];
this.bcc = [];
this.replyTo = [];
this.deliveredTo = [];
this.fromAsString = '';
this.fromAsStringClear = '';
this.toAsString = '';
this.toAsStringClear = '';
this.senderAsString = '';
this.senderAsStringClear = '';
this.size = 0;
this.timestamp = 0;
this.flagged(false); this.flagged(false);
this.selected(false); this.selected(false);
};
/** this.populateSenderEmail();
* @param {Object} oJson
* @return {boolean} bResult = true;
*/ }
MessageSimpleModel.prototype.initByJson = function (oJson)
return bResult;
};
MessageSimpleModel.prototype.populateSenderEmail = function(bDraftOrSentFolder)
{
this.senderAsString = this.fromAsString;
this.senderAsStringClear = this.fromAsStringClear;
if (bDraftOrSentFolder)
{ {
var bResult = false; this.senderAsString = this.toAsString;
this.senderAsStringClear = this.toAsStringClear;
}
};
if (oJson && 'Object/Message' === oJson['@Object']) /**
{ * @returns {Array}
this.folder = Utils.pString(oJson.Folder); */
this.folderFullNameRaw = this.folder; MessageSimpleModel.prototype.threads = function()
{
return [];
};
this.uid = Utils.pString(oJson.Uid); /**
* @static
* @param {Object} oJson
* @returns {?MessageSimpleModel}
*/
MessageSimpleModel.newInstanceFromJson = function(oJson)
{
var oItem = oJson ? new MessageSimpleModel() : null;
return oItem && oItem.initByJson(oJson) ? oItem : null;
};
this.subject = Utils.pString(oJson.Subject); module.exports = MessageSimpleModel;
if (Utils.isArray(oJson.SubjectParts))
{
this.subjectPrefix = Utils.pString(oJson.SubjectParts[0]);
this.subjectSuffix = Utils.pString(oJson.SubjectParts[1]);
}
else
{
this.subjectPrefix = '';
this.subjectSuffix = this.subject;
}
this.from = MessageHelper.emailArrayFromJson(oJson.From);
this.to = MessageHelper.emailArrayFromJson(oJson.To);
this.cc = MessageHelper.emailArrayFromJson(oJson.Cc);
this.bcc = MessageHelper.emailArrayFromJson(oJson.Bcc);
this.replyTo = MessageHelper.emailArrayFromJson(oJson.ReplyTo);
this.deliveredTo = MessageHelper.emailArrayFromJson(oJson.DeliveredTo);
this.size = Utils.pInt(oJson.Size);
this.timestamp = Utils.pInt(oJson.DateTimeStampInUTC);
this.fromAsString = MessageHelper.emailArrayToString(this.from, true);
this.fromAsStringClear = MessageHelper.emailArrayToStringClear(this.from);
this.toAsString = MessageHelper.emailArrayToString(this.to, true);
this.toAsStringClear = MessageHelper.emailArrayToStringClear(this.to);
this.flagged(false);
this.selected(false);
this.populateSenderEmail();
bResult = true;
}
return bResult;
};
MessageSimpleModel.prototype.populateSenderEmail = function (bDraftOrSentFolder)
{
this.senderAsString = this.fromAsString;
this.senderAsStringClear = this.fromAsStringClear;
if (bDraftOrSentFolder)
{
this.senderAsString = this.toAsString;
this.senderAsStringClear = this.toAsStringClear;
}
};
/**
* @return {Array}
*/
MessageSimpleModel.prototype.threads = function ()
{
return [];
};
/**
* @static
* @param {Object} oJson
* @return {?MessageSimpleModel}
*/
MessageSimpleModel.newInstanceFromJson = function (oJson)
{
var oItem = oJson ? new MessageSimpleModel() : null;
return oItem && oItem.initByJson(oJson) ? oItem : null;
};
module.exports = MessageSimpleModel;
}());

View file

@ -1,111 +1,103 @@
(function () { var
_ = require('_'),
ko = require('ko'),
'use strict'; Utils = require('Common/Utils'),
var PgpStore = require('Stores/User/Pgp'),
_ = require('_'),
ko = require('ko'),
Utils = require('Common/Utils'), AbstractModel = require('Knoin/AbstractModel');
PgpStore = require('Stores/User/Pgp'), /**
* @constructor
* @param {string} iIndex
* @param {string} sGuID
* @param {string} sID
* @param {array} aIDs
* @param {array} aUserIDs
* @param {array} aEmails
* @param {boolean} bIsPrivate
* @param {string} sArmor
* @param {string} sUserID
*/
function OpenPgpKeyModel(iIndex, sGuID, sID, aIDs, aUserIDs, aEmails, bIsPrivate, sArmor, sUserID)
{
AbstractModel.call(this, 'OpenPgpKeyModel');
AbstractModel = require('Knoin/AbstractModel') this.index = iIndex;
; this.id = sID;
this.ids = Utils.isNonEmptyArray(aIDs) ? aIDs : [sID];
this.guid = sGuID;
this.users = aUserIDs;
this.emails = aEmails;
this.armor = sArmor;
this.isPrivate = !!bIsPrivate;
/** this.selectUser(sUserID);
* @param {string} iIndex
* @param {string} sGuID this.deleteAccess = ko.observable(false);
* @param {string} sID }
* @param {array} aIDs
* @param {array} aUserIDs _.extend(OpenPgpKeyModel.prototype, AbstractModel.prototype);
* @param {array} aEmails
* @param {boolean} bIsPrivate OpenPgpKeyModel.prototype.index = 0;
* @param {string} sArmor OpenPgpKeyModel.prototype.id = '';
* @param {string} sUserID OpenPgpKeyModel.prototype.ids = [];
* @constructor OpenPgpKeyModel.prototype.guid = '';
*/ OpenPgpKeyModel.prototype.user = '';
function OpenPgpKeyModel(iIndex, sGuID, sID, aIDs, aUserIDs, aEmails, bIsPrivate, sArmor, sUserID) OpenPgpKeyModel.prototype.users = [];
OpenPgpKeyModel.prototype.email = '';
OpenPgpKeyModel.prototype.emails = [];
OpenPgpKeyModel.prototype.armor = '';
OpenPgpKeyModel.prototype.isPrivate = false;
OpenPgpKeyModel.prototype.getNativeKey = function()
{
var oKey = null;
try
{ {
AbstractModel.call(this, 'OpenPgpKeyModel'); oKey = PgpStore.openpgp.key.readArmored(this.armor);
if (oKey && !oKey.err && oKey.keys && oKey.keys[0])
this.index = iIndex; {
this.id = sID; return oKey;
this.ids = Utils.isNonEmptyArray(aIDs) ? aIDs : [sID]; }
this.guid = sGuID; }
this.users = aUserIDs; catch (e)
this.emails = aEmails; {
this.armor = sArmor; Utils.log(e);
this.isPrivate = !!bIsPrivate;
this.selectUser(sUserID);
this.deleteAccess = ko.observable(false);
} }
_.extend(OpenPgpKeyModel.prototype, AbstractModel.prototype); return null;
};
OpenPgpKeyModel.prototype.index = 0; OpenPgpKeyModel.prototype.getNativeKeys = function()
OpenPgpKeyModel.prototype.id = ''; {
OpenPgpKeyModel.prototype.ids = []; var oKey = this.getNativeKey();
OpenPgpKeyModel.prototype.guid = ''; return oKey && oKey.keys ? oKey.keys : null;
OpenPgpKeyModel.prototype.user = ''; };
OpenPgpKeyModel.prototype.users = [];
OpenPgpKeyModel.prototype.email = '';
OpenPgpKeyModel.prototype.emails = [];
OpenPgpKeyModel.prototype.armor = '';
OpenPgpKeyModel.prototype.isPrivate = false;
OpenPgpKeyModel.prototype.getNativeKey = function () OpenPgpKeyModel.prototype.select = function(sPattern, sProperty)
{
if (this[sProperty])
{ {
var oKey = null; var index = this[sProperty].indexOf(sPattern);
try if (-1 !== index)
{ {
oKey = PgpStore.openpgp.key.readArmored(this.armor); this.user = this.users[index];
if (oKey && !oKey.err && oKey.keys && oKey.keys[0]) this.email = this.emails[index];
{
return oKey;
}
}
catch (e)
{
Utils.log(e);
} }
}
};
return null; OpenPgpKeyModel.prototype.selectUser = function(sUser)
}; {
this.select(sUser, 'users');
};
OpenPgpKeyModel.prototype.getNativeKeys = function () OpenPgpKeyModel.prototype.selectEmail = function(sEmail)
{ {
var oKey = this.getNativeKey(); this.select(sEmail, 'emails');
return oKey && oKey.keys ? oKey.keys : null; };
};
OpenPgpKeyModel.prototype.select = function (sPattern, sProperty)
{
if (this[sProperty])
{
var index = this[sProperty].indexOf(sPattern);
if (index !== -1)
{
this.user = this.users[index];
this.email = this.emails[index];
}
}
};
OpenPgpKeyModel.prototype.selectUser = function (sUser)
{
this.select(sUser, 'users');
};
OpenPgpKeyModel.prototype.selectEmail = function (sEmail)
{
this.select(sEmail, 'emails');
};
module.exports = OpenPgpKeyModel;
}());
module.exports = OpenPgpKeyModel;

View file

@ -1,77 +1,69 @@
(function () { var
_ = require('_'),
ko = require('ko'),
'use strict'; Utils = require('Common/Utils'),
var AbstractModel = require('Knoin/AbstractModel');
_ = require('_'),
ko = require('ko'),
Utils = require('Common/Utils'), /**
* @constructor
* @param {string} sID
* @param {string} sName
* @param {string} sBody
*/
function TemplateModel(sID, sName, sBody)
{
AbstractModel.call(this, 'TemplateModel');
AbstractModel = require('Knoin/AbstractModel') this.id = sID;
; this.name = sName;
this.body = sBody;
this.populated = true;
/** this.deleteAccess = ko.observable(false);
* @constructor }
*
* @param {string} sID _.extend(TemplateModel.prototype, AbstractModel.prototype);
* @param {string} sName
* @param {string} sBody /**
*/ * @type {string}
function TemplateModel(sID, sName, sBody) */
TemplateModel.prototype.id = '';
/**
* @type {string}
*/
TemplateModel.prototype.name = '';
/**
* @type {string}
*/
TemplateModel.prototype.body = '';
/**
* @type {boolean}
*/
TemplateModel.prototype.populated = true;
/**
* @type {boolean}
*/
TemplateModel.prototype.parse = function(oItem)
{
var bResult = false;
if (oItem && 'Object/Template' === oItem['@Object'])
{ {
AbstractModel.call(this, 'TemplateModel'); this.id = Utils.pString(oItem.ID);
this.name = Utils.pString(oItem.Name);
this.body = Utils.pString(oItem.Body);
this.populated = !!oItem.Populated;
this.id = sID; bResult = true;
this.name = sName;
this.body = sBody;
this.populated = true;
this.deleteAccess = ko.observable(false);
} }
_.extend(TemplateModel.prototype, AbstractModel.prototype); return bResult;
};
/** module.exports = TemplateModel;
* @type {string}
*/
TemplateModel.prototype.id = '';
/**
* @type {string}
*/
TemplateModel.prototype.name = '';
/**
* @type {string}
*/
TemplateModel.prototype.body = '';
/**
* @type {boolean}
*/
TemplateModel.prototype.populated = true;
/**
* @type {boolean}
*/
TemplateModel.prototype.parse = function (oItem)
{
var bResult = false;
if (oItem && 'Object/Template' === oItem['@Object'])
{
this.id = Utils.pString(oItem.ID);
this.name = Utils.pString(oItem.Name);
this.body = Utils.pString(oItem.Body);
this.populated = !!oItem.Populated;
bResult = true;
}
return bResult;
};
module.exports = TemplateModel;
}());

View file

@ -1,226 +1,219 @@
(function () { var
$ = require('$'),
_ = require('_'),
Promise = require('Promise'),
'use strict'; Consts = require('Common/Consts'),
Enums = require('Common/Enums'),
Globals = require('Common/Globals'),
Utils = require('Common/Utils'),
Links = require('Common/Links'),
Plugins = require('Common/Plugins'),
var Settings = require('Storage/Settings'),
$ = require('$'),
_ = require('_'),
Promise = require('Promise'),
Consts = require('Common/Consts'), AbstractBasicPromises = require('Promises/AbstractBasic');
Enums = require('Common/Enums'),
Globals = require('Common/Globals'),
Utils = require('Common/Utils'),
Links = require('Common/Links'),
Plugins = require('Common/Plugins'),
Settings = require('Storage/Settings'), /**
* @constructor
*/
function AbstractAjaxPromises()
{
AbstractBasicPromises.call(this);
AbstractBasicPromises = require('Promises/AbstractBasic') this.clear();
; }
/** _.extend(AbstractAjaxPromises.prototype, AbstractBasicPromises.prototype);
* @constructor
*/ AbstractAjaxPromises.prototype.oRequests = {};
function AbstractAjaxPromises()
AbstractAjaxPromises.prototype.clear = function()
{
this.oRequests = {};
};
AbstractAjaxPromises.prototype.abort = function(sAction, bClearOnly)
{
if (this.oRequests[sAction])
{ {
AbstractBasicPromises.call(this); if (!bClearOnly && this.oRequests[sAction].abort)
this.clear();
}
_.extend(AbstractAjaxPromises.prototype, AbstractBasicPromises.prototype);
AbstractAjaxPromises.prototype.oRequests = {};
AbstractAjaxPromises.prototype.clear = function ()
{
this.oRequests = {};
};
AbstractAjaxPromises.prototype.abort = function (sAction, bClearOnly)
{
if (this.oRequests[sAction])
{ {
if (!bClearOnly && this.oRequests[sAction].abort) this.oRequests[sAction].__aborted__ = true;
{ this.oRequests[sAction].abort();
this.oRequests[sAction].__aborted__ = true;
this.oRequests[sAction].abort();
}
this.oRequests[sAction] = null;
delete this.oRequests[sAction];
} }
return this; this.oRequests[sAction] = null;
}; delete this.oRequests[sAction];
}
AbstractAjaxPromises.prototype.ajaxRequest = function (sAction, bPost, iTimeOut, oParameters, sAdditionalGetString, fTrigger) return this;
{ };
var self = this;
return new Promise(function(resolve, reject) {
var AbstractAjaxPromises.prototype.ajaxRequest = function(sAction, bPost, iTimeOut, oParameters, sAdditionalGetString, fTrigger)
oH = null, {
iStart = Utils.microtime() var self = this;
; return new Promise(function(resolve, reject) {
iTimeOut = Utils.isNormal(iTimeOut) ? iTimeOut : Consts.DEFAULT_AJAX_TIMEOUT; var
sAdditionalGetString = Utils.isUnd(sAdditionalGetString) ? '' : Utils.pString(sAdditionalGetString); oH = null,
iStart = Utils.microtime();
if (bPost) iTimeOut = Utils.isNormal(iTimeOut) ? iTimeOut : Consts.DEFAULT_AJAX_TIMEOUT;
sAdditionalGetString = Utils.isUnd(sAdditionalGetString) ? '' : Utils.pString(sAdditionalGetString);
if (bPost)
{
oParameters.XToken = Settings.appSettingsGet('token');
}
Plugins.runHook('ajax-default-request', [sAction, oParameters, sAdditionalGetString]);
self.setTrigger(fTrigger, true);
oH = $.ajax({
type: bPost ? 'POST' : 'GET',
url: Links.ajax(sAdditionalGetString),
async: true,
dataType: 'json',
data: bPost ? (oParameters || {}) : {},
timeout: iTimeOut,
global: true
}).always(function(oData, sTextStatus) {
var bCached = false, oErrorData = null, sType = Enums.StorageResultType.Error;
if (oData && oData.Time)
{ {
oParameters.XToken = Settings.appSettingsGet('token'); bCached = Utils.pInt(oData.Time) > Utils.microtime() - iStart;
} }
Plugins.runHook('ajax-default-request', [sAction, oParameters, sAdditionalGetString]); // backward capability
switch (true)
{
case 'success' === sTextStatus && oData && oData.Result && sAction === oData.Action:
sType = Enums.StorageResultType.Success;
break;
case 'abort' === sTextStatus && (!oData || !oData.__aborted__):
sType = Enums.StorageResultType.Abort;
break;
// no default
}
self.setTrigger(fTrigger, true); Plugins.runHook('ajax-default-response', [sAction,
Enums.StorageResultType.Success === sType ? oData : null, sType, bCached, oParameters]);
oH = $.ajax({ if ('success' === sTextStatus)
type: bPost ? 'POST' : 'GET', {
url: Links.ajax(sAdditionalGetString), if (oData && oData.Result && sAction === oData.Action)
async: true,
dataType: 'json',
data: bPost ? (oParameters || {}) : {},
timeout: iTimeOut,
global: true
}).always(function (oData, sTextStatus) {
var bCached = false, oErrorData = null, sType = Enums.StorageResultType.Error;
if (oData && oData.Time)
{ {
bCached = Utils.pInt(oData.Time) > Utils.microtime() - iStart; oData.__cached__ = bCached;
resolve(oData);
} }
else if (oData && oData.Action)
// backward capability
switch (true)
{
case 'success' === sTextStatus && oData && oData.Result && sAction === oData.Action:
sType = Enums.StorageResultType.Success;
break;
case 'abort' === sTextStatus && (!oData || !oData.__aborted__):
sType = Enums.StorageResultType.Abort;
break;
}
Plugins.runHook('ajax-default-response', [sAction,
Enums.StorageResultType.Success === sType ? oData : null, sType, bCached, oParameters]);
if ('success' === sTextStatus)
{
if (oData && oData.Result && sAction === oData.Action)
{
oData.__cached__ = bCached;
resolve(oData);
}
else if (oData && oData.Action)
{
oErrorData = oData;
reject(oData.ErrorCode ? oData.ErrorCode : Enums.Notification.AjaxFalse);
}
else
{
oErrorData = oData;
reject(Enums.Notification.AjaxParse);
}
}
else if ('timeout' === sTextStatus)
{ {
oErrorData = oData; oErrorData = oData;
reject(Enums.Notification.AjaxTimeout); reject(oData.ErrorCode ? oData.ErrorCode : Enums.Notification.AjaxFalse);
}
else if ('abort' === sTextStatus)
{
if (!oData || !oData.__aborted__)
{
reject(Enums.Notification.AjaxAbort);
}
} }
else else
{ {
oErrorData = oData; oErrorData = oData;
reject(Enums.Notification.AjaxParse); reject(Enums.Notification.AjaxParse);
} }
if (self.oRequests[sAction])
{
self.oRequests[sAction] = null;
delete self.oRequests[sAction];
}
self.setTrigger(fTrigger, false);
if (oErrorData)
{
if (-1 < Utils.inArray(oErrorData.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.data.iAjaxErrorCount++;
}
if (Enums.Notification.InvalidToken === oErrorData.ErrorCode)
{
Globals.data.iTokenErrorCount++;
}
if (Consts.TOKEN_ERROR_LIMIT < Globals.data.iTokenErrorCount)
{
if (Globals.data.__APP__ && Globals.data.__APP__.loginAndLogoutReload)
{
Globals.data.__APP__.loginAndLogoutReload(false, true);
}
}
if (oErrorData.ClearAuth || oErrorData.Logout || Consts.AJAX_ERROR_LIMIT < Globals.data.iAjaxErrorCount)
{
if (Globals.data.__APP__ && Globals.data.__APP__.clearClientSideToken)
{
Globals.data.__APP__.clearClientSideToken();
}
if (Globals.data.__APP__ && !oErrorData.ClearAuth && Globals.data.__APP__.loginAndLogoutReload)
{
Globals.data.__APP__.loginAndLogoutReload(false, true);
}
}
}
});
if (oH)
{
if (self.oRequests[sAction])
{
self.oRequests[sAction] = null;
delete self.oRequests[sAction];
}
self.oRequests[sAction] = oH;
} }
else if ('timeout' === sTextStatus)
{
oErrorData = oData;
reject(Enums.Notification.AjaxTimeout);
}
else if ('abort' === sTextStatus)
{
if (!oData || !oData.__aborted__)
{
reject(Enums.Notification.AjaxAbort);
}
}
else
{
oErrorData = oData;
reject(Enums.Notification.AjaxParse);
}
if (self.oRequests[sAction])
{
self.oRequests[sAction] = null;
delete self.oRequests[sAction];
}
self.setTrigger(fTrigger, false);
if (oErrorData)
{
if (-1 < Utils.inArray(oErrorData.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.data.iAjaxErrorCount += 1;
}
if (Enums.Notification.InvalidToken === oErrorData.ErrorCode)
{
Globals.data.iTokenErrorCount += 1;
}
if (Consts.TOKEN_ERROR_LIMIT < Globals.data.iTokenErrorCount)
{
if (Globals.data.__APP__ && Globals.data.__APP__.loginAndLogoutReload)
{
Globals.data.__APP__.loginAndLogoutReload(false, true);
}
}
if (oErrorData.ClearAuth || oErrorData.Logout || Consts.AJAX_ERROR_LIMIT < Globals.data.iAjaxErrorCount)
{
if (Globals.data.__APP__ && Globals.data.__APP__.clearClientSideToken)
{
Globals.data.__APP__.clearClientSideToken();
}
if (Globals.data.__APP__ && !oErrorData.ClearAuth && Globals.data.__APP__.loginAndLogoutReload)
{
Globals.data.__APP__.loginAndLogoutReload(false, true);
}
}
}
}); });
};
AbstractAjaxPromises.prototype.getRequest = function (sAction, fTrigger, sAdditionalGetString, iTimeOut) if (oH)
{ {
sAdditionalGetString = Utils.isUnd(sAdditionalGetString) ? '' : Utils.pString(sAdditionalGetString); if (self.oRequests[sAction])
sAdditionalGetString = sAction + '/' + sAdditionalGetString; {
self.oRequests[sAction] = null;
delete self.oRequests[sAction];
}
return this.ajaxRequest(sAction, false, iTimeOut, null, sAdditionalGetString, fTrigger); self.oRequests[sAction] = oH;
}; }
});
};
AbstractAjaxPromises.prototype.postRequest = function (action, fTrigger, params, timeOut) AbstractAjaxPromises.prototype.getRequest = function(sAction, fTrigger, sAdditionalGetString, iTimeOut)
{ {
params = params || {}; sAdditionalGetString = Utils.isUnd(sAdditionalGetString) ? '' : Utils.pString(sAdditionalGetString);
params.Action = action; sAdditionalGetString = sAction + '/' + sAdditionalGetString;
return this.ajaxRequest(action, true, timeOut, params, '', fTrigger); return this.ajaxRequest(sAction, false, iTimeOut, null, sAdditionalGetString, fTrigger);
}; };
module.exports = AbstractAjaxPromises; AbstractAjaxPromises.prototype.postRequest = function(action, fTrigger, params, timeOut)
{
params = params || {};
params.Action = action;
}()); return this.ajaxRequest(action, true, timeOut, params, '', fTrigger);
};
module.exports = AbstractAjaxPromises;

View file

@ -1,52 +1,45 @@
(function () { var
_ = require('_'),
Promise = require('Promise'),
'use strict'; Utils = require('Common/Utils');
var /**
_ = require('_'), * @constructor
Promise = require('Promise'), */
function AbstractBasicPromises()
{
this.oPromisesStack = {};
}
Utils = require('Common/Utils') AbstractBasicPromises.prototype.func = function(fFunc)
; {
fFunc();
return this;
};
/** AbstractBasicPromises.prototype.fastResolve = function(mData)
* @constructor {
*/ return Promise.resolve(mData);
function AbstractBasicPromises() };
AbstractBasicPromises.prototype.fastReject = function(mData)
{
return Promise.reject(mData);
};
AbstractBasicPromises.prototype.setTrigger = function(mTrigger, bValue)
{
if (mTrigger)
{ {
this.oPromisesStack = {}; _.each(Utils.isArray(mTrigger) ? mTrigger : [mTrigger], function(fTrigger) {
if (fTrigger)
{
fTrigger(!!bValue);
}
});
} }
};
AbstractBasicPromises.prototype.func = function (fFunc) module.exports = AbstractBasicPromises;
{
fFunc();
return this;
};
AbstractBasicPromises.prototype.fastResolve = function (mData)
{
return Promise.resolve(mData);
};
AbstractBasicPromises.prototype.fastReject = function (mData)
{
return Promise.reject(mData);
};
AbstractBasicPromises.prototype.setTrigger = function (mTrigger, bValue)
{
if (mTrigger)
{
_.each(Utils.isArray(mTrigger) ? mTrigger : [mTrigger], function (fTrigger) {
if (fTrigger)
{
fTrigger(!!bValue);
}
});
}
};
module.exports = AbstractBasicPromises;
}());

View file

@ -1,94 +1,78 @@
(function () { var
window = require('window'),
_ = require('_'),
'use strict'; PromisesPopulator = require('Promises/User/Populator'),
AbstractAjaxPromises = require('Promises/AbstractAjax');
var /**
window = require('window'), * @constructor
_ = require('_'), * @extends AbstractAjaxPromises
*/
function UserAjaxUserPromises()
{
AbstractAjaxPromises.call(this);
}
// Enums = require('Common/Enums'), _.extend(UserAjaxUserPromises.prototype, AbstractAjaxPromises.prototype);
// Utils = require('Common/Utils'),
// Base64 = require('Common/Base64'),
// Cache = require('Common/Cache'),
// Links = require('Common/Links'),
//
// AppStore = require('Stores/User/App'),
// SettingsStore = require('Stores/User/Settings'),
PromisesPopulator = require('Promises/User/Populator'), UserAjaxUserPromises.prototype.foldersReload = function(fTrigger)
AbstractAjaxPromises = require('Promises/AbstractAjax') {
; return this.abort('Folders')
.postRequest('Folders', fTrigger).then(function(oData) {
/** PromisesPopulator.foldersList(oData.Result);
* @constructor PromisesPopulator.foldersAdditionalParameters(oData.Result);
* @extends AbstractAjaxPromises return true;
*/
function UserAjaxUserPromises()
{
AbstractAjaxPromises.call(this);
}
_.extend(UserAjaxUserPromises.prototype, AbstractAjaxPromises.prototype);
UserAjaxUserPromises.prototype.foldersReload = function (fTrigger)
{
return this.abort('Folders')
.postRequest('Folders', fTrigger).then(function (oData) {
PromisesPopulator.foldersList(oData.Result);
PromisesPopulator.foldersAdditionalParameters(oData.Result);
return true;
});
};
UserAjaxUserPromises.prototype._folders_timeout_ = 0;
UserAjaxUserPromises.prototype.foldersReloadWithTimeout = function (fTrigger)
{
this.setTrigger(fTrigger, true);
var self = this;
window.clearTimeout(this._folders_timeout_);
this._folders_timeout_ = window.setTimeout(function () {
self.foldersReload(fTrigger);
}, 500);
};
UserAjaxUserPromises.prototype.folderDelete = function (sFolderFullNameRaw, fTrigger)
{
return this.postRequest('FolderDelete', fTrigger, {
'Folder': sFolderFullNameRaw
}); });
}; };
UserAjaxUserPromises.prototype.folderCreate = function (sNewFolderName, sParentName, fTrigger) UserAjaxUserPromises.prototype.foldersTimeout = 0;
{ UserAjaxUserPromises.prototype.foldersReloadWithTimeout = function(fTrigger)
return this.postRequest('FolderCreate', fTrigger, { {
'Folder': sNewFolderName, this.setTrigger(fTrigger, true);
'Parent': sParentName
});
};
UserAjaxUserPromises.prototype.folderRename = function (sPrevFolderFullNameRaw, sNewFolderName, fTrigger) var self = this;
{ window.clearTimeout(this.foldersTimeout);
return this.postRequest('FolderRename', fTrigger, { this.foldersTimeout = window.setTimeout(function() {
'Folder': sPrevFolderFullNameRaw, self.foldersReload(fTrigger);
'NewFolderName': sNewFolderName }, 500);
}); };
};
UserAjaxUserPromises.prototype.attachmentsActions = function (sAction, aHashes, fTrigger) UserAjaxUserPromises.prototype.folderDelete = function(sFolderFullNameRaw, fTrigger)
{ {
return this.postRequest('AttachmentsActions', fTrigger, { return this.postRequest('FolderDelete', fTrigger, {
'Do': sAction, 'Folder': sFolderFullNameRaw
'Hashes': aHashes });
}); };
};
UserAjaxUserPromises.prototype.welcomeClose = function () UserAjaxUserPromises.prototype.folderCreate = function(sNewFolderName, sParentName, fTrigger)
{ {
return this.postRequest('WelcomeClose'); return this.postRequest('FolderCreate', fTrigger, {
}; 'Folder': sNewFolderName,
'Parent': sParentName
});
};
module.exports = new UserAjaxUserPromises(); UserAjaxUserPromises.prototype.folderRename = function(sPrevFolderFullNameRaw, sNewFolderName, fTrigger)
{
return this.postRequest('FolderRename', fTrigger, {
'Folder': sPrevFolderFullNameRaw,
'NewFolderName': sNewFolderName
});
};
}()); UserAjaxUserPromises.prototype.attachmentsActions = function(sAction, aHashes, fTrigger)
{
return this.postRequest('AttachmentsActions', fTrigger, {
'Do': sAction,
'Hashes': aHashes
});
};
UserAjaxUserPromises.prototype.welcomeClose = function()
{
return this.postRequest('WelcomeClose');
};
module.exports = new UserAjaxUserPromises();

View file

@ -1,213 +1,204 @@
(function () { var
_ = require('_'),
'use strict'; Consts = require('Common/Consts'),
Enums = require('Common/Enums'),
Utils = require('Common/Utils'),
Cache = require('Common/Cache'),
AppStore = require('Stores/User/App'),
FolderStore = require('Stores/User/Folder'),
Settings = require('Storage/Settings'),
Local = require('Storage/Client'),
FolderModel = require('Model/Folder'),
AbstractBasicPromises = require('Promises/AbstractBasic');
/**
* @constructor
*/
function PromisesUserPopulator()
{
AbstractBasicPromises.call(this);
}
_.extend(PromisesUserPopulator.prototype, AbstractBasicPromises.prototype);
/**
* @param {string} sFullNameHash
* @returns {boolean}
*/
PromisesUserPopulator.prototype.isFolderExpanded = function(sFullNameHash)
{
var aExpandedList = Local.get(Enums.ClientSideKeyName.ExpandedFolders);
return Utils.isArray(aExpandedList) && -1 !== _.indexOf(aExpandedList, sFullNameHash);
};
/**
* @param {string} sFolderFullNameRaw
* @returns {string}
*/
PromisesUserPopulator.prototype.normalizeFolder = function(sFolderFullNameRaw)
{
return ('' === sFolderFullNameRaw || Consts.UNUSED_OPTION_VALUE === sFolderFullNameRaw ||
null !== Cache.getFolderFromCacheList(sFolderFullNameRaw)) ? sFolderFullNameRaw : '';
};
/**
* @param {string} sNamespace
* @param {Array} aFolders
* @returns {Array}
*/
PromisesUserPopulator.prototype.folderResponseParseRec = function(sNamespace, aFolders)
{
var var
_ = require('_'), self = this,
iIndex = 0,
iLen = 0,
oFolder = null,
oCacheFolder = null,
sFolderFullNameRaw = '',
aSubFolders = [],
aList = [];
Consts = require('Common/Consts'), for (iIndex = 0, iLen = aFolders.length; iIndex < iLen; iIndex++)
Enums = require('Common/Enums'),
Utils = require('Common/Utils'),
Cache = require('Common/Cache'),
AppStore = require('Stores/User/App'),
FolderStore = require('Stores/User/Folder'),
Settings = require('Storage/Settings'),
Local = require('Storage/Client'),
FolderModel = require('Model/Folder'),
AbstractBasicPromises = require('Promises/AbstractBasic')
;
/**
* @constructor
*/
function PromisesUserPopulator()
{ {
AbstractBasicPromises.call(this); oFolder = aFolders[iIndex];
} if (oFolder)
_.extend(PromisesUserPopulator.prototype, AbstractBasicPromises.prototype);
/**
* @param {string} sFullNameHash
* @return {boolean}
*/
PromisesUserPopulator.prototype.isFolderExpanded = function (sFullNameHash)
{
var aExpandedList = Local.get(Enums.ClientSideKeyName.ExpandedFolders);
return Utils.isArray(aExpandedList) && -1 !== _.indexOf(aExpandedList, sFullNameHash);
};
/**
* @param {string} sFolderFullNameRaw
* @return {string}
*/
PromisesUserPopulator.prototype.normalizeFolder = function (sFolderFullNameRaw)
{
return ('' === sFolderFullNameRaw || Consts.UNUSED_OPTION_VALUE === sFolderFullNameRaw ||
null !== Cache.getFolderFromCacheList(sFolderFullNameRaw)) ? sFolderFullNameRaw : '';
};
/**
* @param {string} sNamespace
* @param {Array} aFolders
* @return {Array}
*/
PromisesUserPopulator.prototype.folderResponseParseRec = function (sNamespace, aFolders)
{
var
self = this,
iIndex = 0,
iLen = 0,
oFolder = null,
oCacheFolder = null,
sFolderFullNameRaw = '',
aSubFolders = [],
aList = []
;
for (iIndex = 0, iLen = aFolders.length; iIndex < iLen; iIndex++)
{ {
oFolder = aFolders[iIndex]; sFolderFullNameRaw = oFolder.FullNameRaw;
if (oFolder)
oCacheFolder = Cache.getFolderFromCacheList(sFolderFullNameRaw);
if (!oCacheFolder)
{ {
sFolderFullNameRaw = oFolder.FullNameRaw; oCacheFolder = FolderModel.newInstanceFromJson(oFolder);
oCacheFolder = Cache.getFolderFromCacheList(sFolderFullNameRaw);
if (!oCacheFolder)
{
oCacheFolder = FolderModel.newInstanceFromJson(oFolder);
if (oCacheFolder)
{
Cache.setFolderToCacheList(sFolderFullNameRaw, oCacheFolder);
Cache.setFolderFullNameRaw(oCacheFolder.fullNameHash, sFolderFullNameRaw, oCacheFolder);
}
}
if (oCacheFolder) if (oCacheFolder)
{ {
if (!FolderStore.displaySpecSetting()) Cache.setFolderToCacheList(sFolderFullNameRaw, oCacheFolder);
{ Cache.setFolderFullNameRaw(oCacheFolder.fullNameHash, sFolderFullNameRaw, oCacheFolder);
oCacheFolder.checkable(true);
}
else
{
oCacheFolder.checkable(!!oFolder.Checkable);
}
oCacheFolder.collapsed(!self.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);
} }
} }
if (oCacheFolder)
{
if (!FolderStore.displaySpecSetting())
{
oCacheFolder.checkable(true);
}
else
{
oCacheFolder.checkable(!!oFolder.Checkable);
}
oCacheFolder.collapsed(!self.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; return aList;
}; };
PromisesUserPopulator.prototype.foldersList = function (oData) PromisesUserPopulator.prototype.foldersList = function(oData)
{
if (oData && 'Collection/FolderCollection' === oData['@Object'] &&
oData['@Collection'] && Utils.isArray(oData['@Collection']))
{ {
if (oData && 'Collection/FolderCollection' === oData['@Object'] && var
oData['@Collection'] && Utils.isArray(oData['@Collection'])) iLimit = Utils.pInt(Settings.appSettingsGet('folderSpecLimit')),
{ iC = Utils.pInt(oData.CountRec);
var
iLimit = Utils.pInt(Settings.appSettingsGet('folderSpecLimit')),
iC = Utils.pInt(oData.CountRec)
;
iLimit = 100 < iLimit ? 100 : (10 > iLimit ? 10 : iLimit); iLimit = 100 < iLimit ? 100 : (10 > iLimit ? 10 : iLimit);
FolderStore.displaySpecSetting(0 >= iC || iLimit < iC); FolderStore.displaySpecSetting(0 >= iC || iLimit < iC);
FolderStore.folderList(this.folderResponseParseRec( FolderStore.folderList(this.folderResponseParseRec(
Utils.isUnd(oData.Namespace) ? '' : oData.Namespace, oData['@Collection'])); Utils.isUnd(oData.Namespace) ? '' : oData.Namespace, oData['@Collection']));
} }
}; };
PromisesUserPopulator.prototype.foldersAdditionalParameters = function (oData) PromisesUserPopulator.prototype.foldersAdditionalParameters = function(oData)
{
if (oData && oData && 'Collection/FolderCollection' === oData['@Object'] &&
oData['@Collection'] && Utils.isArray(oData['@Collection']))
{ {
if (oData && oData && 'Collection/FolderCollection' === oData['@Object'] && if (!Utils.isUnd(oData.Namespace))
oData['@Collection'] && Utils.isArray(oData['@Collection']))
{ {
if (!Utils.isUnd(oData.Namespace)) FolderStore.namespace = oData.Namespace;
{
FolderStore.namespace = oData.Namespace;
}
AppStore.threadsAllowed(!!Settings.appSettingsGet('useImapThread') && oData.IsThreadsSupported && true);
FolderStore.folderList.optimized(!!oData.Optimized);
var bUpdate = false;
if (oData.SystemFolders && '' === '' +
Settings.settingsGet('SentFolder') +
Settings.settingsGet('DraftFolder') +
Settings.settingsGet('SpamFolder') +
Settings.settingsGet('TrashFolder') +
Settings.settingsGet('ArchiveFolder') +
Settings.settingsGet('NullFolder'))
{
Settings.settingsSet('SentFolder', oData.SystemFolders[Enums.ServerFolderType.SENT] || null);
Settings.settingsSet('DraftFolder', oData.SystemFolders[Enums.ServerFolderType.DRAFTS] || null);
Settings.settingsSet('SpamFolder', oData.SystemFolders[Enums.ServerFolderType.JUNK] || null);
Settings.settingsSet('TrashFolder', oData.SystemFolders[Enums.ServerFolderType.TRASH] || null);
Settings.settingsSet('ArchiveFolder', oData.SystemFolders[Enums.ServerFolderType.ALL] || null);
bUpdate = true;
}
FolderStore.sentFolder(this.normalizeFolder(Settings.settingsGet('SentFolder')));
FolderStore.draftFolder(this.normalizeFolder(Settings.settingsGet('DraftFolder')));
FolderStore.spamFolder(this.normalizeFolder(Settings.settingsGet('SpamFolder')));
FolderStore.trashFolder(this.normalizeFolder(Settings.settingsGet('TrashFolder')));
FolderStore.archiveFolder(this.normalizeFolder(Settings.settingsGet('ArchiveFolder')));
if (bUpdate)
{
require('Remote/User/Ajax').saveSystemFolders(Utils.noop, {
SentFolder: FolderStore.sentFolder(),
DraftFolder: FolderStore.draftFolder(),
SpamFolder: FolderStore.spamFolder(),
TrashFolder: FolderStore.trashFolder(),
ArchiveFolder: FolderStore.archiveFolder(),
NullFolder: 'NullFolder'
});
}
Local.set(Enums.ClientSideKeyName.FoldersLashHash, oData.FoldersHash);
} }
};
module.exports = new PromisesUserPopulator(); AppStore.threadsAllowed(!!Settings.appSettingsGet('useImapThread') && oData.IsThreadsSupported && true);
}()); FolderStore.folderList.optimized(!!oData.Optimized);
var bUpdate = false;
if (oData.SystemFolders && '' === '' +
Settings.settingsGet('SentFolder') +
Settings.settingsGet('DraftFolder') +
Settings.settingsGet('SpamFolder') +
Settings.settingsGet('TrashFolder') +
Settings.settingsGet('ArchiveFolder') +
Settings.settingsGet('NullFolder'))
{
Settings.settingsSet('SentFolder', oData.SystemFolders[Enums.ServerFolderType.SENT] || null);
Settings.settingsSet('DraftFolder', oData.SystemFolders[Enums.ServerFolderType.DRAFTS] || null);
Settings.settingsSet('SpamFolder', oData.SystemFolders[Enums.ServerFolderType.JUNK] || null);
Settings.settingsSet('TrashFolder', oData.SystemFolders[Enums.ServerFolderType.TRASH] || null);
Settings.settingsSet('ArchiveFolder', oData.SystemFolders[Enums.ServerFolderType.ALL] || null);
bUpdate = true;
}
FolderStore.sentFolder(this.normalizeFolder(Settings.settingsGet('SentFolder')));
FolderStore.draftFolder(this.normalizeFolder(Settings.settingsGet('DraftFolder')));
FolderStore.spamFolder(this.normalizeFolder(Settings.settingsGet('SpamFolder')));
FolderStore.trashFolder(this.normalizeFolder(Settings.settingsGet('TrashFolder')));
FolderStore.archiveFolder(this.normalizeFolder(Settings.settingsGet('ArchiveFolder')));
if (bUpdate)
{
require('Remote/User/Ajax').saveSystemFolders(Utils.noop, {
SentFolder: FolderStore.sentFolder(),
DraftFolder: FolderStore.draftFolder(),
SpamFolder: FolderStore.spamFolder(),
TrashFolder: FolderStore.trashFolder(),
ArchiveFolder: FolderStore.archiveFolder(),
NullFolder: 'NullFolder'
});
}
Local.set(Enums.ClientSideKeyName.FoldersLashHash, oData.FoldersHash);
}
};
module.exports = new PromisesUserPopulator();

View file

@ -1,311 +1,302 @@
(function () { var
window = require('window'),
_ = require('_'),
$ = require('$'),
'use strict'; Consts = require('Common/Consts'),
Enums = require('Common/Enums'),
Globals = require('Common/Globals'),
Utils = require('Common/Utils'),
Plugins = require('Common/Plugins'),
Links = require('Common/Links'),
Settings = require('Storage/Settings');
/**
* @constructor
*/
function AbstractAjaxRemote()
{
this.oRequests = {};
}
AbstractAjaxRemote.prototype.oRequests = {};
/**
* @param {?Function} fCallback
* @param {string} sRequestAction
* @param {string} sType
* @param {?AjaxJsonDefaultResponse} oData
* @param {boolean} bCached
* @param {*=} oRequestParameters
*/
AbstractAjaxRemote.prototype.defaultResponse = function(fCallback, sRequestAction, sType, oData, bCached, oRequestParameters)
{
var var
window = require('window'), fCall = function() {
_ = require('_'), if (Enums.StorageResultType.Success !== sType && Globals.data.bUnload)
$ = require('$'), {
sType = Enums.StorageResultType.Unload;
}
Consts = require('Common/Consts'), if (Enums.StorageResultType.Success === sType && oData && !oData.Result)
Enums = require('Common/Enums'), {
Globals = require('Common/Globals'), if (oData && -1 < Utils.inArray(oData.ErrorCode, [
Utils = require('Common/Utils'), Enums.Notification.AuthError, Enums.Notification.AccessError,
Plugins = require('Common/Plugins'), Enums.Notification.ConnectionError, Enums.Notification.DomainNotAllowed, Enums.Notification.AccountNotAllowed,
Links = require('Common/Links'), Enums.Notification.MailServerError, Enums.Notification.UnknownNotification, Enums.Notification.UnknownError
]))
Settings = require('Storage/Settings')
;
/**
* @constructor
*/
function AbstractAjaxRemote()
{
this.oRequests = {};
}
AbstractAjaxRemote.prototype.oRequests = {};
/**
* @param {?Function} fCallback
* @param {string} sRequestAction
* @param {string} sType
* @param {?AjaxJsonDefaultResponse} oData
* @param {boolean} bCached
* @param {*=} oRequestParameters
*/
AbstractAjaxRemote.prototype.defaultResponse = function (fCallback, sRequestAction, sType, oData, bCached, oRequestParameters)
{
var
fCall = function () {
if (Enums.StorageResultType.Success !== sType && Globals.data.bUnload)
{ {
sType = Enums.StorageResultType.Unload; Globals.data.iAjaxErrorCount += 1;
} }
if (Enums.StorageResultType.Success === sType && oData && !oData.Result) if (oData && Enums.Notification.InvalidToken === oData.ErrorCode)
{ {
if (oData && -1 < Utils.inArray(oData.ErrorCode, [ Globals.data.iTokenErrorCount += 1;
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.data.iAjaxErrorCount++;
}
if (oData && Enums.Notification.InvalidToken === oData.ErrorCode) if (Consts.TOKEN_ERROR_LIMIT < Globals.data.iTokenErrorCount)
{
if (Globals.data.__APP__ && Globals.data.__APP__.loginAndLogoutReload)
{ {
Globals.data.iTokenErrorCount++; Globals.data.__APP__.loginAndLogoutReload(false, true);
} }
}
if (Consts.TOKEN_ERROR_LIMIT < Globals.data.iTokenErrorCount) if (oData.ClearAuth || oData.Logout || Consts.AJAX_ERROR_LIMIT < Globals.data.iAjaxErrorCount)
{
if (Globals.data.__APP__ && Globals.data.__APP__.clearClientSideToken)
{ {
if (Globals.data.__APP__ && Globals.data.__APP__.loginAndLogoutReload) Globals.data.__APP__.clearClientSideToken();
if (!oData.ClearAuth && Globals.data.__APP__.loginAndLogoutReload)
{ {
Globals.data.__APP__.loginAndLogoutReload(false, true); Globals.data.__APP__.loginAndLogoutReload(false, true);
} }
} }
if (oData.ClearAuth || oData.Logout || Consts.AJAX_ERROR_LIMIT < Globals.data.iAjaxErrorCount)
{
if (Globals.data.__APP__ && Globals.data.__APP__.clearClientSideToken)
{
Globals.data.__APP__.clearClientSideToken();
if (!oData.ClearAuth && Globals.data.__APP__.loginAndLogoutReload)
{
Globals.data.__APP__.loginAndLogoutReload(false, true);
}
}
}
}
else if (Enums.StorageResultType.Success === sType && oData && oData.Result)
{
Globals.data.iAjaxErrorCount = 0;
Globals.data.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
);
} }
} }
; else if (Enums.StorageResultType.Success === sType && oData && oData.Result)
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}
*/
AbstractAjaxRemote.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 = Settings.appSettingsGet('token');
}
oDefAjax = $.ajax({
type: bPost ? 'POST' : 'GET',
url: Links.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; Globals.data.iAjaxErrorCount = 0;
Globals.data.iTokenErrorCount = 0;
} }
if (sAction && self.oRequests[sAction]) if (fCallback)
{ {
if (self.oRequests[sAction].__aborted) Plugins.runHook('ajax-default-response', [sRequestAction, Enums.StorageResultType.Success === sType ? oData : null, sType, bCached, oRequestParameters]);
{
sType = 'abort';
}
self.oRequests[sAction] = null; fCallback(
sType,
Enums.StorageResultType.Success === sType ? oData : null,
bCached,
sRequestAction,
oRequestParameters
);
} }
};
self.defaultResponse(fResultCallback, sAction, sType, oData, bCached, oParameters); 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 = []
* @returns {jQuery.jqXHR}
*/
AbstractAjaxRemote.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 (sAction && 0 < aAbortActions.length && -1 < Utils.inArray(sAction, aAbortActions)) if (bPost)
{
oParameters.XToken = Settings.appSettingsGet('token');
}
oDefAjax = $.ajax({
type: bPost ? 'POST' : 'GET',
url: Links.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 (this.oRequests[sAction]) bCached = Utils.pInt(oData.Time) > (new window.Date()).getTime() - iStart;
{
this.oRequests[sAction].__aborted = true;
if (this.oRequests[sAction].abort)
{
this.oRequests[sAction].abort();
}
this.oRequests[sAction] = null;
}
this.oRequests[sAction] = oDefAjax;
} }
return oDefAjax; if (sAction && self.oRequests[sAction])
}; {
if (self.oRequests[sAction].__aborted)
{
sType = 'abort';
}
/** self.oRequests[sAction] = null;
* @param {?Function} fCallback }
* @param {string} sAction
* @param {Object=} oParameters self.defaultResponse(fResultCallback, sAction, sType, oData, bCached, oParameters);
* @param {?number=} iTimeout });
* @param {string=} sGetAdd = ''
* @param {Array=} aAbortActions = [] if (sAction && 0 < aAbortActions.length && -1 < Utils.inArray(sAction, aAbortActions))
*/
AbstractAjaxRemote.prototype.defaultRequest = function (fCallback, sAction, oParameters, iTimeout, sGetAdd, aAbortActions)
{ {
oParameters = oParameters || {}; if (this.oRequests[sAction])
oParameters.Action = sAction; {
this.oRequests[sAction].__aborted = true;
if (this.oRequests[sAction].abort)
{
this.oRequests[sAction].abort();
}
this.oRequests[sAction] = null;
}
sGetAdd = Utils.pString(sGetAdd); this.oRequests[sAction] = oDefAjax;
}
Plugins.runHook('ajax-default-request', [sAction, oParameters, sGetAdd]); return oDefAjax;
};
return this.ajaxRequest(fCallback, oParameters, /**
Utils.isUnd(iTimeout) ? Consts.DEFAULT_AJAX_TIMEOUT : Utils.pInt(iTimeout), sGetAdd, aAbortActions); * @param {?Function} fCallback
}; * @param {string} sAction
* @param {Object=} oParameters
* @param {?number=} iTimeout
* @param {string=} sGetAdd = ''
* @param {Array=} aAbortActions = []
*/
AbstractAjaxRemote.prototype.defaultRequest = function(fCallback, sAction, oParameters, iTimeout, sGetAdd, aAbortActions)
{
oParameters = oParameters || {};
oParameters.Action = sAction;
/** sGetAdd = Utils.pString(sGetAdd);
* @param {?Function} fCallback
*/
AbstractAjaxRemote.prototype.noop = function (fCallback)
{
this.defaultRequest(fCallback, 'Noop');
};
/** Plugins.runHook('ajax-default-request', [sAction, oParameters, sGetAdd]);
* @param {?Function} fCallback
* @param {string} sMessage
* @param {string} sFileName
* @param {number} iLineNo
* @param {string} sLocation
* @param {string} sHtmlCapa
* @param {number} iTime
*/
AbstractAjaxRemote.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
});
};
/** return this.ajaxRequest(fCallback, oParameters,
* @param {?Function} fCallback Utils.isUnd(iTimeout) ? Consts.DEFAULT_AJAX_TIMEOUT : Utils.pInt(iTimeout), sGetAdd, aAbortActions);
* @param {string} sType };
* @param {Array=} mData = null
* @param {boolean=} bIsError = false
*/
AbstractAjaxRemote.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 * @param {?Function} fCallback
*/ */
AbstractAjaxRemote.prototype.getPublicKey = function (fCallback) AbstractAjaxRemote.prototype.noop = function(fCallback)
{ {
this.defaultRequest(fCallback, 'GetPublicKey'); this.defaultRequest(fCallback, 'Noop');
}; };
/** /**
* @param {?Function} fCallback * @param {?Function} fCallback
* @param {string} sVersion * @param {string} sMessage
*/ * @param {string} sFileName
AbstractAjaxRemote.prototype.jsVersion = function (fCallback, sVersion) * @param {number} iLineNo
{ * @param {string} sLocation
this.defaultRequest(fCallback, 'Version', { * @param {string} sHtmlCapa
'Version': sVersion * @param {number} iTime
}); */
}; AbstractAjaxRemote.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
});
};
module.exports = AbstractAjaxRemote; /**
* @param {?Function} fCallback
* @param {string} sType
* @param {Array=} mData = null
* @param {boolean=} bIsError = false
*/
AbstractAjaxRemote.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
*/
AbstractAjaxRemote.prototype.getPublicKey = function(fCallback)
{
this.defaultRequest(fCallback, 'GetPublicKey');
};
/**
* @param {?Function} fCallback
* @param {string} sVersion
*/
AbstractAjaxRemote.prototype.jsVersion = function(fCallback, sVersion)
{
this.defaultRequest(fCallback, 'Version', {
'Version': sVersion
});
};
module.exports = AbstractAjaxRemote;

View file

@ -1,308 +1,301 @@
(function () { var
_ = require('_'),
'use strict'; Utils = require('Common/Utils'),
var AbstractAjaxRemote = require('Remote/AbstractAjax');
_ = require('_'),
Utils = require('Common/Utils'), /**
* @constructor
* @extends AbstractAjaxRemote
*/
function RemoteAdminStorage()
{
AbstractAjaxRemote.call(this);
AbstractAjaxRemote = require('Remote/AbstractAjax') this.oRequests = {};
; }
/** _.extend(RemoteAdminStorage.prototype, AbstractAjaxRemote.prototype);
* @constructor
* @extends AbstractAjaxRemote
*/
function RemoteAdminStorage()
{
AbstractAjaxRemote.call(this);
this.oRequests = {}; /**
} * @param {?Function} fCallback
* @param {string} sLogin
* @param {string} sPassword
*/
RemoteAdminStorage.prototype.adminLogin = function(fCallback, sLogin, sPassword)
{
this.defaultRequest(fCallback, 'AdminLogin', {
'Login': sLogin,
'Password': sPassword
});
};
_.extend(RemoteAdminStorage.prototype, AbstractAjaxRemote.prototype); /**
* @param {?Function} fCallback
*/
RemoteAdminStorage.prototype.adminLogout = function(fCallback)
{
this.defaultRequest(fCallback, 'AdminLogout');
};
/** /**
* @param {?Function} fCallback * @param {?Function} fCallback
* @param {string} sLogin * @param {?} oData
* @param {string} sPassword */
*/ RemoteAdminStorage.prototype.saveAdminConfig = function(fCallback, oData)
RemoteAdminStorage.prototype.adminLogin = function (fCallback, sLogin, sPassword) {
{ this.defaultRequest(fCallback, 'AdminSettingsUpdate', oData);
this.defaultRequest(fCallback, 'AdminLogin', { };
'Login': sLogin,
'Password': sPassword
});
};
/** /**
* @param {?Function} fCallback * @param {?Function} fCallback
*/ * @param {boolean=} bIncludeAliases = true
RemoteAdminStorage.prototype.adminLogout = function (fCallback) */
{ RemoteAdminStorage.prototype.domainList = function(fCallback, bIncludeAliases)
this.defaultRequest(fCallback, 'AdminLogout'); {
}; bIncludeAliases = Utils.isUnd(bIncludeAliases) ? true : bIncludeAliases;
this.defaultRequest(fCallback, 'AdminDomainList', {
'IncludeAliases': bIncludeAliases ? '1' : '0'
});
};
/** /**
* @param {?Function} fCallback * @param {?Function} fCallback
* @param {?} oData */
*/ RemoteAdminStorage.prototype.pluginList = function(fCallback)
RemoteAdminStorage.prototype.saveAdminConfig = function (fCallback, oData) {
{ this.defaultRequest(fCallback, 'AdminPluginList');
this.defaultRequest(fCallback, 'AdminSettingsUpdate', oData); };
};
/** /**
* @param {?Function} fCallback * @param {?Function} fCallback
* @param {boolean=} bIncludeAliases = true */
*/ RemoteAdminStorage.prototype.packagesList = function(fCallback)
RemoteAdminStorage.prototype.domainList = function (fCallback, bIncludeAliases) {
{ this.defaultRequest(fCallback, 'AdminPackagesList');
bIncludeAliases = Utils.isUnd(bIncludeAliases) ? true : bIncludeAliases; };
this.defaultRequest(fCallback, 'AdminDomainList', {
'IncludeAliases': bIncludeAliases ? '1' : '0'
});
};
/** /**
* @param {?Function} fCallback * @param {?Function} fCallback
*/ */
RemoteAdminStorage.prototype.pluginList = function (fCallback) RemoteAdminStorage.prototype.coreData = function(fCallback)
{ {
this.defaultRequest(fCallback, 'AdminPluginList'); this.defaultRequest(fCallback, 'AdminCoreData');
}; };
/** /**
* @param {?Function} fCallback * @param {?Function} fCallback
*/ */
RemoteAdminStorage.prototype.packagesList = function (fCallback) RemoteAdminStorage.prototype.updateCoreData = function(fCallback)
{ {
this.defaultRequest(fCallback, 'AdminPackagesList'); this.defaultRequest(fCallback, 'AdminUpdateCoreData', {}, 90000);
}; };
/** /**
* @param {?Function} fCallback * @param {?Function} fCallback
*/ * @param {Object} oPackage
RemoteAdminStorage.prototype.coreData = function (fCallback) */
{ RemoteAdminStorage.prototype.packageInstall = function(fCallback, oPackage)
this.defaultRequest(fCallback, 'AdminCoreData'); {
}; this.defaultRequest(fCallback, 'AdminPackageInstall', {
'Id': oPackage.id,
'Type': oPackage.type,
'File': oPackage.file
}, 60000);
};
/** /**
* @param {?Function} fCallback * @param {?Function} fCallback
*/ * @param {Object} oPackage
RemoteAdminStorage.prototype.updateCoreData = function (fCallback) */
{ RemoteAdminStorage.prototype.packageDelete = function(fCallback, oPackage)
this.defaultRequest(fCallback, 'AdminUpdateCoreData', {}, 90000); {
}; this.defaultRequest(fCallback, 'AdminPackageDelete', {
'Id': oPackage.id
});
};
/** /**
* @param {?Function} fCallback * @param {?Function} fCallback
* @param {Object} oPackage * @param {string} sName
*/ */
RemoteAdminStorage.prototype.packageInstall = function (fCallback, oPackage) RemoteAdminStorage.prototype.domain = function(fCallback, sName)
{ {
this.defaultRequest(fCallback, 'AdminPackageInstall', { this.defaultRequest(fCallback, 'AdminDomainLoad', {
'Id': oPackage.id, 'Name': sName
'Type': oPackage.type, });
'File': oPackage.file };
}, 60000);
};
/** /**
* @param {?Function} fCallback * @param {?Function} fCallback
* @param {Object} oPackage * @param {string} sName
*/ */
RemoteAdminStorage.prototype.packageDelete = function (fCallback, oPackage) RemoteAdminStorage.prototype.plugin = function(fCallback, sName)
{ {
this.defaultRequest(fCallback, 'AdminPackageDelete', { this.defaultRequest(fCallback, 'AdminPluginLoad', {
'Id': oPackage.id 'Name': sName
}); });
}; };
/** /**
* @param {?Function} fCallback * @param {?Function} fCallback
* @param {string} sName * @param {string} sName
*/ */
RemoteAdminStorage.prototype.domain = function (fCallback, sName) RemoteAdminStorage.prototype.domainDelete = function(fCallback, sName)
{ {
this.defaultRequest(fCallback, 'AdminDomainLoad', { this.defaultRequest(fCallback, 'AdminDomainDelete', {
'Name': sName 'Name': sName
}); });
}; };
/** /**
* @param {?Function} fCallback * @param {?Function} fCallback
* @param {string} sName * @param {string} sName
*/ * @param {boolean} bDisabled
RemoteAdminStorage.prototype.plugin = function (fCallback, sName) */
{ RemoteAdminStorage.prototype.domainDisable = function(fCallback, sName, bDisabled)
this.defaultRequest(fCallback, 'AdminPluginLoad', { {
'Name': sName return this.defaultRequest(fCallback, 'AdminDomainDisable', {
}); Name: sName,
}; Disabled: bDisabled ? '1' : '0'
});
};
/** /**
* @param {?Function} fCallback * @param {?Function} fCallback
* @param {string} sName * @param {Object} oConfig
*/ */
RemoteAdminStorage.prototype.domainDelete = function (fCallback, sName) RemoteAdminStorage.prototype.pluginSettingsUpdate = function(fCallback, oConfig)
{ {
this.defaultRequest(fCallback, 'AdminDomainDelete', { return this.defaultRequest(fCallback, 'AdminPluginSettingsUpdate', oConfig);
'Name': sName };
});
};
/** /**
* @param {?Function} fCallback * @param {?Function} fCallback
* @param {string} sName * @param {boolean} bForce
* @param {boolean} bDisabled */
*/ RemoteAdminStorage.prototype.licensing = function(fCallback, bForce)
RemoteAdminStorage.prototype.domainDisable = function (fCallback, sName, bDisabled) {
{ return this.defaultRequest(fCallback, 'AdminLicensing', {
return this.defaultRequest(fCallback, 'AdminDomainDisable', { Force: bForce ? '1' : '0'
Name: sName, });
Disabled: bDisabled ? '1' : '0' };
});
};
/** /**
* @param {?Function} fCallback * @param {?Function} fCallback
* @param {Object} oConfig * @param {string} sDomain
*/ * @param {string} sKey
RemoteAdminStorage.prototype.pluginSettingsUpdate = function (fCallback, oConfig) */
{ RemoteAdminStorage.prototype.licensingActivate = function(fCallback, sDomain, sKey)
return this.defaultRequest(fCallback, 'AdminPluginSettingsUpdate', oConfig); {
}; return this.defaultRequest(fCallback, 'AdminLicensingActivate', {
Domain: sDomain,
Key: sKey
});
};
/** /**
* @param {?Function} fCallback * @param {?Function} fCallback
* @param {boolean} bForce * @param {string} sName
*/ * @param {boolean} bDisabled
RemoteAdminStorage.prototype.licensing = function (fCallback, bForce) */
{ RemoteAdminStorage.prototype.pluginDisable = function(fCallback, sName, bDisabled)
return this.defaultRequest(fCallback, 'AdminLicensing', { {
Force: bForce ? '1' : '0' return this.defaultRequest(fCallback, 'AdminPluginDisable', {
}); Name: sName,
}; Disabled: bDisabled ? '1' : '0'
});
};
/** RemoteAdminStorage.prototype.createDomainAlias = function(fCallback, sName, sAlias)
* @param {?Function} fCallback {
* @param {string} sDomain this.defaultRequest(fCallback, 'AdminDomainAliasSave', {
* @param {string} sKey Name: sName,
*/ Alias: sAlias
RemoteAdminStorage.prototype.licensingActivate = function (fCallback, sDomain, sKey) });
{ };
return this.defaultRequest(fCallback, 'AdminLicensingActivate', {
Domain: sDomain,
Key: sKey
});
};
/** RemoteAdminStorage.prototype.createOrUpdateDomain = function(fCallback,
* @param {?Function} fCallback bCreate, sName,
* @param {string} sName sIncHost, iIncPort, sIncSecure, bIncShortLogin,
* @param {boolean} bDisabled bUseSieve, sSieveAllowRaw, sSieveHost, iSievePort, sSieveSecure,
*/ sOutHost, iOutPort, sOutSecure, bOutShortLogin, bOutAuth, bOutPhpMail,
RemoteAdminStorage.prototype.pluginDisable = function (fCallback, sName, bDisabled) sWhiteList)
{ {
return this.defaultRequest(fCallback, 'AdminPluginDisable', { this.defaultRequest(fCallback, 'AdminDomainSave', {
Name: sName, 'Create': bCreate ? '1' : '0',
Disabled: bDisabled ? '1' : '0' 'Name': sName,
});
};
RemoteAdminStorage.prototype.createDomainAlias = function (fCallback, sName, sAlias) 'IncHost': sIncHost,
{ 'IncPort': iIncPort,
this.defaultRequest(fCallback, 'AdminDomainAliasSave', { 'IncSecure': sIncSecure,
Name: sName, 'IncShortLogin': bIncShortLogin ? '1' : '0',
Alias: sAlias
});
};
RemoteAdminStorage.prototype.createOrUpdateDomain = function (fCallback, 'UseSieve': bUseSieve ? '1' : '0',
bCreate, sName, 'SieveAllowRaw': sSieveAllowRaw ? '1' : '0',
sIncHost, iIncPort, sIncSecure, bIncShortLogin, 'SieveHost': sSieveHost,
bUseSieve, sSieveAllowRaw, sSieveHost, iSievePort, sSieveSecure, 'SievePort': iSievePort,
sOutHost, iOutPort, sOutSecure, bOutShortLogin, bOutAuth, bOutPhpMail, 'SieveSecure': sSieveSecure,
sWhiteList)
{
this.defaultRequest(fCallback, 'AdminDomainSave', {
'Create': bCreate ? '1' : '0',
'Name': sName,
'IncHost': sIncHost, 'OutHost': sOutHost,
'IncPort': iIncPort, 'OutPort': iOutPort,
'IncSecure': sIncSecure, 'OutSecure': sOutSecure,
'IncShortLogin': bIncShortLogin ? '1' : '0', 'OutShortLogin': bOutShortLogin ? '1' : '0',
'OutAuth': bOutAuth ? '1' : '0',
'OutUsePhpMail': bOutPhpMail ? '1' : '0',
'UseSieve': bUseSieve ? '1' : '0', 'WhiteList': sWhiteList
'SieveAllowRaw': sSieveAllowRaw ? '1' : '0', });
'SieveHost': sSieveHost, };
'SievePort': iSievePort,
'SieveSecure': sSieveSecure,
'OutHost': sOutHost, RemoteAdminStorage.prototype.testConnectionForDomain = function(fCallback, sName,
'OutPort': iOutPort, sIncHost, iIncPort, sIncSecure,
'OutSecure': sOutSecure, bUseSieve, sSieveHost, iSievePort, sSieveSecure,
'OutShortLogin': bOutShortLogin ? '1' : '0', sOutHost, iOutPort, sOutSecure, bOutAuth, bOutPhpMail)
'OutAuth': bOutAuth ? '1' : '0', {
'OutUsePhpMail': bOutPhpMail ? '1' : '0', this.defaultRequest(fCallback, 'AdminDomainTest', {
'Name': sName,
'IncHost': sIncHost,
'IncPort': iIncPort,
'IncSecure': sIncSecure,
'UseSieve': bUseSieve ? '1' : '0',
'SieveHost': sSieveHost,
'SievePort': iSievePort,
'SieveSecure': sSieveSecure,
'OutHost': sOutHost,
'OutPort': iOutPort,
'OutSecure': sOutSecure,
'OutAuth': bOutAuth ? '1' : '0',
'OutUsePhpMail': bOutPhpMail ? '1' : '0'
});
};
'WhiteList': sWhiteList /**
}); * @param {?Function} fCallback
}; * @param {?} oData
*/
RemoteAdminStorage.prototype.testContacts = function(fCallback, oData)
{
this.defaultRequest(fCallback, 'AdminContactsTest', oData);
};
RemoteAdminStorage.prototype.testConnectionForDomain = function (fCallback, sName, /**
sIncHost, iIncPort, sIncSecure, * @param {?Function} fCallback
bUseSieve, sSieveHost, iSievePort, sSieveSecure, * @param {?} oData
sOutHost, iOutPort, sOutSecure, bOutAuth, bOutPhpMail) */
{ RemoteAdminStorage.prototype.saveNewAdminPassword = function(fCallback, oData)
this.defaultRequest(fCallback, 'AdminDomainTest', { {
'Name': sName, this.defaultRequest(fCallback, 'AdminPasswordUpdate', oData);
'IncHost': sIncHost, };
'IncPort': iIncPort,
'IncSecure': sIncSecure,
'UseSieve': bUseSieve ? '1' : '0',
'SieveHost': sSieveHost,
'SievePort': iSievePort,
'SieveSecure': sSieveSecure,
'OutHost': sOutHost,
'OutPort': iOutPort,
'OutSecure': sOutSecure,
'OutAuth': bOutAuth ? '1' : '0',
'OutUsePhpMail': bOutPhpMail ? '1' : '0'
});
};
/** /**
* @param {?Function} fCallback * @param {?Function} fCallback
* @param {?} oData */
*/ RemoteAdminStorage.prototype.adminPing = function(fCallback)
RemoteAdminStorage.prototype.testContacts = function (fCallback, oData) {
{ this.defaultRequest(fCallback, 'AdminPing');
this.defaultRequest(fCallback, 'AdminContactsTest', oData); };
};
/** module.exports = new RemoteAdminStorage();
* @param {?Function} fCallback
* @param {?} oData
*/
RemoteAdminStorage.prototype.saveNewAdminPassword = function (fCallback, oData)
{
this.defaultRequest(fCallback, 'AdminPasswordUpdate', oData);
};
/**
* @param {?Function} fCallback
*/
RemoteAdminStorage.prototype.adminPing = function (fCallback)
{
this.defaultRequest(fCallback, 'AdminPing');
};
module.exports = new RemoteAdminStorage();
}());

File diff suppressed because it is too large Load diff

View file

@ -1,214 +1,209 @@
(function () { var
_ = require('_'),
$ = require('$'),
ko = require('ko'),
'use strict'; Globals = require('Common/Globals'),
Utils = require('Common/Utils'),
Links = require('Common/Links'),
var kn = require('Knoin/Knoin'),
_ = require('_'), AbstractScreen = require('Knoin/AbstractScreen');
$ = require('$'),
ko = require('ko'),
Globals = require('Common/Globals'), /**
Utils = require('Common/Utils'), * @constructor
Links = require('Common/Links'), * @param {Array} aViewModels
* @extends AbstractScreen
*/
function AbstractSettingsScreen(aViewModels)
{
AbstractScreen.call(this, 'settings', aViewModels);
kn = require('Knoin/Knoin'), this.menu = ko.observableArray([]);
AbstractScreen = require('Knoin/AbstractScreen')
;
/** this.oCurrentSubScreen = null;
* @constructor this.oViewModelPlace = null;
* @param {Array} aViewModels
* @extends AbstractScreen this.setupSettings();
*/ }
function AbstractSettingsScreen(aViewModels)
_.extend(AbstractSettingsScreen.prototype, AbstractScreen.prototype);
/**
* @param {Function=} fCallback
*/
AbstractSettingsScreen.prototype.setupSettings = function(fCallback)
{
if (fCallback)
{ {
AbstractScreen.call(this, 'settings', aViewModels); fCallback();
}
};
this.menu = ko.observableArray([]); AbstractSettingsScreen.prototype.onRoute = function(sSubName)
{
var
self = this,
oSettingsScreen = null,
RoutedSettingsViewModel = null,
oViewModelPlace = null,
oViewModelDom = null;
this.oCurrentSubScreen = null; RoutedSettingsViewModel = _.find(Globals.aViewModels.settings, function(SettingsViewModel) {
this.oViewModelPlace = null; return SettingsViewModel && SettingsViewModel.__rlSettingsData &&
sSubName === SettingsViewModel.__rlSettingsData.Route;
});
this.setupSettings(); if (RoutedSettingsViewModel)
{
if (_.find(Globals.aViewModels['settings-removed'], function(DisabledSettingsViewModel) {
return DisabledSettingsViewModel && DisabledSettingsViewModel === RoutedSettingsViewModel;
}))
{
RoutedSettingsViewModel = null;
}
if (RoutedSettingsViewModel && _.find(Globals.aViewModels['settings-disabled'], function(DisabledSettingsViewModel) {
return DisabledSettingsViewModel && DisabledSettingsViewModel === RoutedSettingsViewModel;
}))
{
RoutedSettingsViewModel = null;
}
} }
_.extend(AbstractSettingsScreen.prototype, AbstractScreen.prototype); if (RoutedSettingsViewModel)
/**
* @param {Function=} fCallback
*/
AbstractSettingsScreen.prototype.setupSettings = function (fCallback)
{ {
if (fCallback) if (RoutedSettingsViewModel.__builded && RoutedSettingsViewModel.__vm)
{ {
fCallback(); oSettingsScreen = RoutedSettingsViewModel.__vm;
}
};
AbstractSettingsScreen.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;
}))
{
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)
{
oSettingsScreen = new RoutedSettingsViewModel();
oViewModelDom = $('<div></div>').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], {
'translatorInit': 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)
{
Utils.delegateRun(self.oCurrentSubScreen, 'onBeforeShow');
self.oCurrentSubScreen.viewModelDom.show();
Utils.delegateRun(self.oCurrentSubScreen, 'onShow');
Utils.delegateRun(self.oCurrentSubScreen, 'onShowWithDelay', [], 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 else
{ {
kn.setHash(Links.settings(), false, true); oViewModelPlace = this.oViewModelPlace;
} if (oViewModelPlace && 1 === oViewModelPlace.length)
};
AbstractSettingsScreen.prototype.onHide = function ()
{
if (this.oCurrentSubScreen && this.oCurrentSubScreen.viewModelDom)
{
Utils.delegateRun(this.oCurrentSubScreen, 'onHide');
this.oCurrentSubScreen.viewModelDom.hide();
}
};
AbstractSettingsScreen.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({ oSettingsScreen = new RoutedSettingsViewModel();
route: SettingsViewModel.__rlSettingsData.Route,
label: SettingsViewModel.__rlSettingsData.Label, oViewModelDom = $('<div></div>').addClass('rl-settings-view-model').hide();
selected: ko.observable(false), oViewModelDom.appendTo(oViewModelPlace);
disabled: !!_.find(Globals.aViewModels['settings-disabled'], function (DisabledSettingsViewModel) {
return DisabledSettingsViewModel && DisabledSettingsViewModel === SettingsViewModel; oSettingsScreen.viewModelDom = oViewModelDom;
})
}); oSettingsScreen.__rlSettingsData = RoutedSettingsViewModel.__rlSettingsData;
RoutedSettingsViewModel.__dom = oViewModelDom;
RoutedSettingsViewModel.__builded = true;
RoutedSettingsViewModel.__vm = oSettingsScreen;
ko.applyBindingAccessorsToNode(oViewModelDom[0], {
translatorInit: true,
template: function() {
return {
name: RoutedSettingsViewModel.__rlSettingsData.Template
};
}
}, oSettingsScreen);
Utils.delegateRun(oSettingsScreen, 'onBuild', [oViewModelDom]);
} }
}, this); else
{
Utils.log('Cannot find sub settings view model position: SettingsSubScreen');
}
}
this.oViewModelPlace = $('#rl-content #rl-settings-subscreen'); if (oSettingsScreen)
}; {
_.defer(function() {
AbstractSettingsScreen.prototype.routes = function () // hide
{ if (self.oCurrentSubScreen)
var {
DefaultViewModel = _.find(Globals.aViewModels.settings, function (SettingsViewModel) { Utils.delegateRun(self.oCurrentSubScreen, 'onHide');
return SettingsViewModel && SettingsViewModel.__rlSettingsData && SettingsViewModel.__rlSettingsData.IsDefault; self.oCurrentSubScreen.viewModelDom.hide();
}),
sDefaultRoute = DefaultViewModel && DefaultViewModel.__rlSettingsData ?
DefaultViewModel.__rlSettingsData.Route : 'general',
oRules = {
subname: /^(.*)$/,
normalize_: function (oRequest, oVals) {
oVals.subname = Utils.isUnd(oVals.subname) ? sDefaultRoute : Utils.pString(oVals.subname);
return [oVals.subname];
} }
// --
self.oCurrentSubScreen = oSettingsScreen;
// show
if (self.oCurrentSubScreen)
{
Utils.delegateRun(self.oCurrentSubScreen, 'onBeforeShow');
self.oCurrentSubScreen.viewModelDom.show();
Utils.delegateRun(self.oCurrentSubScreen, 'onShow');
Utils.delegateRun(self.oCurrentSubScreen, 'onShowWithDelay', [], 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(Links.settings(), false, true);
}
};
AbstractSettingsScreen.prototype.onHide = function()
{
if (this.oCurrentSubScreen && this.oCurrentSubScreen.viewModelDom)
{
Utils.delegateRun(this.oCurrentSubScreen, 'onHide');
this.oCurrentSubScreen.viewModelDom.hide();
}
};
AbstractSettingsScreen.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');
};
AbstractSettingsScreen.prototype.routes = function()
{
var
DefaultViewModel = _.find(Globals.aViewModels.settings, function(SettingsViewModel) {
return SettingsViewModel && SettingsViewModel.__rlSettingsData && SettingsViewModel.__rlSettingsData.IsDefault;
}),
sDefaultRoute = DefaultViewModel && DefaultViewModel.__rlSettingsData ?
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 [ return [
['{subname}/', oRules], ['{subname}/', oRules],
['{subname}', oRules], ['{subname}', oRules],
['', oRules] ['', oRules]
]; ];
}; };
module.exports = AbstractSettingsScreen; module.exports = AbstractSettingsScreen;
}());

View file

@ -1,32 +1,25 @@
(function () { var
_ = require('_'),
'use strict'; AbstractScreen = require('Knoin/AbstractScreen');
var /**
_ = require('_'), * @constructor
* @extends AbstractScreen
*/
function LoginAdminScreen()
{
AbstractScreen.call(this, 'login', [
require('View/Admin/Login')
]);
}
AbstractScreen = require('Knoin/AbstractScreen') _.extend(LoginAdminScreen.prototype, AbstractScreen.prototype);
;
/** LoginAdminScreen.prototype.onShow = function()
* @constructor {
* @extends AbstractScreen require('App/Admin').default.setWindowTitle('');
*/ };
function LoginAdminScreen()
{
AbstractScreen.call(this, 'login', [
require('View/Admin/Login')
]);
}
_.extend(LoginAdminScreen.prototype, AbstractScreen.prototype); module.exports = LoginAdminScreen;
LoginAdminScreen.prototype.onShow = function ()
{
require('App/Admin').default.setWindowTitle('');
};
module.exports = LoginAdminScreen;
}());

View file

@ -1,96 +1,89 @@
/* global RL_COMMUNITY */ /* global RL_COMMUNITY */
(function () { var
_ = require('_'),
'use strict'; kn = require('Knoin/Knoin'),
var Plugins = require('Common/Plugins'),
_ = require('_'),
kn = require('Knoin/Knoin'), AbstractSettings = require('Screen/AbstractSettings');
Plugins = require('Common/Plugins'), /**
* @constructor
* @extends AbstractSettings
*/
function SettingsAdminScreen()
{
AbstractSettings.call(this, [
require('View/Admin/Settings/Menu'),
require('View/Admin/Settings/Pane')
]);
}
AbstractSettings = require('Screen/AbstractSettings') _.extend(SettingsAdminScreen.prototype, AbstractSettings.prototype);
;
/** /**
* @constructor * @param {Function=} fCallback
* @extends AbstractSettings */
*/ SettingsAdminScreen.prototype.setupSettings = function(fCallback)
function SettingsAdminScreen() {
kn.addSettingsViewModel(require('Settings/Admin/General'),
'AdminSettingsGeneral', 'TABS_LABELS/LABEL_GENERAL_NAME', 'general', true);
kn.addSettingsViewModel(require('Settings/Admin/Login'),
'AdminSettingsLogin', 'TABS_LABELS/LABEL_LOGIN_NAME', 'login');
if (RL_COMMUNITY)
{ {
AbstractSettings.call(this, [ kn.addSettingsViewModel(require('Settings/Admin/Branding'),
require('View/Admin/Settings/Menu'), 'AdminSettingsBranding', 'TABS_LABELS/LABEL_BRANDING_NAME', 'branding');
require('View/Admin/Settings/Pane') }
]); else
{
kn.addSettingsViewModel(require('Settings/Admin/Prem/Branding'),
'AdminSettingsBranding', 'TABS_LABELS/LABEL_BRANDING_NAME', 'branding');
} }
_.extend(SettingsAdminScreen.prototype, AbstractSettings.prototype); kn.addSettingsViewModel(require('Settings/Admin/Contacts'),
'AdminSettingsContacts', 'TABS_LABELS/LABEL_CONTACTS_NAME', 'contacts');
/** kn.addSettingsViewModel(require('Settings/Admin/Domains'),
* @param {Function=} fCallback 'AdminSettingsDomains', 'TABS_LABELS/LABEL_DOMAINS_NAME', 'domains');
*/
SettingsAdminScreen.prototype.setupSettings = function (fCallback) kn.addSettingsViewModel(require('Settings/Admin/Security'),
'AdminSettingsSecurity', 'TABS_LABELS/LABEL_SECURITY_NAME', 'security');
kn.addSettingsViewModel(require('Settings/Admin/Social'),
'AdminSettingsSocial', 'TABS_LABELS/LABEL_INTEGRATION_NAME', 'integrations');
kn.addSettingsViewModel(require('Settings/Admin/Plugins'),
'AdminSettingsPlugins', 'TABS_LABELS/LABEL_PLUGINS_NAME', 'plugins');
kn.addSettingsViewModel(require('Settings/Admin/Packages'),
'AdminSettingsPackages', 'TABS_LABELS/LABEL_PACKAGES_NAME', 'packages');
if (!RL_COMMUNITY)
{ {
kn.addSettingsViewModel(require('Settings/Admin/General'), kn.addSettingsViewModel(require('Settings/Admin/Prem/Licensing'),
'AdminSettingsGeneral', 'TABS_LABELS/LABEL_GENERAL_NAME', 'general', true); 'AdminSettingsLicensing', 'TABS_LABELS/LABEL_LICENSING_NAME', 'licensing');
}
kn.addSettingsViewModel(require('Settings/Admin/Login'), kn.addSettingsViewModel(require('Settings/Admin/About'),
'AdminSettingsLogin', 'TABS_LABELS/LABEL_LOGIN_NAME', 'login'); 'AdminSettingsAbout', 'TABS_LABELS/LABEL_ABOUT_NAME', 'about');
if (RL_COMMUNITY) Plugins.runSettingsViewModelHooks(true);
{
kn.addSettingsViewModel(require('Settings/Admin/Branding'),
'AdminSettingsBranding', 'TABS_LABELS/LABEL_BRANDING_NAME', 'branding');
}
else
{
kn.addSettingsViewModel(require('Settings/Admin/Prem/Branding'),
'AdminSettingsBranding', 'TABS_LABELS/LABEL_BRANDING_NAME', 'branding');
}
kn.addSettingsViewModel(require('Settings/Admin/Contacts'), if (fCallback)
'AdminSettingsContacts', 'TABS_LABELS/LABEL_CONTACTS_NAME', 'contacts');
kn.addSettingsViewModel(require('Settings/Admin/Domains'),
'AdminSettingsDomains', 'TABS_LABELS/LABEL_DOMAINS_NAME', 'domains');
kn.addSettingsViewModel(require('Settings/Admin/Security'),
'AdminSettingsSecurity', 'TABS_LABELS/LABEL_SECURITY_NAME', 'security');
kn.addSettingsViewModel(require('Settings/Admin/Social'),
'AdminSettingsSocial', 'TABS_LABELS/LABEL_INTEGRATION_NAME', 'integrations');
kn.addSettingsViewModel(require('Settings/Admin/Plugins'),
'AdminSettingsPlugins', 'TABS_LABELS/LABEL_PLUGINS_NAME', 'plugins');
kn.addSettingsViewModel(require('Settings/Admin/Packages'),
'AdminSettingsPackages', 'TABS_LABELS/LABEL_PACKAGES_NAME', 'packages');
if (!RL_COMMUNITY)
{
kn.addSettingsViewModel(require('Settings/Admin/Prem/Licensing'),
'AdminSettingsLicensing', 'TABS_LABELS/LABEL_LICENSING_NAME', 'licensing');
}
kn.addSettingsViewModel(require('Settings/Admin/About'),
'AdminSettingsAbout', 'TABS_LABELS/LABEL_ABOUT_NAME', 'about');
Plugins.runSettingsViewModelHooks(true);
if (fCallback)
{
fCallback();
}
};
SettingsAdminScreen.prototype.onShow = function ()
{ {
require('App/Admin').default.setWindowTitle(''); fCallback();
}; }
};
module.exports = SettingsAdminScreen; SettingsAdminScreen.prototype.onShow = function()
{
require('App/Admin').default.setWindowTitle('');
};
}()); module.exports = SettingsAdminScreen;

View file

@ -1,32 +1,25 @@
(function () { var
_ = require('_'),
'use strict'; AbstractScreen = require('Knoin/AbstractScreen');
var /**
_ = require('_'), * @constructor
* @extends AbstractScreen
*/
function AboutUserScreen()
{
AbstractScreen.call(this, 'about', [
require('View/User/About')
]);
}
AbstractScreen = require('Knoin/AbstractScreen') _.extend(AboutUserScreen.prototype, AbstractScreen.prototype);
;
/** AboutUserScreen.prototype.onShow = function()
* @constructor {
* @extends AbstractScreen require('App/User').default.setWindowTitle('RainLoop');
*/ };
function AboutUserScreen()
{
AbstractScreen.call(this, 'about', [
require('View/User/About')
]);
}
_.extend(AboutUserScreen.prototype, AbstractScreen.prototype); module.exports = AboutUserScreen;
AboutUserScreen.prototype.onShow = function ()
{
require('App/User').default.setWindowTitle('RainLoop');
};
module.exports = AboutUserScreen;
}());

View file

@ -1,32 +1,25 @@
(function () { var
_ = require('_'),
'use strict'; AbstractScreen = require('Knoin/AbstractScreen');
var /**
_ = require('_'), * @constructor
* @extends AbstractScreen
*/
function LoginUserScreen()
{
AbstractScreen.call(this, 'login', [
require('View/User/Login')
]);
}
AbstractScreen = require('Knoin/AbstractScreen') _.extend(LoginUserScreen.prototype, AbstractScreen.prototype);
;
/** LoginUserScreen.prototype.onShow = function()
* @constructor {
* @extends AbstractScreen require('App/User').default.setWindowTitle('');
*/ };
function LoginUserScreen()
{
AbstractScreen.call(this, 'login', [
require('View/User/Login')
]);
}
_.extend(LoginUserScreen.prototype, AbstractScreen.prototype); module.exports = LoginUserScreen;
LoginUserScreen.prototype.onShow = function ()
{
require('App/User').default.setWindowTitle('');
};
module.exports = LoginUserScreen;
}());

View file

@ -1,204 +1,194 @@
(function () { var
_ = require('_'),
'use strict'; Enums = require('Common/Enums'),
Globals = require('Common/Globals'),
Utils = require('Common/Utils'),
Events = require('Common/Events'),
Translator = require('Common/Translator'),
Cache = require('Common/Cache'),
AppStore = require('Stores/User/App'),
AccountStore = require('Stores/User/Account'),
SettingsStore = require('Stores/User/Settings'),
FolderStore = require('Stores/User/Folder'),
MessageStore = require('Stores/User/Message'),
Settings = require('Storage/Settings'),
AbstractScreen = require('Knoin/AbstractScreen');
/**
* @constructor
* @extends AbstractScreen
*/
function MailBoxUserScreen()
{
AbstractScreen.call(this, 'mailbox', [
require('View/User/MailBox/SystemDropDown'),
require('View/User/MailBox/FolderList'),
require('View/User/MailBox/MessageList'),
require('View/User/MailBox/MessageView')
]);
this.oLastRoute = {};
}
_.extend(MailBoxUserScreen.prototype, AbstractScreen.prototype);
/**
* @type {Object}
*/
MailBoxUserScreen.prototype.oLastRoute = {};
MailBoxUserScreen.prototype.updateWindowTitle = function()
{
var var
_ = require('_'), sEmail = AccountStore.email(),
nFoldersInboxUnreadCount = FolderStore.foldersInboxUnreadCount();
Enums = require('Common/Enums'), if (Settings.appSettingsGet('listPermanentFiltered'))
Globals = require('Common/Globals'),
Utils = require('Common/Utils'),
Events = require('Common/Events'),
Translator = require('Common/Translator'),
Cache = require('Common/Cache'),
AppStore = require('Stores/User/App'),
AccountStore = require('Stores/User/Account'),
SettingsStore = require('Stores/User/Settings'),
FolderStore = require('Stores/User/Folder'),
MessageStore = require('Stores/User/Message'),
Settings = require('Storage/Settings'),
AbstractScreen = require('Knoin/AbstractScreen')
;
/**
* @constructor
* @extends AbstractScreen
*/
function MailBoxUserScreen()
{ {
AbstractScreen.call(this, 'mailbox', [ nFoldersInboxUnreadCount = 0;
require('View/User/MailBox/SystemDropDown'),
require('View/User/MailBox/FolderList'),
require('View/User/MailBox/MessageList'),
require('View/User/MailBox/MessageView')
]);
this.oLastRoute = {};
} }
_.extend(MailBoxUserScreen.prototype, AbstractScreen.prototype); require('App/User').default.setWindowTitle(('' === sEmail ? '' : '' +
(0 < nFoldersInboxUnreadCount ? '(' + nFoldersInboxUnreadCount + ') ' : ' ') +
sEmail + ' - ') + Translator.i18n('TITLES/MAILBOX'));
};
/** MailBoxUserScreen.prototype.onShow = function()
* @type {Object} {
*/ this.updateWindowTitle();
MailBoxUserScreen.prototype.oLastRoute = {};
MailBoxUserScreen.prototype.updateWindowTitle = function () AppStore.focusedState(Enums.Focused.None);
AppStore.focusedState(Enums.Focused.MessageList);
if (Settings.appSettingsGet('mobile'))
{ {
var Globals.leftPanelDisabled(true);
sEmail = AccountStore.email(), }
nFoldersInboxUnreadCount = FolderStore.foldersInboxUnreadCount()
;
if (Settings.appSettingsGet('listPermanentFiltered')) if (!Settings.capa(Enums.Capa.Folders))
{
Globals.leftPanelType(
Settings.capa(Enums.Capa.Composer) || Settings.capa(Enums.Capa.Contacts) ? 'short' : 'none');
}
else
{
Globals.leftPanelType('');
}
};
/**
* @param {string} sFolderHash
* @param {number} iPage
* @param {string} sSearch
*/
MailBoxUserScreen.prototype.onRoute = function(sFolderHash, iPage, sSearch)
{
var
sThreadUid = sFolderHash.replace(/^(.+)~([\d]+)$/, '$2'),
oFolder = Cache.getFolderFromCacheList(Cache.getFolderFullNameRaw(
sFolderHash.replace(/~([\d]+)$/, '')));
if (oFolder)
{
if (sFolderHash === sThreadUid)
{ {
nFoldersInboxUnreadCount = 0; sThreadUid = '';
} }
require('App/User').default.setWindowTitle(('' === sEmail ? '' : '' + FolderStore.currentFolder(oFolder);
(0 < nFoldersInboxUnreadCount ? '(' + nFoldersInboxUnreadCount + ') ' : ' ') +
sEmail + ' - ') + Translator.i18n('TITLES/MAILBOX')); MessageStore.messageListPage(iPage);
}; MessageStore.messageListSearch(sSearch);
MessageStore.messageListThreadUid(sThreadUid);
require('App/User').default.reloadMessageList();
}
};
MailBoxUserScreen.prototype.onStart = function()
{
FolderStore.folderList.subscribe(Utils.windowResizeCallback);
MessageStore.messageList.subscribe(Utils.windowResizeCallback);
MessageStore.message.subscribe(Utils.windowResizeCallback);
_.delay(function() {
SettingsStore.layout.valueHasMutated();
}, 50);
Events.sub('mailbox.inbox-unread-count', _.bind(function(iCount) {
FolderStore.foldersInboxUnreadCount(iCount);
var sEmail = AccountStore.email();
_.each(AccountStore.accounts(), function(oItem) {
if (oItem && sEmail === oItem.email)
{
oItem.count(iCount);
}
});
MailBoxUserScreen.prototype.onShow = function ()
{
this.updateWindowTitle(); this.updateWindowTitle();
AppStore.focusedState(Enums.Focused.None); }, this));
AppStore.focusedState(Enums.Focused.MessageList); };
if (Settings.appSettingsGet('mobile')) MailBoxUserScreen.prototype.onBuild = function()
{ {
Globals.leftPanelDisabled(true); if (!Globals.bMobileDevice && !Settings.appSettingsGet('mobile'))
}
if (!Settings.capa(Enums.Capa.Folders))
{
Globals.leftPanelType(
Settings.capa(Enums.Capa.Composer) || Settings.capa(Enums.Capa.Contacts) ? 'short' : 'none');
}
else
{
Globals.leftPanelType('');
}
};
/**
* @param {string} sFolderHash
* @param {number} iPage
* @param {string} sSearch
*/
MailBoxUserScreen.prototype.onRoute = function (sFolderHash, iPage, sSearch)
{ {
var _.defer(function() {
sThreadUid = sFolderHash.replace(/^(.+)~([\d]+)$/, '$2'), require('App/User').default.initHorizontalLayoutResizer(Enums.ClientSideKeyName.MessageListSize);
oFolder = Cache.getFolderFromCacheList(Cache.getFolderFullNameRaw( });
sFolderHash.replace(/~([\d]+)$/, ''))) }
; };
if (oFolder) /**
{ * @returns {Array}
if (sFolderHash === sThreadUid) */
MailBoxUserScreen.prototype.routes = function()
{
var
sInboxFolderName = Cache.getFolderInboxName(),
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)
{ {
sThreadUid = ''; oVals[0] = sInboxFolderName;
oVals[1] = 1;
} }
FolderStore.currentFolder(oFolder); return [decodeURI(oVals[0]), oVals[1], decodeURI(oVals[2])];
},
fNormD = function(oRequest, oVals) {
oVals[0] = Utils.pString(oVals[0]);
oVals[1] = Utils.pString(oVals[1]);
MessageStore.messageListPage(iPage); if ('' === oRequest)
MessageStore.messageListSearch(sSearch); {
MessageStore.messageListThreadUid(sThreadUid); oVals[0] = sInboxFolderName;
require('App/User').default.reloadMessageList();
}
};
MailBoxUserScreen.prototype.onStart = function ()
{
FolderStore.folderList.subscribe(Utils.windowResizeCallback);
MessageStore.messageList.subscribe(Utils.windowResizeCallback);
MessageStore.message.subscribe(Utils.windowResizeCallback);
_.delay(function () {
SettingsStore.layout.valueHasMutated();
}, 50);
Events.sub('mailbox.inbox-unread-count', _.bind(function (iCount) {
FolderStore.foldersInboxUnreadCount(iCount);
var sEmail = AccountStore.email();
_.each(AccountStore.accounts(), function (oItem) {
if (oItem && sEmail === oItem.email)
{
oItem.count(iCount);
}
});
this.updateWindowTitle();
}, this));
};
MailBoxUserScreen.prototype.onBuild = function ()
{
if (!Globals.bMobileDevice && !Settings.appSettingsGet('mobile'))
{
_.defer(function () {
require('App/User').default.initHorizontalLayoutResizer(Enums.ClientSideKeyName.MessageListSize);
});
}
};
/**
* @return {Array}
*/
MailBoxUserScreen.prototype.routes = function ()
{
var
sInboxFolderName = Cache.getFolderInboxName(),
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] = sInboxFolderName;
oVals[1] = 1;
}
return [decodeURI(oVals[0]), oVals[1], decodeURI(oVals[2])];
},
fNormD = function (oRequest, oVals) {
oVals[0] = Utils.pString(oVals[0]);
oVals[1] = Utils.pString(oVals[1]);
if ('' === oRequest)
{
oVals[0] = sInboxFolderName;
}
return [decodeURI(oVals[0]), 1, decodeURI(oVals[1])];
} }
;
return [ return [decodeURI(oVals[0]), 1, decodeURI(oVals[1])];
[/^([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}],
[/^([^\/]*)$/, {'normalize_': fNormS}]
];
};
module.exports = MailBoxUserScreen; 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}],
[/^([^\/]*)$/, {'normalize_': fNormS}]
];
};
}()); module.exports = MailBoxUserScreen;

View file

@ -1,157 +1,150 @@
(function () { var
_ = require('_'),
'use strict'; Enums = require('Common/Enums'),
Globals = require('Common/Globals'),
Translator = require('Common/Translator'),
var Plugins = require('Common/Plugins'),
_ = require('_'),
Enums = require('Common/Enums'), AppStore = require('Stores/User/App'),
Globals = require('Common/Globals'), AccountStore = require('Stores/User/Account'),
Translator = require('Common/Translator'), Settings = require('Storage/Settings'),
Plugins = require('Common/Plugins'), kn = require('Knoin/Knoin'),
AppStore = require('Stores/User/App'), AbstractSettingsScreen = require('Screen/AbstractSettings');
AccountStore = require('Stores/User/Account'),
Settings = require('Storage/Settings'),
kn = require('Knoin/Knoin'), /**
* @constructor
* @extends AbstractSettingsScreen
*/
function SettingsUserScreen()
{
AbstractSettingsScreen.call(this, [
require('View/User/Settings/SystemDropDown'),
require('View/User/Settings/Menu'),
require('View/User/Settings/Pane')
]);
AbstractSettingsScreen = require('Screen/AbstractSettings') Translator.initOnStartOrLangChange(function() {
; this.sSettingsTitle = Translator.i18n('TITLES/SETTINGS');
}, this, function() {
this.setSettingsTitle();
});
}
/** _.extend(SettingsUserScreen.prototype, AbstractSettingsScreen.prototype);
* @constructor
* @extends AbstractSettingsScreen /**
*/ * @param {Function=} fCallback
function SettingsUserScreen() */
SettingsUserScreen.prototype.setupSettings = function(fCallback)
{
if (!Settings.capa(Enums.Capa.Settings))
{ {
AbstractSettingsScreen.call(this, [
require('View/User/Settings/SystemDropDown'),
require('View/User/Settings/Menu'),
require('View/User/Settings/Pane')
]);
Translator.initOnStartOrLangChange(function () {
this.sSettingsTitle = Translator.i18n('TITLES/SETTINGS');
}, this, function () {
this.setSettingsTitle();
});
}
_.extend(SettingsUserScreen.prototype, AbstractSettingsScreen.prototype);
/**
* @param {Function=} fCallback
*/
SettingsUserScreen.prototype.setupSettings = function (fCallback)
{
if (!Settings.capa(Enums.Capa.Settings))
{
if (fCallback)
{
fCallback();
}
return false;
}
kn.addSettingsViewModel(require('Settings/User/General'),
'SettingsGeneral', 'SETTINGS_LABELS/LABEL_GENERAL_NAME', 'general', true);
if (AppStore.contactsIsAllowed())
{
kn.addSettingsViewModel(require('Settings/User/Contacts'),
'SettingsContacts', 'SETTINGS_LABELS/LABEL_CONTACTS_NAME', 'contacts');
}
if (Settings.capa(Enums.Capa.AdditionalAccounts) || Settings.capa(Enums.Capa.Identities))
{
kn.addSettingsViewModel(require('Settings/User/Accounts'), 'SettingsAccounts',
Settings.capa(Enums.Capa.AdditionalAccounts) ?
'SETTINGS_LABELS/LABEL_ACCOUNTS_NAME' : 'SETTINGS_LABELS/LABEL_IDENTITIES_NAME', 'accounts');
}
if (Settings.capa(Enums.Capa.Sieve))
{
kn.addSettingsViewModel(require('Settings/User/Filters'),
'SettingsFilters', 'SETTINGS_LABELS/LABEL_FILTERS_NAME', 'filters');
}
if (Settings.capa(Enums.Capa.AutoLogout) || Settings.capa(Enums.Capa.TwoFactor))
{
kn.addSettingsViewModel(require('Settings/User/Security'),
'SettingsSecurity', 'SETTINGS_LABELS/LABEL_SECURITY_NAME', 'security');
}
if (AccountStore.isRootAccount() && (
(Settings.settingsGet('AllowGoogleSocial') && Settings.settingsGet('AllowGoogleSocialAuth')) ||
Settings.settingsGet('AllowFacebookSocial') ||
Settings.settingsGet('AllowTwitterSocial')))
{
kn.addSettingsViewModel(require('Settings/User/Social'),
'SettingsSocial', 'SETTINGS_LABELS/LABEL_SOCIAL_NAME', 'social');
}
if (Settings.settingsGet('ChangePasswordIsAllowed'))
{
kn.addSettingsViewModel(require('Settings/User/ChangePassword'),
'SettingsChangePassword', 'SETTINGS_LABELS/LABEL_CHANGE_PASSWORD_NAME', 'change-password');
}
if (Settings.capa(Enums.Capa.Templates))
{
kn.addSettingsViewModel(require('Settings/User/Templates'),
'SettingsTemplates', 'SETTINGS_LABELS/LABEL_TEMPLATES_NAME', 'templates');
}
if (Settings.capa(Enums.Capa.Folders))
{
kn.addSettingsViewModel(require('Settings/User/Folders'),
'SettingsFolders', 'SETTINGS_LABELS/LABEL_FOLDERS_NAME', 'folders');
}
if (Settings.capa(Enums.Capa.Themes))
{
kn.addSettingsViewModel(require('Settings/User/Themes'),
'SettingsThemes', 'SETTINGS_LABELS/LABEL_THEMES_NAME', 'themes');
}
if (Settings.capa(Enums.Capa.OpenPGP))
{
kn.addSettingsViewModel(require('Settings/User/OpenPgp'),
'SettingsOpenPGP', 'SETTINGS_LABELS/LABEL_OPEN_PGP_NAME', 'openpgp');
}
Plugins.runSettingsViewModelHooks(false);
if (fCallback) if (fCallback)
{ {
fCallback(); fCallback();
} }
return true; return false;
}; }
SettingsUserScreen.prototype.onShow = function () kn.addSettingsViewModel(require('Settings/User/General'),
'SettingsGeneral', 'SETTINGS_LABELS/LABEL_GENERAL_NAME', 'general', true);
if (AppStore.contactsIsAllowed())
{ {
this.setSettingsTitle(); kn.addSettingsViewModel(require('Settings/User/Contacts'),
Globals.keyScope(Enums.KeyState.Settings); 'SettingsContacts', 'SETTINGS_LABELS/LABEL_CONTACTS_NAME', 'contacts');
Globals.leftPanelType(''); }
if (Settings.appSettingsGet('mobile')) if (Settings.capa(Enums.Capa.AdditionalAccounts) || Settings.capa(Enums.Capa.Identities))
{
Globals.leftPanelDisabled(true);
}
};
SettingsUserScreen.prototype.setSettingsTitle = function ()
{ {
var sEmail = AccountStore.email(); kn.addSettingsViewModel(require('Settings/User/Accounts'), 'SettingsAccounts',
require('App/User').default.setWindowTitle(('' === sEmail ? '' : sEmail + ' - ') + this.sSettingsTitle); Settings.capa(Enums.Capa.AdditionalAccounts) ?
}; 'SETTINGS_LABELS/LABEL_ACCOUNTS_NAME' : 'SETTINGS_LABELS/LABEL_IDENTITIES_NAME', 'accounts');
}
module.exports = SettingsUserScreen; if (Settings.capa(Enums.Capa.Sieve))
{
kn.addSettingsViewModel(require('Settings/User/Filters'),
'SettingsFilters', 'SETTINGS_LABELS/LABEL_FILTERS_NAME', 'filters');
}
}()); if (Settings.capa(Enums.Capa.AutoLogout) || Settings.capa(Enums.Capa.TwoFactor))
{
kn.addSettingsViewModel(require('Settings/User/Security'),
'SettingsSecurity', 'SETTINGS_LABELS/LABEL_SECURITY_NAME', 'security');
}
if (AccountStore.isRootAccount() && (
(Settings.settingsGet('AllowGoogleSocial') && Settings.settingsGet('AllowGoogleSocialAuth')) ||
Settings.settingsGet('AllowFacebookSocial') ||
Settings.settingsGet('AllowTwitterSocial')))
{
kn.addSettingsViewModel(require('Settings/User/Social'),
'SettingsSocial', 'SETTINGS_LABELS/LABEL_SOCIAL_NAME', 'social');
}
if (Settings.settingsGet('ChangePasswordIsAllowed'))
{
kn.addSettingsViewModel(require('Settings/User/ChangePassword'),
'SettingsChangePassword', 'SETTINGS_LABELS/LABEL_CHANGE_PASSWORD_NAME', 'change-password');
}
if (Settings.capa(Enums.Capa.Templates))
{
kn.addSettingsViewModel(require('Settings/User/Templates'),
'SettingsTemplates', 'SETTINGS_LABELS/LABEL_TEMPLATES_NAME', 'templates');
}
if (Settings.capa(Enums.Capa.Folders))
{
kn.addSettingsViewModel(require('Settings/User/Folders'),
'SettingsFolders', 'SETTINGS_LABELS/LABEL_FOLDERS_NAME', 'folders');
}
if (Settings.capa(Enums.Capa.Themes))
{
kn.addSettingsViewModel(require('Settings/User/Themes'),
'SettingsThemes', 'SETTINGS_LABELS/LABEL_THEMES_NAME', 'themes');
}
if (Settings.capa(Enums.Capa.OpenPGP))
{
kn.addSettingsViewModel(require('Settings/User/OpenPgp'),
'SettingsOpenPGP', 'SETTINGS_LABELS/LABEL_OPEN_PGP_NAME', 'openpgp');
}
Plugins.runSettingsViewModelHooks(false);
if (fCallback)
{
fCallback();
}
return true;
};
SettingsUserScreen.prototype.onShow = function()
{
this.setSettingsTitle();
Globals.keyScope(Enums.KeyState.Settings);
Globals.leftPanelType('');
if (Settings.appSettingsGet('mobile'))
{
Globals.leftPanelDisabled(true);
}
};
SettingsUserScreen.prototype.setSettingsTitle = function()
{
var sEmail = AccountStore.email();
require('App/User').default.setWindowTitle(('' === sEmail ? '' : sEmail + ' - ') + this.sSettingsTitle);
};
module.exports = SettingsUserScreen;

View file

@ -1,102 +1,94 @@
/* global RL_COMMUNITY */ /* global RL_COMMUNITY */
(function () { var
ko = require('ko'),
'use strict'; Translator = require('Common/Translator'),
var Settings = require('Storage/Settings'),
ko = require('ko'), CoreStore = require('Stores/Admin/Core'),
AppStore = require('Stores/Admin/App');
Translator = require('Common/Translator'), /**
* @constructor
*/
function AboutAdminSettings()
{
this.version = ko.observable(Settings.appSettingsGet('version'));
this.access = ko.observable(!!Settings.settingsGet('CoreAccess'));
this.errorDesc = ko.observable('');
Settings = require('Storage/Settings'), this.coreReal = CoreStore.coreReal;
CoreStore = require('Stores/Admin/Core'), this.coreChannel = CoreStore.coreChannel;
AppStore = require('Stores/Admin/App') this.coreType = CoreStore.coreType;
; this.coreUpdatable = CoreStore.coreUpdatable;
this.coreAccess = CoreStore.coreAccess;
this.coreChecking = CoreStore.coreChecking;
this.coreUpdating = CoreStore.coreUpdating;
this.coreWarning = CoreStore.coreWarning;
this.coreVersion = CoreStore.coreVersion;
this.coreRemoteVersion = CoreStore.coreRemoteVersion;
this.coreRemoteRelease = CoreStore.coreRemoteRelease;
this.coreVersionCompare = CoreStore.coreVersionCompare;
/** this.community = RL_COMMUNITY || AppStore.community();
* @constructor
*/ this.coreRemoteVersionHtmlDesc = ko.computed(function() {
function AboutAdminSettings() Translator.trigger();
return Translator.i18n('TAB_ABOUT/HTML_NEW_VERSION', {'VERSION': this.coreRemoteVersion()});
}, this);
this.statusType = ko.computed(function() {
var
sType = '',
iVersionCompare = this.coreVersionCompare(),
bChecking = this.coreChecking(),
bUpdating = this.coreUpdating(),
bReal = this.coreReal();
if (bChecking)
{
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.');
}
return sType;
}, this);
}
AboutAdminSettings.prototype.onBuild = function()
{
if (this.access() && !this.community)
{ {
this.version = ko.observable(Settings.appSettingsGet('version')); require('App/Admin').default.reloadCoreData();
this.access = ko.observable(!!Settings.settingsGet('CoreAccess'));
this.errorDesc = ko.observable('');
this.coreReal = CoreStore.coreReal;
this.coreChannel = CoreStore.coreChannel;
this.coreType = CoreStore.coreType;
this.coreUpdatable = CoreStore.coreUpdatable;
this.coreAccess = CoreStore.coreAccess;
this.coreChecking = CoreStore.coreChecking;
this.coreUpdating = CoreStore.coreUpdating;
this.coreWarning = CoreStore.coreWarning;
this.coreVersion = CoreStore.coreVersion;
this.coreRemoteVersion = CoreStore.coreRemoteVersion;
this.coreRemoteRelease = CoreStore.coreRemoteRelease;
this.coreVersionCompare = CoreStore.coreVersionCompare;
this.community = RL_COMMUNITY || AppStore.community();
this.coreRemoteVersionHtmlDesc = ko.computed(function () {
Translator.trigger();
return Translator.i18n('TAB_ABOUT/HTML_NEW_VERSION', {'VERSION': this.coreRemoteVersion()});
}, this);
this.statusType = ko.computed(function () {
var
sType = '',
iVersionCompare = this.coreVersionCompare(),
bChecking = this.coreChecking(),
bUpdating = this.coreUpdating(),
bReal = this.coreReal()
;
if (bChecking)
{
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.');
}
return sType;
}, this);
} }
};
AboutAdminSettings.prototype.onBuild = function () AboutAdminSettings.prototype.updateCoreData = function()
{
if (!this.coreUpdating() && !this.community)
{ {
if (this.access() && !this.community) require('App/Admin').default.updateCoreData();
{ }
require('App/Admin').default.reloadCoreData(); };
}
};
AboutAdminSettings.prototype.updateCoreData = function () module.exports = AboutAdminSettings;
{
if (!this.coreUpdating() && !this.community)
{
require('App/Admin').default.updateCoreData();
}
};
module.exports = AboutAdminSettings;
}());

View file

@ -1,123 +1,113 @@
/* global RL_COMMUNITY */ /* global RL_COMMUNITY */
(function () { var
_ = require('_'),
ko = require('ko'),
'use strict'; Utils = require('Common/Utils'),
Translator = require('Common/Translator');
/**
* @constructor
*/
function BrandingAdminSettings()
{
var var
_ = require('_'), Enums = require('Common/Enums'),
ko = require('ko'), Settings = require('Storage/Settings'),
AppStore = require('Stores/Admin/App');
Utils = require('Common/Utils'), this.capa = AppStore.prem;
Translator = require('Common/Translator')
; this.title = ko.observable(Settings.settingsGet('Title'));
this.title.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.loadingDesc = ko.observable(Settings.settingsGet('LoadingDescription'));
this.loadingDesc.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.faviconUrl = ko.observable(Settings.settingsGet('FaviconUrl'));
this.faviconUrl.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.loginLogo = ko.observable(Settings.settingsGet('LoginLogo') || '');
this.loginLogo.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.loginBackground = ko.observable(Settings.settingsGet('LoginBackground') || '');
this.loginBackground.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.userLogo = ko.observable(Settings.settingsGet('UserLogo') || '');
this.userLogo.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.userLogoMessage = ko.observable(Settings.settingsGet('UserLogoMessage') || '');
this.userLogoMessage.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.userIframeMessage = ko.observable(Settings.settingsGet('UserIframeMessage') || '');
this.userIframeMessage.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.userLogoTitle = ko.observable(Settings.settingsGet('UserLogoTitle') || '');
this.userLogoTitle.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.loginDescription = ko.observable(Settings.settingsGet('LoginDescription'));
this.loginDescription.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.loginCss = ko.observable(Settings.settingsGet('LoginCss'));
this.loginCss.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.userCss = ko.observable(Settings.settingsGet('UserCss'));
this.userCss.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.welcomePageUrl = ko.observable(Settings.settingsGet('WelcomePageUrl'));
this.welcomePageUrl.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.welcomePageDisplay = ko.observable(Settings.settingsGet('WelcomePageDisplay'));
this.welcomePageDisplay.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.welcomePageDisplay.options = ko.computed(function() {
Translator.trigger();
return [
{'optValue': 'none', 'optText': Translator.i18n('TAB_BRANDING/OPTION_WELCOME_PAGE_DISPLAY_NONE')},
{'optValue': 'once', 'optText': Translator.i18n('TAB_BRANDING/OPTION_WELCOME_PAGE_DISPLAY_ONCE')},
{'optValue': 'always', 'optText': Translator.i18n('TAB_BRANDING/OPTION_WELCOME_PAGE_DISPLAY_ALWAYS')}
];
});
this.loginPowered = ko.observable(!!Settings.settingsGet('LoginPowered'));
this.community = RL_COMMUNITY || AppStore.community();
}
BrandingAdminSettings.prototype.onBuild = function()
{
var
self = this,
Remote = require('Remote/Admin/Ajax');
_.delay(function() {
/**
* @constructor
*/
function BrandingAdminSettings()
{
var var
Enums = require('Common/Enums'), f1 = Utils.settingsSaveHelperSimpleFunction(self.title.trigger, self),
Settings = require('Storage/Settings'), f2 = Utils.settingsSaveHelperSimpleFunction(self.loadingDesc.trigger, self),
AppStore = require('Stores/Admin/App') f3 = Utils.settingsSaveHelperSimpleFunction(self.faviconUrl.trigger, self);
;
this.capa = AppStore.prem; self.title.subscribe(function(sValue) {
Remote.saveAdminConfig(f1, {
this.title = ko.observable(Settings.settingsGet('Title')); 'Title': Utils.trim(sValue)
this.title.trigger = ko.observable(Enums.SaveSettingsStep.Idle); });
this.loadingDesc = ko.observable(Settings.settingsGet('LoadingDescription'));
this.loadingDesc.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.faviconUrl = ko.observable(Settings.settingsGet('FaviconUrl'));
this.faviconUrl.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.loginLogo = ko.observable(Settings.settingsGet('LoginLogo') || '');
this.loginLogo.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.loginBackground = ko.observable(Settings.settingsGet('LoginBackground') || '');
this.loginBackground.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.userLogo = ko.observable(Settings.settingsGet('UserLogo') || '');
this.userLogo.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.userLogoMessage = ko.observable(Settings.settingsGet('UserLogoMessage') || '');
this.userLogoMessage.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.userIframeMessage = ko.observable(Settings.settingsGet('UserIframeMessage') || '');
this.userIframeMessage.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.userLogoTitle = ko.observable(Settings.settingsGet('UserLogoTitle') || '');
this.userLogoTitle.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.loginDescription = ko.observable(Settings.settingsGet('LoginDescription'));
this.loginDescription.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.loginCss = ko.observable(Settings.settingsGet('LoginCss'));
this.loginCss.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.userCss = ko.observable(Settings.settingsGet('UserCss'));
this.userCss.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.welcomePageUrl = ko.observable(Settings.settingsGet('WelcomePageUrl'));
this.welcomePageUrl.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.welcomePageDisplay = ko.observable(Settings.settingsGet('WelcomePageDisplay'));
this.welcomePageDisplay.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.welcomePageDisplay.options = ko.computed(function () {
Translator.trigger();
return [
{'optValue': 'none', 'optText': Translator.i18n('TAB_BRANDING/OPTION_WELCOME_PAGE_DISPLAY_NONE')},
{'optValue': 'once', 'optText': Translator.i18n('TAB_BRANDING/OPTION_WELCOME_PAGE_DISPLAY_ONCE')},
{'optValue': 'always', 'optText': Translator.i18n('TAB_BRANDING/OPTION_WELCOME_PAGE_DISPLAY_ALWAYS')}
];
}); });
this.loginPowered = ko.observable(!!Settings.settingsGet('LoginPowered')); self.loadingDesc.subscribe(function(sValue) {
Remote.saveAdminConfig(f2, {
this.community = RL_COMMUNITY || AppStore.community(); 'LoadingDescription': Utils.trim(sValue)
}
BrandingAdminSettings.prototype.onBuild = function ()
{
var
self = this,
Remote = require('Remote/Admin/Ajax')
;
_.delay(function () {
var
f1 = Utils.settingsSaveHelperSimpleFunction(self.title.trigger, self),
f2 = Utils.settingsSaveHelperSimpleFunction(self.loadingDesc.trigger, self),
f3 = Utils.settingsSaveHelperSimpleFunction(self.faviconUrl.trigger, self)
;
self.title.subscribe(function (sValue) {
Remote.saveAdminConfig(f1, {
'Title': Utils.trim(sValue)
});
}); });
});
self.loadingDesc.subscribe(function (sValue) { self.faviconUrl.subscribe(function(sValue) {
Remote.saveAdminConfig(f2, { Remote.saveAdminConfig(f3, {
'LoadingDescription': Utils.trim(sValue) 'FaviconUrl': Utils.trim(sValue)
});
}); });
});
self.faviconUrl.subscribe(function (sValue) { }, 50);
Remote.saveAdminConfig(f3, { };
'FaviconUrl': Utils.trim(sValue)
});
});
}, 50); module.exports = BrandingAdminSettings;
};
module.exports = BrandingAdminSettings;
}());

View file

@ -1,244 +1,234 @@
(function () { var
_ = require('_'),
ko = require('ko'),
'use strict'; Enums = require('Common/Enums'),
Utils = require('Common/Utils'),
Translator = require('Common/Translator'),
Settings = require('Storage/Settings');
/**
* @constructor
*/
function ContactsAdminSettings()
{
var
Remote = require('Remote/Admin/Ajax');
this.defautOptionsAfterRender = Utils.defautOptionsAfterRender;
this.enableContacts = ko.observable(!!Settings.settingsGet('ContactsEnable'));
this.contactsSharing = ko.observable(!!Settings.settingsGet('ContactsSharing'));
this.contactsSync = ko.observable(!!Settings.settingsGet('ContactsSync'));
var var
_ = require('_'), aTypes = ['sqlite', 'mysql', 'pgsql'],
ko = require('ko'), aSupportedTypes = [],
getTypeName = function(sName) {
switch (sName)
{
case 'sqlite':
sName = 'SQLite';
break;
case 'mysql':
sName = 'MySQL';
break;
case 'pgsql':
sName = 'PostgreSQL';
break;
// no default
}
Enums = require('Common/Enums'), return sName;
Utils = require('Common/Utils'), };
Translator = require('Common/Translator'), if (Settings.settingsGet('SQLiteIsSupported'))
Settings = require('Storage/Settings')
;
/**
* @constructor
*/
function ContactsAdminSettings()
{ {
var aSupportedTypes.push('sqlite');
Remote = require('Remote/Admin/Ajax') }
; if (Settings.settingsGet('MySqlIsSupported'))
{
this.defautOptionsAfterRender = Utils.defautOptionsAfterRender; aSupportedTypes.push('mysql');
this.enableContacts = ko.observable(!!Settings.settingsGet('ContactsEnable')); }
this.contactsSharing = ko.observable(!!Settings.settingsGet('ContactsSharing')); if (Settings.settingsGet('PostgreSqlIsSupported'))
this.contactsSync = ko.observable(!!Settings.settingsGet('ContactsSync')); {
aSupportedTypes.push('pgsql');
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 (Settings.settingsGet('SQLiteIsSupported'))
{
aSupportedTypes.push('sqlite');
}
if (Settings.settingsGet('MySqlIsSupported'))
{
aSupportedTypes.push('mysql');
}
if (Settings.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 ? ' (' + Translator.i18n('HINTS/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();
}
}
}).extend({'notify': 'always'});
this.contactsType.subscribe(function () {
this.testContactsSuccess(false);
this.testContactsError(false);
this.testContactsErrorMessage('');
}, this);
this.pdoDsn = ko.observable(Settings.settingsGet('ContactsPdoDsn'));
this.pdoUser = ko.observable(Settings.settingsGet('ContactsPdoUser'));
this.pdoPassword = ko.observable(Settings.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);
Remote.testContacts(this.onTestContactsResponse, {
'ContactsPdoType': this.contactsType(),
'ContactsPdoDsn': this.pdoDsn(),
'ContactsPdoUser': this.pdoUser(),
'ContactsPdoPassword': this.pdoPassword()
});
}, function () {
return '' !== this.pdoDsn() && '' !== this.pdoUser();
});
this.contactsType(Settings.settingsGet('ContactsPdoType'));
this.onTestContactsResponse = _.bind(this.onTestContactsResponse, this);
} }
ContactsAdminSettings.prototype.onTestContactsResponse = function (sResult, oData) this.contactsSupported = 0 < aSupportedTypes.length;
{
this.testContactsSuccess(false);
this.testContactsError(false);
this.testContactsErrorMessage('');
if (Enums.StorageResultType.Success === sResult && oData && oData.Result && oData.Result.Result) this.contactsTypes = ko.observableArray([]);
{ this.contactsTypesOptions = this.contactsTypes.map(function(sValue) {
this.testContactsSuccess(true); var bDisabled = -1 === Utils.inArray(sValue, aSupportedTypes);
} return {
else 'id': sValue,
{ 'name': getTypeName(sValue) + (bDisabled ? ' (' + Translator.i18n('HINTS/NOT_SUPPORTED') + ')' : ''),
this.testContactsError(true); 'disabled': bDisabled
if (oData && oData.Result) };
});
this.contactsTypes(aTypes);
this.contactsType = ko.observable('');
this.mainContactsType = ko.computed({
'owner': this,
'read': this.contactsType,
'write': function(sValue) {
if (sValue !== this.contactsType())
{ {
this.testContactsErrorMessage(oData.Result.Message || ''); if (-1 < Utils.inArray(sValue, aSupportedTypes))
{
this.contactsType(sValue);
}
else if (0 < aSupportedTypes.length)
{
this.contactsType('');
}
} }
else else
{ {
this.testContactsErrorMessage(''); this.contactsType.valueHasMutated();
} }
} }
}).extend({'notify': 'always'});
this.testing(false); this.contactsType.subscribe(function() {
};
ContactsAdminSettings.prototype.onShow = function ()
{
this.testContactsSuccess(false); this.testContactsSuccess(false);
this.testContactsError(false); this.testContactsError(false);
this.testContactsErrorMessage(''); this.testContactsErrorMessage('');
}; }, this);
ContactsAdminSettings.prototype.onBuild = function () this.pdoDsn = ko.observable(Settings.settingsGet('ContactsPdoDsn'));
this.pdoUser = ko.observable(Settings.settingsGet('ContactsPdoUser'));
this.pdoPassword = ko.observable(Settings.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);
Remote.testContacts(this.onTestContactsResponse, {
'ContactsPdoType': this.contactsType(),
'ContactsPdoDsn': this.pdoDsn(),
'ContactsPdoUser': this.pdoUser(),
'ContactsPdoPassword': this.pdoPassword()
});
}, function() {
return '' !== this.pdoDsn() && '' !== this.pdoUser();
});
this.contactsType(Settings.settingsGet('ContactsPdoType'));
this.onTestContactsResponse = _.bind(this.onTestContactsResponse, this);
}
ContactsAdminSettings.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.testContactsErrorMessage(oData.Result.Message || '');
}
else
{
this.testContactsErrorMessage('');
}
}
this.testing(false);
};
ContactsAdminSettings.prototype.onShow = function()
{
this.testContactsSuccess(false);
this.testContactsError(false);
this.testContactsErrorMessage('');
};
ContactsAdminSettings.prototype.onBuild = function()
{
var
self = this,
Remote = require('Remote/Admin/Ajax');
_.delay(function() {
var var
self = this, f1 = Utils.settingsSaveHelperSimpleFunction(self.pdoDsnTrigger, self),
Remote = require('Remote/Admin/Ajax') f3 = Utils.settingsSaveHelperSimpleFunction(self.pdoUserTrigger, self),
; f4 = Utils.settingsSaveHelperSimpleFunction(self.pdoPasswordTrigger, self),
f5 = Utils.settingsSaveHelperSimpleFunction(self.contactsTypeTrigger, self);
_.delay(function () { self.enableContacts.subscribe(function(bValue) {
Remote.saveAdminConfig(null, {
var 'ContactsEnable': bValue ? '1' : '0'
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) {
Remote.saveAdminConfig(null, {
'ContactsEnable': bValue ? '1' : '0'
});
}); });
});
self.contactsSharing.subscribe(function (bValue) { self.contactsSharing.subscribe(function(bValue) {
Remote.saveAdminConfig(null, { Remote.saveAdminConfig(null, {
'ContactsSharing': bValue ? '1' : '0' 'ContactsSharing': bValue ? '1' : '0'
});
}); });
});
self.contactsSync.subscribe(function (bValue) { self.contactsSync.subscribe(function(bValue) {
Remote.saveAdminConfig(null, { Remote.saveAdminConfig(null, {
'ContactsSync': bValue ? '1' : '0' 'ContactsSync': bValue ? '1' : '0'
});
}); });
});
self.contactsType.subscribe(function (sValue) { self.contactsType.subscribe(function(sValue) {
Remote.saveAdminConfig(f5, { Remote.saveAdminConfig(f5, {
'ContactsPdoType': sValue 'ContactsPdoType': sValue
});
}); });
});
self.pdoDsn.subscribe(function (sValue) { self.pdoDsn.subscribe(function(sValue) {
Remote.saveAdminConfig(f1, { Remote.saveAdminConfig(f1, {
'ContactsPdoDsn': Utils.trim(sValue) 'ContactsPdoDsn': Utils.trim(sValue)
});
}); });
});
self.pdoUser.subscribe(function (sValue) { self.pdoUser.subscribe(function(sValue) {
Remote.saveAdminConfig(f3, { Remote.saveAdminConfig(f3, {
'ContactsPdoUser': Utils.trim(sValue) 'ContactsPdoUser': Utils.trim(sValue)
});
}); });
});
self.pdoPassword.subscribe(function (sValue) { self.pdoPassword.subscribe(function(sValue) {
Remote.saveAdminConfig(f4, { Remote.saveAdminConfig(f4, {
'ContactsPdoPassword': Utils.trim(sValue) 'ContactsPdoPassword': Utils.trim(sValue)
});
}); });
});
self.contactsType(Settings.settingsGet('ContactsPdoType')); self.contactsType(Settings.settingsGet('ContactsPdoType'));
}, 50); }, 50);
}; };
module.exports = ContactsAdminSettings; module.exports = ContactsAdminSettings;
}());

View file

@ -1,86 +1,78 @@
(function () { var
_ = require('_'),
ko = require('ko'),
'use strict'; Enums = require('Common/Enums'),
var DomainStore = require('Stores/Admin/Domain'),
_ = require('_'), Remote = require('Remote/Admin/Ajax');
ko = require('ko'),
Enums = require('Common/Enums'), /**
* @constructor
*/
function DomainsAdminSettings()
{
this.domains = DomainStore.domains;
DomainStore = require('Stores/Admin/Domain'), this.visibility = ko.computed(function() {
Remote = require('Remote/Admin/Ajax') return this.domains.loading() ? 'visible' : 'hidden';
; }, this);
/** this.domainForDeletion = ko.observable(null).deleteAccessHelper();
* @constructor
*/ this.onDomainListChangeRequest = _.bind(this.onDomainListChangeRequest, this);
function DomainsAdminSettings() this.onDomainLoadRequest = _.bind(this.onDomainLoadRequest, this);
}
DomainsAdminSettings.prototype.createDomain = function()
{
require('Knoin/Knoin').showScreenPopup(require('View/Popup/Domain'));
};
DomainsAdminSettings.prototype.createDomainAlias = function()
{
require('Knoin/Knoin').showScreenPopup(require('View/Popup/DomainAlias'));
};
DomainsAdminSettings.prototype.deleteDomain = function(oDomain)
{
this.domains.remove(oDomain);
Remote.domainDelete(this.onDomainListChangeRequest, oDomain.name);
};
DomainsAdminSettings.prototype.disableDomain = function(oDomain)
{
oDomain.disabled(!oDomain.disabled());
Remote.domainDisable(this.onDomainListChangeRequest, oDomain.name, oDomain.disabled());
};
DomainsAdminSettings.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)
{
Remote.domain(self.onDomainLoadRequest, oDomainItem.name);
}
});
require('App/Admin').default.reloadDomainList();
};
DomainsAdminSettings.prototype.onDomainLoadRequest = function(sResult, oData)
{
if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
{ {
this.domains = DomainStore.domains; require('Knoin/Knoin').showScreenPopup(require('View/Popup/Domain'), [oData.Result]);
this.visibility = ko.computed(function () {
return this.domains.loading() ? 'visible' : 'hidden';
}, this);
this.domainForDeletion = ko.observable(null).deleteAccessHelper();
this.onDomainListChangeRequest = _.bind(this.onDomainListChangeRequest, this);
this.onDomainLoadRequest = _.bind(this.onDomainLoadRequest, this);
} }
};
DomainsAdminSettings.prototype.createDomain = function () DomainsAdminSettings.prototype.onDomainListChangeRequest = function()
{ {
require('Knoin/Knoin').showScreenPopup(require('View/Popup/Domain')); require('App/Admin').default.reloadDomainList();
}; };
DomainsAdminSettings.prototype.createDomainAlias = function () module.exports = DomainsAdminSettings;
{
require('Knoin/Knoin').showScreenPopup(require('View/Popup/DomainAlias'));
};
DomainsAdminSettings.prototype.deleteDomain = function (oDomain)
{
this.domains.remove(oDomain);
Remote.domainDelete(this.onDomainListChangeRequest, oDomain.name);
};
DomainsAdminSettings.prototype.disableDomain = function (oDomain)
{
oDomain.disabled(!oDomain.disabled());
Remote.domainDisable(this.onDomainListChangeRequest, oDomain.name, oDomain.disabled());
};
DomainsAdminSettings.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)
{
Remote.domain(self.onDomainLoadRequest, oDomainItem.name);
}
})
;
require('App/Admin').default.reloadDomainList();
};
DomainsAdminSettings.prototype.onDomainLoadRequest = function (sResult, oData)
{
if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
{
require('Knoin/Knoin').showScreenPopup(require('View/Popup/Domain'), [oData.Result]);
}
};
DomainsAdminSettings.prototype.onDomainListChangeRequest = function ()
{
require('App/Admin').default.reloadDomainList();
};
module.exports = DomainsAdminSettings;
}());

View file

@ -1,211 +1,202 @@
(function () { var
_ = require('_'),
ko = require('ko'),
'use strict'; Enums = require('Common/Enums'),
Utils = require('Common/Utils'),
Links = require('Common/Links'),
Translator = require('Common/Translator'),
ThemeStore = require('Stores/Theme'),
LanguageStore = require('Stores/Language'),
AppAdminStore = require('Stores/Admin/App'),
CapaAdminStore = require('Stores/Admin/Capa'),
Settings = require('Storage/Settings');
/**
* @constructor
*/
function GeneralAdminSettings()
{
this.language = LanguageStore.language;
this.languages = LanguageStore.languages;
this.languageAdmin = LanguageStore.languageAdmin;
this.languagesAdmin = LanguageStore.languagesAdmin;
this.theme = ThemeStore.theme;
this.themes = ThemeStore.themes;
this.capaThemes = CapaAdminStore.themes;
this.capaUserBackground = CapaAdminStore.userBackground;
this.capaGravatar = CapaAdminStore.gravatar;
this.capaAdditionalAccounts = CapaAdminStore.additionalAccounts;
this.capaIdentities = CapaAdminStore.identities;
this.capaAttachmentThumbnails = CapaAdminStore.attachmentThumbnails;
this.capaTemplates = CapaAdminStore.templates;
this.allowLanguagesOnSettings = AppAdminStore.allowLanguagesOnSettings;
this.weakPassword = AppAdminStore.weakPassword;
this.mainAttachmentLimit = ko.observable(Utils.pInt(Settings.settingsGet('AttachmentLimit')) / (1024 * 1024)).extend({'posInterer': 25});
this.uploadData = Settings.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(this.themes(), function(sTheme) {
return {
optValue: sTheme,
optText: Utils.convertThemeName(sTheme)
};
});
}, this);
this.languageFullName = ko.computed(function() {
return Utils.convertLangName(this.language());
}, this);
this.languageAdminFullName = ko.computed(function() {
return Utils.convertLangName(this.languageAdmin());
}, this);
this.attachmentLimitTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.languageTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.languageAdminTrigger = ko.observable(Enums.SaveSettingsStep.Idle).extend({'throttle': 100});
this.themeTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
}
GeneralAdminSettings.prototype.onBuild = function()
{
var var
_ = require('_'), self = this,
ko = require('ko'), Remote = require('Remote/Admin/Ajax');
Enums = require('Common/Enums'), _.delay(function() {
Utils = require('Common/Utils'),
Links = require('Common/Links'),
Translator = require('Common/Translator'),
ThemeStore = require('Stores/Theme'),
LanguageStore = require('Stores/Language'),
AppAdminStore = require('Stores/Admin/App'),
CapaAdminStore = require('Stores/Admin/Capa'),
Settings = require('Storage/Settings')
;
/**
* @constructor
*/
function GeneralAdminSettings()
{
this.language = LanguageStore.language;
this.languages = LanguageStore.languages;
this.languageAdmin = LanguageStore.languageAdmin;
this.languagesAdmin = LanguageStore.languagesAdmin;
this.theme = ThemeStore.theme;
this.themes = ThemeStore.themes;
this.capaThemes = CapaAdminStore.themes;
this.capaUserBackground = CapaAdminStore.userBackground;
this.capaGravatar = CapaAdminStore.gravatar;
this.capaAdditionalAccounts = CapaAdminStore.additionalAccounts;
this.capaIdentities = CapaAdminStore.identities;
this.capaAttachmentThumbnails = CapaAdminStore.attachmentThumbnails;
this.capaTemplates = CapaAdminStore.templates;
this.allowLanguagesOnSettings = AppAdminStore.allowLanguagesOnSettings;
this.weakPassword = AppAdminStore.weakPassword;
this.mainAttachmentLimit = ko.observable(Utils.pInt(Settings.settingsGet('AttachmentLimit')) / (1024 * 1024)).extend({'posInterer': 25});
this.uploadData = Settings.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(this.themes(), function (sTheme) {
return {
optValue: sTheme,
optText: Utils.convertThemeName(sTheme)
};
});
}, this);
this.languageFullName = ko.computed(function () {
return Utils.convertLangName(this.language());
}, this);
this.languageAdminFullName = ko.computed(function () {
return Utils.convertLangName(this.languageAdmin());
}, this);
this.attachmentLimitTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.languageTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.languageAdminTrigger = ko.observable(Enums.SaveSettingsStep.Idle).extend({'throttle': 100});
this.themeTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
}
GeneralAdminSettings.prototype.onBuild = function ()
{
var var
self = this, f1 = Utils.settingsSaveHelperSimpleFunction(self.attachmentLimitTrigger, self),
Remote = require('Remote/Admin/Ajax') f2 = Utils.settingsSaveHelperSimpleFunction(self.languageTrigger, self),
; f3 = Utils.settingsSaveHelperSimpleFunction(self.themeTrigger, self),
fReloadLanguageHelper = function(iSaveSettingsStep) {
return function() {
self.languageAdminTrigger(iSaveSettingsStep);
_.delay(function() {
self.languageAdminTrigger(Enums.SaveSettingsStep.Idle);
}, 1000);
};
};
_.delay(function () { self.mainAttachmentLimit.subscribe(function(sValue) {
Remote.saveAdminConfig(f1, {
var 'AttachmentLimit': Utils.pInt(sValue)
f1 = Utils.settingsSaveHelperSimpleFunction(self.attachmentLimitTrigger, self),
f2 = Utils.settingsSaveHelperSimpleFunction(self.languageTrigger, self),
f3 = Utils.settingsSaveHelperSimpleFunction(self.themeTrigger, self),
fReloadLanguageHelper = function (iSaveSettingsStep) {
return function() {
self.languageAdminTrigger(iSaveSettingsStep);
_.delay(function () {
self.languageAdminTrigger(Enums.SaveSettingsStep.Idle);
}, 1000);
};
}
;
self.mainAttachmentLimit.subscribe(function (sValue) {
Remote.saveAdminConfig(f1, {
'AttachmentLimit': Utils.pInt(sValue)
});
}); });
});
self.language.subscribe(function (sValue) { self.language.subscribe(function(sValue) {
Remote.saveAdminConfig(f2, { Remote.saveAdminConfig(f2, {
'Language': Utils.trim(sValue) 'Language': Utils.trim(sValue)
});
}); });
});
self.languageAdmin.subscribe(function (sValue) { self.languageAdmin.subscribe(function(sValue) {
self.languageAdminTrigger(Enums.SaveSettingsStep.Animate); self.languageAdminTrigger(Enums.SaveSettingsStep.Animate);
Translator.reload(true, sValue).then( Translator.reload(true, sValue).then(
fReloadLanguageHelper(Enums.SaveSettingsStep.TrueResult), fReloadLanguageHelper(Enums.SaveSettingsStep.TrueResult),
fReloadLanguageHelper(Enums.SaveSettingsStep.FalseResult) fReloadLanguageHelper(Enums.SaveSettingsStep.FalseResult)
).then(function() { ).then(function() {
Remote.saveAdminConfig(null, {
'LanguageAdmin': Utils.trim(sValue)
});
});
});
self.theme.subscribe(function (sValue) {
Utils.changeTheme(sValue, self.themeTrigger);
Remote.saveAdminConfig(f3, {
'Theme': Utils.trim(sValue)
});
});
self.capaAdditionalAccounts.subscribe(function (bValue) {
Remote.saveAdminConfig(null, { Remote.saveAdminConfig(null, {
'CapaAdditionalAccounts': bValue ? '1' : '0' 'LanguageAdmin': Utils.trim(sValue)
}); });
}); });
self.capaIdentities.subscribe(function (bValue) { });
Remote.saveAdminConfig(null, {
'CapaIdentities': bValue ? '1' : '0' self.theme.subscribe(function(sValue) {
});
Utils.changeTheme(sValue, self.themeTrigger);
Remote.saveAdminConfig(f3, {
'Theme': Utils.trim(sValue)
}); });
});
self.capaTemplates.subscribe(function (bValue) { self.capaAdditionalAccounts.subscribe(function(bValue) {
Remote.saveAdminConfig(null, { Remote.saveAdminConfig(null, {
'CapaTemplates': bValue ? '1' : '0' 'CapaAdditionalAccounts': bValue ? '1' : '0'
});
}); });
});
self.capaGravatar.subscribe(function (bValue) { self.capaIdentities.subscribe(function(bValue) {
Remote.saveAdminConfig(null, { Remote.saveAdminConfig(null, {
'CapaGravatar': bValue ? '1' : '0' 'CapaIdentities': bValue ? '1' : '0'
});
}); });
});
self.capaAttachmentThumbnails.subscribe(function (bValue) { self.capaTemplates.subscribe(function(bValue) {
Remote.saveAdminConfig(null, { Remote.saveAdminConfig(null, {
'CapaAttachmentThumbnails': bValue ? '1' : '0' 'CapaTemplates': bValue ? '1' : '0'
});
}); });
});
self.capaThemes.subscribe(function (bValue) { self.capaGravatar.subscribe(function(bValue) {
Remote.saveAdminConfig(null, { Remote.saveAdminConfig(null, {
'CapaThemes': bValue ? '1' : '0' 'CapaGravatar': bValue ? '1' : '0'
});
}); });
});
self.capaUserBackground.subscribe(function (bValue) { self.capaAttachmentThumbnails.subscribe(function(bValue) {
Remote.saveAdminConfig(null, { Remote.saveAdminConfig(null, {
'CapaUserBackground': bValue ? '1' : '0' 'CapaAttachmentThumbnails': bValue ? '1' : '0'
});
}); });
});
self.allowLanguagesOnSettings.subscribe(function (bValue) { self.capaThemes.subscribe(function(bValue) {
Remote.saveAdminConfig(null, { Remote.saveAdminConfig(null, {
'AllowLanguagesOnSettings': bValue ? '1' : '0' 'CapaThemes': bValue ? '1' : '0'
});
}); });
});
}, 50); self.capaUserBackground.subscribe(function(bValue) {
}; Remote.saveAdminConfig(null, {
'CapaUserBackground': bValue ? '1' : '0'
});
});
GeneralAdminSettings.prototype.selectLanguage = function () self.allowLanguagesOnSettings.subscribe(function(bValue) {
{ Remote.saveAdminConfig(null, {
require('Knoin/Knoin').showScreenPopup(require('View/Popup/Languages'), [ 'AllowLanguagesOnSettings': bValue ? '1' : '0'
this.language, this.languages(), LanguageStore.userLanguage() });
]); });
};
GeneralAdminSettings.prototype.selectLanguageAdmin = function () }, 50);
{ };
require('Knoin/Knoin').showScreenPopup(require('View/Popup/Languages'), [
this.languageAdmin, this.languagesAdmin(), LanguageStore.userLanguageAdmin()
]);
};
/** GeneralAdminSettings.prototype.selectLanguage = function()
* @return {string} {
*/ require('Knoin/Knoin').showScreenPopup(require('View/Popup/Languages'), [
GeneralAdminSettings.prototype.phpInfoLink = function () this.language, this.languages(), LanguageStore.userLanguage()
{ ]);
return Links.phpInfo(); };
};
module.exports = GeneralAdminSettings; GeneralAdminSettings.prototype.selectLanguageAdmin = function()
{
require('Knoin/Knoin').showScreenPopup(require('View/Popup/Languages'), [
this.languageAdmin, this.languagesAdmin(), LanguageStore.userLanguageAdmin()
]);
};
}()); /**
* @returns {string}
*/
GeneralAdminSettings.prototype.phpInfoLink = function()
{
return Links.phpInfo();
};
module.exports = GeneralAdminSettings;

View file

@ -1,74 +1,66 @@
(function () { var
_ = require('_'),
ko = require('ko'),
'use strict'; Enums = require('Common/Enums'),
Utils = require('Common/Utils'),
AppAdminStore = require('Stores/Admin/App'),
Settings = require('Storage/Settings');
/**
* @constructor
*/
function LoginAdminSettings()
{
this.determineUserLanguage = AppAdminStore.determineUserLanguage;
this.determineUserDomain = AppAdminStore.determineUserDomain;
this.defaultDomain = ko.observable(Settings.settingsGet('LoginDefaultDomain'));
this.allowLanguagesOnLogin = AppAdminStore.allowLanguagesOnLogin;
this.defaultDomainTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.dummy = ko.observable(false);
}
LoginAdminSettings.prototype.onBuild = function()
{
var var
_ = require('_'), self = this,
ko = require('ko'), Remote = require('Remote/Admin/Ajax');
Enums = require('Common/Enums'), _.delay(function() {
Utils = require('Common/Utils'),
AppAdminStore = require('Stores/Admin/App'), var f1 = Utils.settingsSaveHelperSimpleFunction(self.defaultDomainTrigger, self);
Settings = require('Storage/Settings') self.determineUserLanguage.subscribe(function(bValue) {
; Remote.saveAdminConfig(null, {
'DetermineUserLanguage': bValue ? '1' : '0'
/**
* @constructor
*/
function LoginAdminSettings()
{
this.determineUserLanguage = AppAdminStore.determineUserLanguage;
this.determineUserDomain = AppAdminStore.determineUserDomain;
this.defaultDomain = ko.observable(Settings.settingsGet('LoginDefaultDomain'));
this.allowLanguagesOnLogin = AppAdminStore.allowLanguagesOnLogin;
this.defaultDomainTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.dummy = ko.observable(false);
}
LoginAdminSettings.prototype.onBuild = function ()
{
var
self = this,
Remote = require('Remote/Admin/Ajax')
;
_.delay(function () {
var f1 = Utils.settingsSaveHelperSimpleFunction(self.defaultDomainTrigger, self);
self.determineUserLanguage.subscribe(function (bValue) {
Remote.saveAdminConfig(null, {
'DetermineUserLanguage': bValue ? '1' : '0'
});
}); });
});
self.determineUserDomain.subscribe(function (bValue) { self.determineUserDomain.subscribe(function(bValue) {
Remote.saveAdminConfig(null, { Remote.saveAdminConfig(null, {
'DetermineUserDomain': bValue ? '1' : '0' 'DetermineUserDomain': bValue ? '1' : '0'
});
}); });
});
self.allowLanguagesOnLogin.subscribe(function (bValue) { self.allowLanguagesOnLogin.subscribe(function(bValue) {
Remote.saveAdminConfig(null, { Remote.saveAdminConfig(null, {
'AllowLanguagesOnLogin': bValue ? '1' : '0' 'AllowLanguagesOnLogin': bValue ? '1' : '0'
});
}); });
});
self.defaultDomain.subscribe(function (sValue) { self.defaultDomain.subscribe(function(sValue) {
Remote.saveAdminConfig(f1, { Remote.saveAdminConfig(f1, {
'LoginDefaultDomain': Utils.trim(sValue) 'LoginDefaultDomain': Utils.trim(sValue)
});
}); });
});
}, 50); }, 50);
}; };
module.exports = LoginAdminSettings; module.exports = LoginAdminSettings;
}());

View file

@ -1,113 +1,106 @@
(function () { var
window = require('window'),
_ = require('_'),
ko = require('ko'),
'use strict'; Enums = require('Common/Enums'),
Translator = require('Common/Translator'),
var PackageStore = require('Stores/Admin/Package'),
window = require('window'), Remote = require('Remote/Admin/Ajax');
_ = require('_'),
ko = require('ko'),
Enums = require('Common/Enums'), /**
Translator = require('Common/Translator'), * @constructor
*/
function PackagesAdminSettings()
{
this.packagesError = ko.observable('');
PackageStore = require('Stores/Admin/Package'), this.packages = PackageStore.packages;
Remote = require('Remote/Admin/Ajax') this.packagesReal = PackageStore.packagesReal;
; this.packagesMainUpdatable = PackageStore.packagesMainUpdatable;
/** this.packagesCurrent = this.packages.filter(function(item) {
* @constructor return item && '' !== item.installed && !item.compare;
*/ });
function PackagesAdminSettings()
{
this.packagesError = ko.observable('');
this.packages = PackageStore.packages; this.packagesAvailableForUpdate = this.packages.filter(function(item) {
this.packagesReal = PackageStore.packagesReal; return item && '' !== item.installed && !!item.compare;
this.packagesMainUpdatable = PackageStore.packagesMainUpdatable; });
this.packagesCurrent = this.packages.filter(function (item) { this.packagesAvailableForInstallation = this.packages.filter(function(item) {
return item && '' !== item.installed && !item.compare; return item && '' === item.installed;
}); });
this.packagesAvailableForUpdate = this.packages.filter(function (item) { this.visibility = ko.computed(function() {
return item && '' !== item.installed && !!item.compare; return PackageStore.packages.loading() ? 'visible' : 'hidden';
}); }, this);
}
this.packagesAvailableForInstallation = this.packages.filter(function (item) { PackagesAdminSettings.prototype.onShow = function()
return item && '' === item.installed; {
}); this.packagesError('');
};
this.visibility = ko.computed(function () { PackagesAdminSettings.prototype.onBuild = function()
return PackageStore.packages.loading() ? 'visible' : 'hidden'; {
}, this); require('App/Admin').default.reloadPackagesList();
} };
PackagesAdminSettings.prototype.onShow = function () PackagesAdminSettings.prototype.requestHelper = function(oPackage, bInstall)
{ {
this.packagesError(''); var self = this;
}; return function(sResult, oData) {
PackagesAdminSettings.prototype.onBuild = function () if (Enums.StorageResultType.Success !== sResult || !oData || !oData.Result)
{ {
require('App/Admin').default.reloadPackagesList(); if (oData && oData.ErrorCode)
};
PackagesAdminSettings.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(Translator.getNotification(oData.ErrorCode));
{
self.packagesError(Translator.getNotification(oData.ErrorCode));
}
else
{
self.packagesError(Translator.getNotification(
bInstall ? Enums.Notification.CantInstallPackage : Enums.Notification.CantDeletePackage));
}
}
_.each(self.packages(), function (item) {
if (item && oPackage && item.loading && item.loading() && oPackage.file === item.file)
{
oPackage.loading(false);
item.loading(false);
}
});
if (Enums.StorageResultType.Success === sResult && oData && oData.Result && oData.Result.Reload)
{
window.location.reload();
} }
else else
{ {
require('App/Admin').default.reloadPackagesList(); self.packagesError(Translator.getNotification(
bInstall ? Enums.Notification.CantInstallPackage : Enums.Notification.CantDeletePackage));
} }
}; }
};
PackagesAdminSettings.prototype.deletePackage = function (oPackage) _.each(self.packages(), function(item) {
{ if (item && oPackage && item.loading && item.loading() && oPackage.file === item.file)
if (oPackage) {
oPackage.loading(false);
item.loading(false);
}
});
if (Enums.StorageResultType.Success === sResult && oData && oData.Result && oData.Result.Reload)
{ {
oPackage.loading(true); window.location.reload();
Remote.packageDelete(this.requestHelper(oPackage, false), oPackage); }
else
{
require('App/Admin').default.reloadPackagesList();
} }
}; };
};
PackagesAdminSettings.prototype.installPackage = function (oPackage) PackagesAdminSettings.prototype.deletePackage = function(oPackage)
{
if (oPackage)
{ {
if (oPackage) oPackage.loading(true);
{ Remote.packageDelete(this.requestHelper(oPackage, false), oPackage);
oPackage.loading(true); }
Remote.packageInstall(this.requestHelper(oPackage, true), oPackage); };
}
};
module.exports = PackagesAdminSettings; PackagesAdminSettings.prototype.installPackage = function(oPackage)
{
if (oPackage)
{
oPackage.loading(true);
Remote.packageInstall(this.requestHelper(oPackage, true), oPackage);
}
};
}()); module.exports = PackagesAdminSettings;

View file

@ -1,119 +1,111 @@
/* global RL_COMMUNITY */ /* global RL_COMMUNITY */
(function () { var
_ = require('_'),
ko = require('ko'),
'use strict'; Enums = require('Common/Enums'),
Utils = require('Common/Utils'),
Translator = require('Common/Translator'),
var Settings = require('Storage/Settings'),
_ = require('_'),
ko = require('ko'),
Enums = require('Common/Enums'), AppStore = require('Stores/Admin/App'),
Utils = require('Common/Utils'), PluginStore = require('Stores/Admin/Plugin'),
Translator = require('Common/Translator'),
Settings = require('Storage/Settings'), Remote = require('Remote/Admin/Ajax');
AppStore = require('Stores/Admin/App'), /**
PluginStore = require('Stores/Admin/Plugin'), * @constructor
*/
function PluginsAdminSettings()
{
this.enabledPlugins = ko.observable(!!Settings.settingsGet('EnabledPlugins'));
Remote = require('Remote/Admin/Ajax') this.plugins = PluginStore.plugins;
; this.pluginsError = PluginStore.plugins.error;
/** this.community = RL_COMMUNITY || AppStore.community();
* @constructor
*/
function PluginsAdminSettings()
{
this.enabledPlugins = ko.observable(!!Settings.settingsGet('EnabledPlugins'));
this.plugins = PluginStore.plugins; this.visibility = ko.computed(function() {
this.pluginsError = PluginStore.plugins.error; return PluginStore.plugins.loading() ? 'visible' : 'hidden';
}, this);
this.community = RL_COMMUNITY || AppStore.community(); this.onPluginLoadRequest = _.bind(this.onPluginLoadRequest, this);
this.onPluginDisableRequest = _.bind(this.onPluginDisableRequest, this);
}
this.visibility = ko.computed(function () { PluginsAdminSettings.prototype.disablePlugin = function(oPlugin)
return PluginStore.plugins.loading() ? 'visible' : 'hidden'; {
}, this); oPlugin.disabled(!oPlugin.disabled());
Remote.pluginDisable(this.onPluginDisableRequest, oPlugin.name, oPlugin.disabled());
};
this.onPluginLoadRequest = _.bind(this.onPluginLoadRequest, this); PluginsAdminSettings.prototype.configurePlugin = function(oPlugin)
this.onPluginDisableRequest = _.bind(this.onPluginDisableRequest, this); {
} Remote.plugin(this.onPluginLoadRequest, oPlugin.name);
};
PluginsAdminSettings.prototype.disablePlugin = function (oPlugin) PluginsAdminSettings.prototype.onBuild = function(oDom)
{ {
oPlugin.disabled(!oPlugin.disabled()); var self = this;
Remote.pluginDisable(this.onPluginDisableRequest, oPlugin.name, oPlugin.disabled());
};
PluginsAdminSettings.prototype.configurePlugin = function (oPlugin) oDom
{ .on('click', '.e-item .configure-plugin-action', function() {
Remote.plugin(this.onPluginLoadRequest, oPlugin.name); var oPlugin = ko.dataFor(this);
}; if (oPlugin)
PluginsAdminSettings.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) {
Remote.saveAdminConfig(Utils.noop, {
'EnabledPlugins': bValue ? '1' : '0'
});
});
};
PluginsAdminSettings.prototype.onShow = function ()
{
PluginStore.plugins.error('');
require('App/Admin').default.reloadPluginList();
};
PluginsAdminSettings.prototype.onPluginLoadRequest = function (sResult, oData)
{
if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
{
require('Knoin/Knoin').showScreenPopup(require('View/Popup/Plugin'), [oData.Result]);
}
};
PluginsAdminSettings.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) self.configurePlugin(oPlugin);
{ }
PluginStore.plugins.error(oData.ErrorMessage); })
} .on('click', '.e-item .disabled-plugin', function() {
else var oPlugin = ko.dataFor(this);
{ if (oPlugin)
PluginStore.plugins.error(Translator.getNotification(oData.ErrorCode)); {
} self.disablePlugin(oPlugin);
}
});
this.enabledPlugins.subscribe(function(bValue) {
Remote.saveAdminConfig(Utils.noop, {
'EnabledPlugins': bValue ? '1' : '0'
});
});
};
PluginsAdminSettings.prototype.onShow = function()
{
PluginStore.plugins.error('');
require('App/Admin').default.reloadPluginList();
};
PluginsAdminSettings.prototype.onPluginLoadRequest = function(sResult, oData)
{
if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
{
require('Knoin/Knoin').showScreenPopup(require('View/Popup/Plugin'), [oData.Result]);
}
};
PluginsAdminSettings.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)
{
PluginStore.plugins.error(oData.ErrorMessage);
}
else
{
PluginStore.plugins.error(Translator.getNotification(oData.ErrorCode));
} }
} }
}
require('App/Admin').default.reloadPluginList(); require('App/Admin').default.reloadPluginList();
}; };
module.exports = PluginsAdminSettings; module.exports = PluginsAdminSettings;
}());

View file

@ -1,187 +1,180 @@
(function () { var
_ = require('_'),
ko = require('ko'),
'use strict'; Enums = require('Common/Enums'),
Utils = require('Common/Utils'),
Links = require('Common/Links'),
var AppAdminStore = require('Stores/Admin/App'),
_ = require('_'), CapaAdminStore = require('Stores/Admin/Capa'),
ko = require('ko'),
Enums = require('Common/Enums'), Settings = require('Storage/Settings'),
Utils = require('Common/Utils'), Remote = require('Remote/Admin/Ajax');
Links = require('Common/Links'),
AppAdminStore = require('Stores/Admin/App'), /**
CapaAdminStore = require('Stores/Admin/Capa'), * @constructor
*/
function SecurityAdminSettings()
{
this.useLocalProxyForExternalImages = AppAdminStore.useLocalProxyForExternalImages;
Settings = require('Storage/Settings'), this.weakPassword = AppAdminStore.weakPassword;
Remote = require('Remote/Admin/Ajax')
;
/** this.capaOpenPGP = CapaAdminStore.openPGP;
* @constructor
*/
function SecurityAdminSettings()
{
this.useLocalProxyForExternalImages = AppAdminStore.useLocalProxyForExternalImages;
this.weakPassword = AppAdminStore.weakPassword; this.capaTwoFactorAuth = CapaAdminStore.twoFactorAuth;
this.capaTwoFactorAuthForce = CapaAdminStore.twoFactorAuthForce;
this.capaOpenPGP = CapaAdminStore.openPGP; this.capaTwoFactorAuth.subscribe(function(bValue) {
if (!bValue)
this.capaTwoFactorAuth = CapaAdminStore.twoFactorAuth;
this.capaTwoFactorAuthForce = CapaAdminStore.twoFactorAuthForce;
this.capaTwoFactorAuth.subscribe(function (bValue) {
if (!bValue)
{
this.capaTwoFactorAuthForce(false);
}
}, this);
this.verifySslCertificate = ko.observable(!!Settings.settingsGet('VerifySslCertificate'));
this.allowSelfSigned = ko.observable(!!Settings.settingsGet('AllowSelfSigned'));
this.verifySslCertificate.subscribe(function (bValue) {
if (!bValue)
{
this.allowSelfSigned(true);
}
}, this);
this.adminLogin = ko.observable(Settings.settingsGet('AdminLogin'));
this.adminLoginError = ko.observable(false);
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.adminLogin.subscribe(function () {
this.adminLoginError(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 ('' === Utils.trim(this.adminLogin()))
{
this.adminLoginError(true);
return false;
}
if (this.adminPasswordNew() !== this.adminPasswordNew2())
{
this.adminPasswordNewError(true);
return false;
}
this.adminPasswordUpdateError(false);
this.adminPasswordUpdateSuccess(false);
Remote.saveNewAdminPassword(this.onNewAdminPasswordResponse, {
'Login': this.adminLogin(),
'Password': this.adminPassword(),
'NewPassword': this.adminPasswordNew()
});
}, function () {
return '' !== Utils.trim(this.adminLogin()) && '' !== this.adminPassword();
});
this.onNewAdminPasswordResponse = _.bind(this.onNewAdminPasswordResponse, this);
}
SecurityAdminSettings.prototype.onNewAdminPasswordResponse = function (sResult, oData)
{
if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
{ {
this.adminPassword(''); this.capaTwoFactorAuthForce(false);
this.adminPasswordNew('');
this.adminPasswordNew2('');
this.adminPasswordUpdateSuccess(true);
this.weakPassword(!!oData.Result.Weak);
} }
else }, this);
this.verifySslCertificate = ko.observable(!!Settings.settingsGet('VerifySslCertificate'));
this.allowSelfSigned = ko.observable(!!Settings.settingsGet('AllowSelfSigned'));
this.verifySslCertificate.subscribe(function(bValue) {
if (!bValue)
{ {
this.adminPasswordUpdateError(true); this.allowSelfSigned(true);
} }
}; }, this);
SecurityAdminSettings.prototype.onBuild = function () this.adminLogin = ko.observable(Settings.settingsGet('AdminLogin'));
{ this.adminLoginError = ko.observable(false);
this.capaOpenPGP.subscribe(function (bValue) { this.adminPassword = ko.observable('');
Remote.saveAdminConfig(Utils.noop, { this.adminPasswordNew = ko.observable('');
'CapaOpenPGP': bValue ? '1' : '0' 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.adminLogin.subscribe(function() {
this.adminLoginError(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 ('' === Utils.trim(this.adminLogin()))
{
this.adminLoginError(true);
return false;
}
if (this.adminPasswordNew() !== this.adminPasswordNew2())
{
this.adminPasswordNewError(true);
return false;
}
this.adminPasswordUpdateError(false);
this.adminPasswordUpdateSuccess(false);
Remote.saveNewAdminPassword(this.onNewAdminPasswordResponse, {
'Login': this.adminLogin(),
'Password': this.adminPassword(),
'NewPassword': this.adminPasswordNew()
}); });
this.capaTwoFactorAuth.subscribe(function (bValue) { }, function() {
Remote.saveAdminConfig(Utils.noop, { return '' !== Utils.trim(this.adminLogin()) && '' !== this.adminPassword();
'CapaTwoFactorAuth': bValue ? '1' : '0' });
});
});
this.capaTwoFactorAuthForce.subscribe(function (bValue) { this.onNewAdminPasswordResponse = _.bind(this.onNewAdminPasswordResponse, this);
Remote.saveAdminConfig(Utils.noop, { }
'CapaTwoFactorAuthForce': bValue ? '1' : '0'
});
});
this.useLocalProxyForExternalImages.subscribe(function (bValue) { SecurityAdminSettings.prototype.onNewAdminPasswordResponse = function(sResult, oData)
Remote.saveAdminConfig(null, { {
'UseLocalProxyForExternalImages': bValue ? '1' : '0' if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
});
});
this.verifySslCertificate.subscribe(function (bValue) {
Remote.saveAdminConfig(null, {
'VerifySslCertificate': bValue ? '1' : '0'
});
});
this.allowSelfSigned.subscribe(function (bValue) {
Remote.saveAdminConfig(null, {
'AllowSelfSigned': bValue ? '1' : '0'
});
});
};
SecurityAdminSettings.prototype.onHide = function ()
{ {
this.adminPassword(''); this.adminPassword('');
this.adminPasswordNew(''); this.adminPasswordNew('');
this.adminPasswordNew2(''); this.adminPasswordNew2('');
};
/** this.adminPasswordUpdateSuccess(true);
* @return {string}
*/ this.weakPassword(!!oData.Result.Weak);
SecurityAdminSettings.prototype.phpInfoLink = function () }
else
{ {
return Links.phpInfo(); this.adminPasswordUpdateError(true);
}; }
};
module.exports = SecurityAdminSettings; SecurityAdminSettings.prototype.onBuild = function()
{
this.capaOpenPGP.subscribe(function(bValue) {
Remote.saveAdminConfig(Utils.noop, {
'CapaOpenPGP': bValue ? '1' : '0'
});
});
}()); this.capaTwoFactorAuth.subscribe(function(bValue) {
Remote.saveAdminConfig(Utils.noop, {
'CapaTwoFactorAuth': bValue ? '1' : '0'
});
});
this.capaTwoFactorAuthForce.subscribe(function(bValue) {
Remote.saveAdminConfig(Utils.noop, {
'CapaTwoFactorAuthForce': bValue ? '1' : '0'
});
});
this.useLocalProxyForExternalImages.subscribe(function(bValue) {
Remote.saveAdminConfig(null, {
'UseLocalProxyForExternalImages': bValue ? '1' : '0'
});
});
this.verifySslCertificate.subscribe(function(bValue) {
Remote.saveAdminConfig(null, {
'VerifySslCertificate': bValue ? '1' : '0'
});
});
this.allowSelfSigned.subscribe(function(bValue) {
Remote.saveAdminConfig(null, {
'AllowSelfSigned': bValue ? '1' : '0'
});
});
};
SecurityAdminSettings.prototype.onHide = function()
{
this.adminPassword('');
this.adminPasswordNew('');
this.adminPasswordNew2('');
};
/**
* @returns {string}
*/
SecurityAdminSettings.prototype.phpInfoLink = function()
{
return Links.phpInfo();
};
module.exports = SecurityAdminSettings;

View file

@ -1,183 +1,174 @@
(function () { var
_ = require('_'),
ko = require('ko'),
'use strict'; Enums = require('Common/Enums'),
Utils = require('Common/Utils');
/**
* @constructor
*/
function SocialAdminSettings()
{
var SocialStore = require('Stores/Social');
this.googleEnable = SocialStore.google.enabled;
this.googleEnableAuth = SocialStore.google.capa.auth;
this.googleEnableAuthFast = SocialStore.google.capa.authFast;
this.googleEnableDrive = SocialStore.google.capa.drive;
this.googleEnablePreview = SocialStore.google.capa.preview;
this.googleEnableRequireClientSettings = SocialStore.google.require.clientSettings;
this.googleEnableRequireApiKey = SocialStore.google.require.apiKeySettings;
this.googleClientID = SocialStore.google.clientID;
this.googleClientSecret = SocialStore.google.clientSecret;
this.googleApiKey = SocialStore.google.apiKey;
this.googleTrigger1 = ko.observable(Enums.SaveSettingsStep.Idle);
this.googleTrigger2 = ko.observable(Enums.SaveSettingsStep.Idle);
this.googleTrigger3 = ko.observable(Enums.SaveSettingsStep.Idle);
this.facebookSupported = SocialStore.facebook.supported;
this.facebookEnable = SocialStore.facebook.enabled;
this.facebookAppID = SocialStore.facebook.appID;
this.facebookAppSecret = SocialStore.facebook.appSecret;
this.facebookTrigger1 = ko.observable(Enums.SaveSettingsStep.Idle);
this.facebookTrigger2 = ko.observable(Enums.SaveSettingsStep.Idle);
this.twitterEnable = SocialStore.twitter.enabled;
this.twitterConsumerKey = SocialStore.twitter.consumerKey;
this.twitterConsumerSecret = SocialStore.twitter.consumerSecret;
this.twitterTrigger1 = ko.observable(Enums.SaveSettingsStep.Idle);
this.twitterTrigger2 = ko.observable(Enums.SaveSettingsStep.Idle);
this.dropboxEnable = SocialStore.dropbox.enabled;
this.dropboxApiKey = SocialStore.dropbox.apiKey;
this.dropboxTrigger1 = ko.observable(Enums.SaveSettingsStep.Idle);
}
SocialAdminSettings.prototype.onBuild = function()
{
var var
_ = require('_'), self = this,
ko = require('ko'), Remote = require('Remote/Admin/Ajax');
Enums = require('Common/Enums'), _.delay(function() {
Utils = require('Common/Utils')
;
/**
* @constructor
*/
function SocialAdminSettings()
{
var SocialStore = require('Stores/Social');
this.googleEnable = SocialStore.google.enabled;
this.googleEnableAuth = SocialStore.google.capa.auth;
this.googleEnableAuthFast = SocialStore.google.capa.authFast;
this.googleEnableDrive = SocialStore.google.capa.drive;
this.googleEnablePreview = SocialStore.google.capa.preview;
this.googleEnableRequireClientSettings = SocialStore.google.require.clientSettings;
this.googleEnableRequireApiKey = SocialStore.google.require.apiKeySettings;
this.googleClientID = SocialStore.google.clientID;
this.googleClientSecret = SocialStore.google.clientSecret;
this.googleApiKey = SocialStore.google.apiKey;
this.googleTrigger1 = ko.observable(Enums.SaveSettingsStep.Idle);
this.googleTrigger2 = ko.observable(Enums.SaveSettingsStep.Idle);
this.googleTrigger3 = ko.observable(Enums.SaveSettingsStep.Idle);
this.facebookSupported = SocialStore.facebook.supported;
this.facebookEnable = SocialStore.facebook.enabled;
this.facebookAppID = SocialStore.facebook.appID;
this.facebookAppSecret = SocialStore.facebook.appSecret;
this.facebookTrigger1 = ko.observable(Enums.SaveSettingsStep.Idle);
this.facebookTrigger2 = ko.observable(Enums.SaveSettingsStep.Idle);
this.twitterEnable = SocialStore.twitter.enabled;
this.twitterConsumerKey = SocialStore.twitter.consumerKey;
this.twitterConsumerSecret = SocialStore.twitter.consumerSecret;
this.twitterTrigger1 = ko.observable(Enums.SaveSettingsStep.Idle);
this.twitterTrigger2 = ko.observable(Enums.SaveSettingsStep.Idle);
this.dropboxEnable = SocialStore.dropbox.enabled;
this.dropboxApiKey = SocialStore.dropbox.apiKey;
this.dropboxTrigger1 = ko.observable(Enums.SaveSettingsStep.Idle);
}
SocialAdminSettings.prototype.onBuild = function ()
{
var var
self = this, f1 = Utils.settingsSaveHelperSimpleFunction(self.facebookTrigger1, self),
Remote = require('Remote/Admin/Ajax') 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);
_.delay(function () { self.facebookEnable.subscribe(function(bValue) {
if (self.facebookSupported())
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())
{
Remote.saveAdminConfig(Utils.noop, {
'FacebookEnable': bValue ? '1' : '0'
});
}
});
self.facebookAppID.subscribe(function (sValue) {
if (self.facebookSupported())
{
Remote.saveAdminConfig(f1, {
'FacebookAppID': Utils.trim(sValue)
});
}
});
self.facebookAppSecret.subscribe(function (sValue) {
if (self.facebookSupported())
{
Remote.saveAdminConfig(f2, {
'FacebookAppSecret': Utils.trim(sValue)
});
}
});
self.twitterEnable.subscribe(function (bValue) {
Remote.saveAdminConfig(Utils.noop, { Remote.saveAdminConfig(Utils.noop, {
'TwitterEnable': bValue ? '1' : '0' 'FacebookEnable': bValue ? '1' : '0'
}); });
}); }
});
self.twitterConsumerKey.subscribe(function (sValue) { self.facebookAppID.subscribe(function(sValue) {
Remote.saveAdminConfig(f3, { if (self.facebookSupported())
'TwitterConsumerKey': Utils.trim(sValue) {
Remote.saveAdminConfig(f1, {
'FacebookAppID': Utils.trim(sValue)
}); });
}); }
});
self.twitterConsumerSecret.subscribe(function (sValue) { self.facebookAppSecret.subscribe(function(sValue) {
Remote.saveAdminConfig(f4, { if (self.facebookSupported())
'TwitterConsumerSecret': Utils.trim(sValue) {
Remote.saveAdminConfig(f2, {
'FacebookAppSecret': Utils.trim(sValue)
}); });
}
});
self.twitterEnable.subscribe(function(bValue) {
Remote.saveAdminConfig(Utils.noop, {
'TwitterEnable': bValue ? '1' : '0'
}); });
});
self.googleEnable.subscribe(function (bValue) { self.twitterConsumerKey.subscribe(function(sValue) {
Remote.saveAdminConfig(Utils.noop, { Remote.saveAdminConfig(f3, {
'GoogleEnable': bValue ? '1' : '0' 'TwitterConsumerKey': Utils.trim(sValue)
});
}); });
});
self.googleEnableAuth.subscribe(function (bValue) { self.twitterConsumerSecret.subscribe(function(sValue) {
Remote.saveAdminConfig(Utils.noop, { Remote.saveAdminConfig(f4, {
'GoogleEnableAuth': bValue ? '1' : '0' 'TwitterConsumerSecret': Utils.trim(sValue)
});
}); });
});
self.googleEnableDrive.subscribe(function (bValue) { self.googleEnable.subscribe(function(bValue) {
Remote.saveAdminConfig(Utils.noop, { Remote.saveAdminConfig(Utils.noop, {
'GoogleEnableDrive': bValue ? '1' : '0' 'GoogleEnable': bValue ? '1' : '0'
});
}); });
});
self.googleEnablePreview.subscribe(function (bValue) { self.googleEnableAuth.subscribe(function(bValue) {
Remote.saveAdminConfig(Utils.noop, { Remote.saveAdminConfig(Utils.noop, {
'GoogleEnablePreview': bValue ? '1' : '0' 'GoogleEnableAuth': bValue ? '1' : '0'
});
}); });
});
self.googleClientID.subscribe(function (sValue) { self.googleEnableDrive.subscribe(function(bValue) {
Remote.saveAdminConfig(f5, { Remote.saveAdminConfig(Utils.noop, {
'GoogleClientID': Utils.trim(sValue) 'GoogleEnableDrive': bValue ? '1' : '0'
});
}); });
});
self.googleClientSecret.subscribe(function (sValue) { self.googleEnablePreview.subscribe(function(bValue) {
Remote.saveAdminConfig(f6, { Remote.saveAdminConfig(Utils.noop, {
'GoogleClientSecret': Utils.trim(sValue) 'GoogleEnablePreview': bValue ? '1' : '0'
});
}); });
});
self.googleApiKey.subscribe(function (sValue) { self.googleClientID.subscribe(function(sValue) {
Remote.saveAdminConfig(f7, { Remote.saveAdminConfig(f5, {
'GoogleApiKey': Utils.trim(sValue) 'GoogleClientID': Utils.trim(sValue)
});
}); });
});
self.dropboxEnable.subscribe(function (bValue) { self.googleClientSecret.subscribe(function(sValue) {
Remote.saveAdminConfig(Utils.noop, { Remote.saveAdminConfig(f6, {
'DropboxEnable': bValue ? '1' : '0' 'GoogleClientSecret': Utils.trim(sValue)
});
}); });
});
self.dropboxApiKey.subscribe(function (sValue) { self.googleApiKey.subscribe(function(sValue) {
Remote.saveAdminConfig(f8, { Remote.saveAdminConfig(f7, {
'DropboxApiKey': Utils.trim(sValue) 'GoogleApiKey': Utils.trim(sValue)
});
}); });
});
}, 50); self.dropboxEnable.subscribe(function(bValue) {
}; Remote.saveAdminConfig(Utils.noop, {
'DropboxEnable': bValue ? '1' : '0'
});
});
module.exports = SocialAdminSettings; self.dropboxApiKey.subscribe(function(sValue) {
Remote.saveAdminConfig(f8, {
'DropboxApiKey': Utils.trim(sValue)
});
});
}()); }, 50);
};
module.exports = SocialAdminSettings;

View file

@ -1,163 +1,154 @@
(function () { var
window = require('window'),
_ = require('_'),
ko = require('ko'),
'use strict'; Enums = require('Common/Enums'),
Links = require('Common/Links'),
var AccountStore = require('Stores/User/Account'),
window = require('window'), IdentityStore = require('Stores/User/Identity'),
_ = require('_'),
ko = require('ko'),
Enums = require('Common/Enums'), Settings = require('Storage/Settings'),
Links = require('Common/Links'), Remote = require('Remote/User/Ajax');
AccountStore = require('Stores/User/Account'), /**
IdentityStore = require('Stores/User/Identity'), * @constructor
*/
function AccountsUserSettings()
{
this.allowAdditionalAccount = Settings.capa(Enums.Capa.AdditionalAccounts);
this.allowIdentities = Settings.capa(Enums.Capa.Identities);
Settings = require('Storage/Settings'), this.accounts = AccountStore.accounts;
Remote = require('Remote/User/Ajax') this.identities = IdentityStore.identities;
;
/** this.accountForDeletion = ko.observable(null).deleteAccessHelper();
* @constructor this.identityForDeletion = ko.observable(null).deleteAccessHelper();
*/ }
function AccountsUserSettings()
AccountsUserSettings.prototype.scrollableOptions = function(sWrapper)
{
return {
handle: '.drag-handle',
containment: sWrapper || 'parent',
axis: 'y'
};
};
AccountsUserSettings.prototype.addNewAccount = function()
{
require('Knoin/Knoin').showScreenPopup(require('View/Popup/Account'));
};
AccountsUserSettings.prototype.editAccount = function(oAccountItem)
{
if (oAccountItem && oAccountItem.canBeEdit())
{ {
this.allowAdditionalAccount = Settings.capa(Enums.Capa.AdditionalAccounts); require('Knoin/Knoin').showScreenPopup(require('View/Popup/Account'), [oAccountItem]);
this.allowIdentities = Settings.capa(Enums.Capa.Identities);
this.accounts = AccountStore.accounts;
this.identities = IdentityStore.identities;
this.accountForDeletion = ko.observable(null).deleteAccessHelper();
this.identityForDeletion = ko.observable(null).deleteAccessHelper();
} }
};
AccountsUserSettings.prototype.scrollableOptions = function (sWrapper) AccountsUserSettings.prototype.addNewIdentity = function()
{ {
return { require('Knoin/Knoin').showScreenPopup(require('View/Popup/Identity'));
handle: '.drag-handle', };
containment: sWrapper || 'parent',
axis: 'y'
};
};
AccountsUserSettings.prototype.addNewAccount = function () AccountsUserSettings.prototype.editIdentity = function(oIdentity)
{ {
require('Knoin/Knoin').showScreenPopup(require('View/Popup/Account')); require('Knoin/Knoin').showScreenPopup(require('View/Popup/Identity'), [oIdentity]);
}; };
AccountsUserSettings.prototype.editAccount = function (oAccountItem) /**
* @param {AccountModel} oAccountToRemove
*/
AccountsUserSettings.prototype.deleteAccount = function(oAccountToRemove)
{
if (oAccountToRemove && oAccountToRemove.deleteAccess())
{ {
if (oAccountItem && oAccountItem.canBeEdit()) this.accountForDeletion(null);
var
kn = require('Knoin/Knoin'),
fRemoveAccount = function(oAccount) {
return oAccountToRemove === oAccount;
};
if (oAccountToRemove)
{ {
require('Knoin/Knoin').showScreenPopup(require('View/Popup/Account'), [oAccountItem]); this.accounts.remove(fRemoveAccount);
}
};
AccountsUserSettings.prototype.addNewIdentity = function () Remote.accountDelete(function(sResult, oData) {
{
require('Knoin/Knoin').showScreenPopup(require('View/Popup/Identity'));
};
AccountsUserSettings.prototype.editIdentity = function (oIdentity) if (Enums.StorageResultType.Success === sResult && oData &&
{ oData.Result && oData.Reload)
require('Knoin/Knoin').showScreenPopup(require('View/Popup/Identity'), [oIdentity]); {
}; kn.routeOff();
kn.setHash(Links.root(), true);
kn.routeOff();
/** _.defer(function() {
* @param {AccountModel} oAccountToRemove window.location.reload();
*/ });
AccountsUserSettings.prototype.deleteAccount = function (oAccountToRemove)
{
if (oAccountToRemove && oAccountToRemove.deleteAccess())
{
this.accountForDeletion(null);
var
kn = require('Knoin/Knoin'),
fRemoveAccount = function (oAccount) {
return oAccountToRemove === oAccount;
} }
; else
{
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(Links.root(), true);
kn.routeOff();
_.defer(function () {
window.location.reload();
});
}
else
{
require('App/User').default.accountsAndIdentities();
}
}, oAccountToRemove.email);
}
}
};
/**
* @param {IdentityModel} oIdentityToRemove
*/
AccountsUserSettings.prototype.deleteIdentity = function (oIdentityToRemove)
{
if (oIdentityToRemove && oIdentityToRemove.deleteAccess())
{
this.identityForDeletion(null);
if (oIdentityToRemove)
{
IdentityStore.identities.remove(function (oIdentity) {
return oIdentityToRemove === oIdentity;
});
Remote.identityDelete(function () {
require('App/User').default.accountsAndIdentities(); require('App/User').default.accountsAndIdentities();
}, oIdentityToRemove.id); }
}
}, oAccountToRemove.email);
} }
}; }
};
AccountsUserSettings.prototype.accountsAndIdentitiesAfterMove = function () /**
* @param {IdentityModel} oIdentityToRemove
*/
AccountsUserSettings.prototype.deleteIdentity = function(oIdentityToRemove)
{
if (oIdentityToRemove && oIdentityToRemove.deleteAccess())
{ {
Remote.accountsAndIdentitiesSortOrder(null, this.identityForDeletion(null);
AccountStore.accountsEmails.peek(), IdentityStore.identitiesIDS.peek());
};
AccountsUserSettings.prototype.onBuild = function (oDom) if (oIdentityToRemove)
{ {
var self = this; IdentityStore.identities.remove(function(oIdentity) {
return oIdentityToRemove === oIdentity;
});
oDom Remote.identityDelete(function() {
.on('click', '.accounts-list .account-item .e-action', function () { require('App/User').default.accountsAndIdentities();
var oAccountItem = ko.dataFor(this); }, oIdentityToRemove.id);
if (oAccountItem) }
{ }
self.editAccount(oAccountItem); };
}
})
.on('click', '.identities-list .identity-item .e-action', function () {
var oIdentityItem = ko.dataFor(this);
if (oIdentityItem)
{
self.editIdentity(oIdentityItem);
}
})
;
};
module.exports = AccountsUserSettings; AccountsUserSettings.prototype.accountsAndIdentitiesAfterMove = function()
{
Remote.accountsAndIdentitiesSortOrder(null,
AccountStore.accountsEmails.peek(), IdentityStore.identitiesIDS.peek());
};
}()); AccountsUserSettings.prototype.onBuild = function(oDom)
{
var self = this;
oDom
.on('click', '.accounts-list .account-item .e-action', function() {
var oAccountItem = ko.dataFor(this);
if (oAccountItem)
{
self.editAccount(oAccountItem);
}
})
.on('click', '.identities-list .identity-item .e-action', function() {
var oIdentityItem = ko.dataFor(this);
if (oIdentityItem)
{
self.editIdentity(oIdentityItem);
}
});
};
module.exports = AccountsUserSettings;

View file

@ -1,124 +1,117 @@
(function () { var
_ = require('_'),
ko = require('ko'),
'use strict'; Enums = require('Common/Enums'),
Utils = require('Common/Utils'),
Translator = require('Common/Translator'),
var Remote = require('Remote/User/Ajax');
_ = require('_'),
ko = require('ko'),
Enums = require('Common/Enums'), /**
Utils = require('Common/Utils'), * @constructor
Translator = require('Common/Translator'), */
function ChangePasswordUserSettings()
{
this.changeProcess = ko.observable(false);
Remote = require('Remote/User/Ajax') this.errorDescription = ko.observable('');
; this.passwordMismatch = ko.observable(false);
this.passwordUpdateError = ko.observable(false);
this.passwordUpdateSuccess = ko.observable(false);
/** this.currentPassword = ko.observable('');
* @constructor this.currentPassword.error = ko.observable(false);
*/ this.newPassword = ko.observable('');
function ChangePasswordUserSettings() this.newPassword2 = ko.observable('');
{
this.changeProcess = ko.observable(false);
this.errorDescription = ko.observable(''); this.currentPassword.subscribe(function() {
this.passwordMismatch = ko.observable(false); this.passwordUpdateError(false);
this.passwordUpdateError = ko.observable(false); this.passwordUpdateSuccess(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(Translator.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);
}
ChangePasswordUserSettings.prototype.onHide = function ()
{
this.changeProcess(false);
this.currentPassword('');
this.newPassword('');
this.newPassword2('');
this.errorDescription('');
this.passwordMismatch(false);
this.currentPassword.error(false); this.currentPassword.error(false);
}; }, this);
ChangePasswordUserSettings.prototype.onChangePasswordResponse = function (sResult, oData) this.newPassword.subscribe(function() {
{ this.passwordUpdateError(false);
this.changeProcess(false); this.passwordUpdateSuccess(false);
this.passwordMismatch(false); this.passwordMismatch(false);
this.errorDescription(''); }, this);
this.currentPassword.error(false);
if (Enums.StorageResultType.Success === sResult && oData && oData.Result) 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.currentPassword(''); this.passwordMismatch(true);
this.newPassword(''); this.errorDescription(Translator.i18n('SETTINGS_CHANGE_PASSWORD/ERROR_PASSWORD_MISMATCH'));
this.newPassword2('');
this.passwordUpdateSuccess(true);
this.currentPassword.error(false);
require('App/User').default.setClientSideToken(oData.Result);
} }
else else
{ {
if (oData && Enums.Notification.CurrentPasswordIncorrect === oData.ErrorCode) this.changeProcess(true);
{
this.currentPassword.error(true);
}
this.passwordUpdateError(true); this.passwordUpdateError(false);
this.errorDescription( this.passwordUpdateSuccess(false);
Translator.getNotificationFromResponse(oData, Enums.Notification.CouldNotSaveNewPassword)); this.currentPassword.error(false);
this.passwordMismatch(false);
this.errorDescription('');
Remote.changePassword(this.onChangePasswordResponse, this.currentPassword(), this.newPassword());
} }
};
module.exports = ChangePasswordUserSettings; }, function() {
return !this.changeProcess() && '' !== this.currentPassword() &&
'' !== this.newPassword() && '' !== this.newPassword2();
});
}()); this.onChangePasswordResponse = _.bind(this.onChangePasswordResponse, this);
}
ChangePasswordUserSettings.prototype.onHide = function()
{
this.changeProcess(false);
this.currentPassword('');
this.newPassword('');
this.newPassword2('');
this.errorDescription('');
this.passwordMismatch(false);
this.currentPassword.error(false);
};
ChangePasswordUserSettings.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);
require('App/User').default.setClientSideToken(oData.Result);
}
else
{
if (oData && Enums.Notification.CurrentPasswordIncorrect === oData.ErrorCode)
{
this.currentPassword.error(true);
}
this.passwordUpdateError(true);
this.errorDescription(
Translator.getNotificationFromResponse(oData, Enums.Notification.CouldNotSaveNewPassword));
}
};
module.exports = ChangePasswordUserSettings;

View file

@ -1,58 +1,51 @@
(function () { var
ko = require('ko'),
'use strict'; AppStore = require('Stores/User/App'),
ContactStore = require('Stores/User/Contact'),
var Remote = require('Remote/User/Ajax');
ko = require('ko'),
AppStore = require('Stores/User/App'), /**
ContactStore = require('Stores/User/Contact'), * @constructor
*/
function ContactsUserSettings()
{
this.contactsAutosave = AppStore.contactsAutosave;
Remote = require('Remote/User/Ajax') this.allowContactsSync = ContactStore.allowContactsSync;
; this.enableContactsSync = ContactStore.enableContactsSync;
this.contactsSyncUrl = ContactStore.contactsSyncUrl;
this.contactsSyncUser = ContactStore.contactsSyncUser;
this.contactsSyncPass = ContactStore.contactsSyncPass;
/** this.saveTrigger = ko.computed(function() {
* @constructor return [
*/ this.enableContactsSync() ? '1' : '0',
function ContactsUserSettings() this.contactsSyncUrl(),
{ this.contactsSyncUser(),
this.contactsAutosave = AppStore.contactsAutosave; this.contactsSyncPass()
].join('|');
}, this).extend({'throttle': 500});
}
this.allowContactsSync = ContactStore.allowContactsSync; ContactsUserSettings.prototype.onBuild = function()
this.enableContactsSync = ContactStore.enableContactsSync; {
this.contactsSyncUrl = ContactStore.contactsSyncUrl; this.contactsAutosave.subscribe(function(bValue) {
this.contactsSyncUser = ContactStore.contactsSyncUser; Remote.saveSettings(null, {
this.contactsSyncPass = ContactStore.contactsSyncPass; 'ContactsAutosave': bValue ? '1' : '0'
this.saveTrigger = ko.computed(function () {
return [
this.enableContactsSync() ? '1' : '0',
this.contactsSyncUrl(),
this.contactsSyncUser(),
this.contactsSyncPass()
].join('|');
}, this).extend({'throttle': 500});
}
ContactsUserSettings.prototype.onBuild = function ()
{
this.contactsAutosave.subscribe(function (bValue) {
Remote.saveSettings(null, {
'ContactsAutosave': bValue ? '1' : '0'
});
}); });
});
this.saveTrigger.subscribe(function () { this.saveTrigger.subscribe(function() {
Remote.saveContactsSyncData(null, Remote.saveContactsSyncData(null,
this.enableContactsSync(), this.enableContactsSync(),
this.contactsSyncUrl(), this.contactsSyncUrl(),
this.contactsSyncUser(), this.contactsSyncUser(),
this.contactsSyncPass() this.contactsSyncPass()
); );
}, this); }, this);
}; };
module.exports = ContactsUserSettings; module.exports = ContactsUserSettings;
}());

View file

@ -1,246 +1,234 @@
(function () { var
ko = require('ko'),
_ = require('_'),
'use strict'; Enums = require('Common/Enums'),
Utils = require('Common/Utils'),
Translator = require('Common/Translator'),
var FilterStore = require('Stores/User/Filter'),
ko = require('ko'),
_ = require('_'),
Enums = require('Common/Enums'), Remote = require('Remote/User/Ajax');
Utils = require('Common/Utils'),
Translator = require('Common/Translator'),
FilterStore = require('Stores/User/Filter'), /**
* @constructor
*/
function FiltersUserSettings()
{
var self = this;
Remote = require('Remote/User/Ajax') this.modules = FilterStore.modules;
; this.filters = FilterStore.filters;
/** this.inited = ko.observable(false);
* @constructor this.serverError = ko.observable(false);
*/ this.serverErrorDesc = ko.observable('');
function FiltersUserSettings() this.haveChanges = ko.observable(false);
{
var self = this;
this.modules = FilterStore.modules; this.saveErrorText = ko.observable('');
this.filters = FilterStore.filters;
this.inited = ko.observable(false); this.filters.subscribe(Utils.windowResizeCallback);
this.serverError = ko.observable(false);
this.serverErrorDesc = ko.observable('');
this.haveChanges = ko.observable(false);
this.saveErrorText = ko.observable(''); this.serverError.subscribe(function(bValue) {
if (!bValue)
this.filters.subscribe(Utils.windowResizeCallback);
this.serverError.subscribe(function (bValue) {
if (!bValue)
{
this.serverErrorDesc('');
}
}, this);
this.filterRaw = FilterStore.raw;
this.filterRaw.capa = FilterStore.capa;
this.filterRaw.active = ko.observable(false);
this.filterRaw.allow = ko.observable(false);
this.filterRaw.error = ko.observable(false);
this.filterForDeletion = ko.observable(null).extend({'falseTimeout': 3000}).extend(
{'toggleSubscribeProperty': [this, 'deleteAccess']});
this.saveChanges = Utils.createCommand(this, function () {
if (!this.filters.saving())
{
if (this.filterRaw.active() && '' === Utils.trim(this.filterRaw()))
{
this.filterRaw.error(true);
return false;
}
this.filters.saving(true);
this.saveErrorText('');
Remote.filtersSave(function (sResult, oData) {
self.filters.saving(false);
if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
{
self.haveChanges(false);
self.updateList();
}
else if (oData && oData.ErrorCode)
{
self.saveErrorText(oData.ErrorMessageAdditional || Translator.getNotification(oData.ErrorCode));
}
else
{
self.saveErrorText(Translator.getNotification(Enums.Notification.CantSaveFilters));
}
}, this.filters(), this.filterRaw(), this.filterRaw.active());
}
return true;
}, function () {
return this.haveChanges();
});
this.filters.subscribe(function () {
this.haveChanges(true);
}, this);
this.filterRaw.subscribe(function () {
this.haveChanges(true);
this.filterRaw.error(false);
}, this);
this.haveChanges.subscribe(function () {
this.saveErrorText('');
}, this);
this.filterRaw.active.subscribe(function () {
this.haveChanges(true);
this.filterRaw.error(false);
}, this);
}
FiltersUserSettings.prototype.scrollableOptions = function (sWrapper)
{
return {
handle: '.drag-handle',
containment: sWrapper || 'parent',
axis: 'y'
};
};
FiltersUserSettings.prototype.updateList = function ()
{
var
self = this,
FilterModel = require('Model/Filter')
;
if (!this.filters.loading())
{ {
this.filters.loading(true); this.serverErrorDesc('');
}
}, this);
Remote.filtersGet(function (sResult, oData) { this.filterRaw = FilterStore.raw;
this.filterRaw.capa = FilterStore.capa;
this.filterRaw.active = ko.observable(false);
this.filterRaw.allow = ko.observable(false);
this.filterRaw.error = ko.observable(false);
self.filters.loading(false); this.filterForDeletion = ko.observable(null).extend({'falseTimeout': 3000}).extend(
self.serverError(false); {'toggleSubscribeProperty': [this, 'deleteAccess']});
if (Enums.StorageResultType.Success === sResult && oData && this.saveChanges = Utils.createCommand(this, function() {
oData.Result && Utils.isArray(oData.Result.Filters))
if (!this.filters.saving())
{
if (this.filterRaw.active() && '' === Utils.trim(this.filterRaw()))
{
this.filterRaw.error(true);
return false;
}
this.filters.saving(true);
this.saveErrorText('');
Remote.filtersSave(function(sResult, oData) {
self.filters.saving(false);
if (Enums.StorageResultType.Success === sResult && oData && oData.Result)
{ {
self.inited(true); self.haveChanges(false);
self.serverError(false); self.updateList();
}
var aResult = _.compact(_.map(oData.Result.Filters, function (aItem) { else if (oData && oData.ErrorCode)
var oNew = new FilterModel(); {
return (oNew && oNew.parse(aItem)) ? oNew : null; self.saveErrorText(oData.ErrorMessageAdditional || Translator.getNotification(oData.ErrorCode));
}));
self.filters(aResult);
self.modules(oData.Result.Modules ? oData.Result.Modules : {});
self.filterRaw(oData.Result.Raw || '');
self.filterRaw.capa(Utils.isArray(oData.Result.Capa) ? oData.Result.Capa.join(' ') : '');
self.filterRaw.active(!!oData.Result.RawIsActive);
self.filterRaw.allow(!!oData.Result.RawIsAllow);
} }
else else
{ {
self.filters([]); self.saveErrorText(Translator.getNotification(Enums.Notification.CantSaveFilters));
self.modules({});
self.filterRaw('');
self.filterRaw.capa({});
self.serverError(true);
self.serverErrorDesc(oData && oData.ErrorCode ? Translator.getNotification(oData.ErrorCode) :
Translator.getNotification(Enums.Notification.CantGetFilters));
} }
self.haveChanges(false); }, this.filters(), this.filterRaw(), this.filterRaw.active());
});
} }
};
FiltersUserSettings.prototype.deleteFilter = function (oFilter) return true;
}, function() {
return this.haveChanges();
});
this.filters.subscribe(function() {
this.haveChanges(true);
}, this);
this.filterRaw.subscribe(function() {
this.haveChanges(true);
this.filterRaw.error(false);
}, this);
this.haveChanges.subscribe(function() {
this.saveErrorText('');
}, this);
this.filterRaw.active.subscribe(function() {
this.haveChanges(true);
this.filterRaw.error(false);
}, this);
}
FiltersUserSettings.prototype.scrollableOptions = function(sWrapper)
{
return {
handle: '.drag-handle',
containment: sWrapper || 'parent',
axis: 'y'
};
};
FiltersUserSettings.prototype.updateList = function()
{
var
self = this,
FilterModel = require('Model/Filter');
if (!this.filters.loading())
{ {
this.filters.remove(oFilter); this.filters.loading(true);
Utils.delegateRunOnDestroy(oFilter);
};
FiltersUserSettings.prototype.addFilter = function () Remote.filtersGet(function(sResult, oData) {
{
var
self = this,
FilterModel = require('Model/Filter'),
oNew = new FilterModel()
;
oNew.generateID(); self.filters.loading(false);
require('Knoin/Knoin').showScreenPopup( self.serverError(false);
require('View/Popup/Filter'), [oNew, function () {
self.filters.push(oNew);
self.filterRaw.active(false);
}, false]);
};
FiltersUserSettings.prototype.editFilter = function (oEdit) if (Enums.StorageResultType.Success === sResult && oData &&
{ oData.Result && Utils.isArray(oData.Result.Filters))
var {
self = this, self.inited(true);
oCloned = oEdit.cloneSelf() self.serverError(false);
;
require('Knoin/Knoin').showScreenPopup( var aResult = _.compact(_.map(oData.Result.Filters, function(aItem) {
require('View/Popup/Filter'), [oCloned, function () { var oNew = new FilterModel();
return (oNew && oNew.parse(aItem)) ? oNew : null;
}));
var self.filters(aResult);
aFilters = self.filters(),
iIndex = aFilters.indexOf(oEdit)
;
if (-1 < iIndex && aFilters[iIndex]) self.modules(oData.Result.Modules ? oData.Result.Modules : {});
{
Utils.delegateRunOnDestroy(aFilters[iIndex]);
aFilters[iIndex] = oCloned;
self.filters(aFilters); self.filterRaw(oData.Result.Raw || '');
self.haveChanges(true); self.filterRaw.capa(Utils.isArray(oData.Result.Capa) ? oData.Result.Capa.join(' ') : '');
} self.filterRaw.active(!!oData.Result.RawIsActive);
self.filterRaw.allow(!!oData.Result.RawIsAllow);
}
else
{
self.filters([]);
self.modules({});
self.filterRaw('');
self.filterRaw.capa({});
}, true]); self.serverError(true);
}; self.serverErrorDesc(oData && oData.ErrorCode ? Translator.getNotification(oData.ErrorCode) :
Translator.getNotification(Enums.Notification.CantGetFilters));
}
FiltersUserSettings.prototype.onBuild = function (oDom) self.haveChanges(false);
{ });
var self = this; }
};
oDom FiltersUserSettings.prototype.deleteFilter = function(oFilter)
.on('click', '.filter-item .e-action', function () { {
var oFilterItem = ko.dataFor(this); this.filters.remove(oFilter);
if (oFilterItem) Utils.delegateRunOnDestroy(oFilter);
{ };
self.editFilter(oFilterItem);
}
})
;
};
FiltersUserSettings.prototype.onShow = function () FiltersUserSettings.prototype.addFilter = function()
{ {
this.updateList(); var
}; self = this,
FilterModel = require('Model/Filter'),
oNew = new FilterModel();
module.exports = FiltersUserSettings; oNew.generateID();
require('Knoin/Knoin').showScreenPopup(
require('View/Popup/Filter'), [oNew, function() {
self.filters.push(oNew);
self.filterRaw.active(false);
}, false]);
};
}()); FiltersUserSettings.prototype.editFilter = function(oEdit)
{
var
self = this,
oCloned = oEdit.cloneSelf();
require('Knoin/Knoin').showScreenPopup(
require('View/Popup/Filter'), [oCloned, function() {
var
aFilters = self.filters(),
iIndex = aFilters.indexOf(oEdit);
if (-1 < iIndex && aFilters[iIndex])
{
Utils.delegateRunOnDestroy(aFilters[iIndex]);
aFilters[iIndex] = oCloned;
self.filters(aFilters);
self.haveChanges(true);
}
}, true]);
};
FiltersUserSettings.prototype.onBuild = function(oDom)
{
var self = this;
oDom
.on('click', '.filter-item .e-action', function() {
var oFilterItem = ko.dataFor(this);
if (oFilterItem)
{
self.editFilter(oFilterItem);
}
});
};
FiltersUserSettings.prototype.onShow = function()
{
this.updateList();
};
module.exports = FiltersUserSettings;

View file

@ -1,203 +1,192 @@
(function () { var
ko = require('ko'),
'use strict'; Enums = require('Common/Enums'),
Utils = require('Common/Utils'),
Translator = require('Common/Translator'),
var Cache = require('Common/Cache'),
ko = require('ko'),
Enums = require('Common/Enums'), Settings = require('Storage/Settings'),
Utils = require('Common/Utils'), Local = require('Storage/Client'),
Translator = require('Common/Translator'),
Cache = require('Common/Cache'), FolderStore = require('Stores/User/Folder'),
Settings = require('Storage/Settings'), Promises = require('Promises/User/Ajax'),
Local = require('Storage/Client'), Remote = require('Remote/User/Ajax');
FolderStore = require('Stores/User/Folder'), /**
* @constructor
*/
function FoldersUserSettings()
{
this.displaySpecSetting = FolderStore.displaySpecSetting;
this.folderList = FolderStore.folderList;
Promises = require('Promises/User/Ajax'), this.folderListHelp = ko.observable('').extend({'throttle': 100});
Remote = require('Remote/User/Ajax')
;
/** this.loading = ko.computed(function() {
* @constructor
*/
function FoldersUserSettings()
{
this.displaySpecSetting = FolderStore.displaySpecSetting;
this.folderList = FolderStore.folderList;
this.folderListHelp = ko.observable('').extend({'throttle': 100}); var
bLoading = FolderStore.foldersLoading(),
bCreating = FolderStore.foldersCreating(),
bDeleting = FolderStore.foldersDeleting(),
bRenaming = FolderStore.foldersRenaming();
this.loading = ko.computed(function () { return bLoading || bCreating || bDeleting || bRenaming;
var }, this);
bLoading = FolderStore.foldersLoading(),
bCreating = FolderStore.foldersCreating(),
bDeleting = FolderStore.foldersDeleting(),
bRenaming = FolderStore.foldersRenaming()
;
return bLoading || bCreating || bDeleting || bRenaming; this.folderForDeletion = ko.observable(null).deleteAccessHelper();
}, this); this.folderForEdit = ko.observable(null).extend({'toggleSubscribe': [this,
function(oPrev) {
this.folderForDeletion = ko.observable(null).deleteAccessHelper(); if (oPrev)
{
this.folderForEdit = ko.observable(null).extend({'toggleSubscribe': [this, oPrev.edited(false);
function (oPrev) {
if (oPrev)
{
oPrev.edited(false);
}
}, function (oNext) {
if (oNext && oNext.canBeEdited())
{
oNext.edited(true);
}
} }
]}); }, function(oNext) {
if (oNext && oNext.canBeEdited())
{
oNext.edited(true);
}
}
]});
this.useImapSubscribe = !!Settings.appSettingsGet('useImapSubscribe'); this.useImapSubscribe = !!Settings.appSettingsGet('useImapSubscribe');
}
FoldersUserSettings.prototype.folderEditOnEnter = function(oFolder)
{
var
sEditName = oFolder ? Utils.trim(oFolder.nameForEdit()) : '';
if ('' !== sEditName && oFolder.name() !== sEditName)
{
Local.set(Enums.ClientSideKeyName.FoldersLashHash, '');
require('App/User').default.foldersPromisesActionHelper(
Promises.folderRename(oFolder.fullNameRaw, sEditName, FolderStore.foldersRenaming),
Enums.Notification.CantRenameFolder
);
Cache.removeFolderFromCacheList(oFolder.fullNameRaw);
oFolder.name(sEditName);
} }
FoldersUserSettings.prototype.folderEditOnEnter = function (oFolder) oFolder.edited(false);
{ };
var
sEditName = oFolder ? Utils.trim(oFolder.nameForEdit()) : ''
;
if ('' !== sEditName && oFolder.name() !== sEditName) FoldersUserSettings.prototype.folderEditOnEsc = function(oFolder)
{
if (oFolder)
{
oFolder.edited(false);
}
};
FoldersUserSettings.prototype.onShow = function()
{
FolderStore.folderList.error('');
};
FoldersUserSettings.prototype.onBuild = function(oDom)
{
var self = this;
oDom
.on('mouseover', '.delete-folder-parent', function() {
self.folderListHelp(Translator.i18n('SETTINGS_FOLDERS/HELP_DELETE_FOLDER'));
})
.on('mouseover', '.subscribe-folder-parent', function() {
self.folderListHelp(Translator.i18n('SETTINGS_FOLDERS/HELP_SHOW_HIDE_FOLDER'));
})
.on('mouseover', '.check-folder-parent', function() {
self.folderListHelp(Translator.i18n('SETTINGS_FOLDERS/HELP_CHECK_FOR_NEW_MESSAGES'));
})
.on('mouseout', '.subscribe-folder-parent, .check-folder-parent, .delete-folder-parent', function() {
self.folderListHelp('');
});
};
FoldersUserSettings.prototype.createFolder = function()
{
require('Knoin/Knoin').showScreenPopup(require('View/Popup/FolderCreate'));
};
FoldersUserSettings.prototype.systemFolder = function()
{
require('Knoin/Knoin').showScreenPopup(require('View/Popup/FolderSystem'));
};
FoldersUserSettings.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)
{ {
Local.set(Enums.ClientSideKeyName.FoldersLashHash, ''); Local.set(Enums.ClientSideKeyName.FoldersLashHash, '');
FolderStore.folderList.remove(fRemoveFolder);
require('App/User').default.foldersPromisesActionHelper( require('App/User').default.foldersPromisesActionHelper(
Promises.folderRename(oFolder.fullNameRaw, sEditName, FolderStore.foldersRenaming), Promises.folderDelete(oFolderToRemove.fullNameRaw, FolderStore.foldersDeleting),
Enums.Notification.CantRenameFolder Enums.Notification.CantDeleteFolder
); );
Cache.removeFolderFromCacheList(oFolder.fullNameRaw); Cache.removeFolderFromCacheList(oFolderToRemove.fullNameRaw);
oFolder.name(sEditName);
} }
}
oFolder.edited(false); else if (0 < oFolderToRemove.privateMessageCountAll())
};
FoldersUserSettings.prototype.folderEditOnEsc = function (oFolder)
{ {
if (oFolder) FolderStore.folderList.error(Translator.getNotification(Enums.Notification.CantDeleteNonEmptyFolder));
{ }
oFolder.edited(false); };
}
};
FoldersUserSettings.prototype.onShow = function () FoldersUserSettings.prototype.subscribeFolder = function(oFolder)
{ {
FolderStore.folderList.error(''); Local.set(Enums.ClientSideKeyName.FoldersLashHash, '');
}; Remote.folderSetSubscribe(Utils.noop, oFolder.fullNameRaw, true);
FoldersUserSettings.prototype.onBuild = function (oDom) oFolder.subScribed(true);
{ };
var self = this;
oDom
.on('mouseover', '.delete-folder-parent', function () {
self.folderListHelp(Translator.i18n('SETTINGS_FOLDERS/HELP_DELETE_FOLDER'));
})
.on('mouseover', '.subscribe-folder-parent', function () {
self.folderListHelp(Translator.i18n('SETTINGS_FOLDERS/HELP_SHOW_HIDE_FOLDER'));
})
.on('mouseover', '.check-folder-parent', function () {
self.folderListHelp(Translator.i18n('SETTINGS_FOLDERS/HELP_CHECK_FOR_NEW_MESSAGES'));
})
.on('mouseout', '.subscribe-folder-parent, .check-folder-parent, .delete-folder-parent', function () {
self.folderListHelp('');
})
;
};
FoldersUserSettings.prototype.createFolder = function () FoldersUserSettings.prototype.unSubscribeFolder = function(oFolder)
{ {
require('Knoin/Knoin').showScreenPopup(require('View/Popup/FolderCreate')); Local.set(Enums.ClientSideKeyName.FoldersLashHash, '');
}; Remote.folderSetSubscribe(Utils.noop, oFolder.fullNameRaw, false);
FoldersUserSettings.prototype.systemFolder = function () oFolder.subScribed(false);
{ };
require('Knoin/Knoin').showScreenPopup(require('View/Popup/FolderSystem'));
};
FoldersUserSettings.prototype.deleteFolder = function (oFolderToRemove) FoldersUserSettings.prototype.checkableTrueFolder = function(oFolder)
{ {
if (oFolderToRemove && oFolderToRemove.canBeDeleted() && oFolderToRemove.deleteAccess() && Remote.folderSetCheckable(Utils.noop, oFolder.fullNameRaw, true);
0 === oFolderToRemove.privateMessageCountAll())
{
this.folderForDeletion(null);
var oFolder.checkable(true);
fRemoveFolder = function (oFolder) { };
if (oFolderToRemove === oFolder) FoldersUserSettings.prototype.checkableFalseFolder = function(oFolder)
{ {
return true; Remote.folderSetCheckable(Utils.noop, oFolder.fullNameRaw, false);
}
oFolder.subFolders.remove(fRemoveFolder); oFolder.checkable(false);
return false; };
}
;
if (oFolderToRemove) module.exports = FoldersUserSettings;
{
Local.set(Enums.ClientSideKeyName.FoldersLashHash, '');
FolderStore.folderList.remove(fRemoveFolder);
require('App/User').default.foldersPromisesActionHelper(
Promises.folderDelete(oFolderToRemove.fullNameRaw, FolderStore.foldersDeleting),
Enums.Notification.CantDeleteFolder
);
Cache.removeFolderFromCacheList(oFolderToRemove.fullNameRaw);
}
}
else if (0 < oFolderToRemove.privateMessageCountAll())
{
FolderStore.folderList.error(Translator.getNotification(Enums.Notification.CantDeleteNonEmptyFolder));
}
};
FoldersUserSettings.prototype.subscribeFolder = function (oFolder)
{
Local.set(Enums.ClientSideKeyName.FoldersLashHash, '');
Remote.folderSetSubscribe(Utils.noop, oFolder.fullNameRaw, true);
oFolder.subScribed(true);
};
FoldersUserSettings.prototype.unSubscribeFolder = function (oFolder)
{
Local.set(Enums.ClientSideKeyName.FoldersLashHash, '');
Remote.folderSetSubscribe(Utils.noop, oFolder.fullNameRaw, false);
oFolder.subScribed(false);
};
FoldersUserSettings.prototype.checkableTrueFolder = function (oFolder)
{
Remote.folderSetCheckable(Utils.noop, oFolder.fullNameRaw, true);
oFolder.checkable(true);
};
FoldersUserSettings.prototype.checkableFalseFolder = function (oFolder)
{
Remote.folderSetCheckable(Utils.noop, oFolder.fullNameRaw, false);
oFolder.checkable(false);
};
module.exports = FoldersUserSettings;
}());

View file

@ -1,232 +1,224 @@
(function () { var
_ = require('_'),
ko = require('ko'),
'use strict'; Enums = require('Common/Enums'),
Consts = require('Common/Consts'),
Globals = require('Common/Globals'),
Utils = require('Common/Utils'),
Translator = require('Common/Translator'),
var AppStore = require('Stores/User/App'),
_ = require('_'), LanguageStore = require('Stores/Language'),
ko = require('ko'), SettingsStore = require('Stores/User/Settings'),
IdentityStore = require('Stores/User/Identity'),
NotificationStore = require('Stores/User/Notification'),
MessageStore = require('Stores/User/Message'),
Enums = require('Common/Enums'), Remote = require('Remote/User/Ajax');
Consts = require('Common/Consts'),
Globals = require('Common/Globals'),
Utils = require('Common/Utils'),
Translator = require('Common/Translator'),
AppStore = require('Stores/User/App'), /**
LanguageStore = require('Stores/Language'), * @constructor
SettingsStore = require('Stores/User/Settings'), */
IdentityStore = require('Stores/User/Identity'), function GeneralUserSettings()
NotificationStore = require('Stores/User/Notification'), {
MessageStore = require('Stores/User/Message'), this.language = LanguageStore.language;
this.languages = LanguageStore.languages;
this.messagesPerPage = SettingsStore.messagesPerPage;
this.messagesPerPageArray = Consts.MESSAGES_PER_PAGE_VALUES;
Remote = require('Remote/User/Ajax') this.editorDefaultType = SettingsStore.editorDefaultType;
; this.layout = SettingsStore.layout;
this.usePreviewPane = SettingsStore.usePreviewPane;
/** this.soundNotificationIsSupported = NotificationStore.soundNotificationIsSupported;
* @constructor this.enableSoundNotification = NotificationStore.enableSoundNotification;
*/
function GeneralUserSettings()
{
this.language = LanguageStore.language;
this.languages = LanguageStore.languages;
this.messagesPerPage = SettingsStore.messagesPerPage;
this.messagesPerPageArray = Consts.MESSAGES_PER_PAGE_VALUES;
this.editorDefaultType = SettingsStore.editorDefaultType; this.enableDesktopNotification = NotificationStore.enableDesktopNotification;
this.layout = SettingsStore.layout; this.isDesktopNotificationSupported = NotificationStore.isDesktopNotificationSupported;
this.usePreviewPane = SettingsStore.usePreviewPane; this.isDesktopNotificationDenied = NotificationStore.isDesktopNotificationDenied;
this.soundNotificationIsSupported = NotificationStore.soundNotificationIsSupported; this.showImages = SettingsStore.showImages;
this.enableSoundNotification = NotificationStore.enableSoundNotification; this.useCheckboxesInList = SettingsStore.useCheckboxesInList;
this.threadsAllowed = AppStore.threadsAllowed;
this.useThreads = SettingsStore.useThreads;
this.replySameFolder = SettingsStore.replySameFolder;
this.allowLanguagesOnSettings = AppStore.allowLanguagesOnSettings;
this.enableDesktopNotification = NotificationStore.enableDesktopNotification; this.languageFullName = ko.computed(function() {
this.isDesktopNotificationSupported = NotificationStore.isDesktopNotificationSupported; return Utils.convertLangName(this.language());
this.isDesktopNotificationDenied = NotificationStore.isDesktopNotificationDenied; }, this);
this.showImages = SettingsStore.showImages; this.languageTrigger = ko.observable(Enums.SaveSettingsStep.Idle).extend({'throttle': 100});
this.useCheckboxesInList = SettingsStore.useCheckboxesInList;
this.threadsAllowed = AppStore.threadsAllowed;
this.useThreads = SettingsStore.useThreads;
this.replySameFolder = SettingsStore.replySameFolder;
this.allowLanguagesOnSettings = AppStore.allowLanguagesOnSettings;
this.languageFullName = ko.computed(function () { this.mppTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
return Utils.convertLangName(this.language()); this.editorDefaultTypeTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
}, this); this.layoutTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.languageTrigger = ko.observable(Enums.SaveSettingsStep.Idle).extend({'throttle': 100}); this.isAnimationSupported = Globals.bAnimationSupported;
this.mppTrigger = ko.observable(Enums.SaveSettingsStep.Idle); this.identities = IdentityStore.identities;
this.editorDefaultTypeTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.layoutTrigger = ko.observable(Enums.SaveSettingsStep.Idle);
this.isAnimationSupported = Globals.bAnimationSupported; this.identityMain = ko.computed(function() {
var aList = this.identities();
return Utils.isArray(aList) ? _.find(aList, function(oItem) {
return oItem && '' === oItem.id();
}) : null;
}, this);
this.identities = IdentityStore.identities; this.identityMainDesc = ko.computed(function() {
this.identityMain = ko.computed(function () {
var aList = this.identities();
return Utils.isArray(aList) ? _.find(aList, function (oItem) {
return oItem && '' === oItem.id() ? true : false;
}) : null;
}, this);
this.identityMainDesc = ko.computed(function () {
var oIdentity = this.identityMain();
return oIdentity ? oIdentity.formattedName() : '---';
}, this);
this.editorDefaultTypes = ko.computed(function () {
Translator.trigger();
return [
{'id': Enums.EditorDefaultType.Html, 'name': Translator.i18n('SETTINGS_GENERAL/LABEL_EDITOR_HTML')},
{'id': Enums.EditorDefaultType.Plain, 'name': Translator.i18n('SETTINGS_GENERAL/LABEL_EDITOR_PLAIN')},
{'id': Enums.EditorDefaultType.HtmlForced, 'name': Translator.i18n('SETTINGS_GENERAL/LABEL_EDITOR_HTML_FORCED')},
{'id': Enums.EditorDefaultType.PlainForced, 'name': Translator.i18n('SETTINGS_GENERAL/LABEL_EDITOR_PLAIN_FORCED')}
];
}, this);
this.layoutTypes = ko.computed(function () {
Translator.trigger();
return [
{'id': Enums.Layout.NoPreview, 'name': Translator.i18n('SETTINGS_GENERAL/LABEL_LAYOUT_NO_SPLIT')},
{'id': Enums.Layout.SidePreview, 'name': Translator.i18n('SETTINGS_GENERAL/LABEL_LAYOUT_VERTICAL_SPLIT')},
{'id': Enums.Layout.BottomPreview, 'name': Translator.i18n('SETTINGS_GENERAL/LABEL_LAYOUT_HORIZONTAL_SPLIT')}
];
}, this);
}
GeneralUserSettings.prototype.editMainIdentity = function ()
{
var oIdentity = this.identityMain(); var oIdentity = this.identityMain();
if (oIdentity) return oIdentity ? oIdentity.formattedName() : '---';
{ }, this);
require('Knoin/Knoin').showScreenPopup(require('View/Popup/Identity'), [oIdentity]);
}
};
GeneralUserSettings.prototype.testSoundNotification = function () this.editorDefaultTypes = ko.computed(function() {
Translator.trigger();
return [
{'id': Enums.EditorDefaultType.Html, 'name': Translator.i18n('SETTINGS_GENERAL/LABEL_EDITOR_HTML')},
{'id': Enums.EditorDefaultType.Plain, 'name': Translator.i18n('SETTINGS_GENERAL/LABEL_EDITOR_PLAIN')},
{'id': Enums.EditorDefaultType.HtmlForced, 'name': Translator.i18n('SETTINGS_GENERAL/LABEL_EDITOR_HTML_FORCED')},
{'id': Enums.EditorDefaultType.PlainForced, 'name': Translator.i18n('SETTINGS_GENERAL/LABEL_EDITOR_PLAIN_FORCED')}
];
}, this);
this.layoutTypes = ko.computed(function() {
Translator.trigger();
return [
{'id': Enums.Layout.NoPreview, 'name': Translator.i18n('SETTINGS_GENERAL/LABEL_LAYOUT_NO_SPLIT')},
{'id': Enums.Layout.SidePreview, 'name': Translator.i18n('SETTINGS_GENERAL/LABEL_LAYOUT_VERTICAL_SPLIT')},
{'id': Enums.Layout.BottomPreview, 'name': Translator.i18n('SETTINGS_GENERAL/LABEL_LAYOUT_HORIZONTAL_SPLIT')}
];
}, this);
}
GeneralUserSettings.prototype.editMainIdentity = function()
{
var oIdentity = this.identityMain();
if (oIdentity)
{ {
NotificationStore.playSoundNotification(true); require('Knoin/Knoin').showScreenPopup(require('View/Popup/Identity'), [oIdentity]);
}; }
};
GeneralUserSettings.prototype.onBuild = function () GeneralUserSettings.prototype.testSoundNotification = function()
{ {
var self = this; NotificationStore.playSoundNotification(true);
};
_.delay(function () { GeneralUserSettings.prototype.onBuild = function()
{
var self = this;
var _.delay(function() {
f0 = Utils.settingsSaveHelperSimpleFunction(self.editorDefaultTypeTrigger, self),
f1 = Utils.settingsSaveHelperSimpleFunction(self.mppTrigger, self),
f2 = Utils.settingsSaveHelperSimpleFunction(self.layoutTrigger, self),
fReloadLanguageHelper = function (iSaveSettingsStep) {
return function() {
self.languageTrigger(iSaveSettingsStep);
_.delay(function () {
self.languageTrigger(Enums.SaveSettingsStep.Idle);
}, 1000);
};
}
;
self.language.subscribe(function (sValue) { var
f0 = Utils.settingsSaveHelperSimpleFunction(self.editorDefaultTypeTrigger, self),
f1 = Utils.settingsSaveHelperSimpleFunction(self.mppTrigger, self),
f2 = Utils.settingsSaveHelperSimpleFunction(self.layoutTrigger, self),
fReloadLanguageHelper = function(iSaveSettingsStep) {
return function() {
self.languageTrigger(iSaveSettingsStep);
_.delay(function() {
self.languageTrigger(Enums.SaveSettingsStep.Idle);
}, 1000);
};
};
self.languageTrigger(Enums.SaveSettingsStep.Animate); self.language.subscribe(function(sValue) {
Translator.reload(false, sValue).then( self.languageTrigger(Enums.SaveSettingsStep.Animate);
fReloadLanguageHelper(Enums.SaveSettingsStep.TrueResult),
fReloadLanguageHelper(Enums.SaveSettingsStep.FalseResult)
).then(function() {
Remote.saveSettings(null, {
'Language': sValue
});
});
}); Translator.reload(false, sValue).then(
fReloadLanguageHelper(Enums.SaveSettingsStep.TrueResult),
self.editorDefaultType.subscribe(function (sValue) { fReloadLanguageHelper(Enums.SaveSettingsStep.FalseResult)
Remote.saveSettings(f0, { ).then(function() {
'EditorDefaultType': sValue
});
});
self.messagesPerPage.subscribe(function (iValue) {
Remote.saveSettings(f1, {
'MPP': iValue
});
});
self.showImages.subscribe(function (bValue) {
Remote.saveSettings(null, { Remote.saveSettings(null, {
'ShowImages': bValue ? '1' : '0' 'Language': sValue
}); });
}); });
self.enableDesktopNotification.subscribe(function (bValue) { });
Utils.timeOutAction('SaveDesktopNotifications', function () {
Remote.saveSettings(null, { self.editorDefaultType.subscribe(function(sValue) {
'DesktopNotifications': bValue ? '1' : '0' Remote.saveSettings(f0, {
}); 'EditorDefaultType': sValue
}, 3000);
}); });
});
self.enableSoundNotification.subscribe(function (bValue) { self.messagesPerPage.subscribe(function(iValue) {
Utils.timeOutAction('SaveSoundNotification', function () { Remote.saveSettings(f1, {
Remote.saveSettings(null, { 'MPP': iValue
'SoundNotification': bValue ? '1' : '0'
});
}, 3000);
}); });
});
self.replySameFolder.subscribe(function (bValue) { self.showImages.subscribe(function(bValue) {
Utils.timeOutAction('SaveReplySameFolder', function () { Remote.saveSettings(null, {
Remote.saveSettings(null, { 'ShowImages': bValue ? '1' : '0'
'ReplySameFolder': bValue ? '1' : '0'
});
}, 3000);
}); });
});
self.useThreads.subscribe(function (bValue) { self.enableDesktopNotification.subscribe(function(bValue) {
Utils.timeOutAction('SaveDesktopNotifications', function() {
MessageStore.messageList([]);
Remote.saveSettings(null, { Remote.saveSettings(null, {
'UseThreads': bValue ? '1' : '0' 'DesktopNotifications': bValue ? '1' : '0'
}); });
}); }, 3000);
});
self.layout.subscribe(function (nValue) { self.enableSoundNotification.subscribe(function(bValue) {
Utils.timeOutAction('SaveSoundNotification', function() {
MessageStore.messageList([]);
Remote.saveSettings(f2, {
'Layout': nValue
});
});
self.useCheckboxesInList.subscribe(function (bValue) {
Remote.saveSettings(null, { Remote.saveSettings(null, {
'UseCheckboxesInList': bValue ? '1' : '0' 'SoundNotification': bValue ? '1' : '0'
}); });
}, 3000);
});
self.replySameFolder.subscribe(function(bValue) {
Utils.timeOutAction('SaveReplySameFolder', function() {
Remote.saveSettings(null, {
'ReplySameFolder': bValue ? '1' : '0'
});
}, 3000);
});
self.useThreads.subscribe(function(bValue) {
MessageStore.messageList([]);
Remote.saveSettings(null, {
'UseThreads': bValue ? '1' : '0'
}); });
});
}, 50); self.layout.subscribe(function(nValue) {
};
GeneralUserSettings.prototype.onShow = function () MessageStore.messageList([]);
{
this.enableDesktopNotification.valueHasMutated();
};
GeneralUserSettings.prototype.selectLanguage = function () Remote.saveSettings(f2, {
{ 'Layout': nValue
require('Knoin/Knoin').showScreenPopup(require('View/Popup/Languages'), [ });
this.language, this.languages(), LanguageStore.userLanguage() });
]);
};
module.exports = GeneralUserSettings; self.useCheckboxesInList.subscribe(function(bValue) {
Remote.saveSettings(null, {
'UseCheckboxesInList': bValue ? '1' : '0'
});
});
}()); }, 50);
};
GeneralUserSettings.prototype.onShow = function()
{
this.enableDesktopNotification.valueHasMutated();
};
GeneralUserSettings.prototype.selectLanguage = function()
{
require('Knoin/Knoin').showScreenPopup(require('View/Popup/Languages'), [
this.language, this.languages(), LanguageStore.userLanguage()
]);
};
module.exports = GeneralUserSettings;

View file

@ -1,83 +1,76 @@
(function () { var
_ = require('_'),
ko = require('ko'),
window = require('window'),
'use strict'; Utils = require('Common/Utils'),
var kn = require('Knoin/Knoin'),
_ = require('_'),
ko = require('ko'),
window = require('window'),
Utils = require('Common/Utils'), PgpStore = require('Stores/User/Pgp');
kn = require('Knoin/Knoin'), /**
* @constructor
*/
function OpenPgpUserSettings()
{
this.openpgpkeys = PgpStore.openpgpkeys;
this.openpgpkeysPublic = PgpStore.openpgpkeysPublic;
this.openpgpkeysPrivate = PgpStore.openpgpkeysPrivate;
PgpStore = require('Stores/User/Pgp') this.openPgpKeyForDeletion = ko.observable(null).deleteAccessHelper();
;
/** this.isHttps = window.document && window.document.location ? 'https:' === window.document.location.protocol : false;
* @constructor }
*/
function OpenPgpUserSettings() OpenPgpUserSettings.prototype.addOpenPgpKey = function()
{
kn.showScreenPopup(require('View/Popup/AddOpenPgpKey'));
};
OpenPgpUserSettings.prototype.generateOpenPgpKey = function()
{
kn.showScreenPopup(require('View/Popup/NewOpenPgpKey'));
};
OpenPgpUserSettings.prototype.viewOpenPgpKey = function(oOpenPgpKey)
{
if (oOpenPgpKey)
{ {
this.openpgpkeys = PgpStore.openpgpkeys; kn.showScreenPopup(require('View/Popup/ViewOpenPgpKey'), [oOpenPgpKey]);
this.openpgpkeysPublic = PgpStore.openpgpkeysPublic;
this.openpgpkeysPrivate = PgpStore.openpgpkeysPrivate;
this.openPgpKeyForDeletion = ko.observable(null).deleteAccessHelper();
this.isHttps = window.document && window.document.location ? 'https:' === window.document.location.protocol : false;
} }
};
OpenPgpUserSettings.prototype.addOpenPgpKey = function () /**
* @param {OpenPgpKeyModel} oOpenPgpKeyToRemove
*/
OpenPgpUserSettings.prototype.deleteOpenPgpKey = function(oOpenPgpKeyToRemove)
{
if (oOpenPgpKeyToRemove && oOpenPgpKeyToRemove.deleteAccess())
{ {
kn.showScreenPopup(require('View/Popup/AddOpenPgpKey')); this.openPgpKeyForDeletion(null);
};
OpenPgpUserSettings.prototype.generateOpenPgpKey = function () if (oOpenPgpKeyToRemove && PgpStore.openpgpKeyring)
{
kn.showScreenPopup(require('View/Popup/NewOpenPgpKey'));
};
OpenPgpUserSettings.prototype.viewOpenPgpKey = function (oOpenPgpKey)
{
if (oOpenPgpKey)
{ {
kn.showScreenPopup(require('View/Popup/ViewOpenPgpKey'), [oOpenPgpKey]); var oFindedItem = _.find(PgpStore.openpgpkeys(), function(oOpenPgpKey) {
} return oOpenPgpKeyToRemove === oOpenPgpKey;
}; });
/** if (oFindedItem)
* @param {OpenPgpKeyModel} oOpenPgpKeyToRemove
*/
OpenPgpUserSettings.prototype.deleteOpenPgpKey = function (oOpenPgpKeyToRemove)
{
if (oOpenPgpKeyToRemove && oOpenPgpKeyToRemove.deleteAccess())
{
this.openPgpKeyForDeletion(null);
if (oOpenPgpKeyToRemove && PgpStore.openpgpKeyring)
{ {
var oFindedItem = _.find(PgpStore.openpgpkeys(), function (oOpenPgpKey) { PgpStore.openpgpkeys.remove(oFindedItem);
return oOpenPgpKeyToRemove === oOpenPgpKey; Utils.delegateRunOnDestroy(oFindedItem);
});
if (oFindedItem) PgpStore.openpgpKeyring[oFindedItem.isPrivate ? 'privateKeys' : 'publicKeys']
{ .removeForId(oFindedItem.guid);
PgpStore.openpgpkeys.remove(oFindedItem);
Utils.delegateRunOnDestroy(oFindedItem);
PgpStore.openpgpKeyring[oFindedItem.isPrivate ? 'privateKeys' : 'publicKeys'] PgpStore.openpgpKeyring.store();
.removeForId(oFindedItem.guid);
PgpStore.openpgpKeyring.store();
}
require('App/User').default.reloadOpenPgpKeys();
} }
require('App/User').default.reloadOpenPgpKeys();
} }
}; }
};
module.exports = OpenPgpUserSettings; module.exports = OpenPgpUserSettings;
}());

View file

@ -1,76 +1,68 @@
(function () { var
_ = require('_'),
ko = require('ko'),
'use strict'; Enums = require('Common/Enums'),
Utils = require('Common/Utils'),
Translator = require('Common/Translator'),
var SettinsStore = require('Stores/User/Settings'),
_ = require('_'),
ko = require('ko'),
Enums = require('Common/Enums'), Settings = require('Storage/Settings'),
Utils = require('Common/Utils'),
Translator = require('Common/Translator'),
SettinsStore = require('Stores/User/Settings'), Remote = require('Remote/User/Ajax');
Settings = require('Storage/Settings'), /**
* @constructor
*/
function SecurityUserSettings()
{
this.capaAutoLogout = Settings.capa(Enums.Capa.AutoLogout);
this.capaTwoFactor = Settings.capa(Enums.Capa.TwoFactor);
Remote = require('Remote/User/Ajax') this.autoLogout = SettinsStore.autoLogout;
; this.autoLogout.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
/** this.autoLogoutOptions = ko.computed(function() {
* @constructor Translator.trigger();
*/ return [
function SecurityUserSettings() {'id': 0, 'name': Translator.i18n('SETTINGS_SECURITY/AUTOLOGIN_NEVER_OPTION_NAME')},
{'id': 5, 'name': Translator.i18n('SETTINGS_SECURITY/AUTOLOGIN_MINUTES_OPTION_NAME', {'MINUTES': 5})},
{'id': 10, 'name': Translator.i18n('SETTINGS_SECURITY/AUTOLOGIN_MINUTES_OPTION_NAME', {'MINUTES': 10})},
{'id': 30, 'name': Translator.i18n('SETTINGS_SECURITY/AUTOLOGIN_MINUTES_OPTION_NAME', {'MINUTES': 30})},
{'id': 60, 'name': Translator.i18n('SETTINGS_SECURITY/AUTOLOGIN_MINUTES_OPTION_NAME', {'MINUTES': 60})},
{'id': 60 * 2, 'name': Translator.i18n('SETTINGS_SECURITY/AUTOLOGIN_HOURS_OPTION_NAME', {'HOURS': 2})},
{'id': 60 * 5, 'name': Translator.i18n('SETTINGS_SECURITY/AUTOLOGIN_HOURS_OPTION_NAME', {'HOURS': 5})},
{'id': 60 * 10, 'name': Translator.i18n('SETTINGS_SECURITY/AUTOLOGIN_HOURS_OPTION_NAME', {'HOURS': 10})}
];
});
}
SecurityUserSettings.prototype.configureTwoFactor = function()
{
require('Knoin/Knoin').showScreenPopup(require('View/Popup/TwoFactorConfiguration'));
};
SecurityUserSettings.prototype.onBuild = function()
{
if (this.capaAutoLogout)
{ {
this.capaAutoLogout = Settings.capa(Enums.Capa.AutoLogout); var self = this;
this.capaTwoFactor = Settings.capa(Enums.Capa.TwoFactor);
this.autoLogout = SettinsStore.autoLogout; _.delay(function() {
this.autoLogout.trigger = ko.observable(Enums.SaveSettingsStep.Idle);
var
f0 = Utils.settingsSaveHelperSimpleFunction(self.autoLogout.trigger, self);
self.autoLogout.subscribe(function(sValue) {
Remote.saveSettings(f0, {
'AutoLogout': Utils.pInt(sValue)
});
});
this.autoLogoutOptions = ko.computed(function () {
Translator.trigger();
return [
{'id': 0, 'name': Translator.i18n('SETTINGS_SECURITY/AUTOLOGIN_NEVER_OPTION_NAME')},
{'id': 5, 'name': Translator.i18n('SETTINGS_SECURITY/AUTOLOGIN_MINUTES_OPTION_NAME', {'MINUTES': 5})},
{'id': 10, 'name': Translator.i18n('SETTINGS_SECURITY/AUTOLOGIN_MINUTES_OPTION_NAME', {'MINUTES': 10})},
{'id': 30, 'name': Translator.i18n('SETTINGS_SECURITY/AUTOLOGIN_MINUTES_OPTION_NAME', {'MINUTES': 30})},
{'id': 60, 'name': Translator.i18n('SETTINGS_SECURITY/AUTOLOGIN_MINUTES_OPTION_NAME', {'MINUTES': 60})},
{'id': 60 * 2, 'name': Translator.i18n('SETTINGS_SECURITY/AUTOLOGIN_HOURS_OPTION_NAME', {'HOURS': 2})},
{'id': 60 * 5, 'name': Translator.i18n('SETTINGS_SECURITY/AUTOLOGIN_HOURS_OPTION_NAME', {'HOURS': 5})},
{'id': 60 * 10, 'name': Translator.i18n('SETTINGS_SECURITY/AUTOLOGIN_HOURS_OPTION_NAME', {'HOURS': 10})}
];
}); });
} }
};
SecurityUserSettings.prototype.configureTwoFactor = function () module.exports = SecurityUserSettings;
{
require('Knoin/Knoin').showScreenPopup(require('View/Popup/TwoFactorConfiguration'));
};
SecurityUserSettings.prototype.onBuild = function ()
{
if (this.capaAutoLogout)
{
var self = this;
_.delay(function () {
var
f0 = Utils.settingsSaveHelperSimpleFunction(self.autoLogout.trigger, self)
;
self.autoLogout.subscribe(function (sValue) {
Remote.saveSettings(f0, {
'AutoLogout': Utils.pInt(sValue)
});
});
});
}
};
module.exports = SecurityUserSettings;
}());

View file

@ -1,80 +1,73 @@
(function () { /**
* @constructor
*/
function SocialUserSettings()
{
var
Utils = require('Common/Utils'),
SocialStore = require('Stores/Social');
'use strict'; this.googleEnable = SocialStore.google.enabled;
this.googleEnableAuth = SocialStore.google.capa.auth;
this.googleEnableAuthFast = SocialStore.google.capa.authFast;
this.googleEnableDrive = SocialStore.google.capa.drive;
this.googleEnablePreview = SocialStore.google.capa.preview;
/** this.googleActions = SocialStore.google.loading;
* @constructor this.googleLoggined = SocialStore.google.loggined;
*/ this.googleUserName = SocialStore.google.userName;
function SocialUserSettings()
{
var
Utils = require('Common/Utils'),
SocialStore = require('Stores/Social')
;
this.googleEnable = SocialStore.google.enabled; this.facebookEnable = SocialStore.facebook.enabled;
this.googleEnableAuth = SocialStore.google.capa.auth;
this.googleEnableAuthFast = SocialStore.google.capa.authFast;
this.googleEnableDrive = SocialStore.google.capa.drive;
this.googleEnablePreview = SocialStore.google.capa.preview;
this.googleActions = SocialStore.google.loading; this.facebookActions = SocialStore.facebook.loading;
this.googleLoggined = SocialStore.google.loggined; this.facebookLoggined = SocialStore.facebook.loggined;
this.googleUserName = SocialStore.google.userName; this.facebookUserName = SocialStore.facebook.userName;
this.facebookEnable = SocialStore.facebook.enabled; this.twitterEnable = SocialStore.twitter.enabled;
this.facebookActions = SocialStore.facebook.loading; this.twitterActions = SocialStore.twitter.loading;
this.facebookLoggined = SocialStore.facebook.loggined; this.twitterLoggined = SocialStore.twitter.loggined;
this.facebookUserName = SocialStore.facebook.userName; this.twitterUserName = SocialStore.twitter.userName;
this.twitterEnable = SocialStore.twitter.enabled; this.connectGoogle = Utils.createCommand(this, function() {
if (!this.googleLoggined())
{
require('App/User').default.googleConnect();
}
}, function() {
return !this.googleLoggined() && !this.googleActions();
});
this.twitterActions = SocialStore.twitter.loading; this.disconnectGoogle = Utils.createCommand(this, function() {
this.twitterLoggined = SocialStore.twitter.loggined; require('App/User').default.googleDisconnect();
this.twitterUserName = SocialStore.twitter.userName; });
this.connectGoogle = Utils.createCommand(this, function () { this.connectFacebook = Utils.createCommand(this, function() {
if (!this.googleLoggined()) if (!this.facebookLoggined())
{ {
require('App/User').default.googleConnect(); require('App/User').default.facebookConnect();
} }
}, function () { }, function() {
return !this.googleLoggined() && !this.googleActions(); return !this.facebookLoggined() && !this.facebookActions();
}); });
this.disconnectGoogle = Utils.createCommand(this, function () { this.disconnectFacebook = Utils.createCommand(this, function() {
require('App/User').default.googleDisconnect(); require('App/User').default.facebookDisconnect();
}); });
this.connectFacebook = Utils.createCommand(this, function () { this.connectTwitter = Utils.createCommand(this, function() {
if (!this.facebookLoggined()) if (!this.twitterLoggined())
{ {
require('App/User').default.facebookConnect(); require('App/User').default.twitterConnect();
} }
}, function () { }, function() {
return !this.facebookLoggined() && !this.facebookActions(); return !this.twitterLoggined() && !this.twitterActions();
}); });
this.disconnectFacebook = Utils.createCommand(this, function () { this.disconnectTwitter = Utils.createCommand(this, function() {
require('App/User').default.facebookDisconnect(); require('App/User').default.twitterDisconnect();
}); });
}
this.connectTwitter = Utils.createCommand(this, function () { module.exports = SocialUserSettings;
if (!this.twitterLoggined())
{
require('App/User').default.twitterConnect();
}
}, function () {
return !this.twitterLoggined() && !this.twitterActions();
});
this.disconnectTwitter = Utils.createCommand(this, function () {
require('App/User').default.twitterDisconnect();
});
}
module.exports = SocialUserSettings;
}());

View file

@ -1,107 +1,98 @@
(function () { var
ko = require('ko'),
'use strict'; Translator = require('Common/Translator'),
var TemplateStore = require('Stores/User/Template'),
ko = require('ko'),
Translator = require('Common/Translator'), Remote = require('Remote/User/Ajax');
TemplateStore = require('Stores/User/Template'), /**
* @constructor
*/
function TemplatesUserSettings()
{
this.templates = TemplateStore.templates;
Remote = require('Remote/User/Ajax') this.processText = ko.computed(function() {
; return TemplateStore.templates.loading() ? Translator.i18n('SETTINGS_TEMPLETS/LOADING_PROCESS') : '';
}, this);
/** this.visibility = ko.computed(function() {
* @constructor return '' === this.processText() ? 'hidden' : 'visible';
*/ }, this);
function TemplatesUserSettings()
this.templateForDeletion = ko.observable(null).deleteAccessHelper();
}
TemplatesUserSettings.prototype.scrollableOptions = function(sWrapper)
{
return {
handle: '.drag-handle',
containment: sWrapper || 'parent',
axis: 'y'
};
};
TemplatesUserSettings.prototype.addNewTemplate = function()
{
require('Knoin/Knoin').showScreenPopup(require('View/Popup/Template'));
};
TemplatesUserSettings.prototype.editTemplate = function(oTemplateItem)
{
if (oTemplateItem)
{ {
this.templates = TemplateStore.templates; require('Knoin/Knoin').showScreenPopup(require('View/Popup/Template'), [oTemplateItem]);
this.processText = ko.computed(function () {
return TemplateStore.templates.loading() ? Translator.i18n('SETTINGS_TEMPLETS/LOADING_PROCESS') : '';
}, this);
this.visibility = ko.computed(function () {
return '' === this.processText() ? 'hidden' : 'visible';
}, this);
this.templateForDeletion = ko.observable(null).deleteAccessHelper();
} }
};
TemplatesUserSettings.prototype.scrollableOptions = function (sWrapper) /**
* @param {AccountModel} oTemplateToRemove
*/
TemplatesUserSettings.prototype.deleteTemplate = function(oTemplateToRemove)
{
if (oTemplateToRemove && oTemplateToRemove.deleteAccess())
{ {
return { this.templateForDeletion(null);
handle: '.drag-handle',
containment: sWrapper || 'parent',
axis: 'y'
};
};
TemplatesUserSettings.prototype.addNewTemplate = function () var
{ self = this,
require('Knoin/Knoin').showScreenPopup(require('View/Popup/Template')); fRemoveAccount = function(oAccount) {
}; return oTemplateToRemove === oAccount;
};
TemplatesUserSettings.prototype.editTemplate = function (oTemplateItem) if (oTemplateToRemove)
{
if (oTemplateItem)
{ {
require('Knoin/Knoin').showScreenPopup(require('View/Popup/Template'), [oTemplateItem]); this.templates.remove(fRemoveAccount);
Remote.templateDelete(function() {
self.reloadTemplates();
}, oTemplateToRemove.id);
} }
}; }
};
/** TemplatesUserSettings.prototype.reloadTemplates = function()
* @param {AccountModel} oTemplateToRemove {
*/ require('App/User').default.templates();
TemplatesUserSettings.prototype.deleteTemplate = function (oTemplateToRemove) };
{
if (oTemplateToRemove && oTemplateToRemove.deleteAccess())
{
this.templateForDeletion(null);
var TemplatesUserSettings.prototype.onBuild = function(oDom)
self = this, {
fRemoveAccount = function (oAccount) { var self = this;
return oTemplateToRemove === oAccount;
}
;
if (oTemplateToRemove) oDom
.on('click', '.templates-list .template-item .e-action', function() {
var oTemplateItem = ko.dataFor(this);
if (oTemplateItem)
{ {
this.templates.remove(fRemoveAccount); self.editTemplate(oTemplateItem);
Remote.templateDelete(function () {
self.reloadTemplates();
}, oTemplateToRemove.id);
} }
} });
};
TemplatesUserSettings.prototype.reloadTemplates = function () this.reloadTemplates();
{ };
require('App/User').default.templates();
};
TemplatesUserSettings.prototype.onBuild = function (oDom) module.exports = TemplatesUserSettings;
{
var self = this;
oDom
.on('click', '.templates-list .template-item .e-action', function () {
var oTemplateItem = ko.dataFor(this);
if (oTemplateItem)
{
self.editTemplate(oTemplateItem);
}
})
;
this.reloadTemplates();
};
module.exports = TemplatesUserSettings;
}());

View file

@ -1,185 +1,177 @@
(function () { var
_ = require('_'),
$ = require('$'),
ko = require('ko'),
'use strict'; Jua = require('Jua'),
var Enums = require('Common/Enums'),
_ = require('_'), Utils = require('Common/Utils'),
$ = require('$'), Links = require('Common/Links'),
ko = require('ko'), Translator = require('Common/Translator'),
Jua = require('Jua'), ThemeStore = require('Stores/Theme'),
Enums = require('Common/Enums'), Settings = require('Storage/Settings'),
Utils = require('Common/Utils'),
Links = require('Common/Links'),
Translator = require('Common/Translator'),
ThemeStore = require('Stores/Theme'), Remote = require('Remote/User/Ajax');
Settings = require('Storage/Settings'), /**
* @constructor
*/
function ThemesUserSettings()
{
this.theme = ThemeStore.theme;
this.themes = ThemeStore.themes;
this.themesObjects = ko.observableArray([]);
Remote = require('Remote/User/Ajax') this.background = {};
; this.background.name = ThemeStore.themeBackgroundName;
this.background.hash = ThemeStore.themeBackgroundHash;
this.background.uploaderButton = ko.observable(null);
this.background.loading = ko.observable(false);
this.background.error = ko.observable('');
/** this.capaUserBackground = ko.observable(Settings.capa(Enums.Capa.UserBackground));
* @constructor
*/ this.themeTrigger = ko.observable(Enums.SaveSettingsStep.Idle).extend({'throttle': 100});
function ThemesUserSettings()
this.iTimer = 0;
this.oThemeAjaxRequest = null;
this.theme.subscribe(function(sValue) {
_.each(this.themesObjects(), function(oTheme) {
oTheme.selected(sValue === oTheme.name);
});
Utils.changeTheme(sValue, this.themeTrigger);
Remote.saveSettings(null, {
'Theme': sValue
});
}, this);
this.background.hash.subscribe(function(sValue) {
var $oBg = $('#rl-bg');
if (!sValue)
{
if ($oBg.data('backstretch'))
{
$oBg.backstretch('destroy').attr('style', '');
}
}
else
{
$('#rl-bg').attr('style', 'background-image: none !important;').backstretch(
Links.userBackground(sValue), {
'fade': 1000, 'centeredX': true, 'centeredY': true
}).removeAttr('style');
}
}, this);
}
ThemesUserSettings.prototype.onBuild = function()
{
var sCurrentTheme = this.theme();
this.themesObjects(_.map(this.themes(), function(sTheme) {
return {
'name': sTheme,
'nameDisplay': Utils.convertThemeName(sTheme),
'selected': ko.observable(sTheme === sCurrentTheme),
'themePreviewSrc': Links.themePreviewLink(sTheme)
};
}));
this.initUploader();
};
ThemesUserSettings.prototype.onShow = function()
{
this.background.error('');
};
ThemesUserSettings.prototype.clearBackground = function()
{
if (this.capaUserBackground())
{ {
this.theme = ThemeStore.theme; var self = this;
this.themes = ThemeStore.themes; Remote.clearUserBackground(function() {
this.themesObjects = ko.observableArray([]); self.background.name('');
self.background.hash('');
this.background = {}; });
this.background.name = ThemeStore.themeBackgroundName;
this.background.hash = ThemeStore.themeBackgroundHash;
this.background.uploaderButton = ko.observable(null);
this.background.loading = ko.observable(false);
this.background.error = ko.observable('');
this.capaUserBackground = ko.observable(Settings.capa(Enums.Capa.UserBackground));
this.themeTrigger = ko.observable(Enums.SaveSettingsStep.Idle).extend({'throttle': 100});
this.iTimer = 0;
this.oThemeAjaxRequest = null;
this.theme.subscribe(function (sValue) {
_.each(this.themesObjects(), function (oTheme) {
oTheme.selected(sValue === oTheme.name);
});
Utils.changeTheme(sValue, this.themeTrigger);
Remote.saveSettings(null, {
'Theme': sValue
});
}, this);
this.background.hash.subscribe(function (sValue) {
var $oBg = $('#rl-bg');
if (!sValue)
{
if ($oBg.data('backstretch'))
{
$oBg.backstretch('destroy').attr('style', '');
}
}
else
{
$('#rl-bg').attr('style', 'background-image: none !important;').backstretch(
Links.userBackground(sValue), {
'fade': 1000, 'centeredX': true, 'centeredY': true
}).removeAttr('style');
}
}, this);
} }
};
ThemesUserSettings.prototype.onBuild = function () ThemesUserSettings.prototype.initUploader = function()
{
if (this.background.uploaderButton() && this.capaUserBackground())
{ {
var sCurrentTheme = this.theme(); var
this.themesObjects(_.map(this.themes(), function (sTheme) { oJua = new Jua({
return { 'action': Links.uploadBackground(),
'name': sTheme, 'name': 'uploader',
'nameDisplay': Utils.convertThemeName(sTheme), 'queueSize': 1,
'selected': ko.observable(sTheme === sCurrentTheme), 'multipleSizeLimit': 1,
'themePreviewSrc': Links.themePreviewLink(sTheme) 'disableDragAndDrop': true,
}; 'disableMultiple': true,
})); 'clickElement': this.background.uploaderButton()
this.initUploader();
};
ThemesUserSettings.prototype.onShow = function ()
{
this.background.error('');
};
ThemesUserSettings.prototype.clearBackground = function ()
{
if (this.capaUserBackground())
{
var self = this;
Remote.clearUserBackground(function () {
self.background.name('');
self.background.hash('');
}); });
}
};
ThemesUserSettings.prototype.initUploader = function () oJua
{ .on('onStart', _.bind(function() {
if (this.background.uploaderButton() && this.capaUserBackground())
{
var
oJua = new Jua({
'action': Links.uploadBackground(),
'name': 'uploader',
'queueSize': 1,
'multipleSizeLimit': 1,
'disableDragAndDrop': true,
'disableMultiple': true,
'clickElement': this.background.uploaderButton()
})
;
oJua this.background.loading(true);
.on('onStart', _.bind(function () { this.background.error('');
this.background.loading(true); return true;
this.background.error('');
return true; }, this))
.on('onComplete', _.bind(function(sId, bResult, oData) {
}, this)) this.background.loading(false);
.on('onComplete', _.bind(function (sId, bResult, oData) {
this.background.loading(false); if (bResult && sId && oData && oData.Result && oData.Result.Name && oData.Result.Hash)
{
this.background.name(oData.Result.Name);
this.background.hash(oData.Result.Hash);
}
else
{
this.background.name('');
this.background.hash('');
if (bResult && sId && oData && oData.Result && oData.Result.Name && oData.Result.Hash) var sError = '';
if (oData.ErrorCode)
{ {
this.background.name(oData.Result.Name); switch (oData.ErrorCode)
this.background.hash(oData.Result.Hash);
}
else
{
this.background.name('');
this.background.hash('');
var sError = '';
if (oData.ErrorCode)
{ {
switch (oData.ErrorCode) case Enums.UploadErrorCode.FileIsTooBig:
{ sError = Translator.i18n('SETTINGS_THEMES/ERROR_FILE_IS_TOO_BIG');
case Enums.UploadErrorCode.FileIsTooBig: break;
sError = Translator.i18n('SETTINGS_THEMES/ERROR_FILE_IS_TOO_BIG'); case Enums.UploadErrorCode.FileType:
break; sError = Translator.i18n('SETTINGS_THEMES/ERROR_FILE_TYPE_ERROR');
case Enums.UploadErrorCode.FileType: break;
sError = Translator.i18n('SETTINGS_THEMES/ERROR_FILE_TYPE_ERROR'); // no default
break;
}
} }
if (!sError && oData.ErrorMessage)
{
sError = oData.ErrorMessage;
}
this.background.error(sError || Translator.i18n('SETTINGS_THEMES/ERROR_UNKNOWN'));
} }
return true; if (!sError && oData.ErrorMessage)
{
sError = oData.ErrorMessage;
}
}, this)) this.background.error(sError || Translator.i18n('SETTINGS_THEMES/ERROR_UNKNOWN'));
; }
}
};
module.exports = ThemesUserSettings; return true;
}()); }, this));
}
};
module.exports = ThemesUserSettings;

View file

@ -12,7 +12,7 @@ const driver = SupportedStorageDriver ? new SupportedStorageDriver() : null;
/** /**
* @param {number} key * @param {number} key
* @param {*} data * @param {*} data
* @return {boolean} * @returns {boolean}
*/ */
export function set(key, data) export function set(key, data)
{ {
@ -21,7 +21,7 @@ export function set(key, data)
/** /**
* @param {number} key * @param {number} key
* @return {*} * @returns {*}
*/ */
export function get(key) export function get(key)
{ {

View file

@ -45,35 +45,43 @@ const timestamp = () => window.Math.round((new window.Date()).getTime() / 1000);
const setTimestamp = () => __set(TIME_KEY, timestamp()); const setTimestamp = () => __set(TIME_KEY, timestamp());
const getTimestamp = () => { const getTimestamp = () => {
let time = __get(TIME_KEY, 0); const time = __get(TIME_KEY, 0);
return time ? (window.parseInt(time, 10) || 0) : 0; return time ? (window.parseInt(time, 10) || 0) : 0;
}; };
/** /**
* @return {string} * @returns {string}
*/ */
export function getHash() export function getHash()
{ {
return __get(STORAGE_KEY); return __get(STORAGE_KEY);
} }
/**
* @returns {void}
*/
export function setHash() export function setHash()
{ {
const const
key = 'AuthAccountHash', key = 'AuthAccountHash',
appData = window.__rlah_data() appData = window.__rlah_data();
;
__set(STORAGE_KEY, appData && appData[key] ? appData[key] : ''); __set(STORAGE_KEY, appData && appData[key] ? appData[key] : '');
setTimestamp(); setTimestamp();
} }
/**
* @returns {void}
*/
export function clearHash() export function clearHash()
{ {
__set(STORAGE_KEY, ''); __set(STORAGE_KEY, '');
setTimestamp(); setTimestamp();
} }
/**
* @returns {boolean}
*/
export function checkTimestamp() export function checkTimestamp()
{ {
if (timestamp() > getTimestamp() + 1000 * 60 * 60) // 60m if (timestamp() > getTimestamp() + 1000 * 60 * 60) // 60m

View file

@ -10,7 +10,7 @@ APP_SETTINGS = isNormal(APP_SETTINGS) ? APP_SETTINGS : {};
/** /**
* @param {string} name * @param {string} name
* @return {*} * @returns {*}
*/ */
export function settingsGet(name) export function settingsGet(name)
{ {
@ -28,7 +28,7 @@ export function settingsSet(name, value)
/** /**
* @param {string} name * @param {string} name
* @return {*} * @returns {*}
*/ */
export function appSettingsGet(name) export function appSettingsGet(name)
{ {
@ -37,7 +37,7 @@ export function appSettingsGet(name)
/** /**
* @param {string} name * @param {string} name
* @return {boolean} * @returns {boolean}
*/ */
export function capa(name) export function capa(name)
{ {

View file

@ -12,7 +12,7 @@ class AbstractAppStore
this.interfaceAnimation = ko.observable(true); this.interfaceAnimation = ko.observable(true);
this.interfaceAnimation.subscribe(function (bValue) { this.interfaceAnimation.subscribe(function(bValue) {
const bAnim = bMobileDevice || !bValue; const bAnim = bMobileDevice || !bValue;
$html.toggleClass('rl-anim', !bAnim).toggleClass('no-rl-anim', bAnim); $html.toggleClass('rl-anim', !bAnim).toggleClass('no-rl-anim', bAnim);
}); });

View file

@ -1,51 +1,44 @@
(function () { var
ko = require('ko'),
'use strict'; Enums = require('Common/Enums'),
var Settings = require('Storage/Settings');
ko = require('ko'),
Enums = require('Common/Enums'), /**
* @constructor
*/
function CapaAdminStore()
{
this.additionalAccounts = ko.observable(false);
this.identities = ko.observable(false);
this.gravatar = ko.observable(false);
this.attachmentThumbnails = ko.observable(false);
this.sieve = ko.observable(false);
this.filters = ko.observable(false);
this.themes = ko.observable(true);
this.userBackground = ko.observable(false);
this.openPGP = ko.observable(false);
this.twoFactorAuth = ko.observable(false);
this.twoFactorAuthForce = ko.observable(false);
this.templates = ko.observable(false);
}
Settings = require('Storage/Settings') CapaAdminStore.prototype.populate = function()
; {
this.additionalAccounts(Settings.capa(Enums.Capa.AdditionalAccounts));
this.identities(Settings.capa(Enums.Capa.Identities));
this.gravatar(Settings.capa(Enums.Capa.Gravatar));
this.attachmentThumbnails(Settings.capa(Enums.Capa.AttachmentThumbnails));
this.sieve(Settings.capa(Enums.Capa.Sieve));
this.filters(Settings.capa(Enums.Capa.Filters));
this.themes(Settings.capa(Enums.Capa.Themes));
this.userBackground(Settings.capa(Enums.Capa.UserBackground));
this.openPGP(Settings.capa(Enums.Capa.OpenPGP));
this.twoFactorAuth(Settings.capa(Enums.Capa.TwoFactor));
this.twoFactorAuthForce(Settings.capa(Enums.Capa.TwoFactorForce));
this.templates(Settings.capa(Enums.Capa.Templates));
};
/** module.exports = new CapaAdminStore();
* @constructor
*/
function CapaAdminStore()
{
this.additionalAccounts = ko.observable(false);
this.identities = ko.observable(false);
this.gravatar = ko.observable(false);
this.attachmentThumbnails = ko.observable(false);
this.sieve = ko.observable(false);
this.filters = ko.observable(false);
this.themes = ko.observable(true);
this.userBackground = ko.observable(false);
this.openPGP = ko.observable(false);
this.twoFactorAuth = ko.observable(false);
this.twoFactorAuthForce = ko.observable(false);
this.templates = ko.observable(false);
}
CapaAdminStore.prototype.populate = function()
{
this.additionalAccounts(Settings.capa(Enums.Capa.AdditionalAccounts));
this.identities(Settings.capa(Enums.Capa.Identities));
this.gravatar(Settings.capa(Enums.Capa.Gravatar));
this.attachmentThumbnails(Settings.capa(Enums.Capa.AttachmentThumbnails));
this.sieve(Settings.capa(Enums.Capa.Sieve));
this.filters(Settings.capa(Enums.Capa.Filters));
this.themes(Settings.capa(Enums.Capa.Themes));
this.userBackground(Settings.capa(Enums.Capa.UserBackground));
this.openPGP(Settings.capa(Enums.Capa.OpenPGP));
this.twoFactorAuth(Settings.capa(Enums.Capa.TwoFactor));
this.twoFactorAuthForce(Settings.capa(Enums.Capa.TwoFactorForce));
this.templates(Settings.capa(Enums.Capa.Templates));
};
module.exports = new CapaAdminStore();
}());

View file

@ -1,31 +1,23 @@
(function () { var ko = require('ko');
'use strict'; /**
* @constructor
*/
function CoreAdminStore()
{
this.coreReal = ko.observable(true);
this.coreChannel = ko.observable('stable');
this.coreType = ko.observable('stable');
this.coreUpdatable = ko.observable(true);
this.coreAccess = ko.observable(true);
this.coreWarning = ko.observable(false);
this.coreChecking = ko.observable(false).extend({'throttle': 100});
this.coreUpdating = ko.observable(false).extend({'throttle': 100});
this.coreVersion = ko.observable('');
this.coreRemoteVersion = ko.observable('');
this.coreRemoteRelease = ko.observable('');
this.coreVersionCompare = ko.observable(-2);
}
var module.exports = new CoreAdminStore();
ko = require('ko')
;
/**
* @constructor
*/
function CoreAdminStore()
{
this.coreReal = ko.observable(true);
this.coreChannel = ko.observable('stable');
this.coreType = ko.observable('stable');
this.coreUpdatable = ko.observable(true);
this.coreAccess = ko.observable(true);
this.coreWarning = ko.observable(false);
this.coreChecking = ko.observable(false).extend({'throttle': 100});
this.coreUpdating = ko.observable(false).extend({'throttle': 100});
this.coreVersion = ko.observable('');
this.coreRemoteVersion = ko.observable('');
this.coreRemoteRelease = ko.observable('');
this.coreVersionCompare = ko.observable(-2);
}
module.exports = new CoreAdminStore();
}());

View file

@ -1,25 +1,17 @@
(function () { var ko = require('ko');
'use strict'; /**
* @constructor
*/
function DomainAdminStore()
{
this.domains = ko.observableArray([]);
this.domains.loading = ko.observable(false).extend({'throttle': 100});
var this.domainsWithoutAliases = this.domains.filter(function(oItem) {
ko = require('ko') return oItem && !oItem.alias;
; });
}
/** module.exports = new DomainAdminStore();
* @constructor
*/
function DomainAdminStore()
{
this.domains = ko.observableArray([]);
this.domains.loading = ko.observable(false).extend({'throttle': 100});
this.domainsWithoutAliases = this.domains.filter(function (oItem) {
return oItem && !oItem.alias;
});
}
module.exports = new DomainAdminStore();
}());

View file

@ -1,26 +1,18 @@
(function () { var ko = require('ko');
'use strict'; /**
* @constructor
*/
function LicenseAdminStore()
{
this.licensing = ko.observable(false);
this.licensingProcess = ko.observable(false);
this.licenseValid = ko.observable(false);
this.licenseExpired = ko.observable(0);
this.licenseError = ko.observable('');
var this.licenseTrigger = ko.observable(false);
ko = require('ko') }
;
/** module.exports = new LicenseAdminStore();
* @constructor
*/
function LicenseAdminStore()
{
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);
}
module.exports = new LicenseAdminStore();
}());

View file

@ -1,24 +1,16 @@
(function () { var ko = require('ko');
'use strict'; /**
* @constructor
*/
function PackageAdminStore()
{
this.packages = ko.observableArray([]);
this.packages.loading = ko.observable(false).extend({'throttle': 100});
var this.packagesReal = ko.observable(true);
ko = require('ko') this.packagesMainUpdatable = ko.observable(true);
; }
/** module.exports = new PackageAdminStore();
* @constructor
*/
function PackageAdminStore()
{
this.packages = ko.observableArray([]);
this.packages.loading = ko.observable(false).extend({'throttle': 100});
this.packagesReal = ko.observable(true);
this.packagesMainUpdatable = ko.observable(true);
}
module.exports = new PackageAdminStore();
}());

View file

@ -1,22 +1,14 @@
(function () { var ko = require('ko');
'use strict'; /**
* @constructor
*/
function PluginAdminStore()
{
this.plugins = ko.observableArray([]);
this.plugins.loading = ko.observable(false).extend({'throttle': 100});
this.plugins.error = ko.observable('');
}
var module.exports = new PluginAdminStore();
ko = require('ko')
;
/**
* @constructor
*/
function PluginAdminStore()
{
this.plugins = ko.observableArray([]);
this.plugins.loading = ko.observable(false).extend({'throttle': 100});
this.plugins.error = ko.observable('');
}
module.exports = new PluginAdminStore();
}());

View file

@ -1,55 +1,45 @@
(function () { var
ko = require('ko'),
'use strict'; Utils = require('Common/Utils'),
Settings = require('Storage/Settings');
/**
* @constructor
*/
function LanguageStore()
{
this.languages = ko.observableArray([]);
this.languagesAdmin = ko.observableArray([]);
this.language = ko.observable('')
.extend({'limitedList': this.languages})
.extend({'reversible': true});
this.languageAdmin = ko.observable('')
.extend({'limitedList': this.languagesAdmin})
.extend({'reversible': true});
this.userLanguage = ko.observable('');
this.userLanguageAdmin = ko.observable('');
}
LanguageStore.prototype.populate = function()
{
var var
ko = require('ko'), aLanguages = Settings.appSettingsGet('languages'),
aLanguagesAdmin = Settings.appSettingsGet('languagesAdmin');
Utils = require('Common/Utils'), this.languages(Utils.isArray(aLanguages) ? aLanguages : []);
this.languagesAdmin(Utils.isArray(aLanguagesAdmin) ? aLanguagesAdmin : []);
Settings = require('Storage/Settings') this.language(Settings.settingsGet('Language'));
; this.languageAdmin(Settings.settingsGet('LanguageAdmin'));
/** this.userLanguage(Settings.settingsGet('UserLanguage'));
* @constructor this.userLanguageAdmin(Settings.settingsGet('UserLanguageAdmin'));
*/ };
function LanguageStore()
{
this.languages = ko.observableArray([]);
this.languagesAdmin = ko.observableArray([]);
this.language = ko.observable('') module.exports = new LanguageStore();
.extend({'limitedList': this.languages})
.extend({'reversible': true})
;
this.languageAdmin = ko.observable('')
.extend({'limitedList': this.languagesAdmin})
.extend({'reversible': true})
;
this.userLanguage = ko.observable('');
this.userLanguageAdmin = ko.observable('');
}
LanguageStore.prototype.populate = function ()
{
var
aLanguages = Settings.appSettingsGet('languages'),
aLanguagesAdmin = Settings.appSettingsGet('languagesAdmin')
;
this.languages(Utils.isArray(aLanguages) ? aLanguages : []);
this.languagesAdmin(Utils.isArray(aLanguagesAdmin) ? aLanguagesAdmin : []);
this.language(Settings.settingsGet('Language'));
this.languageAdmin(Settings.settingsGet('LanguageAdmin'));
this.userLanguage(Settings.settingsGet('UserLanguage'));
this.userLanguageAdmin(Settings.settingsGet('UserLanguageAdmin'));
};
module.exports = new LanguageStore();
}());

View file

@ -1,111 +1,103 @@
(function () { var ko = require('ko');
'use strict'; /**
* @constructor
*/
function SocialStore()
{
this.google = {};
this.twitter = {};
this.facebook = {};
this.dropbox = {};
var // Google
ko = require('ko') this.google.enabled = ko.observable(false);
;
/** this.google.clientID = ko.observable('');
* @constructor this.google.clientSecret = ko.observable('');
*/ this.google.apiKey = ko.observable('');
function SocialStore()
{
this.google = {};
this.twitter = {};
this.facebook = {};
this.dropbox = {};
// Google this.google.loading = ko.observable(false);
this.google.enabled = ko.observable(false); this.google.userName = ko.observable('');
this.google.clientID = ko.observable(''); this.google.loggined = ko.computed(function() {
this.google.clientSecret = ko.observable(''); return '' !== this.google.userName();
this.google.apiKey = ko.observable(''); }, this);
this.google.loading = ko.observable(false); this.google.capa = {};
this.google.userName = ko.observable(''); this.google.capa.auth = ko.observable(false);
this.google.capa.authFast = ko.observable(false);
this.google.capa.drive = ko.observable(false);
this.google.capa.preview = ko.observable(false);
this.google.loggined = ko.computed(function () { this.google.require = {};
return '' !== this.google.userName(); this.google.require.clientSettings = ko.computed(function() {
}, this); return this.google.enabled() && (this.google.capa.auth() || this.google.capa.drive());
}, this);
this.google.capa = {}; this.google.require.apiKeySettings = ko.computed(function() {
this.google.capa.auth = ko.observable(false); return this.google.enabled() && this.google.capa.drive();
this.google.capa.authFast = ko.observable(false); }, this);
this.google.capa.drive = ko.observable(false);
this.google.capa.preview = ko.observable(false);
this.google.require = {}; // Facebook
this.google.require.clientSettings = ko.computed(function () { this.facebook.enabled = ko.observable(false);
return this.google.enabled() && (this.google.capa.auth() || this.google.capa.drive()); this.facebook.appID = ko.observable('');
}, this); this.facebook.appSecret = ko.observable('');
this.facebook.loading = ko.observable(false);
this.facebook.userName = ko.observable('');
this.facebook.supported = ko.observable(false);
this.google.require.apiKeySettings = ko.computed(function () { this.facebook.loggined = ko.computed(function() {
return this.google.enabled() && this.google.capa.drive(); return '' !== this.facebook.userName();
}, this); }, this);
// Facebook // Twitter
this.facebook.enabled = ko.observable(false); this.twitter.enabled = ko.observable(false);
this.facebook.appID = ko.observable(''); this.twitter.consumerKey = ko.observable('');
this.facebook.appSecret = ko.observable(''); this.twitter.consumerSecret = ko.observable('');
this.facebook.loading = ko.observable(false); this.twitter.loading = ko.observable(false);
this.facebook.userName = ko.observable(''); this.twitter.userName = ko.observable('');
this.facebook.supported = ko.observable(false);
this.facebook.loggined = ko.computed(function () { this.twitter.loggined = ko.computed(function() {
return '' !== this.facebook.userName(); return '' !== this.twitter.userName();
}, this); }, this);
// Twitter // Dropbox
this.twitter.enabled = ko.observable(false); this.dropbox.enabled = ko.observable(false);
this.twitter.consumerKey = ko.observable(''); this.dropbox.apiKey = ko.observable('');
this.twitter.consumerSecret = ko.observable(''); }
this.twitter.loading = ko.observable(false);
this.twitter.userName = ko.observable('');
this.twitter.loggined = ko.computed(function () { SocialStore.prototype.google = {};
return '' !== this.twitter.userName(); SocialStore.prototype.twitter = {};
}, this); SocialStore.prototype.facebook = {};
SocialStore.prototype.dropbox = {};
// Dropbox SocialStore.prototype.populate = function()
this.dropbox.enabled = ko.observable(false); {
this.dropbox.apiKey = ko.observable(''); var Settings = require('Storage/Settings');
}
SocialStore.prototype.google = {}; this.google.enabled(!!Settings.settingsGet('AllowGoogleSocial'));
SocialStore.prototype.twitter = {}; this.google.clientID(Settings.settingsGet('GoogleClientID'));
SocialStore.prototype.facebook = {}; this.google.clientSecret(Settings.settingsGet('GoogleClientSecret'));
SocialStore.prototype.dropbox = {}; this.google.apiKey(Settings.settingsGet('GoogleApiKey'));
SocialStore.prototype.populate = function () this.google.capa.auth(!!Settings.settingsGet('AllowGoogleSocialAuth'));
{ this.google.capa.authFast(!!Settings.settingsGet('AllowGoogleSocialAuthFast'));
var Settings = require('Storage/Settings'); this.google.capa.drive(!!Settings.settingsGet('AllowGoogleSocialDrive'));
this.google.capa.preview(!!Settings.settingsGet('AllowGoogleSocialPreview'));
this.google.enabled(!!Settings.settingsGet('AllowGoogleSocial')); this.facebook.enabled(!!Settings.settingsGet('AllowFacebookSocial'));
this.google.clientID(Settings.settingsGet('GoogleClientID')); this.facebook.appID(Settings.settingsGet('FacebookAppID'));
this.google.clientSecret(Settings.settingsGet('GoogleClientSecret')); this.facebook.appSecret(Settings.settingsGet('FacebookAppSecret'));
this.google.apiKey(Settings.settingsGet('GoogleApiKey')); this.facebook.supported(!!Settings.settingsGet('SupportedFacebookSocial'));
this.google.capa.auth(!!Settings.settingsGet('AllowGoogleSocialAuth')); this.twitter.enabled = ko.observable(!!Settings.settingsGet('AllowTwitterSocial'));
this.google.capa.authFast(!!Settings.settingsGet('AllowGoogleSocialAuthFast')); this.twitter.consumerKey = ko.observable(Settings.settingsGet('TwitterConsumerKey'));
this.google.capa.drive(!!Settings.settingsGet('AllowGoogleSocialDrive')); this.twitter.consumerSecret = ko.observable(Settings.settingsGet('TwitterConsumerSecret'));
this.google.capa.preview(!!Settings.settingsGet('AllowGoogleSocialPreview'));
this.facebook.enabled(!!Settings.settingsGet('AllowFacebookSocial')); this.dropbox.enabled(!!Settings.settingsGet('AllowDropboxSocial'));
this.facebook.appID(Settings.settingsGet('FacebookAppID')); this.dropbox.apiKey(Settings.settingsGet('DropboxApiKey'));
this.facebook.appSecret(Settings.settingsGet('FacebookAppSecret')); };
this.facebook.supported(!!Settings.settingsGet('SupportedFacebookSocial'));
this.twitter.enabled = ko.observable(!!Settings.settingsGet('AllowTwitterSocial')); module.exports = new SocialStore();
this.twitter.consumerKey = ko.observable(Settings.settingsGet('TwitterConsumerKey'));
this.twitter.consumerSecret = ko.observable(Settings.settingsGet('TwitterConsumerSecret'));
this.dropbox.enabled(!!Settings.settingsGet('AllowDropboxSocial'));
this.dropbox.apiKey(Settings.settingsGet('DropboxApiKey'));
};
module.exports = new SocialStore();
}());

View file

@ -1,39 +1,32 @@
(function () { var
ko = require('ko'),
'use strict'; Utils = require('Common/Utils'),
var Settings = require('Storage/Settings');
ko = require('ko'),
Utils = require('Common/Utils'), /**
* @constructor
*/
function ThemeStore()
{
this.themes = ko.observableArray([]);
this.themeBackgroundName = ko.observable('');
this.themeBackgroundHash = ko.observable('');
Settings = require('Storage/Settings') this.theme = ko.observable('')
; .extend({'limitedList': this.themes});
}
/** ThemeStore.prototype.populate = function()
* @constructor {
*/ var aThemes = Settings.appSettingsGet('themes');
function ThemeStore()
{
this.themes = ko.observableArray([]);
this.themeBackgroundName = ko.observable('');
this.themeBackgroundHash = ko.observable('');
this.theme = ko.observable('') this.themes(Utils.isArray(aThemes) ? aThemes : []);
.extend({'limitedList': this.themes}); this.theme(Settings.settingsGet('Theme'));
} this.themeBackgroundName(Settings.settingsGet('UserBackgroundName'));
this.themeBackgroundHash(Settings.settingsGet('UserBackgroundHash'));
};
ThemeStore.prototype.populate = function () module.exports = new ThemeStore();
{
var aThemes = Settings.appSettingsGet('themes');
this.themes(Utils.isArray(aThemes) ? aThemes : []);
this.theme(Settings.settingsGet('Theme'));
this.themeBackgroundName(Settings.settingsGet('UserBackgroundName'));
this.themeBackgroundHash(Settings.settingsGet('UserBackgroundHash'));
};
module.exports = new ThemeStore();
}());

View file

@ -1,71 +1,64 @@
(function () { var
_ = require('_'),
ko = require('ko'),
'use strict'; Settings = require('Storage/Settings');
var /**
_ = require('_'), * @constructor
ko = require('ko'), */
function AccountUserStore()
Settings = require('Storage/Settings') {
; this.email = ko.observable('');
this.parentEmail = ko.observable('');
/**
* @constructor
*/
function AccountUserStore()
{
this.email = ko.observable('');
this.parentEmail = ko.observable('');
// this.incLogin = ko.observable(''); // this.incLogin = ko.observable('');
// this.outLogin = ko.observable(''); // this.outLogin = ko.observable('');
this.signature = ko.observable(''); this.signature = ko.observable('');
this.accounts = ko.observableArray([]); this.accounts = ko.observableArray([]);
this.accounts.loading = ko.observable(false).extend({'throttle': 100}); this.accounts.loading = ko.observable(false).extend({'throttle': 100});
this.computers(); this.computers();
} }
AccountUserStore.prototype.computers = function () AccountUserStore.prototype.computers = function()
{ {
this.accountsEmails = ko.computed(function () { this.accountsEmails = ko.computed(function() {
return _.compact(_.map(this.accounts(), function (oItem) { return _.compact(_.map(this.accounts(), function(oItem) {
return oItem ? oItem.email : null; return oItem ? oItem.email : null;
})); }));
}, this); }, this);
this.accountsUnreadCount = ko.computed(function () { this.accountsUnreadCount = ko.computed(function() {
var iResult = 0; var iResult = 0;
// _.each(this.accounts(), function (oItem) { // _.each(this.accounts(), function(oItem) {
// if (oItem) // if (oItem)
// { // {
// iResult += oItem.count(); // iResult += oItem.count();
// } // }
// }); // });
return iResult; return iResult;
}, this); }, this);
}; };
AccountUserStore.prototype.populate = function () AccountUserStore.prototype.populate = function()
{ {
this.email(Settings.settingsGet('Email')); this.email(Settings.settingsGet('Email'));
this.parentEmail(Settings.settingsGet('ParentEmail')); this.parentEmail(Settings.settingsGet('ParentEmail'));
}; };
/** /**
* @return {boolean} * @returns {boolean}
*/ */
AccountUserStore.prototype.isRootAccount = function () AccountUserStore.prototype.isRootAccount = function()
{ {
return '' === this.parentEmail(); return '' === this.parentEmail();
}; };
module.exports = new AccountUserStore(); module.exports = new AccountUserStore();
}());

View file

@ -17,12 +17,10 @@ class AppUserStore extends AbstractAppStore
this.focusedState = ko.observable(Focused.None); this.focusedState = ko.observable(Focused.None);
this.focusedState.subscribe(function (value) { this.focusedState.subscribe(function(value) {
switch (value) switch (value)
{ {
default:
break;
case Focused.MessageList: case Focused.MessageList:
keyScope(KeyState.MessageList); keyScope(KeyState.MessageList);
break; break;
@ -32,6 +30,8 @@ class AppUserStore extends AbstractAppStore
case Focused.FolderList: case Focused.FolderList:
keyScope(KeyState.FolderList); keyScope(KeyState.FolderList);
break; break;
default:
break;
} }
}, this); }, this);

Some files were not shown because too many files have changed in this diff Show more