From 929aadd3e16e1b1a1790c198f2023e758463c210 Mon Sep 17 00:00:00 2001 From: cdujeu Date: Fri, 16 Oct 2015 14:52:18 +0200 Subject: [PATCH] Remove compiled resources. Update move dependencies at top level of gui.ajax. --- core/src/plugins/gui.ajax/Gruntfile.js | 46 +- core/src/plugins/gui.ajax/package.json | 14 +- .../src/plugins/gui.ajax/res/js/core/Pydio.js | 848 ++++++----- .../gui.ajax/res/js/core/http/PydioApi.js | 865 +++++------ .../res/js/core/http/ResourcesManager.js | 757 +++++----- .../gui.ajax/res/js/core/lang/Logger.js | 31 +- .../gui.ajax/res/js/core/lang/Observable.js | 95 +- .../gui.ajax/res/js/core/model/Action.js | 1250 ++++++++-------- .../gui.ajax/res/js/core/model/AjxpNode.js | 772 +++++----- .../js/core/model/BackgroundTasksManager.js | 255 ++-- .../gui.ajax/res/js/core/model/Controller.js | 926 ++++++------ .../res/js/core/model/EmptyNodeProvider.js | 47 +- .../res/js/core/model/PydioDataModel.js | 1332 +++++++++-------- .../gui.ajax/res/js/core/model/Registry.js | 556 +++---- .../res/js/core/model/RemoteNodeProvider.js | 447 +++--- .../gui.ajax/res/js/core/model/Repository.js | 308 ++-- .../gui.ajax/res/js/core/model/Router.js | 6 +- .../gui.ajax/res/js/core/model/User.js | 472 +++--- .../gui.ajax/res/js/core/util/HasherUtils.js | 693 ++++----- .../gui.ajax/res/js/core/util/LangUtils.js | 207 +-- .../gui.ajax/res/js/core/util/PathUtils.js | 144 +- .../gui.ajax/res/js/core/util/XMLUtils.js | 306 ++-- 22 files changed, 5417 insertions(+), 4960 deletions(-) diff --git a/core/src/plugins/gui.ajax/Gruntfile.js b/core/src/plugins/gui.ajax/Gruntfile.js index 151546276b..8dde66f8ba 100644 --- a/core/src/plugins/gui.ajax/Gruntfile.js +++ b/core/src/plugins/gui.ajax/Gruntfile.js @@ -5,7 +5,7 @@ module.exports = function(grunt) { mangle: false, compress: { hoist_funs: false - }, + } }, js: { files: { @@ -93,10 +93,10 @@ module.exports = function(grunt) { 'res/js/ui/prototype/class.ActivityMonitor.js', 'res/js/ui/prototype/class.AjxpReactComponent.js', 'res/js/ui/prototype/class.PydioUI.js', - 'res/js/core/Pydio.js', + 'res/js/core/Pydio.js' ] - }, - }, + } + } }, babel: { @@ -106,23 +106,23 @@ module.exports = function(grunt) { dist: { files: [ { - mode: { loose : true, }, + mode: { loose : true }, expand: true, cwd: 'res/js/es6/', src: ['**/*.es6'], dest: 'res/js/core/', ext: '.js' - }, - ], - }, + } + ] + } }, browserify: { dist: { files: { - 'bundle.js': 'export.js' - }, - }, + 'res/js/vendor/nodejs/bundle.js': 'res/js/vendor/nodejs/export.js' + } + } }, @@ -212,20 +212,20 @@ module.exports = function(grunt) { 'res/js/ui/prototype/class.ActivityMonitor.js', 'res/js/ui/prototype/class.AjxpReactComponent.js', 'res/js/ui/prototype/class.PydioUI.js', - 'res/js/core/Pydio.js', + 'res/js/core/Pydio.js' ], tasks: ['uglify'], options: { - spawn: false, - }, - }, - }, - }) + spawn: false + } + } + } + }); - grunt.loadNpmTasks('grunt-browserify') - grunt.loadNpmTasks('grunt-babel') - grunt.loadNpmTasks('grunt-contrib-uglify') - grunt.loadNpmTasks('grunt-contrib-watch') - grunt.registerTask('default', ['babel','uglify']) -} + grunt.loadNpmTasks('grunt-browserify'); + grunt.loadNpmTasks('grunt-babel'); + grunt.loadNpmTasks('grunt-contrib-uglify'); + grunt.loadNpmTasks('grunt-contrib-watch'); + grunt.registerTask('default', ['babel','uglify', 'browserify']); +}; diff --git a/core/src/plugins/gui.ajax/package.json b/core/src/plugins/gui.ajax/package.json index 7c4ad09d57..c372c2eb97 100644 --- a/core/src/plugins/gui.ajax/package.json +++ b/core/src/plugins/gui.ajax/package.json @@ -9,7 +9,19 @@ "author": "", "license": "BSD-2-Clause", "dependencies": { - "grunt": "~0.4.5" + "grunt": "~0.4.5", + "chart.js": "^1.0.2", + "material-ui": "^0.7.5", + "react": "0.13.3", + "react-chartjs":"git://github.com/dehbmarques/react-chartjs.git#master", + "react-grid-layout": "^0.8.5", + "react-infinite": "^0.3.4", + "react-tap-event-plugin": "^0.1.7", + "reactify": "^1.1.1", + "react-select":"^0.6.5", + "react-dnd":"^1.1.5", + "lodash":"^3.10.1", + "classnames":"~2.1.3" }, "devDependencies": { "grunt-babel": "~5.0.3", diff --git a/core/src/plugins/gui.ajax/res/js/core/Pydio.js b/core/src/plugins/gui.ajax/res/js/core/Pydio.js index cac69244cd..1e391805ec 100644 --- a/core/src/plugins/gui.ajax/res/js/core/Pydio.js +++ b/core/src/plugins/gui.ajax/res/js/core/Pydio.js @@ -1,10 +1,15 @@ 'use strict'; +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +var _get = function get(_x3, _x4, _x5) { var _again = true; _function: while (_again) { var object = _x3, property = _x4, receiver = _x5; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x3 = parent; _x4 = property; _x5 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } -function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } +function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Pydio = (function (_Observable) { + _inherits(Pydio, _Observable); /** * @@ -14,21 +19,21 @@ var Pydio = (function (_Observable) { function Pydio(parameters) { _classCallCheck(this, Pydio); - _Observable.call(this); + _get(Object.getPrototypeOf(Pydio.prototype), 'constructor', this).call(this); this.Parameters = parameters; this._initLoadRep = parameters.get('initLoadRep') || null; this.usersEnabled = parameters.get('usersEnabled') || null; this.currentLanguage = parameters.get('currentLanguage') || null; - this.appTitle = 'Pydio'; - if (this.Parameters.has('customWording')) { - this.appTitle = this.Parameters.get('customWording').title || 'Pydio'; + this.appTitle = "Pydio"; + if (this.Parameters.has("customWording")) { + this.appTitle = this.Parameters.get("customWording").title || "Pydio"; } this.MessageHash = {}; if (window.MessageHash) this.MessageHash = window.MessageHash; this.ApiClient = PydioApi.getClient(); this.ApiClient.setPydioObject(this); this.Registry = new Registry(this); - this._rootNode = new AjxpNode('/', 'Root'); + this._rootNode = new AjxpNode("/", "Root"); this._dataModel = this._contextHolder = new PydioDataModel(false); this._dataModel.setAjxpNodeProvider(new RemoteNodeProvider()); this._dataModel.setRootNode(this._rootNode); @@ -36,472 +41,493 @@ var Pydio = (function (_Observable) { this.Controller = new Controller(this); } - _inherits(Pydio, _Observable); - - Pydio.prototype.fire = function fire(eventName, data) { - this.notify(eventName, data); - // Backward compatibility - if (document.fire) { - document.fire('ajaxplorer:' + eventName, data); + _createClass(Pydio, [{ + key: 'fire', + value: function fire(eventName, data) { + this.notify(eventName, data); + // Backward compatibility + if (document.fire) { + document.fire("ajaxplorer:" + eventName, data); + } } - }; - /** - * Real initialisation sequence. Will Trigger the whole GUI building. - * Event ajaxplorer:loaded is fired at the end. - */ - - Pydio.prototype.init = function init() { - if (!this.Parameters.has('SECURE_TOKEN')) { - PydioApi.getClient().getBootConf((function () { - this.init(); - }).bind(this)); - return; - } + /** + * Real initialisation sequence. Will Trigger the whole GUI building. + * Event ajaxplorer:loaded is fired at the end. + */ + }, { + key: 'init', + value: function init() { + if (!this.Parameters.has('SECURE_TOKEN')) { + PydioApi.getClient().getBootConf((function () { + this.init(); + }).bind(this)); + return; + } - if (window.PydioUI) { - this.UI = new PydioUI(this); - } else { - // FAKE CLASSE - this.UI = { - guiLoaded: true, - modal: { - setLoadingStepCounts: function setLoadingStepCounts() {}, - refreshDialogAppearance: function refreshDialogAppearance() {}, - displayMessage: function displayMessage() {}, - initForms: function initForms() {}, - updateLoadingProgress: function updateLoadingProgress(progress) { - Logger.log(progress); + if (window.PydioUI) { + this.UI = new PydioUI(this); + } else { + // FAKE CLASSE + this.UI = { + guiLoaded: true, + modal: { + setLoadingStepCounts: function setLoadingStepCounts() {}, + refreshDialogAppearance: function refreshDialogAppearance() {}, + displayMessage: function displayMessage() {}, + initForms: function initForms() {}, + updateLoadingProgress: function updateLoadingProgress(progress) { + Logger.log(progress); + }, + prepareHeader: function prepareHeader() {}, + showModalDialog: function showModalDialog() {} }, - prepareHeader: function prepareHeader() {}, - showModalDialog: function showModalDialog() {} - }, - refreshTemplateParts: function refreshTemplateParts() {}, - initTemplates: function initTemplates() {}, - initObjects: function initObjects() {}, - updateI18nTags: function updateI18nTags() {}, - insertForm: function insertForm(formId, formCode) {}, - removeForm: function removeForm(formId) {}, - mountComponents: function mountComponents(componentsNodes) {} - }; - } - - this.observe('registry_loaded', (function () { - this.Registry.refreshExtensionsRegistry(); - this.Registry.logXmlUser(false); - if (this.user) { - var repId = this.user.getActiveRepository(); - var repList = this.user.getRepositoriesList(); - var repositoryObject = repList.get(repId); - if (repositoryObject) repositoryObject.loadResources(); + refreshTemplateParts: function refreshTemplateParts() {}, + initTemplates: function initTemplates() {}, + initObjects: function initObjects() {}, + updateI18nTags: function updateI18nTags() {}, + insertForm: function insertForm(formId, formCode) {}, + removeForm: function removeForm(formId) {}, + mountComponents: function mountComponents(componentsNodes) {} + }; } - if (this.UI.guiLoaded) { - this.UI.refreshTemplateParts(); + + this.observe("registry_loaded", (function () { this.Registry.refreshExtensionsRegistry(); - this.Controller.loadActionsFromRegistry(this.getXmlRegistry()); - } else { - this.observe('gui_loaded', (function () { + this.Registry.logXmlUser(false); + if (this.user) { + var repId = this.user.getActiveRepository(); + var repList = this.user.getRepositoriesList(); + var repositoryObject = repList.get(repId); + if (repositoryObject) repositoryObject.loadResources(); + } + if (this.UI.guiLoaded) { this.UI.refreshTemplateParts(); this.Registry.refreshExtensionsRegistry(); this.Controller.loadActionsFromRegistry(this.getXmlRegistry()); - }).bind(this)); - } - this.loadActiveRepository(); - if (this.Parameters.has('USER_GUI_ACTION')) { - var a = this.Parameters.get('USER_GUI_ACTION'); - this.Parameters['delete']('USER_GUI_ACTION'); - var aBar = this.Controller; - window.setTimeout(function () { - aBar.fireAction(a); - }, 2000); - } - }).bind(this)); + } else { + this.observe("gui_loaded", (function () { + this.UI.refreshTemplateParts(); + this.Registry.refreshExtensionsRegistry(); + this.Controller.loadActionsFromRegistry(this.getXmlRegistry()); + }).bind(this)); + } + this.loadActiveRepository(); + if (this.Parameters.has("USER_GUI_ACTION")) { + var a = this.Parameters.get("USER_GUI_ACTION"); + this.Parameters['delete']("USER_GUI_ACTION"); + var aBar = this.Controller; + window.setTimeout(function () { + aBar.fireAction(a); + }, 2000); + } + }).bind(this)); - if (this.UI.modal) this.UI.modal.setLoadingStepCounts(5); + if (this.UI.modal) this.UI.modal.setLoadingStepCounts(5); - var starterFunc = (function () { + var starterFunc = (function () { - this.UI.initTemplates(); - if (this.UI.modal) this.UI.modal.initForms(); - this.UI.initObjects(); + this.UI.initTemplates(); + if (this.UI.modal) this.UI.modal.initForms(); + this.UI.initObjects(); - this.tryLogUserFromCookie(); - this.fire('registry_loaded', this.Registry.getXML()); + this.tryLogUserFromCookie(); + this.fire("registry_loaded", this.Registry.getXML()); - window.setTimeout((function () { - this.fire('loaded'); - }).bind(this), 200); + window.setTimeout((function () { + this.fire('loaded'); + }).bind(this), 200); - this.Router = new Router(this); - }).bind(this); + this.Router = new Router(this); + }).bind(this); - if (this.Parameters.get('PRELOADED_REGISTRY')) { - this.Registry.loadFromString(this.Parameters.get('PRELOADED_REGISTRY')); - this.Parameters['delete']('PRELOADED_REGISTRY'); - if (this.UI.modal) this.UI.modal.updateLoadingProgress('XML Registry loaded'); - starterFunc(); - } else { - this.loadXmlRegistry(false, null, starterFunc); - } - this.observe('server_message', (function (xml) { - var reload = XMLUtils.XPathSelectSingleNode(xml, 'tree/require_registry_reload'); - if (reload) { - if (reload.getAttribute('repositoryId') != this.repositoryId) { - this.loadXmlRegistry(false); - this.repositoryId = null; - } + if (this.Parameters.get("PRELOADED_REGISTRY")) { + this.Registry.loadFromString(this.Parameters.get("PRELOADED_REGISTRY")); + this.Parameters['delete']("PRELOADED_REGISTRY"); + if (this.UI.modal) this.UI.modal.updateLoadingProgress('XML Registry loaded'); + starterFunc(); + } else { + this.loadXmlRegistry(false, null, starterFunc); } - }).bind(this)); - }; - - /** - * Loads the XML Registry, an image of the application in its current state - * sent by the server. - * @param sync Boolean Whether to send synchronously or not. - * @param xPath String An XPath to load only a subpart of the registry - */ - - Pydio.prototype.loadXmlRegistry = function loadXmlRegistry(sync) { - var xPath = arguments[1] === undefined ? null : arguments[1]; - var completeFunc = arguments[2] === undefined ? null : arguments[2]; - - this.Registry.load(sync, xPath, completeFunc, this.repositoryId); - }; - - /** - * Get the XML Registry - * @returns Document - */ + this.observe("server_message", (function (xml) { + var reload = XMLUtils.XPathSelectSingleNode(xml, "tree/require_registry_reload"); + if (reload) { + if (reload.getAttribute("repositoryId") != this.repositoryId) { + this.loadXmlRegistry(false); + this.repositoryId = null; + } + } + }).bind(this)); + } - Pydio.prototype.getXmlRegistry = function getXmlRegistry() { - return this.Registry.getXML(); - }; + /** + * Loads the XML Registry, an image of the application in its current state + * sent by the server. + * @param sync Boolean Whether to send synchronously or not. + * @param xPath String An XPath to load only a subpart of the registry + */ + }, { + key: 'loadXmlRegistry', + value: function loadXmlRegistry(sync) { + var xPath = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + var completeFunc = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2]; + + this.Registry.load(sync, xPath, completeFunc, this.repositoryId); + } - /** - * Try reading the cookie and sending it to the server - */ + /** + * Get the XML Registry + * @returns Document + */ + }, { + key: 'getXmlRegistry', + value: function getXmlRegistry() { + return this.Registry.getXML(); + } - Pydio.prototype.tryLogUserFromCookie = function tryLogUserFromCookie() {}; + /** + * Try reading the cookie and sending it to the server + */ + }, { + key: 'tryLogUserFromCookie', + value: function tryLogUserFromCookie() {} + // TODO: to grab from somewhere else + /* + var connexion = new Connexion(); + var rememberData = retrieveRememberData(); + if(rememberData!=null){ + connexion.addParameter('get_action', 'login'); + connexion.addParameter('userid', rememberData.user); + connexion.addParameter('password', rememberData.pass); + connexion.addParameter('cookie_login', 'true'); + connexion.onComplete = function(transport){ + hideLightBox(); + this.Controller.parseXmlMessage(transport.responseXML); + }.bind(this); + connexion.sendSync(); + } + */ - /** - * Find the current repository (from the current user) and load it. - */ + /** + * Find the current repository (from the current user) and load it. + */ - Pydio.prototype.loadActiveRepository = function loadActiveRepository() { - var repositoryObject = new Repository(null); - if (this.user != null) { - var repId = this.user.getActiveRepository(); - var repList = this.user.getRepositoriesList(); - repositoryObject = repList.get(repId); - if (!repositoryObject) { - if (this.user.lock) { - this.Controller.loadActionsFromRegistry(this.getXmlRegistry()); - window.setTimeout((function () { - this.Controller.fireAction(this.user.lock); - }).bind(this), 50); - return; + }, { + key: 'loadActiveRepository', + value: function loadActiveRepository() { + var repositoryObject = new Repository(null); + if (this.user != null) { + var repId = this.user.getActiveRepository(); + var repList = this.user.getRepositoriesList(); + repositoryObject = repList.get(repId); + if (!repositoryObject) { + if (this.user.lock) { + this.Controller.loadActionsFromRegistry(this.getXmlRegistry()); + window.setTimeout((function () { + this.Controller.fireAction(this.user.lock); + }).bind(this), 50); + return; + } + alert("No active repository found for user!"); + } + if (this.user.getPreference("pending_folder") && this.user.getPreference("pending_folder") != "-1") { + this._initLoadRep = this.user.getPreference("pending_folder"); + this.user.setPreference("pending_folder", "-1"); + this.user.savePreference("pending_folder"); + } else if (this.user.getPreference("ls_history", true)) { + var data = this.user.getPreference("ls_history", true); + this._initLoadRep = data[repId]; } - alert('No active repository found for user!'); } - if (this.user.getPreference('pending_folder') && this.user.getPreference('pending_folder') != '-1') { - this._initLoadRep = this.user.getPreference('pending_folder'); - this.user.setPreference('pending_folder', '-1'); - this.user.savePreference('pending_folder'); - } else if (this.user.getPreference('ls_history', true)) { - var data = this.user.getPreference('ls_history', true); - this._initLoadRep = data[repId]; + this.loadRepository(repositoryObject); + if (repList && repId) { + this.fire("repository_list_refreshed", { list: repList, active: repId }); + } else { + this.fire("repository_list_refreshed", { list: false, active: false }); } } - this.loadRepository(repositoryObject); - if (repList && repId) { - this.fire('repository_list_refreshed', { list: repList, active: repId }); - } else { - this.fire('repository_list_refreshed', { list: false, active: false }); - } - }; - - /** - * Refresh the repositories list for the current user - */ - - Pydio.prototype.reloadRepositoriesList = function reloadRepositoriesList() { - if (!this.user) return; - this.observeOnce('registry_part_loaded', (function (data) { - if (data != 'user/repositories') return; - this.Registry.logXmlUser(true); - document.fire('ajaxplorer:repository_list_refreshed', { - list: this.user.getRepositoriesList(), - active: this.user.getActiveRepository() }); - }).bind(this)); - this.loadXmlRegistry(false, 'user/repositories'); - }; - - /** - * Load a Repository instance - * @param repository Repository - */ - - Pydio.prototype.loadRepository = function loadRepository(repository) { - if (this.repositoryId != null && this.repositoryId == repository.getId()) { - Logger.debug('Repository already loaded, do nothing'); + /** + * Refresh the repositories list for the current user + */ + }, { + key: 'reloadRepositoriesList', + value: function reloadRepositoriesList() { + if (!this.user) return; + this.observeOnce("registry_part_loaded", (function (data) { + if (data != "user/repositories") return; + this.Registry.logXmlUser(true); + document.fire("ajaxplorer:repository_list_refreshed", { + list: this.user.getRepositoriesList(), + active: this.user.getActiveRepository() }); + }).bind(this)); + this.loadXmlRegistry(false, "user/repositories"); } - this._contextHolder.setSelectedNodes([]); - if (repository == null) return; - - repository.loadResources(); - var repositoryId = repository.getId(); - var newIcon = repository.getIcon(); - this.skipLsHistory = true; + /** + * Load a Repository instance + * @param repository Repository + */ + }, { + key: 'loadRepository', + value: function loadRepository(repository) { - var providerDef = repository.getNodeProviderDef(); - var rootNode; - if (providerDef != null) { - var provider = eval('new ' + providerDef.name + '()'); - if (providerDef.options) { - provider.initProvider(providerDef.options); + if (this.repositoryId != null && this.repositoryId == repository.getId()) { + Logger.debug('Repository already loaded, do nothing'); } - this._contextHolder.setAjxpNodeProvider(provider); - rootNode = new AjxpNode('/', false, repository.getLabel(), newIcon, provider); - } else { - rootNode = new AjxpNode('/', false, repository.getLabel(), newIcon); - // Default - this._contextHolder.setAjxpNodeProvider(new RemoteNodeProvider()); - } - this._contextHolder.setRootNode(rootNode); - rootNode.observeOnce('first_load', (function () { - this._contextHolder.notify('context_changed', rootNode); - }).bind(this)); - this.repositoryId = repositoryId; - - if (this._initLoadRep) { - if (this._initLoadRep != '' && this._initLoadRep != '/') { - var copy = this._initLoadRep.valueOf(); - this._initLoadRep = null; - rootNode.observeOnce('first_load', (function () { - setTimeout((function () { - this.goTo(copy); - this.skipLsHistory = false; - }).bind(this), 1000); - }).bind(this)); - } else { - this.skipLsHistory = false; - } - } else { - this.skipLsHistory = false; - } + this._contextHolder.setSelectedNodes([]); + if (repository == null) return; - rootNode.load(); - }; + repository.loadResources(); + var repositoryId = repository.getId(); + var newIcon = repository.getIcon(); - /** - * Require a context change to the given path - * @param nodeOrPath AjxpNode|String A node or a path - */ + this.skipLsHistory = true; - Pydio.prototype.goTo = function goTo(nodeOrPath) { - var path; - if (typeof nodeOrPath == 'string') { - path = nodeOrPath; - } else { - path = nodeOrPath.getPath(); - if (nodeOrPath.getMetadata().has('repository_id') && nodeOrPath.getMetadata().get('repository_id') != this.repositoryId && nodeOrPath.getAjxpMime() != 'repository' && nodeOrPath.getAjxpMime() != 'repository_editable') { - if (this.user) { - this.user.setPreference('pending_folder', nodeOrPath.getPath()); + var providerDef = repository.getNodeProviderDef(); + var rootNode; + if (providerDef != null) { + var provider = eval('new ' + providerDef.name + '()'); + if (providerDef.options) { + provider.initProvider(providerDef.options); } - this.triggerRepositoryChange(nodeOrPath.getMetadata().get('repository_id')); - return; + this._contextHolder.setAjxpNodeProvider(provider); + rootNode = new AjxpNode("/", false, repository.getLabel(), newIcon, provider); + } else { + rootNode = new AjxpNode("/", false, repository.getLabel(), newIcon); + // Default + this._contextHolder.setAjxpNodeProvider(new RemoteNodeProvider()); } - } - - var current = this._contextHolder.getContextNode(); - if (current && current.getPath() == path) { - return; - } - var gotoNode; - if (path == '' || path == '/') { - gotoNode = new AjxpNode('/'); - this._contextHolder.requireContextChange(gotoNode); - return; - } - this._contextHolder.loadPathInfoAsync(path, (function (foundNode) { - if (foundNode.isLeaf() && foundNode.getAjxpMime() != 'ajxp_browsable_archive') { - this._contextHolder.setPendingSelection(PathUtils.getBasename(path)); - gotoNode = new AjxpNode(PathUtils.getDirname(path)); + this._contextHolder.setRootNode(rootNode); + rootNode.observeOnce('first_load', (function () { + this._contextHolder.notify('context_changed', rootNode); + }).bind(this)); + this.repositoryId = repositoryId; + + if (this._initLoadRep) { + if (this._initLoadRep != "" && this._initLoadRep != "/") { + var copy = this._initLoadRep.valueOf(); + this._initLoadRep = null; + rootNode.observeOnce("first_load", (function () { + setTimeout((function () { + this.goTo(copy); + this.skipLsHistory = false; + }).bind(this), 1000); + }).bind(this)); + } else { + this.skipLsHistory = false; + } } else { - gotoNode = foundNode; + this.skipLsHistory = false; } - this._contextHolder.requireContextChange(gotoNode); - }).bind(this)); - }; - - /** - * Change the repository of the current user and reload list and current. - * @param repositoryId String Id of the new repository - */ - Pydio.prototype.triggerRepositoryChange = function triggerRepositoryChange(repositoryId) { - this.fire('trigger_repository_switch'); - var onComplete = (function (transport) { - if (transport.responseXML) { - this.Controller.parseXmlMessage(transport.responseXML); - } - this.loadXmlRegistry(); - this.repositoryId = null; - }).bind(this); - var root = this._contextHolder.getRootNode(); - if (root) { - this.skipLsHistory = true; - root.clear(); + rootNode.load(); } - this.ApiClient.switchRepository(repositoryId, onComplete); - }; - Pydio.prototype.getPluginConfigs = function getPluginConfigs(pluginQuery) { - return this.Registry.getPluginConfigs(pluginQuery); - }; - - /** - * Reload all messages from server and trigger updateI18nTags - * @param newLanguage String - */ - - Pydio.prototype.loadI18NMessages = function loadI18NMessages(newLanguage) { - var onComplete = (function (transport) { - if (transport.responseJSON) { - this.MessageHash = transport.responseJSON; - for (var key in this.MessageHash) { - if (this.MessageHash.hasOwnProperty(key)) { - this.MessageHash[key] = this.MessageHash[key].replace('\\n', '\n'); + /** + * Require a context change to the given path + * @param nodeOrPath AjxpNode|String A node or a path + */ + }, { + key: 'goTo', + value: function goTo(nodeOrPath) { + var path; + if (typeof nodeOrPath == "string") { + path = nodeOrPath; + } else { + path = nodeOrPath.getPath(); + if (nodeOrPath.getMetadata().has("repository_id") && nodeOrPath.getMetadata().get("repository_id") != this.repositoryId && nodeOrPath.getAjxpMime() != "repository" && nodeOrPath.getAjxpMime() != "repository_editable") { + if (this.user) { + this.user.setPreference("pending_folder", nodeOrPath.getPath()); } + this.triggerRepositoryChange(nodeOrPath.getMetadata().get("repository_id")); + return; } - this.UI.updateI18nTags(); - this.Controller.refreshGuiActionsI18n(); - - this.loadXmlRegistry(); - this.fireContextRefresh(); - this.currentLanguage = newLanguage; } - }).bind(this); - this.ApiClient.switchLanguage(newLanguage, onComplete); - }; - - /** - * Get the main controller - * @returns ActionManager - */ - - Pydio.prototype.getController = function getController() { - return this.Controller; - }; - /** - * Display an information or error message to the user - * @param messageType String ERROR or SUCCESS - * @param message String the message - */ - - Pydio.prototype.displayMessage = function displayMessage(messageType, message) { - var urls = LangUtils.parseUrl(message); - if (urls.length && this.user && this.user.repositories) { - urls.forEach((function (match) { - var repo = this.user.repositories.get(match.host); - if (!repo) return; - message = message.replace(match.url, repo.label + ':' + match.path + match.file); + var current = this._contextHolder.getContextNode(); + if (current && current.getPath() == path) { + return; + } + var gotoNode; + if (path == "" || path == "/") { + gotoNode = new AjxpNode("/"); + this._contextHolder.requireContextChange(gotoNode); + return; + } + this._contextHolder.loadPathInfoAsync(path, (function (foundNode) { + if (foundNode.isLeaf() && foundNode.getAjxpMime() != 'ajxp_browsable_archive') { + this._contextHolder.setPendingSelection(PathUtils.getBasename(path)); + gotoNode = new AjxpNode(PathUtils.getDirname(path)); + } else { + gotoNode = foundNode; + } + this._contextHolder.requireContextChange(gotoNode); }).bind(this)); } - if (messageType == 'ERROR') Logger.error(message);else Logger.log(message); - if (this.UI.modal) this.UI.modal.displayMessage(messageType, message); - }; - /************************************************* - * - * PROXY METHODS FOR DATAMODEL - * - ************************************************/ - - /** - * Accessor for updating the datamodel context - * @param ajxpContextNode AjxpNode - * @param ajxpSelectedNodes AjxpNode[] - * @param selectionSource String - */ - - Pydio.prototype.updateContextData = function updateContextData(ajxpContextNode, ajxpSelectedNodes, selectionSource) { - if (ajxpContextNode) { - this._contextHolder.requireContextChange(ajxpContextNode); + /** + * Change the repository of the current user and reload list and current. + * @param repositoryId String Id of the new repository + */ + }, { + key: 'triggerRepositoryChange', + value: function triggerRepositoryChange(repositoryId) { + this.fire("trigger_repository_switch"); + var onComplete = (function (transport) { + if (transport.responseXML) { + this.Controller.parseXmlMessage(transport.responseXML); + } + this.loadXmlRegistry(); + this.repositoryId = null; + }).bind(this); + var root = this._contextHolder.getRootNode(); + if (root) { + this.skipLsHistory = true; + root.clear(); + } + this.ApiClient.switchRepository(repositoryId, onComplete); } - if (ajxpSelectedNodes) { - this._contextHolder.setSelectedNodes(ajxpSelectedNodes, selectionSource); + }, { + key: 'getPluginConfigs', + value: function getPluginConfigs(pluginQuery) { + return this.Registry.getPluginConfigs(pluginQuery); } - }; - /** - * @returns AjxpDataModel - */ - - Pydio.prototype.getContextHolder = function getContextHolder() { - return this._contextHolder; - }; + /** + * Reload all messages from server and trigger updateI18nTags + * @param newLanguage String + */ + }, { + key: 'loadI18NMessages', + value: function loadI18NMessages(newLanguage) { + var onComplete = (function (transport) { + if (transport.responseJSON) { + this.MessageHash = transport.responseJSON; + for (var key in this.MessageHash) { + if (this.MessageHash.hasOwnProperty(key)) { + this.MessageHash[key] = this.MessageHash[key].replace("\\n", "\n"); + } + } + this.UI.updateI18nTags(); + this.Controller.refreshGuiActionsI18n(); - /** - * @returns AjxpNode - */ + this.loadXmlRegistry(); + this.fireContextRefresh(); + this.currentLanguage = newLanguage; + } + }).bind(this); + this.ApiClient.switchLanguage(newLanguage, onComplete); + } - Pydio.prototype.getContextNode = function getContextNode() { - return this._contextHolder.getContextNode() || new AjxpNode(''); - }; + /** + * Get the main controller + * @returns ActionManager + */ + }, { + key: 'getController', + value: function getController() { + return this.Controller; + } - /** - * @returns AjxpDataModel - */ + /** + * Display an information or error message to the user + * @param messageType String ERROR or SUCCESS + * @param message String the message + */ + }, { + key: 'displayMessage', + value: function displayMessage(messageType, message) { + var urls = LangUtils.parseUrl(message); + if (urls.length && this.user && this.user.repositories) { + urls.forEach((function (match) { + var repo = this.user.repositories.get(match.host); + if (!repo) return; + message = message.replace(match.url, repo.label + ":" + match.path + match.file); + }).bind(this)); + } + if (messageType == 'ERROR') Logger.error(message);else Logger.log(message); + if (this.UI.modal) this.UI.modal.displayMessage(messageType, message); + } - Pydio.prototype.getUserSelection = function getUserSelection() { - return this._contextHolder; - }; + /************************************************* + * + * PROXY METHODS FOR DATAMODEL + * + ************************************************/ + + /** + * Accessor for updating the datamodel context + * @param ajxpContextNode AjxpNode + * @param ajxpSelectedNodes AjxpNode[] + * @param selectionSource String + */ + }, { + key: 'updateContextData', + value: function updateContextData(ajxpContextNode, ajxpSelectedNodes, selectionSource) { + if (ajxpContextNode) { + this._contextHolder.requireContextChange(ajxpContextNode); + } + if (ajxpSelectedNodes) { + this._contextHolder.setSelectedNodes(ajxpSelectedNodes, selectionSource); + } + } - /** - * Accessor for datamodel.requireContextChange() - */ + /** + * @returns AjxpDataModel + */ + }, { + key: 'getContextHolder', + value: function getContextHolder() { + return this._contextHolder; + } - Pydio.prototype.fireContextRefresh = function fireContextRefresh() { - this.getContextHolder().requireContextChange(this.getContextNode(), true); - }; + /** + * @returns AjxpNode + */ + }, { + key: 'getContextNode', + value: function getContextNode() { + return this._contextHolder.getContextNode() || new AjxpNode(""); + } - /** - * Accessor for datamodel.requireContextChange() - */ + /** + * @returns AjxpDataModel + */ + }, { + key: 'getUserSelection', + value: function getUserSelection() { + return this._contextHolder; + } - Pydio.prototype.fireNodeRefresh = function fireNodeRefresh(nodePathOrNode, completeCallback) { - this.getContextHolder().requireNodeReload(nodePathOrNode, completeCallback); - }; + /** + * Accessor for datamodel.requireContextChange() + */ + }, { + key: 'fireContextRefresh', + value: function fireContextRefresh() { + this.getContextHolder().requireContextChange(this.getContextNode(), true); + } - /** - * Accessor for datamodel.requireContextChange() - */ + /** + * Accessor for datamodel.requireContextChange() + */ + }, { + key: 'fireNodeRefresh', + value: function fireNodeRefresh(nodePathOrNode, completeCallback) { + this.getContextHolder().requireNodeReload(nodePathOrNode, completeCallback); + } - Pydio.prototype.fireContextUp = function fireContextUp() { - if (this.getContextNode().isRoot()) return; - this.updateContextData(this.getContextNode().getParent()); - }; + /** + * Accessor for datamodel.requireContextChange() + */ + }, { + key: 'fireContextUp', + value: function fireContextUp() { + if (this.getContextNode().isRoot()) return; + this.updateContextData(this.getContextNode().getParent()); + } + }]); return Pydio; })(Observable); - -// TODO: to grab from somewhere else -/* -var connexion = new Connexion(); -var rememberData = retrieveRememberData(); -if(rememberData!=null){ - connexion.addParameter('get_action', 'login'); - connexion.addParameter('userid', rememberData.user); - connexion.addParameter('password', rememberData.pass); - connexion.addParameter('cookie_login', 'true'); - connexion.onComplete = function(transport){ - hideLightBox(); - this.Controller.parseXmlMessage(transport.responseXML); - }.bind(this); - connexion.sendSync(); -} -*/ \ No newline at end of file diff --git a/core/src/plugins/gui.ajax/res/js/core/http/PydioApi.js b/core/src/plugins/gui.ajax/res/js/core/http/PydioApi.js index fa2c621732..c418bfe31c 100644 --- a/core/src/plugins/gui.ajax/res/js/core/http/PydioApi.js +++ b/core/src/plugins/gui.ajax/res/js/core/http/PydioApi.js @@ -1,5 +1,7 @@ 'use strict'; +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var PydioApi = (function () { @@ -9,460 +11,481 @@ var PydioApi = (function () { this._secureToken = ''; } - PydioApi.prototype.setPydioObject = function setPydioObject(pydioObject) { - this._pydioObject = pydioObject; - this._baseUrl = pydioObject.Parameters.get('serverAccessPath'); - this._secureToken = pydioObject.Parameters.get('SECURE_TOKEN'); - }; - - PydioApi.prototype.setSecureToken = function setSecureToken(token) { - this._secureToken = token; - }; - - PydioApi.prototype.request = function request(parameters) { - var onComplete = arguments[1] === undefined ? null : arguments[1]; - var onError = arguments[2] === undefined ? null : arguments[2]; - var settings = arguments[3] === undefined ? {} : arguments[3]; - - if (window.Connexion) { - // Connexion already handles secure_token - var c = new Connexion(); - if (settings.discrete) { - c.discrete = true; - } - c.setParameters($H(parameters)); - if (settings.method) { - c.setMethod(settings.method); + _createClass(PydioApi, [{ + key: 'setPydioObject', + value: function setPydioObject(pydioObject) { + this._pydioObject = pydioObject; + this._baseUrl = pydioObject.Parameters.get('serverAccessPath'); + this._secureToken = pydioObject.Parameters.get('SECURE_TOKEN'); + } + }, { + key: 'setSecureToken', + value: function setSecureToken(token) { + this._secureToken = token; + } + }, { + key: 'request', + value: function request(parameters) { + var onComplete = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + var onError = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2]; + var settings = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3]; + + if (window.Connexion) { + // Connexion already handles secure_token + var c = new Connexion(); + if (settings.discrete) { + c.discrete = true; + } + c.setParameters($H(parameters)); + if (settings.method) { + c.setMethod(settings.method); + } + c.onComplete = onComplete; + if (settings.async === false) { + c.sendSync(); + } else { + c.sendAsync(); + } + } else if (window.jQuery) { + parameters['secure_token'] = this._secureToken; + jQuery.ajax(this._baseUrl, { + method: settings.method || 'post', + data: parameters, + async: settings && settings.async !== undefined ? settings.async : true, + complete: onComplete, + error: onError + }); } - c.onComplete = onComplete; - if (settings.async === false) { - c.sendSync(); - } else { + } + }, { + key: 'loadFile', + value: function loadFile(filePath) { + var onComplete = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + var onError = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2]; + + if (window.Connexion) { + var c = new Connexion(filePath); + c.setMethod('GET'); + c.onComplete = onComplete; c.sendAsync(); + } else if (window.jQuery) { + jQuery.ajax(filePath, { + method: 'GET', + async: true, + complete: onComplete, + error: onError + }); } - } else if (window.jQuery) { - parameters['secure_token'] = this._secureToken; - jQuery.ajax(this._baseUrl, { - method: settings.method || 'post', - data: parameters, - async: settings && settings.async !== undefined ? settings.async : true, - complete: onComplete, - error: onError - }); } - }; - - PydioApi.prototype.loadFile = function loadFile(filePath) { - var onComplete = arguments[1] === undefined ? null : arguments[1]; - var onError = arguments[2] === undefined ? null : arguments[2]; - - if (window.Connexion) { - var c = new Connexion(filePath); - c.setMethod('GET'); - c.onComplete = onComplete; - c.sendAsync(); - } else if (window.jQuery) { - jQuery.ajax(filePath, { - method: 'GET', - async: true, - complete: onComplete, - error: onError - }); + }, { + key: 'uploadFile', + value: function uploadFile(file, fileParameterName) { + var queryStringParams = arguments.length <= 2 || arguments[2] === undefined ? '' : arguments[2]; + var onComplete = arguments.length <= 3 || arguments[3] === undefined ? function () {} : arguments[3]; + var onError = arguments.length <= 4 || arguments[4] === undefined ? function () {} : arguments[4]; + var onProgress = arguments.length <= 5 || arguments[5] === undefined ? function () {} : arguments[5]; + + if (window.Connexion) { + var c = new Connexion(); + c.uploadFile(file, fileParameterName, queryStringParams, onComplete, onError, onProgress); + } else if (window.jQuery) { + var formData = new FormData(); + formData.append(fileParameterName, file); + queryStringParams += '&secure_token' + this._secureToken; + jQuery.ajax(this._baseUrl + '&' + queryStringParams, { + method: 'POST', + data: formData, + complete: onComplete, + error: onError, + progress: onProgress + }); + } } - }; - - PydioApi.prototype.uploadFile = function uploadFile(file, fileParameterName) { - var queryStringParams = arguments[2] === undefined ? '' : arguments[2]; - var onComplete = arguments[3] === undefined ? function () {} : arguments[3]; - var onError = arguments[4] === undefined ? function () {} : arguments[4]; - var onProgress = arguments[5] === undefined ? function () {} : arguments[5]; - - if (window.Connexion) { - var c = new Connexion(); - c.uploadFile(file, fileParameterName, queryStringParams, onComplete, onError, onProgress); - } else if (window.jQuery) { - var formData = new FormData(); - formData.append(fileParameterName, file); - queryStringParams += '&secure_token' + this._secureToken; - jQuery.ajax(this._baseUrl + '&' + queryStringParams, { - method: 'POST', - data: formData, - complete: onComplete, - error: onError, - progress: onProgress - }); + }, { + key: 'switchRepository', + value: function switchRepository(repositoryId, completeCallback) { + var params = { + get_action: 'switch_repository', + repository_id: repositoryId + }; + this.request(params, completeCallback); } - }; - - PydioApi.supportsUpload = function supportsUpload() { - if (window.Connexion) { - return window.FormData || window.FileReader; - } else if (window.jQuery) { - return window.FormData; + }, { + key: 'switchLanguage', + value: function switchLanguage(lang, completeCallback) { + var params = { + get_action: 'get_i18n_messages', + lang: lang, + format: 'json' + }; + this.request(params, completeCallback); } - return false; - }; - - PydioApi.getClient = function getClient() { - if (PydioApi._PydioClient) return PydioApi._PydioClient; - var client = new PydioApi(); - PydioApi._PydioClient = client; - return client; - }; - - /** - * Load a javascript library - * @param fileName String - * @param onLoadedCode Function Callback - * @param aSync Boolean load library asynchroneously - * @todo : We should use Require or equivalent instead. - */ - - PydioApi.loadLibrary = function loadLibrary(fileName, onLoadedCode, aSync) { - if (window.pydio && pydio.Parameters.get('ajxpVersion') && fileName.indexOf('?') == -1) { - fileName += '?v=' + pydio.Parameters.get('ajxpVersion'); + }, { + key: 'loadXmlRegistry', + value: function loadXmlRegistry(completeCallback) { + var xPath = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + + var params = { get_action: 'get_xml_registry' }; + if (xPath) params[xPath] = xPath; + this.request(params, completeCallback); } - PydioApi._libUrl = false; - if (window.pydio && pydio.Parameters.get('SERVER_PREFIX_URI')) { - PydioApi._libUrl = pydio.Parameters.get('SERVER_PREFIX_URI'); + }, { + key: 'getBootConf', + value: function getBootConf(completeCallback) { + var params = { get_action: 'get_boot_conf' }; + var cB = (function (transport) { + if (transport.responseJSON && transport.responseJSON.SECURE_TOKEN) { + this._pydioObject.Parameters.set('SECURE_TOKEN', transport.responseJSON.SECURE_TOKEN); + this.setSecureToken(transport.responseJSON.SECURE_TOKEN); + } + if (completeCallback) { + completeCallback(transport); + } + }).bind(this); + this.request(params, cB); } - //var path = (PydioApi._libUrl?PydioApi._libUrl+'/'+fileName:fileName); - - /*if(window.jQuery && window.jQuery.ajax){ - jQuery.ajax(path, - { - method:'get', - async: (aSync?true:false), - complete:function(transport){ - if(transport.responseText) - { - try - { - var script = transport.responseText; - if (window.execScript){ - window.execScript( script ); - } - else{ - // TO TEST, THIS SEEM TO WORK ON SAFARI - window.my_code = script; - var script_tag = document.createElement('script'); - script_tag.type = 'text/javascript'; - script_tag.innerHTML = 'eval(window.my_code)'; - document.getElementsByTagName('head')[0].appendChild(script_tag); - } - if(onLoadedCode != null) onLoadedCode(); - } - catch(e) - { - alert('error loading '+fileName+':'+ e.message); - } - } - pydio.fire("server_answer"); - } - }); - }else */if (window.Connexion) { - + }, { + key: 'userSavePreference', + value: function userSavePreference(prefName, prefValue) { var conn = new Connexion(); - conn._libUrl = false; - if (pydio.Parameters.get('SERVER_PREFIX_URI')) { - conn._libUrl = pydio.Parameters.get('SERVER_PREFIX_URI'); - } - conn.loadLibrary(fileName, onLoadedCode, aSync); + conn.setMethod('post'); + conn.discrete = true; + conn.addParameter("get_action", "save_user_pref"); + conn.addParameter("pref_name_" + 0, prefName); + conn.addParameter("pref_value_" + 0, prefValue); + conn.sendAsync(); + } + }, { + key: 'userSavePreferences', + value: function userSavePreferences(preferences, completeCallback) { + var conn = new Connexion(); + conn.addParameter("get_action", "save_user_pref"); + var i = 0; + preferences.forEach(function (value, key) { + conn.addParameter("pref_name_" + i, key); + conn.addParameter("pref_value_" + i, value); + i++; + }); + conn.onComplete = completeCallback; + conn.sendAsync(); + } + }, { + key: 'userSavePassword', + value: function userSavePassword(oldPass, newPass, seed, completeCallback) { + var conn = new Connexion(); + conn.addParameter("get_action", "save_user_pref"); + conn.addParameter("pref_name_" + i, "password"); + conn.addParameter("pref_value_" + i, newPass); + conn.addParameter("crt", oldPass); + conn.addParameter("pass_seed", seed); + conn.onComplete = completeCallback; + conn.sendAsync(); + } + }, { + key: 'applyCheckHook', + value: function applyCheckHook(node, hookName, hookArg, completeCallback) { + var params = { + get_action: "apply_check_hook", + file: node.getPath(), + hook_name: hookName, + hook_arg: hookArg + }; + this.request(params, completeCallback, null, { async: false }); } - }; - - PydioApi.prototype.switchRepository = function switchRepository(repositoryId, completeCallback) { - var params = { - get_action: 'switch_repository', - repository_id: repositoryId - }; - this.request(params, completeCallback); - }; - - PydioApi.prototype.switchLanguage = function switchLanguage(lang, completeCallback) { - var params = { - get_action: 'get_i18n_messages', - lang: lang, - format: 'json' - }; - this.request(params, completeCallback); - }; - - PydioApi.prototype.loadXmlRegistry = function loadXmlRegistry(completeCallback) { - var xPath = arguments[1] === undefined ? null : arguments[1]; - - var params = { get_action: 'get_xml_registry' }; - if (xPath) params[xPath] = xPath; - this.request(params, completeCallback); - }; - - PydioApi.prototype.getBootConf = function getBootConf(completeCallback) { - var params = { get_action: 'get_boot_conf' }; - var cB = (function (transport) { - if (transport.responseJSON && transport.responseJSON.SECURE_TOKEN) { - this._pydioObject.Parameters.set('SECURE_TOKEN', transport.responseJSON.SECURE_TOKEN); - this.setSecureToken(transport.responseJSON.SECURE_TOKEN); - } - if (completeCallback) { - completeCallback(transport); - } - }).bind(this); - this.request(params, cB); - }; - - PydioApi.prototype.userSavePreference = function userSavePreference(prefName, prefValue) { - var conn = new Connexion(); - conn.setMethod('post'); - conn.discrete = true; - conn.addParameter('get_action', 'save_user_pref'); - conn.addParameter('pref_name_' + 0, prefName); - conn.addParameter('pref_value_' + 0, prefValue); - conn.sendAsync(); - }; - - PydioApi.prototype.userSavePreferences = function userSavePreferences(preferences, completeCallback) { - var conn = new Connexion(); - conn.addParameter('get_action', 'save_user_pref'); - var i = 0; - preferences.forEach(function (value, key) { - conn.addParameter('pref_name_' + i, key); - conn.addParameter('pref_value_' + i, value); - i++; - }); - conn.onComplete = completeCallback; - conn.sendAsync(); - }; - - PydioApi.prototype.userSavePassword = function userSavePassword(oldPass, newPass, seed, completeCallback) { - var conn = new Connexion(); - conn.addParameter('get_action', 'save_user_pref'); - conn.addParameter('pref_name_' + i, 'password'); - conn.addParameter('pref_value_' + i, newPass); - conn.addParameter('crt', oldPass); - conn.addParameter('pass_seed', seed); - conn.onComplete = completeCallback; - conn.sendAsync(); - }; - - PydioApi.prototype.applyCheckHook = function applyCheckHook(node, hookName, hookArg, completeCallback) { - var params = { - get_action: 'apply_check_hook', - file: node.getPath(), - hook_name: hookName, - hook_arg: hookArg - }; - this.request(params, completeCallback, null, { async: false }); - }; - - /** - * Standard parser for server XML answers - * @param xmlResponse DOMDocument - */ - - PydioApi.prototype.parseXmlMessage = function parseXmlMessage(xmlResponse) { - if (xmlResponse == null || xmlResponse.documentElement == null) return null; - var childs = xmlResponse.documentElement.childNodes; - - var reloadNodes = []; - var error = false; - this.LAST_ERROR_ID = null; - - for (var i = 0; i < childs.length; i++) { - if (childs[i].tagName == 'message') { - var messageTxt = 'No message'; - if (childs[i].firstChild) messageTxt = childs[i].firstChild.nodeValue; - if (childs[i].getAttribute('type') == 'ERROR') { - Logger.error(messageTxt); - error = true; - } else { - Logger.log(messageTxt); - } - } else if (childs[i].tagName == 'prompt') { - var message = XMLUtils.XPathSelectSingleNode(childs[i], 'message').firstChild.nodeValue; - var jsonData = XMLUtils.XPathSelectSingleNode(childs[i], 'data').firstChild.nodeValue; - var json = JSON.parse(jsonData); - // TODO: DELEGATE TO UI - /* - var dialogContent = new Element('div').update(json["DIALOG"]); - modal.showSimpleModal(modal.messageBox?modal.messageBox:document.body, dialogContent, function(){ - // ok callback; - if(json["OK"]["GET_FIELDS"]){ - var params = $H(); - $A(json["OK"]["GET_FIELDS"]).each(function(fName){ - params.set(fName, dialogContent.down('input[name="'+fName+'"]').getValue()); - }); - var conn = new Connexion(); - conn.setParameters(params); - if(json["OK"]["EVAL"]){ - conn.onComplete = function(){ + /** + * Standard parser for server XML answers + * @param xmlResponse DOMDocument + */ + }, { + key: 'parseXmlMessage', + value: function parseXmlMessage(xmlResponse) { + if (xmlResponse == null || xmlResponse.documentElement == null) return null; + var childs = xmlResponse.documentElement.childNodes; + + var reloadNodes = []; + var error = false; + this.LAST_ERROR_ID = null; + + for (var i = 0; i < childs.length; i++) { + if (childs[i].tagName == "message") { + var messageTxt = "No message"; + if (childs[i].firstChild) messageTxt = childs[i].firstChild.nodeValue; + if (childs[i].getAttribute('type') == 'ERROR') { + Logger.error(messageTxt); + error = true; + } else { + Logger.log(messageTxt); + } + } else if (childs[i].tagName == "prompt") { + + var message = XMLUtils.XPathSelectSingleNode(childs[i], "message").firstChild.nodeValue; + var jsonData = XMLUtils.XPathSelectSingleNode(childs[i], "data").firstChild.nodeValue; + var json = JSON.parse(jsonData); + // TODO: DELEGATE TO UI + /* + var dialogContent = new Element('div').update(json["DIALOG"]); + modal.showSimpleModal(modal.messageBox?modal.messageBox:document.body, dialogContent, function(){ + // ok callback; + if(json["OK"]["GET_FIELDS"]){ + var params = $H(); + $A(json["OK"]["GET_FIELDS"]).each(function(fName){ + params.set(fName, dialogContent.down('input[name="'+fName+'"]').getValue()); + }); + var conn = new Connexion(); + conn.setParameters(params); + if(json["OK"]["EVAL"]){ + conn.onComplete = function(){ + eval(json["OK"]["EVAL"]); + }; + } + conn.sendAsync(); + }else{ + if(json["OK"]["EVAL"]){ eval(json["OK"]["EVAL"]); - }; + } } - conn.sendAsync(); - }else{ - if(json["OK"]["EVAL"]){ - eval(json["OK"]["EVAL"]); + return true; + }, function(){ + // cancel callback + if(json["CANCEL"]["EVAL"]){ + eval(json["CANCEL"]["EVAL"]); } + return true; + }); + */ + throw new Error(); + } else if (childs[i].tagName == "reload_instruction") { + var obName = childs[i].getAttribute('object'); + if (obName == 'data') { + var node = childs[i].getAttribute('node'); + if (node) { + reloadNodes.push(node); + } else { + var file = childs[i].getAttribute('file'); + if (file) { + this._pydioObject.getContextHolder().setPendingSelection(file); + } + reloadNodes.push(this._pydioObject.getContextNode()); + } + } else if (obName == 'repository_list') { + this._pydioObject.reloadRepositoriesList(); } - return true; - }, function(){ - // cancel callback - if(json["CANCEL"]["EVAL"]){ - eval(json["CANCEL"]["EVAL"]); + } else if (childs[i].nodeName == 'nodes_diff') { + var dm = this._pydioObject.getContextHolder(); + if (dm.getAjxpNodeProvider().parseAjxpNodesDiffs) { + dm.getAjxpNodeProvider().parseAjxpNodesDiffs(childs[i], dm, !window.currentLightBox); } - return true; - }); - */ - throw new Error(); - } else if (childs[i].tagName == 'reload_instruction') { - var obName = childs[i].getAttribute('object'); - if (obName == 'data') { - var node = childs[i].getAttribute('node'); - if (node) { - reloadNodes.push(node); - } else { - var file = childs[i].getAttribute('file'); - if (file) { - this._pydioObject.getContextHolder().setPendingSelection(file); + } else if (childs[i].tagName == "logging_result") { + if (childs[i].getAttribute("secure_token")) { + var serverAccessPath = this._pydioObject.Parameters.get("ajxpServerAccess"); + var regex = new RegExp('.*?[&\\?]' + 'minisite_session' + '=(.*?)&.*'); + + var val = serverAccessPath.replace(regex, "$1"); + var minisite_session = val == serverAccessPath ? false : val; + + var secure_token = childs[i].getAttribute("secure_token"); + + var parts = serverAccessPath.split("?secure_token"); + serverAccessPath = parts[0] + "?secure_token=" + secure_token; + if (minisite_session) serverAccessPath += "&minisite_session=" + minisite_session; + + this.setSecureToken(secure_token); + this._pydioObject.Parameters.set("SECURE_TOKEN", secure_token); + // BACKWARD COMPAT + window.ajxpServerAccessPath = serverAccessPath; + this._pydioObject.Parameters.set("ajxpServerAccess", serverAccessPath); + if (window.ajxpBootstrap && ajxpBootstrap.parameters) { + ajxpBootstrap.parameters.set("ajxpServerAccess", serverAccessPath); + ajxpBootstrap.parameters.set("SECURE_TOKEN", secure_token); } - reloadNodes.push(this._pydioObject.getContextNode()); + if (window.Connexion) Connexion.SECURE_TOKEN = secure_token; } - } else if (obName == 'repository_list') { - this._pydioObject.reloadRepositoriesList(); - } - } else if (childs[i].nodeName == 'nodes_diff') { - var dm = this._pydioObject.getContextHolder(); - if (dm.getAjxpNodeProvider().parseAjxpNodesDiffs) { - dm.getAjxpNodeProvider().parseAjxpNodesDiffs(childs[i], dm, !window.currentLightBox); - } - } else if (childs[i].tagName == 'logging_result') { - if (childs[i].getAttribute('secure_token')) { - var serverAccessPath = this._pydioObject.Parameters.get('ajxpServerAccess'); - var regex = new RegExp('.*?[&\\?]' + 'minisite_session' + '=(.*?)&.*'); - - var val = serverAccessPath.replace(regex, '$1'); - var minisite_session = val == serverAccessPath ? false : val; - - var secure_token = childs[i].getAttribute('secure_token'); - - var parts = serverAccessPath.split('?secure_token'); - serverAccessPath = parts[0] + '?secure_token=' + secure_token; - if (minisite_session) serverAccessPath += '&minisite_session=' + minisite_session; - - this.setSecureToken(secure_token); - this._pydioObject.Parameters.set('SECURE_TOKEN', secure_token); - // BACKWARD COMPAT - window.ajxpServerAccessPath = serverAccessPath; - this._pydioObject.Parameters.set('ajxpServerAccess', serverAccessPath); - if (window.ajxpBootstrap && ajxpBootstrap.parameters) { - ajxpBootstrap.parameters.set('ajxpServerAccess', serverAccessPath); - ajxpBootstrap.parameters.set('SECURE_TOKEN', secure_token); + var result = childs[i].getAttribute('value'); + var errorId = false; + if (result == '1') { + try { + /* + TODO: REMEMBER COOKIE STUFF + if(childs[i].getAttribute('remember_login') && childs[i].getAttribute('remember_pass')){ + var login = childs[i].getAttribute('remember_login'); + var pass = childs[i].getAttribute('remember_pass'); + storeRememberData(login, pass); + } + */ + } catch (e) { + Logger.error('Error after login, could prevent registry loading!', e); + } + this._pydioObject.loadXmlRegistry(); + } else if (result == '0' || result == '-1') { + errorId = 285; + } else if (result == '2') { + this._pydioObject.loadXmlRegistry(); + } else if (result == '-2') { + errorId = 285; + } else if (result == '-3') { + errorId = 366; + } else if (result == '-4') { + errorId = 386; } - if (window.Connexion) Connexion.SECURE_TOKEN = secure_token; - } - var result = childs[i].getAttribute('value'); - var errorId = false; - if (result == '1') { - try {} catch (e) { - Logger.error('Error after login, could prevent registry loading!', e); + if (errorId) { + error = true; + this.LAST_ERROR_ID = errorId; + Logger.error(this._pydioObject.MessageHash[errorId]); } - this._pydioObject.loadXmlRegistry(); - } else if (result == '0' || result == '-1') { - errorId = 285; - } else if (result == '2') { - this._pydioObject.loadXmlRegistry(); - } else if (result == '-2') { - errorId = 285; - } else if (result == '-3') { - errorId = 366; - } else if (result == '-4') { - errorId = 386; - } - if (errorId) { - error = true; - this.LAST_ERROR_ID = errorId; - Logger.error(this._pydioObject.MessageHash[errorId]); - } - } else if (childs[i].tagName == 'trigger_bg_action') { - var name = childs[i].getAttribute('name'); - var messageId = childs[i].getAttribute('messageId'); - var parameters = {}; - for (var j = 0; j < childs[i].childNodes.length; j++) { - var paramChild = childs[i].childNodes[j]; - if (paramChild.tagName == 'param') { - parameters[paramChild.getAttribute('name')] = paramChild.getAttribute('value'); + } else if (childs[i].tagName == "trigger_bg_action") { + var name = childs[i].getAttribute("name"); + var messageId = childs[i].getAttribute("messageId"); + var parameters = {}; + for (var j = 0; j < childs[i].childNodes.length; j++) { + var paramChild = childs[i].childNodes[j]; + if (paramChild.tagName == 'param') { + parameters[paramChild.getAttribute("name")] = paramChild.getAttribute("value"); + } + } + var bgManager = this._pydioObject.getController().getBackgroundTasksManager(); + if (bgManager) { + bgManager.queueAction(name, parameters, messageId); + bgManager.next(); } - } - var bgManager = this._pydioObject.getController().getBackgroundTasksManager(); - if (bgManager) { - bgManager.queueAction(name, parameters, messageId); - bgManager.next(); } } + if (reloadNodes.length) { + this._pydioObject.getContextHolder().multipleNodesReload(reloadNodes); + } + return !error; } - if (reloadNodes.length) { - this._pydioObject.getContextHolder().multipleNodesReload(reloadNodes); - } - return !error; - }; - - /** - * Submits a form using Connexion class. - * @param formName String The id of the form - * @param post Boolean Whether to POST or GET - * @param completeCallback Function Callback to be called on complete - */ - PydioApi.prototype.submitForm = function submitForm(formName, post, completeCallback) { - var params = {}; - // TODO: UI IMPLEMENTATION - $(formName).getElements().each(function (fElement) { - var fValue = fElement.getValue(); - if (fElement.name == 'get_action' && fValue.substr(0, 4) == 'http') { - fValue = getBaseName(fValue); + /** + * Submits a form using Connexion class. + * @param formName String The id of the form + * @param post Boolean Whether to POST or GET + * @param completeCallback Function Callback to be called on complete + */ + }, { + key: 'submitForm', + value: function submitForm(formName, post, completeCallback) { + var params = {}; + // TODO: UI IMPLEMENTATION + $(formName).getElements().each(function (fElement) { + var fValue = fElement.getValue(); + if (fElement.name == 'get_action' && fValue.substr(0, 4) == 'http') { + fValue = getBaseName(fValue); + } + if (fElement.type == 'radio' && !fElement.checked) return; + if (params[fElement.name] && fElement.name.endsWith('[]')) { + var existing = params[fElement.name]; + if (typeof existing == 'string') existing = [existing]; + existing.push(fValue); + params[fElement.name] = existing; + } else { + params[fElement.name] = fValue; + } + }); + if (this._pydioObject.getContextNode()) { + params['dir'] = this._pydioObject.getContextNode().getPath(); } - if (fElement.type == 'radio' && !fElement.checked) return; - if (params[fElement.name] && fElement.name.endsWith('[]')) { - var existing = params[fElement.name]; - if (typeof existing == 'string') existing = [existing]; - existing.push(fValue); - params[fElement.name] = existing; + var onComplete; + if (completeCallback) { + onComplete = completeCallback; } else { - params[fElement.name] = fValue; + onComplete = (function (transport) { + this.parseXmlMessage(transport.responseXML); + }).bind(this); } - }); - if (this._pydioObject.getContextNode()) { - params['dir'] = this._pydioObject.getContextNode().getPath(); + this.request(params, onComplete, null, { method: post ? 'post' : 'get' }); } - var onComplete; - if (completeCallback) { - onComplete = completeCallback; - } else { - onComplete = (function (transport) { - this.parseXmlMessage(transport.responseXML); - }).bind(this); + + /** + * Trigger a simple download + * @param url String + */ + }, { + key: 'triggerDownload', + value: function triggerDownload(url) { + document.location.href = url; + } + }], [{ + key: 'supportsUpload', + value: function supportsUpload() { + if (window.Connexion) { + return window.FormData || window.FileReader; + } else if (window.jQuery) { + return window.FormData; + } + return false; + } + }, { + key: 'getClient', + value: function getClient() { + if (PydioApi._PydioClient) return PydioApi._PydioClient; + var client = new PydioApi(); + PydioApi._PydioClient = client; + return client; } - this.request(params, onComplete, null, { method: post ? 'post' : 'get' }); - }; - /** - * Trigger a simple download - * @param url String - */ + /** + * Load a javascript library + * @param fileName String + * @param onLoadedCode Function Callback + * @param aSync Boolean load library asynchroneously + * @todo : We should use Require or equivalent instead. + */ + }, { + key: 'loadLibrary', + value: function loadLibrary(fileName, onLoadedCode, aSync) { + if (window.pydio && pydio.Parameters.get("ajxpVersion") && fileName.indexOf("?") == -1) { + fileName += "?v=" + pydio.Parameters.get("ajxpVersion"); + } + PydioApi._libUrl = false; + if (window.pydio && pydio.Parameters.get('SERVER_PREFIX_URI')) { + PydioApi._libUrl = pydio.Parameters.get('SERVER_PREFIX_URI'); + } + //var path = (PydioApi._libUrl?PydioApi._libUrl+'/'+fileName:fileName); + + /*if(window.jQuery && window.jQuery.ajax){ + jQuery.ajax(path, + { + method:'get', + async: (aSync?true:false), + complete:function(transport){ + if(transport.responseText) + { + try + { + var script = transport.responseText; + if (window.execScript){ + window.execScript( script ); + } + else{ + // TO TEST, THIS SEEM TO WORK ON SAFARI + window.my_code = script; + var script_tag = document.createElement('script'); + script_tag.type = 'text/javascript'; + script_tag.innerHTML = 'eval(window.my_code)'; + document.getElementsByTagName('head')[0].appendChild(script_tag); + } + if(onLoadedCode != null) onLoadedCode(); + } + catch(e) + { + alert('error loading '+fileName+':'+ e.message); + } + } + pydio.fire("server_answer"); + } + }); + }else */if (window.Connexion) { - PydioApi.prototype.triggerDownload = function triggerDownload(url) { - document.location.href = url; - }; + var conn = new Connexion(); + conn._libUrl = false; + if (pydio.Parameters.get('SERVER_PREFIX_URI')) { + conn._libUrl = pydio.Parameters.get('SERVER_PREFIX_URI'); + } + conn.loadLibrary(fileName, onLoadedCode, aSync); + } + } + }]); return PydioApi; })(); - -/* -TODO: REMEMBER COOKIE STUFF -if(childs[i].getAttribute('remember_login') && childs[i].getAttribute('remember_pass')){ - var login = childs[i].getAttribute('remember_login'); - var pass = childs[i].getAttribute('remember_pass'); - storeRememberData(login, pass); -} -*/ \ No newline at end of file diff --git a/core/src/plugins/gui.ajax/res/js/core/http/ResourcesManager.js b/core/src/plugins/gui.ajax/res/js/core/http/ResourcesManager.js index 9bb4ef3010..23cf9ecbe9 100644 --- a/core/src/plugins/gui.ajax/res/js/core/http/ResourcesManager.js +++ b/core/src/plugins/gui.ajax/res/js/core/http/ResourcesManager.js @@ -23,6 +23,8 @@ */ 'use strict'; +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var ResourcesManager = (function () { @@ -44,405 +46,476 @@ var ResourcesManager = (function () { * @param className String */ - ResourcesManager.prototype.addJSResource = function addJSResource(fileName, className) { - if (!this.resources.js) { - this.resources.js = []; + _createClass(ResourcesManager, [{ + key: 'addJSResource', + value: function addJSResource(fileName, className) { + if (!this.resources.js) { + this.resources.js = []; + } + this.resources.js.push({ + fileName: fileName, + className: className, + autoload: false + }); } - this.resources.js.push({ - fileName: fileName, - className: className, - autoload: false - }); - }; - - /** - * Adds a CSS resource - * @param fileName String - */ - ResourcesManager.prototype.addCSSResource = function addCSSResource(fileName) { - if (!this.resources.css) { - this.resources.css = []; + /** + * Adds a CSS resource + * @param fileName String + */ + }, { + key: 'addCSSResource', + value: function addCSSResource(fileName) { + if (!this.resources.css) { + this.resources.css = []; + } + this.resources.css.push(fileName); } - this.resources.css.push(fileName); - }; - /** - * Adds a FORM from html snipper - * @param formId String - * @param htmlSnippet String - */ - - ResourcesManager.prototype.addGuiForm = function addGuiForm(formId, htmlSnippet) { - if (!this.resources.forms) { - this.resources.forms = new Map(); + /** + * Adds a FORM from html snipper + * @param formId String + * @param htmlSnippet String + */ + }, { + key: 'addGuiForm', + value: function addGuiForm(formId, htmlSnippet) { + if (!this.resources.forms) { + this.resources.forms = new Map(); + } + this.resources.forms.set(formId, htmlSnippet); } - this.resources.forms.set(formId, htmlSnippet); - }; - - /** - * Add a dependency to another plugin - * @param data Object - */ - ResourcesManager.prototype.addDependency = function addDependency(data) { - if (!this.resources.dependencies) { - this.resources.dependencies = []; + /** + * Add a dependency to another plugin + * @param data Object + */ + }, { + key: 'addDependency', + value: function addDependency(data) { + if (!this.resources.dependencies) { + this.resources.dependencies = []; + } + this.resources.dependencies.push(data); } - this.resources.dependencies.push(data); - }; - - /** - * Check if some dependencies must be loaded before - * @returns Boolean - */ - ResourcesManager.prototype.hasDependencies = function hasDependencies() { - return this.resources.dependencies || false; - }; - - /** - * Load resources - * @param resourcesRegistry $H Ajaxplorer ressources registry - */ + /** + * Check if some dependencies must be loaded before + * @returns Boolean + */ + }, { + key: 'hasDependencies', + value: function hasDependencies() { + return this.resources.dependencies || false; + } - ResourcesManager.prototype.load = function load(resourcesRegistry) { - var jsAutoloadOnly = arguments[1] === undefined ? false : arguments[1]; + /** + * Load resources + * @param resourcesRegistry $H Ajaxplorer ressources registry + */ + }, { + key: 'load', + value: function load(resourcesRegistry) { + var jsAutoloadOnly = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; + + if (this.loaded) return; + if (this.hasDependencies()) { + this.resources.dependencies.forEach((function (el) { + if (resourcesRegistry[el]) { + resourcesRegistry[el].load(resourcesRegistry); + } + }).bind(this)); + } + if (this.resources.forms) { + this.resources.forms.forEach((function (value, key) { + this.loadGuiForm(key, value); + }).bind(this)); + } + if (this.resources.js) { + this.resources.js.forEach((function (value) { + if (jsAutoloadOnly && !value.autoload) return; + this.loadJSResource(value.fileName, value.className); + }).bind(this)); + } + if (this.resources.css) { + this.resources.css.forEach((function (value) { + this.loadCSSResource(value); + }).bind(this)); + } + this.loaded = true; + } - if (this.loaded) return; - if (this.hasDependencies()) { - this.resources.dependencies.forEach((function (el) { - if (resourcesRegistry[el]) { - resourcesRegistry[el].load(resourcesRegistry); + /** + * Load a javascript file + * @param fileName String + * @param className String + * @param callback Function + * @param aSync Boolean + */ + }, { + key: 'loadJSResource', + value: function loadJSResource(fileName, className, callback, aSync) { + + if (!window[className]) { + if (typeof className != 'function' || typeof className.prototype != 'object') { + var registry = ResourcesManager.__asyncCallbacks; + if (aSync && registry && registry.get(fileName) && registry.get(fileName)) { + // Already loading, just register a callback and return + this.wrapCallback(callback ? callback : function () {}, fileName); + return; + } + PydioApi.loadLibrary(fileName, aSync && callback ? this.wrapCallback(callback, fileName) : callback, aSync); } - }).bind(this)); - } - if (this.resources.forms) { - this.resources.forms.forEach((function (value, key) { - this.loadGuiForm(key, value); - }).bind(this)); + } else if (callback) { + callback(); + } } - if (this.resources.js) { - this.resources.js.forEach((function (value) { - if (jsAutoloadOnly && !value.autoload) return; - this.loadJSResource(value.fileName, value.className); - }).bind(this)); + }, { + key: 'wrapCallback', + value: function wrapCallback(callback, fileName) { + if (!ResourcesManager.__asyncCallbacks) ResourcesManager.__asyncCallbacks = new Map(); + var registry = ResourcesManager.__asyncCallbacks; + if (!registry.get(fileName)) registry.set(fileName, []); + registry.get(fileName).push(callback); + return function () { + while (registry.get(fileName).length) { + var cb = registry.get(fileName).pop(); + cb(); + } + }; } - if (this.resources.css) { - this.resources.css.forEach((function (value) { - this.loadCSSResource(value); - }).bind(this)); + }, { + key: 'loadWebComponents', + value: function loadWebComponents(fileNames, callback) { + if (!Polymer) { + throw Error('Cannot find Polymer library!'); + } + Polymer['import'](fileNames, callback); } - this.loaded = true; - }; - - /** - * Load a javascript file - * @param fileName String - * @param className String - * @param callback Function - * @param aSync Boolean - */ - - ResourcesManager.prototype.loadJSResource = function loadJSResource(fileName, className, callback, aSync) { - if (!window[className]) { - if (typeof className != 'function' || typeof className.prototype != 'object') { - var registry = ResourcesManager.__asyncCallbacks; - if (aSync && registry && registry.get(fileName) && registry.get(fileName)) { - // Already loading, just register a callback and return - this.wrapCallback(callback ? callback : function () {}, fileName); - return; + /** + * Load a CSS file + * @param fileName String + */ + }, { + key: 'loadCSSResource', + value: function loadCSSResource(fileName) { + + var head = document.getElementsByTagName('head')[0]; + if (head && head.down) { + if (pydio.Parameters.get('SERVER_PREFIX_URI')) { + fileName = pydio.Parameters.get('SERVER_PREFIX_URI') + fileName; + } + fileName = fileName + "?v=" + pydio.Parameters.get("ajxpVersion"); + // WARNING PROTOTYPE STUFF + var select = head.down('[href="' + fileName + '"]'); + if (!select) { + var cssNode = new Element('link', { + type: 'text/css', + rel: 'stylesheet', + href: fileName, + media: 'screen' + }); + head.insert(cssNode); } - PydioApi.loadLibrary(fileName, aSync && callback ? this.wrapCallback(callback, fileName) : callback, aSync); } - } else if (callback) { - callback(); } - }; - - ResourcesManager.prototype.wrapCallback = function wrapCallback(callback, fileName) { - if (!ResourcesManager.__asyncCallbacks) ResourcesManager.__asyncCallbacks = new Map(); - var registry = ResourcesManager.__asyncCallbacks; - if (!registry.get(fileName)) registry.set(fileName, []); - registry.get(fileName).push(callback); - return function () { - while (registry.get(fileName).length) { - var cb = registry.get(fileName).pop(); - cb(); - } - }; - }; - ResourcesManager.prototype.loadWebComponents = function loadWebComponents(fileNames, callback) { - if (!Polymer) { - throw Error('Cannot find Polymer library!'); + /** + * Insert the HTML snipper and evaluate scripts + * @param formId String + * @param htmlSnippet String + */ + }, { + key: 'loadGuiForm', + value: function loadGuiForm(formId, htmlSnippet) { + if (!$(this.mainFormContainerId).select('[id="' + formId + '"]').length) { + // TODO - PROTOTYPE STUFF + htmlSnippet.evalScripts(); + $(this.mainFormContainerId).insert(htmlSnippet.stripScripts()); + } } - Polymer['import'](fileNames, callback); - }; - - /** - * Load a CSS file - * @param fileName String - */ - - ResourcesManager.prototype.loadCSSResource = function loadCSSResource(fileName) { - var head = document.getElementsByTagName('head')[0]; - if (head && head.down) { - if (pydio.Parameters.get('SERVER_PREFIX_URI')) { - fileName = pydio.Parameters.get('SERVER_PREFIX_URI') + fileName; + /** + * Load the resources from XML + * @param node XMLNode + */ + }, { + key: 'loadFromXmlNode', + value: function loadFromXmlNode(node) { + var clForm = {}; + var k; + if (node.nodeName == "resources") { + for (k = 0; k < node.childNodes.length; k++) { + if (node.childNodes[k].nodeName == 'js') { + this.addJSResource(node.childNodes[k].getAttribute('file'), node.childNodes[k].getAttribute('className'), node.childNodes[k].getAttribute('autoload') === true); + } else if (node.childNodes[k].nodeName == 'css') { + this.addCSSResource(node.childNodes[k].getAttribute('file')); + } else if (node.childNodes[k].nodeName == 'img_library') { + ResourcesManager.addImageLibrary(node.childNodes[k].getAttribute('alias'), node.childNodes[k].getAttribute('path')); + } + } + } else if (node.nodeName == "dependencies") { + for (k = 0; k < node.childNodes.length; k++) { + if (node.childNodes[k].nodeName == "pluginResources") { + this.addDependency(node.childNodes[k].getAttribute("pluginName")); + } + } + } else if (node.nodeName == "clientForm") { + if (!node.getAttribute("theme") || node.getAttribute("theme") == pydio.Parameters.get("theme")) { + clForm = { formId: node.getAttribute("id"), formCode: node.firstChild.nodeValue }; + } } - fileName = fileName + '?v=' + pydio.Parameters.get('ajxpVersion'); - // WARNING PROTOTYPE STUFF - var select = head.down('[href="' + fileName + '"]'); - if (!select) { - var cssNode = new Element('link', { - type: 'text/css', - rel: 'stylesheet', - href: fileName, - media: 'screen' - }); - head.insert(cssNode); + if (clForm.formId) { + this.addGuiForm(clForm.formId, clForm.formCode); } } - }; - - /** - * Insert the HTML snipper and evaluate scripts - * @param formId String - * @param htmlSnippet String - */ - ResourcesManager.prototype.loadGuiForm = function loadGuiForm(formId, htmlSnippet) { - if (!$(this.mainFormContainerId).select('[id="' + formId + '"]').length) { - // TODO - PROTOTYPE STUFF - htmlSnippet.evalScripts(); - $(this.mainFormContainerId).insert(htmlSnippet.stripScripts()); + /** + * + * @param aliasName + * @param aliasPath + * @todo MOVE OUTSIDE? + */ + }], [{ + key: 'addImageLibrary', + value: function addImageLibrary(aliasName, aliasPath) { + if (!window.AjxpImageLibraries) window.AjxpImageLibraries = {}; + window.AjxpImageLibraries[aliasName] = aliasPath; } - }; - - /** - * Load the resources from XML - * @param node XMLNode - */ - ResourcesManager.prototype.loadFromXmlNode = function loadFromXmlNode(node) { - var clForm = {}; - var k; - if (node.nodeName == 'resources') { - for (k = 0; k < node.childNodes.length; k++) { - if (node.childNodes[k].nodeName == 'js') { - this.addJSResource(node.childNodes[k].getAttribute('file'), node.childNodes[k].getAttribute('className'), node.childNodes[k].getAttribute('autoload') === true); - } else if (node.childNodes[k].nodeName == 'css') { - this.addCSSResource(node.childNodes[k].getAttribute('file')); - } else if (node.childNodes[k].nodeName == 'img_library') { - ResourcesManager.addImageLibrary(node.childNodes[k].getAttribute('alias'), node.childNodes[k].getAttribute('path')); + /** + * Check if resources are tagged autoload and load them + * @param registry DOMDocument XML Registry + */ + }, { + key: 'loadAutoLoadResources', + value: function loadAutoLoadResources(registry) { + var manager = new ResourcesManager(); + var jsNodes = XMLUtils.XPathSelectNodes(registry, 'plugins/*/client_settings/resources/js'); + var node; + ResourcesManager.__modules = new Map(); + ResourcesManager.__dependencies = new Map(); + ResourcesManager.__components = new Map(); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = jsNodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + node = _step.value; + + ResourcesManager.__modules.set(node.getAttribute('className'), node.getAttribute('file')); + if (node.getAttribute('autoload') === "true") { + manager.loadJSResource(node.getAttribute('file'), node.getAttribute('className'), null, false); + } + if (node.getAttribute('depends')) { + ResourcesManager.__dependencies.set(node.getAttribute('className'), node.getAttribute('depends').split(',')); + } } - } - } else if (node.nodeName == 'dependencies') { - for (k = 0; k < node.childNodes.length; k++) { - if (node.childNodes[k].nodeName == 'pluginResources') { - this.addDependency(node.childNodes[k].getAttribute('pluginName')); + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator['return']) { + _iterator['return'](); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } } } - } else if (node.nodeName == 'clientForm') { - if (!node.getAttribute('theme') || node.getAttribute('theme') == pydio.Parameters.get('theme')) { - clForm = { formId: node.getAttribute('id'), formCode: node.firstChild.nodeValue }; - } - } - if (clForm.formId) { - this.addGuiForm(clForm.formId, clForm.formCode); - } - }; - /** - * - * @param aliasName - * @param aliasPath - * @todo MOVE OUTSIDE? - */ + var compNodes = XMLUtils.XPathSelectNodes(registry, 'plugins/*/client_settings/resources/component'); + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; - ResourcesManager.addImageLibrary = function addImageLibrary(aliasName, aliasPath) { - if (!window.AjxpImageLibraries) window.AjxpImageLibraries = {}; - window.AjxpImageLibraries[aliasName] = aliasPath; - }; + try { + for (var _iterator2 = compNodes[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + node = _step2.value; - /** - * Check if resources are tagged autoload and load them - * @param registry DOMDocument XML Registry - */ - - ResourcesManager.loadAutoLoadResources = function loadAutoLoadResources(registry) { - var manager = new ResourcesManager(); - var jsNodes = XMLUtils.XPathSelectNodes(registry, 'plugins/*/client_settings/resources/js'); - var node; - ResourcesManager.__modules = new Map(); - ResourcesManager.__dependencies = new Map(); - ResourcesManager.__components = new Map(); - for (var _iterator = jsNodes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { - if (_isArray) { - if (_i >= _iterator.length) break; - node = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - node = _i.value; + ResourcesManager.__components.set(node.getAttribute('componentName'), node.getAttribute('file')); + if (node.getAttribute('autoload') === "true") { + manager.loadWebComponents([node.getAttribute('file')]); + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2['return']) { + _iterator2['return'](); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } } - ResourcesManager.__modules.set(node.getAttribute('className'), node.getAttribute('file')); - if (node.getAttribute('autoload') === 'true') { - manager.loadJSResource(node.getAttribute('file'), node.getAttribute('className'), null, false); - } - if (node.getAttribute('depends')) { - ResourcesManager.__dependencies.set(node.getAttribute('className'), node.getAttribute('depends').split(',')); - } - } - var compNodes = XMLUtils.XPathSelectNodes(registry, 'plugins/*/client_settings/resources/component'); - for (var _iterator2 = compNodes, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) { - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - node = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - node = _i2.value; - } + var imgNodes = XMLUtils.XPathSelectNodes(registry, 'plugins/*/client_settings/resources/img_library'); + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; - ResourcesManager.__components.set(node.getAttribute('componentName'), node.getAttribute('file')); - if (node.getAttribute('autoload') === 'true') { - manager.loadWebComponents([node.getAttribute('file')]); - } - } - var imgNodes = XMLUtils.XPathSelectNodes(registry, 'plugins/*/client_settings/resources/img_library'); - for (var _iterator3 = imgNodes, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) { - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - node = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - node = _i3.value; - } + try { + for (var _iterator3 = imgNodes[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + node = _step3.value; - ResourcesManager.addImageLibrary(node.getAttribute('alias'), node.getAttribute('path')); - } - var cssNodes = XMLUtils.XPathSelectNodes(registry, 'plugins/*/client_settings/resources/css[@autoload="true"]'); - for (var _iterator4 = cssNodes, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) { - if (_isArray4) { - if (_i4 >= _iterator4.length) break; - node = _iterator4[_i4++]; - } else { - _i4 = _iterator4.next(); - if (_i4.done) break; - node = _i4.value; + ResourcesManager.addImageLibrary(node.getAttribute('alias'), node.getAttribute('path')); + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3['return']) { + _iterator3['return'](); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } } - manager.loadCSSResource(node.getAttribute('file')); - } - }; + var cssNodes = XMLUtils.XPathSelectNodes(registry, 'plugins/*/client_settings/resources/css[@autoload="true"]'); + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; - /** - * - * @param className String - * @param dependencies Set - */ + try { + for (var _iterator4 = cssNodes[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + node = _step4.value; - ResourcesManager.findDependencies = function findDependencies(className, dependencies) { - if (ResourcesManager.__dependencies.has(className)) { - var deps = ResourcesManager.__dependencies.get(className); - deps.forEach(function (dep) { - if (!dependencies.has(dep) && ResourcesManager.__modules.has(dep)) { - dependencies.add(dep); - ResourcesManager.findDependencies(dep, dependencies); + manager.loadCSSResource(node.getAttribute("file")); } - }); + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4['return']) { + _iterator4['return'](); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } } - }; - ResourcesManager.loadClassesAndApply = function loadClassesAndApply(classNames, callbackFunc) { - if (!ResourcesManager.__modules) { - ResourcesManager.loadAutoLoadResources(pydio.Registry.getXML()); + /** + * + * @param className String + * @param dependencies Set + */ + }, { + key: 'findDependencies', + value: function findDependencies(className, dependencies) { + if (ResourcesManager.__dependencies.has(className)) { + var deps = ResourcesManager.__dependencies.get(className); + deps.forEach(function (dep) { + if (!dependencies.has(dep) && ResourcesManager.__modules.has(dep)) { + dependencies.add(dep); + ResourcesManager.findDependencies(dep, dependencies); + } + }); + } } - var modules = new Map(); - classNames.forEach(function (c) { - if (!window[c] && ResourcesManager.__modules.has(c)) { - var deps = new Set(); - ResourcesManager.findDependencies(c, deps); - if (deps.size) { - deps.forEach(function (d) { - modules.set(d, { - className: d, - fileName: ResourcesManager.__modules.get(d), - require: ResourcesManager.__modules.get(d).replace('.js', '') + }, { + key: 'loadClassesAndApply', + value: function loadClassesAndApply(classNames, callbackFunc) { + if (!ResourcesManager.__modules) { + ResourcesManager.loadAutoLoadResources(pydio.Registry.getXML()); + } + var modules = new Map(); + classNames.forEach(function (c) { + if (!window[c] && ResourcesManager.__modules.has(c)) { + var deps = new Set(); + ResourcesManager.findDependencies(c, deps); + if (deps.size) { + deps.forEach(function (d) { + modules.set(d, { + className: d, + fileName: ResourcesManager.__modules.get(d), + require: ResourcesManager.__modules.get(d).replace('.js', '') + }); }); + } + modules.set(c, { + className: c, + fileName: ResourcesManager.__modules.get(c), + require: ResourcesManager.__modules.get(c).replace('.js', '') }); } - modules.set(c, { - className: c, - fileName: ResourcesManager.__modules.get(c), - require: ResourcesManager.__modules.get(c).replace('.js', '') - }); - } - }); - if (!modules.size) { - callbackFunc(); - return; - } - - if (modules.size == 1) { - ResourcesManager.detectModuleToLoadAndApply(modules.keys().next().value, callbackFunc); - return; - } - if (window.requirejs) { - // Let require handle multiple async - var requires = []; - modules.forEach(function (e) { - requires.push(e.require); - }); - requirejs(requires, callbackFunc); - } else { - // Load sync and apply the callback manually - var loader = new ResourcesManager(); - modules.forEach(function (element) { - loader.loadJSResource(element.fileName, element.className, null, false); }); - callbackFunc(); - } - }; + if (!modules.size) { + callbackFunc(); + return; + } - ResourcesManager.detectModuleToLoadAndApply = function detectModuleToLoadAndApply(callbackString, callbackFunc) { - if (!ResourcesManager.__modules) { - ResourcesManager.loadAutoLoadResources(pydio.Registry.getXML()); - } - var className = callbackString.split('.', 1).shift(); - if (!window[className] && ResourcesManager.__modules.has(className)) { + if (modules.size == 1) { + ResourcesManager.detectModuleToLoadAndApply(modules.keys().next().value, callbackFunc); + return; + } if (window.requirejs) { - requirejs([ResourcesManager.__modules.get(className).replace('.js', '')], callbackFunc); + // Let require handle multiple async + var requires = []; + modules.forEach(function (e) { + requires.push(e.require); + }); + requirejs(requires, callbackFunc); } else { + // Load sync and apply the callback manually var loader = new ResourcesManager(); - loader.loadJSResource(ResourcesManager.__modules.get(className), className, callbackFunc, true); + modules.forEach(function (element) { + loader.loadJSResource(element.fileName, element.className, null, false); + }); + callbackFunc(); } - } else { - callbackFunc(); } - }; - - ResourcesManager.loadWebComponentsAndApply = function loadWebComponentsAndApply(componentsList, callbackFunc) { - if (!ResourcesManager.__modules) { - ResourcesManager.loadAutoLoadResources(pydio.Registry.getXML()); + }, { + key: 'detectModuleToLoadAndApply', + value: function detectModuleToLoadAndApply(callbackString, callbackFunc) { + if (!ResourcesManager.__modules) { + ResourcesManager.loadAutoLoadResources(pydio.Registry.getXML()); + } + var className = callbackString.split('.', 1).shift(); + if (!window[className] && ResourcesManager.__modules.has(className)) { + if (window.requirejs) { + requirejs([ResourcesManager.__modules.get(className).replace('.js', '')], callbackFunc); + } else { + var loader = new ResourcesManager(); + loader.loadJSResource(ResourcesManager.__modules.get(className), className, callbackFunc, true); + } + } else { + callbackFunc(); + } } - var files = []; - componentsList.forEach(function (v) { - if (ResourcesManager.__components.has(v)) { - files.push(ResourcesManager.__components.get(v)); + }, { + key: 'loadWebComponentsAndApply', + value: function loadWebComponentsAndApply(componentsList, callbackFunc) { + if (!ResourcesManager.__modules) { + ResourcesManager.loadAutoLoadResources(pydio.Registry.getXML()); + } + var files = []; + componentsList.forEach(function (v) { + if (ResourcesManager.__components.has(v)) { + files.push(ResourcesManager.__components.get(v)); + } + }); + if (files.length) { + var manager = new ResourcesManager(); + manager.loadWebComponents(files, callbackFunc); } - }); - if (files.length) { - var manager = new ResourcesManager(); - manager.loadWebComponents(files, callbackFunc); } - }; + }]); return ResourcesManager; -})(); \ No newline at end of file +})(); diff --git a/core/src/plugins/gui.ajax/res/js/core/lang/Logger.js b/core/src/plugins/gui.ajax/res/js/core/lang/Logger.js index c4197c6136..a06e87dfe5 100644 --- a/core/src/plugins/gui.ajax/res/js/core/lang/Logger.js +++ b/core/src/plugins/gui.ajax/res/js/core/lang/Logger.js @@ -1,5 +1,7 @@ "use strict"; +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Logger = (function () { @@ -7,17 +9,22 @@ var Logger = (function () { _classCallCheck(this, Logger); } - Logger.log = function log(message) { - if (window.console) console.log(message); - }; - - Logger.error = function error(message) { - if (window.console) console.error(message); - }; - - Logger.debug = function debug(message) { - if (window.console) console.debug(message); - }; + _createClass(Logger, null, [{ + key: "log", + value: function log(message) { + if (window.console) console.log(message); + } + }, { + key: "error", + value: function error(message) { + if (window.console) console.error(message); + } + }, { + key: "debug", + value: function debug(message) { + if (window.console) console.debug(message); + } + }]); return Logger; -})(); \ No newline at end of file +})(); diff --git a/core/src/plugins/gui.ajax/res/js/core/lang/Observable.js b/core/src/plugins/gui.ajax/res/js/core/lang/Observable.js index 4b0f804fc7..92173c76e1 100644 --- a/core/src/plugins/gui.ajax/res/js/core/lang/Observable.js +++ b/core/src/plugins/gui.ajax/res/js/core/lang/Observable.js @@ -1,5 +1,7 @@ 'use strict'; +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var Observable = (function () { @@ -7,53 +9,60 @@ var Observable = (function () { _classCallCheck(this, Observable); } - Observable.prototype._objectEventSetup = function _objectEventSetup(event_name) { - this._observers = this._observers || {}; - this._observers[event_name] = this._observers[event_name] || []; - }; - - Observable.prototype.observe = function observe(event_name, observer) { - if (typeof event_name == 'string' && typeof observer != 'undefined') { - this._objectEventSetup(event_name); - if (this._observers[event_name].indexOf(observer) == -1) this._observers[event_name].push(observer); - } else { - for (var e in event_name) { - if (event_name.hasOwnProperty(e)) { - this.observe(e, event_name[e]); + _createClass(Observable, [{ + key: '_objectEventSetup', + value: function _objectEventSetup(event_name) { + this._observers = this._observers || {}; + this._observers[event_name] = this._observers[event_name] || []; + } + }, { + key: 'observe', + value: function observe(event_name, observer) { + if (typeof event_name == 'string' && typeof observer != 'undefined') { + this._objectEventSetup(event_name); + if (this._observers[event_name].indexOf(observer) == -1) this._observers[event_name].push(observer); + } else { + for (var e in event_name) { + if (event_name.hasOwnProperty(e)) { + this.observe(e, event_name[e]); + } } } } - }; - - Observable.prototype.stopObserving = function stopObserving(event_name, observer) { - this._objectEventSetup(event_name); - if (event_name && observer) this._observers[event_name] = this._observers[event_name].filter(function (o) { - return o != observer; - });else if (event_name) { - this._observers[event_name] = []; - } else { - this._observers = {}; + }, { + key: 'stopObserving', + value: function stopObserving(event_name, observer) { + this._objectEventSetup(event_name); + if (event_name && observer) this._observers[event_name] = this._observers[event_name].filter(function (o) { + return o != observer; + });else if (event_name) { + this._observers[event_name] = []; + } else { + this._observers = {}; + } } - }; - - Observable.prototype.observeOnce = function observeOnce(event_name, outer_observer) { - var inner_observer = (function () { - outer_observer.apply(this, arguments); - this.stopObserving(event_name, inner_observer); - }).bind(this); - this._objectEventSetup(event_name); - this._observers[event_name].push(inner_observer); - }; - - Observable.prototype.notify = function notify(event_name) { - this._objectEventSetup(event_name); - var collected_return_values = []; - var args = Array.from(arguments).slice(1); - for (var i = 0; i < this._observers[event_name].length; ++i) { - collected_return_values.push(this._observers[event_name][i].apply(this._observers[event_name][i], args) || null); + }, { + key: 'observeOnce', + value: function observeOnce(event_name, outer_observer) { + var inner_observer = (function () { + outer_observer.apply(this, arguments); + this.stopObserving(event_name, inner_observer); + }).bind(this); + this._objectEventSetup(event_name); + this._observers[event_name].push(inner_observer); + } + }, { + key: 'notify', + value: function notify(event_name) { + this._objectEventSetup(event_name); + var collected_return_values = []; + var args = Array.from(arguments).slice(1); + for (var i = 0; i < this._observers[event_name].length; ++i) { + collected_return_values.push(this._observers[event_name][i].apply(this._observers[event_name][i], args) || null); + } + return collected_return_values; } - return collected_return_values; - }; + }]); return Observable; -})(); \ No newline at end of file +})(); diff --git a/core/src/plugins/gui.ajax/res/js/core/model/Action.js b/core/src/plugins/gui.ajax/res/js/core/model/Action.js index 19802c23c9..02793a0acc 100644 --- a/core/src/plugins/gui.ajax/res/js/core/model/Action.js +++ b/core/src/plugins/gui.ajax/res/js/core/model/Action.js @@ -23,11 +23,16 @@ */ 'use strict'; +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } -function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } +function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Action = (function (_Observable) { + _inherits(Action, _Observable); /** * Standard constructor @@ -36,8 +41,8 @@ var Action = (function (_Observable) { function Action() { _classCallCheck(this, Action); - _Observable.call(this); - this.__DEFAULT_ICON_PATH = '/images/actions/ICON_SIZE'; + _get(Object.getPrototypeOf(Action.prototype), 'constructor', this).call(this); + this.__DEFAULT_ICON_PATH = "/images/actions/ICON_SIZE"; this.options = LangUtils.objectMerge({ name: '', src: '', @@ -114,674 +119,697 @@ var Action = (function (_Observable) { } } - _inherits(Action, _Observable); - - Action.prototype._evalScripts = function _evalScripts(data, localScopeMetadata) { - var metadata = localScopeMetadata; - return eval(data); - }; - - /** - * Sets the manager for this action - * @param manager ActionsManager - */ - - Action.prototype.setManager = function setManager(manager) { - this.manager = manager; - if (this.options.subMenu) { - if (this.subMenuItems.staticItems) { - this.buildSubmenuStaticItems(); - } - if (this.subMenuItems.dynamicItems || this.subMenuItems.dynamicBuilderCode) { - this.prepareSubmenuDynamicBuilder(); - } - } - if (this.options.listeners['init']) { - try { - window.listenerContext = this; - if (typeof this.options.listeners['init'] == 'string') { - this._evalScripts(this.options.listeners['init']); - } else { - this.options.listeners['init'](); + _createClass(Action, [{ + key: '_evalScripts', + value: function _evalScripts(data, localScopeMetadata) { + var metadata = localScopeMetadata; + return eval(data); + } + + /** + * Sets the manager for this action + * @param manager ActionsManager + */ + }, { + key: 'setManager', + value: function setManager(manager) { + this.manager = manager; + if (this.options.subMenu) { + if (this.subMenuItems.staticItems) { + this.buildSubmenuStaticItems(); + } + if (this.subMenuItems.dynamicItems || this.subMenuItems.dynamicBuilderCode) { + this.prepareSubmenuDynamicBuilder(); } - } catch (e) { - Logger.error('Error while evaluating init script for action ' + this.options.name); - } - } - }; - - /** - * Execute the action code - */ - - Action.prototype.apply = function apply() { - if (this.deny) return; - this.manager.publishActionEvent('beforeApply-' + this.options.name); - if (this.options.prepareModal) { - var modal = this.manager.uiGetModal(); - if (modal) { - modal.prepareHeader(this.options.title, this.options.src, this.options.icon_class); } - } - window.actionArguments = []; - window.actionManager = this.manager; - if (arguments[0]) window.actionArguments = arguments[0]; - if (this.options.callbackCode) { - try { - this._evalScripts(this.options.callbackCode); - } catch (e) { - Logger.error(e); - } - } else if (this.options.callbackDialogNode && this.options.callbackDialogNode.getAttribute('dialogOpenForm')) { - var node = this.options.callbackDialogNode; - var dialogFormId = node.getAttribute('dialogOpenForm'); - var okButtonOnly = node.getAttribute('dialogOkButtonOnly') === 'true'; - var skipButtons = node.getAttribute('dialogSkipButtons') === 'true'; - - var onOpenFunc = null;var onCompleteFunc = null;var onCancelFunc = null; - var onOpenNode = XMLUtils.XPathSelectSingleNode(node, 'dialogOnOpen'); - if (onOpenNode && onOpenNode.firstChild) onOpenFunc = new Function('oForm', onOpenNode.firstChild.nodeValue); - var onCompleteNode = XMLUtils.XPathSelectSingleNode(node, 'dialogOnComplete'); - if (onCompleteNode && onCompleteNode.firstChild) { - var completeCode = onCompleteNode.firstChild.nodeValue; - if (onCompleteNode.getAttribute('hideDialog') === 'true') { - completeCode += 'hideLightBox(true);'; + if (this.options.listeners['init']) { + try { + window.listenerContext = this; + if (typeof this.options.listeners['init'] == "string") { + this._evalScripts(this.options.listeners['init']); + } else { + this.options.listeners['init'](); + } + } catch (e) { + Logger.error('Error while evaluating init script for action ' + this.options.name); } - onCompleteFunc = new Function('oForm', completeCode); } - var onCancelNode = XMLUtils.XPathSelectSingleNode(node, 'dialogOnCancel'); - if (onCancelNode && onCancelNode.firstChild) onCancelFunc = new Function('oForm', onCancelNode.firstChild.nodeValue); + } - this.options.callback = (function () { + /** + * Execute the action code + */ + }, { + key: 'apply', + value: function apply() { + if (this.deny) return; + this.manager.publishActionEvent("beforeApply-" + this.options.name); + if (this.options.prepareModal) { var modal = this.manager.uiGetModal(); if (modal) { - modal.showDialogForm('Dialog', dialogFormId, onOpenFunc, onCompleteFunc, onCancelFunc, okButtonOnly, skipButtons); + modal.prepareHeader(this.options.title, this.options.src, this.options.icon_class); } - }).bind(this); - this.options.callback(); - this.options.callbackDialogNode = null; - } else if (this.options.callbackDialogNode && this.options.callbackDialogNode.getAttribute('components')) { - var components = XMLUtils.XPathSelectNodes(this.options.callbackDialogNode, 'component'); - this.manager.uiMountComponents(components); - } else if (this.options.callback) { - this.options.callback(); - } - if (this.options.subMenu && arguments[0] && arguments[0][0]) { - this.notify('submenu_active', arguments[0][0]); - } - window.actionArguments = null; - window.actionManager = null; - this.manager.publishActionEvent('afterApply-' + this.options.name); - }; - - /** - * Updates the action status on context change - * @returns void - */ + } + window.actionArguments = []; + window.actionManager = this.manager; + if (arguments[0]) window.actionArguments = arguments[0]; + if (this.options.callbackCode) { + try { + this._evalScripts(this.options.callbackCode); + } catch (e) { + Logger.error(e); + } + } else if (this.options.callbackDialogNode && this.options.callbackDialogNode.getAttribute("dialogOpenForm")) { + var node = this.options.callbackDialogNode; + var dialogFormId = node.getAttribute("dialogOpenForm"); + var okButtonOnly = node.getAttribute("dialogOkButtonOnly") === "true"; + var skipButtons = node.getAttribute("dialogSkipButtons") === "true"; + + var onOpenFunc = null;var onCompleteFunc = null;var onCancelFunc = null; + var onOpenNode = XMLUtils.XPathSelectSingleNode(node, "dialogOnOpen"); + if (onOpenNode && onOpenNode.firstChild) onOpenFunc = new Function("oForm", onOpenNode.firstChild.nodeValue); + var onCompleteNode = XMLUtils.XPathSelectSingleNode(node, "dialogOnComplete"); + if (onCompleteNode && onCompleteNode.firstChild) { + var completeCode = onCompleteNode.firstChild.nodeValue; + if (onCompleteNode.getAttribute("hideDialog") === "true") { + completeCode += "hideLightBox(true);"; + } + onCompleteFunc = new Function("oForm", completeCode); + } + var onCancelNode = XMLUtils.XPathSelectSingleNode(node, "dialogOnCancel"); + if (onCancelNode && onCancelNode.firstChild) onCancelFunc = new Function("oForm", onCancelNode.firstChild.nodeValue); - Action.prototype.fireContextChange = function fireContextChange() { - if (arguments.length < 3) return; - var usersEnabled = arguments[0]; - var crtUser = arguments[1]; - - var crtIsRecycle = false; - var crtInZip = false; - var crtIsRoot = false; - var crtAjxpMime = ''; - var crtIsReadOnly = false; - - var crtNode = arguments[2]; - if (crtNode) { - crtIsRecycle = crtNode.getAjxpMime() == 'ajxp_recycle'; - crtInZip = crtNode.hasAjxpMimeInBranch('ajxp_browsable_archive'); - crtIsRoot = crtNode.isRoot(); - crtAjxpMime = crtNode.getAjxpMime(); - crtIsReadOnly = crtNode.hasMetadataInBranch('ajxp_readonly', 'true'); - } + this.options.callback = (function () { + var modal = this.manager.uiGetModal(); + if (modal) { + modal.showDialogForm('Dialog', dialogFormId, onOpenFunc, onCompleteFunc, onCancelFunc, okButtonOnly, skipButtons); + } + }).bind(this); + this.options.callback(); + this.options.callbackDialogNode = null; + } else if (this.options.callbackDialogNode && this.options.callbackDialogNode.getAttribute("components")) { + var components = XMLUtils.XPathSelectNodes(this.options.callbackDialogNode, "component"); + this.manager.uiMountComponents(components); + } else if (this.options.callback) { + this.options.callback(); + } + if (this.options.subMenu && arguments[0] && arguments[0][0]) { + this.notify("submenu_active", arguments[0][0]); + } + window.actionArguments = null; + window.actionManager = null; + this.manager.publishActionEvent("afterApply-" + this.options.name); + } + + /** + * Updates the action status on context change + * @returns void + */ + }, { + key: 'fireContextChange', + value: function fireContextChange() { + if (arguments.length < 3) return; + var usersEnabled = arguments[0]; + var crtUser = arguments[1]; + + var crtIsRecycle = false; + var crtInZip = false; + var crtIsRoot = false; + var crtAjxpMime = ''; + var crtIsReadOnly = false; + + var crtNode = arguments[2]; + if (crtNode) { + crtIsRecycle = crtNode.getAjxpMime() == "ajxp_recycle"; + crtInZip = crtNode.hasAjxpMimeInBranch("ajxp_browsable_archive"); + crtIsRoot = crtNode.isRoot(); + crtAjxpMime = crtNode.getAjxpMime(); + crtIsReadOnly = crtNode.hasMetadataInBranch("ajxp_readonly", "true"); + } - if (this.options.listeners['contextChange']) { - window.listenerContext = this; - try { - this._evalScripts(this.options.listeners['contextChange']); - } catch (e) { - Logger.error('Error while evaluating script for contextChange event - action ' + this.options.name); + if (this.options.listeners["contextChange"]) { + window.listenerContext = this; + try { + this._evalScripts(this.options.listeners["contextChange"]); + } catch (e) { + Logger.error("Error while evaluating script for contextChange event - action " + this.options.name); + } } - } - var rightsContext = this.rightsContext; - if (!rightsContext.noUser && !usersEnabled) { - return this.hideForContext(); - } - if (rightsContext.userLogged == 'only' && crtUser == null || rightsContext.guestLogged && rightsContext.guestLogged == 'hidden' && crtUser != null && crtUser.id == 'guest') { - return this.hideForContext(); - } - if (rightsContext.userLogged == 'hidden' && crtUser != null && !(crtUser.id == 'guest' && rightsContext.guestLogged && rightsContext.guestLogged == 'show')) { - return this.hideForContext(); - } - if (rightsContext.adminOnly && (crtUser == null || !crtUser.isAdmin)) { - return this.hideForContext(); - } - if (rightsContext.read && crtUser != null && !crtUser.canRead()) { - return this.hideForContext(); - } - if (rightsContext.write && crtUser != null && !crtUser.canWrite()) { - return this.hideForContext(); - } - if (rightsContext.write && crtIsReadOnly) { - return this.hideForContext(); - } - if (this.context.allowedMimes.length) { - if (this.context.allowedMimes.indexOf('*') == -1 && this.context.allowedMimes.indexOf(crtAjxpMime) == -1) { + var rightsContext = this.rightsContext; + if (!rightsContext.noUser && !usersEnabled) { return this.hideForContext(); } - if (this.context.allowedMimes.indexOf('^' + crtAjxpMime) != -1) { + if (rightsContext.userLogged == 'only' && crtUser == null || rightsContext.guestLogged && rightsContext.guestLogged == 'hidden' && crtUser != null && crtUser.id == 'guest') { return this.hideForContext(); } - } - if (this.context.recycle) { - if (this.context.recycle == 'only' && !crtIsRecycle) { + if (rightsContext.userLogged == 'hidden' && crtUser != null && !(crtUser.id == 'guest' && rightsContext.guestLogged && rightsContext.guestLogged == 'show')) { return this.hideForContext(); } - if (this.context.recycle == 'hidden' && crtIsRecycle) { + if (rightsContext.adminOnly && (crtUser == null || !crtUser.isAdmin)) { return this.hideForContext(); } + if (rightsContext.read && crtUser != null && !crtUser.canRead()) { + return this.hideForContext(); + } + if (rightsContext.write && crtUser != null && !crtUser.canWrite()) { + return this.hideForContext(); + } + if (rightsContext.write && crtIsReadOnly) { + return this.hideForContext(); + } + if (this.context.allowedMimes.length) { + if (this.context.allowedMimes.indexOf("*") == -1 && this.context.allowedMimes.indexOf(crtAjxpMime) == -1) { + return this.hideForContext(); + } + if (this.context.allowedMimes.indexOf("^" + crtAjxpMime) != -1) { + return this.hideForContext(); + } + } + if (this.context.recycle) { + if (this.context.recycle == 'only' && !crtIsRecycle) { + return this.hideForContext(); + } + if (this.context.recycle == 'hidden' && crtIsRecycle) { + return this.hideForContext(); + } + } + if (!this.context.inZip && crtInZip) { + return this.hideForContext(); + } + if (!this.context.root && crtIsRoot) { + return this.hideForContext(); + } + this.showForContext(); } - if (!this.context.inZip && crtInZip) { - return this.hideForContext(); - } - if (!this.context.root && crtIsRoot) { - return this.hideForContext(); - } - this.showForContext(); - }; - - /** - * Upates the action status on selection change - */ - Action.prototype.fireSelectionChange = function fireSelectionChange() { - if (this.options.listeners['selectionChange']) { - window.listenerContext = this; - try { - this._evalScripts(this.options.listeners['selectionChange']); - } catch (e) { - Logger.error('Error while evaluating script for selectionChange event - action ' + this.options.name); + /** + * Upates the action status on selection change + */ + }, { + key: 'fireSelectionChange', + value: function fireSelectionChange() { + if (this.options.listeners["selectionChange"]) { + window.listenerContext = this; + try { + this._evalScripts(this.options.listeners["selectionChange"]); + } catch (e) { + Logger.error("Error while evaluating script for selectionChange event - action " + this.options.name); + } } - } - if (this.options.activeCondition) { - try { - var result = this.options.activeCondition(); - if (result === false) this.disable();else if (result === true) this.enable(); - } catch (e) { - Logger.error('Error while evaluating activeCondition() script for action ' + this.options.name); + if (this.options.activeCondition) { + try { + var result = this.options.activeCondition(); + if (result === false) this.disable();else if (result === true) this.enable(); + } catch (e) { + Logger.error("Error while evaluating activeCondition() script for action " + this.options.name); + } } - } - if (this.contextHidden || !this.context.selection) { - return; - } - var userSelection = arguments[0]; - var hasRoot = false; - if (userSelection != null) { - hasRoot = userSelection.selectionHasRootNode(); - var bUnique = userSelection.isUnique(); - var bFile = userSelection.hasFile(); - var bDir = userSelection.hasDir(); - var bRecycle = userSelection.isRecycle(); - } - var selectionContext = this.selectionContext; - if (selectionContext.allowedMimes.length) { - if (selectionContext.behaviour == 'hidden') this.hide();else this.disable(); - } - if (selectionContext.evalMetadata && userSelection && userSelection.isUnique()) { - var result = this._evalScripts(selectionContext.evalMetadata, userSelection.getUniqueNode().getMetadata()); - if (!result) { - if (selectionContext.behaviour == 'hidden') this.hide();else this.disable(); + if (this.contextHidden || !this.context.selection) { return; } - } - if (!selectionContext.enableRoot && hasRoot) { - return this.disable(); - } - if (selectionContext.unique && !bUnique) { - return this.disable(); - } - if (selectionContext.multipleOnly && bUnique) { - return this.disable(); - } - if ((selectionContext.file || selectionContext.dir) && !bFile && !bDir) { - return this.disable(); - } - if (selectionContext.dir && !selectionContext.file && bFile || !selectionContext.dir && selectionContext.file && bDir) { - return this.disable(); - } - if (!selectionContext.recycle && bRecycle) { - return this.disable(); - } - if (this.rightsContext.write && userSelection.hasReadOnly()) { - return this.disable(); - } - if (selectionContext.allowedMimes.length && userSelection && selectionContext.allowedMimes.indexOf('*') == -1 && !userSelection.hasMime(selectionContext.allowedMimes)) { - if (selectionContext.behaviour == 'hidden') return this.hide();else return this.disable(); - } - if (selectionContext.allowedMimes.length && userSelection && selectionContext.allowedMimes.indexOf('^') !== -1) { - var forbiddenValueFound = false; - selectionContext.allowedMimes.forEach(function (m) { - if (m.indexOf('^') == -1) return; - if (userSelection.hasMime([m.replace('^', '')])) { - forbiddenValueFound = true; - //throw $break; + var userSelection = arguments[0]; + var hasRoot = false; + if (userSelection != null) { + hasRoot = userSelection.selectionHasRootNode(); + var bUnique = userSelection.isUnique(); + var bFile = userSelection.hasFile(); + var bDir = userSelection.hasDir(); + var bRecycle = userSelection.isRecycle(); + } + var selectionContext = this.selectionContext; + if (selectionContext.allowedMimes.length) { + if (selectionContext.behaviour == 'hidden') this.hide();else this.disable(); + } + if (selectionContext.evalMetadata && userSelection && userSelection.isUnique()) { + var result = this._evalScripts(selectionContext.evalMetadata, userSelection.getUniqueNode().getMetadata()); + if (!result) { + if (selectionContext.behaviour == 'hidden') this.hide();else this.disable(); + return; } - }); - if (forbiddenValueFound) { + } + if (!selectionContext.enableRoot && hasRoot) { + return this.disable(); + } + if (selectionContext.unique && !bUnique) { + return this.disable(); + } + if (selectionContext.multipleOnly && bUnique) { + return this.disable(); + } + if ((selectionContext.file || selectionContext.dir) && !bFile && !bDir) { + return this.disable(); + } + if (selectionContext.dir && !selectionContext.file && bFile || !selectionContext.dir && selectionContext.file && bDir) { + return this.disable(); + } + if (!selectionContext.recycle && bRecycle) { + return this.disable(); + } + if (this.rightsContext.write && userSelection.hasReadOnly()) { + return this.disable(); + } + if (selectionContext.allowedMimes.length && userSelection && selectionContext.allowedMimes.indexOf('*') == -1 && !userSelection.hasMime(selectionContext.allowedMimes)) { if (selectionContext.behaviour == 'hidden') return this.hide();else return this.disable(); } - } - this.show(); - this.enable(); - }; - - /** - * Parses an XML fragment to configure this action - * @param xmlNode Node XML Fragment describing the action - */ - - Action.prototype.createFromXML = function createFromXML(xmlNode) { - - this.options.name = xmlNode.getAttribute('name'); - for (var i = 0; i < xmlNode.childNodes.length; i++) { - var node = xmlNode.childNodes[i]; - var defaultAttributes = { - dir: 'dirDefault', - file: 'fileDefault', - dragndrop: 'dragndropDefault', - ctrldragndrop: 'ctrlDragndropDefault', - expire: 'expireDefault' - }; - for (var key in defaultAttributes) { - if (!defaultAttributes.hasOwnProperty(key)) continue; - var value = defaultAttributes[key]; - if (xmlNode.getAttribute(value) && xmlNode.getAttribute(value) == 'true') { - if (!this.defaults) this.defaults = {}; - this.defaults[key] = true; + if (selectionContext.allowedMimes.length && userSelection && selectionContext.allowedMimes.indexOf("^") !== -1) { + var forbiddenValueFound = false; + selectionContext.allowedMimes.forEach(function (m) { + if (m.indexOf("^") == -1) return; + if (userSelection.hasMime([m.replace("^", "")])) { + forbiddenValueFound = true; + //throw $break; + } + }); + if (forbiddenValueFound) { + if (selectionContext.behaviour == 'hidden') return this.hide();else return this.disable(); } } - var j; - if (node.nodeName == 'processing') { - var clientFormData = {}; - for (j = 0; j < node.childNodes.length; j++) { - var processNode = node.childNodes[j]; - if (processNode.nodeName == 'clientForm') { - // TODO: Filtering by theme - if (!processNode.getAttribute('theme') || pydio.Parameters.get('theme') == processNode.getAttribute('theme')) { - clientFormData.formId = processNode.getAttribute('id'); - clientFormData.formCode = processNode.firstChild.nodeValue; - } - } else if (processNode.nodeName == 'clientCallback') { - if (processNode.getAttribute('prepareModal') && processNode.getAttribute('prepareModal') == 'true') { - this.options.prepareModal = true; + this.show(); + this.enable(); + } + + /** + * Parses an XML fragment to configure this action + * @param xmlNode Node XML Fragment describing the action + */ + }, { + key: 'createFromXML', + value: function createFromXML(xmlNode) { + + this.options.name = xmlNode.getAttribute('name'); + for (var i = 0; i < xmlNode.childNodes.length; i++) { + var node = xmlNode.childNodes[i]; + var defaultAttributes = { + dir: "dirDefault", + file: "fileDefault", + dragndrop: "dragndropDefault", + ctrldragndrop: "ctrlDragndropDefault", + expire: "expireDefault" + }; + for (var key in defaultAttributes) { + if (!defaultAttributes.hasOwnProperty(key)) continue; + var value = defaultAttributes[key]; + if (xmlNode.getAttribute(value) && xmlNode.getAttribute(value) == "true") { + if (!this.defaults) this.defaults = {}; + this.defaults[key] = true; + } + } + var j; + if (node.nodeName == "processing") { + var clientFormData = {}; + for (j = 0; j < node.childNodes.length; j++) { + var processNode = node.childNodes[j]; + if (processNode.nodeName == "clientForm") { + // TODO: Filtering by theme + if (!processNode.getAttribute("theme") || pydio.Parameters.get('theme') == processNode.getAttribute("theme")) { + clientFormData.formId = processNode.getAttribute("id"); + clientFormData.formCode = processNode.firstChild.nodeValue; + } + } else if (processNode.nodeName == "clientCallback") { + if (processNode.getAttribute('prepareModal') && processNode.getAttribute('prepareModal') == "true") { + this.options.prepareModal = true; + } + if (processNode.getAttribute('dialogOpenForm') || processNode.getAttribute("components")) { + this.options.callbackDialogNode = processNode; + } else if (processNode.firstChild) { + this.options.callbackCode = processNode.firstChild.nodeValue.trim(); + } + } else if (processNode.nodeName == "clientListener" && processNode.firstChild) { + this.options.listeners[processNode.getAttribute('name')] = processNode.firstChild.nodeValue.trim(); + } else if (processNode.nodeName == "activeCondition" && processNode.firstChild) { + this.options.activeCondition = new Function(processNode.firstChild.nodeValue.trim()); } - if (processNode.getAttribute('dialogOpenForm') || processNode.getAttribute('components')) { - this.options.callbackDialogNode = processNode; - } else if (processNode.firstChild) { - this.options.callbackCode = processNode.firstChild.nodeValue.trim(); + } + if (clientFormData.formId) { + this.options.formId = clientFormData.formId; + this.options.formCode = clientFormData.formCode; + if (this.options.formCode && this.options.formId) { + this.manager.uiInsertForm(this.options.formId, this.options.formCode); } - } else if (processNode.nodeName == 'clientListener' && processNode.firstChild) { - this.options.listeners[processNode.getAttribute('name')] = processNode.firstChild.nodeValue.trim(); - } else if (processNode.nodeName == 'activeCondition' && processNode.firstChild) { - this.options.activeCondition = new Function(processNode.firstChild.nodeValue.trim()); } - } - if (clientFormData.formId) { - this.options.formId = clientFormData.formId; - this.options.formCode = clientFormData.formCode; - if (this.options.formCode && this.options.formId) { - this.manager.uiInsertForm(this.options.formId, this.options.formCode); + } else if (node.nodeName == "gui") { + this.options.text_id = node.getAttribute('text'); + this.options.title_id = node.getAttribute('title'); + this.options.text = this.manager.getMessage(node.getAttribute('text')) || 'not_found'; + this.options.title = this.manager.getMessage(node.getAttribute('title')) || 'not_found'; + this.options.src = node.getAttribute('src'); + this.options.icon_class = node.getAttribute('iconClass'); + if (node.getAttribute('hasAccessKey') && node.getAttribute('hasAccessKey') == "true") { + this.options.accessKey = node.getAttribute('accessKey'); + this.options.hasAccessKey = true; } - } - } else if (node.nodeName == 'gui') { - this.options.text_id = node.getAttribute('text'); - this.options.title_id = node.getAttribute('title'); - this.options.text = this.manager.getMessage(node.getAttribute('text')) || 'not_found'; - this.options.title = this.manager.getMessage(node.getAttribute('title')) || 'not_found'; - this.options.src = node.getAttribute('src'); - this.options.icon_class = node.getAttribute('iconClass'); - if (node.getAttribute('hasAccessKey') && node.getAttribute('hasAccessKey') == 'true') { - this.options.accessKey = node.getAttribute('accessKey'); - this.options.hasAccessKey = true; - } - if (node.getAttribute('specialAccessKey')) { - this.options.specialAccessKey = node.getAttribute('specialAccessKey'); - } - for (j = 0; j < node.childNodes.length; j++) { - if (node.childNodes[j].nodeName == 'context') { - this.attributesToObject(this.context, node.childNodes[j]); - if (this.context.ajxpWidgets) { - this.context.ajxpWidgets = this.context.ajxpWidgets.split(','); - } else { - this.context.ajxpWidgets = []; + if (node.getAttribute('specialAccessKey')) { + this.options.specialAccessKey = node.getAttribute('specialAccessKey'); + } + for (j = 0; j < node.childNodes.length; j++) { + if (node.childNodes[j].nodeName == "context") { + this.attributesToObject(this.context, node.childNodes[j]); + if (this.context.ajxpWidgets) { + this.context.ajxpWidgets = this.context.ajxpWidgets.split(','); + } else { + this.context.ajxpWidgets = []; + } + // Backward compatibility + if (this.context.infoPanel) this.context.ajxpWidgets.push('InfoPanel'); + if (this.context.actionBar) this.context.ajxpWidgets.push('ActionsToolbar'); + } else if (node.childNodes[j].nodeName == "selectionContext") { + this.attributesToObject(this.selectionContext, node.childNodes[j]); } - // Backward compatibility - if (this.context.infoPanel) this.context.ajxpWidgets.push('InfoPanel'); - if (this.context.actionBar) this.context.ajxpWidgets.push('ActionsToolbar'); - } else if (node.childNodes[j].nodeName == 'selectionContext') { - this.attributesToObject(this.selectionContext, node.childNodes[j]); } - } - } else if (node.nodeName == 'rightsContext') { - this.attributesToObject(this.rightsContext, node); - } else if (node.nodeName == 'subMenu') { - this.options.subMenu = true; - if (node.getAttribute('updateImageOnSelect') && node.getAttribute('updateImageOnSelect') == 'true') { - this.options.subMenuUpdateImage = true; - } - if (node.getAttribute('updateTitleOnSelect') && node.getAttribute('updateTitleOnSelect') == 'true') { - this.options.subMenuUpdateTitle = true; - } - for (j = 0; j < node.childNodes.length; j++) { - if (node.childNodes[j].nodeName == 'staticItems' || node.childNodes[j].nodeName == 'dynamicItems') { - this.subMenuItems[node.childNodes[j].nodeName] = []; - for (var k = 0; k < node.childNodes[j].childNodes.length; k++) { - if (node.childNodes[j].childNodes[k].nodeName.startsWith('item')) { - var item = {}; - for (var z = 0; z < node.childNodes[j].childNodes[k].attributes.length; z++) { - var attribute = node.childNodes[j].childNodes[k].attributes[z]; - item[attribute.nodeName] = attribute.value; + } else if (node.nodeName == "rightsContext") { + this.attributesToObject(this.rightsContext, node); + } else if (node.nodeName == "subMenu") { + this.options.subMenu = true; + if (node.getAttribute("updateImageOnSelect") && node.getAttribute("updateImageOnSelect") == "true") { + this.options.subMenuUpdateImage = true; + } + if (node.getAttribute("updateTitleOnSelect") && node.getAttribute("updateTitleOnSelect") == "true") { + this.options.subMenuUpdateTitle = true; + } + for (j = 0; j < node.childNodes.length; j++) { + if (node.childNodes[j].nodeName == "staticItems" || node.childNodes[j].nodeName == "dynamicItems") { + this.subMenuItems[node.childNodes[j].nodeName] = []; + for (var k = 0; k < node.childNodes[j].childNodes.length; k++) { + if (node.childNodes[j].childNodes[k].nodeName.startsWith("item")) { + var item = {}; + for (var z = 0; z < node.childNodes[j].childNodes[k].attributes.length; z++) { + var attribute = node.childNodes[j].childNodes[k].attributes[z]; + item[attribute.nodeName] = attribute.value; + } + this.subMenuItems[node.childNodes[j].nodeName].push(item); } - this.subMenuItems[node.childNodes[j].nodeName].push(item); } + } else if (node.childNodes[j].nodeName == "dynamicBuilder") { + this.subMenuItems.dynamicBuilderCode = node.childNodes[j].firstChild.nodeValue; } - } else if (node.childNodes[j].nodeName == 'dynamicBuilder') { - this.subMenuItems.dynamicBuilderCode = node.childNodes[j].firstChild.nodeValue; } } } + if (!this.options.hasAccessKey) return; + if (this.options.accessKey == '' || !this.manager.getMessage(this.options.accessKey) || this.options.text.indexOf(this.manager.getMessage(this.options.accessKey)) == -1) { + this.options.accessKey = this.options.text.charAt(0); + } else { + this.options.accessKey = this.manager.getMessage(this.options.accessKey); + } } - if (!this.options.hasAccessKey) return; - if (this.options.accessKey == '' || !this.manager.getMessage(this.options.accessKey) || this.options.text.indexOf(this.manager.getMessage(this.options.accessKey)) == -1) { - this.options.accessKey = this.options.text.charAt(0); - } else { - this.options.accessKey = this.manager.getMessage(this.options.accessKey); - } - }; - - /** - * Creates the submenu items - */ - - Action.prototype.buildSubmenuStaticItems = function buildSubmenuStaticItems() { - var menuItems = []; - if (this.subMenuItems.staticItems) { - this.subMenuItems.staticItems.forEach(function (item) { - var itemText = this.manager.getMessage(item.text); - if (item.hasAccessKey && (item.hasAccessKey == 'true' || item.hasAccessKey === true) && this.manager.getMessage(item.accessKey)) { - itemText = this.getKeyedText(this.manager.getMessage(item.text), true, this.manager.getMessage(item.accessKey)); - if (!this.subMenuItems.accessKeys) this.subMenuItems.accessKeys = []; - this.manager.registerKey(this.manager.getMessage(item.accessKey), this.options.name, item.command); - } - menuItems.push({ - name: itemText, - alt: this.manager.getMessage(item.title), - image_unresolved: item.src, - icon_class: item.icon_class, - isDefault: item.isDefault ? true : false, - callback: (function () { - this.apply([item]); - }).bind(this) - }); - }, this); - } - this.subMenuItems.staticOptions = menuItems; - }; - /** - * Caches some data for dynamically built menus - */ - - Action.prototype.prepareSubmenuDynamicBuilder = function prepareSubmenuDynamicBuilder() { - this.subMenuItems.dynamicBuilder = (function (protoMenu) { - var menuItems; - setTimeout((function () { - if (this.subMenuItems.dynamicBuilderCode) { - window.builderContext = this; - window.builderProtoMenu = protoMenu; - this._evalScripts(this.subMenuItems.dynamicBuilderCode); - menuItems = this.builderMenuItems || []; - } else { - menuItems = []; - this.subMenuItems.dynamicItems.forEach(function (item) { - if (item.separator) { - menuItems.push(item); - return; - } - var action = this.manager.actions.get(item['actionId']); - if (action.deny) return; - var itemData = { - name: action.getKeyedText(), - alt: action.options.title, - icon_class: action.options.icon_class, - image_unresolved: action.options.src, - callback: (function () { - this.apply(); - }).bind(action) - }; - if (action.options.subMenu) { - itemData.subMenu = []; - if (action.subMenuItems.staticOptions) { - itemData.subMenu = action.subMenuItems.staticOptions; + /** + * Creates the submenu items + */ + }, { + key: 'buildSubmenuStaticItems', + value: function buildSubmenuStaticItems() { + var menuItems = []; + if (this.subMenuItems.staticItems) { + this.subMenuItems.staticItems.forEach(function (item) { + var itemText = this.manager.getMessage(item.text); + if (item.hasAccessKey && (item.hasAccessKey == 'true' || item.hasAccessKey === true) && this.manager.getMessage(item.accessKey)) { + itemText = this.getKeyedText(this.manager.getMessage(item.text), true, this.manager.getMessage(item.accessKey)); + if (!this.subMenuItems.accessKeys) this.subMenuItems.accessKeys = []; + this.manager.registerKey(this.manager.getMessage(item.accessKey), this.options.name, item.command); + } + menuItems.push({ + name: itemText, + alt: this.manager.getMessage(item.title), + image_unresolved: item.src, + icon_class: item.icon_class, + isDefault: item.isDefault ? true : false, + callback: (function () { + this.apply([item]); + }).bind(this) + }); + }, this); + } + this.subMenuItems.staticOptions = menuItems; + } + + /** + * Caches some data for dynamically built menus + */ + }, { + key: 'prepareSubmenuDynamicBuilder', + value: function prepareSubmenuDynamicBuilder() { + this.subMenuItems.dynamicBuilder = (function (protoMenu) { + var menuItems; + setTimeout((function () { + if (this.subMenuItems.dynamicBuilderCode) { + window.builderContext = this; + window.builderProtoMenu = protoMenu; + this._evalScripts(this.subMenuItems.dynamicBuilderCode); + menuItems = this.builderMenuItems || []; + } else { + menuItems = []; + this.subMenuItems.dynamicItems.forEach(function (item) { + if (item.separator) { + menuItems.push(item); + return; } - if (action.subMenuItems.dynamicBuilder) { - itemData.subMenuBeforeShow = action.subMenuItems.dynamicBuilder; + var action = this.manager.actions.get(item['actionId']); + if (action.deny) return; + var itemData = { + name: action.getKeyedText(), + alt: action.options.title, + icon_class: action.options.icon_class, + image_unresolved: action.options.src, + callback: (function () { + this.apply(); + }).bind(action) + }; + if (action.options.subMenu) { + itemData.subMenu = []; + if (action.subMenuItems.staticOptions) { + itemData.subMenu = action.subMenuItems.staticOptions; + } + if (action.subMenuItems.dynamicBuilder) { + itemData.subMenuBeforeShow = action.subMenuItems.dynamicBuilder; + } } - } - menuItems.push(itemData); - }, this); - } - protoMenu.options.menuItems = menuItems; - protoMenu.refreshList(); - }).bind(this), 0); - }).bind(this); - }; - - /** - * Refresh icon image source - * @param newSrc String The image source. Can reference an image library - * @param iconClass String Optional class to replace image - */ - - Action.prototype.setIconSrc = function setIconSrc(newSrc, iconClass) { - this.options.src = newSrc; - var previousIconClass = this.options.icon_class; - this.notify('update_icon', { new_src: newSrc, new_class: iconClass, previous_class: previousIconClass }); - if (iconClass) { - this.options.icon_class = iconClass; + menuItems.push(itemData); + }, this); + } + protoMenu.options.menuItems = menuItems; + protoMenu.refreshList(); + }).bind(this), 0); + }).bind(this); } - }; - /** - * Refresh the action label - * @param newLabel String the new label - * @param newTitle String the new tooltip - */ - - Action.prototype.setLabel = function setLabel(newLabel, newTitle) { - this.options.text = this.manager.getMessage(newLabel); - this.notify('update_label', this.getKeyedText()); - if (newTitle) { - this.options.title = this.manager.getMessage(newTitle); - this.notify('update_title', this.options.title); + /** + * Refresh icon image source + * @param newSrc String The image source. Can reference an image library + * @param iconClass String Optional class to replace image + */ + }, { + key: 'setIconSrc', + value: function setIconSrc(newSrc, iconClass) { + this.options.src = newSrc; + var previousIconClass = this.options.icon_class; + this.notify("update_icon", { new_src: newSrc, new_class: iconClass, previous_class: previousIconClass }); + if (iconClass) { + this.options.icon_class = iconClass; + } } - }; - - Action.prototype.refreshInstances = function refreshInstances() {}; - - /** - * Grab its label from the i18n - */ - Action.prototype.refreshFromI18NHash = function refreshFromI18NHash() { - this.setLabel(this.options.text_id, this.options.title_id); - }; - - /** - * Return data necessary to build InfoPanel - * @returns Object - */ - - Action.prototype.toInfoPanel = function toInfoPanel() { - return this.options; - }; - - /** - * Return necessary data to build contextual menu - * @returns Object - */ - - Action.prototype.toContextMenu = function toContextMenu() { - return this.options; - }; - - /** - * Changes show/hide state - */ - - Action.prototype.hideForContext = function hideForContext() { - this.hide(); - this.contextHidden = true; - }; - - /** - * Changes show/hide state - */ - - Action.prototype.showForContext = function showForContext() { - this.contextHidden = false; - this.show(); - if (this.selectionContext) { - this.fireSelectionChange(); + /** + * Refresh the action label + * @param newLabel String the new label + * @param newTitle String the new tooltip + */ + }, { + key: 'setLabel', + value: function setLabel(newLabel, newTitle) { + this.options.text = this.manager.getMessage(newLabel); + this.notify("update_label", this.getKeyedText()); + if (newTitle) { + this.options.title = this.manager.getMessage(newTitle); + this.notify("update_title", this.options.title); + } } - }; - - /** - * Changes show/hide state - * Notifies "hide" Event - */ - - Action.prototype.hide = function hide() { - this.deny = true; - this.notify('hide'); - }; - - /** - * Changes show/hide state - * Notifies "show" Event - */ - - Action.prototype.show = function show() { - this.deny = false; - this.notify('show'); - }; - - /** - * Changes enable/disable state - * Notifies "disable" Event - */ - - Action.prototype.disable = function disable() { - this.deny = true; - this.notify('disable'); - }; - - /** - * Changes enable/disable state - * Notifies "enable" Event + }, { + key: 'refreshInstances', + value: function refreshInstances() {} + /* + TODO : UI Stuff, should be bound + */ + /* + $$('#action_instance_'+this.options.name).each(function(instance){ + // Check img + var img; + if(instance.firstChild.nodeType == Node.ELEMENT_NODE && instance.firstChild.nodeName.toLowerCase()=="img"){ + img = instance.firstChild.cloneNode(true); + } + instance.update(this.getKeyedText()); + if(img){ + instance.insert({top:img}); + } + }.bind(this)); */ - Action.prototype.enable = function enable() { - this.deny = false; - this.notify('enable'); - }; - - /** - * To be called when removing - */ - - Action.prototype.remove = function remove() { - this.notify('remove'); - if (this.options.formId) { - this.manager.uiRemoveForm(this.options.formId); + /** + * Grab its label from the i18n + */ + + }, { + key: 'refreshFromI18NHash', + value: function refreshFromI18NHash() { + this.setLabel(this.options.text_id, this.options.title_id); + } + + /** + * Return data necessary to build InfoPanel + * @returns Object + */ + }, { + key: 'toInfoPanel', + value: function toInfoPanel() { + return this.options; + } + + /** + * Return necessary data to build contextual menu + * @returns Object + */ + }, { + key: 'toContextMenu', + value: function toContextMenu() { + return this.options; + } + + /** + * Changes show/hide state + */ + }, { + key: 'hideForContext', + value: function hideForContext() { + this.hide(); + this.contextHidden = true; + } + + /** + * Changes show/hide state + */ + }, { + key: 'showForContext', + value: function showForContext() { + this.contextHidden = false; + this.show(); + if (this.selectionContext) { + this.fireSelectionChange(); + } } - }; - - /** - * Create a text label with access-key underlined. - * @param displayString String the label - * @param hasAccessKey Boolean whether there is an accessKey or not - * @param accessKey String The key to underline - * @returns String - */ - Action.prototype.getKeyedText = function getKeyedText(displayString, hasAccessKey, accessKey) { - if (!displayString) { - displayString = this.options.text; - } - if (!hasAccessKey) { - hasAccessKey = this.options.hasAccessKey; - } - if (!accessKey) { - accessKey = this.options.accessKey; - } - if (!hasAccessKey) return displayString; - var keyPos = displayString.toLowerCase().indexOf(accessKey.toLowerCase()); - if (keyPos == -1) { - return displayString + ' (' + accessKey + ')'; - } - if (displayString.charAt(keyPos) != accessKey) { - // case differ - accessKey = displayString.charAt(keyPos); + /** + * Changes show/hide state + * Notifies "hide" Event + */ + }, { + key: 'hide', + value: function hide() { + this.deny = true; + this.notify('hide'); + } + + /** + * Changes show/hide state + * Notifies "show" Event + */ + }, { + key: 'show', + value: function show() { + this.deny = false; + this.notify('show'); + } + + /** + * Changes enable/disable state + * Notifies "disable" Event + */ + }, { + key: 'disable', + value: function disable() { + this.deny = true; + this.notify('disable'); + } + + /** + * Changes enable/disable state + * Notifies "enable" Event + */ + }, { + key: 'enable', + value: function enable() { + this.deny = false; + this.notify('enable'); + } + + /** + * To be called when removing + */ + }, { + key: 'remove', + value: function remove() { + this.notify("remove"); + if (this.options.formId) { + this.manager.uiRemoveForm(this.options.formId); + } } - var returnString = displayString.substring(0, displayString.indexOf(accessKey)); - returnString += '' + accessKey + ''; - returnString += displayString.substring(displayString.indexOf(accessKey) + 1, displayString.length); - return returnString; - }; - /** - * Utilitary function to transform XML Node attributes into Object mapping keys. - * @param object Object The target object - * @param node Node The source node - */ - - Action.prototype.attributesToObject = function attributesToObject(object, node) { - for (var key in object) { - if (!object.hasOwnProperty(key) || !node.getAttribute(key)) continue; - var value = node.getAttribute(key); - if (value == 'true') value = true;else if (value == 'false') value = false; - if (key == 'allowedMimes') { - if (value && value.split(',').length) { - value = value.split(','); - } else { - value = []; + /** + * Create a text label with access-key underlined. + * @param displayString String the label + * @param hasAccessKey Boolean whether there is an accessKey or not + * @param accessKey String The key to underline + * @returns String + */ + }, { + key: 'getKeyedText', + value: function getKeyedText(displayString, hasAccessKey, accessKey) { + if (!displayString) { + displayString = this.options.text; + } + if (!hasAccessKey) { + hasAccessKey = this.options.hasAccessKey; + } + if (!accessKey) { + accessKey = this.options.accessKey; + } + if (!hasAccessKey) return displayString; + var keyPos = displayString.toLowerCase().indexOf(accessKey.toLowerCase()); + if (keyPos == -1) { + return displayString + ' (' + accessKey + ')'; + } + if (displayString.charAt(keyPos) != accessKey) { + // case differ + accessKey = displayString.charAt(keyPos); + } + var returnString = displayString.substring(0, displayString.indexOf(accessKey)); + returnString += '' + accessKey + ''; + returnString += displayString.substring(displayString.indexOf(accessKey) + 1, displayString.length); + return returnString; + } + + /** + * Utilitary function to transform XML Node attributes into Object mapping keys. + * @param object Object The target object + * @param node Node The source node + */ + }, { + key: 'attributesToObject', + value: function attributesToObject(object, node) { + for (var key in object) { + if (!object.hasOwnProperty(key) || !node.getAttribute(key)) continue; + var value = node.getAttribute(key); + if (value == 'true') value = true;else if (value == 'false') value = false; + if (key == 'allowedMimes') { + if (value && value.split(',').length) { + value = value.split(','); + } else { + value = []; + } } + object[key] = value; } - object[key] = value; } - }; + }]); return Action; })(Observable); - -/* - TODO : UI Stuff, should be bound - */ -/* -$$('#action_instance_'+this.options.name).each(function(instance){ - // Check img - var img; - if(instance.firstChild.nodeType == Node.ELEMENT_NODE && instance.firstChild.nodeName.toLowerCase()=="img"){ - img = instance.firstChild.cloneNode(true); - } - instance.update(this.getKeyedText()); - if(img){ - instance.insert({top:img}); - } -}.bind(this)); -*/ \ No newline at end of file diff --git a/core/src/plugins/gui.ajax/res/js/core/model/AjxpNode.js b/core/src/plugins/gui.ajax/res/js/core/model/AjxpNode.js index e1796a4419..cb265e61eb 100644 --- a/core/src/plugins/gui.ajax/res/js/core/model/AjxpNode.js +++ b/core/src/plugins/gui.ajax/res/js/core/model/AjxpNode.js @@ -1,10 +1,15 @@ 'use strict'; +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +var _get = function get(_x5, _x6, _x7) { var _again = true; _function: while (_again) { var object = _x5, property = _x6, receiver = _x7; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x5 = parent; _x6 = property; _x7 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } -function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } +function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var AjxpNode = (function (_Observable) { + _inherits(AjxpNode, _Observable); /** * @@ -16,17 +21,17 @@ var AjxpNode = (function (_Observable) { */ function AjxpNode(path) { - var isLeaf = arguments[1] === undefined ? false : arguments[1]; - var label = arguments[2] === undefined ? '' : arguments[2]; - var icon = arguments[3] === undefined ? '' : arguments[3]; - var iNodeProvider = arguments[4] === undefined ? null : arguments[4]; + var isLeaf = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; + var label = arguments.length <= 2 || arguments[2] === undefined ? '' : arguments[2]; + var icon = arguments.length <= 3 || arguments[3] === undefined ? '' : arguments[3]; + var iNodeProvider = arguments.length <= 4 || arguments[4] === undefined ? null : arguments[4]; _classCallCheck(this, AjxpNode); - _Observable.call(this); + _get(Object.getPrototypeOf(AjxpNode.prototype), 'constructor', this).call(this); this._path = path; if (this._path && this._path.length && this._path.length > 1) { - if (this._path[this._path.length - 1] == '/') { + if (this._path[this._path.length - 1] == "/") { this._path = this._path.substring(0, this._path.length - 1); } } @@ -43,417 +48,446 @@ var AjxpNode = (function (_Observable) { this._iNodeProvider = iNodeProvider; } - _inherits(AjxpNode, _Observable); - /** * The node is loaded or not * @returns Boolean */ - AjxpNode.prototype.isLoaded = function isLoaded() { - return this._isLoaded; - }; - - /** - * Changes loaded status - * @param bool Boolean - */ - - AjxpNode.prototype.setLoaded = function setLoaded(bool) { - this._isLoaded = bool; - }; + _createClass(AjxpNode, [{ + key: 'isLoaded', + value: function isLoaded() { + return this._isLoaded; + } - /** - * Loads the node using its own provider or the one passed - * @param iAjxpNodeProvider IAjxpNodeProvider Optionnal - */ + /** + * Changes loaded status + * @param bool Boolean + */ + }, { + key: 'setLoaded', + value: function setLoaded(bool) { + this._isLoaded = bool; + } - AjxpNode.prototype.load = function load(iAjxpNodeProvider) { - if (this._isLoading) return; - if (!iAjxpNodeProvider) { - if (this._iNodeProvider) { - iAjxpNodeProvider = this._iNodeProvider; - } else { - iAjxpNodeProvider = new RemoteNodeProvider(); + /** + * Loads the node using its own provider or the one passed + * @param iAjxpNodeProvider IAjxpNodeProvider Optionnal + */ + }, { + key: 'load', + value: function load(iAjxpNodeProvider) { + if (this._isLoading) return; + if (!iAjxpNodeProvider) { + if (this._iNodeProvider) { + iAjxpNodeProvider = this._iNodeProvider; + } else { + iAjxpNodeProvider = new RemoteNodeProvider(); + } } + this._isLoading = true; + this.notify("loading"); + if (this._isLoaded) { + this._isLoading = false; + this.notify("loaded"); + return; + } + iAjxpNodeProvider.loadNode(this, (function (node) { + this._isLoaded = true; + this._isLoading = false; + this.notify("loaded"); + this.notify("first_load"); + }).bind(this)); } - this._isLoading = true; - this.notify('loading'); - if (this._isLoaded) { - this._isLoading = false; - this.notify('loaded'); - return; - } - iAjxpNodeProvider.loadNode(this, (function (node) { - this._isLoaded = true; - this._isLoading = false; - this.notify('loaded'); - this.notify('first_load'); - }).bind(this)); - }; - - /** - * Remove children and reload node - * @param iAjxpNodeProvider IAjxpNodeProvider Optionnal - */ - - AjxpNode.prototype.reload = function reload(iAjxpNodeProvider) { - this._children.forEach(function (child, key) { - child.notify('node_removed'); - child._parentNode = null; - this._children['delete'](key); - this.notify('child_removed', child); - }, this); - this._isLoaded = false; - this.load(iAjxpNodeProvider); - }; - - /** - * Unload child and notify "force_clear" - */ - - AjxpNode.prototype.clear = function clear() { - this._children.forEach(function (child, key) { - child.notify('node_removed'); - child._parentNode = null; - this._children['delete'](key); - this.notify('child_removed', child); - }, this); - this._isLoaded = false; - this.notify('force_clear'); - }; - - /** - * Sets this AjxpNode as being the root parent - */ - - AjxpNode.prototype.setRoot = function setRoot() { - this._isRoot = true; - }; - - /** - * Set the node children as a bunch - * @param ajxpNodes AjxpNodes[] - */ - - AjxpNode.prototype.setChildren = function setChildren(ajxpNodes) { - this._children = new Map(); - ajxpNodes.forEach((function (value) { - this._children.set(value.getPath(), value); - value.setParent(this); - }).bind(this)); - }; - /** - * Get all children as a bunch - * @returns AjxpNode[] - */ - - AjxpNode.prototype.getChildren = function getChildren() { - return this._children; - }; - - AjxpNode.prototype.getFirstChildIfExists = function getFirstChildIfExists() { - if (this._children.size) { - return this._children.values().next().value; + /** + * Remove children and reload node + * @param iAjxpNodeProvider IAjxpNodeProvider Optionnal + */ + }, { + key: 'reload', + value: function reload(iAjxpNodeProvider) { + this._children.forEach(function (child, key) { + child.notify("node_removed"); + child._parentNode = null; + this._children['delete'](key); + this.notify("child_removed", child); + }, this); + this._isLoaded = false; + this.load(iAjxpNodeProvider); } - return null; - }; - - /** - * Adds a child to children - * @param ajxpNode AjxpNode The child - */ - AjxpNode.prototype.addChild = function addChild(ajxpNode) { - ajxpNode.setParent(this); - if (this._iNodeProvider) ajxpNode._iNodeProvider = this._iNodeProvider; - var existingNode = this.findChildByPath(ajxpNode.getPath()); - if (existingNode && !(existingNode instanceof String)) { - existingNode.replaceBy(ajxpNode, 'override'); - } else { - this._children.set(ajxpNode.getPath(), ajxpNode); - this.notify('child_added', ajxpNode.getPath()); + /** + * Unload child and notify "force_clear" + */ + }, { + key: 'clear', + value: function clear() { + this._children.forEach(function (child, key) { + child.notify("node_removed"); + child._parentNode = null; + this._children['delete'](key); + this.notify("child_removed", child); + }, this); + this._isLoaded = false; + this.notify("force_clear"); } - }; - - /** - * Removes the child from the children - * @param ajxpNode AjxpNode - */ - AjxpNode.prototype.removeChild = function removeChild(ajxpNode) { - var removePath = ajxpNode.getPath(); - ajxpNode.notify('node_removed'); - ajxpNode._parentNode = null; - this._children['delete'](ajxpNode.getPath()); - this.notify('child_removed', removePath); - }; - - /** - * Replaces the current node by a new one. Copy all properties deeply - * @param ajxpNode AjxpNode - * @param metaMerge - */ - - AjxpNode.prototype.replaceBy = function replaceBy(ajxpNode, metaMerge) { - this._isLeaf = ajxpNode._isLeaf; - if (ajxpNode.getPath() && this._path != ajxpNode.getPath()) { - var originalPath = this._path; - if (this.getParent()) { - var parentChildrenIndex = this.getParent()._children; - parentChildrenIndex.set(ajxpNode.getPath(), this); - parentChildrenIndex['delete'](originalPath); - } - this._path = ajxpNode.getPath(); - var pathChanged = true; + /** + * Sets this AjxpNode as being the root parent + */ + }, { + key: 'setRoot', + value: function setRoot() { + this._isRoot = true; } - if (ajxpNode._label) { - this._label = ajxpNode._label; + + /** + * Set the node children as a bunch + * @param ajxpNodes AjxpNodes[] + */ + }, { + key: 'setChildren', + value: function setChildren(ajxpNodes) { + this._children = new Map(); + ajxpNodes.forEach((function (value) { + this._children.set(value.getPath(), value); + value.setParent(this); + }).bind(this)); } - if (ajxpNode._icon) { - this._icon = ajxpNode._icon; + + /** + * Get all children as a bunch + * @returns AjxpNode[] + */ + }, { + key: 'getChildren', + value: function getChildren() { + return this._children; } - if (ajxpNode._iNodeProvider) { - this._iNodeProvider = ajxpNode._iNodeProvider; + }, { + key: 'getFirstChildIfExists', + value: function getFirstChildIfExists() { + if (this._children.size) { + return this._children.values().next().value; + } + return null; } - //this._isRoot = ajxpNode._isRoot; - this._isLoaded = ajxpNode._isLoaded; - this.fake = ajxpNode.fake; - var meta = ajxpNode.getMetadata(); - if (metaMerge == 'override') this._metadata = new Map(); - meta.forEach((function (value, key) { - if (metaMerge == 'override') { - this._metadata.set(key, value); + + /** + * Adds a child to children + * @param ajxpNode AjxpNode The child + */ + }, { + key: 'addChild', + value: function addChild(ajxpNode) { + ajxpNode.setParent(this); + if (this._iNodeProvider) ajxpNode._iNodeProvider = this._iNodeProvider; + var existingNode = this.findChildByPath(ajxpNode.getPath()); + if (existingNode && !(existingNode instanceof String)) { + existingNode.replaceBy(ajxpNode, "override"); } else { - if (this._metadata.has(key) && value === '') { - return; - } - this._metadata.set(key, value); + this._children.set(ajxpNode.getPath(), ajxpNode); + this.notify("child_added", ajxpNode.getPath()); } - }).bind(this)); - if (pathChanged && !this._isLeaf && this.getChildren().size) { - window.setTimeout((function () { - this.reload(this._iNodeProvider); - }).bind(this), 100); - return; } - ajxpNode.getChildren().forEach((function (child) { - this.addChild(child); - }).bind(this)); - this.notify('node_replaced', this); - }; - - /** - * Finds a child node by its path - * @param path String - * @returns AjxpNode - */ - - AjxpNode.prototype.findChildByPath = function findChildByPath(path) { - return this._children.get(path); - }; - - /** - * Sets the metadata as a bunch - * @param data Map A Map - */ - - AjxpNode.prototype.setMetadata = function setMetadata(data) { - this._metadata = data; - }; - - /** - * Gets the metadat - * @returns Map - */ - - AjxpNode.prototype.getMetadata = function getMetadata() { - return this._metadata; - }; - - /** - * Is this node a leaf - * @returns Boolean - */ - AjxpNode.prototype.isLeaf = function isLeaf() { - return this._isLeaf; - }; - - /** - * @returns String - */ - - AjxpNode.prototype.getPath = function getPath() { - return this._path; - }; + /** + * Removes the child from the children + * @param ajxpNode AjxpNode + */ + }, { + key: 'removeChild', + value: function removeChild(ajxpNode) { + var removePath = ajxpNode.getPath(); + ajxpNode.notify("node_removed"); + ajxpNode._parentNode = null; + this._children['delete'](ajxpNode.getPath()); + this.notify("child_removed", removePath); + } - /** - * @returns String - */ + /** + * Replaces the current node by a new one. Copy all properties deeply + * @param ajxpNode AjxpNode + * @param metaMerge + */ + }, { + key: 'replaceBy', + value: function replaceBy(ajxpNode, metaMerge) { + this._isLeaf = ajxpNode._isLeaf; + if (ajxpNode.getPath() && this._path != ajxpNode.getPath()) { + var originalPath = this._path; + if (this.getParent()) { + var parentChildrenIndex = this.getParent()._children; + parentChildrenIndex.set(ajxpNode.getPath(), this); + parentChildrenIndex['delete'](originalPath); + } + this._path = ajxpNode.getPath(); + var pathChanged = true; + } + if (ajxpNode._label) { + this._label = ajxpNode._label; + } + if (ajxpNode._icon) { + this._icon = ajxpNode._icon; + } + if (ajxpNode._iNodeProvider) { + this._iNodeProvider = ajxpNode._iNodeProvider; + } + //this._isRoot = ajxpNode._isRoot; + this._isLoaded = ajxpNode._isLoaded; + this.fake = ajxpNode.fake; + var meta = ajxpNode.getMetadata(); + if (metaMerge == "override") this._metadata = new Map(); + meta.forEach((function (value, key) { + if (metaMerge == "override") { + this._metadata.set(key, value); + } else { + if (this._metadata.has(key) && value === "") { + return; + } + this._metadata.set(key, value); + } + }).bind(this)); + if (pathChanged && !this._isLeaf && this.getChildren().size) { + window.setTimeout((function () { + this.reload(this._iNodeProvider); + }).bind(this), 100); + return; + } + ajxpNode.getChildren().forEach((function (child) { + this.addChild(child); + }).bind(this)); + this.notify("node_replaced", this); + } - AjxpNode.prototype.getLabel = function getLabel() { - return this._label; - }; + /** + * Finds a child node by its path + * @param path String + * @returns AjxpNode + */ + }, { + key: 'findChildByPath', + value: function findChildByPath(path) { + return this._children.get(path); + } - /** - * @returns String - */ + /** + * Sets the metadata as a bunch + * @param data Map A Map + */ + }, { + key: 'setMetadata', + value: function setMetadata(data) { + this._metadata = data; + } - AjxpNode.prototype.getIcon = function getIcon() { - return this._icon; - }; + /** + * Gets the metadat + * @returns Map + */ + }, { + key: 'getMetadata', + value: function getMetadata() { + return this._metadata; + } - /** - * @returns Boolean - */ + /** + * Is this node a leaf + * @returns Boolean + */ + }, { + key: 'isLeaf', + value: function isLeaf() { + return this._isLeaf; + } - AjxpNode.prototype.isRecycle = function isRecycle() { - return this.getAjxpMime() == 'ajxp_recycle'; - }; + /** + * @returns String + */ + }, { + key: 'getPath', + value: function getPath() { + return this._path; + } - /** - * Search the mime type in the parent branch - * @param ajxpMime String - * @returns Boolean - */ + /** + * @returns String + */ + }, { + key: 'getLabel', + value: function getLabel() { + return this._label; + } - AjxpNode.prototype.hasAjxpMimeInBranch = function hasAjxpMimeInBranch(ajxpMime) { - if (this.getAjxpMime() == ajxpMime.toLowerCase()) return true; - var parent, - crt = this; - while (parent = crt._parentNode) { - if (parent.getAjxpMime() == ajxpMime.toLowerCase()) { - return true; - } - crt = parent; + /** + * @returns String + */ + }, { + key: 'getIcon', + value: function getIcon() { + return this._icon; } - return false; - }; - /** - * Search the mime type in the parent branch - * @returns Boolean - * @param metadataKey - * @param metadataValue - */ + /** + * @returns Boolean + */ + }, { + key: 'isRecycle', + value: function isRecycle() { + return this.getAjxpMime() == 'ajxp_recycle'; + } - AjxpNode.prototype.hasMetadataInBranch = function hasMetadataInBranch(metadataKey, metadataValue) { - if (this.getMetadata().has(metadataKey)) { - if (metadataValue) { - return this.getMetadata().get(metadataKey) == metadataValue; - } else { - return true; + /** + * Search the mime type in the parent branch + * @param ajxpMime String + * @returns Boolean + */ + }, { + key: 'hasAjxpMimeInBranch', + value: function hasAjxpMimeInBranch(ajxpMime) { + if (this.getAjxpMime() == ajxpMime.toLowerCase()) return true; + var parent, + crt = this; + while (parent = crt._parentNode) { + if (parent.getAjxpMime() == ajxpMime.toLowerCase()) { + return true; + } + crt = parent; } + return false; } - var parent, - crt = this; - while (parent = crt._parentNode) { - if (parent.getMetadata().has(metadataKey)) { + + /** + * Search the mime type in the parent branch + * @returns Boolean + * @param metadataKey + * @param metadataValue + */ + }, { + key: 'hasMetadataInBranch', + value: function hasMetadataInBranch(metadataKey, metadataValue) { + if (this.getMetadata().has(metadataKey)) { if (metadataValue) { - return parent.getMetadata().get(metadataKey) == metadataValue; + return this.getMetadata().get(metadataKey) == metadataValue; } else { return true; } } - crt = parent; + var parent, + crt = this; + while (parent = crt._parentNode) { + if (parent.getMetadata().has(metadataKey)) { + if (metadataValue) { + return parent.getMetadata().get(metadataKey) == metadataValue; + } else { + return true; + } + } + crt = parent; + } + return false; } - return false; - }; - - /** - * Sets a reference to the parent node - * @param parentNode AjxpNode - */ - - AjxpNode.prototype.setParent = function setParent(parentNode) { - this._parentNode = parentNode; - }; - /** - * Gets the parent Node - * @returns AjxpNode - */ - - AjxpNode.prototype.getParent = function getParent() { - return this._parentNode; - }; + /** + * Sets a reference to the parent node + * @param parentNode AjxpNode + */ + }, { + key: 'setParent', + value: function setParent(parentNode) { + this._parentNode = parentNode; + } - /** - * Finds this node by path if it already exists in arborescence - * @param rootNode AjxpNode - * @param fakeNodes AjxpNode[] - * @returns AjxpNode|undefined - */ + /** + * Gets the parent Node + * @returns AjxpNode + */ + }, { + key: 'getParent', + value: function getParent() { + return this._parentNode; + } - AjxpNode.prototype.findInArbo = function findInArbo(rootNode, fakeNodes) { - if (!this.getPath()) return; - var pathParts = this.getPath().split('/'); - var crtPath = ''; - var crtNode, - crtParentNode = rootNode; - for (var i = 0; i < pathParts.length; i++) { - if (pathParts[i] == '') continue; - crtPath = crtPath + '/' + pathParts[i]; - var node = crtParentNode.findChildByPath(crtPath); - if (node && !(node instanceof String)) { - crtNode = node; - } else { - if (fakeNodes === undefined) return undefined; - crtNode = new AjxpNode(crtPath, false, PathUtils.getBasename(crtPath)); - crtNode.fake = true; - crtNode.getMetadata().set('text', PathUtils.getBasename(crtPath)); - fakeNodes.push(crtNode); - crtParentNode.addChild(crtNode); + /** + * Finds this node by path if it already exists in arborescence + * @param rootNode AjxpNode + * @param fakeNodes AjxpNode[] + * @returns AjxpNode|undefined + */ + }, { + key: 'findInArbo', + value: function findInArbo(rootNode, fakeNodes) { + if (!this.getPath()) return; + var pathParts = this.getPath().split("/"); + var crtPath = ""; + var crtNode, + crtParentNode = rootNode; + for (var i = 0; i < pathParts.length; i++) { + if (pathParts[i] == "") continue; + crtPath = crtPath + "/" + pathParts[i]; + var node = crtParentNode.findChildByPath(crtPath); + if (node && !(node instanceof String)) { + crtNode = node; + } else { + if (fakeNodes === undefined) return undefined; + crtNode = new AjxpNode(crtPath, false, PathUtils.getBasename(crtPath)); + crtNode.fake = true; + crtNode.getMetadata().set("text", PathUtils.getBasename(crtPath)); + fakeNodes.push(crtNode); + crtParentNode.addChild(crtNode); + } + crtParentNode = crtNode; } - crtParentNode = crtNode; + return crtNode; } - return crtNode; - }; - /** - * @returns Boolean - */ - - AjxpNode.prototype.isRoot = function isRoot() { - return this._isRoot; - }; - - /** - * Check if it's the parent of the given node - * @param node AjxpNode - * @returns Boolean - */ - - AjxpNode.prototype.isParentOf = function isParentOf(node) { - var childPath = node.getPath(); - var parentPath = this.getPath(); - return childPath.substring(0, parentPath.length) == parentPath; - }; - - /** - * Check if it's a child of the given node - * @param node AjxpNode - * @returns Boolean - */ + /** + * @returns Boolean + */ + }, { + key: 'isRoot', + value: function isRoot() { + return this._isRoot; + } - AjxpNode.prototype.isChildOf = function isChildOf(node) { - var childPath = this.getPath(); - var parentPath = node.getPath(); - return childPath.substring(0, parentPath.length) == parentPath; - }; + /** + * Check if it's the parent of the given node + * @param node AjxpNode + * @returns Boolean + */ + }, { + key: 'isParentOf', + value: function isParentOf(node) { + var childPath = node.getPath(); + var parentPath = this.getPath(); + return childPath.substring(0, parentPath.length) == parentPath; + } - /** - * Gets the current's node mime type, either by ajxp_mime or by extension. - * @returns String - */ + /** + * Check if it's a child of the given node + * @param node AjxpNode + * @returns Boolean + */ + }, { + key: 'isChildOf', + value: function isChildOf(node) { + var childPath = this.getPath(); + var parentPath = node.getPath(); + return childPath.substring(0, parentPath.length) == parentPath; + } - AjxpNode.prototype.getAjxpMime = function getAjxpMime() { - if (this._metadata && this._metadata.has('ajxp_mime')) return this._metadata.get('ajxp_mime').toLowerCase(); - if (this._metadata && this.isLeaf()) return PathUtils.getAjxpMimeType(this._metadata).toLowerCase(); - return ''; - }; + /** + * Gets the current's node mime type, either by ajxp_mime or by extension. + * @returns String + */ + }, { + key: 'getAjxpMime', + value: function getAjxpMime() { + if (this._metadata && this._metadata.has("ajxp_mime")) return this._metadata.get("ajxp_mime").toLowerCase(); + if (this._metadata && this.isLeaf()) return PathUtils.getAjxpMimeType(this._metadata).toLowerCase(); + return ""; + } + }]); return AjxpNode; -})(Observable); \ No newline at end of file +})(Observable); diff --git a/core/src/plugins/gui.ajax/res/js/core/model/BackgroundTasksManager.js b/core/src/plugins/gui.ajax/res/js/core/model/BackgroundTasksManager.js index 190840912e..6e9834ef7f 100644 --- a/core/src/plugins/gui.ajax/res/js/core/model/BackgroundTasksManager.js +++ b/core/src/plugins/gui.ajax/res/js/core/model/BackgroundTasksManager.js @@ -23,11 +23,16 @@ */ 'use strict'; +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } -function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } +function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var BackgroundTasksManager = (function (_Observable) { + _inherits(BackgroundTasksManager, _Observable); /** * Constructor @@ -37,14 +42,12 @@ var BackgroundTasksManager = (function (_Observable) { function BackgroundTasksManager(actionManager) { _classCallCheck(this, BackgroundTasksManager); - _Observable.call(this); + _get(Object.getPrototypeOf(BackgroundTasksManager.prototype), 'constructor', this).call(this); this.queue = []; this.actionManager = actionManager; this.working = false; } - _inherits(BackgroundTasksManager, _Observable); - /** * Add an action to the queue * @param actionName String Name of the action @@ -52,136 +55,144 @@ var BackgroundTasksManager = (function (_Observable) { * @param messageId String An i18n id of the message to be displayed during the action */ - BackgroundTasksManager.prototype.queueAction = function queueAction(actionName, parameters, messageId) { - var actionDef = {}; - actionDef['name'] = actionName; - actionDef['messageId'] = messageId; - actionDef['parameters'] = parameters; - this.queue.push(actionDef); - }; - - /** - * Processes the next action in the queue - */ - - BackgroundTasksManager.prototype.next = function next() { - if (!this.queue.length) { - this.finished(); - return; + _createClass(BackgroundTasksManager, [{ + key: 'queueAction', + value: function queueAction(actionName, parameters, messageId) { + var actionDef = {}; + actionDef['name'] = actionName; + actionDef['messageId'] = messageId; + actionDef['parameters'] = parameters; + this.queue.push(actionDef); } - if (this.working) return; - var actionDef = this.queue[0]; - if (actionDef['name'] == 'javascript_instruction' && actionDef['parameters']['callback']) { - var cb = actionDef['parameters']['callback']; - this.notify('update_message', actionDef['messageId']); - this.queue.shift(); - cb(); - this.working = false; - this.next(); - } else { - var client = PydioApi.getClient(); - var params = { get_action: actionDef['name'] }; - for (var k in actionDef['parameters']) { - if (actionDef['parameters'].hasOwnProperty(k)) params[k] = actionDef['parameters'][k]; + + /** + * Processes the next action in the queue + */ + }, { + key: 'next', + value: function next() { + if (!this.queue.length) { + this.finished(); + return; } - client.request(params, (function (transport) { - var xmlResponse = transport.responseXML; - if (xmlResponse == null || xmlResponse.documentElement == null) { - this.working = false; - this.next(); - return; - } - this.parseAnswer(transport.responseXML); + if (this.working) return; + var actionDef = this.queue[0]; + if (actionDef['name'] == "javascript_instruction" && actionDef['parameters']['callback']) { + var cb = actionDef['parameters']['callback']; + this.notify("update_message", actionDef['messageId']); + this.queue.shift(); + cb(); this.working = false; - }).bind(this), null, { method: 'POST' }); - this.notify('update_message', actionDef['messageId']); - this.queue.shift(); - this.working = true; + this.next(); + } else { + var client = PydioApi.getClient(); + var params = { get_action: actionDef['name'] }; + for (var k in actionDef['parameters']) { + if (actionDef['parameters'].hasOwnProperty(k)) params[k] = actionDef['parameters'][k]; + } + client.request(params, (function (transport) { + var xmlResponse = transport.responseXML; + if (xmlResponse == null || xmlResponse.documentElement == null) { + this.working = false; + this.next(); + return; + } + this.parseAnswer(transport.responseXML); + this.working = false; + }).bind(this), null, { method: 'POST' }); + this.notify("update_message", actionDef['messageId']); + this.queue.shift(); + this.working = true; + } } - }; - /** - * Parses the response. Should probably use the actionBar parser instead. - * @param xmlResponse XMLDocument - */ - - BackgroundTasksManager.prototype.parseAnswer = function parseAnswer(xmlResponse) { - var childs = xmlResponse.documentElement.childNodes; - var delay = 0; - for (var i = 0; i < childs.length; i++) { - if (childs[i].tagName == 'message') { - var type = childs[i].getAttribute('type'); - if (type != 'SUCCESS') { - this.interruptOnError(childs[i].firstChild.nodeValue); - } - } else if (childs[i].nodeName == 'trigger_bg_action') { - var name = childs[i].getAttribute('name'); - var messageId = childs[i].getAttribute('messageId'); - delay = parseInt(childs[i].getAttribute('delay')); - var parameters = {}; - for (var j = 0; j < childs[i].childNodes.length; j++) { - var paramChild = childs[i].childNodes[j]; - if (paramChild.tagName == 'param') { - parameters[paramChild.getAttribute('name')] = paramChild.getAttribute('value'); - } else if (paramChild.tagName == 'clientCallback') { - var callbackCode = paramChild.firstChild.nodeValue; - var callback = new Function(callbackCode); + /** + * Parses the response. Should probably use the actionBar parser instead. + * @param xmlResponse XMLDocument + */ + }, { + key: 'parseAnswer', + value: function parseAnswer(xmlResponse) { + var childs = xmlResponse.documentElement.childNodes; + var delay = 0; + for (var i = 0; i < childs.length; i++) { + if (childs[i].tagName == "message") { + var type = childs[i].getAttribute('type'); + if (type != 'SUCCESS') { + this.interruptOnError(childs[i].firstChild.nodeValue); } - } - if (name == 'reload_node') { - if (delay) { - window.setTimeout((function () { - this.actionManager.getDataModel().requireContextChange(this.actionManager.getDataModel().getContextNode(), true); - this.next(); - }).bind(this), delay * 1000); - return; + } else if (childs[i].nodeName == "trigger_bg_action") { + var name = childs[i].getAttribute("name"); + var messageId = childs[i].getAttribute("messageId"); + delay = parseInt(childs[i].getAttribute("delay")); + var parameters = {}; + for (var j = 0; j < childs[i].childNodes.length; j++) { + var paramChild = childs[i].childNodes[j]; + if (paramChild.tagName == 'param') { + parameters[paramChild.getAttribute("name")] = paramChild.getAttribute("value"); + } else if (paramChild.tagName == 'clientCallback') { + var callbackCode = paramChild.firstChild.nodeValue; + var callback = new Function(callbackCode); + } + } + if (name == "reload_node") { + if (delay) { + window.setTimeout((function () { + this.actionManager.getDataModel().requireContextChange(this.actionManager.getDataModel().getContextNode(), true); + this.next(); + }).bind(this), delay * 1000); + return; + } + this.actionManager.getDataModel().requireContextChange(this.actionManager.getDataModel().getContextNode(), true); + } else if (name == "info_message") { + this.notify("update_message", messageId); + } else if (name == "javascript_instruction" && callback) { + parameters["callback"] = callback; + this.queueAction('javascript_instruction', parameters, messageId); + } else { + this.queueAction(name, parameters, messageId); } - this.actionManager.getDataModel().requireContextChange(this.actionManager.getDataModel().getContextNode(), true); - } else if (name == 'info_message') { - this.notify('update_message', messageId); - } else if (name == 'javascript_instruction' && callback) { - parameters['callback'] = callback; - this.queueAction('javascript_instruction', parameters, messageId); - } else { - this.queueAction(name, parameters, messageId); } } + this.working = false; + if (delay) { + window.setTimeout(this.next.bind(this), delay * 1000); + } else { + this.next(); + } } - this.working = false; - if (delay) { - window.setTimeout(this.next.bind(this), delay * 1000); - } else { - this.next(); - } - }; - - /** - * Interrupt the task on error - * @param errorMessage String - */ - - BackgroundTasksManager.prototype.interruptOnError = function interruptOnError(errorMessage) { - if (this.queue.length) this.queue = []; - this.notify('update_message_error', errorMessage); - this.working = false; - }; - /** - * All tasks are processed - */ - - BackgroundTasksManager.prototype.finished = function finished() { - this.working = false; - this.notify('tasks_finished'); - }; + /** + * Interrupt the task on error + * @param errorMessage String + */ + }, { + key: 'interruptOnError', + value: function interruptOnError(errorMessage) { + if (this.queue.length) this.queue = []; + this.notify("update_message_error", errorMessage); + this.working = false; + } - /** - * Create a stub action with not parameter. - */ + /** + * All tasks are processed + */ + }, { + key: 'finished', + value: function finished() { + this.working = false; + this.notify("tasks_finished"); + } - BackgroundTasksManager.prototype.addStub = function addStub() { - this.queueAction('local_to_remote', {}, 'Stubing a 10s bg action'); - }; + /** + * Create a stub action with not parameter. + */ + }, { + key: 'addStub', + value: function addStub() { + this.queueAction('local_to_remote', {}, 'Stubing a 10s bg action'); + } + }]); return BackgroundTasksManager; -})(Observable); \ No newline at end of file +})(Observable); diff --git a/core/src/plugins/gui.ajax/res/js/core/model/Controller.js b/core/src/plugins/gui.ajax/res/js/core/model/Controller.js index 187d4c8fa6..7f8c7e7d13 100644 --- a/core/src/plugins/gui.ajax/res/js/core/model/Controller.js +++ b/core/src/plugins/gui.ajax/res/js/core/model/Controller.js @@ -23,11 +23,16 @@ */ "use strict"; +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +var _get = function get(_x3, _x4, _x5) { var _again = true; _function: while (_again) { var object = _x3, property = _x4, receiver = _x5; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x3 = parent; _x4 = property; _x5 = receiver; _again = true; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Controller = (function (_Observable) { + _inherits(Controller, _Observable); /** * Standard constructor @@ -36,11 +41,11 @@ var Controller = (function (_Observable) { */ function Controller(pydioObject) { - var dataModelElementId = arguments[1] === undefined ? null : arguments[1]; + var dataModelElementId = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; _classCallCheck(this, Controller); - _Observable.call(this); + _get(Object.getPrototypeOf(Controller.prototype), "constructor", this).call(this); this._pydioObject = pydioObject; this._registeredKeys = new Map(); this.usersEnabled = pydioObject.Parameters.get("usersEnabled"); @@ -90,500 +95,541 @@ var Controller = (function (_Observable) { } } - _inherits(Controller, _Observable); - - Controller.prototype.publishActionEvent = function publishActionEvent(eventName, data) { - this._pydioObject.fire(eventName, data); - }; - - Controller.prototype._connectDataModel = function _connectDataModel() { - if (this.localDataModel) { - this._dataModel.observe("context_changed", this.contextChangedObs); - this._dataModel.observe("selection_changed", this.selectionChangedObs); - this.loadActionsFromRegistry(); - this._pydioObject.observe("registry_loaded", (function (registry) { - this.loadActionsFromRegistry(registry); + _createClass(Controller, [{ + key: "publishActionEvent", + value: function publishActionEvent(eventName, data) { + this._pydioObject.fire(eventName, data); + } + }, { + key: "_connectDataModel", + value: function _connectDataModel() { + if (this.localDataModel) { + this._dataModel.observe("context_changed", this.contextChangedObs); + this._dataModel.observe("selection_changed", this.selectionChangedObs); + this.loadActionsFromRegistry(); + this._pydioObject.observe("registry_loaded", (function (registry) { + this.loadActionsFromRegistry(registry); + }).bind(this)); + } else { + this._pydioObject.observe("context_changed", this.contextChangedObs); + this._pydioObject.observe("selection_changed", this.selectionChangedObs); + this._dataModel = this._pydioObject.getContextHolder(); + } + } + }, { + key: "updateGuiActions", + value: function updateGuiActions(actions) { + actions.forEach((function (v, k) { + this._guiActions.set(k, v); }).bind(this)); - } else { - this._pydioObject.observe("context_changed", this.contextChangedObs); - this._pydioObject.observe("selection_changed", this.selectionChangedObs); - this._dataModel = this._pydioObject.getContextHolder(); } - }; - - Controller.prototype.updateGuiActions = function updateGuiActions(actions) { - actions.forEach((function (v, k) { - this._guiActions.set(k, v); - }).bind(this)); - }; - - Controller.prototype.deleteFromGuiActions = function deleteFromGuiActions(actionName) { - this._guiActions["delete"](actionName); - }; - - Controller.prototype.refreshGuiActionsI18n = function refreshGuiActionsI18n() { - this._guiActions.forEach(function (value, key) { - value.refreshFromI18NHash(); - }); - }; - - Controller.prototype.getBackgroundTasksManager = function getBackgroundTasksManager() { - if (!Controller._bgManager) { - Controller._bgManager = new BackgroundTasksManager(); + }, { + key: "deleteFromGuiActions", + value: function deleteFromGuiActions(actionName) { + this._guiActions["delete"](actionName); } - return Controller._bgManager; - }; - - Controller.prototype.getDataModel = function getDataModel() { - return this._dataModel; - }; - - Controller.prototype.destroy = function destroy() { - if (this.localDataModel && this._dataModel) { - this._dataModel.stopObserving("context_changed", this.contextChangedObs); - this._dataModel.stopObserving("selection_changed", this.selectionChangedObs); + }, { + key: "refreshGuiActionsI18n", + value: function refreshGuiActionsI18n() { + this._guiActions.forEach(function (value, key) { + value.refreshFromI18NHash(); + }); } - }; - - Controller.prototype.getMessage = function getMessage(messageId) { - try { - return this._pydioObject.MessageHash[messageId]; - } catch (e) { - return messageId; + }, { + key: "getBackgroundTasksManager", + value: function getBackgroundTasksManager() { + if (!Controller._bgManager) { + Controller._bgManager = new BackgroundTasksManager(); + } + return Controller._bgManager; } - }; - - Controller.prototype.uiInsertForm = function uiInsertForm(formId, formCode) { - if (this._pydioObject.UI) { - this._pydioObject.UI.insertForm(formId, formCode); + }, { + key: "getDataModel", + value: function getDataModel() { + return this._dataModel; } - }; - - Controller.prototype.uiRemoveForm = function uiRemoveForm(formId) { - if (this._pydioObject.UI) { - this._pydioObject.UI.removeForm(formId); + }, { + key: "destroy", + value: function destroy() { + if (this.localDataModel && this._dataModel) { + this._dataModel.stopObserving("context_changed", this.contextChangedObs); + this._dataModel.stopObserving("selection_changed", this.selectionChangedObs); + } } - }; - - Controller.prototype.uiGetModal = function uiGetModal() { - if (this._pydioObject && this._pydioObject.UI) { - return this._pydioObject.UI.modal; + }, { + key: "getMessage", + value: function getMessage(messageId) { + try { + return this._pydioObject.MessageHash[messageId]; + } catch (e) { + return messageId; + } } - return null; - }; - - Controller.prototype.uiMountComponents = function uiMountComponents(componentsNodes) { - if (this._pydioObject && this._pydioObject.UI) { - return this._pydioObject.UI.mountComponents(componentsNodes); + }, { + key: "uiInsertForm", + value: function uiInsertForm(formId, formCode) { + if (this._pydioObject.UI) { + this._pydioObject.UI.insertForm(formId, formCode); + } } - }; - - /** - * COMPATIBILITY METHD - * @param xmlDoc - * @returns {*} - */ - - Controller.prototype.parseXmlMessage = function parseXmlMessage(xmlDoc) { - Logger.log("Controller.parseXmlMessage() is deprecated, use PydioApi instead"); - if (window.console && window.console.trace) { - Logger.log(console.trace()); + }, { + key: "uiRemoveForm", + value: function uiRemoveForm(formId) { + if (this._pydioObject.UI) { + this._pydioObject.UI.removeForm(formId); + } + } + }, { + key: "uiGetModal", + value: function uiGetModal() { + if (this._pydioObject && this._pydioObject.UI) { + return this._pydioObject.UI.modal; + } + return null; + } + }, { + key: "uiMountComponents", + value: function uiMountComponents(componentsNodes) { + if (this._pydioObject && this._pydioObject.UI) { + return this._pydioObject.UI.mountComponents(componentsNodes); + } } - return PydioApi.getClient().parseXmlMessage(xmlDoc); - }; - - /** - * Submits a form using Connexion class. - * @param formName String The id of the form - * @param post Boolean Whether to POST or GET - * @param completeCallback Function Callback to be called on complete - */ - - Controller.prototype.submitForm = function submitForm(formName, post, completeCallback) { - Logger.log("Controller.submitForm() is deprecated, use PydioApi instead"); - return PydioApi.getClient().submitForm(formName, post, completeCallback); - }; - /** - * Stores the currently logged user object - * @param oUser User User instance - */ + /** + * COMPATIBILITY METHD + * @param xmlDoc + * @returns {*} + */ + }, { + key: "parseXmlMessage", + value: function parseXmlMessage(xmlDoc) { + Logger.log("Controller.parseXmlMessage() is deprecated, use PydioApi instead"); + if (window.console && window.console.trace) { + Logger.log(console.trace()); + } + return PydioApi.getClient().parseXmlMessage(xmlDoc); + } - Controller.prototype.setUser = function setUser(oUser) { - this.oUser = oUser; - if (oUser != null && oUser.id != "guest" && oUser.getPreference("lang") != null && oUser.getPreference("lang") != "" && oUser.getPreference("lang") != this._pydioObject.currentLanguage && !oUser.lock) { - this._pydioObject.loadI18NMessages(oUser.getPreference("lang")); + /** + * Submits a form using Connexion class. + * @param formName String The id of the form + * @param post Boolean Whether to POST or GET + * @param completeCallback Function Callback to be called on complete + */ + }, { + key: "submitForm", + value: function submitForm(formName, post, completeCallback) { + Logger.log("Controller.submitForm() is deprecated, use PydioApi instead"); + return PydioApi.getClient().submitForm(formName, post, completeCallback); } - }; - /** - * Filter the actions given the srcElement passed as arguments. - * TODO: SIGNATURE CHANGED, FROM srcElement to actionsSelectorAtt - * @param srcElement String An identifier among selectionContext, genericContext, a webfx object id - * @param ignoreGroups Array a list of groups to ignore - * @returns Array - */ + /** + * Stores the currently logged user object + * @param oUser User User instance + */ + }, { + key: "setUser", + value: function setUser(oUser) { + this.oUser = oUser; + if (oUser != null && oUser.id != 'guest' && oUser.getPreference('lang') != null && oUser.getPreference('lang') != "" && oUser.getPreference('lang') != this._pydioObject.currentLanguage && !oUser.lock) { + this._pydioObject.loadI18NMessages(oUser.getPreference('lang')); + } + } - Controller.prototype.getContextActions = function getContextActions(actionsSelectorAtt, ignoreGroups) { - var contextActions = []; - var defaultGroup; - var contextActionsGroup = new Map(); - this.actions.forEach((function (action) { - if (!action.context.contextMenu) return; - if (actionsSelectorAtt == "selectionContext" && !action.context.selection) return; - if (actionsSelectorAtt == "directoryContext" && !action.context.dir) return; - if (actionsSelectorAtt == "genericContext" && action.context.selection) return; - if (action.contextHidden || action.deny) return; - action.context.actionBarGroup.split(",").forEach(function (barGroup) { - if (!contextActionsGroup.has(barGroup)) { - contextActionsGroup.set(barGroup, []); - } - }); - var isDefault = false; - if (actionsSelectorAtt == "selectionContext") { - // set default in bold - var userSelection = this._dataModel; - if (!userSelection.isEmpty()) { - var defaultAction = "file"; - if (userSelection.isUnique() && (userSelection.hasDir() || userSelection.hasMime(["ajxp_browsable_archive"]))) { - defaultAction = "dir"; + /** + * Filter the actions given the srcElement passed as arguments. + * TODO: SIGNATURE CHANGED, FROM srcElement to actionsSelectorAtt + * @param srcElement String An identifier among selectionContext, genericContext, a webfx object id + * @param ignoreGroups Array a list of groups to ignore + * @returns Array + */ + }, { + key: "getContextActions", + value: function getContextActions(actionsSelectorAtt, ignoreGroups) { + var contextActions = []; + var defaultGroup; + var contextActionsGroup = new Map(); + this.actions.forEach((function (action) { + if (!action.context.contextMenu) return; + if (actionsSelectorAtt == 'selectionContext' && !action.context.selection) return; + if (actionsSelectorAtt == 'directoryContext' && !action.context.dir) return; + if (actionsSelectorAtt == 'genericContext' && action.context.selection) return; + if (action.contextHidden || action.deny) return; + action.context.actionBarGroup.split(',').forEach(function (barGroup) { + if (!contextActionsGroup.has(barGroup)) { + contextActionsGroup.set(barGroup, []); } - if (this.defaultActions.get(defaultAction) && action.options.name == this.defaultActions.get(defaultAction)) { - isDefault = true; + }); + var isDefault = false; + if (actionsSelectorAtt == 'selectionContext') { + // set default in bold + var userSelection = this._dataModel; + if (!userSelection.isEmpty()) { + var defaultAction = 'file'; + if (userSelection.isUnique() && (userSelection.hasDir() || userSelection.hasMime(['ajxp_browsable_archive']))) { + defaultAction = 'dir'; + } + if (this.defaultActions.get(defaultAction) && action.options.name == this.defaultActions.get(defaultAction)) { + isDefault = true; + } } } + action.context.actionBarGroup.split(',').forEach(function (barGroup) { + var menuItem = { + name: action.getKeyedText(), + alt: action.options.title, + action_id: action.options.name, + image_unresolved: action.options.src, + isDefault: isDefault, + callback: (function (e) { + this.apply(); + }).bind(action) + }; + if (action.options.icon_class) { + menuItem.icon_class = action.options.icon_class; + } + if (action.options.subMenu) { + menuItem.subMenu = []; + if (action.subMenuItems.staticOptions) { + menuItem.subMenu = action.subMenuItems.staticOptions; + } + if (action.subMenuItems.dynamicBuilder) { + menuItem.subMenuBeforeShow = action.subMenuItems.dynamicBuilder; + } + } + contextActionsGroup.get(barGroup).push(menuItem); + if (isDefault) { + defaultGroup = barGroup; + } + }); + }).bind(this)); + var first = true, + keys = []; + if (defaultGroup && contextActionsGroup.has(defaultGroup)) { + keys.push(defaultGroup); } - action.context.actionBarGroup.split(",").forEach(function (barGroup) { - var menuItem = { - name: action.getKeyedText(), - alt: action.options.title, - action_id: action.options.name, - image_unresolved: action.options.src, - isDefault: isDefault, - callback: (function (e) { - this.apply(); - }).bind(action) - }; - if (action.options.icon_class) { - menuItem.icon_class = action.options.icon_class; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = contextActionsGroup.keys()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var k = _step.value; + + if (k == defaultGroup) continue; + keys.push(k); } - if (action.options.subMenu) { - menuItem.subMenu = []; - if (action.subMenuItems.staticOptions) { - menuItem.subMenu = action.subMenuItems.staticOptions; + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator["return"]) { + _iterator["return"](); } - if (action.subMenuItems.dynamicBuilder) { - menuItem.subMenuBeforeShow = action.subMenuItems.dynamicBuilder; + } finally { + if (_didIteratorError) { + throw _iteratorError; } } - contextActionsGroup.get(barGroup).push(menuItem); - if (isDefault) { - defaultGroup = barGroup; - } - }); - }).bind(this)); - var first = true, - keys = []; - if (defaultGroup && contextActionsGroup.has(defaultGroup)) { - keys.push(defaultGroup); - } - for (var _iterator = contextActionsGroup.keys(), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; } - var k = _ref; - - if (k == defaultGroup) continue; - keys.push(k); - } - keys.sort(); - keys.each(function (key) { - var value = contextActionsGroup.get(key); - if (!first) { - contextActions.push({ separator: true }); - } - if (ignoreGroups && ignoreGroups.indexOf(key) != -1) { - return; - } - first = false; - value.forEach(function (mItem) { - contextActions.push(mItem); + keys.sort(); + keys.each(function (key) { + var value = contextActionsGroup.get(key); + if (!first) { + contextActions.push({ separator: true }); + } + if (ignoreGroups && ignoreGroups.indexOf(key) != -1) { + return; + } + first = false; + value.forEach(function (mItem) { + contextActions.push(mItem); + }); }); - }); - return contextActions; - }; - - /** - * Generic method to get actions for a given component part. - * @param ajxpClassName String - * @param widgetId String - * @returns [] - */ - - Controller.prototype.getActionsForAjxpWidget = function getActionsForAjxpWidget(ajxpClassName, widgetId) { - var actions = []; - this.actions.forEach(function (action) { - if (action.context.ajxpWidgets && (action.context.ajxpWidgets.indexOf(ajxpClassName + "::" + widgetId) != -1 || action.context.ajxpWidgets.indexOf(ajxpClassName) != -1) && !action.deny) actions.push(action); - }); - return actions; - }; + return contextActions; + } - /** - * Finds a default action and fires it. - * @param defaultName String ("file", "dir", "dragndrop", "ctrldragndrop") - */ + /** + * Generic method to get actions for a given component part. + * @param ajxpClassName String + * @param widgetId String + * @returns [] + */ + }, { + key: "getActionsForAjxpWidget", + value: function getActionsForAjxpWidget(ajxpClassName, widgetId) { + var actions = []; + this.actions.forEach(function (action) { + if (action.context.ajxpWidgets && (action.context.ajxpWidgets.indexOf(ajxpClassName + '::' + widgetId) != -1 || action.context.ajxpWidgets.indexOf(ajxpClassName) != -1) && !action.deny) actions.push(action); + }); + return actions; + } - Controller.prototype.fireDefaultAction = function fireDefaultAction(defaultName) { - var actionName = this.defaultActions.get(defaultName); - if (actionName) { - arguments[0] = actionName; - if (actionName == "ls") { - var action = this.actions.get(actionName); - if (action) action.enable(); // Force enable on default action + /** + * Finds a default action and fires it. + * @param defaultName String ("file", "dir", "dragndrop", "ctrldragndrop") + */ + }, { + key: "fireDefaultAction", + value: function fireDefaultAction(defaultName) { + var actionName = this.defaultActions.get(defaultName); + if (actionName) { + arguments[0] = actionName; + if (actionName == "ls") { + var action = this.actions.get(actionName); + if (action) action.enable(); // Force enable on default action + } + this.fireAction.apply(this, arguments); } - this.fireAction.apply(this, arguments); } - }; - /** - * Fire an action based on its name - * @param actionName String The name of the action - */ - - Controller.prototype.fireAction = function fireAction(actionName) { - var action = this.actions.get(actionName); - if (action != null) { - var args = Array.from(arguments).slice(1); - action.apply(args); + /** + * Fire an action based on its name + * @param actionName String The name of the action + */ + }, { + key: "fireAction", + value: function fireAction(actionName) { + var action = this.actions.get(actionName); + if (action != null) { + var args = Array.from(arguments).slice(1); + action.apply(args); + } } - }; - - /** - * Registers an accesskey for a given action. - * @param key String The access key - * @param actionName String The name of the action - * @param optionnalCommand String An optionnal argument - * that will be passed to the action when fired. - */ - Controller.prototype.registerKey = function registerKey(key, actionName, optionnalCommand) { - if (optionnalCommand) { - actionName = actionName + "::" + optionnalCommand; + /** + * Registers an accesskey for a given action. + * @param key String The access key + * @param actionName String The name of the action + * @param optionnalCommand String An optionnal argument + * that will be passed to the action when fired. + */ + }, { + key: "registerKey", + value: function registerKey(key, actionName, optionnalCommand) { + if (optionnalCommand) { + actionName = actionName + "::" + optionnalCommand; + } + this._registeredKeys.set(key.toLowerCase(), actionName); } - this._registeredKeys.set(key.toLowerCase(), actionName); - }; - - /** - * Remove all registered keys. - */ - - Controller.prototype.clearRegisteredKeys = function clearRegisteredKeys() { - this._registeredKeys = new Map(); - }; - /** - * Triggers an action by its access key. - * @param event Event The key event (will be stopped) - * @param keyName String A key name - */ + /** + * Remove all registered keys. + */ + }, { + key: "clearRegisteredKeys", + value: function clearRegisteredKeys() { + this._registeredKeys = new Map(); + } - Controller.prototype.fireActionByKey = function fireActionByKey(event, keyName) { - if (this._registeredKeys.get(keyName)) { - if (this._registeredKeys.get(keyName).indexOf("::") !== -1) { - var parts = this._registeredKeys.get(keyName).split("::"); - this.fireAction(parts[0], parts[1]); - } else { - this.fireAction(this._registeredKeys.get(keyName)); - } - try { - event.preventDefault(); - event.stopPropagation(); - } catch (e) { - Logger.error("Error trying to stop event propagation"); + /** + * Triggers an action by its access key. + * @param event Event The key event (will be stopped) + * @param keyName String A key name + */ + }, { + key: "fireActionByKey", + value: function fireActionByKey(event, keyName) { + if (this._registeredKeys.get(keyName)) { + if (this._registeredKeys.get(keyName).indexOf("::") !== -1) { + var parts = this._registeredKeys.get(keyName).split("::"); + this.fireAction(parts[0], parts[1]); + } else { + this.fireAction(this._registeredKeys.get(keyName)); + } + try { + event.preventDefault(); + event.stopPropagation(); + } catch (e) { + Logger.error("Error trying to stop event propagation"); + } } } - }; - - /** - * Complex function called when drag'n'dropping. Basic checks of who is child of who. - * @param fileName String The dragged element - * @param destDir String The drop target node path - * @param destNodeName String The drop target node name - * @param copy Boolean Copy or Move - */ - Controller.prototype.applyDragMove = function applyDragMove(fileName, destDir, destNodeName, copy) { - if (!copy && (!this.defaultActions.has("dragndrop") || this.getDefaultAction("dragndrop").deny) || copy && (!this.defaultActions.has("ctrldragndrop") || this.getDefaultAction("ctrldragndrop").deny)) { - return; - } - var fileNames; - if (fileName == null) fileNames = this._dataModel.getFileNames();else fileNames = [fileName]; - // Check that dest is not the direct parent of source, ie current rep! - if (destDir == this._dataModel.getContextNode().getPath()) { - this._pydioObject.displayMessage("ERROR", MessageHash[203]); - return; - } - // Check that dest is not child of source it self - for (var i = 0; i < fileNames.length; i++) { - if (destDir.lastIndexOf(fileNames[i], 0) === 0) { - this._pydioObject.displayMessage("ERROR", MessageHash[202]); + /** + * Complex function called when drag'n'dropping. Basic checks of who is child of who. + * @param fileName String The dragged element + * @param destDir String The drop target node path + * @param destNodeName String The drop target node name + * @param copy Boolean Copy or Move + */ + }, { + key: "applyDragMove", + value: function applyDragMove(fileName, destDir, destNodeName, copy) { + if (!copy && (!this.defaultActions.has('dragndrop') || this.getDefaultAction('dragndrop').deny) || copy && (!this.defaultActions.has('ctrldragndrop') || this.getDefaultAction('ctrldragndrop').deny)) { return; } + var fileNames; + if (fileName == null) fileNames = this._dataModel.getFileNames();else fileNames = [fileName]; + // Check that dest is not the direct parent of source, ie current rep! + if (destDir == this._dataModel.getContextNode().getPath()) { + this._pydioObject.displayMessage('ERROR', MessageHash[203]); + return; + } + // Check that dest is not child of source it self + for (var i = 0; i < fileNames.length; i++) { + if (destDir.lastIndexOf(fileNames[i], 0) === 0) { + this._pydioObject.displayMessage('ERROR', MessageHash[202]); + return; + } + } + var params = {}; + params['get_action'] = this.defaultActions.get(copy ? 'ctrldragndrop' : 'dragndrop'); + params['nodes[]'] = fileNames; + params['dest'] = destDir; + params['dir'] = this._dataModel.getContextNode().getPath(); + PydioApi.getClient().request(params, (function (transport) { + this.parseXmlMessage(transport.responseXML); + }).bind(PydioApi.getClient())); } - var params = {}; - params["get_action"] = this.defaultActions.get(copy ? "ctrldragndrop" : "dragndrop"); - params["nodes[]"] = fileNames; - params["dest"] = destDir; - params["dir"] = this._dataModel.getContextNode().getPath(); - PydioApi.getClient().request(params, (function (transport) { - this.parseXmlMessage(transport.responseXML); - }).bind(PydioApi.getClient())); - }; - - /** - * Get the action defined as default for a given default string - * @param defaultName String - * @returns Action - */ - Controller.prototype.getDefaultAction = function getDefaultAction(defaultName) { - if (this.defaultActions.has(defaultName)) { - return this.actions.get(this.defaultActions.get(defaultName)); + /** + * Get the action defined as default for a given default string + * @param defaultName String + * @returns Action + */ + }, { + key: "getDefaultAction", + value: function getDefaultAction(defaultName) { + if (this.defaultActions.has(defaultName)) { + return this.actions.get(this.defaultActions.get(defaultName)); + } + return null; } - return null; - }; - - /** - * Spreads a selection change to all actions and to registered components - * by triggering ajaxplorer:actions_refreshed event. - */ - Controller.prototype.fireSelectionChange = function fireSelectionChange() { - var userSelection = null; - userSelection = this._dataModel; - if (userSelection.isEmpty()) userSelection = null; - this.actions.forEach(function (action) { - action.fireSelectionChange(userSelection); - }); - if (this.localDataModel) { - this.notify("actions_refreshed"); - } else { - this._pydioObject.fire("actions_refreshed"); + /** + * Spreads a selection change to all actions and to registered components + * by triggering ajaxplorer:actions_refreshed event. + */ + }, { + key: "fireSelectionChange", + value: function fireSelectionChange() { + var userSelection = null; + userSelection = this._dataModel; + if (userSelection.isEmpty()) userSelection = null; + this.actions.forEach(function (action) { + action.fireSelectionChange(userSelection); + }); + if (this.localDataModel) { + this.notify("actions_refreshed"); + } else { + this._pydioObject.fire("actions_refreshed"); + } } - }; - /** - * Spreads a context change to all actions and to registered components - * by triggering ajaxplorer:actions_refreshed event. - */ - - Controller.prototype.fireContextChange = function fireContextChange() { - var crtNode = this._dataModel.getContextNode(); - this.actions.forEach((function (action) { - action.fireContextChange(this.usersEnabled, this.oUser, crtNode); - }).bind(this)); - if (this.localDataModel) { - this.notify("actions_refreshed"); - } else { - this._pydioObject.fire("actions_refreshed"); + /** + * Spreads a context change to all actions and to registered components + * by triggering ajaxplorer:actions_refreshed event. + */ + }, { + key: "fireContextChange", + value: function fireContextChange() { + var crtNode = this._dataModel.getContextNode(); + this.actions.forEach((function (action) { + action.fireContextChange(this.usersEnabled, this.oUser, crtNode); + }).bind(this)); + if (this.localDataModel) { + this.notify("actions_refreshed"); + } else { + this._pydioObject.fire("actions_refreshed"); + } } - }; - - /** - * Remove all actions - */ - Controller.prototype.removeActions = function removeActions() { - this.actions.forEach(function (action) { - action.remove(); - }); - this.actions = new Map(); - this.clearRegisteredKeys(); - }; - - /** - * Create actions from XML Registry - * @param registry DOMDocument - */ - - Controller.prototype.loadActionsFromRegistry = function loadActionsFromRegistry() { - var registry = arguments[0] === undefined ? null : arguments[0]; - - if (!registry) { - registry = pydio.getXmlRegistry(); - } - this.removeActions(); - this.parseActions(registry); - this._guiActions.forEach((function (act) { - this.registerAction(act); - }).bind(this)); - if (this.localDataModel) { - this.notify("actions_loaded"); - } else { - this._pydioObject.fire("actions_loaded", this.actions); + /** + * Remove all actions + */ + }, { + key: "removeActions", + value: function removeActions() { + this.actions.forEach(function (action) { + action.remove(); + }); + this.actions = new Map(); + this.clearRegisteredKeys(); } - this.fireContextChange(); - this.fireSelectionChange(); - }; - /** - * Registers an action to this manager (default, accesskey). - * @param action Action - */ + /** + * Create actions from XML Registry + * @param registry DOMDocument + */ + }, { + key: "loadActionsFromRegistry", + value: function loadActionsFromRegistry() { + var registry = arguments.length <= 0 || arguments[0] === undefined ? null : arguments[0]; + + if (!registry) { + registry = pydio.getXmlRegistry(); + } + this.removeActions(); + this.parseActions(registry); + this._guiActions.forEach((function (act) { + this.registerAction(act); + }).bind(this)); + if (this.localDataModel) { + this.notify("actions_loaded"); + } else { + this._pydioObject.fire("actions_loaded", this.actions); + } + this.fireContextChange(); + this.fireSelectionChange(); + } - Controller.prototype.registerAction = function registerAction(action) { - var actionName = action.options.name; - this.actions.set(actionName, action); - if (action.defaults) { - for (var key in action.defaults) { - if (action.defaults.hasOwnProperty(key)) { - this.defaultActions.set(key, actionName); + /** + * Registers an action to this manager (default, accesskey). + * @param action Action + */ + }, { + key: "registerAction", + value: function registerAction(action) { + var actionName = action.options.name; + this.actions.set(actionName, action); + if (action.defaults) { + for (var key in action.defaults) { + if (action.defaults.hasOwnProperty(key)) { + this.defaultActions.set(key, actionName); + } } } + if (action.options.hasAccessKey) { + this.registerKey(action.options.accessKey, actionName); + } + if (action.options.specialAccessKey) { + this.registerKey("key_" + action.options.specialAccessKey, actionName); + } + action.setManager(this); } - if (action.options.hasAccessKey) { - this.registerKey(action.options.accessKey, actionName); - } - if (action.options.specialAccessKey) { - this.registerKey("key_" + action.options.specialAccessKey, actionName); - } - action.setManager(this); - }; - /** - * Parse an XML action node and registers the action - * @param documentElement DOMNode The node to parse - */ - - Controller.prototype.parseActions = function parseActions(documentElement) { - var actions = XMLUtils.XPathSelectNodes(documentElement, "actions/action"); - for (var i = 0; i < actions.length; i++) { - if (actions[i].nodeName != "action") continue; - if (actions[i].getAttribute("enabled") == "false") continue; - var newAction = new Action(); - newAction.setManager(this); - newAction.createFromXML(actions[i]); - this.registerAction(newAction); + /** + * Parse an XML action node and registers the action + * @param documentElement DOMNode The node to parse + */ + }, { + key: "parseActions", + value: function parseActions(documentElement) { + var actions = XMLUtils.XPathSelectNodes(documentElement, "actions/action"); + for (var i = 0; i < actions.length; i++) { + if (actions[i].nodeName != 'action') continue; + if (actions[i].getAttribute('enabled') == 'false') continue; + var newAction = new Action(); + newAction.setManager(this); + newAction.createFromXML(actions[i]); + this.registerAction(newAction); + } } - }; - /** - * Find an action by its name - * @param actionName String - * @returns Action - */ - - Controller.prototype.getActionByName = function getActionByName(actionName) { - return this.actions.get(actionName); - }; + /** + * Find an action by its name + * @param actionName String + * @returns Action + */ + }, { + key: "getActionByName", + value: function getActionByName(actionName) { + return this.actions.get(actionName); + } + }]); return Controller; -})(Observable); \ No newline at end of file +})(Observable); diff --git a/core/src/plugins/gui.ajax/res/js/core/model/EmptyNodeProvider.js b/core/src/plugins/gui.ajax/res/js/core/model/EmptyNodeProvider.js index 11fd6e09eb..339be8bbc9 100644 --- a/core/src/plugins/gui.ajax/res/js/core/model/EmptyNodeProvider.js +++ b/core/src/plugins/gui.ajax/res/js/core/model/EmptyNodeProvider.js @@ -1,32 +1,41 @@ "use strict"; +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var EmptyNodeProvider = (function (_Observable) { + _inherits(EmptyNodeProvider, _Observable); + function EmptyNodeProvider() { _classCallCheck(this, EmptyNodeProvider); - _Observable.call(this); + _get(Object.getPrototypeOf(EmptyNodeProvider.prototype), "constructor", this).call(this); } - _inherits(EmptyNodeProvider, _Observable); - - EmptyNodeProvider.prototype.initProvider = function initProvider(properties) { - this.properties = properties; - }; - - /** - * - * @param node AjxpNode - * @param nodeCallback Function - * @param childCallback Function - */ - - EmptyNodeProvider.prototype.loadNode = function loadNode(node, nodeCallback, childCallback) {}; - - EmptyNodeProvider.prototype.loadLeafNodeSyncfunction = function loadLeafNodeSyncfunction(node, callback) {}; + _createClass(EmptyNodeProvider, [{ + key: "initProvider", + value: function initProvider(properties) { + this.properties = properties; + } + + /** + * + * @param node AjxpNode + * @param nodeCallback Function + * @param childCallback Function + */ + }, { + key: "loadNode", + value: function loadNode(node, nodeCallback, childCallback) {} + }, { + key: "loadLeafNodeSyncfunction", + value: function loadLeafNodeSyncfunction(node, callback) {} + }]); return EmptyNodeProvider; -})(Observable); \ No newline at end of file +})(Observable); diff --git a/core/src/plugins/gui.ajax/res/js/core/model/PydioDataModel.js b/core/src/plugins/gui.ajax/res/js/core/model/PydioDataModel.js index 0d4774be39..41be911ef3 100644 --- a/core/src/plugins/gui.ajax/res/js/core/model/PydioDataModel.js +++ b/core/src/plugins/gui.ajax/res/js/core/model/PydioDataModel.js @@ -23,11 +23,16 @@ */ "use strict"; +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +var _get = function get(_x5, _x6, _x7) { var _again = true; _function: while (_again) { var object = _x5, property = _x6, receiver = _x7; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x5 = parent; _x6 = property; _x7 = receiver; _again = true; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var PydioDataModel = (function (_Observable) { + _inherits(PydioDataModel, _Observable); /** * Constructor @@ -35,12 +40,12 @@ var PydioDataModel = (function (_Observable) { */ function PydioDataModel() { - var localEvents = arguments[0] === undefined ? true : arguments[0]; + var localEvents = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0]; _classCallCheck(this, PydioDataModel); - _Observable.call(this); - this._currentRep = "/"; + _get(Object.getPrototypeOf(PydioDataModel.prototype), "constructor", this).call(this); + this._currentRep = '/'; this._selectedNodes = []; this._bEmpty = true; this._globalEvents = !localEvents; @@ -56,733 +61,778 @@ var PydioDataModel = (function (_Observable) { this._rootNode = null; } - _inherits(PydioDataModel, _Observable); - /** * Sets the data source that will feed the nodes with children. * @param iAjxpNodeProvider IAjxpNodeProvider */ - PydioDataModel.prototype.setAjxpNodeProvider = function setAjxpNodeProvider(iAjxpNodeProvider) { - this._iAjxpNodeProvider = iAjxpNodeProvider; - }; - - /** - * Return the current data source provider - * @return IAjxpNodeProvider - */ - - PydioDataModel.prototype.getAjxpNodeProvider = function getAjxpNodeProvider() { - return this._iAjxpNodeProvider; - }; + _createClass(PydioDataModel, [{ + key: "setAjxpNodeProvider", + value: function setAjxpNodeProvider(iAjxpNodeProvider) { + this._iAjxpNodeProvider = iAjxpNodeProvider; + } - /** - * Changes the current context node. - * @param ajxpNode AjxpNode Target node, either an existing one or a fake one containing the target part. - * @param forceReload Boolean If set to true, the node will be reloaded even if already loaded. - */ + /** + * Return the current data source provider + * @return IAjxpNodeProvider + */ + }, { + key: "getAjxpNodeProvider", + value: function getAjxpNodeProvider() { + return this._iAjxpNodeProvider; + } - PydioDataModel.prototype.requireContextChange = function requireContextChange(ajxpNode) { - var forceReload = arguments[1] === undefined ? false : arguments[1]; - - if (ajxpNode == null) return; - var path = ajxpNode.getPath(); - if ((path == "" || path == "/") && ajxpNode != this._rootNode) { - ajxpNode = this._rootNode; - } - if (ajxpNode.getMetadata().has("paginationData") && ajxpNode.getMetadata().get("paginationData").has("new_page") && ajxpNode.getMetadata().get("paginationData").get("new_page") != ajxpNode.getMetadata().get("paginationData").get("current")) { - var paginationPage = ajxpNode.getMetadata().get("paginationData").get("new_page"); - forceReload = true; - } - if (ajxpNode != this._rootNode && (!ajxpNode.getParent() || ajxpNode.fake)) { - // Find in arbo or build fake arbo - var fakeNodes = []; - ajxpNode = ajxpNode.findInArbo(this._rootNode, fakeNodes); - if (fakeNodes.length) { - var firstFake = fakeNodes.shift(); - firstFake.observeOnce("first_load", (function (e) { - this.requireContextChange(ajxpNode); - }).bind(this)); - firstFake.observeOnce("error", (function (message) { - Logger.error(message); - firstFake.notify("node_removed"); - var parent = firstFake.getParent(); - parent.removeChild(firstFake); - //delete(firstFake); - this.requireContextChange(parent); - }).bind(this)); - this.publish("context_loading"); - firstFake.load(this._iAjxpNodeProvider); - return; + /** + * Changes the current context node. + * @param ajxpNode AjxpNode Target node, either an existing one or a fake one containing the target part. + * @param forceReload Boolean If set to true, the node will be reloaded even if already loaded. + */ + }, { + key: "requireContextChange", + value: function requireContextChange(ajxpNode) { + var forceReload = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; + + if (ajxpNode == null) return; + var path = ajxpNode.getPath(); + if ((path == "" || path == "/") && ajxpNode != this._rootNode) { + ajxpNode = this._rootNode; } - } - ajxpNode.observeOnce("loaded", (function () { - this.setContextNode(ajxpNode, true); - this.publish("context_loaded"); - if (this.getPendingSelection()) { - var selPath = ajxpNode.getPath() + (ajxpNode.getPath() == "/" ? "" : "/") + this.getPendingSelection(); - var selNode = ajxpNode.findChildByPath(selPath); - if (selNode) { - this.setSelectedNodes([selNode], this); - } else { - if (ajxpNode.getMetadata().get("paginationData") && arguments.length < 3) { - var newPage; - var currentPage = ajxpNode.getMetadata().get("paginationData").get("current"); - this.loadPathInfoSync(selPath, function (foundNode) { - newPage = foundNode.getMetadata().get("page_position"); - }); - if (newPage && newPage != currentPage) { - ajxpNode.getMetadata().get("paginationData").set("new_page", newPage); - this.requireContextChange(ajxpNode, true, true); - return; + if (ajxpNode.getMetadata().has('paginationData') && ajxpNode.getMetadata().get('paginationData').has('new_page') && ajxpNode.getMetadata().get('paginationData').get('new_page') != ajxpNode.getMetadata().get('paginationData').get('current')) { + var paginationPage = ajxpNode.getMetadata().get('paginationData').get('new_page'); + forceReload = true; + } + if (ajxpNode != this._rootNode && (!ajxpNode.getParent() || ajxpNode.fake)) { + // Find in arbo or build fake arbo + var fakeNodes = []; + ajxpNode = ajxpNode.findInArbo(this._rootNode, fakeNodes); + if (fakeNodes.length) { + var firstFake = fakeNodes.shift(); + firstFake.observeOnce("first_load", (function (e) { + this.requireContextChange(ajxpNode); + }).bind(this)); + firstFake.observeOnce("error", (function (message) { + Logger.error(message); + firstFake.notify("node_removed"); + var parent = firstFake.getParent(); + parent.removeChild(firstFake); + //delete(firstFake); + this.requireContextChange(parent); + }).bind(this)); + this.publish("context_loading"); + firstFake.load(this._iAjxpNodeProvider); + return; + } + } + ajxpNode.observeOnce("loaded", (function () { + this.setContextNode(ajxpNode, true); + this.publish("context_loaded"); + if (this.getPendingSelection()) { + var selPath = ajxpNode.getPath() + (ajxpNode.getPath() == "/" ? "" : "/") + this.getPendingSelection(); + var selNode = ajxpNode.findChildByPath(selPath); + if (selNode) { + this.setSelectedNodes([selNode], this); + } else { + if (ajxpNode.getMetadata().get("paginationData") && arguments.length < 3) { + var newPage; + var currentPage = ajxpNode.getMetadata().get("paginationData").get("current"); + this.loadPathInfoSync(selPath, function (foundNode) { + newPage = foundNode.getMetadata().get("page_position"); + }); + if (newPage && newPage != currentPage) { + ajxpNode.getMetadata().get("paginationData").set("new_page", newPage); + this.requireContextChange(ajxpNode, true, true); + return; + } } } + this.clearPendingSelection(); } - this.clearPendingSelection(); - } - }).bind(this)); - ajxpNode.observeOnce("error", (function (message) { - Logger.error(message); - this.publish("context_loaded"); - }).bind(this)); - this.publish("context_loading"); - try { - if (forceReload) { - if (paginationPage) { - ajxpNode.getMetadata().get("paginationData").set("current", paginationPage); + }).bind(this)); + ajxpNode.observeOnce("error", (function (message) { + Logger.error(message); + this.publish("context_loaded"); + }).bind(this)); + this.publish("context_loading"); + try { + if (forceReload) { + if (paginationPage) { + ajxpNode.getMetadata().get('paginationData').set('current', paginationPage); + } + ajxpNode.reload(this._iAjxpNodeProvider); + } else { + ajxpNode.load(this._iAjxpNodeProvider); } - ajxpNode.reload(this._iAjxpNodeProvider); - } else { - ajxpNode.load(this._iAjxpNodeProvider); + } catch (e) { + this.publish("context_loaded"); } - } catch (e) { - this.publish("context_loaded"); } - }; - - PydioDataModel.prototype.requireNodeReload = function requireNodeReload(nodeOrPath, completeCallback) { - if (nodeOrPath instanceof String) { - nodeOrPath = new AjxpNode(nodeOrPath); - } - var onComplete = null; - if (this._selectedNodes.length) { - var found = false; - this._selectedNodes.each(function (node) { - if (node.getPath() == nodeOrPath.getPath()) found = node; - }); - if (found) { - // MAKE SURE SELECTION IS OK AFTER RELOAD - this._selectedNodes = this._selectedNodes.without(found); - this.publish("selection_changed", this); - onComplete = (function (newNode) { - this._selectedNodes.push(newNode); - this._selectionSource = {}; + }, { + key: "requireNodeReload", + value: function requireNodeReload(nodeOrPath, completeCallback) { + if (nodeOrPath instanceof String) { + nodeOrPath = new AjxpNode(nodeOrPath); + } + var onComplete = null; + if (this._selectedNodes.length) { + var found = false; + this._selectedNodes.each(function (node) { + if (node.getPath() == nodeOrPath.getPath()) found = node; + }); + if (found) { + // MAKE SURE SELECTION IS OK AFTER RELOAD + this._selectedNodes = this._selectedNodes.without(found); this.publish("selection_changed", this); - if (completeCallback) completeCallback(newNode); - }).bind(this); + onComplete = (function (newNode) { + this._selectedNodes.push(newNode); + this._selectionSource = {}; + this.publish("selection_changed", this); + if (completeCallback) completeCallback(newNode); + }).bind(this); + } } + this._iAjxpNodeProvider.refreshNodeAndReplace(nodeOrPath, onComplete); } - this._iAjxpNodeProvider.refreshNodeAndReplace(nodeOrPath, onComplete); - }; - - PydioDataModel.prototype.loadPathInfoSync = function loadPathInfoSync(path, callback) { - this._iAjxpNodeProvider.loadLeafNodeSync(new AjxpNode(path), callback, false); - }; - - PydioDataModel.prototype.loadPathInfoAsync = function loadPathInfoAsync(path, callback) { - this._iAjxpNodeProvider.loadLeafNodeSync(new AjxpNode(path), callback, true); - }; - - /** - * Sets the root of the data store - * @param ajxpRootNode AjxpNode The parent node - */ - - PydioDataModel.prototype.setRootNode = function setRootNode(ajxpRootNode) { - this._rootNode = ajxpRootNode; - this._rootNode.setRoot(); - this._rootNode.observe("child_added", function (c) {}); - this.publish("root_node_changed", this._rootNode); - this.setContextNode(this._rootNode); - }; - - /** - * Gets the current root node - * @returns AjxpNode - */ - - PydioDataModel.prototype.getRootNode = function getRootNode() { - return this._rootNode; - }; - - /** - * Sets the current context node - * @param ajxpDataNode AjxpNode - * @param forceEvent Boolean If set to true, event will be triggered even if the current node is already the same. - */ - - PydioDataModel.prototype.setContextNode = function setContextNode(ajxpDataNode, forceEvent) { - if (this._contextNode && this._contextNode == ajxpDataNode && this._currentRep == ajxpDataNode.getPath() && !forceEvent) { - return; // No changes + }, { + key: "loadPathInfoSync", + value: function loadPathInfoSync(path, callback) { + this._iAjxpNodeProvider.loadLeafNodeSync(new AjxpNode(path), callback, false); } - if (!ajxpDataNode) return; - if (this._contextNodeReplacedObserver && this._contextNode) { - this._contextNode.stopObserving("node_replaced", this._contextNodeReplacedObserver); + }, { + key: "loadPathInfoAsync", + value: function loadPathInfoAsync(path, callback) { + this._iAjxpNodeProvider.loadLeafNodeSync(new AjxpNode(path), callback, true); } - this._contextNode = ajxpDataNode; - this._currentRep = ajxpDataNode.getPath(); - this.publish("context_changed", ajxpDataNode); - if (!this._contextNodeReplacedObserver) this._contextNodeReplacedObserver = this.contextNodeReplaced.bind(this); - ajxpDataNode.observe("node_replaced", this._contextNodeReplacedObserver); - }; - PydioDataModel.prototype.contextNodeReplaced = function contextNodeReplaced(newNode) { - this.setContextNode(newNode); - }; + /** + * Sets the root of the data store + * @param ajxpRootNode AjxpNode The parent node + */ + }, { + key: "setRootNode", + value: function setRootNode(ajxpRootNode) { + this._rootNode = ajxpRootNode; + this._rootNode.setRoot(); + this._rootNode.observe("child_added", function (c) { + //console.log(c); + }); + this.publish("root_node_changed", this._rootNode); + this.setContextNode(this._rootNode); + } - /** - * - */ + /** + * Gets the current root node + * @returns AjxpNode + */ + }, { + key: "getRootNode", + value: function getRootNode() { + return this._rootNode; + } - PydioDataModel.prototype.publish = function publish(eventName, optionalData) { - var args = []; - if (this._globalEvents) { - if (window.pydio) { - args.push(eventName); - if (optionalData) args.push(optionalData); - pydio.fire.apply(pydio, args); - } else if (document.fire) { - args.push("ajaxplorer:" + eventName); - if (optionalData) args.push(optionalData); - document.fire.apply(document, args); + /** + * Sets the current context node + * @param ajxpDataNode AjxpNode + * @param forceEvent Boolean If set to true, event will be triggered even if the current node is already the same. + */ + }, { + key: "setContextNode", + value: function setContextNode(ajxpDataNode, forceEvent) { + if (this._contextNode && this._contextNode == ajxpDataNode && this._currentRep == ajxpDataNode.getPath() && !forceEvent) { + return; // No changes } - if (optionalData) { - args = [eventName, { memo: optionalData }]; - } else { - args = [eventName]; - } - this.notify.apply(this, args); - } else { - if (optionalData) { - args = [eventName, { memo: optionalData }]; - } else { - args = [eventName]; + if (!ajxpDataNode) return; + if (this._contextNodeReplacedObserver && this._contextNode) { + this._contextNode.stopObserving("node_replaced", this._contextNodeReplacedObserver); } - this.notify.apply(this, args); + this._contextNode = ajxpDataNode; + this._currentRep = ajxpDataNode.getPath(); + this.publish("context_changed", ajxpDataNode); + if (!this._contextNodeReplacedObserver) this._contextNodeReplacedObserver = this.contextNodeReplaced.bind(this); + ajxpDataNode.observe("node_replaced", this._contextNodeReplacedObserver); + } + }, { + key: "contextNodeReplaced", + value: function contextNodeReplaced(newNode) { + this.setContextNode(newNode); } - }; - - /** - * Get the current context node - * @returns AjxpNode - */ - - PydioDataModel.prototype.getContextNode = function getContextNode() { - return this._contextNode; - }; - - /** - * After a copy or move operation, many nodes may have to be reloaded - * This function tries to reload them in the right order and if necessary. - * @param nodes AjxpNodes[] An array of nodes - */ - PydioDataModel.prototype.multipleNodesReload = function multipleNodesReload(nodes) { - for (var i = 0; i < nodes.length; i++) { - var nodePathOrNode = nodes[i]; - var node; - if (nodePathOrNode instanceof String) { - node = new AjxpNode(nodePathOrNode); - if (node.getPath() == this._rootNode.getPath()) node = this._rootNode;else node = node.findInArbo(this._rootNode, []); + /** + * + */ + }, { + key: "publish", + value: function publish(eventName, optionalData) { + var args = []; + if (this._globalEvents) { + if (window.pydio) { + args.push(eventName); + if (optionalData) args.push(optionalData); + pydio.fire.apply(pydio, args); + } else if (document.fire) { + args.push("ajaxplorer:" + eventName); + if (optionalData) args.push(optionalData); + document.fire.apply(document, args); + } + if (optionalData) { + args = [eventName, { memo: optionalData }]; + } else { + args = [eventName]; + } + this.notify.apply(this, args); } else { - node = nodePathOrNode; + if (optionalData) { + args = [eventName, { memo: optionalData }]; + } else { + args = [eventName]; + } + this.notify.apply(this, args); } - nodes[i] = node; } - var children = []; - nodes.sort(function (a, b) { - if (a.isParentOf(b)) { - children.push(b); - return -1; - } - if (a.isChildOf(b)) { - children.push(a); - return +1; - } - return 0; - }); - children.each(function (c) { - nodes = nodes.without(c); - }); - nodes.each(this.queueNodeReload.bind(this)); - this.nextNodeReloader(); - }; - - /** - * Add a node to the queue of nodes to reload. - * @param node AjxpNode - */ - PydioDataModel.prototype.queueNodeReload = function queueNodeReload(node) { - if (!this.queue) this.queue = []; - if (node) { - this.queue.push(node); + /** + * Get the current context node + * @returns AjxpNode + */ + }, { + key: "getContextNode", + value: function getContextNode() { + return this._contextNode; } - }; - - /** - * Queue processor for the nodes to reload - */ - PydioDataModel.prototype.nextNodeReloader = function nextNodeReloader() { - if (!this.queue.length) { - window.setTimeout((function () { - this.publish("context_changed", this._contextNode); - }).bind(this), 200); - return; - } - var next = this.queue.shift(); - var observer = this.nextNodeReloader.bind(this); - next.observeOnce("loaded", observer); - next.observeOnce("error", observer); - if (next == this._contextNode || next.isParentOf(this._contextNode)) { - this.requireContextChange(next, true); - } else { - next.reload(this._iAjxpNodeProvider); + /** + * After a copy or move operation, many nodes may have to be reloaded + * This function tries to reload them in the right order and if necessary. + * @param nodes AjxpNodes[] An array of nodes + */ + }, { + key: "multipleNodesReload", + value: function multipleNodesReload(nodes) { + for (var i = 0; i < nodes.length; i++) { + var nodePathOrNode = nodes[i]; + var node; + if (nodePathOrNode instanceof String) { + node = new AjxpNode(nodePathOrNode); + if (node.getPath() == this._rootNode.getPath()) node = this._rootNode;else node = node.findInArbo(this._rootNode, []); + } else { + node = nodePathOrNode; + } + nodes[i] = node; + } + var children = []; + nodes.sort(function (a, b) { + if (a.isParentOf(b)) { + children.push(b); + return -1; + } + if (a.isChildOf(b)) { + children.push(a); + return +1; + } + return 0; + }); + children.each(function (c) { + nodes = nodes.without(c); + }); + nodes.each(this.queueNodeReload.bind(this)); + this.nextNodeReloader(); } - }; - - /** - * Insert a node somewhere in the datamodel - * @param node AjxpNode - * @param setSelectedAfterAdd bool - */ - PydioDataModel.prototype.addNode = function addNode(node) { - var setSelectedAfterAdd = arguments[1] === undefined ? false : arguments[1]; - - var parentFake = new AjxpNode(PathUtils.getDirname(node.getPath())); - var parent = parentFake.findInArbo(this.getRootNode(), undefined); - if (!parent && PathUtils.getDirname(node.getPath()) == "") parent = this.getRootNode(); - if (parent) { - parent.addChild(node); - if (setSelectedAfterAdd && this.getContextNode() == parent) { - this.setSelectedNodes([node], {}); + /** + * Add a node to the queue of nodes to reload. + * @param node AjxpNode + */ + }, { + key: "queueNodeReload", + value: function queueNodeReload(node) { + if (!this.queue) this.queue = []; + if (node) { + this.queue.push(node); } } - }; - - /** - * Remove a node by path somewhere - * @param path string - */ - PydioDataModel.prototype.removeNodeByPath = function removeNodeByPath(path) { - var fake = new AjxpNode(path); - var n = fake.findInArbo(this.getRootNode(), undefined); - if (n) { - n.getParent().removeChild(n); - return true; + /** + * Queue processor for the nodes to reload + */ + }, { + key: "nextNodeReloader", + value: function nextNodeReloader() { + if (!this.queue.length) { + window.setTimeout((function () { + this.publish("context_changed", this._contextNode); + }).bind(this), 200); + return; + } + var next = this.queue.shift(); + var observer = this.nextNodeReloader.bind(this); + next.observeOnce("loaded", observer); + next.observeOnce("error", observer); + if (next == this._contextNode || next.isParentOf(this._contextNode)) { + this.requireContextChange(next, true); + } else { + next.reload(this._iAjxpNodeProvider); + } } - return false; - }; - - /** - * Update a node somewhere in the datamodel - * @param node AjxpNode - * @param setSelectedAfterUpdate bool - */ - PydioDataModel.prototype.updateNode = function updateNode(node) { - var setSelectedAfterUpdate = arguments[1] === undefined ? false : arguments[1]; - - var original = node.getMetadata().get("original_path"); - var fake, n; - if (original && original != node.getPath() && PathUtils.getDirname(original) != PathUtils.getDirname(node.getPath())) { - // Node was really moved to another folder - fake = new AjxpNode(original); - n = fake.findInArbo(this.getRootNode(), undefined); - if (n) { - n.getParent().removeChild(n); - } - var parentFake = new AjxpNode(getRepName(node.getPath())); + /** + * Insert a node somewhere in the datamodel + * @param node AjxpNode + * @param setSelectedAfterAdd bool + */ + }, { + key: "addNode", + value: function addNode(node) { + var setSelectedAfterAdd = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; + + var parentFake = new AjxpNode(PathUtils.getDirname(node.getPath())); var parent = parentFake.findInArbo(this.getRootNode(), undefined); - if (!parent && getRepName(node.getPath()) == "") parent = this.getRootNode(); + if (!parent && PathUtils.getDirname(node.getPath()) == "") parent = this.getRootNode(); if (parent) { - node.getMetadata().set("original_path", undefined); parent.addChild(node); - } - } else { - fake = new AjxpNode(original); - n = fake.findInArbo(this.getRootNode(), undefined); - if (n) { - node._isLoaded = n._isLoaded; - n.replaceBy(node, "override"); - if (setSelectedAfterUpdate && this.getContextNode() == n.getParent()) { - this.setSelectedNodes([n], {}); + if (setSelectedAfterAdd && this.getContextNode() == parent) { + this.setSelectedNodes([node], {}); } } } - }; - - /** - * Sets an array of nodes to be selected after the context is (re)loaded - * @param selection AjxpNode[] - */ - - PydioDataModel.prototype.setPendingSelection = function setPendingSelection(selection) { - this._pendingSelection = selection; - }; - - /** - * Gets the array of nodes to be selected after the context is (re)loaded - * @returns AjxpNode[] - */ - - PydioDataModel.prototype.getPendingSelection = function getPendingSelection() { - return this._pendingSelection; - }; - - /** - * Clears the nodes to be selected - */ - - PydioDataModel.prototype.clearPendingSelection = function clearPendingSelection() { - this._pendingSelection = null; - }; - /** - * Set an array of nodes as the current selection - * @param ajxpDataNodes AjxpNode[] The nodes to select - * @param source String The source of this selection action - */ - - PydioDataModel.prototype.setSelectedNodes = function setSelectedNodes(ajxpDataNodes, source) { - if (!source) { - this._selectionSource = {}; - } else { - this._selectionSource = source; - } - this._selectedNodes = ajxpDataNodes; - this._bEmpty = ajxpDataNodes && ajxpDataNodes.length ? false : true; - this._bFile = this._bDir = this._isRecycle = false; - this._bUnique = false; - if (!this._bEmpty) { - this._bUnique = ajxpDataNodes.length == 1; - for (var i = 0; i < ajxpDataNodes.length; i++) { - var selectedNode = ajxpDataNodes[i]; - if (selectedNode.isLeaf()) this._bFile = true;else this._bDir = true; - if (selectedNode.isRecycle()) this._isRecycle = true; + /** + * Remove a node by path somewhere + * @param path string + */ + }, { + key: "removeNodeByPath", + value: function removeNodeByPath(path) { + var fake = new AjxpNode(path); + var n = fake.findInArbo(this.getRootNode(), undefined); + if (n) { + n.getParent().removeChild(n); + return true; } + return false; } - this.publish("selection_changed", this); - }; - - /** - * Gets the currently selected nodes - * @returns AjxpNode[] - */ - - PydioDataModel.prototype.getSelectedNodes = function getSelectedNodes() { - return this._selectedNodes; - }; - - /** - * Gets the source of the last selection action - * @returns String - */ - - PydioDataModel.prototype.getSelectionSource = function getSelectionSource() { - return this._selectionSource; - }; - - /** - * Manually sets the source of the selection - * @param object - */ - - PydioDataModel.prototype.setSelectionSource = function setSelectionSource(object) { - this._selectionSource = object; - }; - - /** - * DEPRECATED - */ - PydioDataModel.prototype.getSelectedItems = function getSelectedItems() { - throw new Error("Deprecated : use getSelectedNodes() instead"); - }; - - /** - * Select all the children of the current context node - */ - - PydioDataModel.prototype.selectAll = function selectAll() { - var nodes = []; - var childrenMap = this._contextNode.getChildren(); - childrenMap.forEach(function (child) { - nodes.push(child); - }); - this.setSelectedNodes(nodes, "dataModel"); - }; - - /** - * Whether the selection is empty - * @returns Boolean - */ - - PydioDataModel.prototype.isEmpty = function isEmpty() { - return this._selectedNodes ? this._selectedNodes.length == 0 : true; - }; - - PydioDataModel.prototype.hasReadOnly = function hasReadOnly() { - var test = false; - try { - this._selectedNodes.forEach(function (node) { - if (node.hasMetadataInBranch("ajxp_readonly", "true")) { - test = true; - throw $break; + /** + * Update a node somewhere in the datamodel + * @param node AjxpNode + * @param setSelectedAfterUpdate bool + */ + }, { + key: "updateNode", + value: function updateNode(node) { + var setSelectedAfterUpdate = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; + + var original = node.getMetadata().get("original_path"); + var fake, n; + if (original && original != node.getPath() && PathUtils.getDirname(original) != PathUtils.getDirname(node.getPath())) { + // Node was really moved to another folder + fake = new AjxpNode(original); + n = fake.findInArbo(this.getRootNode(), undefined); + if (n) { + n.getParent().removeChild(n); } - }); - } catch (e) {} - return test; - }; - - PydioDataModel.prototype.selectionHasRootNode = function selectionHasRootNode() { - var found = false; - try { - this._selectedNodes.forEach(function (el) { - if (el.isRoot()) { - found = true; - throw new Error(); + var parentFake = new AjxpNode(getRepName(node.getPath())); + var parent = parentFake.findInArbo(this.getRootNode(), undefined); + if (!parent && getRepName(node.getPath()) == "") parent = this.getRootNode(); + if (parent) { + node.getMetadata().set("original_path", undefined); + parent.addChild(node); } - }); - } catch (e) {} - }; - - /** - * Whether the selection is unique - * @returns Boolean - */ - - PydioDataModel.prototype.isUnique = function isUnique() { - return this._bUnique; - }; - - /** - * Whether the selection has a file selected. - * Should be hasLeaf - * @returns Boolean - */ + } else { + fake = new AjxpNode(original); + n = fake.findInArbo(this.getRootNode(), undefined); + if (n) { + node._isLoaded = n._isLoaded; + n.replaceBy(node, "override"); + if (setSelectedAfterUpdate && this.getContextNode() == n.getParent()) { + this.setSelectedNodes([n], {}); + } + } + } + } - PydioDataModel.prototype.hasFile = function hasFile() { - return this._bFile; - }; + /** + * Sets an array of nodes to be selected after the context is (re)loaded + * @param selection AjxpNode[] + */ + }, { + key: "setPendingSelection", + value: function setPendingSelection(selection) { + this._pendingSelection = selection; + } - /** - * Whether the selection has a dir selected - * @returns Boolean - */ + /** + * Gets the array of nodes to be selected after the context is (re)loaded + * @returns AjxpNode[] + */ + }, { + key: "getPendingSelection", + value: function getPendingSelection() { + return this._pendingSelection; + } - PydioDataModel.prototype.hasDir = function hasDir() { - return this._bDir; - }; + /** + * Clears the nodes to be selected + */ + }, { + key: "clearPendingSelection", + value: function clearPendingSelection() { + this._pendingSelection = null; + } - /** - * Whether the current context is the recycle bin - * @returns Boolean - */ + /** + * Set an array of nodes as the current selection + * @param ajxpDataNodes AjxpNode[] The nodes to select + * @param source String The source of this selection action + */ + }, { + key: "setSelectedNodes", + value: function setSelectedNodes(ajxpDataNodes, source) { + if (!source) { + this._selectionSource = {}; + } else { + this._selectionSource = source; + } + this._selectedNodes = ajxpDataNodes; + this._bEmpty = ajxpDataNodes && ajxpDataNodes.length ? false : true; + this._bFile = this._bDir = this._isRecycle = false; + this._bUnique = false; + if (!this._bEmpty) { + this._bUnique = ajxpDataNodes.length == 1; + for (var i = 0; i < ajxpDataNodes.length; i++) { + var selectedNode = ajxpDataNodes[i]; + if (selectedNode.isLeaf()) this._bFile = true;else this._bDir = true; + if (selectedNode.isRecycle()) this._isRecycle = true; + } + } + this.publish("selection_changed", this); + } - PydioDataModel.prototype.isRecycle = function isRecycle() { - return this._isRecycle; - }; + /** + * Gets the currently selected nodes + * @returns AjxpNode[] + */ + }, { + key: "getSelectedNodes", + value: function getSelectedNodes() { + return this._selectedNodes; + } - /** - * Whether the selection has more than one node selected - * @returns Boolean - */ + /** + * Gets the source of the last selection action + * @returns String + */ + }, { + key: "getSelectionSource", + value: function getSelectionSource() { + return this._selectionSource; + } - PydioDataModel.prototype.isMultiple = function isMultiple() { - return this._selectedNodes && this._selectedNodes.length > 1; - }; + /** + * Manually sets the source of the selection + * @param object + */ + }, { + key: "setSelectionSource", + value: function setSelectionSource(object) { + this._selectionSource = object; + } - /** - * Whether the selection has a file with one of the mimes - * @param mimeTypes Array Array of mime types - * @returns Boolean - */ + /** + * DEPRECATED + */ + }, { + key: "getSelectedItems", + value: function getSelectedItems() { + throw new Error("Deprecated : use getSelectedNodes() instead"); + } - PydioDataModel.prototype.hasMime = function hasMime(mimeTypes) { - if (mimeTypes.length == 1 && mimeTypes[0] == "*") return true; - var has = false; - mimeTypes.each((function (mime) { - if (has) return; - has = this._selectedNodes.any(function (node) { - return getAjxpMimeType(node) == mime; + /** + * Select all the children of the current context node + */ + }, { + key: "selectAll", + value: function selectAll() { + var nodes = []; + var childrenMap = this._contextNode.getChildren(); + childrenMap.forEach(function (child) { + nodes.push(child); }); - }).bind(this)); - return has; - }; - - /** - * Get all selected filenames as an array. - * @param separator String Is a separator, will return a string joined - * @returns Array|String|bool - */ - - PydioDataModel.prototype.getFileNames = function getFileNames(separator) { - if (!this._selectedNodes.length) { - alert("Please select a file!"); - return false; - } - var tmp = new Array(this._selectedNodes.length); - for (var i = 0; i < this._selectedNodes.length; i++) { - tmp[i] = this._selectedNodes[i].getPath(); - } - if (separator) { - return tmp.join(separator); - } else { - return tmp; + this.setSelectedNodes(nodes, "dataModel"); } - }; - /** - * Get all the filenames of the current context node children - * @param separator String If passed, will join the array as a string - * @return Array|String|bool - */ - - PydioDataModel.prototype.getContextFileNames = function getContextFileNames(separator) { - var allItems = this._contextNode.getChildren(); - if (!allItems.length) { - return false; + /** + * Whether the selection is empty + * @returns Boolean + */ + }, { + key: "isEmpty", + value: function isEmpty() { + return this._selectedNodes ? this._selectedNodes.length == 0 : true; } - var names = []; - for (var i = 0; i < allItems.length; i++) { - names.push(getBaseName(allItems[i].getPath())); - } - if (separator) { - return names.join(separator); - } else { - return names; - } - }; - - /** - * Whether the context node has a child with this basename - * @param newFileName String The name to check - * @returns Boolean - * @param local - * @param contextNode - */ - - PydioDataModel.prototype.fileNameExists = function fileNameExists(newFileName, local, contextNode) { - if (!contextNode) { - contextNode = this._contextNode; + }, { + key: "hasReadOnly", + value: function hasReadOnly() { + var test = false; + try { + this._selectedNodes.forEach(function (node) { + if (node.hasMetadataInBranch("ajxp_readonly", "true")) { + test = true; + throw $break; + } + }); + } catch (e) {} + return test; } - if (local) { - var test = (contextNode.getPath() == "/" ? "" : contextNode.getPath()) + "/" + newFileName; + }, { + key: "selectionHasRootNode", + value: function selectionHasRootNode() { var found = false; try { - contextNode.getChildren().forEach(function (c) { - if (c.getPath() == test) { + this._selectedNodes.forEach(function (el) { + if (el.isRoot()) { found = true; throw new Error(); } }); } catch (e) {} - return found; - } else { - var nodeExists = false; - this.loadPathInfoSync(contextNode.getPath() + "/" + newFileName, function (foundNode) { - nodeExists = true; - }); - return nodeExists; } - }; - PydioDataModel.prototype.applyCheckHook = function applyCheckHook(node) { - "use strict"; - var client = PydioApi.getClient(); - var result; - client.applyCheckHook(node, "before_create", node.getMetadata().get("filesize") || -1, function (transport) { - result = pydio.getController().parseXmlMessage(transport.responseXML); - }); - if (result === false) { - throw new Error("Check failed"); + /** + * Whether the selection is unique + * @returns Boolean + */ + }, { + key: "isUnique", + value: function isUnique() { + return this._bUnique; } - }; - /** - * Gets the first name of the current selection - * @returns String - */ + /** + * Whether the selection has a file selected. + * Should be hasLeaf + * @returns Boolean + */ + }, { + key: "hasFile", + value: function hasFile() { + return this._bFile; + } - PydioDataModel.prototype.getUniqueFileName = function getUniqueFileName() { - if (this.getFileNames().length) return this.getFileNames()[0]; - return null; - }; + /** + * Whether the selection has a dir selected + * @returns Boolean + */ + }, { + key: "hasDir", + value: function hasDir() { + return this._bDir; + } - /** - * Gets the first node of the selection, or Null - * @returns AjxpNode - */ + /** + * Whether the current context is the recycle bin + * @returns Boolean + */ + }, { + key: "isRecycle", + value: function isRecycle() { + return this._isRecycle; + } - PydioDataModel.prototype.getUniqueNode = function getUniqueNode() { - if (this._selectedNodes.length) { - return this._selectedNodes[0]; + /** + * Whether the selection has more than one node selected + * @returns Boolean + */ + }, { + key: "isMultiple", + value: function isMultiple() { + return this._selectedNodes && this._selectedNodes.length > 1; } - return null; - }; - /** - * Gets a node from the current selection - * @param i Integer the node index - * @returns AjxpNode - */ + /** + * Whether the selection has a file with one of the mimes + * @param mimeTypes Array Array of mime types + * @returns Boolean + */ + }, { + key: "hasMime", + value: function hasMime(mimeTypes) { + if (mimeTypes.length == 1 && mimeTypes[0] == "*") return true; + var has = false; + mimeTypes.each((function (mime) { + if (has) return; + has = this._selectedNodes.any(function (node) { + return getAjxpMimeType(node) == mime; + }); + }).bind(this)); + return has; + } - PydioDataModel.prototype.getNode = function getNode(i) { - return this._selectedNodes[i]; - }; + /** + * Get all selected filenames as an array. + * @param separator String Is a separator, will return a string joined + * @returns Array|String|bool + */ + }, { + key: "getFileNames", + value: function getFileNames(separator) { + if (!this._selectedNodes.length) { + alert('Please select a file!'); + return false; + } + var tmp = new Array(this._selectedNodes.length); + for (var i = 0; i < this._selectedNodes.length; i++) { + tmp[i] = this._selectedNodes[i].getPath(); + } + if (separator) { + return tmp.join(separator); + } else { + return tmp; + } + } - /** - * Will add the current selection nodes as serializable data to the element passed : - * either as hidden input elements if it's a form, or as query parameters if it's an url - * @param oFormElement HTMLForm The form - * @param sUrl String An url to complete - * @returns String - */ + /** + * Get all the filenames of the current context node children + * @param separator String If passed, will join the array as a string + * @return Array|String|bool + */ + }, { + key: "getContextFileNames", + value: function getContextFileNames(separator) { + var allItems = this._contextNode.getChildren(); + if (!allItems.length) { + return false; + } + var names = []; + for (var i = 0; i < allItems.length; i++) { + names.push(getBaseName(allItems[i].getPath())); + } + if (separator) { + return names.join(separator); + } else { + return names; + } + } - PydioDataModel.prototype.updateFormOrUrl = function updateFormOrUrl(oFormElement, sUrl) { - // CLEAR FROM PREVIOUS ACTIONS! - if (oFormElement) { - $(oFormElement).select("input[type=\"hidden\"]").each(function (element) { - if (element.name == "nodes[]" || element.name == "file") element.remove(); + /** + * Whether the context node has a child with this basename + * @param newFileName String The name to check + * @returns Boolean + * @param local + * @param contextNode + */ + }, { + key: "fileNameExists", + value: function fileNameExists(newFileName, local, contextNode) { + if (!contextNode) { + contextNode = this._contextNode; + } + if (local) { + var test = (contextNode.getPath() == "/" ? "" : contextNode.getPath()) + "/" + newFileName; + var found = false; + try { + contextNode.getChildren().forEach(function (c) { + if (c.getPath() == test) { + found = true; + throw new Error(); + } + }); + } catch (e) {} + return found; + } else { + var nodeExists = false; + this.loadPathInfoSync(contextNode.getPath() + "/" + newFileName, function (foundNode) { + nodeExists = true; + }); + return nodeExists; + } + } + }, { + key: "applyCheckHook", + value: function applyCheckHook(node) { + "use strict"; + var client = PydioApi.getClient(); + var result; + client.applyCheckHook(node, "before_create", node.getMetadata().get("filesize") || -1, function (transport) { + result = pydio.getController().parseXmlMessage(transport.responseXML); }); + if (result === false) { + throw new Error("Check failed"); + } } - // UPDATE THE 'DIR' FIELDS - if (oFormElement && oFormElement["rep"]) oFormElement["rep"].value = this._currentRep; - sUrl += "&dir=" + encodeURIComponent(this._currentRep); - // UPDATE THE 'file' FIELDS - if (this.isEmpty()) return sUrl; - var fileNames = this.getFileNames(); - for (var i = 0; i < fileNames.length; i++) { - sUrl += "&" + "nodes[]=" + encodeURIComponent(fileNames[i]); - if (oFormElement) this._addHiddenField(oFormElement, "nodes[]", fileNames[i]); + /** + * Gets the first name of the current selection + * @returns String + */ + }, { + key: "getUniqueFileName", + value: function getUniqueFileName() { + if (this.getFileNames().length) return this.getFileNames()[0]; + return null; } - if (fileNames.length == 1) { - sUrl += "&" + "file=" + encodeURIComponent(fileNames[0]); - if (oFormElement) this._addHiddenField(oFormElement, "file", fileNames[0]); + + /** + * Gets the first node of the selection, or Null + * @returns AjxpNode + */ + }, { + key: "getUniqueNode", + value: function getUniqueNode() { + if (this._selectedNodes.length) { + return this._selectedNodes[0]; + } + return null; } - return sUrl; - }; - PydioDataModel.prototype._addHiddenField = function _addHiddenField(oFormElement, sFieldName, sFieldValue) { - oFormElement.insert(new Element("input", { type: "hidden", name: sFieldName, value: sFieldValue })); - }; + /** + * Gets a node from the current selection + * @param i Integer the node index + * @returns AjxpNode + */ + }, { + key: "getNode", + value: function getNode(i) { + return this._selectedNodes[i]; + } + + /** + * Will add the current selection nodes as serializable data to the element passed : + * either as hidden input elements if it's a form, or as query parameters if it's an url + * @param oFormElement HTMLForm The form + * @param sUrl String An url to complete + * @returns String + */ + }, { + key: "updateFormOrUrl", + value: function updateFormOrUrl(oFormElement, sUrl) { + // CLEAR FROM PREVIOUS ACTIONS! + if (oFormElement) { + $(oFormElement).select('input[type="hidden"]').each(function (element) { + if (element.name == "nodes[]" || element.name == "file") element.remove(); + }); + } + // UPDATE THE 'DIR' FIELDS + if (oFormElement && oFormElement['rep']) oFormElement['rep'].value = this._currentRep; + sUrl += '&dir=' + encodeURIComponent(this._currentRep); + + // UPDATE THE 'file' FIELDS + if (this.isEmpty()) return sUrl; + var fileNames = this.getFileNames(); + for (var i = 0; i < fileNames.length; i++) { + sUrl += '&' + 'nodes[]=' + encodeURIComponent(fileNames[i]); + if (oFormElement) this._addHiddenField(oFormElement, 'nodes[]', fileNames[i]); + } + if (fileNames.length == 1) { + sUrl += '&' + 'file=' + encodeURIComponent(fileNames[0]); + if (oFormElement) this._addHiddenField(oFormElement, 'file', fileNames[0]); + } + return sUrl; + } + }, { + key: "_addHiddenField", + value: function _addHiddenField(oFormElement, sFieldName, sFieldValue) { + oFormElement.insert(new Element('input', { type: 'hidden', name: sFieldName, value: sFieldValue })); + } + }]); return PydioDataModel; })(Observable); - -//console.log(c); \ No newline at end of file diff --git a/core/src/plugins/gui.ajax/res/js/core/model/Registry.js b/core/src/plugins/gui.ajax/res/js/core/model/Registry.js index 84fce4d187..5e5eec6586 100644 --- a/core/src/plugins/gui.ajax/res/js/core/model/Registry.js +++ b/core/src/plugins/gui.ajax/res/js/core/model/Registry.js @@ -19,6 +19,8 @@ */ "use strict"; +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Registry = (function () { @@ -32,305 +34,321 @@ var Registry = (function () { this._stateLoading = false; } - Registry.prototype.loadFromString = function loadFromString(s) { - this._registry = XMLUtils.parseXml(s).documentElement; - }; - - Registry.prototype.load = function load(sync, xPath, completeFunc, repositoryId) { - if (this._stateLoading) { - return; + _createClass(Registry, [{ + key: "loadFromString", + value: function loadFromString(s) { + this._registry = XMLUtils.parseXml(s).documentElement; } - this._stateLoading = true; - var onComplete = (function (transport) { - this._stateLoading = false; - if (transport.responseXML == null || transport.responseXML.documentElement == null) return; - if (transport.responseXML.documentElement.nodeName == "ajxp_registry") { - this._registry = transport.responseXML.documentElement; - //modal.updateLoadingProgress('XML Registry loaded'); - if (!sync && !completeFunc) { - this._pydioObject.fire("registry_loaded", this._registry); - } - } else if (transport.responseXML.documentElement.nodeName == "ajxp_registry_part") { - this.refreshXmlRegistryPart(transport.responseXML.documentElement); + }, { + key: "load", + value: function load(sync, xPath, completeFunc, repositoryId) { + if (this._stateLoading) { + return; } - if (completeFunc) completeFunc(this._registry); - }).bind(this); - var params = { get_action: "get_xml_registry" }; - if (xPath) { - params["xPath"] = xPath; - } - if (repositoryId) { - params["ws_id"] = repositoryId; // for caching only - } - PydioApi.getClient().request(params, onComplete, null, { - async: !sync, - method: "get" - }); - }; - - /** - * Inserts a document fragment retrieved from server inside the full tree. - * The node must contains the xPath attribute to locate it inside the registry. - * Event ajaxplorer:registry_part_loaded is triggerd once this is done. - * @param documentElement DOMNode - */ - - Registry.prototype.refreshXmlRegistryPart = function refreshXmlRegistryPart(documentElement) { - var xPath = documentElement.getAttribute("xPath"); - var existingNode = XMLUtils.XPathSelectSingleNode(this._registry, xPath); - var parentNode; - if (existingNode && existingNode.parentNode) { - parentNode = existingNode.parentNode; - parentNode.removeChild(existingNode); - if (documentElement.firstChild) { - parentNode.appendChild(documentElement.firstChild.cloneNode(true)); + this._stateLoading = true; + var onComplete = (function (transport) { + this._stateLoading = false; + if (transport.responseXML == null || transport.responseXML.documentElement == null) return; + if (transport.responseXML.documentElement.nodeName == "ajxp_registry") { + this._registry = transport.responseXML.documentElement; + //modal.updateLoadingProgress('XML Registry loaded'); + if (!sync && !completeFunc) { + this._pydioObject.fire("registry_loaded", this._registry); + } + } else if (transport.responseXML.documentElement.nodeName == "ajxp_registry_part") { + this.refreshXmlRegistryPart(transport.responseXML.documentElement); + } + if (completeFunc) completeFunc(this._registry); + }).bind(this); + var params = { get_action: 'get_xml_registry' }; + if (xPath) { + params['xPath'] = xPath; } - } else if (xPath.indexOf("/") > -1) { - // try selecting parentNode - var parentPath = xPath.substring(0, xPath.lastIndexOf("/")); - parentNode = XMLUtils.XPathSelectSingleNode(this._registry, parentPath); - if (parentNode && documentElement.firstChild) { - parentNode.appendChild(documentElement.firstChild.cloneNode(true)); + if (repositoryId) { + params['ws_id'] = repositoryId; // for caching only } - } else { - if (documentElement.firstChild) this._registry.appendChild(documentElement.firstChild.cloneNode(true)); + PydioApi.getClient().request(params, onComplete, null, { + async: !sync, + method: 'get' + }); } - this._pydioObject.fire("registry_part_loaded", xPath); - }; - - /** - * Translate the XML answer to a new User object - * @param skipEvent Boolean Whether to skip the sending of ajaxplorer:user_logged event. - */ - Registry.prototype.logXmlUser = function logXmlUser(skipEvent) { - this._pydioObject.user = null; - var userNode; - if (this._registry) { - userNode = XMLUtils.XPathSelectSingleNode(this._registry, "user"); - } - if (userNode) { - var userId = userNode.getAttribute("id"); - var children = userNode.childNodes; - if (userId) { - this._pydioObject.user = new User(userId, children); + /** + * Inserts a document fragment retrieved from server inside the full tree. + * The node must contains the xPath attribute to locate it inside the registry. + * Event ajaxplorer:registry_part_loaded is triggerd once this is done. + * @param documentElement DOMNode + */ + }, { + key: "refreshXmlRegistryPart", + value: function refreshXmlRegistryPart(documentElement) { + var xPath = documentElement.getAttribute("xPath"); + var existingNode = XMLUtils.XPathSelectSingleNode(this._registry, xPath); + var parentNode; + if (existingNode && existingNode.parentNode) { + parentNode = existingNode.parentNode; + parentNode.removeChild(existingNode); + if (documentElement.firstChild) { + parentNode.appendChild(documentElement.firstChild.cloneNode(true)); + } + } else if (xPath.indexOf("/") > -1) { + // try selecting parentNode + var parentPath = xPath.substring(0, xPath.lastIndexOf("/")); + parentNode = XMLUtils.XPathSelectSingleNode(this._registry, parentPath); + if (parentNode && documentElement.firstChild) { + parentNode.appendChild(documentElement.firstChild.cloneNode(true)); + } + } else { + if (documentElement.firstChild) this._registry.appendChild(documentElement.firstChild.cloneNode(true)); } + this._pydioObject.fire("registry_part_loaded", xPath); } - if (!skipEvent) { - this._pydioObject.fire("user_logged", this._pydioObject.user); - } - }; - Registry.prototype.getXML = function getXML() { - return this._registry; - }; - - /** - * Find Extension initialisation nodes (activeCondition, onInit, etc), parses - * the XML and execute JS. - * @param xmlNode DOMNode The extension node - * @param extensionDefinition Object Information already collected about this extension - * @returns Boolean - */ - - Registry.prototype.initExtension = function initExtension(xmlNode, extensionDefinition) { - var activeCondition = XMLUtils.XPathSelectSingleNode(xmlNode, "processing/activeCondition"); - if (activeCondition && activeCondition.firstChild) { - try { - var func = new Function(activeCondition.firstChild.nodeValue.trim()); - if (func() === false) return false; - } catch (e) {} - } - if (xmlNode.nodeName == "editor") { - var properties = { - openable: xmlNode.getAttribute("openable") == "true", - modalOnly: xmlNode.getAttribute("modalOnly") == "true", - previewProvider: xmlNode.getAttribute("previewProvider") == "true", - order: xmlNode.getAttribute("order") ? parseInt(xmlNode.getAttribute("order")) : 0, - formId: xmlNode.getAttribute("formId") || null, - text: this._pydioObject.MessageHash[xmlNode.getAttribute("text")], - title: this._pydioObject.MessageHash[xmlNode.getAttribute("title")], - icon: xmlNode.getAttribute("icon"), - icon_class: xmlNode.getAttribute("iconClass"), - editorClass: xmlNode.getAttribute("className"), - mimes: xmlNode.getAttribute("mimes").split(","), - write: xmlNode.getAttribute("write") && xmlNode.getAttribute("write") == "true" ? true : false - }; - for (var k in properties) { - if (properties.hasOwnProperty(k)) { - extensionDefinition[k] = properties[k]; - } - } - } else if (xmlNode.nodeName == "uploader") { - var th = this._pydioObject.Parameters.get("theme"); - var clientForm = XMLUtils.XPathSelectSingleNode(xmlNode, "processing/clientForm[@theme=\"" + th + "\"]"); - if (!clientForm) { - clientForm = XMLUtils.XPathSelectSingleNode(xmlNode, "processing/clientForm"); - } - if (clientForm && clientForm.firstChild && clientForm.getAttribute("id")) { - extensionDefinition.formId = clientForm.getAttribute("id"); - this._pydioObject.UI.insertForm(clientForm.getAttribute("id"), clientForm.firstChild.nodeValue); - } - if (xmlNode.getAttribute("order")) { - extensionDefinition.order = parseInt(xmlNode.getAttribute("order")); - } else { - extensionDefinition.order = 0; + /** + * Translate the XML answer to a new User object + * @param skipEvent Boolean Whether to skip the sending of ajaxplorer:user_logged event. + */ + }, { + key: "logXmlUser", + value: function logXmlUser(skipEvent) { + this._pydioObject.user = null; + var userNode; + if (this._registry) { + userNode = XMLUtils.XPathSelectSingleNode(this._registry, "user"); } - var extensionOnInit = XMLUtils.XPathSelectSingleNode(xmlNode, "processing/extensionOnInit"); - if (extensionOnInit && extensionOnInit.firstChild) { - try { - // @TODO: THIS WILL LIKELY TRIGGER PROTOTYPE CODE - eval(extensionOnInit.firstChild.nodeValue); - } catch (e) { - Logger.error("Ignoring Error in extensionOnInit code:"); - Logger.error(extensionOnInit.firstChild.nodeValue); + if (userNode) { + var userId = userNode.getAttribute('id'); + var children = userNode.childNodes; + if (userId) { + this._pydioObject.user = new User(userId, children); } } - var dialogOnOpen = XMLUtils.XPathSelectSingleNode(xmlNode, "processing/dialogOnOpen"); - if (dialogOnOpen && dialogOnOpen.firstChild) { - extensionDefinition.dialogOnOpen = dialogOnOpen.firstChild.nodeValue; - } - var dialogOnComplete = XMLUtils.XPathSelectSingleNode(xmlNode, "processing/dialogOnComplete"); - if (dialogOnComplete && dialogOnComplete.firstChild) { - extensionDefinition.dialogOnComplete = dialogOnComplete.firstChild.nodeValue; + if (!skipEvent) { + this._pydioObject.fire("user_logged", this._pydioObject.user); } } - return true; - }; - - /** - * Refresh the currently active extensions - * Extensions are editors and uploaders for the moment. - */ + }, { + key: "getXML", + value: function getXML() { + return this._registry; + } - Registry.prototype.refreshExtensionsRegistry = function refreshExtensionsRegistry() { - this._extensionsRegistry = { "editor": [], "uploader": [] }; - var extensions = XMLUtils.XPathSelectNodes(this._registry, "plugins/editor|plugins/uploader"); - for (var i = 0; i < extensions.length; i++) { - var extensionDefinition = { - id: extensions[i].getAttribute("id"), - xmlNode: extensions[i], - resourcesManager: new ResourcesManager() - }; - this._resourcesRegistry[extensionDefinition.id] = extensionDefinition.resourcesManager; - var resourceNodes = XMLUtils.XPathSelectNodes(extensions[i], "client_settings/resources|dependencies|clientForm"); - for (var j = 0; j < resourceNodes.length; j++) { - var child = resourceNodes[j]; - extensionDefinition.resourcesManager.loadFromXmlNode(child); + /** + * Find Extension initialisation nodes (activeCondition, onInit, etc), parses + * the XML and execute JS. + * @param xmlNode DOMNode The extension node + * @param extensionDefinition Object Information already collected about this extension + * @returns Boolean + */ + }, { + key: "initExtension", + value: function initExtension(xmlNode, extensionDefinition) { + var activeCondition = XMLUtils.XPathSelectSingleNode(xmlNode, 'processing/activeCondition'); + if (activeCondition && activeCondition.firstChild) { + try { + var func = new Function(activeCondition.firstChild.nodeValue.trim()); + if (func() === false) return false; + } catch (e) {} } - if (this.initExtension(extensions[i], extensionDefinition)) { - this._extensionsRegistry[extensions[i].nodeName].push(extensionDefinition); + if (xmlNode.nodeName == 'editor') { + var properties = { + openable: xmlNode.getAttribute("openable") == "true", + modalOnly: xmlNode.getAttribute("modalOnly") == "true", + previewProvider: xmlNode.getAttribute("previewProvider") == "true", + order: xmlNode.getAttribute("order") ? parseInt(xmlNode.getAttribute("order")) : 0, + formId: xmlNode.getAttribute("formId") || null, + text: this._pydioObject.MessageHash[xmlNode.getAttribute("text")], + title: this._pydioObject.MessageHash[xmlNode.getAttribute("title")], + icon: xmlNode.getAttribute("icon"), + icon_class: xmlNode.getAttribute("iconClass"), + editorClass: xmlNode.getAttribute("className"), + mimes: xmlNode.getAttribute("mimes").split(","), + write: xmlNode.getAttribute("write") && xmlNode.getAttribute("write") == "true" ? true : false + }; + for (var k in properties) { + if (properties.hasOwnProperty(k)) { + extensionDefinition[k] = properties[k]; + } + } + } else if (xmlNode.nodeName == 'uploader') { + var th = this._pydioObject.Parameters.get('theme'); + var clientForm = XMLUtils.XPathSelectSingleNode(xmlNode, 'processing/clientForm[@theme="' + th + '"]'); + if (!clientForm) { + clientForm = XMLUtils.XPathSelectSingleNode(xmlNode, 'processing/clientForm'); + } + if (clientForm && clientForm.firstChild && clientForm.getAttribute('id')) { + extensionDefinition.formId = clientForm.getAttribute('id'); + this._pydioObject.UI.insertForm(clientForm.getAttribute('id'), clientForm.firstChild.nodeValue); + } + if (xmlNode.getAttribute("order")) { + extensionDefinition.order = parseInt(xmlNode.getAttribute("order")); + } else { + extensionDefinition.order = 0; + } + var extensionOnInit = XMLUtils.XPathSelectSingleNode(xmlNode, 'processing/extensionOnInit'); + if (extensionOnInit && extensionOnInit.firstChild) { + try { + // @TODO: THIS WILL LIKELY TRIGGER PROTOTYPE CODE + eval(extensionOnInit.firstChild.nodeValue); + } catch (e) { + Logger.error("Ignoring Error in extensionOnInit code:"); + Logger.error(extensionOnInit.firstChild.nodeValue); + } + } + var dialogOnOpen = XMLUtils.XPathSelectSingleNode(xmlNode, 'processing/dialogOnOpen'); + if (dialogOnOpen && dialogOnOpen.firstChild) { + extensionDefinition.dialogOnOpen = dialogOnOpen.firstChild.nodeValue; + } + var dialogOnComplete = XMLUtils.XPathSelectSingleNode(xmlNode, 'processing/dialogOnComplete'); + if (dialogOnComplete && dialogOnComplete.firstChild) { + extensionDefinition.dialogOnComplete = dialogOnComplete.firstChild.nodeValue; + } } + return true; } - ResourcesManager.loadAutoLoadResources(this._registry); - }; - - /** - * Find the currently active extensions by type - * @param extensionType String "editor" or "uploader" - * @returns {array} - */ - Registry.prototype.getActiveExtensionByType = function getActiveExtensionByType(extensionType) { - return this._extensionsRegistry[extensionType]; - }; - - /** - * Find a given editor by its id - * @param editorId String - * @returns AbstractEditor - */ - - Registry.prototype.findEditorById = function findEditorById(editorId) { - return this._extensionsRegistry.editor.find(function (el) { - return el.id == editorId; - }); - }; + /** + * Refresh the currently active extensions + * Extensions are editors and uploaders for the moment. + */ + }, { + key: "refreshExtensionsRegistry", + value: function refreshExtensionsRegistry() { + this._extensionsRegistry = { "editor": [], "uploader": [] }; + var extensions = XMLUtils.XPathSelectNodes(this._registry, "plugins/editor|plugins/uploader"); + for (var i = 0; i < extensions.length; i++) { + var extensionDefinition = { + id: extensions[i].getAttribute("id"), + xmlNode: extensions[i], + resourcesManager: new ResourcesManager() + }; + this._resourcesRegistry[extensionDefinition.id] = extensionDefinition.resourcesManager; + var resourceNodes = XMLUtils.XPathSelectNodes(extensions[i], "client_settings/resources|dependencies|clientForm"); + for (var j = 0; j < resourceNodes.length; j++) { + var child = resourceNodes[j]; + extensionDefinition.resourcesManager.loadFromXmlNode(child); + } + if (this.initExtension(extensions[i], extensionDefinition)) { + this._extensionsRegistry[extensions[i].nodeName].push(extensionDefinition); + } + } + ResourcesManager.loadAutoLoadResources(this._registry); + } - /** - * Find Editors that can handle a given mime type - * @param mime String - * @returns AbstractEditor[] - * @param restrictToPreviewProviders - */ + /** + * Find the currently active extensions by type + * @param extensionType String "editor" or "uploader" + * @returns {array} + */ + }, { + key: "getActiveExtensionByType", + value: function getActiveExtensionByType(extensionType) { + return this._extensionsRegistry[extensionType]; + } - Registry.prototype.findEditorsForMime = function findEditorsForMime(mime, restrictToPreviewProviders) { - var editors = []; - var checkWrite = false; - if (this.user != null && !this.user.canWrite()) { - checkWrite = true; + /** + * Find a given editor by its id + * @param editorId String + * @returns AbstractEditor + */ + }, { + key: "findEditorById", + value: function findEditorById(editorId) { + return this._extensionsRegistry.editor.find(function (el) { + return el.id == editorId; + }); } - this._extensionsRegistry.editor.forEach(function (el) { - if (el.mimes.indexOf(mime) !== -1 || el.mimes.indexOf("*") !== -1) { - if (restrictToPreviewProviders && !el.previewProvider) return; - if (!checkWrite || !el.write) editors.push(el); + + /** + * Find Editors that can handle a given mime type + * @param mime String + * @returns AbstractEditor[] + * @param restrictToPreviewProviders + */ + }, { + key: "findEditorsForMime", + value: function findEditorsForMime(mime, restrictToPreviewProviders) { + var editors = []; + var checkWrite = false; + if (this.user != null && !this.user.canWrite()) { + checkWrite = true; } - }); - if (editors.length && editors.length > 1) { - editors = editors.sort(function (a, b) { - return (a.order || 0) - (b.order || 0); + this._extensionsRegistry.editor.forEach(function (el) { + if (el.mimes.indexOf(mime) !== -1 || el.mimes.indexOf('*') !== -1) { + if (restrictToPreviewProviders && !el.previewProvider) return; + if (!checkWrite || !el.write) editors.push(el); + } }); + if (editors.length && editors.length > 1) { + editors = editors.sort(function (a, b) { + return (a.order || 0) - (b.order || 0); + }); + } + return editors; } - return editors; - }; - - /** - * Trigger the load method of the resourcesManager. - * @param resourcesManager ResourcesManager - */ - - Registry.prototype.loadEditorResources = function loadEditorResources(resourcesManager) { - resourcesManager.load(this._resourcesRegistry); - }; - - /** - * - * @param pluginQuery - * @returns {Map} - */ - Registry.prototype.getPluginConfigs = function getPluginConfigs(pluginQuery) { - var xpath = "plugins/*[@id=\"core." + pluginQuery + "\"]/plugin_configs/property | plugins/*[@id=\"" + pluginQuery + "\"]/plugin_configs/property"; - if (pluginQuery.indexOf(".") == -1) { - xpath = "plugins/" + pluginQuery + "/plugin_configs/property |" + xpath; + /** + * Trigger the load method of the resourcesManager. + * @param resourcesManager ResourcesManager + */ + }, { + key: "loadEditorResources", + value: function loadEditorResources(resourcesManager) { + resourcesManager.load(this._resourcesRegistry); } - var properties = XMLUtils.XPathSelectNodes(this._registry, xpath); - var configs = new Map(); - properties.forEach(function (propNode) { - configs.set(propNode.getAttribute("name"), JSON.parse(propNode.firstChild.nodeValue)); - }); - return configs; - }; - /** - * - * @param pluginId - * @param paramName - * @returns {string} - */ - - Registry.prototype.getDefaultImageFromParameters = function getDefaultImageFromParameters(pluginId, paramName) { - var node = XMLUtils.XPathSelectSingleNode(this._registry, "plugins/*[@id='" + pluginId + "']/server_settings/global_param[@name='" + paramName + "']"); - if (!node) return ""; - return node.getAttribute("defaultImage") || ""; - }; + /** + * + * @param pluginQuery + * @returns {Map} + */ + }, { + key: "getPluginConfigs", + value: function getPluginConfigs(pluginQuery) { + var xpath = 'plugins/*[@id="core.' + pluginQuery + '"]/plugin_configs/property | plugins/*[@id="' + pluginQuery + '"]/plugin_configs/property'; + if (pluginQuery.indexOf('.') == -1) { + xpath = 'plugins/' + pluginQuery + '/plugin_configs/property |' + xpath; + } + var properties = XMLUtils.XPathSelectNodes(this._registry, xpath); + var configs = new Map(); + properties.forEach(function (propNode) { + configs.set(propNode.getAttribute("name"), JSON.parse(propNode.firstChild.nodeValue)); + }); + return configs; + } - /** - * - * @param type - * @param name - * @returns {bool} - */ + /** + * + * @param pluginId + * @param paramName + * @returns {string} + */ + }, { + key: "getDefaultImageFromParameters", + value: function getDefaultImageFromParameters(pluginId, paramName) { + var node = XMLUtils.XPathSelectSingleNode(this._registry, "plugins/*[@id='" + pluginId + "']/server_settings/global_param[@name='" + paramName + "']"); + if (!node) return ''; + return node.getAttribute("defaultImage") || ''; + } - Registry.prototype.hasPluginOfType = function hasPluginOfType(type, name) { - var node; - if (name == null) { - node = XMLUtils.XPathSelectSingleNode(this._registry, "plugins/ajxp_plugin[contains(@id, \"" + type + ".\")] | plugins/" + type + "[@id]"); - } else { - node = XMLUtils.XPathSelectSingleNode(this._registry, "plugins/ajxp_plugin[@id=\"" + type + "." + name + "\"] | plugins/" + type + "[@id=\"" + type + "." + name + "\"]"); + /** + * + * @param type + * @param name + * @returns {bool} + */ + }, { + key: "hasPluginOfType", + value: function hasPluginOfType(type, name) { + var node; + if (name == null) { + node = XMLUtils.XPathSelectSingleNode(this._registry, 'plugins/ajxp_plugin[contains(@id, "' + type + '.")] | plugins/' + type + '[@id]'); + } else { + node = XMLUtils.XPathSelectSingleNode(this._registry, 'plugins/ajxp_plugin[@id="' + type + '.' + name + '"] | plugins/' + type + '[@id="' + type + '.' + name + '"]'); + } + return node != undefined; } - return node != undefined; - }; + }]); return Registry; -})(); \ No newline at end of file +})(); diff --git a/core/src/plugins/gui.ajax/res/js/core/model/RemoteNodeProvider.js b/core/src/plugins/gui.ajax/res/js/core/model/RemoteNodeProvider.js index 1f39c35a66..2cf2ea2252 100644 --- a/core/src/plugins/gui.ajax/res/js/core/model/RemoteNodeProvider.js +++ b/core/src/plugins/gui.ajax/res/js/core/model/RemoteNodeProvider.js @@ -24,6 +24,8 @@ */ 'use strict'; +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var RemoteNodeProvider = (function () { @@ -43,253 +45,262 @@ var RemoteNodeProvider = (function () { * @param properties Object */ - RemoteNodeProvider.prototype.initProvider = function initProvider(properties) { - this.properties = new Map(); - for (var p in properties) { - if (properties.hasOwnProperty(p)) this.properties.set(p, properties[p]); - } - if (this.properties && this.properties.has('connexion_discrete')) { - this.discrete = true; - this.properties['delete']('connexion_discrete'); + _createClass(RemoteNodeProvider, [{ + key: 'initProvider', + value: function initProvider(properties) { + this.properties = new Map(); + for (var p in properties) { + if (properties.hasOwnProperty(p)) this.properties.set(p, properties[p]); + } + if (this.properties && this.properties.has('connexion_discrete')) { + this.discrete = true; + this.properties['delete']('connexion_discrete'); + } } - }; - /** - * Load a node - * @param node AjxpNode - * @param nodeCallback Function On node loaded - * @param childCallback Function On child added - * @param recursive - * @param depth - */ + /** + * Load a node + * @param node AjxpNode + * @param nodeCallback Function On node loaded + * @param childCallback Function On child added + * @param recursive + * @param depth + */ + }, { + key: 'loadNode', + value: function loadNode(node) { + var nodeCallback = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + var childCallback = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2]; + var recursive = arguments.length <= 3 || arguments[3] === undefined ? false : arguments[3]; + var depth = arguments.length <= 4 || arguments[4] === undefined ? -1 : arguments[4]; - RemoteNodeProvider.prototype.loadNode = function loadNode(node) { - var nodeCallback = arguments[1] === undefined ? null : arguments[1]; - var childCallback = arguments[2] === undefined ? null : arguments[2]; - var recursive = arguments[3] === undefined ? false : arguments[3]; - var depth = arguments[4] === undefined ? -1 : arguments[4]; - - var params = { - get_action: 'ls', - options: 'al' - }; - if (recursive) { - params['recursive'] = true; - params['depth'] = depth; - } - //if(this.discrete) conn.discrete = true; - var path = node.getPath(); - // Double encode # character - var paginationHash; - if (node.getMetadata().has('paginationData')) { - paginationHash = '%23' + node.getMetadata().get('paginationData').get('current'); - path += paginationHash; - params['remote_order'] = 'true'; - if (node.getMetadata().get('remote_order')) { - node.getMetadata().get('remote_order').forEach(function (value, key) { - params[key] = value; + var params = { + get_action: 'ls', + options: 'al' + }; + if (recursive) { + params['recursive'] = true; + params['depth'] = depth; + } + //if(this.discrete) conn.discrete = true; + var path = node.getPath(); + // Double encode # character + var paginationHash; + if (node.getMetadata().has("paginationData")) { + paginationHash = "%23" + node.getMetadata().get("paginationData").get("current"); + path += paginationHash; + params['remote_order'] = 'true'; + if (node.getMetadata().get("remote_order")) { + node.getMetadata().get("remote_order").forEach(function (value, key) { + params[key] = value; + }); + } + } + params['dir'] = path; + if (this.properties) { + this.properties.forEach(function (value, key) { + params[key] = value + (key == 'dir' && paginationHash ? paginationHash : ''); }); } + var complete = (function (transport) { + this.parseNodes(node, transport, nodeCallback, childCallback); + }).bind(this); + PydioApi.getClient().request(params, complete); } - params['dir'] = path; - if (this.properties) { - this.properties.forEach(function (value, key) { - params[key] = value + (key == 'dir' && paginationHash ? paginationHash : ''); - }); - } - var complete = (function (transport) { - this.parseNodes(node, transport, nodeCallback, childCallback); - }).bind(this); - PydioApi.getClient().request(params, complete); - }; - /** - * Load a node - * @param node AjxpNode - * @param nodeCallback Function On node loaded - * @param aSync bool - */ + /** + * Load a node + * @param node AjxpNode + * @param nodeCallback Function On node loaded + * @param aSync bool + */ + }, { + key: 'loadLeafNodeSync', + value: function loadLeafNodeSync(node, nodeCallback) { + var aSync = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2]; - RemoteNodeProvider.prototype.loadLeafNodeSync = function loadLeafNodeSync(node, nodeCallback) { - var aSync = arguments[2] === undefined ? false : arguments[2]; - - var params = { - get_action: 'ls', - options: 'al', - dir: PathUtils.getDirname(node.getPath()), - file: PathUtils.getBasename(node.getPath()) - }; - if (this.properties) { - this.properties.forEach(function (value, key) { - params[key] = value; - }); - } - var complete = (function (transport) { - try { - if (node.isRoot()) { - this.parseNodes(node, transport, nodeCallback, null, true); - } else { - this.parseNodes(node, transport, null, nodeCallback, true); - } - } catch (e) { - Logger.error('Loading error :' + e.message); + var params = { + get_action: 'ls', + options: 'al', + dir: PathUtils.getDirname(node.getPath()), + file: PathUtils.getBasename(node.getPath()) + }; + if (this.properties) { + this.properties.forEach(function (value, key) { + params[key] = value; + }); } - }).bind(this); - PydioApi.getClient().request(params, complete, null, { async: aSync }); - }; + var complete = (function (transport) { + try { + if (node.isRoot()) { + this.parseNodes(node, transport, nodeCallback, null, true); + } else { + this.parseNodes(node, transport, null, nodeCallback, true); + } + } catch (e) { + Logger.error('Loading error :' + e.message); + } + }).bind(this); + PydioApi.getClient().request(params, complete, null, { async: aSync }); + } + }, { + key: 'refreshNodeAndReplace', + value: function refreshNodeAndReplace(node, onComplete) { - RemoteNodeProvider.prototype.refreshNodeAndReplace = function refreshNodeAndReplace(node, onComplete) { + var params = { + get_action: 'ls', + options: 'al', + dir: PathUtils.getDirname(node.getPath()), + file: PathUtils.getBasename(node.getPath()) + }; + if (this.properties) { + this.properties.forEach(function (value, key) { + params[key] = value; + }); + } - var params = { - get_action: 'ls', - options: 'al', - dir: PathUtils.getDirname(node.getPath()), - file: PathUtils.getBasename(node.getPath()) - }; - if (this.properties) { - this.properties.forEach(function (value, key) { - params[key] = value; - }); + var nodeCallback = function nodeCallback(newNode) { + node.replaceBy(newNode, "override"); + if (onComplete) onComplete(node); + }; + PydioApi.getClient().request(params, (function (transport) { + try { + if (node.isRoot()) { + this.parseNodes(node, transport, nodeCallback, null, true); + } else { + this.parseNodes(node, transport, null, nodeCallback, true); + } + } catch (e) { + Logger.error(e); + } + }).bind(this)); } - var nodeCallback = function nodeCallback(newNode) { - node.replaceBy(newNode, 'override'); - if (onComplete) onComplete(node); - }; - PydioApi.getClient().request(params, (function (transport) { - try { - if (node.isRoot()) { - this.parseNodes(node, transport, nodeCallback, null, true); - } else { - this.parseNodes(node, transport, null, nodeCallback, true); + /** + * Parse the answer and create AjxpNodes + * @param origNode AjxpNode + * @param transport Ajax.Response + * @param nodeCallback Function + * @param childCallback Function + * @param childrenOnly + */ + }, { + key: 'parseNodes', + value: function parseNodes(origNode, transport, nodeCallback, childCallback, childrenOnly) { + if (!transport.responseXML || !transport.responseXML.documentElement) { + Logger.debug('Loading node ' + origNode.getPath() + ' has wrong response: ' + transport.responseText); + if (nodeCallback) nodeCallback(origNode); + origNode.setLoaded(false); + if (!transport.responseText) { + throw new Error('Empty response!'); } - } catch (e) { - Logger.error(e); + throw new Error('Invalid XML Document (see console)'); + } + var rootNode = transport.responseXML.documentElement; + if (!childrenOnly) { + var contextNode = this.parseAjxpNode(rootNode); + origNode.replaceBy(contextNode, "merge"); } - }).bind(this)); - }; - /** - * Parse the answer and create AjxpNodes - * @param origNode AjxpNode - * @param transport Ajax.Response - * @param nodeCallback Function - * @param childCallback Function - * @param childrenOnly - */ + // CHECK FOR MESSAGE OR ERRORS + var errorNode = XMLUtils.XPathSelectSingleNode(rootNode, "error|message"); + if (errorNode) { + var type; + if (errorNode.nodeName == "message") type = errorNode.getAttribute('type'); + if (type == "ERROR") { + origNode.notify("error", errorNode.firstChild.nodeValue + '(Source:' + origNode.getPath() + ')'); + } + } - RemoteNodeProvider.prototype.parseNodes = function parseNodes(origNode, transport, nodeCallback, childCallback, childrenOnly) { - if (!transport.responseXML || !transport.responseXML.documentElement) { - Logger.debug('Loading node ' + origNode.getPath() + ' has wrong response: ' + transport.responseText); - if (nodeCallback) nodeCallback(origNode); - origNode.setLoaded(false); - if (!transport.responseText) { - throw new Error('Empty response!'); + // CHECK FOR PAGINATION DATA + var paginationNode = XMLUtils.XPathSelectSingleNode(rootNode, "pagination"); + if (paginationNode) { + var paginationData = new Map(); + Array.from(paginationNode.attributes).forEach((function (att) { + paginationData.set(att.nodeName, att.value); + }).bind(this)); + origNode.getMetadata().set('paginationData', paginationData); + } else if (origNode.getMetadata().get('paginationData')) { + origNode.getMetadata()['delete']('paginationData'); } - throw new Error('Invalid XML Document (see console)'); - } - var rootNode = transport.responseXML.documentElement; - if (!childrenOnly) { - var contextNode = this.parseAjxpNode(rootNode); - origNode.replaceBy(contextNode, 'merge'); - } - // CHECK FOR MESSAGE OR ERRORS - var errorNode = XMLUtils.XPathSelectSingleNode(rootNode, 'error|message'); - if (errorNode) { - var type; - if (errorNode.nodeName == 'message') type = errorNode.getAttribute('type'); - if (type == 'ERROR') { - origNode.notify('error', errorNode.firstChild.nodeValue + '(Source:' + origNode.getPath() + ')'); + // CHECK FOR COMPONENT CONFIGS CONTEXTUAL DATA + var configs = XMLUtils.XPathSelectSingleNode(rootNode, "client_configs"); + if (configs) { + origNode.getMetadata().set('client_configs', configs); } - } - // CHECK FOR PAGINATION DATA - var paginationNode = XMLUtils.XPathSelectSingleNode(rootNode, 'pagination'); - if (paginationNode) { - var paginationData = new Map(); - Array.from(paginationNode.attributes).forEach((function (att) { - paginationData.set(att.nodeName, att.value); + // NOW PARSE CHILDREN + var children = XMLUtils.XPathSelectNodes(rootNode, "tree"); + children.forEach((function (childNode) { + var child = this.parseAjxpNode(childNode); + if (!childrenOnly) origNode.addChild(child); + var cLoaded; + if (XMLUtils.XPathSelectNodes(childNode, 'tree').length) { + XMLUtils.XPathSelectNodes(childNode, 'tree').forEach((function (c) { + var newChild = this.parseAjxpNode(c); + if (newChild) { + child.addChild(newChild); + } + }).bind(this)); + cLoaded = true; + } + if (childCallback) { + childCallback(child); + } + if (cLoaded) child.setLoaded(true); }).bind(this)); - origNode.getMetadata().set('paginationData', paginationData); - } else if (origNode.getMetadata().get('paginationData')) { - origNode.getMetadata()['delete']('paginationData'); - } - // CHECK FOR COMPONENT CONFIGS CONTEXTUAL DATA - var configs = XMLUtils.XPathSelectSingleNode(rootNode, 'client_configs'); - if (configs) { - origNode.getMetadata().set('client_configs', configs); + if (nodeCallback) { + nodeCallback(origNode); + } } + }, { + key: 'parseAjxpNodesDiffs', + value: function parseAjxpNodesDiffs(xmlElement, targetDataModel) { + var setContextChildrenSelected = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2]; - // NOW PARSE CHILDREN - var children = XMLUtils.XPathSelectNodes(rootNode, 'tree'); - children.forEach((function (childNode) { - var child = this.parseAjxpNode(childNode); - if (!childrenOnly) origNode.addChild(child); - var cLoaded; - if (XMLUtils.XPathSelectNodes(childNode, 'tree').length) { - XMLUtils.XPathSelectNodes(childNode, 'tree').forEach((function (c) { - var newChild = this.parseAjxpNode(c); - if (newChild) { - child.addChild(newChild); - } - }).bind(this)); - cLoaded = true; + var removes = XMLUtils.XPathSelectNodes(xmlElement, "remove/tree"); + var adds = XMLUtils.XPathSelectNodes(xmlElement, "add/tree"); + var updates = XMLUtils.XPathSelectNodes(xmlElement, "update/tree"); + // TODO: MOVE TO DATAMODEL + if (removes && removes.length) { + removes.forEach(function (r) { + var p = r.getAttribute("filename"); + targetDataModel.removeNodeByPath(p); + }); } - if (childCallback) { - childCallback(child); + if (adds && adds.length && targetDataModel.getAjxpNodeProvider().parseAjxpNode) { + adds.forEach(function (tree) { + var newNode = targetDataModel.getAjxpNodeProvider().parseAjxpNode(tree); + targetDataModel.addNode(newNode, setContextChildrenSelected); + }); + } + if (updates && updates.length && targetDataModel.getAjxpNodeProvider().parseAjxpNode) { + updates.forEach(function (tree) { + var newNode = targetDataModel.getAjxpNodeProvider().parseAjxpNode(tree); + targetDataModel.updateNode(newNode, setContextChildrenSelected); + }); } - if (cLoaded) child.setLoaded(true); - }).bind(this)); - - if (nodeCallback) { - nodeCallback(origNode); - } - }; - - RemoteNodeProvider.prototype.parseAjxpNodesDiffs = function parseAjxpNodesDiffs(xmlElement, targetDataModel) { - var setContextChildrenSelected = arguments[2] === undefined ? false : arguments[2]; - - var removes = XMLUtils.XPathSelectNodes(xmlElement, 'remove/tree'); - var adds = XMLUtils.XPathSelectNodes(xmlElement, 'add/tree'); - var updates = XMLUtils.XPathSelectNodes(xmlElement, 'update/tree'); - // TODO: MOVE TO DATAMODEL - if (removes && removes.length) { - removes.forEach(function (r) { - var p = r.getAttribute('filename'); - targetDataModel.removeNodeByPath(p); - }); - } - if (adds && adds.length && targetDataModel.getAjxpNodeProvider().parseAjxpNode) { - adds.forEach(function (tree) { - var newNode = targetDataModel.getAjxpNodeProvider().parseAjxpNode(tree); - targetDataModel.addNode(newNode, setContextChildrenSelected); - }); - } - if (updates && updates.length && targetDataModel.getAjxpNodeProvider().parseAjxpNode) { - updates.forEach(function (tree) { - var newNode = targetDataModel.getAjxpNodeProvider().parseAjxpNode(tree); - targetDataModel.updateNode(newNode, setContextChildrenSelected); - }); } - }; - /** - * Parses XML Node and create AjxpNode - * @param xmlNode XMLNode - * @returns AjxpNode - */ - - RemoteNodeProvider.prototype.parseAjxpNode = function parseAjxpNode(xmlNode) { - var node = new AjxpNode(xmlNode.getAttribute('filename'), xmlNode.getAttribute('is_file') == '1' || xmlNode.getAttribute('is_file') == 'true', xmlNode.getAttribute('text'), xmlNode.getAttribute('icon')); - var metadata = new Map(); - for (var i = 0; i < xmlNode.attributes.length; i++) { - metadata.set(xmlNode.attributes[i].nodeName, xmlNode.attributes[i].value); + /** + * Parses XML Node and create AjxpNode + * @param xmlNode XMLNode + * @returns AjxpNode + */ + }, { + key: 'parseAjxpNode', + value: function parseAjxpNode(xmlNode) { + var node = new AjxpNode(xmlNode.getAttribute('filename'), xmlNode.getAttribute('is_file') == "1" || xmlNode.getAttribute('is_file') == "true", xmlNode.getAttribute('text'), xmlNode.getAttribute('icon')); + var metadata = new Map(); + for (var i = 0; i < xmlNode.attributes.length; i++) { + metadata.set(xmlNode.attributes[i].nodeName, xmlNode.attributes[i].value); + } + node.setMetadata(metadata); + return node; } - node.setMetadata(metadata); - return node; - }; + }]); return RemoteNodeProvider; -})(); \ No newline at end of file +})(); diff --git a/core/src/plugins/gui.ajax/res/js/core/model/Repository.js b/core/src/plugins/gui.ajax/res/js/core/model/Repository.js index b93d42e684..c897f9056a 100644 --- a/core/src/plugins/gui.ajax/res/js/core/model/Repository.js +++ b/core/src/plugins/gui.ajax/res/js/core/model/Repository.js @@ -23,6 +23,8 @@ */ 'use strict'; +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var Repository = (function () { @@ -56,167 +58,185 @@ var Repository = (function () { * @returns String */ - Repository.prototype.getId = function getId() { - return this.id; - }; - - /** - * @returns String - */ - - Repository.prototype.getLabel = function getLabel() { - return this.label; - }; - - /** - * @param label String - */ - - Repository.prototype.setLabel = function setLabel(label) { - this.label = label; - }; - - Repository.prototype.getHtmlBadge = function getHtmlBadge() { - if (!this.label) return ''; - if (!this.badge) { - var letters = this.label.split(' ').map(function (word) { - return word.substr(0, 1); - }).slice(0, 3).join(''); - this.badge = '' + letters + ''; + _createClass(Repository, [{ + key: 'getId', + value: function getId() { + return this.id; } - return this.badge; - }; - - /** - * @return String - */ - - Repository.prototype.getDescription = function getDescription() { - return this.description; - }; - - /** - * @returns String - */ - - Repository.prototype.getIcon = function getIcon() { - return this.icon; - }; - /** - * @param icon String - */ - - Repository.prototype.setIcon = function setIcon(icon) { - this.icon = icon; - }; - - /** - * @return String - */ - - Repository.prototype.getOwner = function getOwner() { - return this.owner; - }; - - /** - * @returns String - */ - - Repository.prototype.getAccessType = function getAccessType() { - return this.accessType; - }; - - /** - * @param access String - */ + /** + * @returns String + */ + }, { + key: 'getLabel', + value: function getLabel() { + return this.label; + } - Repository.prototype.setAccessType = function setAccessType(access) { - this.accessType = access; - }; + /** + * @param label String + */ + }, { + key: 'setLabel', + value: function setLabel(label) { + this.label = label; + } + }, { + key: 'getHtmlBadge', + value: function getHtmlBadge() { + if (!this.label) return ''; + if (!this.badge) { + var letters = this.label.split(" ").map(function (word) { + return word.substr(0, 1); + }).slice(0, 3).join(""); + this.badge = "" + letters + ""; + } + return this.badge; + } - /** - * Triggers ResourcesManager.load - */ + /** + * @return String + */ + }, { + key: 'getDescription', + value: function getDescription() { + return this.description; + } - Repository.prototype.loadResources = function loadResources() { - this.resourcesManager.load(null, true); - }; + /** + * @returns String + */ + }, { + key: 'getIcon', + value: function getIcon() { + return this.icon; + } - /** - * @returns Object - */ + /** + * @param icon String + */ + }, { + key: 'setIcon', + value: function setIcon(icon) { + this.icon = icon; + } - Repository.prototype.getNodeProviderDef = function getNodeProviderDef() { - return this.nodeProviderDef; - }; + /** + * @return String + */ + }, { + key: 'getOwner', + value: function getOwner() { + return this.owner; + } - /** - * @param slug String - */ + /** + * @returns String + */ + }, { + key: 'getAccessType', + value: function getAccessType() { + return this.accessType; + } - Repository.prototype.setSlug = function setSlug(slug) { - this.slug = slug; - }; + /** + * @param access String + */ + }, { + key: 'setAccessType', + value: function setAccessType(access) { + this.accessType = access; + } - /** - * @returns String - */ + /** + * Triggers ResourcesManager.load + */ + }, { + key: 'loadResources', + value: function loadResources() { + this.resourcesManager.load(null, true); + } - Repository.prototype.getSlug = function getSlug() { - return this.slug; - }; + /** + * @returns Object + */ + }, { + key: 'getNodeProviderDef', + value: function getNodeProviderDef() { + return this.nodeProviderDef; + } - Repository.prototype.getOverlay = function getOverlay() { - return this.getOwner() ? resolveImageSource('shared.png', '/images/overlays/ICON_SIZE', 8) : ''; - }; + /** + * @param slug String + */ + }, { + key: 'setSlug', + value: function setSlug(slug) { + this.slug = slug; + } - /** - * Parses XML Node - * @param repoNode XMLNode - */ + /** + * @returns String + */ + }, { + key: 'getSlug', + value: function getSlug() { + return this.slug; + } + }, { + key: 'getOverlay', + value: function getOverlay() { + return this.getOwner() ? resolveImageSource("shared.png", "/images/overlays/ICON_SIZE", 8) : ""; + } - Repository.prototype.loadFromXml = function loadFromXml(repoNode) { - if (repoNode.getAttribute('allowCrossRepositoryCopy') && repoNode.getAttribute('allowCrossRepositoryCopy') == 'true') { - this.allowCrossRepositoryCopy = true; - } - if (repoNode.getAttribute('user_editable_repository') && repoNode.getAttribute('user_editable_repository') == 'true') { - this.userEditable = true; - } - if (repoNode.getAttribute('access_type')) { - this.setAccessType(repoNode.getAttribute('access_type')); - } - if (repoNode.getAttribute('repositorySlug')) { - this.setSlug(repoNode.getAttribute('repositorySlug')); - } - if (repoNode.getAttribute('owner')) { - this.owner = repoNode.getAttribute('owner'); - } - for (var i = 0; i < repoNode.childNodes.length; i++) { - var childNode = repoNode.childNodes[i]; - if (childNode.nodeName == 'label') { - this.setLabel(childNode.firstChild.nodeValue); - } else if (childNode.nodeName == 'description') { - this.description = childNode.firstChild.nodeValue; - } else if (childNode.nodeName == 'client_settings') { - if (childNode.getAttribute('icon_tpl_id')) { - this.setIcon(window.ajxpServerAccessPath + '&get_action=get_user_template_logo&template_id=' + childNode.getAttribute('icon_tpl_id') + '&icon_format=small'); - } else { - this.setIcon(childNode.getAttribute('icon')); - } - for (var j = 0; j < childNode.childNodes.length; j++) { - var subCh = childNode.childNodes[j]; - if (subCh.nodeName == 'resources') { - this.resourcesManager.loadFromXmlNode(subCh); - } else if (subCh.nodeName == 'node_provider') { - var nodeProviderName = subCh.getAttribute('ajxpClass'); - var nodeProviderOptions = JSON.parse(subCh.getAttribute('ajxpOptions')); - this.nodeProviderDef = { name: nodeProviderName, options: nodeProviderOptions }; + /** + * Parses XML Node + * @param repoNode XMLNode + */ + }, { + key: 'loadFromXml', + value: function loadFromXml(repoNode) { + if (repoNode.getAttribute('allowCrossRepositoryCopy') && repoNode.getAttribute('allowCrossRepositoryCopy') == "true") { + this.allowCrossRepositoryCopy = true; + } + if (repoNode.getAttribute('user_editable_repository') && repoNode.getAttribute('user_editable_repository') == "true") { + this.userEditable = true; + } + if (repoNode.getAttribute('access_type')) { + this.setAccessType(repoNode.getAttribute('access_type')); + } + if (repoNode.getAttribute('repositorySlug')) { + this.setSlug(repoNode.getAttribute('repositorySlug')); + } + if (repoNode.getAttribute('owner')) { + this.owner = repoNode.getAttribute('owner'); + } + for (var i = 0; i < repoNode.childNodes.length; i++) { + var childNode = repoNode.childNodes[i]; + if (childNode.nodeName == "label") { + this.setLabel(childNode.firstChild.nodeValue); + } else if (childNode.nodeName == "description") { + this.description = childNode.firstChild.nodeValue; + } else if (childNode.nodeName == "client_settings") { + if (childNode.getAttribute('icon_tpl_id')) { + this.setIcon(window.ajxpServerAccessPath + '&get_action=get_user_template_logo&template_id=' + childNode.getAttribute('icon_tpl_id') + '&icon_format=small'); + } else { + this.setIcon(childNode.getAttribute('icon')); + } + for (var j = 0; j < childNode.childNodes.length; j++) { + var subCh = childNode.childNodes[j]; + if (subCh.nodeName == 'resources') { + this.resourcesManager.loadFromXmlNode(subCh); + } else if (subCh.nodeName == 'node_provider') { + var nodeProviderName = subCh.getAttribute("ajxpClass"); + var nodeProviderOptions = JSON.parse(subCh.getAttribute("ajxpOptions")); + this.nodeProviderDef = { name: nodeProviderName, options: nodeProviderOptions }; + } } } } } - }; + }]); return Repository; -})(); \ No newline at end of file +})(); diff --git a/core/src/plugins/gui.ajax/res/js/core/model/Router.js b/core/src/plugins/gui.ajax/res/js/core/model/Router.js index 712fdbd7e4..09be98ed5f 100644 --- a/core/src/plugins/gui.ajax/res/js/core/model/Router.js +++ b/core/src/plugins/gui.ajax/res/js/core/model/Router.js @@ -15,7 +15,7 @@ var Router = function Router(pydioObject) { if (!pydioObject.user) { return; } - if (path) path = "/" + path;else path = "/"; + if (path) path = '/' + path;else path = '/'; var repos = pydioObject.user.getRepositoriesList(); workspace = workspace.replace("ws-", ""); @@ -44,7 +44,7 @@ var Router = function Router(pydioObject) { }); this.router = new WorkspaceRouter(); - var appRoot = pydioObject.Parameters.get("APPLICATION_ROOT"); + var appRoot = pydioObject.Parameters.get('APPLICATION_ROOT'); if (appRoot && appRoot != "/") { Backbone.history.start({ pushState: true, @@ -94,4 +94,4 @@ var Router = function Router(pydioObject) { this.router.navigate(slug + path); } }).bind(this)); -}; \ No newline at end of file +}; diff --git a/core/src/plugins/gui.ajax/res/js/core/model/User.js b/core/src/plugins/gui.ajax/res/js/core/model/User.js index 4c376f5859..5343bf5dda 100644 --- a/core/src/plugins/gui.ajax/res/js/core/model/User.js +++ b/core/src/plugins/gui.ajax/res/js/core/model/User.js @@ -24,6 +24,8 @@ */ "use strict"; +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var User = (function () { @@ -102,265 +104,283 @@ var User = (function () { * @param write Boolean */ - User.prototype.setActiveRepository = function setActiveRepository(id, read, write) { - this.activeRepository = id; - this.read = read == "1"; - this.write = write == "1"; - if (this.repositories.has(id)) { - this.crossRepositoryCopy = this.repositories.get(id).allowCrossRepositoryCopy; - } - if (this.crossRepositories.has(id)) { - this.crossRepositories["delete"](id); + _createClass(User, [{ + key: "setActiveRepository", + value: function setActiveRepository(id, read, write) { + this.activeRepository = id; + this.read = read == "1"; + this.write = write == "1"; + if (this.repositories.has(id)) { + this.crossRepositoryCopy = this.repositories.get(id).allowCrossRepositoryCopy; + } + if (this.crossRepositories.has(id)) { + this.crossRepositories["delete"](id); + } } - }; - - /** - * Gets the current active repository - * @returns String - */ - - User.prototype.getActiveRepository = function getActiveRepository() { - return this.activeRepository; - }; - - /** - * Whether current repo is allowed to be read - * @returns Boolean - */ - - User.prototype.canRead = function canRead() { - return this.read; - }; - - /** - * Whether current repo is allowed to be written - * @returns Boolean - */ - - User.prototype.canWrite = function canWrite() { - return this.write; - }; - /** - * Whether current repo is allowed to be cross-copied - * @returns Boolean - */ + /** + * Gets the current active repository + * @returns String + */ + }, { + key: "getActiveRepository", + value: function getActiveRepository() { + return this.activeRepository; + } - User.prototype.canCrossRepositoryCopy = function canCrossRepositoryCopy() { - return this.crossRepositoryCopy; - }; + /** + * Whether current repo is allowed to be read + * @returns Boolean + */ + }, { + key: "canRead", + value: function canRead() { + return this.read; + } - /** - * Get a user preference by its name - * @returns Mixed - */ + /** + * Whether current repo is allowed to be written + * @returns Boolean + */ + }, { + key: "canWrite", + value: function canWrite() { + return this.write; + } - User.prototype.getPreference = function getPreference(prefName, fromJSON) { - if (fromJSON) { - var test = this._parsedJSONCache.get(prefName); - if (test !== undefined) return test; + /** + * Whether current repo is allowed to be cross-copied + * @returns Boolean + */ + }, { + key: "canCrossRepositoryCopy", + value: function canCrossRepositoryCopy() { + return this.crossRepositoryCopy; } - var value = this.preferences.get(prefName); - if (fromJSON && value) { - try { - if (typeof value == "object") return value; - var parsed = JSON.parse(value); - this._parsedJSONCache.set(prefName, parsed); - return parsed; - } catch (e) { - if (window.console) { - Logger.log("Error parsing JSON in preferences (" + prefName + "). You should contact system admin and clear user preferences."); - } else { - alert("Error parsing JSON in preferences. You should contact system admin and clear user preferences."); + + /** + * Get a user preference by its name + * @returns Mixed + */ + }, { + key: "getPreference", + value: function getPreference(prefName, fromJSON) { + if (fromJSON) { + var test = this._parsedJSONCache.get(prefName); + if (test !== undefined) return test; + } + var value = this.preferences.get(prefName); + if (fromJSON && value) { + try { + if (typeof value == "object") return value; + var parsed = JSON.parse(value); + this._parsedJSONCache.set(prefName, parsed); + return parsed; + } catch (e) { + if (window.console) { + Logger.log("Error parsing JSON in preferences (" + prefName + "). You should contact system admin and clear user preferences."); + } else { + alert("Error parsing JSON in preferences. You should contact system admin and clear user preferences."); + } } } + return value; } - return value; - }; - - /** - * Get all repositories - * @returns Map - */ - User.prototype.getRepositoriesList = function getRepositoriesList() { - return this.repositories; - }; - - /** - * Set a preference value - * @param prefName String - * @param prefValue Mixed - * @param toJSON Boolean Whether to convert the value to JSON representation - */ - - User.prototype.setPreference = function setPreference(prefName, prefValue) { - var toJSON = arguments[2] === undefined ? false : arguments[2]; - - if (toJSON) { - this._parsedJSONCache["delete"](prefName); - try { - prefValue = JSON.stringify(prefValue); - } catch (e) { - if (console) { - var isCyclic = function (obj) { - var seenObjects = []; + /** + * Get all repositories + * @returns Map + */ + }, { + key: "getRepositoriesList", + value: function getRepositoriesList() { + return this.repositories; + } - function detect(obj) { - if (obj && typeof obj === "object") { - if (seenObjects.indexOf(obj) !== -1) { - return true; - } - seenObjects.push(obj); - for (var key in obj) { - if (obj.hasOwnProperty(key) && detect(obj[key])) { - console.log(obj, "cycle at " + key); + /** + * Set a preference value + * @param prefName String + * @param prefValue Mixed + * @param toJSON Boolean Whether to convert the value to JSON representation + */ + }, { + key: "setPreference", + value: function setPreference(prefName, prefValue) { + var toJSON = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2]; + + if (toJSON) { + this._parsedJSONCache["delete"](prefName); + try { + prefValue = JSON.stringify(prefValue); + } catch (e) { + if (console) { + var isCyclic = function isCyclic(obj) { + var seenObjects = []; + + function detect(obj) { + if (obj && typeof obj === 'object') { + if (seenObjects.indexOf(obj) !== -1) { return true; } + seenObjects.push(obj); + for (var key in obj) { + if (obj.hasOwnProperty(key) && detect(obj[key])) { + console.log(obj, 'cycle at ' + key); + return true; + } + } } + return false; } - return false; - } - return detect(obj); - }; + return detect(obj); + }; - console.log("Caught toJSON error " + e.message, prefValue, isCyclic(prefValue)); + console.log("Caught toJSON error " + e.message, prefValue, isCyclic(prefValue)); + } + return; } - return; } + this.preferences.set(prefName, prefValue); } - this.preferences.set(prefName, prefValue); - }; - - /** - * Set the repositories as a bunch - * @param repoHash Map - */ - - User.prototype.setRepositoriesList = function setRepositoriesList(repoHash) { - this.repositories = repoHash; - // filter repositories once for all - this.crossRepositories = new Map(); - this.repositories.forEach((function (value, key) { - if (value.allowCrossRepositoryCopy) { - this.crossRepositories.set(key, value); - } - }).bind(this)); - }; - - /** - * Whether there are any repositories allowing crossCopy - * @returns Boolean - */ - - User.prototype.hasCrossRepositories = function hasCrossRepositories() { - return this.crossRepositories.size; - }; - - /** - * Get repositories allowing cross copy - * @returns {Map} - */ - - User.prototype.getCrossRepositories = function getCrossRepositories() { - return this.crossRepositories; - }; - - /** - * Get the current repository Icon - * @param repoId String - * @returns String - */ - User.prototype.getRepositoryIcon = function getRepositoryIcon(repoId) { - return this.repoIcon.get(repoId); - }; - - /** - * Get the repository search engine - * @param repoId String - * @returns String - */ - - User.prototype.getRepoSearchEngine = function getRepoSearchEngine(repoId) { - return this.repoSearchEngines.get(repoId); - }; + /** + * Set the repositories as a bunch + * @param repoHash Map + */ + }, { + key: "setRepositoriesList", + value: function setRepositoriesList(repoHash) { + this.repositories = repoHash; + // filter repositories once for all + this.crossRepositories = new Map(); + this.repositories.forEach((function (value, key) { + if (value.allowCrossRepositoryCopy) { + this.crossRepositories.set(key, value); + } + }).bind(this)); + } - /** - * Send the preference to the server for saving - * @param prefName String - */ + /** + * Whether there are any repositories allowing crossCopy + * @returns Boolean + */ + }, { + key: "hasCrossRepositories", + value: function hasCrossRepositories() { + return this.crossRepositories.size; + } - User.prototype.savePreference = function savePreference(prefName) { - if (!this.preferences.has(prefName)) return; - var prefValue = this.preferences.get(prefName); - window.setTimeout(function () { - PydioApi.getClient().userSavePreference(prefName, prefValue); - }, 250); - }; + /** + * Get repositories allowing cross copy + * @returns {Map} + */ + }, { + key: "getCrossRepositories", + value: function getCrossRepositories() { + return this.crossRepositories; + } - /** - * Send all preferences to the server. If oldPass, newPass and seed are set, also save pass. - * @param oldPass String - * @param newPass String - * @param seed String - * @param onCompleteFunc Function - */ + /** + * Get the current repository Icon + * @param repoId String + * @returns String + */ + }, { + key: "getRepositoryIcon", + value: function getRepositoryIcon(repoId) { + return this.repoIcon.get(repoId); + } - User.prototype.savePreferences = function savePreferences(oldPass, newPass, seed, onCompleteFunc) { - if (oldPass && newPass) { - PydioApi.getClient().userSavePassword(oldPass, newPass, seed, onCompleteFunc); - } else { - PydioApi.getClient().userSavePreferences(this.preferences, onCompleteFunc); + /** + * Get the repository search engine + * @param repoId String + * @returns String + */ + }, { + key: "getRepoSearchEngine", + value: function getRepoSearchEngine(repoId) { + return this.repoSearchEngines.get(repoId); } - }; - /** - * Parse the registry fragment to load this user - * @param userNodes DOMNode - */ + /** + * Send the preference to the server for saving + * @param prefName String + */ + }, { + key: "savePreference", + value: function savePreference(prefName) { + if (!this.preferences.has(prefName)) return; + var prefValue = this.preferences.get(prefName); + window.setTimeout(function () { + PydioApi.getClient().userSavePreference(prefName, prefValue); + }, 250); + } - User.prototype.loadFromXml = function loadFromXml(userNodes) { + /** + * Send all preferences to the server. If oldPass, newPass and seed are set, also save pass. + * @param oldPass String + * @param newPass String + * @param seed String + * @param onCompleteFunc Function + */ + }, { + key: "savePreferences", + value: function savePreferences(oldPass, newPass, seed, onCompleteFunc) { + if (oldPass && newPass) { + PydioApi.getClient().userSavePassword(oldPass, newPass, seed, onCompleteFunc); + } else { + PydioApi.getClient().userSavePreferences(this.preferences, onCompleteFunc); + } + } - var repositories = new Map(); - var i, j; - for (i = 0; i < userNodes.length; i++) { - if (userNodes[i].nodeName == "active_repo") { - var activeNode = userNodes[i]; - } else if (userNodes[i].nodeName == "repositories") { - for (j = 0; j < userNodes[i].childNodes.length; j++) { - var repoChild = userNodes[i].childNodes[j]; - if (repoChild.nodeName == "repo") { - var repository = new Repository(repoChild.getAttribute("id"), repoChild); - repositories.set(repoChild.getAttribute("id"), repository); + /** + * Parse the registry fragment to load this user + * @param userNodes DOMNode + */ + }, { + key: "loadFromXml", + value: function loadFromXml(userNodes) { + + var repositories = new Map(); + var i, j; + for (i = 0; i < userNodes.length; i++) { + if (userNodes[i].nodeName == "active_repo") { + var activeNode = userNodes[i]; + } else if (userNodes[i].nodeName == "repositories") { + for (j = 0; j < userNodes[i].childNodes.length; j++) { + var repoChild = userNodes[i].childNodes[j]; + if (repoChild.nodeName == "repo") { + var repository = new Repository(repoChild.getAttribute("id"), repoChild); + repositories.set(repoChild.getAttribute("id"), repository); + } } - } - this.setRepositoriesList(repositories); - } else if (userNodes[i].nodeName == "preferences") { - for (j = 0; j < userNodes[i].childNodes.length; j++) { - var prefChild = userNodes[i].childNodes[j]; - if (prefChild.nodeName == "pref") { - var value = prefChild.getAttribute("value"); - if (!value && prefChild.firstChild) { - // Retrieve value from CDATA - value = prefChild.firstChild.nodeValue; + this.setRepositoriesList(repositories); + } else if (userNodes[i].nodeName == "preferences") { + for (j = 0; j < userNodes[i].childNodes.length; j++) { + var prefChild = userNodes[i].childNodes[j]; + if (prefChild.nodeName == "pref") { + var value = prefChild.getAttribute("value"); + if (!value && prefChild.firstChild) { + // Retrieve value from CDATA + value = prefChild.firstChild.nodeValue; + } + this.setPreference(prefChild.getAttribute("name"), value); } - this.setPreference(prefChild.getAttribute("name"), value); } - } - } else if (userNodes[i].nodeName == "special_rights") { - var attr = userNodes[i].getAttribute("is_admin"); - if (attr && attr == "1") this.isAdmin = true; - if (userNodes[i].getAttribute("lock")) { - this.lock = userNodes[i].getAttribute("lock"); + } else if (userNodes[i].nodeName == "special_rights") { + var attr = userNodes[i].getAttribute("is_admin"); + if (attr && attr == "1") this.isAdmin = true; + if (userNodes[i].getAttribute("lock")) { + this.lock = userNodes[i].getAttribute("lock"); + } } } + // Make sure it happens at the end + if (activeNode) { + this.setActiveRepository(activeNode.getAttribute('id'), activeNode.getAttribute('read'), activeNode.getAttribute('write')); + } } - // Make sure it happens at the end - if (activeNode) { - this.setActiveRepository(activeNode.getAttribute("id"), activeNode.getAttribute("read"), activeNode.getAttribute("write")); - } - }; + }]); return User; -})(); \ No newline at end of file +})(); diff --git a/core/src/plugins/gui.ajax/res/js/core/util/HasherUtils.js b/core/src/plugins/gui.ajax/res/js/core/util/HasherUtils.js index aca0bf0229..070dc61c66 100644 --- a/core/src/plugins/gui.ajax/res/js/core/util/HasherUtils.js +++ b/core/src/plugins/gui.ajax/res/js/core/util/HasherUtils.js @@ -1,5 +1,7 @@ 'use strict'; +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var HasherUtils = (function () { @@ -17,376 +19,401 @@ var HasherUtils = (function () { _classCallCheck(this, HasherUtils); } + /* + * Configurable variables. You may need to tweak these to be compatible with + * the server-side, but the defaults work in most cases. + */ + /* * These are the functions you'll usually want to call * They take string arguments and return either hex or base-64 encoded strings */ - HasherUtils.hex_md5 = function hex_md5(s) { - return HasherUtils.binl2hex(HasherUtils.core_md5(HasherUtils.str2binl(s), s.length * HasherUtils.chrsz)); - }; - - HasherUtils.b64_md5 = function b64_md5(s) { - return HasherUtils.binl2b64(HasherUtils.core_md5(HasherUtils.str2binl(s), s.length * HasherUtils.chrsz)); - }; - - HasherUtils.str_md5 = function str_md5(s) { - return HasherUtils.binl2str(HasherUtils.core_md5(HasherUtils.str2binl(s), s.length * HasherUtils.chrsz)); - }; - - HasherUtils.hex_hmac_md5 = function hex_hmac_md5(key, data) { - return HasherUtils.binl2hex(HasherUtils.core_hmac_md5(key, data)); - }; - - HasherUtils.b64_hmac_md5 = function b64_hmac_md5(key, data) { - return HasherUtils.binl2b64(HasherUtils.core_hmac_md5(key, data)); - }; - - HasherUtils.str_hmac_md5 = function str_hmac_md5(key, data) { - return HasherUtils.binl2str(HasherUtils.core_hmac_md5(key, data)); - }; - - HasherUtils.base64_encode = function base64_encode(data) { - // http://kevin.vanzonneveld.net - // + original by: Tyler Akins (http://rumkin.com) - // + improved by: Bayron Guevara - // + improved by: Thunder.m - // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) - // + bugfixed by: Pellentesque Malesuada - // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) - // - depends on: utf8_encode - // * example 1: base64_encode('Kevin van Zonneveld'); - // * returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA==' - - // mozilla has this native - // - but breaks in 2.0.0.12! - //if (typeof window['atob'] == 'function') { - // return atob(data); - //} - - var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; - var o1, - o2, - o3, - h1, - h2, - h3, - h4, - bits, - i = 0, - ac = 0, - enc, - tmp_arr = []; - - if (!data) { - return data; + _createClass(HasherUtils, null, [{ + key: 'hex_md5', + value: function hex_md5(s) { + return HasherUtils.binl2hex(HasherUtils.core_md5(HasherUtils.str2binl(s), s.length * HasherUtils.chrsz)); } - - data = HasherUtils.utf8_encode(data + ''); - - do { - // pack three octets into four hexets - o1 = data.charCodeAt(i++); - o2 = data.charCodeAt(i++); - o3 = data.charCodeAt(i++); - - bits = o1 << 16 | o2 << 8 | o3; - - h1 = bits >> 18 & 63; - h2 = bits >> 12 & 63; - h3 = bits >> 6 & 63; - h4 = bits & 63; - - // use hexets to index into b64, and append result to encoded string - tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4); - } while (i < data.length); - - enc = tmp_arr.join(''); - - switch (data.length % 3) { - case 1: - enc = enc.slice(0, -2) + '=='; - break; - case 2: - enc = enc.slice(0, -1) + '='; - break; + }, { + key: 'b64_md5', + value: function b64_md5(s) { + return HasherUtils.binl2b64(HasherUtils.core_md5(HasherUtils.str2binl(s), s.length * HasherUtils.chrsz)); } - - return enc; - }; - - HasherUtils.utf8_encode = function utf8_encode(string) { - // http://kevin.vanzonneveld.net - // + original by: Webtoolkit.info (http://www.webtoolkit.info/) - // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) - // + improved by: sowberry - // + tweaked by: Jack - // + bugfixed by: Onno Marsman - // + improved by: Yves Sucaet - // + bugfixed by: Onno Marsman - // * example 1: utf8_encode('Kevin van Zonneveld'); - // * returns 1: 'Kevin van Zonneveld' - - string = (string + '').replace(/\r\n/g, '\n').replace(/\r/g, '\n'); - - var utftext = ''; - var start, end; - var stringl; - - start = end = 0; - stringl = string.length; - for (var n = 0; n < stringl; n++) { - var c1 = string.charCodeAt(n); - var enc = null; - - if (c1 < 128) { - end++; - } else if (c1 > 127 && c1 < 2048) { - enc = String.fromCharCode(c1 >> 6 | 192) + String.fromCharCode(c1 & 63 | 128); - } else { - enc = String.fromCharCode(c1 >> 12 | 224) + String.fromCharCode(c1 >> 6 & 63 | 128) + String.fromCharCode(c1 & 63 | 128); - } - if (enc != null) { - if (end > start) { - utftext += string.substring(start, end); - } - utftext += enc; - start = end = n + 1; - } + }, { + key: 'str_md5', + value: function str_md5(s) { + return HasherUtils.binl2str(HasherUtils.core_md5(HasherUtils.str2binl(s), s.length * HasherUtils.chrsz)); } - - if (end > start) { - utftext += string.substring(start, string.length); + }, { + key: 'hex_hmac_md5', + value: function hex_hmac_md5(key, data) { + return HasherUtils.binl2hex(HasherUtils.core_hmac_md5(key, data)); } - - return utftext; - }; - - /* - * Perform a simple self-test to see if the VM is working - */ - - HasherUtils.md5_vm_test = function md5_vm_test() { - return HasherUtils.hex_md5('abc') == '900150983cd24fb0d6963f7d28e17f72'; - }; - - /* - * Calculate the MD5 of an array of little-endian words, and a bit length - */ - - HasherUtils.core_md5 = function core_md5(x, len) { - /* append padding */ - x[len >> 5] |= 128 << len % 32; - x[(len + 64 >>> 9 << 4) + 14] = len; - - var a = 1732584193; - var b = -271733879; - var c = -1732584194; - var d = 271733878; - - for (var i = 0; i < x.length; i += 16) { - var olda = a; - var oldb = b; - var oldc = c; - var oldd = d; - - a = HasherUtils.md5_ff(a, b, c, d, x[i + 0], 7, -680876936); - d = HasherUtils.md5_ff(d, a, b, c, x[i + 1], 12, -389564586); - c = HasherUtils.md5_ff(c, d, a, b, x[i + 2], 17, 606105819); - b = HasherUtils.md5_ff(b, c, d, a, x[i + 3], 22, -1044525330); - a = HasherUtils.md5_ff(a, b, c, d, x[i + 4], 7, -176418897); - d = HasherUtils.md5_ff(d, a, b, c, x[i + 5], 12, 1200080426); - c = HasherUtils.md5_ff(c, d, a, b, x[i + 6], 17, -1473231341); - b = HasherUtils.md5_ff(b, c, d, a, x[i + 7], 22, -45705983); - a = HasherUtils.md5_ff(a, b, c, d, x[i + 8], 7, 1770035416); - d = HasherUtils.md5_ff(d, a, b, c, x[i + 9], 12, -1958414417); - c = HasherUtils.md5_ff(c, d, a, b, x[i + 10], 17, -42063); - b = HasherUtils.md5_ff(b, c, d, a, x[i + 11], 22, -1990404162); - a = HasherUtils.md5_ff(a, b, c, d, x[i + 12], 7, 1804603682); - d = HasherUtils.md5_ff(d, a, b, c, x[i + 13], 12, -40341101); - c = HasherUtils.md5_ff(c, d, a, b, x[i + 14], 17, -1502002290); - b = HasherUtils.md5_ff(b, c, d, a, x[i + 15], 22, 1236535329); - - a = HasherUtils.md5_gg(a, b, c, d, x[i + 1], 5, -165796510); - d = HasherUtils.md5_gg(d, a, b, c, x[i + 6], 9, -1069501632); - c = HasherUtils.md5_gg(c, d, a, b, x[i + 11], 14, 643717713); - b = HasherUtils.md5_gg(b, c, d, a, x[i + 0], 20, -373897302); - a = HasherUtils.md5_gg(a, b, c, d, x[i + 5], 5, -701558691); - d = HasherUtils.md5_gg(d, a, b, c, x[i + 10], 9, 38016083); - c = HasherUtils.md5_gg(c, d, a, b, x[i + 15], 14, -660478335); - b = HasherUtils.md5_gg(b, c, d, a, x[i + 4], 20, -405537848); - a = HasherUtils.md5_gg(a, b, c, d, x[i + 9], 5, 568446438); - d = HasherUtils.md5_gg(d, a, b, c, x[i + 14], 9, -1019803690); - c = HasherUtils.md5_gg(c, d, a, b, x[i + 3], 14, -187363961); - b = HasherUtils.md5_gg(b, c, d, a, x[i + 8], 20, 1163531501); - a = HasherUtils.md5_gg(a, b, c, d, x[i + 13], 5, -1444681467); - d = HasherUtils.md5_gg(d, a, b, c, x[i + 2], 9, -51403784); - c = HasherUtils.md5_gg(c, d, a, b, x[i + 7], 14, 1735328473); - b = HasherUtils.md5_gg(b, c, d, a, x[i + 12], 20, -1926607734); - - a = HasherUtils.md5_hh(a, b, c, d, x[i + 5], 4, -378558); - d = HasherUtils.md5_hh(d, a, b, c, x[i + 8], 11, -2022574463); - c = HasherUtils.md5_hh(c, d, a, b, x[i + 11], 16, 1839030562); - b = HasherUtils.md5_hh(b, c, d, a, x[i + 14], 23, -35309556); - a = HasherUtils.md5_hh(a, b, c, d, x[i + 1], 4, -1530992060); - d = HasherUtils.md5_hh(d, a, b, c, x[i + 4], 11, 1272893353); - c = HasherUtils.md5_hh(c, d, a, b, x[i + 7], 16, -155497632); - b = HasherUtils.md5_hh(b, c, d, a, x[i + 10], 23, -1094730640); - a = HasherUtils.md5_hh(a, b, c, d, x[i + 13], 4, 681279174); - d = HasherUtils.md5_hh(d, a, b, c, x[i + 0], 11, -358537222); - c = HasherUtils.md5_hh(c, d, a, b, x[i + 3], 16, -722521979); - b = HasherUtils.md5_hh(b, c, d, a, x[i + 6], 23, 76029189); - a = HasherUtils.md5_hh(a, b, c, d, x[i + 9], 4, -640364487); - d = HasherUtils.md5_hh(d, a, b, c, x[i + 12], 11, -421815835); - c = HasherUtils.md5_hh(c, d, a, b, x[i + 15], 16, 530742520); - b = HasherUtils.md5_hh(b, c, d, a, x[i + 2], 23, -995338651); - - a = HasherUtils.md5_ii(a, b, c, d, x[i + 0], 6, -198630844); - d = HasherUtils.md5_ii(d, a, b, c, x[i + 7], 10, 1126891415); - c = HasherUtils.md5_ii(c, d, a, b, x[i + 14], 15, -1416354905); - b = HasherUtils.md5_ii(b, c, d, a, x[i + 5], 21, -57434055); - a = HasherUtils.md5_ii(a, b, c, d, x[i + 12], 6, 1700485571); - d = HasherUtils.md5_ii(d, a, b, c, x[i + 3], 10, -1894986606); - c = HasherUtils.md5_ii(c, d, a, b, x[i + 10], 15, -1051523); - b = HasherUtils.md5_ii(b, c, d, a, x[i + 1], 21, -2054922799); - a = HasherUtils.md5_ii(a, b, c, d, x[i + 8], 6, 1873313359); - d = HasherUtils.md5_ii(d, a, b, c, x[i + 15], 10, -30611744); - c = HasherUtils.md5_ii(c, d, a, b, x[i + 6], 15, -1560198380); - b = HasherUtils.md5_ii(b, c, d, a, x[i + 13], 21, 1309151649); - a = HasherUtils.md5_ii(a, b, c, d, x[i + 4], 6, -145523070); - d = HasherUtils.md5_ii(d, a, b, c, x[i + 11], 10, -1120210379); - c = HasherUtils.md5_ii(c, d, a, b, x[i + 2], 15, 718787259); - b = HasherUtils.md5_ii(b, c, d, a, x[i + 9], 21, -343485551); - - a = HasherUtils.safe_add(a, olda); - b = HasherUtils.safe_add(b, oldb); - c = HasherUtils.safe_add(c, oldc); - d = HasherUtils.safe_add(d, oldd); + }, { + key: 'b64_hmac_md5', + value: function b64_hmac_md5(key, data) { + return HasherUtils.binl2b64(HasherUtils.core_hmac_md5(key, data)); } - return [a, b, c, d]; - }; - - /* - * These functions implement the four basic operations the algorithm uses. - */ + }, { + key: 'str_hmac_md5', + value: function str_hmac_md5(key, data) { + return HasherUtils.binl2str(HasherUtils.core_hmac_md5(key, data)); + } + }, { + key: 'base64_encode', + value: function base64_encode(data) { + // http://kevin.vanzonneveld.net + // + original by: Tyler Akins (http://rumkin.com) + // + improved by: Bayron Guevara + // + improved by: Thunder.m + // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) + // + bugfixed by: Pellentesque Malesuada + // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) + // - depends on: utf8_encode + // * example 1: base64_encode('Kevin van Zonneveld'); + // * returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA==' + + // mozilla has this native + // - but breaks in 2.0.0.12! + //if (typeof window['atob'] == 'function') { + // return atob(data); + //} + + var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + var o1, + o2, + o3, + h1, + h2, + h3, + h4, + bits, + i = 0, + ac = 0, + enc, + tmp_arr = []; + + if (!data) { + return data; + } - HasherUtils.md5_cmn = function md5_cmn(q, a, b, x, s, t) { - return HasherUtils.safe_add(HasherUtils.bit_rol(HasherUtils.safe_add(HasherUtils.safe_add(a, q), HasherUtils.safe_add(x, t)), s), b); - }; + data = HasherUtils.utf8_encode(data + ''); - HasherUtils.md5_ff = function md5_ff(a, b, c, d, x, s, t) { - return HasherUtils.md5_cmn(b & c | ~b & d, a, b, x, s, t); - }; + do { + // pack three octets into four hexets + o1 = data.charCodeAt(i++); + o2 = data.charCodeAt(i++); + o3 = data.charCodeAt(i++); - HasherUtils.md5_gg = function md5_gg(a, b, c, d, x, s, t) { - return HasherUtils.md5_cmn(b & d | c & ~d, a, b, x, s, t); - }; + bits = o1 << 16 | o2 << 8 | o3; - HasherUtils.md5_hh = function md5_hh(a, b, c, d, x, s, t) { - return HasherUtils.md5_cmn(b ^ c ^ d, a, b, x, s, t); - }; + h1 = bits >> 18 & 0x3f; + h2 = bits >> 12 & 0x3f; + h3 = bits >> 6 & 0x3f; + h4 = bits & 0x3f; - HasherUtils.md5_ii = function md5_ii(a, b, c, d, x, s, t) { - return HasherUtils.md5_cmn(c ^ (b | ~d), a, b, x, s, t); - }; + // use hexets to index into b64, and append result to encoded string + tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4); + } while (i < data.length); - /* - * Calculate the HMAC-MD5, of a key and some data - */ + enc = tmp_arr.join(''); - HasherUtils.core_hmac_md5 = function core_hmac_md5(key, data) { - var bkey = HasherUtils.str2binl(key); - if (bkey.length > 16) bkey = HasherUtils.core_md5(bkey, key.length * HasherUtils.chrsz); + switch (data.length % 3) { + case 1: + enc = enc.slice(0, -2) + '=='; + break; + case 2: + enc = enc.slice(0, -1) + '='; + break; + } - var ipad = new Array(16), - opad = new Array(16); - for (var i = 0; i < 16; i++) { - ipad[i] = bkey[i] ^ 909522486; - opad[i] = bkey[i] ^ 1549556828; + return enc; } + }, { + key: 'utf8_encode', + value: function utf8_encode(string) { + // http://kevin.vanzonneveld.net + // + original by: Webtoolkit.info (http://www.webtoolkit.info/) + // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) + // + improved by: sowberry + // + tweaked by: Jack + // + bugfixed by: Onno Marsman + // + improved by: Yves Sucaet + // + bugfixed by: Onno Marsman + // * example 1: utf8_encode('Kevin van Zonneveld'); + // * returns 1: 'Kevin van Zonneveld' + + string = (string + '').replace(/\r\n/g, "\n").replace(/\r/g, "\n"); + + var utftext = ""; + var start, end; + var stringl; + + start = end = 0; + stringl = string.length; + for (var n = 0; n < stringl; n++) { + var c1 = string.charCodeAt(n); + var enc = null; + + if (c1 < 128) { + end++; + } else if (c1 > 127 && c1 < 2048) { + enc = String.fromCharCode(c1 >> 6 | 192) + String.fromCharCode(c1 & 63 | 128); + } else { + enc = String.fromCharCode(c1 >> 12 | 224) + String.fromCharCode(c1 >> 6 & 63 | 128) + String.fromCharCode(c1 & 63 | 128); + } + if (enc != null) { + if (end > start) { + utftext += string.substring(start, end); + } + utftext += enc; + start = end = n + 1; + } + } - var hash = HasherUtils.core_md5(ipad.concat(HasherUtils.str2binl(data)), 512 + data.length * HasherUtils.chrsz); - return HasherUtils.core_md5(opad.concat(hash), 512 + 128); - }; + if (end > start) { + utftext += string.substring(start, string.length); + } - /* - * Add integers, wrapping at 2^32. This uses 16-bit operations internally - * to work around bugs in some JS interpreters. - */ + return utftext; + } - HasherUtils.safe_add = function safe_add(x, y) { - var lsw = (x & 65535) + (y & 65535); - var msw = (x >> 16) + (y >> 16) + (lsw >> 16); - return msw << 16 | lsw & 65535; - }; + /* + * Perform a simple self-test to see if the VM is working + */ + }, { + key: 'md5_vm_test', + value: function md5_vm_test() { + return HasherUtils.hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72"; + } - /* - * Bitwise rotate a 32-bit number to the left. - */ + /* + * Calculate the MD5 of an array of little-endian words, and a bit length + */ + }, { + key: 'core_md5', + value: function core_md5(x, len) { + /* append padding */ + x[len >> 5] |= 0x80 << len % 32; + x[(len + 64 >>> 9 << 4) + 14] = len; + + var a = 1732584193; + var b = -271733879; + var c = -1732584194; + var d = 271733878; + + for (var i = 0; i < x.length; i += 16) { + var olda = a; + var oldb = b; + var oldc = c; + var oldd = d; + + a = HasherUtils.md5_ff(a, b, c, d, x[i + 0], 7, -680876936); + d = HasherUtils.md5_ff(d, a, b, c, x[i + 1], 12, -389564586); + c = HasherUtils.md5_ff(c, d, a, b, x[i + 2], 17, 606105819); + b = HasherUtils.md5_ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = HasherUtils.md5_ff(a, b, c, d, x[i + 4], 7, -176418897); + d = HasherUtils.md5_ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = HasherUtils.md5_ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = HasherUtils.md5_ff(b, c, d, a, x[i + 7], 22, -45705983); + a = HasherUtils.md5_ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = HasherUtils.md5_ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = HasherUtils.md5_ff(c, d, a, b, x[i + 10], 17, -42063); + b = HasherUtils.md5_ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = HasherUtils.md5_ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = HasherUtils.md5_ff(d, a, b, c, x[i + 13], 12, -40341101); + c = HasherUtils.md5_ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = HasherUtils.md5_ff(b, c, d, a, x[i + 15], 22, 1236535329); + + a = HasherUtils.md5_gg(a, b, c, d, x[i + 1], 5, -165796510); + d = HasherUtils.md5_gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = HasherUtils.md5_gg(c, d, a, b, x[i + 11], 14, 643717713); + b = HasherUtils.md5_gg(b, c, d, a, x[i + 0], 20, -373897302); + a = HasherUtils.md5_gg(a, b, c, d, x[i + 5], 5, -701558691); + d = HasherUtils.md5_gg(d, a, b, c, x[i + 10], 9, 38016083); + c = HasherUtils.md5_gg(c, d, a, b, x[i + 15], 14, -660478335); + b = HasherUtils.md5_gg(b, c, d, a, x[i + 4], 20, -405537848); + a = HasherUtils.md5_gg(a, b, c, d, x[i + 9], 5, 568446438); + d = HasherUtils.md5_gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = HasherUtils.md5_gg(c, d, a, b, x[i + 3], 14, -187363961); + b = HasherUtils.md5_gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = HasherUtils.md5_gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = HasherUtils.md5_gg(d, a, b, c, x[i + 2], 9, -51403784); + c = HasherUtils.md5_gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = HasherUtils.md5_gg(b, c, d, a, x[i + 12], 20, -1926607734); + + a = HasherUtils.md5_hh(a, b, c, d, x[i + 5], 4, -378558); + d = HasherUtils.md5_hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = HasherUtils.md5_hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = HasherUtils.md5_hh(b, c, d, a, x[i + 14], 23, -35309556); + a = HasherUtils.md5_hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = HasherUtils.md5_hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = HasherUtils.md5_hh(c, d, a, b, x[i + 7], 16, -155497632); + b = HasherUtils.md5_hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = HasherUtils.md5_hh(a, b, c, d, x[i + 13], 4, 681279174); + d = HasherUtils.md5_hh(d, a, b, c, x[i + 0], 11, -358537222); + c = HasherUtils.md5_hh(c, d, a, b, x[i + 3], 16, -722521979); + b = HasherUtils.md5_hh(b, c, d, a, x[i + 6], 23, 76029189); + a = HasherUtils.md5_hh(a, b, c, d, x[i + 9], 4, -640364487); + d = HasherUtils.md5_hh(d, a, b, c, x[i + 12], 11, -421815835); + c = HasherUtils.md5_hh(c, d, a, b, x[i + 15], 16, 530742520); + b = HasherUtils.md5_hh(b, c, d, a, x[i + 2], 23, -995338651); + + a = HasherUtils.md5_ii(a, b, c, d, x[i + 0], 6, -198630844); + d = HasherUtils.md5_ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = HasherUtils.md5_ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = HasherUtils.md5_ii(b, c, d, a, x[i + 5], 21, -57434055); + a = HasherUtils.md5_ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = HasherUtils.md5_ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = HasherUtils.md5_ii(c, d, a, b, x[i + 10], 15, -1051523); + b = HasherUtils.md5_ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = HasherUtils.md5_ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = HasherUtils.md5_ii(d, a, b, c, x[i + 15], 10, -30611744); + c = HasherUtils.md5_ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = HasherUtils.md5_ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = HasherUtils.md5_ii(a, b, c, d, x[i + 4], 6, -145523070); + d = HasherUtils.md5_ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = HasherUtils.md5_ii(c, d, a, b, x[i + 2], 15, 718787259); + b = HasherUtils.md5_ii(b, c, d, a, x[i + 9], 21, -343485551); + + a = HasherUtils.safe_add(a, olda); + b = HasherUtils.safe_add(b, oldb); + c = HasherUtils.safe_add(c, oldc); + d = HasherUtils.safe_add(d, oldd); + } + return [a, b, c, d]; + } - HasherUtils.bit_rol = function bit_rol(num, cnt) { - return num << cnt | num >>> 32 - cnt; - }; + /* + * These functions implement the four basic operations the algorithm uses. + */ + }, { + key: 'md5_cmn', + value: function md5_cmn(q, a, b, x, s, t) { + return HasherUtils.safe_add(HasherUtils.bit_rol(HasherUtils.safe_add(HasherUtils.safe_add(a, q), HasherUtils.safe_add(x, t)), s), b); + } + }, { + key: 'md5_ff', + value: function md5_ff(a, b, c, d, x, s, t) { + return HasherUtils.md5_cmn(b & c | ~b & d, a, b, x, s, t); + } + }, { + key: 'md5_gg', + value: function md5_gg(a, b, c, d, x, s, t) { + return HasherUtils.md5_cmn(b & d | c & ~d, a, b, x, s, t); + } + }, { + key: 'md5_hh', + value: function md5_hh(a, b, c, d, x, s, t) { + return HasherUtils.md5_cmn(b ^ c ^ d, a, b, x, s, t); + } + }, { + key: 'md5_ii', + value: function md5_ii(a, b, c, d, x, s, t) { + return HasherUtils.md5_cmn(c ^ (b | ~d), a, b, x, s, t); + } - /* - * Convert a string to an array of little-endian words - * If HasherUtils.chrsz is ASCII, characters >255 have their hi-byte silently ignored. - */ + /* + * Calculate the HMAC-MD5, of a key and some data + */ + }, { + key: 'core_hmac_md5', + value: function core_hmac_md5(key, data) { + var bkey = HasherUtils.str2binl(key); + if (bkey.length > 16) bkey = HasherUtils.core_md5(bkey, key.length * HasherUtils.chrsz); + + var ipad = new Array(16), + opad = new Array(16); + for (var i = 0; i < 16; i++) { + ipad[i] = bkey[i] ^ 0x36363636; + opad[i] = bkey[i] ^ 0x5C5C5C5C; + } - HasherUtils.str2binl = function str2binl(str) { - var bin = []; - var mask = (1 << HasherUtils.chrsz) - 1; - for (var i = 0; i < str.length * HasherUtils.chrsz; i += HasherUtils.chrsz) bin[i >> 5] |= (str.charCodeAt(i / HasherUtils.chrsz) & mask) << i % 32; - return bin; - }; + var hash = HasherUtils.core_md5(ipad.concat(HasherUtils.str2binl(data)), 512 + data.length * HasherUtils.chrsz); + return HasherUtils.core_md5(opad.concat(hash), 512 + 128); + } - /* - * Convert an array of little-endian words to a string - */ + /* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ + }, { + key: 'safe_add', + value: function safe_add(x, y) { + var lsw = (x & 0xFFFF) + (y & 0xFFFF); + var msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return msw << 16 | lsw & 0xFFFF; + } - HasherUtils.binl2str = function binl2str(bin) { - var str = ''; - var mask = (1 << HasherUtils.chrsz) - 1; - for (var i = 0; i < bin.length * 32; i += HasherUtils.chrsz) str += String.fromCharCode(bin[i >> 5] >>> i % 32 & mask); - return str; - }; + /* + * Bitwise rotate a 32-bit number to the left. + */ + }, { + key: 'bit_rol', + value: function bit_rol(num, cnt) { + return num << cnt | num >>> 32 - cnt; + } - /* - * Convert an array of little-endian words to a hex string. - */ + /* + * Convert a string to an array of little-endian words + * If HasherUtils.chrsz is ASCII, characters >255 have their hi-byte silently ignored. + */ + }, { + key: 'str2binl', + value: function str2binl(str) { + var bin = []; + var mask = (1 << HasherUtils.chrsz) - 1; + for (var i = 0; i < str.length * HasherUtils.chrsz; i += HasherUtils.chrsz) bin[i >> 5] |= (str.charCodeAt(i / HasherUtils.chrsz) & mask) << i % 32; + return bin; + } - HasherUtils.binl2hex = function binl2hex(binarray) { - var hex_tab = HasherUtils.hexcase ? '0123456789ABCDEF' : '0123456789abcdef'; - var str = ''; - for (var i = 0; i < binarray.length * 4; i++) { - str += hex_tab.charAt(binarray[i >> 2] >> i % 4 * 8 + 4 & 15) + hex_tab.charAt(binarray[i >> 2] >> i % 4 * 8 & 15); + /* + * Convert an array of little-endian words to a string + */ + }, { + key: 'binl2str', + value: function binl2str(bin) { + var str = ""; + var mask = (1 << HasherUtils.chrsz) - 1; + for (var i = 0; i < bin.length * 32; i += HasherUtils.chrsz) str += String.fromCharCode(bin[i >> 5] >>> i % 32 & mask); + return str; } - return str; - }; - /* - * Convert an array of little-endian words to a base-64 string - */ + /* + * Convert an array of little-endian words to a hex string. + */ + }, { + key: 'binl2hex', + value: function binl2hex(binarray) { + var hex_tab = HasherUtils.hexcase ? "0123456789ABCDEF" : "0123456789abcdef"; + var str = ""; + for (var i = 0; i < binarray.length * 4; i++) { + str += hex_tab.charAt(binarray[i >> 2] >> i % 4 * 8 + 4 & 0xF) + hex_tab.charAt(binarray[i >> 2] >> i % 4 * 8 & 0xF); + } + return str; + } - HasherUtils.binl2b64 = function binl2b64(binarray) { - var tab = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - var str = ''; - for (var i = 0; i < binarray.length * 4; i += 3) { - var triplet = (binarray[i >> 2] >> 8 * (i % 4) & 255) << 16 | (binarray[i + 1 >> 2] >> 8 * ((i + 1) % 4) & 255) << 8 | binarray[i + 2 >> 2] >> 8 * ((i + 2) % 4) & 255; - for (var j = 0; j < 4; j++) { - if (i * 8 + j * 6 > binarray.length * 32) str += HasherUtils.b64pad;else str += tab.charAt(triplet >> 6 * (3 - j) & 63); + /* + * Convert an array of little-endian words to a base-64 string + */ + }, { + key: 'binl2b64', + value: function binl2b64(binarray) { + var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + var str = ""; + for (var i = 0; i < binarray.length * 4; i += 3) { + var triplet = (binarray[i >> 2] >> 8 * (i % 4) & 0xFF) << 16 | (binarray[i + 1 >> 2] >> 8 * ((i + 1) % 4) & 0xFF) << 8 | binarray[i + 2 >> 2] >> 8 * ((i + 2) % 4) & 0xFF; + for (var j = 0; j < 4; j++) { + if (i * 8 + j * 6 > binarray.length * 32) str += HasherUtils.b64pad;else str += tab.charAt(triplet >> 6 * (3 - j) & 0x3F); + } } + return str; } - return str; - }; + }]); return HasherUtils; })(); -/* - * Configurable variables. You may need to tweak these to be compatible with - * the server-side, but the defaults work in most cases. - */ HasherUtils.hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */ -HasherUtils.b64pad = ''; /* base-64 pad character. "=" for strict RFC compliance */ -HasherUtils.chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */ \ No newline at end of file +HasherUtils.b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */ +HasherUtils.chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */ diff --git a/core/src/plugins/gui.ajax/res/js/core/util/LangUtils.js b/core/src/plugins/gui.ajax/res/js/core/util/LangUtils.js index 01d7d543a5..d6199b3a4c 100644 --- a/core/src/plugins/gui.ajax/res/js/core/util/LangUtils.js +++ b/core/src/plugins/gui.ajax/res/js/core/util/LangUtils.js @@ -1,5 +1,7 @@ 'use strict'; +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var LangUtils = (function () { @@ -7,121 +9,132 @@ var LangUtils = (function () { _classCallCheck(this, LangUtils); } - LangUtils.arrayWithout = function arrayWithout(array, key) { - if (!array.length) return array; - if (key >= array.length) return array; - var newArray; - if (key == 0) newArray = array.slice(1);else if (key == array.length - 1) newArray = array.slice(0, -1);else newArray = array.slice(0, key).concat(array.slice(key + 1)); - return newArray; - }; - - LangUtils.objectMerge = function objectMerge(obj1, obj2) { - for (var k in obj2) { - if (obj2.hasOwnProperty(k)) { - obj1[k] = obj2[k]; + _createClass(LangUtils, null, [{ + key: 'arrayWithout', + value: function arrayWithout(array, key) { + if (!array.length) return array; + if (key >= array.length) return array; + var newArray; + if (key == 0) newArray = array.slice(1);else if (key == array.length - 1) newArray = array.slice(0, -1);else newArray = array.slice(0, key).concat(array.slice(key + 1)); + return newArray; + } + }, { + key: 'objectMerge', + value: function objectMerge(obj1, obj2) { + for (var k in obj2) { + if (obj2.hasOwnProperty(k)) { + obj1[k] = obj2[k]; + } } + return obj1; } - return obj1; - }; - - LangUtils.parseUrl = function parseUrl(data) { - var matches = $A(); - //var e=/((http|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+\.[^#?\s]+)(#[\w\-]+)?/; - var detect = /(pydio:\/)?\/?([^:\/\s]+)((\/\w+)*\/)(.*)(#[\w\-]+)?/g; - var results = data.match(detect); - if (results && results.length) { - var e = /^((pydio):\/)?\/?([^:\/\s]+)((\/\w+)*\/)(.*)(#[\w\-]+)?$/; - for (var i = 0; i < results.length; i++) { - if (results[i].match(e)) { - matches.push({ url: RegExp['$&'], - protocol: RegExp.$2, - host: RegExp.$3, - path: RegExp.$4, - file: RegExp.$6, - hash: RegExp.$7 }); + }, { + key: 'parseUrl', + value: function parseUrl(data) { + var matches = $A(); + //var e=/((http|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+\.[^#?\s]+)(#[\w\-]+)?/; + var detect = /(pydio:\/)?\/?([^:\/\s]+)((\/\w+)*\/)(.*)(#[\w\-]+)?/g; + var results = data.match(detect); + if (results && results.length) { + var e = /^((pydio):\/)?\/?([^:\/\s]+)((\/\w+)*\/)(.*)(#[\w\-]+)?$/; + for (var i = 0; i < results.length; i++) { + if (results[i].match(e)) { + matches.push({ url: RegExp['$&'], + protocol: RegExp.$2, + host: RegExp.$3, + path: RegExp.$4, + file: RegExp.$6, + hash: RegExp.$7 }); + } } } + return matches; } - return matches; - }; + }, { + key: 'computeStringSlug', + value: function computeStringSlug(value) { + for (var i = 0, len = LangUtils.slugTable.length; i < len; i++) value = value.replace(LangUtils.slugTable[i].re, LangUtils.slugTable[i].ch); - LangUtils.computeStringSlug = function computeStringSlug(value) { - for (var i = 0, len = LangUtils.slugTable.length; i < len; i++) value = value.replace(LangUtils.slugTable[i].re, LangUtils.slugTable[i].ch); - - // 1) met en bas de casse - // 2) remplace les espace par des tirets - // 3) enleve tout les caratères non alphanumeriques - // 4) enlève les doubles tirets - return value.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '').replace(/\-{2,}/g, '-'); - }; - - LangUtils.forceJSONArrayToObject = function forceJSONArrayToObject(container, value) { - if (container[value] instanceof Array) { - // Clone - var copy = container[value].slice(0); - container[value] = {}; - for (var i = 0; i < copy.length; i++) { - container[value][i] = copy[i]; + // 1) met en bas de casse + // 2) remplace les espace par des tirets + // 3) enleve tout les caratères non alphanumeriques + // 4) enlève les doubles tirets + return value.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '').replace(/\-{2,}/g, '-'); + } + }, { + key: 'forceJSONArrayToObject', + value: function forceJSONArrayToObject(container, value) { + if (container[value] instanceof Array) { + // Clone + var copy = container[value].slice(0); + container[value] = {}; + for (var i = 0; i < copy.length; i++) { + container[value][i] = copy[i]; + } } } - }; - - LangUtils.deepCopy = function deepCopy(source) { - return LangUtils.mergeObjectsRecursive({}, source); - }; - - LangUtils.simpleCopy = function simpleCopy(source) { - var copy = {}; - for (var property in source) { - if (source.hasOwnProperty(property)) { - copy[property] = source[property]; + }, { + key: 'deepCopy', + value: function deepCopy(source) { + return LangUtils.mergeObjectsRecursive({}, source); + } + }, { + key: 'simpleCopy', + value: function simpleCopy(source) { + var copy = {}; + for (var property in source) { + if (source.hasOwnProperty(property)) { + copy[property] = source[property]; + } } + return copy; } - return copy; - }; - - LangUtils.mergeObjectsRecursive = function mergeObjectsRecursive(source, destination) { - var newObject = {}, - property; - for (property in source) { - if (source.hasOwnProperty(property)) { - //if (source[property] === null) continue; - if (destination.hasOwnProperty(property)) { - if (source[property] instanceof Object && destination instanceof Object) { - newObject[property] = LangUtils.mergeObjectsRecursive(source[property], destination[property]); - } else { - newObject[property] = destination[property]; - } - } else { - if (source[property] instanceof Object) { - newObject[property] = LangUtils.mergeObjectsRecursive(source[property], {}); + }, { + key: 'mergeObjectsRecursive', + value: function mergeObjectsRecursive(source, destination) { + var newObject = {}, + property; + for (property in source) { + if (source.hasOwnProperty(property)) { + //if (source[property] === null) continue; + if (destination.hasOwnProperty(property)) { + if (source[property] instanceof Object && destination instanceof Object) { + newObject[property] = LangUtils.mergeObjectsRecursive(source[property], destination[property]); + } else { + newObject[property] = destination[property]; + } } else { - newObject[property] = source[property]; + if (source[property] instanceof Object) { + newObject[property] = LangUtils.mergeObjectsRecursive(source[property], {}); + } else { + newObject[property] = source[property]; + } } } } - } - for (property in destination) { - if (destination.hasOwnProperty(property) && !newObject.hasOwnProperty(property) /*&& destination[property] !== null*/) { - if (destination[property] instanceof Object) { - newObject[property] = LangUtils.mergeObjectsRecursive(destination[property], {}); - } else { - newObject[property] = destination[property]; - } + for (property in destination) { + if (destination.hasOwnProperty(property) && !newObject.hasOwnProperty(property) /*&& destination[property] !== null*/) { + if (destination[property] instanceof Object) { + newObject[property] = LangUtils.mergeObjectsRecursive(destination[property], {}); + } else { + newObject[property] = destination[property]; + } + } } + return newObject; } - return newObject; - }; - - LangUtils.objectValues = function objectValues(object) { - var results = []; - for (var property in object) if (object.hasOwnProperty(property)) { - results.push(object[property]); + }, { + key: 'objectValues', + value: function objectValues(object) { + var results = []; + for (var property in object) if (object.hasOwnProperty(property)) { + results.push(object[property]); + } + return results; } - return results; - }; + }]); return LangUtils; })(); -LangUtils.slugTable = [{ re: /[\xC0-\xC6]/g, ch: 'A' }, { re: /[\xE0-\xE6]/g, ch: 'a' }, { re: /[\xC8-\xCB]/g, ch: 'E' }, { re: /[\xE8-\xEB]/g, ch: 'e' }, { re: /[\xCC-\xCF]/g, ch: 'I' }, { re: /[\xEC-\xEF]/g, ch: 'i' }, { re: /[\xD2-\xD6]/g, ch: 'O' }, { re: /[\xF2-\xF6]/g, ch: 'o' }, { re: /[\xD9-\xDC]/g, ch: 'U' }, { re: /[\xF9-\xFC]/g, ch: 'u' }, { re: /[\xC7-\xE7]/g, ch: 'c' }, { re: /[\xD1]/g, ch: 'N' }, { re: /[\xF1]/g, ch: 'n' }]; \ No newline at end of file +LangUtils.slugTable = [{ re: /[\xC0-\xC6]/g, ch: 'A' }, { re: /[\xE0-\xE6]/g, ch: 'a' }, { re: /[\xC8-\xCB]/g, ch: 'E' }, { re: /[\xE8-\xEB]/g, ch: 'e' }, { re: /[\xCC-\xCF]/g, ch: 'I' }, { re: /[\xEC-\xEF]/g, ch: 'i' }, { re: /[\xD2-\xD6]/g, ch: 'O' }, { re: /[\xF2-\xF6]/g, ch: 'o' }, { re: /[\xD9-\xDC]/g, ch: 'U' }, { re: /[\xF9-\xFC]/g, ch: 'u' }, { re: /[\xC7-\xE7]/g, ch: 'c' }, { re: /[\xD1]/g, ch: 'N' }, { re: /[\xF1]/g, ch: 'n' }]; diff --git a/core/src/plugins/gui.ajax/res/js/core/util/PathUtils.js b/core/src/plugins/gui.ajax/res/js/core/util/PathUtils.js index 3f6f3bbfe6..904c0c42fc 100644 --- a/core/src/plugins/gui.ajax/res/js/core/util/PathUtils.js +++ b/core/src/plugins/gui.ajax/res/js/core/util/PathUtils.js @@ -1,5 +1,7 @@ "use strict"; +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var PathUtils = (function () { @@ -7,77 +9,85 @@ var PathUtils = (function () { _classCallCheck(this, PathUtils); } - PathUtils.getBasename = function getBasename(fileName) { - if (fileName == null) return null; - var separator = "/"; - if (fileName.indexOf("\\") != -1) separator = "\\"; - return fileName.substr(fileName.lastIndexOf(separator) + 1, fileName.length); - }; - - PathUtils.getDirname = function getDirname(fileName) { - return fileName.substr(0, fileName.lastIndexOf("/")); - }; - - PathUtils.getAjxpMimeType = function getAjxpMimeType(item) { - if (!item) return ""; - if (item instanceof Map) { - return item.get("ajxp_mime") || PathUtils.getFileExtension(item.get("filename")); - } else if (item.getMetadata) { - return item.getMetadata().get("ajxp_mime") || PathUtils.getFileExtension(item.getPath()); - } else { - return item.getAttribute("ajxp_mime") || PathUtils.getFileExtension(item.getAttribute("filename")); + _createClass(PathUtils, null, [{ + key: "getBasename", + value: function getBasename(fileName) { + if (fileName == null) return null; + var separator = "/"; + if (fileName.indexOf("\\") != -1) separator = "\\"; + return fileName.substr(fileName.lastIndexOf(separator) + 1, fileName.length); } - }; - - PathUtils.getFileExtension = function getFileExtension(fileName) { - if (!fileName || fileName == "") return ""; - var split = PathUtils.getBasename(fileName).split("."); - if (split.length > 1) return split[split.length - 1].toLowerCase(); - return ""; - }; - - PathUtils.roundFileSize = function roundFileSize(filesize) { - var size_unit = arguments[1] === undefined ? "o" : arguments[1]; - - if (filesize >= 1073741824) { - filesize = Math.round(filesize / 1073741824 * 100) / 100 + " G" + size_unit; - } else if (filesize >= 1048576) { - filesize = Math.round(filesize / 1048576 * 100) / 100 + " M" + size_unit; - } else if (filesize >= 1024) { - filesize = Math.round(filesize / 1024 * 100) / 100 + " K" + size_unit; - } else { - filesize = filesize + " " + size_unit; + }, { + key: "getDirname", + value: function getDirname(fileName) { + return fileName.substr(0, fileName.lastIndexOf("/")); + } + }, { + key: "getAjxpMimeType", + value: function getAjxpMimeType(item) { + if (!item) return ""; + if (item instanceof Map) { + return item.get('ajxp_mime') || PathUtils.getFileExtension(item.get('filename')); + } else if (item.getMetadata) { + return item.getMetadata().get('ajxp_mime') || PathUtils.getFileExtension(item.getPath()); + } else { + return item.getAttribute('ajxp_mime') || PathUtils.getFileExtension(item.getAttribute('filename')); + } } - return filesize; - }; + }, { + key: "getFileExtension", + value: function getFileExtension(fileName) { + if (!fileName || fileName == "") return ""; + var split = PathUtils.getBasename(fileName).split('.'); + if (split.length > 1) return split[split.length - 1].toLowerCase(); + return ''; + } + }, { + key: "roundFileSize", + value: function roundFileSize(filesize) { + var size_unit = arguments.length <= 1 || arguments[1] === undefined ? "o" : arguments[1]; - /** - * - * @param dateObject Date - * @param format String - * @returns {*} - */ + if (filesize >= 1073741824) { + filesize = Math.round(filesize / 1073741824 * 100) / 100 + " G" + size_unit; + } else if (filesize >= 1048576) { + filesize = Math.round(filesize / 1048576 * 100) / 100 + " M" + size_unit; + } else if (filesize >= 1024) { + filesize = Math.round(filesize / 1024 * 100) / 100 + " K" + size_unit; + } else { + filesize = filesize + " " + size_unit; + } + return filesize; + } - PathUtils.formatModifDate = function formatModifDate(dateObject, format) { - if (!format && window && window.pydio && pydio.MessageHash) { - format = pydio.MessageHash["date_format"]; + /** + * + * @param dateObject Date + * @param format String + * @returns {*} + */ + }, { + key: "formatModifDate", + value: function formatModifDate(dateObject, format) { + if (!format && window && window.pydio && pydio.MessageHash) { + format = pydio.MessageHash["date_format"]; + } + if (!format) return 'no format'; + format = format.replace("d", dateObject.getDate() < 10 ? '0' + dateObject.getDate() : dateObject.getDate()); + format = format.replace("D", dateObject.getDay()); + format = format.replace("Y", dateObject.getFullYear()); + format = format.replace("y", dateObject.getYear()); + var month = dateObject.getMonth() + 1; + format = format.replace("m", month < 10 ? '0' + month : month); + format = format.replace("H", (dateObject.getHours() < 10 ? '0' : '') + dateObject.getHours()); + // Support 12 hour format compatibility + format = format.replace("h", dateObject.getHours() % 12 || 12); + format = format.replace("p", dateObject.getHours() < 12 ? "am" : "pm"); + format = format.replace("P", dateObject.getHours() < 12 ? "AM" : "PM"); + format = format.replace("i", (dateObject.getMinutes() < 10 ? '0' : '') + dateObject.getMinutes()); + format = format.replace("s", (dateObject.getSeconds() < 10 ? '0' : '') + dateObject.getSeconds()); + return format; } - if (!format) return "no format"; - format = format.replace("d", dateObject.getDate() < 10 ? "0" + dateObject.getDate() : dateObject.getDate()); - format = format.replace("D", dateObject.getDay()); - format = format.replace("Y", dateObject.getFullYear()); - format = format.replace("y", dateObject.getYear()); - var month = dateObject.getMonth() + 1; - format = format.replace("m", month < 10 ? "0" + month : month); - format = format.replace("H", (dateObject.getHours() < 10 ? "0" : "") + dateObject.getHours()); - // Support 12 hour format compatibility - format = format.replace("h", dateObject.getHours() % 12 || 12); - format = format.replace("p", dateObject.getHours() < 12 ? "am" : "pm"); - format = format.replace("P", dateObject.getHours() < 12 ? "AM" : "PM"); - format = format.replace("i", (dateObject.getMinutes() < 10 ? "0" : "") + dateObject.getMinutes()); - format = format.replace("s", (dateObject.getSeconds() < 10 ? "0" : "") + dateObject.getSeconds()); - return format; - }; + }]); return PathUtils; -})(); \ No newline at end of file +})(); diff --git a/core/src/plugins/gui.ajax/res/js/core/util/XMLUtils.js b/core/src/plugins/gui.ajax/res/js/core/util/XMLUtils.js index 993dd30fd8..8da3bf67ce 100644 --- a/core/src/plugins/gui.ajax/res/js/core/util/XMLUtils.js +++ b/core/src/plugins/gui.ajax/res/js/core/util/XMLUtils.js @@ -1,5 +1,7 @@ "use strict"; +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var XMLUtils = (function () { @@ -7,177 +9,185 @@ var XMLUtils = (function () { _classCallCheck(this, XMLUtils); } - XMLUtils.loadXPathReplacer = function loadXPathReplacer() { - if (document.createExpression) return; - PydioApi.loadLibrary("plugins/gui.ajax/res/js/vendor/xpath-polyfill/javascript-xpath-cmp.js", null, false); - }; - - /** - * Selects the first XmlNode that matches the XPath expression. - * - * @param element {Element | Document} root element for the search - * @param query {String} XPath query - * @return {Element} first matching element - * @signature function(element, query) - */ - - XMLUtils.XPathSelectSingleNode = function XPathSelectSingleNode(element, query) { - try { - var res = element.selectSingleNode(query); - if (res) return res; - } catch (e) {} - - if (!XMLUtils.__xpe) { + _createClass(XMLUtils, null, [{ + key: "loadXPathReplacer", + value: function loadXPathReplacer() { + if (document.createExpression) return; + PydioApi.loadLibrary('plugins/gui.ajax/res/js/vendor/xpath-polyfill/javascript-xpath-cmp.js', null, false); + } + + /** + * Selects the first XmlNode that matches the XPath expression. + * + * @param element {Element | Document} root element for the search + * @param query {String} XPath query + * @return {Element} first matching element + * @signature function(element, query) + */ + }, { + key: "XPathSelectSingleNode", + value: function XPathSelectSingleNode(element, query) { try { - XMLUtils.__xpe = new XPathEvaluator(); + var res = element.selectSingleNode(query); + if (res) return res; } catch (e) {} - } - if (!XMLUtils.__xpe) { - if (!document.createExpression) XMLUtils.loadXPathReplacer(); - query = document.createExpression(query, null); - var result = query.evaluate(element, 7, null); - return result.snapshotLength ? result.snapshotItem(0) : null; - } + if (!XMLUtils.__xpe) { + try { + XMLUtils.__xpe = new XPathEvaluator(); + } catch (e) {} + } + + if (!XMLUtils.__xpe) { + if (!document.createExpression) XMLUtils.loadXPathReplacer(); + query = document.createExpression(query, null); + var result = query.evaluate(element, 7, null); + return result.snapshotLength ? result.snapshotItem(0) : null; + } - var xpe = XMLUtils.__xpe; + var xpe = XMLUtils.__xpe; - try { - return xpe.evaluate(query, element, xpe.createNSResolver(element), XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; - } catch (err) { - throw new Error("selectSingleNode: query: " + query + ", element: " + element + ", error: " + err); + try { + return xpe.evaluate(query, element, xpe.createNSResolver(element), XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; + } catch (err) { + throw new Error("selectSingleNode: query: " + query + ", element: " + element + ", error: " + err); + } } - }; - - /** - * Selects a list of nodes matching the XPath expression. - * - * @param element {Element | Document} root element for the search - * @param query {String} XPath query - * @return {Element[]} List of matching elements - * @signature function(element, query) - */ - - XMLUtils.XPathSelectNodes = function XPathSelectNodes(element, query) { - try { + + /** + * Selects a list of nodes matching the XPath expression. + * + * @param element {Element | Document} root element for the search + * @param query {String} XPath query + * @return {Element[]} List of matching elements + * @signature function(element, query) + */ + }, { + key: "XPathSelectNodes", + value: function XPathSelectNodes(element, query) { try { - if (element.ownerDocument) { - element.ownerDocument.setProperty("SelectionLanguage", "XPath"); - } else { - element.setProperty("SelectionLanguage", "XPath"); - } + try { + if (element.ownerDocument) { + element.ownerDocument.setProperty("SelectionLanguage", "XPath"); + } else { + element.setProperty("SelectionLanguage", "XPath"); + } + } catch (e) {} + var res = Array.from(element.selectNodes(query)); + if (res) return res; } catch (e) {} - var res = Array.from(element.selectNodes(query)); - if (res) return res; - } catch (e) {} - var xpe = XMLUtils.__xpe; + var xpe = XMLUtils.__xpe; + + if (!xpe) { + try { + XMLUtils.__xpe = xpe = new XPathEvaluator(); + } catch (e) {} + } + var result, + nodes = [], + i; + if (!XMLUtils.__xpe) { + if (!document.createExpression) XMLUtils.loadXPathReplacer(); + query = document.createExpression(query, null); + result = query.evaluate(element, 7, null); + nodes = []; + for (i = 0; i < result.snapshotLength; i++) { + if (Element.extend) { + nodes[i] = Element.extend(result.snapshotItem(i)); + } else { + nodes[i] = result.snapshotItem(i); + } + } + return nodes; + } - if (!xpe) { try { - XMLUtils.__xpe = xpe = new XPathEvaluator(); - } catch (e) {} - } - var result, - nodes = [], - i; - if (!XMLUtils.__xpe) { - if (!document.createExpression) XMLUtils.loadXPathReplacer(); - query = document.createExpression(query, null); - result = query.evaluate(element, 7, null); - nodes = []; + result = xpe.evaluate(query, element, xpe.createNSResolver(element), XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); + } catch (err) { + throw new Error("selectNodes: query: " + query + ", element: " + element + ", error: " + err); + } + for (i = 0; i < result.snapshotLength; i++) { - if (Element.extend) { - nodes[i] = Element.extend(result.snapshotItem(i)); - } else { - nodes[i] = result.snapshotItem(i); - } + nodes[i] = result.snapshotItem(i); } - return nodes; - } - try { - result = xpe.evaluate(query, element, xpe.createNSResolver(element), XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); - } catch (err) { - throw new Error("selectNodes: query: " + query + ", element: " + element + ", error: " + err); + return nodes; } - for (i = 0; i < result.snapshotLength; i++) { - nodes[i] = result.snapshotItem(i); + /** + * Selects the first XmlNode that matches the XPath expression and returns the text content of the element + * + * @param element {Element|Document} root element for the search + * @param query {String} XPath query + * @return {String} the joined text content of the found element or null if not appropriate. + * @signature function(element, query) + */ + }, { + key: "XPathGetSingleNodeText", + value: function XPathGetSingleNodeText(element, query) { + var node = XPathSelectSingleNode(element, query); + return XMLUtils.getDomNodeText(node); } + }, { + key: "getDomNodeText", + value: function getDomNodeText(node) { + var includeCData = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; - return nodes; - }; - - /** - * Selects the first XmlNode that matches the XPath expression and returns the text content of the element - * - * @param element {Element|Document} root element for the search - * @param query {String} XPath query - * @return {String} the joined text content of the found element or null if not appropriate. - * @signature function(element, query) - */ - - XMLUtils.XPathGetSingleNodeText = function XPathGetSingleNodeText(element, query) { - var node = XPathSelectSingleNode(element, query); - return XMLUtils.getDomNodeText(node); - }; + if (!node || !node.nodeType) { + return null; + } - XMLUtils.getDomNodeText = function getDomNodeText(node) { - var includeCData = arguments[1] === undefined ? false : arguments[1]; + switch (node.nodeType) { + case 1: + // NODE_ELEMENT + var i, + a = [], + nodes = node.childNodes, + length = nodes.length; + for (i = 0; i < length; i++) { + a[i] = XMLUtils.getDomNodeText(nodes[i], includeCData); + } + + return a.join(""); + + case 2: + // NODE_ATTRIBUTE + return node.value; + + case 3: + // NODE_TEXT + return node.nodeValue; + + case 4: + // CDATA + if (includeCData) return node.nodeValue; + break; + } - if (!node || !node.nodeType) { return null; } - switch (node.nodeType) { - case 1: - // NODE_ELEMENT - var i, - a = [], - nodes = node.childNodes, - length = nodes.length; - for (i = 0; i < length; i++) { - a[i] = XMLUtils.getDomNodeText(nodes[i], includeCData); - } - - return a.join(""); - - case 2: - // NODE_ATTRIBUTE - return node.value; - - case 3: - // NODE_TEXT - return node.nodeValue; - - case 4: - // CDATA - if (includeCData) return node.nodeValue; - break; - } - - return null; - }; - - /** - * @param xmlStr - * @returns {*} - */ - - XMLUtils.parseXml = function parseXml(xmlStr) { - - if (typeof window.ActiveXObject != "undefined" && new window.ActiveXObject("MSXML2.DOMDocument.6.0")) { - var xmlDoc = new window.ActiveXObject("MSXML2.DOMDocument.6.0"); - xmlDoc.validateOnParse = false; - xmlDoc.async = false; - xmlDoc.loadXML(xmlStr); - xmlDoc.setProperty("SelectionLanguage", "XPath"); - return xmlDoc; - } else if (typeof window.DOMParser != "undefined") { - return new window.DOMParser().parseFromString(xmlStr, "text/xml"); + /** + * @param xmlStr + * @returns {*} + */ + }, { + key: "parseXml", + value: function parseXml(xmlStr) { + + if (typeof window.ActiveXObject != "undefined" && new window.ActiveXObject("MSXML2.DOMDocument.6.0")) { + var xmlDoc = new window.ActiveXObject("MSXML2.DOMDocument.6.0"); + xmlDoc.validateOnParse = false; + xmlDoc.async = false; + xmlDoc.loadXML(xmlStr); + xmlDoc.setProperty('SelectionLanguage', 'XPath'); + return xmlDoc; + } else if (typeof window.DOMParser != "undefined") { + return new window.DOMParser().parseFromString(xmlStr, "text/xml"); + } } - }; + }]); return XMLUtils; -})(); \ No newline at end of file +})();