Commit fd87000b authored by Tristan Cavelier's avatar Tristan Cavelier

grunt jio and jio.storages + remove console.log and tests code

parent add5497c
/*! JIO - v0.1.0 - 2012-08-14 /*! JIO - v0.1.0 - 2012-08-21
* Copyright (c) 2012 Nexedi; Licensed */ * Copyright (c) 2012 Nexedi; Licensed */
var jio = (function () { var jio = (function () {
"use strict";
var jioException = function(spec, my) { var jioException = function(spec, my) {
var that = {}; var that = {};
...@@ -68,6 +69,9 @@ var invalidJobException = function(spec, my) { ...@@ -68,6 +69,9 @@ var invalidJobException = function(spec, my) {
return that; return that;
}; };
var jio = function(spec) {
var storage = function(spec, my) { var storage = function(spec, my) {
var that = {}; var that = {};
spec = spec || {}; spec = spec || {};
...@@ -77,12 +81,12 @@ var storage = function(spec, my) { ...@@ -77,12 +81,12 @@ var storage = function(spec, my) {
priv.type = spec.type || ''; priv.type = spec.type || '';
// Methods // // Methods //
that.getType = function() { Object.defineProperty(that,"getType",{
configurable:false,enumerable:false,writable:false,value:
function() {
return priv.type; return priv.type;
}; }
that.setType = function(type) { });
priv.type = type;
};
/** /**
* Execute the command on this storage. * Execute the command on this storage.
...@@ -111,7 +115,8 @@ var storage = function(spec, my) { ...@@ -111,7 +115,8 @@ var storage = function(spec, my) {
that.validate = function () { that.validate = function () {
var mess = that.validateState(); var mess = that.validateState();
if (mess) { if (mess) {
that.error({status:0,statusText:'Invalid Storage', that.error({
status:0,statusText:'Invalid Storage',
error:'invalid_storage', error:'invalid_storage',
message:mess,reason:mess}); message:mess,reason:mess});
return false; return false;
...@@ -156,14 +161,6 @@ var storage = function(spec, my) { ...@@ -156,14 +161,6 @@ var storage = function(spec, my) {
that.error = function() {}; that.error = function() {};
that.end = function() {}; // terminate the current job. that.end = function() {}; // terminate the current job.
return that;
};
var storageHandler = function(spec, my) {
spec = spec || {};
my = my || {};
var that = storage( spec, my ), priv = {};
priv.newCommand = function (method, spec) { priv.newCommand = function (method, spec) {
var o = spec || {}; var o = spec || {};
o.label = method; o.label = method;
...@@ -182,9 +179,9 @@ var storageHandler = function(spec, my) { ...@@ -182,9 +179,9 @@ var storageHandler = function(spec, my) {
command_opt.doc = doc; command_opt.doc = doc;
} }
} }
my.jobManager.addJob ( jobManager.addJob (
job({ job({
storage:jioNamespace.storage(storage_spec||{}), storage:my.storage(storage_spec||{}),
command:priv.newCommand(method,command_opt) command:priv.newCommand(method,command_opt)
}, my) }, my)
); );
...@@ -788,13 +785,12 @@ var waitStatus = function(spec, my) { ...@@ -788,13 +785,12 @@ var waitStatus = function(spec, my) {
return that; return that;
}; };
var job = function(spec, my) { var job = function(spec) {
var that = {}; var that = {};
spec = spec || {}; spec = spec || {};
my = my || {};
// Attributes // // Attributes //
var priv = {}; var priv = {};
priv.id = my.jobIdHandler.nextId(); priv.id = jobIdHandler.nextId();
priv.command = spec.command; priv.command = spec.command;
priv.storage = spec.storage; priv.storage = spec.storage;
priv.status = initialStatus(); priv.status = initialStatus();
...@@ -866,7 +862,7 @@ var job = function(spec, my) { ...@@ -866,7 +862,7 @@ var job = function(spec, my) {
*/ */
that.waitForJob = function(job) { that.waitForJob = function(job) {
if (priv.status.getLabel() !== 'wait') { if (priv.status.getLabel() !== 'wait') {
priv.status = waitStatus({},my); priv.status = waitStatus({});
} }
priv.status.waitForJob(job); priv.status.waitForJob(job);
}; };
...@@ -889,7 +885,7 @@ var job = function(spec, my) { ...@@ -889,7 +885,7 @@ var job = function(spec, my) {
*/ */
that.waitForTime = function(ms) { that.waitForTime = function(ms) {
if (priv.status.getLabel() !== 'wait') { if (priv.status.getLabel() !== 'wait') {
priv.status = waitStatus({},my); priv.status = waitStatus({});
} }
priv.status.waitForTime(ms); priv.status.waitForTime(ms);
}; };
...@@ -907,18 +903,19 @@ var job = function(spec, my) { ...@@ -907,18 +903,19 @@ var job = function(spec, my) {
that.eliminated = function () { that.eliminated = function () {
priv.command.error ({ priv.command.error ({
status:10,statusText:'Stopped',error:'stopped', status:10,statusText:'Stopped',error:'stopped',
message:'This job has been stoped by another one.', message:'This job has been stopped by another one.',
reason:this.message}); reason:'this job has been stopped by another one'});
}; };
that.notAccepted = function () { that.notAccepted = function () {
priv.command.onEndDo (function () { priv.command.onEndDo (function () {
priv.status = failStatus(); priv.status = failStatus();
my.jobManager.terminateJob (that); jobManager.terminateJob (that);
}); });
priv.command.error ({ priv.command.error ({
status:11,statusText:'Not Accepted',error:'not_accepted', status:11,statusText:'Not Accepted',error:'not_accepted',
message:'This job is already running.',reason:this.message}); message:'This job is already running.',
reason:'this job is already running'});
}; };
/** /**
...@@ -960,7 +957,7 @@ var job = function(spec, my) { ...@@ -960,7 +957,7 @@ var job = function(spec, my) {
}); });
priv.command.onEndDo (function(status) { priv.command.onEndDo (function(status) {
priv.status = status; priv.status = status;
my.jobManager.terminateJob (that); jobManager.terminateJob (that);
}); });
priv.command.execute (priv.storage); priv.command.execute (priv.storage);
}; };
...@@ -1009,9 +1006,6 @@ var announcement = function(spec, my) { ...@@ -1009,9 +1006,6 @@ var announcement = function(spec, my) {
return that; return that;
}; };
var jio = function(spec, my) {
var activityUpdater = (function(spec, my) { var activityUpdater = (function(spec, my) {
var that = {}; var that = {};
spec = spec || {}; spec = spec || {};
...@@ -1123,10 +1117,9 @@ var announcer = (function(spec, my) { ...@@ -1123,10 +1117,9 @@ var announcer = (function(spec, my) {
return that; return that;
}()); }());
var jobIdHandler = (function(spec, my) { var jobIdHandler = (function(spec) {
var that = {}; var that = {};
spec = spec || {}; spec = spec || {};
my = my || {};
// Attributes // // Attributes //
var id = 0; var id = 0;
// Methods // // Methods //
...@@ -1138,10 +1131,9 @@ var jobIdHandler = (function(spec, my) { ...@@ -1138,10 +1131,9 @@ var jobIdHandler = (function(spec, my) {
return that; return that;
}()); }());
var jobManager = (function(spec, my) { var jobManager = (function(spec) {
var that = {}; var that = {};
spec = spec || {}; spec = spec || {};
my = my || {};
// Attributes // // Attributes //
var job_array_name = 'jio/job_array'; var job_array_name = 'jio/job_array';
var priv = {}; var priv = {};
...@@ -1150,9 +1142,6 @@ var jobManager = (function(spec, my) { ...@@ -1150,9 +1142,6 @@ var jobManager = (function(spec, my) {
priv.interval = 200; priv.interval = 200;
priv.job_array = []; priv.job_array = [];
my.jobManager = that;
my.jobIdHandler = jobIdHandler;
// Methods // // Methods //
/** /**
* Get the job array name in the localStorage * Get the job array name in the localStorage
...@@ -1280,11 +1269,11 @@ var jobManager = (function(spec, my) { ...@@ -1280,11 +1269,11 @@ var jobManager = (function(spec, my) {
var i, jio_job_array; var i, jio_job_array;
jio_job_array = LocalOrCookieStorage.getItem('jio/job_array/'+id)||[]; jio_job_array = LocalOrCookieStorage.getItem('jio/job_array/'+id)||[];
for (i = 0; i < jio_job_array.length; i+= 1) { for (i = 0; i < jio_job_array.length; i+= 1) {
var command_object = command(jio_job_array[i].command, my); var command_object = command(jio_job_array[i].command);
if (command_object.canBeRestored()) { if (command_object.canBeRestored()) {
that.addJob ( job( that.addJob ( job(
{storage:jioNamespace.storage(jio_job_array[i].storage,my), {storage:that.storage(jio_job_array[i].storage),
command:command_object}, my)); command:command_object}));
} }
} }
}; };
...@@ -1433,18 +1422,33 @@ var jobManager = (function(spec, my) { ...@@ -1433,18 +1422,33 @@ var jobManager = (function(spec, my) {
return that; return that;
}()); }());
var jobRules = (function(spec, my) { var jobRules = (function(spec) {
var that = {}; var that = {};
// Attributes // // Attributes //
var priv = {}; var priv = {};
priv.compare = {}; priv.compare = {};
priv.action = {}; priv.action = {};
that.eliminate = function() { return 'eliminate'; }; Object.defineProperty(that,"eliminate",{
that.update = function() { return 'update'; }; configurable:false,enumerable:false,writable:false,value:
that.dontAccept = function() { return 'dont accept'; }; function() { return 'eliminate'; }
that.wait = function() { return 'wait'; }; });
that.none = function() { return 'none'; }; Object.defineProperty(that,"update",{
configurable:false,enumerable:false,writable:false,value:
function() { return 'update'; }
});
Object.defineProperty(that,"dontAccept",{
configurable:false,enumerable:false,writable:false,value:
function() { return 'dont accept'; }
});
Object.defineProperty(that,"wait",{
configurable:false,enumerable:false,writable:false,value:
function() { return 'wait'; }
});
Object.defineProperty(that,"none",{
configurable:false,enumerable:false,writable:false,value:
function() { return 'none'; }
});
that.default_action = that.none; that.default_action = that.none;
that.default_compare = function(job1,job2) { that.default_compare = function(job1,job2) {
return (job1.getCommand().getDocId() === return (job1.getCommand().getDocId() ===
...@@ -1505,12 +1509,15 @@ var jobRules = (function(spec, my) { ...@@ -1505,12 +1509,15 @@ var jobRules = (function(spec, my) {
* @param job2 {object} The new job. * @param job2 {object} The new job.
* @return {string} The action string. * @return {string} The action string.
*/ */
that.validateJobAccordingToJob = function(job1,job2) { Object.defineProperty(that,"validateJobAccordingToJob",{
configurable:false,enumerable:false,writable:false,value:
function(job1,job2) {
if (priv.canCompare(job1,job2)) { if (priv.canCompare(job1,job2)) {
return {action:priv.getAction(job1,job2),job:job1}; return {action:priv.getAction(job1,job2),job:job1};
} }
return {action:that.default_action(job1,job2),job:job1}; return {action:that.default_action(job1,job2),job:job1};
}; }
});
/** /**
* Adds a rule the action rules. * Adds a rule the action rules.
...@@ -1520,12 +1527,16 @@ var jobRules = (function(spec, my) { ...@@ -1520,12 +1527,16 @@ var jobRules = (function(spec, my) {
* @param method2 {string} The action label from the new job. * @param method2 {string} The action label from the new job.
* @param rule {function} The rule that return an action string. * @param rule {function} The rule that return an action string.
*/ */
that.addActionRule = function(method1,ongoing,method2,rule) { Object.defineProperty(that,"addActionRule",{
configurable:false,enumerable:false,writable:false,value:
function(method1,ongoing,method2,rule) {
var ongoing_s = (ongoing?'on going':'not on going'); var ongoing_s = (ongoing?'on going':'not on going');
priv.action[method1] = priv.action[method1] || {}; priv.action[method1] = priv.action[method1] || {};
priv.action[method1][ongoing_s] = priv.action[method1][ongoing_s] || {}; priv.action[method1][ongoing_s] =
priv.action[method1][ongoing_s] || {};
priv.action[method1][ongoing_s][method2] = rule; priv.action[method1][ongoing_s][method2] = rule;
}; }
});
/** /**
* Adds a rule the compare rules. * Adds a rule the compare rules.
...@@ -1535,10 +1546,13 @@ var jobRules = (function(spec, my) { ...@@ -1535,10 +1546,13 @@ var jobRules = (function(spec, my) {
* @param rule {function} The rule that return a boolean * @param rule {function} The rule that return a boolean
* - true if job1 and job2 can be compared, else false. * - true if job1 and job2 can be compared, else false.
*/ */
that.addCompareRule = function(method1,method2,rule) { Object.defineProperty(that,"addCompareRule",{
configurable:false,enumerable:false,writable:false,value:
function(method1,method2,rule) {
priv.compare[method1] = priv.compare[method1] || {}; priv.compare[method1] = priv.compare[method1] || {};
priv.compare[method1][method2] = rule; priv.compare[method1][method2] = rule;
}; }
});
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
// Adding some rules // Adding some rules
...@@ -1628,16 +1642,12 @@ var jobRules = (function(spec, my) { ...@@ -1628,16 +1642,12 @@ var jobRules = (function(spec, my) {
}()); }());
// Class jio // Class jio
var that = {}; var that = {}, priv = {};
spec = spec || {}; spec = spec || {};
my = my || {};
// Attributes // // Attributes //
var priv = {};
var jio_id_array_name = 'jio/id_array'; var jio_id_array_name = 'jio/id_array';
priv.id = null; priv.id = null;
my.jobManager = jobManager;
my.jobIdHandler = jobIdHandler;
priv.storage_spec = spec; priv.storage_spec = spec;
// initialize // // initialize //
...@@ -1660,38 +1670,80 @@ var jobRules = (function(spec, my) { ...@@ -1660,38 +1670,80 @@ var jobRules = (function(spec, my) {
}; };
// Methods // // Methods //
that.start = function() { /**
* Returns a storage from a storage description.
* @method storage
* @param {object} spec The specifications.
* @param {object} my The protected object.
* @param {string} forcetype Force storage type
* @return {object} The storage object.
*/
Object.defineProperty(that,"storage",{
configurable:false,enumerable:false,writable:false,value:
function(spec, my, forcetype) {
spec = spec || {};
my = my || {};
my.basicStorage = storage;
my.storage = that.storage; // NOTE : or proxy storage
var type = forcetype || spec.type || 'base';
if (type === 'base') {
return storage(spec, my);
}
if (!storage_type_object[type]) {
throw invalidStorageType(
{type:type,message:'Storage does not exists.'});
}
return storage_type_object[type](spec, my);
}
});
jobManager.storage = that.storage;
Object.defineProperty(that,"start",{
configurable:false,enumerable:false,writable:false,value:
function() {
priv.init(); priv.init();
activityUpdater.start(); activityUpdater.start();
jobManager.start(); jobManager.start();
}; }
that.stop = function() { });
Object.defineProperty(that,"stop",{
configurable:false,enumerable:false,writable:false,value:
function() {
jobManager.stop(); jobManager.stop();
}; }
that.close = function() { });
Object.defineProperty(that,"close",{
configurable:false,enumerable:false,writable:false,value:
function() {
activityUpdater.stop(); activityUpdater.stop();
jobManager.stop(); jobManager.stop();
priv.id = null; priv.id = null;
}; }
that.start(); });
/** /**
* Returns the jio id. * Returns the jio id.
* @method getId * @method getId
* @return {number} The jio id. * @return {number} The jio id.
*/ */
that.getId = function() { Object.defineProperty(that,"getId",{
configurable:false,enumerable:false,writable:false,value:
function() {
return priv.id; return priv.id;
}; }
});
/** /**
* Returns the jio job rules object used by the job manager. * Returns the jio job rules object used by the job manager.
* @method getJobRules * @method getJobRules
* @return {object} The job rules object * @return {object} The job rules object
*/ */
that.getJobRules = function() { Object.defineProperty(that,"getJobRules",{
configurable:false,enumerable:false,writable:false,value:
function() {
return jobRules; return jobRules;
}; }
});
/** /**
* Checks if the storage description is valid or not. * Checks if the storage description is valid or not.
...@@ -1699,13 +1751,19 @@ var jobRules = (function(spec, my) { ...@@ -1699,13 +1751,19 @@ var jobRules = (function(spec, my) {
* @param {object} description The description object. * @param {object} description The description object.
* @return {boolean} true if ok, else false. * @return {boolean} true if ok, else false.
*/ */
that.validateStorageDescription = function(description) { Object.defineProperty(that,"validateStorageDescription",{
return jioNamespace.storage(description, my).isValid(); configurable:false,enumerable:false,writable:false,value:
}; function(description) {
return that.storage(description).isValid();
}
});
that.getJobArray = function () { Object.defineProperty(that,"getJobArray",{
configurable:false,enumerable:false,writable:false,value:
function () {
return jobManager.serialized(); return jobManager.serialized();
}; }
});
priv.getParam = function (list,nodoc) { priv.getParam = function (list,nodoc) {
var param = {}, i = 0; var param = {}, i = 0;
...@@ -1739,33 +1797,36 @@ var jobRules = (function(spec, my) { ...@@ -1739,33 +1797,36 @@ var jobRules = (function(spec, my) {
priv.addJob = function (commandCreator,spec) { priv.addJob = function (commandCreator,spec) {
jobManager.addJob( jobManager.addJob(
job({storage:jioNamespace.storage(priv.storage_spec,my), job({storage:that.storage(priv.storage_spec),
command:commandCreator(spec,my)},my)); command:commandCreator(spec)}));
}; };
// /** /**
// * Post a document. * Post a document.
// * @method post * @method post
// * @param {object} doc The document {"content":}. * @param {object} doc The document {"content":}.
// * @param {object} options (optional) Contains some options: * @param {object} options (optional) Contains some options:
// * - {number} max_retry The number max of retries, 0 = infinity. * - {number} max_retry The number max of retries, 0 = infinity.
// * - {boolean} revs Include revision history of the document. * - {boolean} revs Include revision history of the document.
// * - {boolean} revs_info Retreive the revisions. * - {boolean} revs_info Retreive the revisions.
// * - {boolean} conflicts Retreive the conflict list. * - {boolean} conflicts Retreive the conflict list.
// * @param {function} callback (optional) The callback(err,response). * @param {function} callback (optional) The callback(err,response).
// * @param {function} error (optional) The callback on error, if this * @param {function} error (optional) The callback on error, if this
// * callback is given in parameter, "callback" is changed as "success", * callback is given in parameter, "callback" is changed as "success",
// * called on success. * called on success.
// */ */
// that.post = function() { Object.defineProperty(that,"post",{
// var param = priv.getParam(arguments); configurable:false,enumerable:false,writable:false,value:
// param.options.max_retry = param.options.max_retry || 0; function() {
// priv.addJob(postCommand,{ var param = priv.getParam(arguments);
// doc:param.doc, param.options.max_retry = param.options.max_retry || 0;
// options:param.options, priv.addJob(postCommand,{
// callbacks:{success:param.success,error:param.error} doc:param.doc,
// }); options:param.options,
// }; callbacks:{success:param.success,error:param.error}
});
}
});
/** /**
* Put a document. * Put a document.
...@@ -1781,7 +1842,9 @@ var jobRules = (function(spec, my) { ...@@ -1781,7 +1842,9 @@ var jobRules = (function(spec, my) {
* callback is given in parameter, "callback" is changed as "success", * callback is given in parameter, "callback" is changed as "success",
* called on success. * called on success.
*/ */
that.put = function() { Object.defineProperty(that,"put",{
configurable:false,enumerable:false,writable:false,value:
function() {
var param = priv.getParam(arguments); var param = priv.getParam(arguments);
param.options.max_retry = param.options.max_retry || 0; param.options.max_retry = param.options.max_retry || 0;
priv.addJob(putCommand,{ priv.addJob(putCommand,{
...@@ -1789,7 +1852,8 @@ var jobRules = (function(spec, my) { ...@@ -1789,7 +1852,8 @@ var jobRules = (function(spec, my) {
options:param.options, options:param.options,
callbacks:{success:param.success,error:param.error} callbacks:{success:param.success,error:param.error}
}); });
}; }
});
/** /**
* Get a document. * Get a document.
...@@ -1807,7 +1871,9 @@ var jobRules = (function(spec, my) { ...@@ -1807,7 +1871,9 @@ var jobRules = (function(spec, my) {
* callback is given in parameter, "callback" is changed as "success", * callback is given in parameter, "callback" is changed as "success",
* called on success. * called on success.
*/ */
that.get = function() { Object.defineProperty(that,"get",{
configurable:false,enumerable:false,writable:false,value:
function() {
var param = priv.getParam(arguments); var param = priv.getParam(arguments);
param.options.max_retry = param.options.max_retry || 3; param.options.max_retry = param.options.max_retry || 3;
param.options.metadata_only = ( param.options.metadata_only = (
...@@ -1818,7 +1884,8 @@ var jobRules = (function(spec, my) { ...@@ -1818,7 +1884,8 @@ var jobRules = (function(spec, my) {
options:param.options, options:param.options,
callbacks:{success:param.success,error:param.error} callbacks:{success:param.success,error:param.error}
}); });
}; }
});
/** /**
* Remove a document. * Remove a document.
...@@ -1834,7 +1901,9 @@ var jobRules = (function(spec, my) { ...@@ -1834,7 +1901,9 @@ var jobRules = (function(spec, my) {
* callback is given in parameter, "callback" is changed as "success", * callback is given in parameter, "callback" is changed as "success",
* called on success. * called on success.
*/ */
that.remove = function() { Object.defineProperty(that,"remove",{
configurable:false,enumerable:false,writable:false,value:
function() {
var param = priv.getParam(arguments); var param = priv.getParam(arguments);
param.options.max_retry = param.options.max_retry || 0; param.options.max_retry = param.options.max_retry || 0;
priv.addJob(removeCommand,{ priv.addJob(removeCommand,{
...@@ -1842,7 +1911,8 @@ var jobRules = (function(spec, my) { ...@@ -1842,7 +1911,8 @@ var jobRules = (function(spec, my) {
options:param.options, options:param.options,
callbacks:{success:param.success,error:param.error} callbacks:{success:param.success,error:param.error}
}); });
}; }
});
/** /**
* Get a list of documents. * Get a list of documents.
...@@ -1859,7 +1929,9 @@ var jobRules = (function(spec, my) { ...@@ -1859,7 +1929,9 @@ var jobRules = (function(spec, my) {
* callback is given in parameter, "callback" is changed as "success", * callback is given in parameter, "callback" is changed as "success",
* called on success. * called on success.
*/ */
that.allDocs = function() { Object.defineProperty(that,"allDocs",{
configurable:false,enumerable:false,writable:false,value:
function() {
var param = priv.getParam(arguments,'no doc'); var param = priv.getParam(arguments,'no doc');
param.options.max_retry = param.options.max_retry || 3; param.options.max_retry = param.options.max_retry || 3;
param.options.metadata_only = ( param.options.metadata_only = (
...@@ -1869,42 +1941,22 @@ var jobRules = (function(spec, my) { ...@@ -1869,42 +1941,22 @@ var jobRules = (function(spec, my) {
options:param.options, options:param.options,
callbacks:{success:param.success,error:param.error} callbacks:{success:param.success,error:param.error}
}); });
}; }
});
return that; return that;
}; // End Class jio }; // End Class jio
var jioNamespace = (function(spec, my) { var storage_type_object = { // -> 'key':constructorFunction
'base': function () {} // overriden by jio
};
var jioNamespace = (function(spec) {
var that = {}; var that = {};
spec = spec || {}; spec = spec || {};
my = my || {};
// Attributes // // Attributes //
var storage_type_o = { // -> 'key':constructorFunction
'base': storage,
'handler': storageHandler
};
// Methods // // Methods //
/**
* Returns a storage from a storage description.
* @method storage
* @param {object} spec The specifications.
* @param {object} my The protected object.
* @param {string} forcetype Force storage type
* @return {object} The storage object.
*/
that.storage = function(spec, my, forcetype) {
spec = spec || {};
my = my || {};
var type = forcetype || spec.type || 'base';
if (!storage_type_o[type]) {
throw invalidStorageType({type:type,
message:'Storage does not exists.'});
}
return storage_type_o[type](spec, my);
};
/** /**
* Creates a new jio instance. * Creates a new jio instance.
* @method newJio * @method newJio
...@@ -1915,14 +1967,19 @@ var jioNamespace = (function(spec, my) { ...@@ -1915,14 +1967,19 @@ var jioNamespace = (function(spec, my) {
* - {string} spec.storage.applicationname: The application name * - {string} spec.storage.applicationname: The application name
* @return {object} The new Jio instance. * @return {object} The new Jio instance.
*/ */
that.newJio = function(spec) { Object.defineProperty(that,"newJio",{
var storage = spec; configurable:false,enumerable:false,writable:false,value:
function(spec) {
var storage = spec, instance = null;
if (typeof storage === 'string') { if (typeof storage === 'string') {
storage = JSON.parse (storage); storage = JSON.parse (storage);
} }
storage = storage || {type:'base'}; storage = storage || {type:'base'};
return jio(spec); instance = jio(spec);
}; instance.start();
return instance;
}
});
/** /**
* Add a storage type to jio. * Add a storage type to jio.
...@@ -1930,13 +1987,16 @@ var jioNamespace = (function(spec, my) { ...@@ -1930,13 +1987,16 @@ var jioNamespace = (function(spec, my) {
* @param {string} type The storage type * @param {string} type The storage type
* @param {function} constructor The associated constructor * @param {function} constructor The associated constructor
*/ */
that.addStorageType = function(type, constructor) { Object.defineProperty(that,"addStorageType",{
configurable:false,enumerable:false,writable:false,value:
function(type, constructor) {
constructor = constructor || function(){return null;}; constructor = constructor || function(){return null;};
if (storage_type_o[type]) { if (storage_type_object[type]) {
throw invalidStorageType({type:type,message:'Already known.'}); throw invalidStorageType({type:type,message:'Already known.'});
} }
storage_type_o[type] = constructor; storage_type_object[type] = constructor;
}; }
});
return that; return that;
}()); }());
......
/*! JIO - v0.1.0 - 2012-08-14 /*! JIO - v0.1.0 - 2012-08-21
* Copyright (c) 2012 Nexedi; Licensed */ * Copyright (c) 2012 Nexedi; Licensed */
var jio=function(){var a=function(a,b){var c={};return a=a||{},b=b||{},c.name="jioException",c.message=a.message||"Unknown Reason.",c.toString=function(){return c.name+": "+c.message},c},b=function(b,c){var d=a(b,c);b=b||{};var e=b.command;return d.name="invalidCommandState",d.toString=function(){return d.name+": "+e.getLabel()+", "+d.message},d},c=function(b,c){var d=a(b,c);b=b||{};var e=b.storage.getType();return d.name="invalidStorage",d.toString=function(){return d.name+": "+'Type "'+e+'", '+d.message},d},d=function(b,c){var d=a(b,c),e=b.type;return d.name="invalidStorageType",d.toString=function(){return d.name+": "+e+", "+d.message},d},e=function(b,c){var d=a(b,c);return d.name="jobNotReadyException",d},f=function(b,c){var d=a(b,c);return d.name="tooMuchTriesJobException",d},g=function(b,c){var d=a(b,c);return d.name="invalidJobException",d},h=function(a,b){var c={};a=a||{},b=b||{};var d={};return d.type=a.type||"",c.getType=function(){return d.type},c.setType=function(a){d.type=a},c.execute=function(a){c.success=a.success,c.error=a.error,c.retry=a.retry,c.end=a.end,c.validate(a)&&a.executeOn(c)},c.isValid=function(){return!0},c.validate=function(){var a=c.validateState();return a?(c.error({status:0,statusText:"Invalid Storage",error:"invalid_storage",message:a,reason:a}),!1):!0},c.serialized=function(){return{type:c.getType()}},c.saveDocument=function(a){c.error({status:0,statusText:"Unknown storage",error:"unknown_storage",message:"Unknown Storage"})},c.loadDocument=function(a){c.saveDocument()},c.removeDocument=function(a){c.saveDocument()},c.getDocumentList=function(a){c.saveDocument()},c.validateState=function(){return""},c.success=function(){},c.retry=function(){},c.error=function(){},c.end=function(){},c},i=function(a,b){a=a||{},b=b||{};var c=h(a,b),d={};return d.newCommand=function(a,c){var d=c||{};return d.label=a,j(d,b)},c.addJob=function(a,c,e,f,g,h){var i={options:f,callbacks:{success:g,error:h}};e&&(a==="get"?i.docid=e:i.doc=e),b.jobManager.addJob(v({storage:y.storage(c||{}),command:d.newCommand(a,i)},b))},c},j=function(a,b){var c={};a=a||{},b=b||{};var d={};return d.commandlist={post:o,put:n,get:l,remove:m,allDocs:k},a.label&&d.commandlist[a.label]?(d.label=a.label,delete a.label,d.commandlist[d.label](a,b)):(d.tried=0,d.doc=a.doc||{},d.docid=a.docid||"",d.option=a.options||{},d.callbacks=a.callbacks||{},d.success=d.callbacks.success||function(){},d.error=d.callbacks.error||function(){},d.retry=function(){c.error({status:13,statusText:"Fail Retry",error:"fail_retry",message:"Impossible to retry.",reason:"Impossible to retry."})},d.end=function(){},d.on_going=!1,c.serialized=function(){return{label:c.getLabel(),tried:d.tried,doc:c.cloneDoc(),option:c.cloneOption()}},c.getLabel=function(){return"command"},c.getDocId=function(){return d.docid||d.doc._id},c.getDocContent=function(){return d.doc.content},c.getDocInfo=function(a){return d.doc[a]},c.getOption=function(a){return d.option[a]},c.validate=function(a){return c.validateState()?a.validate():!1},c.validateState=function(){return typeof d.doc!="object"?(c.error({status:20,statusText:"Document_Id Required",error:"document_id_required",message:"No document id.",reason:"no document id"}),!1):!0},c.canBeRetried=function(){return typeof d.option.max_retry=="undefined"||d.option.max_retry===0||d.tried<d.option.max_retry},c.getTried=function(){return d.tried},c.execute=function(a){d.on_going||c.validate(a)&&(d.tried++,d.on_going=!0,a.execute(c))},c.executeOn=function(a){},c.success=function(a){d.on_going=!1,d.success(a),d.end(q())},c.retry=function(a){d.on_going=!1,c.canBeRetried()?d.retry():c.error(a)},c.error=function(a){d.on_going=!1,d.error(a),d.end(r())},c.end=function(){d.end(q())},c.onSuccessDo=function(a){if(a)d.success=a;else return d.success},c.onErrorDo=function(a){if(a)d.error=a;else return d.error},c.onEndDo=function(a){d.end=a},c.onRetryDo=function(a){d.retry=a},c.canBeRestored=function(){return!0},c.clone=function(){return j(c.serialized(),b)},c.cloneOption=function(){var a,b={};for(a in d.option)b[a]=d.option[a];return b},c.cloneDoc=function(){if(d.docid)return d.docid;var a,b={};for(a in d.doc)b[a]=d.doc[a];return b},c)},k=function(a,b){var c=j(a,b);return a=a||{},b=b||{},c.getLabel=function(){return"allDocs"},c.executeOn=function(a){a.allDocs(c)},c.canBeRestored=function(){return!1},c},l=function(a,b){var c=j(a,b);return a=a||{},b=b||{},c.getLabel=function(){return"get"},c.validateState=function(){return c.getDocId()?!0:(c.error({status:20,statusText:"Document Id Required",error:"document_id_required",message:"No document id.",reason:"no document id"}),!1)},c.executeOn=function(a){a.get(c)},c.canBeRestored=function(){return!1},c},m=function(a,b){var c=j(a,b);return a=a||{},b=b||{},c.getLabel=function(){return"remove"},c.executeOn=function(a){a.remove(c)},c},n=function(a,b){var c=j(a,b);a=a||{},b=b||{};var d={};c.getLabel=function(){return"put"};var e=c.validateState;return c.validate=function(){return typeof c.getDocInfo("content")!="string"?(c.error({status:21,statusText:"Content Required",error:"content_required",message:"No data to put.",reason:"no data to put"}),!1):e()},c.executeOn=function(a){a.put(c)},c},o=function(a,b){var c=j(a,b);a=a||{},b=b||{};var d={};c.getLabel=function(){return"post"};var e=c.validateState;return c.validate=function(){return typeof c.getDocInfo("content")!="string"?(c.error({status:21,statusText:"Content Required",error:"content_required",message:"No data to put.",reason:"no data to put"}),!1):e()},c.executeOn=function(a){a.put(c)},c},p=function(a,b){var c={};return a=a||{},b=b||{},c.getLabel=function(){return"job status"},c.canStart=function(){},c.canRestart=function(){},c.serialized=function(){return{label:c.getLabel()}},c.isWaitStatus=function(){return!1},c.isDone=function(){return!1},c},q=function(a,b){var c=p(a,b);return a=a||{},b=b||{},c.getLabel=function(){return"done"},c.canStart=function(){return!1},c.canRestart=function(){return!1},c.isDone=function(){return!0},c},r=function(a,b){var c=p(a,b);return a=a||{},b=b||{},c.getLabel=function(){return"fail"},c.canStart=function(){return!1},c.canRestart=function(){return!0},c},s=function(a,b){var c=p(a,b);return a=a||{},b=b||{},c.getLabel=function(){return"initial"},c.canStart=function(){return!0},c.canRestart=function(){return!0},c},t=function(a,b){var c=p(a,b);return a=a||{},b=b||{},c.getLabel=function(){return"on going"},c.canStart=function(){return!1},c.canRestart=function(){return!1},c},u=function(a,b){var c=p(a,b);a=a||{},b=b||{};var d={};return d.job_id_array=a.job_id_array||[],d.threshold=0,c.getLabel=function(){return"wait"},d.refreshJobIdArray=function(){var a=[],c;for(c=0;c<d.job_id_array.length;c+=1)b.jobManager.jobIdExists(d.job_id_array[c])&&a.push(d.job_id_array[c]);d.job_id_array=a},c.waitForJob=function(a){var b;for(b=0;b<d.job_id_array.length;b+=1)if(d.job_id_array[b]===a.getId())return;d.job_id_array.push(a.getId())},c.dontWaitForJob=function(a){var b,c=[];for(b=0;b<d.job_id_array.length;b+=1)d.job_id_array[b]!==a.getId()&&c.push(d.job_id_array[b]);d.job_id_array=c},c.waitForTime=function(a){d.threshold=Date.now()+a},c.stopWaitForTime=function(){d.threshold=0},c.canStart=function(){return d.refreshJobIdArray(),d.job_id_array.length===0&&Date.now()>=d.threshold},c.canRestart=function(){return c.canStart()},c.serialized=function(){return{label:c.getLabel(),waitfortime:d.threshold,waitforjob:d.job_id_array}},c.isWaitStatus=function(){return!0},c},v=function(a,b){var c={};a=a||{},b=b||{};var d={};d.id=b.jobIdHandler.nextId(),d.command=a.command,d.storage=a.storage,d.status=s(),d.date=new Date;if(!d.storage)throw g({job:c,message:"No storage set"});if(!d.command)throw g({job:c,message:"No command set"});return c.getCommand=function(){return d.command},c.getStatus=function(){return d.status},c.getId=function(){return d.id},c.getStorage=function(){return d.storage},c.getDate=function(){return d.date},c.isReady=function(){return d.command.getTried()===0?d.status.canStart():d.status.canRestart()},c.serialized=function(){return{id:d.id,date:d.date.getTime(),status:d.status.serialized(),command:d.command.serialized(),storage:d.storage.serialized()}},c.waitForJob=function(a){d.status.getLabel()!=="wait"&&(d.status=u({},b)),d.status.waitForJob(a)},c.dontWaitFor=function(a){d.status.getLabel()==="wait"&&d.status.dontWaitForJob(a)},c.waitForTime=function(a){d.status.getLabel()!=="wait"&&(d.status=u({},b)),d.status.waitForTime(a)},c.stopWaitForTime=function(){d.status.getLabel()==="wait"&&d.status.stopWaitForTime()},c.eliminated=function(){d.command.error({status:10,statusText:"Stopped",error:"stopped",message:"This job has been stoped by another one.",reason:this.message})},c.notAccepted=function(){d.command.onEndDo(function(){d.status=r(),b.jobManager.terminateJob(c)}),d.command.error({status:11,statusText:"Not Accepted",error:"not_accepted",message:"This job is already running.",reason:this.message})},c.update=function(a){d.command.error({status:12,statusText:"Replaced",error:"replaced",message:"Job has been replaced by another one.",reason:"job has been replaced by another one"}),d.date=new Date(a.getDate().getTime()),d.command=a.getCommand(),d.status=a.getStatus()},c.execute=function(){if(!c.getCommand().canBeRetried())throw f({job:c,message:"The job was invoked too much time."});if(!c.isReady())throw e({job:c,message:"Can not execute this job."});d.status=t(),d.command.onRetryDo(function(){var a=d.command.getTried();a=a*a*200,a>1e4&&(a=1e4),c.waitForTime(a)}),d.command.onEndDo(function(a){d.status=a,b.jobManager.terminateJob(c)}),d.command.execute(d.storage)},c},w=function(a,b){var c={};a=a||{},b=b||{};var d=[],e=a.name||"",f=a.announcer||{};return c.add=function(a){d.push(a)},c.remove=function(a){var b,c=[];for(b=0;b<d.length;b+=1)d[b]!==a&&c.push(d[b]);d=c},c.register=function(){f.register(c)},c.unregister=function(){f.unregister(c)},c.trigger=function(a){var b;for(b=0;b<d.length;b++)d[b].apply(null,a)},c},x=function(a,b){var c=function(a,b){var c={};a=a||{},b=b||{};var d={};return d.id=a.id||0,d.interval=400,d.interval_id=null,d.touch=function(){LocalOrCookieStorage.setItem("jio/id/"+d.id,Date.now())},c.setId=function(a){d.id=a},c.setIntervalDelay=function(a){d.interval=a},c.getIntervalDelay=function(){return d.interval},c.start=function(){d.interval_id||(d.touch(),d.interval_id=setInterval(function(){d.touch()},d.interval))},c.stop=function(){d.interval_id!==null&&(clearInterval(d.interval_id),d.interval_id=null)},c}(),d=function(a,b){var c={};a=a||{},b=b||{};var d={};return c.register=function(a){d[a]||(d[a]=w())},c.unregister=function(a){d[a]&&delete d[a]},c.at=function(a){return d[a]},c.on=function(a,b){c.register(a),c.at(a).add(b)},c.trigger=function(a,b){c.at(a).trigger(b)},c}(),e=function(a,b){var c={};a=a||{},b=b||{};var d=0;return c.nextId=function(){return d=d+1,d},c}(),f=function(a,b){var c={};a=a||{},b=b||{};var d="jio/job_array",f={};return f.id=a.id,f.interval_id=null,f.interval=200,f.job_array=[],b.jobManager=c,b.jobIdHandler=e,f.getJobArrayName=function(){return d+"/"+f.id},f.getJobArray=function(){return LocalOrCookieStorage.getItem(f.getJobArrayName())||[]},f.copyJobArrayToLocal=function(){var a=[],b;for(b=0;b<f.job_array.length;b+=1)a.push(f.job_array[b].serialized());LocalOrCookieStorage.setItem(f.getJobArrayName(),a)},f.removeJob=function(a){var b,c=[];for(b=0;b<f.job_array.length;b+=1)f.job_array[b]!==a&&c.push(f.job_array[b]);f.job_array=c,f.copyJobArrayToLocal()},c.setId=function(a){f.id=a},c.start=function(){var a;f.interval_id===null&&(f.interval_id=setInterval(function(){f.restoreOldJio();for(a=0;a<f.job_array.length;a+=1)c.execute(f.job_array[a])},f.interval))},c.stop=function(){f.interval_id!==null&&(clearInterval(f.interval_id),f.interval_id=null,f.job_array.length===0&&LocalOrCookieStorage.deleteItem(f.getJobArrayName()))},f.restoreOldJio=function(){var a,b;f.lastrestore=f.lastrestore||0;if(f.lastrestore>Date.now()-2e3)return;b=LocalOrCookieStorage.getItem("jio/id_array")||[];for(a=0;a<b.length;a+=1)f.restoreOldJioId(b[a]);f.lastrestore=Date.now()},f.restoreOldJioId=function(a){var b;b=LocalOrCookieStorage.getItem("jio/id/"+a)||0,(new Date(b)).getTime()<Date.now()-1e4&&(f.restoreOldJobFromJioId(a),f.removeOldJioId(a),f.removeJobArrayFromJioId(a))},f.restoreOldJobFromJioId=function(a){var d,e;e=LocalOrCookieStorage.getItem("jio/job_array/"+a)||[];for(d=0;d<e.length;d+=1){var f=j(e[d].command,b);f.canBeRestored()&&c.addJob(v({storage:y.storage(e[d].storage,b),command:f},b))}},f.removeOldJioId=function(a){var b,c,d=[];c=LocalOrCookieStorage.getItem("jio/id_array")||[];for(b=0;b<c.length;b+=1)c[b]!==a&&d.push(c[b]);LocalOrCookieStorage.setItem("jio/id_array",d),LocalOrCookieStorage.deleteItem("jio/id/"+a)},f.removeJobArrayFromJioId=function(a){LocalOrCookieStorage.deleteItem("jio/job_array/"+a)},c.execute=function(a){try{a.execute()}catch(b){switch(b.name){case"jobNotReadyException":break;case"tooMuchTriesJobException":break;default:throw b}}f.copyJobArrayToLocal()},c.jobIdExists=function(a){var b;for(b=0;b<f.job_array.length;b+=1)if(f.job_array[b].getId()===a)return!0;return!1},c.terminateJob=function(a){f.removeJob(a)},c.addJob=function(a){var b=c.validateJobAccordingToJobList(f.job_array,a);f.appendJob(a,b)},c.validateJobAccordingToJobList=function(a,b){var c,d=[];for(c=0;c<a.length;c+=1)d.push(g.validateJobAccordingToJob(a[c],b));return d},f.appendJob=function(a,b){var c;if(f.job_array.length!==b.length)throw new RangeError("Array out of bound");for(c=0;c<b.length;c+=1)if(b[c].action==="dont accept")return a.notAccepted();for(c=0;c<b.length;c+=1)switch(b[c].action){case"eliminate":b[c].job.eliminated(),f.removeJob(b[c].job);break;case"update":b[c].job.update(a),f.copyJobArrayToLocal();return;case"wait":a.waitForJob(b[c].job);break;default:}f.job_array.push(a),f.copyJobArrayToLocal()},c.serialized=function(){var a=[],b,c=f.job_array||[];for(b=0;b<c.length;b+=1)a.push(c[b].serialized());return a},c}(),g=function(a,b){var c={},d={};return d.compare={},d.action={},c.eliminate=function(){return"eliminate"},c.update=function(){return"update"},c.dontAccept=function(){return"dont accept"},c.wait=function(){return"wait"},c.none=function(){return"none"},c.default_action=c.none,c.default_compare=function(a,b){return a.getCommand().getDocId()===b.getCommand().getDocId()&&a.getCommand().getDocInfo("_rev")===b.getCommand().getDocInfo("_rev")&&a.getCommand().getOption("rev")===b.getCommand().getOption("rev")&&JSON.stringify(a.getStorage().serialized())===JSON.stringify(b.getStorage().serialized())},d.getAction=function(a,b){var e,f,g;return e=a.getCommand().getLabel(),f=b.getCommand().getLabel(),g=a.getStatus().getLabel()==="on going"?"on going":"not on going",d.action[e]&&d.action[e][g]&&d.action[e][g][f]?d.action[e][g][f](a,b):c.default_action(a,b)},d.canCompare=function(a,b){var e=a.getCommand().getLabel(),f=b.getCommand().getLabel();return d.compare[e]&&d.compare[f]?d.compare[e][f](a,b):c.default_compare(a,b)},c.validateJobAccordingToJob=function(a,b){return d.canCompare(a,b)?{action:d.getAction(a,b),job:a}:{action:c.default_action(a,b),job:a}},c.addActionRule=function(a,b,c,e){var f=b?"on going":"not on going";d.action[a]=d.action[a]||{},d.action[a][f]=d.action[a][f]||{},d.action[a][f][c]=e},c.addCompareRule=function(a,b,c){d.compare[a]=d.compare[a]||{},d.compare[a][b]=c},c.addActionRule("put",!0,"put",function(a,b){return a.getCommand().getDocInfo("content")===b.getCommand().getDocInfo("content")?c.dontAccept():c.wait()}),c.addActionRule("put",!0,"get",c.wait),c.addActionRule("put",!0,"remove",c.wait),c.addActionRule("put",!1,"put",c.update),c.addActionRule("put",!1,"get",c.wait),c.addActionRule("put",!1,"remove",c.eliminate),c.addActionRule("get",!0,"put",c.wait),c.addActionRule("get",!0,"get",c.dontAccept),c.addActionRule("get",!0,"remove",c.wait),c.addActionRule("get",!1,"put",c.wait),c.addActionRule("get",!1,"get",c.update),c.addActionRule("get",!1,"remove",c.wait),c.addActionRule("remove",!0,"get",c.dontAccept),c.addActionRule("remove",!0,"remove",c.dontAccept),c.addActionRule("remove",!1,"put",c.eliminate),c.addActionRule("remove",!1,"get",c.dontAccept),c.addActionRule("remove",!1,"remove",c.update),c.addActionRule("allDocs",!0,"allDocs",c.dontAccept),c.addActionRule("allDocs",!1,"allDocs",c.update),c}(),h={};a=a||{},b=b||{};var i={},o="jio/id_array";return i.id=null,b.jobManager=f,b.jobIdHandler=e,i.storage_spec=a,i.init=function(){if(i.id===null){var a,b=LocalOrCookieStorage.getItem(o)||[];i.id=1;for(a=0;a<b.length;a+=1)b[a]>=i.id&&(i.id=b[a]+1);b.push(i.id),LocalOrCookieStorage.setItem(o,b),c.setId(i.id),f.setId(i.id)}},h.start=function(){i.init(),c.start(),f.start()},h.stop=function(){f.stop()},h.close=function(){c.stop(),f.stop(),i.id=null},h.start(),h.getId=function(){return i.id},h.getJobRules=function(){return g},h.validateStorageDescription=function(a){return y.storage(a,b).isValid()},h.getJobArray=function(){return f.serialized()},i.getParam=function(a,b){var c={},d=0;return b||(c.doc=a[d],d++),typeof a[d]=="object"?(c.options=a[d],d++):c.options={},c.callback=function(a,b){},c.success=function(a){c.callback(undefined,a)},c.error=function(a){c.callback(a,undefined)},typeof a[d]=="function"&&(typeof a[d+1]=="function"?(c.success=a[d],c.error=a[d+1]):c.callback=a[d]),c},i.addJob=function(a,c){f.addJob(v({storage:y.storage(i.storage_spec,b),command:a(c,b)},b))},h.put=function(){var a=i.getParam(arguments);a.options.max_retry=a.options.max_retry||0,i.addJob(n,{doc:a.doc,options:a.options,callbacks:{success:a.success,error:a.error}})},h.get=function(){var a=i.getParam(arguments);a.options.max_retry=a.options.max_retry||3,a.options.metadata_only=a.options.metadata_only!==undefined?a.options.metadata_only:!1,i.addJob(l,{docid:a.doc,options:a.options,callbacks:{success:a.success,error:a.error}})},h.remove=function(){var a=i.getParam(arguments);a.options.max_retry=a.options.max_retry||0,i.addJob(m,{doc:a.doc,options:a.options,callbacks:{success:a.success,error:a.error}})},h.allDocs=function(){var a=i.getParam(arguments,"no doc");a.options.max_retry=a.options.max_retry||3,a.options.metadata_only=a.options.metadata_only!==undefined?a.options.metadata_only:!0,i.addJob(k,{options:a.options,callbacks:{success:a.success,error:a.error}})},h},y=function(a,b){var c={};a=a||{},b=b||{};var e={base:h,handler:i};return c.storage=function(a,b,c){a=a||{},b=b||{};var f=c||a.type||"base";if(!e[f])throw d({type:f,message:"Storage does not exists."});return e[f](a,b)},c.newJio=function(a){var b=a;return typeof b=="string"&&(b=JSON.parse(b)),b=b||{type:"base"},x(a)},c.addStorageType=function(a,b){b=b||function(){return null};if(e[a])throw d({type:a,message:"Already known."});e[a]=b},c}();return y}(); var jio=function(){"use strict";var a=function(a,b){var c={};return a=a||{},b=b||{},c.name="jioException",c.message=a.message||"Unknown Reason.",c.toString=function(){return c.name+": "+c.message},c},b=function(b,c){var d=a(b,c);b=b||{};var e=b.command;return d.name="invalidCommandState",d.toString=function(){return d.name+": "+e.getLabel()+", "+d.message},d},c=function(b,c){var d=a(b,c);b=b||{};var e=b.storage.getType();return d.name="invalidStorage",d.toString=function(){return d.name+": "+'Type "'+e+'", '+d.message},d},d=function(b,c){var d=a(b,c),e=b.type;return d.name="invalidStorageType",d.toString=function(){return d.name+": "+e+", "+d.message},d},e=function(b,c){var d=a(b,c);return d.name="jobNotReadyException",d},f=function(b,c){var d=a(b,c);return d.name="tooMuchTriesJobException",d},g=function(b,c){var d=a(b,c);return d.name="invalidJobException",d},h=function(a){var b=function(a,b){var d={};a=a||{},b=b||{};var e={};return e.type=a.type||"",Object.defineProperty(d,"getType",{configurable:!1,enumerable:!1,writable:!1,value:function(){return e.type}}),d.execute=function(a){d.success=a.success,d.error=a.error,d.retry=a.retry,d.end=a.end,d.validate(a)&&a.executeOn(d)},d.isValid=function(){return!0},d.validate=function(){var a=d.validateState();return a?(d.error({status:0,statusText:"Invalid Storage",error:"invalid_storage",message:a,reason:a}),!1):!0},d.serialized=function(){return{type:d.getType()}},d.saveDocument=function(a){d.error({status:0,statusText:"Unknown storage",error:"unknown_storage",message:"Unknown Storage"})},d.loadDocument=function(a){d.saveDocument()},d.removeDocument=function(a){d.saveDocument()},d.getDocumentList=function(a){d.saveDocument()},d.validateState=function(){return""},d.success=function(){},d.retry=function(){},d.error=function(){},d.end=function(){},e.newCommand=function(a,d){var e=d||{};return e.label=a,c(e,b)},d.addJob=function(a,c,d,f,g,h){var i={options:f,callbacks:{success:g,error:h}};d&&(a==="get"?i.docid=d:i.doc=d),y.addJob(t({storage:b.storage(c||{}),command:e.newCommand(a,i)},b))},d},c=function(a,b){var d={};a=a||{},b=b||{};var e={};return e.commandlist={post:m,put:l,get:j,remove:k,allDocs:h},a.label&&e.commandlist[a.label]?(e.label=a.label,delete a.label,e.commandlist[e.label](a,b)):(e.tried=0,e.doc=a.doc||{},e.docid=a.docid||"",e.option=a.options||{},e.callbacks=a.callbacks||{},e.success=e.callbacks.success||function(){},e.error=e.callbacks.error||function(){},e.retry=function(){d.error({status:13,statusText:"Fail Retry",error:"fail_retry",message:"Impossible to retry.",reason:"Impossible to retry."})},e.end=function(){},e.on_going=!1,d.serialized=function(){return{label:d.getLabel(),tried:e.tried,doc:d.cloneDoc(),option:d.cloneOption()}},d.getLabel=function(){return"command"},d.getDocId=function(){return e.docid||e.doc._id},d.getDocContent=function(){return e.doc.content},d.getDocInfo=function(a){return e.doc[a]},d.getOption=function(a){return e.option[a]},d.validate=function(a){return d.validateState()?a.validate():!1},d.validateState=function(){return typeof e.doc!="object"?(d.error({status:20,statusText:"Document_Id Required",error:"document_id_required",message:"No document id.",reason:"no document id"}),!1):!0},d.canBeRetried=function(){return typeof e.option.max_retry=="undefined"||e.option.max_retry===0||e.tried<e.option.max_retry},d.getTried=function(){return e.tried},d.execute=function(a){e.on_going||d.validate(a)&&(e.tried++,e.on_going=!0,a.execute(d))},d.executeOn=function(a){},d.success=function(a){e.on_going=!1,e.success(a),e.end(o())},d.retry=function(a){e.on_going=!1,d.canBeRetried()?e.retry():d.error(a)},d.error=function(a){e.on_going=!1,e.error(a),e.end(p())},d.end=function(){e.end(o())},d.onSuccessDo=function(a){if(a)e.success=a;else return e.success},d.onErrorDo=function(a){if(a)e.error=a;else return e.error},d.onEndDo=function(a){e.end=a},d.onRetryDo=function(a){e.retry=a},d.canBeRestored=function(){return!0},d.clone=function(){return c(d.serialized(),b)},d.cloneOption=function(){var a,b={};for(a in e.option)b[a]=e.option[a];return b},d.cloneDoc=function(){if(e.docid)return e.docid;var a,b={};for(a in e.doc)b[a]=e.doc[a];return b},d)},h=function(a,b){var d=c(a,b);return a=a||{},b=b||{},d.getLabel=function(){return"allDocs"},d.executeOn=function(a){a.allDocs(d)},d.canBeRestored=function(){return!1},d},j=function(a,b){var d=c(a,b);return a=a||{},b=b||{},d.getLabel=function(){return"get"},d.validateState=function(){return d.getDocId()?!0:(d.error({status:20,statusText:"Document Id Required",error:"document_id_required",message:"No document id.",reason:"no document id"}),!1)},d.executeOn=function(a){a.get(d)},d.canBeRestored=function(){return!1},d},k=function(a,b){var d=c(a,b);return a=a||{},b=b||{},d.getLabel=function(){return"remove"},d.executeOn=function(a){a.remove(d)},d},l=function(a,b){var d=c(a,b);a=a||{},b=b||{};var e={};d.getLabel=function(){return"put"};var f=d.validateState;return d.validate=function(){return typeof d.getDocInfo("content")!="string"?(d.error({status:21,statusText:"Content Required",error:"content_required",message:"No data to put.",reason:"no data to put"}),!1):f()},d.executeOn=function(a){a.put(d)},d},m=function(a,b){var d=c(a,b);a=a||{},b=b||{};var e={};d.getLabel=function(){return"post"};var f=d.validateState;return d.validate=function(){return typeof d.getDocInfo("content")!="string"?(d.error({status:21,statusText:"Content Required",error:"content_required",message:"No data to put.",reason:"no data to put"}),!1):f()},d.executeOn=function(a){a.put(d)},d},n=function(a,b){var c={};return a=a||{},b=b||{},c.getLabel=function(){return"job status"},c.canStart=function(){},c.canRestart=function(){},c.serialized=function(){return{label:c.getLabel()}},c.isWaitStatus=function(){return!1},c.isDone=function(){return!1},c},o=function(a,b){var c=n(a,b);return a=a||{},b=b||{},c.getLabel=function(){return"done"},c.canStart=function(){return!1},c.canRestart=function(){return!1},c.isDone=function(){return!0},c},p=function(a,b){var c=n(a,b);return a=a||{},b=b||{},c.getLabel=function(){return"fail"},c.canStart=function(){return!1},c.canRestart=function(){return!0},c},q=function(a,b){var c=n(a,b);return a=a||{},b=b||{},c.getLabel=function(){return"initial"},c.canStart=function(){return!0},c.canRestart=function(){return!0},c},r=function(a,b){var c=n(a,b);return a=a||{},b=b||{},c.getLabel=function(){return"on going"},c.canStart=function(){return!1},c.canRestart=function(){return!1},c},s=function(a,b){var c=n(a,b);a=a||{},b=b||{};var d={};return d.job_id_array=a.job_id_array||[],d.threshold=0,c.getLabel=function(){return"wait"},d.refreshJobIdArray=function(){var a=[],c;for(c=0;c<d.job_id_array.length;c+=1)b.jobManager.jobIdExists(d.job_id_array[c])&&a.push(d.job_id_array[c]);d.job_id_array=a},c.waitForJob=function(a){var b;for(b=0;b<d.job_id_array.length;b+=1)if(d.job_id_array[b]===a.getId())return;d.job_id_array.push(a.getId())},c.dontWaitForJob=function(a){var b,c=[];for(b=0;b<d.job_id_array.length;b+=1)d.job_id_array[b]!==a.getId()&&c.push(d.job_id_array[b]);d.job_id_array=c},c.waitForTime=function(a){d.threshold=Date.now()+a},c.stopWaitForTime=function(){d.threshold=0},c.canStart=function(){return d.refreshJobIdArray(),d.job_id_array.length===0&&Date.now()>=d.threshold},c.canRestart=function(){return c.canStart()},c.serialized=function(){return{label:c.getLabel(),waitfortime:d.threshold,waitforjob:d.job_id_array}},c.isWaitStatus=function(){return!0},c},t=function(a){var b={};a=a||{};var c={};c.id=x.nextId(),c.command=a.command,c.storage=a.storage,c.status=q(),c.date=new Date;if(!c.storage)throw g({job:b,message:"No storage set"});if(!c.command)throw g({job:b,message:"No command set"});return b.getCommand=function(){return c.command},b.getStatus=function(){return c.status},b.getId=function(){return c.id},b.getStorage=function(){return c.storage},b.getDate=function(){return c.date},b.isReady=function(){return c.command.getTried()===0?c.status.canStart():c.status.canRestart()},b.serialized=function(){return{id:c.id,date:c.date.getTime(),status:c.status.serialized(),command:c.command.serialized(),storage:c.storage.serialized()}},b.waitForJob=function(a){c.status.getLabel()!=="wait"&&(c.status=s({})),c.status.waitForJob(a)},b.dontWaitFor=function(a){c.status.getLabel()==="wait"&&c.status.dontWaitForJob(a)},b.waitForTime=function(a){c.status.getLabel()!=="wait"&&(c.status=s({})),c.status.waitForTime(a)},b.stopWaitForTime=function(){c.status.getLabel()==="wait"&&c.status.stopWaitForTime()},b.eliminated=function(){c.command.error({status:10,statusText:"Stopped",error:"stopped",message:"This job has been stopped by another one.",reason:"this job has been stopped by another one"})},b.notAccepted=function(){c.command.onEndDo(function(){c.status=p(),y.terminateJob(b)}),c.command.error({status:11,statusText:"Not Accepted",error:"not_accepted",message:"This job is already running.",reason:"this job is already running"})},b.update=function(a){c.command.error({status:12,statusText:"Replaced",error:"replaced",message:"Job has been replaced by another one.",reason:"job has been replaced by another one"}),c.date=new Date(a.getDate().getTime()),c.command=a.getCommand(),c.status=a.getStatus()},b.execute=function(){if(!b.getCommand().canBeRetried())throw f({job:b,message:"The job was invoked too much time."});if(!b.isReady())throw e({job:b,message:"Can not execute this job."});c.status=r(),c.command.onRetryDo(function(){var a=c.command.getTried();a=a*a*200,a>1e4&&(a=1e4),b.waitForTime(a)}),c.command.onEndDo(function(a){c.status=a,y.terminateJob(b)}),c.command.execute(c.storage)},b},u=function(a,b){var c={};a=a||{},b=b||{};var d=[],e=a.name||"",f=a.announcer||{};return c.add=function(a){d.push(a)},c.remove=function(a){var b,c=[];for(b=0;b<d.length;b+=1)d[b]!==a&&c.push(d[b]);d=c},c.register=function(){f.register(c)},c.unregister=function(){f.unregister(c)},c.trigger=function(a){var b;for(b=0;b<d.length;b++)d[b].apply(null,a)},c},v=function(a,b){var c={};a=a||{},b=b||{};var d={};return d.id=a.id||0,d.interval=400,d.interval_id=null,d.touch=function(){LocalOrCookieStorage.setItem("jio/id/"+d.id,Date.now())},c.setId=function(a){d.id=a},c.setIntervalDelay=function(a){d.interval=a},c.getIntervalDelay=function(){return d.interval},c.start=function(){d.interval_id||(d.touch(),d.interval_id=setInterval(function(){d.touch()},d.interval))},c.stop=function(){d.interval_id!==null&&(clearInterval(d.interval_id),d.interval_id=null)},c}(),w=function(a,b){var c={};a=a||{},b=b||{};var d={};return c.register=function(a){d[a]||(d[a]=u())},c.unregister=function(a){d[a]&&delete d[a]},c.at=function(a){return d[a]},c.on=function(a,b){c.register(a),c.at(a).add(b)},c.trigger=function(a,b){c.at(a).trigger(b)},c}(),x=function(a){var b={};a=a||{};var c=0;return b.nextId=function(){return c=c+1,c},b}(),y=function(a){var b={};a=a||{};var d="jio/job_array",e={};return e.id=a.id,e.interval_id=null,e.interval=200,e.job_array=[],e.getJobArrayName=function(){return d+"/"+e.id},e.getJobArray=function(){return LocalOrCookieStorage.getItem(e.getJobArrayName())||[]},e.copyJobArrayToLocal=function(){var a=[],b;for(b=0;b<e.job_array.length;b+=1)a.push(e.job_array[b].serialized());LocalOrCookieStorage.setItem(e.getJobArrayName(),a)},e.removeJob=function(a){var b,c=[];for(b=0;b<e.job_array.length;b+=1)e.job_array[b]!==a&&c.push(e.job_array[b]);e.job_array=c,e.copyJobArrayToLocal()},b.setId=function(a){e.id=a},b.start=function(){var a;e.interval_id===null&&(e.interval_id=setInterval(function(){e.restoreOldJio();for(a=0;a<e.job_array.length;a+=1)b.execute(e.job_array[a])},e.interval))},b.stop=function(){e.interval_id!==null&&(clearInterval(e.interval_id),e.interval_id=null,e.job_array.length===0&&LocalOrCookieStorage.deleteItem(e.getJobArrayName()))},e.restoreOldJio=function(){var a,b;e.lastrestore=e.lastrestore||0;if(e.lastrestore>Date.now()-2e3)return;b=LocalOrCookieStorage.getItem("jio/id_array")||[];for(a=0;a<b.length;a+=1)e.restoreOldJioId(b[a]);e.lastrestore=Date.now()},e.restoreOldJioId=function(a){var b;b=LocalOrCookieStorage.getItem("jio/id/"+a)||0,(new Date(b)).getTime()<Date.now()-1e4&&(e.restoreOldJobFromJioId(a),e.removeOldJioId(a),e.removeJobArrayFromJioId(a))},e.restoreOldJobFromJioId=function(a){var d,e;e=LocalOrCookieStorage.getItem("jio/job_array/"+a)||[];for(d=0;d<e.length;d+=1){var f=c(e[d].command);f.canBeRestored()&&b.addJob(t({storage:b.storage(e[d].storage),command:f}))}},e.removeOldJioId=function(a){var b,c,d=[];c=LocalOrCookieStorage.getItem("jio/id_array")||[];for(b=0;b<c.length;b+=1)c[b]!==a&&d.push(c[b]);LocalOrCookieStorage.setItem("jio/id_array",d),LocalOrCookieStorage.deleteItem("jio/id/"+a)},e.removeJobArrayFromJioId=function(a){LocalOrCookieStorage.deleteItem("jio/job_array/"+a)},b.execute=function(a){try{a.execute()}catch(b){switch(b.name){case"jobNotReadyException":break;case"tooMuchTriesJobException":break;default:throw b}}e.copyJobArrayToLocal()},b.jobIdExists=function(a){var b;for(b=0;b<e.job_array.length;b+=1)if(e.job_array[b].getId()===a)return!0;return!1},b.terminateJob=function(a){e.removeJob(a)},b.addJob=function(a){var c=b.validateJobAccordingToJobList(e.job_array,a);e.appendJob(a,c)},b.validateJobAccordingToJobList=function(a,b){var c,d=[];for(c=0;c<a.length;c+=1)d.push(z.validateJobAccordingToJob(a[c],b));return d},e.appendJob=function(a,b){var c;if(e.job_array.length!==b.length)throw new RangeError("Array out of bound");for(c=0;c<b.length;c+=1)if(b[c].action==="dont accept")return a.notAccepted();for(c=0;c<b.length;c+=1)switch(b[c].action){case"eliminate":b[c].job.eliminated(),e.removeJob(b[c].job);break;case"update":b[c].job.update(a),e.copyJobArrayToLocal();return;case"wait":a.waitForJob(b[c].job);break;default:}e.job_array.push(a),e.copyJobArrayToLocal()},b.serialized=function(){var a=[],b,c=e.job_array||[];for(b=0;b<c.length;b+=1)a.push(c[b].serialized());return a},b}(),z=function(a){var b={},c={};return c.compare={},c.action={},Object.defineProperty(b,"eliminate",{configurable:!1,enumerable:!1,writable:!1,value:function(){return"eliminate"}}),Object.defineProperty(b,"update",{configurable:!1,enumerable:!1,writable:!1,value:function(){return"update"}}),Object.defineProperty(b,"dontAccept",{configurable:!1,enumerable:!1,writable:!1,value:function(){return"dont accept"}}),Object.defineProperty(b,"wait",{configurable:!1,enumerable:!1,writable:!1,value:function(){return"wait"}}),Object.defineProperty(b,"none",{configurable:!1,enumerable:!1,writable:!1,value:function(){return"none"}}),b.default_action=b.none,b.default_compare=function(a,b){return a.getCommand().getDocId()===b.getCommand().getDocId()&&a.getCommand().getDocInfo("_rev")===b.getCommand().getDocInfo("_rev")&&a.getCommand().getOption("rev")===b.getCommand().getOption("rev")&&JSON.stringify(a.getStorage().serialized())===JSON.stringify(b.getStorage().serialized())},c.getAction=function(a,d){var e,f,g;return e=a.getCommand().getLabel(),f=d.getCommand().getLabel(),g=a.getStatus().getLabel()==="on going"?"on going":"not on going",c.action[e]&&c.action[e][g]&&c.action[e][g][f]?c.action[e][g][f](a,d):b.default_action(a,d)},c.canCompare=function(a,d){var e=a.getCommand().getLabel(),f=d.getCommand().getLabel();return c.compare[e]&&c.compare[f]?c.compare[e][f](a,d):b.default_compare(a,d)},Object.defineProperty(b,"validateJobAccordingToJob",{configurable:!1,enumerable:!1,writable:!1,value:function(a,d){return c.canCompare(a,d)?{action:c.getAction(a,d),job:a}:{action:b.default_action(a,d),job:a}}}),Object.defineProperty(b,"addActionRule",{configurable:!1,enumerable:!1,writable:!1,value:function(a,b,d,e){var f=b?"on going":"not on going";c.action[a]=c.action[a]||{},c.action[a][f]=c.action[a][f]||{},c.action[a][f][d]=e}}),Object.defineProperty(b,"addCompareRule",{configurable:!1,enumerable:!1,writable:!1,value:function(a,b,d){c.compare[a]=c.compare[a]||{},c.compare[a][b]=d}}),b.addActionRule("put",!0,"put",function(a,c){return a.getCommand().getDocInfo("content")===c.getCommand().getDocInfo("content")?b.dontAccept():b.wait()}),b.addActionRule("put",!0,"get",b.wait),b.addActionRule("put",!0,"remove",b.wait),b.addActionRule("put",!1,"put",b.update),b.addActionRule("put",!1,"get",b.wait),b.addActionRule("put",!1,"remove",b.eliminate),b.addActionRule("get",!0,"put",b.wait),b.addActionRule("get",!0,"get",b.dontAccept),b.addActionRule("get",!0,"remove",b.wait),b.addActionRule("get",!1,"put",b.wait),b.addActionRule("get",!1,"get",b.update),b.addActionRule("get",!1,"remove",b.wait),b.addActionRule("remove",!0,"get",b.dontAccept),b.addActionRule("remove",!0,"remove",b.dontAccept),b.addActionRule("remove",!1,"put",b.eliminate),b.addActionRule("remove",!1,"get",b.dontAccept),b.addActionRule("remove",!1,"remove",b.update),b.addActionRule("allDocs",!0,"allDocs",b.dontAccept),b.addActionRule("allDocs",!1,"allDocs",b.update),b}(),A={},B={};a=a||{};var C="jio/id_array";return B.id=null,B.storage_spec=a,B.init=function(){if(B.id===null){var a,b=LocalOrCookieStorage.getItem(C)||[];B.id=1;for(a=0;a<b.length;a+=1)b[a]>=B.id&&(B.id=b[a]+1);b.push(B.id),LocalOrCookieStorage.setItem(C,b),v.setId(B.id),y.setId(B.id)}},Object.defineProperty(A,"storage",{configurable:!1,enumerable:!1,writable:!1,value:function(a,c,e){a=a||{},c=c||{},c.basicStorage=b,c.storage=A.storage;var f=e||a.type||"base";if(f==="base")return b(a,c);if(!i[f])throw d({type:f,message:"Storage does not exists."});return i[f](a,c)}}),y.storage=A.storage,Object.defineProperty(A,"start",{configurable:!1,enumerable:!1,writable:!1,value:function(){B.init(),v.start(),y.start()}}),Object.defineProperty(A,"stop",{configurable:!1,enumerable:!1,writable:!1,value:function(){y.stop()}}),Object.defineProperty(A,"close",{configurable:!1,enumerable:!1,writable:!1,value:function(){v.stop(),y.stop(),B.id=null}}),Object.defineProperty(A,"getId",{configurable:!1,enumerable:!1,writable:!1,value:function(){return B.id}}),Object.defineProperty(A,"getJobRules",{configurable:!1,enumerable:!1,writable:!1,value:function(){return z}}),Object.defineProperty(A,"validateStorageDescription",{configurable:!1,enumerable:!1,writable:!1,value:function(a){return A.storage(a).isValid()}}),Object.defineProperty(A,"getJobArray",{configurable:!1,enumerable:!1,writable:!1,value:function(){return y.serialized()}}),B.getParam=function(a,b){var c={},d=0;return b||(c.doc=a[d],d++),typeof a[d]=="object"?(c.options=a[d],d++):c.options={},c.callback=function(a,b){},c.success=function(a){c.callback(undefined,a)},c.error=function(a){c.callback(a,undefined)},typeof a[d]=="function"&&(typeof a[d+1]=="function"?(c.success=a[d],c.error=a[d+1]):c.callback=a[d]),c},B.addJob=function(a,b){y.addJob(t({storage:A.storage(B.storage_spec),command:a(b)}))},Object.defineProperty(A,"post",{configurable:!1,enumerable:!1,writable:!1,value:function(){var a=B.getParam(arguments);a.options.max_retry=a.options.max_retry||0,B.addJob(m,{doc:a.doc,options:a.options,callbacks:{success:a.success,error:a.error}})}}),Object.defineProperty(A,"put",{configurable:!1,enumerable:!1,writable:!1,value:function(){var a=B.getParam(arguments);a.options.max_retry=a.options.max_retry||0,B.addJob(l,{doc:a.doc,options:a.options,callbacks:{success:a.success,error:a.error}})}}),Object.defineProperty(A,"get",{configurable:!1,enumerable:!1,writable:!1,value:function(){var a=B.getParam(arguments);a.options.max_retry=a.options.max_retry||3,a.options.metadata_only=a.options.metadata_only!==undefined?a.options.metadata_only:!1,B.addJob(j,{docid:a.doc,options:a.options,callbacks:{success:a.success,error:a.error}})}}),Object.defineProperty(A,"remove",{configurable:!1,enumerable:!1,writable:!1,value:function(){var a=B.getParam(arguments);a.options.max_retry=a.options.max_retry||0,B.addJob(k,{doc:a.doc,options:a.options,callbacks:{success:a.success,error:a.error}})}}),Object.defineProperty(A,"allDocs",{configurable:!1,enumerable:!1,writable:!1,value:function(){var a=B.getParam(arguments,"no doc");a.options.max_retry=a.options.max_retry||3,a.options.metadata_only=a.options.metadata_only!==undefined?a.options.metadata_only:!0,B.addJob(h,{options:a.options,callbacks:{success:a.success,error:a.error}})}}),A},i={base:function(){}},j=function(a){var b={};return a=a||{},Object.defineProperty(b,"newJio",{configurable:!1,enumerable:!1,writable:!1,value:function(a){var b=a,c=null;return typeof b=="string"&&(b=JSON.parse(b)),b=b||{type:"base"},c=h(a),c.start(),c}}),Object.defineProperty(b,"addStorageType",{configurable:!1,enumerable:!1,writable:!1,value:function(a,b){b=b||function(){return null};if(i[a])throw d({type:a,message:"Already known."});i[a]=b}}),b}();return j}();
\ No newline at end of file \ No newline at end of file
/*! JIO Storage - v0.1.0 - 2012-08-20 /*! JIO Storage - v0.1.0 - 2012-08-21
* Copyright (c) 2012 Nexedi; Licensed */ * Copyright (c) 2012 Nexedi; Licensed */
(function(LocalOrCookieStorage, $, Base64, sjcl, hex_sha256, Jio) { (function(LocalOrCookieStorage, $, Base64, sjcl, hex_sha256, Jio) {
var newLocalStorage = function ( spec, my ) { var newLocalStorage = function ( spec, my ) {
var that = Jio.storage( spec, my, 'base' ), priv = {}; spec = spec || {};
var that = my.basicStorage( spec, my ), priv = {};
priv.secureDocId = function (string) { priv.secureDocId = function (string) {
var split = string.split('/'), i; var split = string.split('/'), i;
...@@ -279,7 +280,8 @@ var newLocalStorage = function ( spec, my ) { ...@@ -279,7 +280,8 @@ var newLocalStorage = function ( spec, my ) {
Jio.addStorageType('local', newLocalStorage); Jio.addStorageType('local', newLocalStorage);
var newDAVStorage = function ( spec, my ) { var newDAVStorage = function ( spec, my ) {
var that = Jio.storage( spec, my, 'base' ), priv = {}; spec = spec || {};
var that = my.basicStorage( spec, my ), priv = {};
priv.secureDocId = function (string) { priv.secureDocId = function (string) {
var split = string.split('/'), i; var split = string.split('/'), i;
...@@ -355,24 +357,16 @@ var newDAVStorage = function ( spec, my ) { ...@@ -355,24 +357,16 @@ var newDAVStorage = function ( spec, my ) {
return async; return async;
}; };
that.post = function (command) { priv.putOrPost = function (command,type) {
that.put(command);
};
/**
* Saves a document in the distant dav storage.
* @method put
*/
that.put = function (command) {
var secured_docid = priv.secureDocId(command.getDocId()); var secured_docid = priv.secureDocId(command.getDocId());
$.ajax ( { $.ajax ( {
url: priv.url + '/' + url: priv.url + '/' +
priv.secured_username + '/' + priv.secured_username + '/' +
priv.secured_applicationname + '/' + priv.secured_applicationname + '/' +
secured_docid, secured_docid + '?_=' + Date.now(), // to make url unique!
type: 'PUT', // and avoid chrome PUT on cache !
type: type,
data: command.getDocContent(), data: command.getDocContent(),
async: true, async: true,
dataType: 'text', // TODO is it necessary ? dataType: 'text', // TODO is it necessary ?
...@@ -390,6 +384,18 @@ var newDAVStorage = function ( spec, my ) { ...@@ -390,6 +384,18 @@ var newDAVStorage = function ( spec, my ) {
that.retry(type); that.retry(type);
} }
} ); } );
};
that.post = function (command) {
priv.putOrPost (command,'POST');
};
/**
* Saves a document in the distant dav storage.
* @method put
*/
that.put = function (command) {
priv.putOrPost (command,'PUT');
}; // end put }; // end put
/** /**
...@@ -403,7 +409,7 @@ var newDAVStorage = function ( spec, my ) { ...@@ -403,7 +409,7 @@ var newDAVStorage = function ( spec, my ) {
url: priv.url + '/' + url: priv.url + '/' +
priv.secured_username + '/' + priv.secured_username + '/' +
priv.secured_applicationname + '/' + priv.secured_applicationname + '/' +
secured_docid, secured_docid + '?_=' + Date.now(),
type: "GET", type: "GET",
async: true, async: true,
dataType: 'text', // TODO is it necessary ? dataType: 'text', // TODO is it necessary ?
...@@ -439,7 +445,7 @@ var newDAVStorage = function ( spec, my ) { ...@@ -439,7 +445,7 @@ var newDAVStorage = function ( spec, my ) {
url: priv.url + '/' + url: priv.url + '/' +
priv.secured_username + '/' + priv.secured_username + '/' +
priv.secured_applicationname + '/' + priv.secured_applicationname + '/' +
secured_docid, secured_docid + '?_=' + Date.now(),
type: "PROPFIND", type: "PROPFIND",
async: true, async: true,
dataType: 'xml', dataType: 'xml',
...@@ -494,7 +500,7 @@ var newDAVStorage = function ( spec, my ) { ...@@ -494,7 +500,7 @@ var newDAVStorage = function ( spec, my ) {
url: priv.url + '/' + url: priv.url + '/' +
priv.secured_username + '/' + priv.secured_username + '/' +
priv.secured_applicationname + '/' + priv.secured_applicationname + '/' +
priv.secureDocId(file.id), priv.secureDocId(file.id) + '?_=' + Date.now(),
type: "GET", type: "GET",
async: true, async: true,
dataType: 'text', // TODO : is it necessary ? dataType: 'text', // TODO : is it necessary ?
...@@ -521,12 +527,13 @@ var newDAVStorage = function ( spec, my ) { ...@@ -521,12 +527,13 @@ var newDAVStorage = function ( spec, my ) {
$.ajax ( { $.ajax ( {
url: priv.url + '/' + url: priv.url + '/' +
priv.secured_username + '/' + priv.secured_username + '/' +
priv.secured_applicationname + '/', priv.secured_applicationname + '/' + '?_=' + Date.now(),
async: true, async: true,
type: 'PROPFIND', type: 'PROPFIND',
dataType: 'xml', dataType: 'xml',
headers: {'Authorization': 'Basic '+Base64.encode( headers: {'Authorization': 'Basic '+Base64.encode(
priv.username + ':' + priv.password ), Depth: '1'}, priv.username + ':' + priv.password ), Depth: '1'},
// xhrFields: {withCredentials: 'true'}, // cross domain
success: function (xmlData) { success: function (xmlData) {
var response = $(xmlData).find( var response = $(xmlData).find(
'D\\:response, response' 'D\\:response, response'
...@@ -613,12 +620,11 @@ var newDAVStorage = function ( spec, my ) { ...@@ -613,12 +620,11 @@ var newDAVStorage = function ( spec, my ) {
that.remove = function (command) { that.remove = function (command) {
var secured_docid = priv.secureDocId(command.getDocId()); var secured_docid = priv.secureDocId(command.getDocId());
$.ajax ( { $.ajax ( {
url: priv.url + '/' + url: priv.url + '/' +
priv.secured_username + '/' + priv.secured_username + '/' +
priv.secured_applicationname + '/' + priv.secured_applicationname + '/' +
secured_docid, secured_docid + '?_=' + Date.now(),
type: "DELETE", type: "DELETE",
async: true, async: true,
headers: {'Authorization':'Basic '+Base64.encode( headers: {'Authorization':'Basic '+Base64.encode(
...@@ -648,7 +654,8 @@ var newDAVStorage = function ( spec, my ) { ...@@ -648,7 +654,8 @@ var newDAVStorage = function ( spec, my ) {
Jio.addStorageType('dav', newDAVStorage); Jio.addStorageType('dav', newDAVStorage);
var newReplicateStorage = function ( spec, my ) { var newReplicateStorage = function ( spec, my ) {
var that = Jio.storage( spec, my, 'handler' ), priv = {}; spec = spec || {};
var that = my.basicStorage( spec, my ), priv = {};
priv.return_value_array = []; priv.return_value_array = [];
priv.storagelist = spec.storagelist || []; priv.storagelist = spec.storagelist || [];
...@@ -753,7 +760,8 @@ var newReplicateStorage = function ( spec, my ) { ...@@ -753,7 +760,8 @@ var newReplicateStorage = function ( spec, my ) {
Jio.addStorageType('replicate', newReplicateStorage); Jio.addStorageType('replicate', newReplicateStorage);
var newIndexStorage = function ( spec, my ) { var newIndexStorage = function ( spec, my ) {
var that = Jio.storage( spec, my, 'handler' ), priv = {}; spec = spec || {};
var that = my.basicStorage( spec, my ), priv = {};
var validatestate_secondstorage = spec.storage || false; var validatestate_secondstorage = spec.storage || false;
priv.secondstorage_spec = spec.storage || {type:'base'}; priv.secondstorage_spec = spec.storage || {type:'base'};
...@@ -961,7 +969,8 @@ var newIndexStorage = function ( spec, my ) { ...@@ -961,7 +969,8 @@ var newIndexStorage = function ( spec, my ) {
Jio.addStorageType ('indexed', newIndexStorage); Jio.addStorageType ('indexed', newIndexStorage);
var newCryptedStorage = function ( spec, my ) { var newCryptedStorage = function ( spec, my ) {
var that = Jio.storage( spec, my, 'handler' ), priv = {}; spec = spec || {};
var that = my.basicStorage( spec, my ), priv = {};
var is_valid_storage = (spec.storage?true:false); var is_valid_storage = (spec.storage?true:false);
...@@ -1223,9 +1232,8 @@ var newCryptedStorage = function ( spec, my ) { ...@@ -1223,9 +1232,8 @@ var newCryptedStorage = function ( spec, my ) {
Jio.addStorageType('crypt', newCryptedStorage); Jio.addStorageType('crypt', newCryptedStorage);
var newConflictManagerStorage = function ( spec, my ) { var newConflictManagerStorage = function ( spec, my ) {
var that = Jio.storage( spec, my, 'handler' ), priv = {};
spec = spec || {}; spec = spec || {};
my = my || {}; var that = my.basicStorage( spec, my ), priv = {};
var storage_exists = (spec.storage?true:false); var storage_exists = (spec.storage?true:false);
priv.secondstorage_spec = spec.storage || {type:'base'}; priv.secondstorage_spec = spec.storage || {type:'base'};
...@@ -1253,20 +1261,18 @@ var newConflictManagerStorage = function ( spec, my ) { ...@@ -1253,20 +1261,18 @@ var newConflictManagerStorage = function ( spec, my ) {
priv.getDistantMetadata = function (command,path,success,error) { priv.getDistantMetadata = function (command,path,success,error) {
var cloned_option = command.cloneOption (); var cloned_option = command.cloneOption ();
cloned_option.metadata_only = false; cloned_option.metadata_only = false;
cloned_option.max_retry = command.getOption('max_retry') || 3;
that.addJob ('get',priv.secondstorage_spec,path,cloned_option, that.addJob ('get',priv.secondstorage_spec,path,cloned_option,
success, error); success, error);
}; };
priv.saveMetadataToDistant = function (command,path,content,success,error) { priv.saveMetadataToDistant = function (command,path,content,success,error) {
// max_retry:0 // inf
that.addJob ('put',priv.secondstorage_spec, that.addJob ('put',priv.secondstorage_spec,
{_id:path,content:JSON.stringify (content)}, {_id:path,content:JSON.stringify (content)},
command.cloneOption(),success,error); command.cloneOption(),success,error);
}; };
priv.saveNewRevision = function (command,path,content,success,error) { priv.saveNewRevision = function (command,path,content,success,error) {
that.addJob ('put',priv.secondstorage_spec,{_id:path,content:content}, that.addJob ('post',priv.secondstorage_spec,{_id:path,content:content},
command.cloneOption(),success,error); command.cloneOption(),success,error);
}; };
...@@ -1277,7 +1283,6 @@ var newConflictManagerStorage = function ( spec, my ) { ...@@ -1277,7 +1283,6 @@ var newConflictManagerStorage = function ( spec, my ) {
priv.deleteAFile = function (command,path,success,error) { priv.deleteAFile = function (command,path,success,error) {
var cloned_option = command.cloneOption(); var cloned_option = command.cloneOption();
cloned_option.max_retry = 0; // inf
that.addJob ('remove',priv.secondstorage_spec,{_id:path}, that.addJob ('remove',priv.secondstorage_spec,{_id:path},
command.cloneOption(), success, error); command.cloneOption(), success, error);
}; };
...@@ -1296,6 +1301,7 @@ var newConflictManagerStorage = function ( spec, my ) { ...@@ -1296,6 +1301,7 @@ var newConflictManagerStorage = function ( spec, my ) {
}; };
priv._revs = function (metadata,revision) { priv._revs = function (metadata,revision) {
if (!(metadata && revision)) { return null; }
if (metadata[revision]) { if (metadata[revision]) {
return {start:metadata[revision]._revisions.length, return {start:metadata[revision]._revisions.length,
ids:metadata[revision]._revisions}; ids:metadata[revision]._revisions};
...@@ -1305,6 +1311,7 @@ var newConflictManagerStorage = function ( spec, my ) { ...@@ -1305,6 +1311,7 @@ var newConflictManagerStorage = function ( spec, my ) {
}; };
priv._revs_info = function (metadata) { priv._revs_info = function (metadata) {
if (!metadata) { return null; }
var k, l = []; var k, l = [];
for (k in metadata) { for (k in metadata) {
l.push({ l.push({
......
/*! JIO Storage - v0.1.0 - 2012-08-20 /*! JIO Storage - v0.1.0 - 2012-08-21
* Copyright (c) 2012 Nexedi; Licensed */ * Copyright (c) 2012 Nexedi; Licensed */
(function(a,b,c,d,e,f){var g=function(b,c){var d=f.storage(b,c,"base"),e={};e.secureDocId=function(a){var b=a.split("/"),c;b[0]===""&&(b=b.slice(1));for(c=0;c<b.length;c+=1)if(b[c]==="")return"";return b.join("%2F")},e.convertSlashes=function(a){return a.split("/").join("%2F")},e.restoreSlashes=function(a){return a.split("%2F").join("/")},e.username=b.username||"",e.secured_username=e.convertSlashes(e.username),e.applicationname=b.applicationname||"untitled",e.secured_applicationname=e.convertSlashes(e.applicationname);var g="jio/local_user_array",h="jio/local_file_name_array/"+e.secured_username+"/"+e.secured_applicationname,i=d.serialized;return d.serialized=function(){var a=i();return a.applicationname=e.applicationname,a.username=e.username,a},d.validateState=function(){return e.secured_username?"":'Need at least one parameter: "username".'},e.getUserArray=function(){return a.getItem(g)||[]},e.addUser=function(b){var c=e.getUserArray();c.push(b),a.setItem(g,c)},e.userExists=function(a){var b=e.getUserArray(),c,d;for(c=0,d=b.length;c<d;c+=1)if(b[c]===a)return!0;return!1},e.getFileNameArray=function(){return a.getItem(h)||[]},e.addFileName=function(b){var c=e.getFileNameArray();c.push(b),a.setItem(h,c)},e.removeFileName=function(b){var c,d,f=e.getFileNameArray(),g=[];for(c=0,d=f.length;c<d;c+=1)f[c]!==b&&g.push(f[c]);a.setItem(h,g)},e.checkSecuredDocId=function(a,b,c){return a?!0:(d.error({status:403,statusText:"Method Not Allowed",error:"method_not_allowed",message:"Cannot "+c+' "'+b+'", file name is incorrect.',reason:"Cannot "+c+' "'+b+'", file name is incorrect'}),!1)},d.post=function(a){d.put(a)},d.put=function(b){setTimeout(function(){var c=e.secureDocId(b.getDocId()),f=null,g="jio/local/"+e.secured_username+"/"+e.secured_applicationname+"/"+c;if(!e.checkSecuredDocId(c,b.getDocId(),"put"))return;f=a.getItem(g),f?(f.content=b.getDocContent(),f._last_modified=Date.now()):(f={_id:b.getDocId(),content:b.getDocContent(),_creation_date:Date.now(),_last_modified:Date.now()},e.userExists(e.secured_username)||e.addUser(e.secured_username),e.addFileName(c)),a.setItem(g,f),d.success({ok:!0,id:b.getDocId()})})},d.get=function(b){setTimeout(function(){var c=e.secureDocId(b.getDocId()),f=null;if(!e.checkSecuredDocId(c,b.getDocId(),"get"))return;f=a.getItem("jio/local/"+e.secured_username+"/"+e.secured_applicationname+"/"+c),f?(b.getOption("metadata_only")&&delete f.content,d.success(f)):d.error({status:404,statusText:"Not Found.",error:"not_found",message:'Document "'+b.getDocId()+'" not found.',reason:"missing"})})},d.allDocs=function(b){setTimeout(function(){var c=[],f=[],g,h,i="key",j="jio/local/"+e.secured_username+"/"+e.secured_applicationname,k={};f=e.getFileNameArray();for(g=0,h=f.length;g<h;g+=1)k=a.getItem(j+"/"+f[g]),k&&(b.getOption("metadata_only")?c.push({id:k._id,key:k._id,value:{_creation_date:k._creation_date,_last_modified:k._last_modified}}):c.push({id:k._id,key:k._id,value:{content:k.content,_creation_date:k._creation_date,_last_modified:k._last_modified}}));d.success({total_rows:c.length,rows:c})})},d.remove=function(b){setTimeout(function(){var c=e.secureDocId(b.getDocId()),f="jio/local/"+e.secured_username+"/"+e.secured_applicationname+"/"+c;if(!e.checkSecuredDocId(c,b.getDocId(),"remove"))return;a.deleteItem(f),e.removeFileName(c),d.success({ok:!0,id:b.getDocId()})})},d};f.addStorageType("local",g);var h=function(a,d){var e=f.storage(a,d,"base"),g={};g.secureDocId=function(a){var b=a.split("/"),c;b[0]===""&&(b=b.slice(1));for(c=0;c<b.length;c+=1)if(b[c]==="")return"";return b.join("%2F")},g.convertSlashes=function(a){return a.split("/").join("%2F")},g.restoreSlashes=function(a){return a.split("%2F").join("/")},g.username=a.username||"",g.secured_username=g.convertSlashes(g.username),g.applicationname=a.applicationname||"untitled",g.secured_applicationname=g.convertSlashes(g.applicationname),g.url=a.url||"",g.password=a.password||"";var h=e.serialized;return e.serialized=function(){var a=h();return a.username=g.username,a.applicationname=g.applicationname,a.url=g.url,a.password=g.password,a},e.validateState=function(){return g.secured_username&&g.url?"":'Need at least 2 parameters: "username" and "url".'},g.newAsyncModule=function(){var a={};return a.call=function(a,b,c){return a._wait=a._wait||{},a._wait[b]?(a._wait[b]--,function(){}):(c=c||[],a[b].apply(a[b],c))},a.neverCall=function(a,b){a._wait=a._wait||{},a._wait[b]=-1},a.wait=function(a,b,c){a._wait=a._wait||{},a._wait[b]=c},a.end=function(){a.call=function(){}},a},e.post=function(a){e.put(a)},e.put=function(a){var d=g.secureDocId(a.getDocId());b.ajax({url:g.url+"/"+g.secured_username+"/"+g.secured_applicationname+"/"+d,type:"PUT",data:a.getDocContent(),async:!0,dataType:"text",headers:{Authorization:"Basic "+c.encode(g.username+":"+g.password)},success:function(){e.success({ok:!0,id:a.getDocId()})},error:function(b){b.error=b.statusText,b.reason='Cannot save "'+a.getDocId()+'"',b.message=b.reason+".",e.retry(b)}})},e.get=function(a){var d=g.secureDocId(a.getDocId()),f={},h=function(){b.ajax({url:g.url+"/"+g.secured_username+"/"+g.secured_applicationname+"/"+d,type:"GET",async:!0,dataType:"text",headers:{Authorization:"Basic "+c.encode(g.username+":"+g.password)},success:function(a){f.content=a,e.success(f)},error:function(b){b.error=b.statusText,b.status===404?(b.message='Document "'+a.getDocId()+'" not found.',b.reason="missing",e.error(b)):(b.reason='An error occured when trying to get "'+a.getDocId()+'"',b.message=b.reason+".",e.retry(b))}})};f._id=a.getDocId(),b.ajax({url:g.url+"/"+g.secured_username+"/"+g.secured_applicationname+"/"+d,type:"PROPFIND",async:!0,dataType:"xml",headers:{Authorization:"Basic "+c.encode(g.username+":"+g.password)},success:function(c){b(c).find("lp1\\:getlastmodified, getlastmodified").each(function(){f._last_modified=(new Date(b(this).text())).getTime()}),b(c).find("lp1\\:creationdate, creationdate").each(function(){f._creation_date=(new Date(b(this).text())).getTime()}),a.getOption("metadata_only")?e.success(f):h()},error:function(b){b.status===404?(b.message='Cannot find "'+a.getDocId()+'" informations.',b.reason="missing",e.error(b)):(b.reason='Cannot get "'+a.getDocId()+'" informations',b.message=b.reason+".",e.retry(b))}})},e.allDocs=function(a){var d=[],f=g.newAsyncModule(),h={};h.getContent=function(a){b.ajax({url:g.url+"/"+g.secured_username+"/"+g.secured_applicationname+"/"+g.secureDocId(a.id),type:"GET",async:!0,dataType:"text",headers:{Authorization:"Basic "+c.encode(g.username+":"+g.password)},success:function(b){a.value.content=b,d.push(a),f.call(h,"success")},error:function(a){a.error=a.statusText,a.reason="Cannot get a document content from DAVStorage",a.message=a.message+".",f.call(h,"error",[a])}})},h.getDocumentList=function(){b.ajax({url:g.url+"/"+g.secured_username+"/"+g.secured_applicationname+"/",async:!0,type:"PROPFIND",dataType:"xml",headers:{Authorization:"Basic "+c.encode(g.username+":"+g.password),Depth:"1"},success:function(c){var e=b(c).find("D\\:response, response"),i=e.length;if(i===1)return f.call(h,"success");f.wait(h,"success",i-2),e.each(function(c,e){if(c>0){var i={value:{}};b(e).find("D\\:href, href").each(function(){var a=b(this).text().split("/");i.id=a[a.length-1],i.id=g.restoreSlashes(i.id),i.key=i.id});if(i.id===".htaccess"||i.id===".htpasswd")return;b(e).find("lp1\\:getlastmodified, getlastmodified").each(function(){i.value._last_modified=(new Date(b(this).text())).getTime()}),b(e).find("lp1\\:creationdate, creationdate").each(function(){i.value._creation_date=(new Date(b(this).text())).getTime()}),a.getOption("metadata_only")?(d.push(i),f.call(h,"success")):f.call(h,"getContent",[i])}})},error:function(a){a.status===404?(a.error="not_found",a.reason="missing",f.call(h,"error",[a])):(a.error=a.statusText,a.reason="Cannot get a document list from DAVStorage",a.message=a.reason+".",f.call(h,"retry",[a]))}})},h.retry=function(a){f.neverCall(h,"retry"),f.neverCall(h,"success"),f.neverCall(h,"error"),e.retry(a)},h.error=function(a){f.neverCall(h,"retry"),f.neverCall(h,"success"),f.neverCall(h,"error"),e.error(a)},h.success=function(){f.neverCall(h,"retry"),f.neverCall(h,"success"),f.neverCall(h,"error"),e.success({total_rows:d.length,rows:d})},f.call(h,"getDocumentList")},e.remove=function(a){var d=g.secureDocId(a.getDocId());b.ajax({url:g.url+"/"+g.secured_username+"/"+g.secured_applicationname+"/"+d,type:"DELETE",async:!0,headers:{Authorization:"Basic "+c.encode(g.username+":"+g.password)},success:function(b,c,d){e.success({ok:!0,id:a.getDocId()})},error:function(a,b,c){a.status===404?(a.error="not_found",a.reason="missing",a.message="Cannot remove missing file.",e.error(a)):(a.reason='Cannot remove "'+e.getDocId()+'"',a.message=a.reason+".",e.retry(a))}})},e};f.addStorageType("dav",h);var i=function(a,b){var c=f.storage(a,b,"handler"),d={};d.return_value_array=[],d.storagelist=a.storagelist||[],d.nb_storage=d.storagelist.length;var e=c.serialized;return c.serialized=function(){var a=e();return a.storagelist=d.storagelist,a},c.validateState=function(){return d.storagelist.length===0?'Need at least one parameter: "storagelist" containing at least one storage.':""},d.isTheLast=function(a){return a.length===d.nb_storage},d.doJob=function(a,b,e){var f=!1,g=[],h,i=function(h){f||(g.push(h),d.isTheLast(g)&&c.error({status:207,statusText:"Multi-Status",error:"multi_status",message:"All "+b+(e?" ":' "'+a.getDocId()+'"')+" requests have failed.",reason:"requests fail",array:g}))},j=function(a){f||(f=!0,c.success(a))};for(h=0;h<d.nb_storage;h+=1){var k=a.cloneOption();c.addJob(a.getLabel(),d.storagelist[h],a.cloneDoc(),k,j,i)}},c.post=function(a){d.doJob(a,"post"),c.end()},c.put=function(a){d.doJob(a,"put"),c.end()},c.get=function(a){d.doJob(a,"get"),c.end()},c.allDocs=function(a){d.doJob(a,"allDocs",!0),c.end()},c.remove=function(a){d.doJob(a,"remove"),c.end()},c};f.addStorageType("replicate",i);var j=function(b,c){var d=f.storage(b,c,"handler"),e={},g=b.storage||!1;e.secondstorage_spec=b.storage||{type:"base"},e.secondstorage_string=JSON.stringify(e.secondstorage_spec);var h="jio/indexed_storage_object",i="jio/indexed_file_object/"+e.secondstorage_string,j=d.serialized;return d.serialized=function(){var a=j();return a.storage=e.secondstorage_spec,a},d.validateState=function(){return g?"":'Need at least one parameter: "storage" containing storage specifications.'},e.secureDocId=function(a){var b=a.split("/"),c;b[0]===""&&(b=b.slice(1));for(c=0;c<b.length;c+=1)if(b[c]==="")return"";return b.join("%2F")},e.indexStorage=function(){var b=a.getItem(h)||{};b[e.secondstorage_spec]=(new Date).getTime(),a.setItem(h,b)},e.formatToFileObject=function(a){var b,c={_id:a.id};for(b in a.value)c[b]=a.value[b];return c},e.allDocs=function(a){var b,c={rows:[]},d=0;for(b in a)c.rows[d]={},c.rows[d].value=a[b],c.rows[d].id=c.rows[d].key=c.rows[d].value._id,delete c.rows[d].value._id,d++;return c.total_rows=c.rows.length,c},e.setFileArray=function(b){var c,d={};for(c=0;c<b.length;c+=1)d[b[c].id]=e.formatToFileObject(b[c]);a.setItem(i,d)},e.getFileObject=function(b){var c=a.getItem(i)||{};return c[b]},e.addFile=function(b){var c=a.getItem(i)||{};c[b._id]=b,a.setItem(i,c)},e.removeFile=function(b){var c=a.getItem(i)||{};delete c[b],a.setItem(i,c)},e.update=function(){var a=function(a){e.setFileArray(a.rows)};d.addJob("allDocs",e.secondstorage_spec,null,{max_retry:3},a,function(){})},d.post=function(a){d.put(a)},d.put=function(a){var b=a.cloneDoc(),c=a.cloneOption(),f=function(a){e.update(),d.success(a)},g=function(a){d.error(a)};e.indexStorage(),d.addJob("put",e.secondstorage_spec,b,c,f,g)},d.get=function(a){var b,c=function(a){d.success(a)},f=function(a){d.error(a)},g=function(){var b=a.cloneOption();d.addJob("get",e.secondstorage_spec,a.cloneDoc(),b,c,f),d.end()};e.indexStorage(),e.update(),a.getOption("metadata_only")?setTimeout(function(){var b=e.getFileObject(a.getDocId());b&&(b._last_modified||b._creation_date)?d.success(b):g()}):g()},d.allDocs=function(b){var c=a.getItem(i);if(c)e.update(),setTimeout(function(){d.success(e.allDocs(c))});else{var f=function(a){e.setFileArray(a.rows),d.success(a)},g=function(a){d.error(a)};d.addJob("allDocs",e.secondstorage_spec,null,b.cloneOption(),f,g)}},d.remove=function(a){var b=function(b){e.removeFile(a.getDocId()),e.update(),d.success(b)},c=function(a){d.error(a)};d.addJob("remove",e.secondstorage_spec,a.cloneDoc(),a.cloneOption(),b,c)},d};f.addStorageType("indexed",j);var k=function(a,c){var e=f.storage(a,c,"handler"),g={},h=a.storage?!0:!1;g.username=a.username||"",g.password=a.password||"",g.secondstorage_spec=a.storage||{type:"base"},g.secondstorage_string=JSON.stringify(g.secondstorage_string);var i=e.serialized;return e.serialized=function(){var a=i();return a.username=g.username,a.password=g.password,a.storage=g.secondstorage_string,a},e.validateState=function(){return g.username&&h?"":'Need at least two parameters: "username" and "storage".'},g.encrypt_param_object={iv:"kaprWwY/Ucr7pumXoTHbpA",v:1,iter:1e3,ks:256,ts:128,mode:"ccm",adata:"",cipher:"aes",salt:"K4bmZG9d704"},g.decrypt_param_object={iv:"kaprWwY/Ucr7pumXoTHbpA",ks:256,ts:128,salt:"K4bmZG9d704"},g.encrypt=function(a,b){var c=d.encrypt(g.username+":"+g.password,a,g.encrypt_param_object);b(JSON.parse(c).ct)},g.decrypt=function(a,c){var e,f=b.extend(!0,{},g.decrypt_param_object);f.ct=a||"",f=JSON.stringify(f);try{e=d.decrypt(g.username+":"+g.password,f)}catch(h){c({status:403,statusText:"Forbidden",error:"forbidden",message:"Unable to decrypt.",reason:"unable to decrypt"});return}c(undefined,e)},g.newAsyncModule=function(){var a={};return a.call=function(a,b,c){a._wait=a._wait||{};if(a._wait[b])return a._wait[b]--,function(){};c=c||[],setTimeout(function(){a[b].apply(a[b],c)})},a.neverCall=function(a,b){a._wait=a._wait||{},a._wait[b]=-1},a.wait=function(a,b,c){a._wait=a._wait||{},a._wait[b]=c},a.end=function(){a.call=function(){}},a},e.post=function(a){e.put(a)},e.put=function(a){var b,c,d=g.newAsyncModule(),f={};f.encryptFilePath=function(){g.encrypt(a.getDocId(),function(a){b=a,d.call(f,"save")})},f.encryptFileContent=function(){g.encrypt(a.getDocContent(),function(a){c=a,d.call(f,"save")})},f.save=function(){var d=function(b){b.id=a.getDocId(),e.success(b)},f=function(a){e.error(a)},h=a.cloneDoc();h._id=b,h.content=c,e.addJob("put",g.secondstorage_spec,h,a.cloneOption(),d,f)},d.wait(f,"save",1),d.call(f,"encryptFilePath"),d.call(f,"encryptFileContent")},e.get=function(a){var b,c,d=g.newAsyncModule(),f={};f.encryptFilePath=function(){g.encrypt(a.getDocId(),function(a){b=a,d.call(f,"get")})},f.get=function(){e.addJob("get",g.secondstorage_spec,b,a.cloneOption(),f.success,f.error)},f.success=function(b){b._id=a.getDocId(),a.getOption("metadata_only")?e.success(b):g.decrypt(b.content,function(a,c){a?e.error(a):(b.content=c,e.success(b))})},f.error=function(a){e.error(a)},d.call(f,"encryptFilePath")},e.allDocs=function(a){var b=[],c=g.newAsyncModule(),d={};d.allDocs=function(){e.addJob("allDocs",g.secondstorage_spec,null,a.cloneOption(),d.onSuccess,d.error)},d.onSuccess=function(e){if(e.total_rows===0)return c.call(d,"success");b=e.rows;var f,h=function(e){g.decrypt(b[e].id,function(a,f){a?c.call(d,"error",[a]):(b[e].id=f,b[e].key=f,c.call(d,"success"))}),a.getOption("metadata_only")||g.decrypt(b[e].value.content,function(a,f){a?c.call(d,"error",[a]):(b[e].value.content=f,c.call(d,"success"))})};a.getOption("metadata_only")?c.wait(d,"success",e.total_rows*1-1):c.wait(d,"success",e.total_rows*2-1);for(f=0;f<b.length;f+=1)h(f)},d.error=function(a){c.end(),e.error(a)},d.success=function(){c.end(),e.success({total_rows:b.length,rows:b})},c.call(d,"allDocs")},e.remove=function(a){var b,c={};c.encryptDocId=function(){g.encrypt(a.getDocId(),function(a){b=a,c.removeDocument()})},c.removeDocument=function(){var d=a.cloneDoc();d._id=b,e.addJob("remove",g.secondstorage_spec,d,a.cloneOption(),c.success,e.error)},c.success=function(b){b.id=a.getDocId(),e.success(b)},c.encryptDocId()},e};f.addStorageType("crypt",k);var l=function(a,b){var c=f.storage(a,b,"handler"),d={};a=a||{},b=b||{};var g=a.storage?!0:!1;d.secondstorage_spec=a.storage||{type:"base"},d.secondstorage_string=JSON.stringify(d.secondstorage_spec);var h="jio/conflictmanager/"+d.secondstorage_string+"/",i=function(){},j=c.serialized;return c.serialized=function(){var a=j();return a.storage=d.secondstorage_spec,a},c.validateState=function(){return g?"":'Need at least one parameter: "storage".'},d.getDistantMetadata=function(a,b,e,f){var g=a.cloneOption();g.metadata_only=!1,g.max_retry=a.getOption("max_retry")||3,c.addJob("get",d.secondstorage_spec,b,g,e,f)},d.saveMetadataToDistant=function(a,b,e,f,g){c.addJob("put",d.secondstorage_spec,{_id:b,content:JSON.stringify(e)},a.cloneOption(),f,g)},d.saveNewRevision=function(a,b,e,f,g){c.addJob("put",d.secondstorage_spec,{_id:b,content:e},a.cloneOption(),f,g)},d.loadRevision=function(a,b,e,f){c.addJob("get",d.secondstorage_spec,b,a.cloneOption(),e,f)},d.deleteAFile=function(a,b,e,f){var g=a.cloneOption();g.max_retry=0,c.addJob("remove",d.secondstorage_spec,{_id:b},a.cloneOption(),e,f)},d.chooseARevision=function(a){var b=0,c="",d;for(d in a)b<a[d]._last_modified&&(b=a[d]._last_modified,c=d);return c},d._revs=function(a,b){return a[b]?{start:a[b]._revisions.length,ids:a[b]._revisions}:null},d._revs_info=function(a){var b,c=[];for(b in a)c.push({rev:b,status:a[b]?a[b]._deleted?"deleted":"available":"missing"});return c},d.solveConflict=function(a,b,c){var f={},g=d.newAsyncModule(),h=c.command,j=c.docid+".metadata",k="",l="",m=null,n=!1,o={total_rows:0,rows:[]},p=c._deleted,q=c.previous_revision,r=null,s=new Date,t;f.getDistantMetadata=function(){d.getDistantMetadata(h,j,function(b){var d=parseInt(q.split("-")[0],10);m=JSON.parse(b.content),k=d+1+"-"+e(""+a.content+q+JSON.stringify(m)),l=c.docid+"."+k,r=m[q]||{},p||(g.wait(f,"saveMetadataOnDistant",1),g.call(f,"saveNewRevision")),g.call(f,"previousUpdateMetadata")},function(a){g.call(f,"error",[a])})},f.saveNewRevision=function(){d.saveNewRevision(h,l,a.content,function(a){g.call(f,"saveMetadataOnDistant")},function(a){g.call(f,"error",[a])})},f.previousUpdateMetadata=function(){var a;for(a=0;a<c.key.length;a+=1)delete m[c.key[a]];g.call(f,"checkForConflicts")},f.checkForConflicts=function(){var a;for(a in m){var b;n=!0,t={status:409,error:"conflict",statusText:"Conflict",reason:"document update conflict",message:"There is one or more conflicts"};break}g.call(f,"updateMetadata")},f.updateMetadata=function(){var a,b="";b=k.split("-"),b.shift(),b=b.join("-"),a=r._revisions,a.unshift(b),m[k]={_creation_date:r._creation_date||s.getTime(),_last_modified:s.getTime(),_revisions:a,_conflict:n,_deleted:p},n&&(o=d.createConflictObject(h,m,k)),g.call(f,"saveMetadataOnDistant")},f.saveMetadataOnDistant=function(){d.saveMetadataToDistant(h,j,m,function(a){g.call(f,"deleteAllConflictingRevision"),n?g.call(f,"error"):g.call(f,"success")},function(a){g.call(f,"error",[a])})},f.deleteAllConflictingRevision=function(){var a;for(a=0;a<c.key.length;a+=1)d.deleteAFile(h,c.docid+"."+c.key[a],i,i)},f.success=function(){var a={ok:!0,id:c.docid,rev:k};g.neverCall(f,"error"),g.neverCall(f,"success"),b.revs&&(a.revisions=d._revs(m,k)),b.revs_info&&(a.revs_info=d._revs_info(m)),b.conflicts&&(a.conflicts=o),c.success(a)},f.error=function(a){var e=a||t||{status:0,statusText:"Unknown",error:"unknown_error",message:"Unknown error.",reason:"unknown error"};k&&(e.rev=k),b.revs&&(e.revisions=d._revs(m,k)),b.revs_info&&(e.revs_info=d._revs_info(m)),b.conflicts&&(e.conflicts=o),g.neverCall(f,"error"),g.neverCall(f,"success"),c.error(e)},g.call(f,"getDistantMetadata")},d.createConflictObject=function(a,b,c){return{total_rows:1,rows:[d.createConflictRow(a,a.getDocId(),b,c)]}},d.getParam=function(a){var b={},c=0;return typeof a[c]=="string"&&(b.content=a[c],c++),typeof a[c]=="object"?(b.options=a[c],c++):b.options={},b.callback=function(a,b){},b.success=function(a){b.callback(undefined,a)},b.error=function(a){b.callback(a,undefined)},typeof a[c]=="function"&&(typeof a[c+1]=="function"?(b.success=a[c],b.error=a[c+1]):b.callback=a[c]),b},d.createConflictRow=function(a,b,c,e){var f={id:b,key:[],value:{_solveConflict:function(){var c={},g=d.getParam(arguments);return g.content===undefined?c._deleted=!0:c._deleted=!1,c.success=g.success,c.error=g.error,c.previous_revision=e,c.docid=b,c.key=f.key,c.command=a.clone(),d.solveConflict({_id:b,content:g.content,_rev:e},g.options,c)}}},g;for(g in c)f.key.push(g);return f},d.newAsyncModule=function(){var a={};return a.call=function(a,b,c){a._wait=a._wait||{};if(a._wait[b])return a._wait[b]--,i;c=c||[],setTimeout(function(){a[b].apply(a[b],c)})},a.neverCall=function(a,b){a._wait=a._wait||{},a._wait[b]=-1},a.wait=function(a,b,c){a._wait=a._wait||{},a._wait[b]=c},a.end=function(){a.call=i},a},c.post=function(a){c.put(a)},c.put=function(a){var b={},f=d.newAsyncModule(),g=a.getDocId()+".metadata",h="",j="",k=null,l=!1,m={total_rows:0,rows:[]},n=a.getDocInfo("_rev")||"0",o=a.getDocId()+"."+n,p=new Date,q;b.getDistantMetadata=function(){d.getDistantMetadata(a,g,function(c){var d=parseInt(n.split("-")[0],10);k=JSON.parse(c.content),h=d+1+"-"+e(""+a.getDocContent()+n+JSON.stringify(k)),j=a.getDocId()+"."+h,f.wait(b,"saveMetadataOnDistant",1),f.call(b,"saveNewRevision"),f.call(b,"checkForConflicts")},function(c){c.status===404?(h="1-"+e(a.getDocContent()),j=a.getDocId()+"."+h,f.wait(b,"saveMetadataOnDistant",1),f.call(b,"saveNewRevision"),f.call(b,"createMetadata")):f.call(b,"error",[c])})},b.saveNewRevision=function(){d.saveNewRevision(a,j,a.getDocContent(),function(a){f.call(b,"saveMetadataOnDistant")},function(a){f.call(b,"error",[a])})},b.checkForConflicts=function(){var a;for(a in k)if(a!==n){l=!0,q={status:409,error:"conflict",statusText:"Conflict",reason:"document update conflict",message:"Document update conflict."};break}f.call(b,"updateMetadata")},b.createMetadata=function(){var a=h;a=a.split("-"),a.shift(),a=a.join("-"),k={},k[h]={_creation_date:p.getTime(),_last_modified:p.getTime(),_revisions:[a],_conflict:!1,_deleted:!1},f.call(b,"saveMetadataOnDistant")},b.updateMetadata=function(){var c,e=[],g="";k[n]&&(c=k[n]._creation_date,e=k[n]._revisions,delete k[n]),g=h.split("-"),g.shift(),g=g.join("-"),e.unshift(g),k[h]={_creation_date:c||p.getTime(),_last_modified:p.getTime(),_revisions:e,_conflict:l,_deleted:!1},l&&(m=d.createConflictObject(a,k,h)),f.call(b,"saveMetadataOnDistant")},b.saveMetadataOnDistant=function(){d.saveMetadataToDistant(a,g,k,function(a){f.call(b,"deletePreviousRevision"),l?f.call(b,"error"):f.call(b,"success")},function(a){f.call(b,"error",[a])})},b.deletePreviousRevision=function(){n!=="0"&&d.deleteAFile(a,o,i,i)},b.success=function(){var e={ok:!0,id:a.getDocId(),rev:h};f.neverCall(b,"error"),f.neverCall(b,"success"),a.getOption("revs")&&(e.revisions=d._revs(k,h)),a.getOption("revs_info")&&(e.revs_info=d._revs_info(k)),a.getOption("conflicts")&&(e.conflicts=m),c.success(e)},b.error=function(e){var g=e||q||{status:0,statusText:"Unknown",error:"unknown_error",message:"Unknown error.",reason:"unknown error"};h&&(g.rev=h),a.getOption("revs")&&(g.revisions=d._revs(k,h)),a.getOption("revs_info")&&(g.revs_info=d._revs_info(k)),a.getOption("conflicts")&&(g.conflicts=m),f.neverCall(b,"error"),f.neverCall(b,"success"),c.error(g)},f.call(b,"getDistantMetadata")},c.get=function(a){var b={},e=d.newAsyncModule(),f=a.getDocId()+".metadata",g=a.getOption("rev")||"",h=null,i=a.getOption("metadata_only"),j=!1,k={total_rows:0,rows:[]},l=new Date,m={_id:a.getDocId()},n=function(a){e.call(b,"error",[{status:404,statusText:"Not Found",error:"not_found",message:a,reason:a}])};b.getDistantMetadata=function(){d.getDistantMetadata(a,f,function(a){h=JSON.parse(a.content),i||e.wait(b,"success",1),e.call(b,"affectMetadata"),e.call(b,"checkForConflicts")},function(a){e.call(b,"error",[a])})},b.affectMetadata=function(){if(g){if(!h[g])return n("Document revision does not exists.")}else g=d.chooseARevision(h);m._last_modified=h[g]._last_modified,m._creation_date=h[g]._creation_date,m._rev=g,i?e.call(b,"success"):e.call(b,"loadRevision")},b.loadRevision=function(){if(!g||h[g]._deleted)return n("Document has been removed.");d.loadRevision(a,m._id+"."+g,function(a){m.content=a.content,e.call(b,"success")},function(a){e.call(b,"error",[a])})},b.checkForConflicts=function(){h[g]._conflict&&(j=!0,k=d.createConflictObject(a,h,g)),e.call(b,"success")},b.success=function(){e.neverCall(b,"error"),e.neverCall(b,"success"),a.getOption("revs")&&(m._revisions=d._revs(h,g)),a.getOption("revs_info")&&(m._revs_info=d._revs_info(h)),a.getOption("conflicts")&&(m._conflicts=k),c.success(m)},b.error=function(f){var i=f||{status:0,statusText:"Unknown",message:"Unknown error."};a.getOption("revs")&&(i._revisions=d._revs(h,g)),a.getOption("revs_info")&&(i._revs_info=d._revs_info(h)),a.getOption("conflicts")&&(i._conflicts=k),e.neverCall(b,"error"),e.neverCall(b,"success"),c.error(i)},e.call(b,"getDistantMetadata")},c.allDocs=function(a){var b={},e=d.newAsyncModule(),f=a.getOption("metadata_only"),g=[],h={total_rows:0,rows:[]},i=0,j=0,k=0;b.retreiveList=function(){var f=a.cloneOption(),g=function(a){e.call(b,"filterTheList",[a])},h=function(a){e.call(b,"error",[a])};f.metadata_only=!0,c.addJob("allDocs",d.secondstorage_spec,null,f,g,h)},b.filterTheList=function(a){var c;k++;for(c=0;c<a.total_rows;c+=1){var d=a.rows[c].id.split(".")||[];d.length>0&&d[d.length-1]==="metadata"&&(k++,d.length--,e.call(b,"loadMetadataFile",[d.join(".")]))}e.call(b,"success")},b.loadMetadataFile=function(c){d.getDistantMetadata(a,c+".metadata",function(a){a=JSON.parse(a.content);var f=d.chooseARevision(a);a[f]._deleted?e.call(b,"success"):e.call(b,"loadFile",[c,f,a])},function(a){e.call(b,"error",[a])})},b.loadFile=function(c,i,j){var k={id:c,key:c,value:{_last_modified:j[i]._last_modified,_creation_date:j[i]._creation_date,_rev:i}};a.getOption("revs")&&(k.value._revisions=d._revs(j,i)),a.getOption("revs_info")&&(k.value._revs_info=d._revs_info(j,i)),a.getOption("conflicts")&&j[i]._conflict&&(h.total_rows++,h.rows.push(d.createConflictRow(a,c,j,i))),f?(g.push(k),e.call(b,"success")):d.loadRevision(a,c+"."+i,function(a){k.content=a.content,g.push(k),e.call(b,"success")},function(a){e.call(b,"error",[a])})},b.success=function(){var b;j++,j>=k&&(e.end(),b={total_rows:g.length,rows:g},a.getOption("conflicts")&&(b.conflicts=h),c.success(b))},b.error=function(a){e.end(),c.error(a)},e.call(b,"retreiveList")},c.remove=function(a){var b={},f=d.newAsyncModule(),g=a.getDocId()+".metadata",h="",j="",k=null,l=!1,m={total_rows:0,rows:[]},n=a.getOption("rev")||"0",o=a.getDocId()+"."+n,p=new Date,q;b.getDistantMetadata=function(){d.getDistantMetadata(a,g,function(c){k=JSON.parse(c.content),n==="last"&&(n=d.chooseARevision(k),o=a.getDocId()+"."+n);var g=parseInt(n.split("-")[0],10)||0;h=g+1+"-"+e(""+n+JSON.stringify(k)),j=a.getDocId()+"."+h,f.call(b,"checkForConflicts")},function(a){a.status===404?f.call(b,"error",[{status:404,statusText:"Not Found",error:"not_found",reason:"missing",message:"Document not found."}]):f.call(b,"error",[a])})},b.checkForConflicts=function(){var a;for(a in k)if(a!==n){l=!0,q={status:409,error:"conflict",statusText:"Conflict",reason:"document update conflict",message:"There is one or more conflicts"};break}f.call(b,"updateMetadata")},b.updateMetadata=function(){var c,e=[],g="";k[n]&&(c=k[n]._creation_date,e=k[n]._revisions,delete k[n]),g=h,g=g.split("-"),g.shift(),g=g.join("-"),e.unshift(g),k[h]={_creation_date:c||p.getTime(),_last_modified:p.getTime(),_revisions:e,_conflict:l,_deleted:!0},l&&(m=d.createConflictObject(a,k,h)),f.call(b,"saveMetadataOnDistant")},b.saveMetadataOnDistant=function(){d.saveMetadataToDistant(a,g,k,function(a){f.call(b,"deletePreviousRevision"),l?f.call(b,"error"):f.call(b,"success")},function(a){f.call(b,"error",[a])})},b.deletePreviousRevision=function(){n!=="0"&&d.deleteAFile(a,o,i,i)},b.success=function(e){var g={ok:!0,id:a.getDocId(),rev:e||h};f.neverCall(b,"error"),f.neverCall(b,"success"),a.getOption("revs")&&(g.revisions=d._revs(k,h)),a.getOption("revs_info")&&(g.revs_info=d._revs_info(k)),a.getOption("conflicts")&&(g.conflicts=m),c.success(g)},b.error=function(e){var g=e||q||{status:0,statusText:"Unknown",error:"unknown_error",message:"Unknown error.",reason:"unknown error"};h&&(g.rev=h),a.getOption("revs")&&(g.revisions=d._revs(k,h)),a.getOption("revs_info")&&(g.revs_info=d._revs_info(k)),a.getOption("conflicts")&&(g.conflicts=m),f.neverCall(b,"error"),f.neverCall(b,"success"),c.error(g)},f.call(b,"getDistantMetadata")},c};f.addStorageType("conflictmanager",l)})(LocalOrCookieStorage,jQuery,Base64,sjcl,hex_sha256,jio); (function(a,b,c,d,e,f){var g=function(b,c){b=b||{};var d=c.basicStorage(b,c),e={};e.secureDocId=function(a){var b=a.split("/"),c;b[0]===""&&(b=b.slice(1));for(c=0;c<b.length;c+=1)if(b[c]==="")return"";return b.join("%2F")},e.convertSlashes=function(a){return a.split("/").join("%2F")},e.restoreSlashes=function(a){return a.split("%2F").join("/")},e.username=b.username||"",e.secured_username=e.convertSlashes(e.username),e.applicationname=b.applicationname||"untitled",e.secured_applicationname=e.convertSlashes(e.applicationname);var f="jio/local_user_array",g="jio/local_file_name_array/"+e.secured_username+"/"+e.secured_applicationname,h=d.serialized;return d.serialized=function(){var a=h();return a.applicationname=e.applicationname,a.username=e.username,a},d.validateState=function(){return e.secured_username?"":'Need at least one parameter: "username".'},e.getUserArray=function(){return a.getItem(f)||[]},e.addUser=function(b){var c=e.getUserArray();c.push(b),a.setItem(f,c)},e.userExists=function(a){var b=e.getUserArray(),c,d;for(c=0,d=b.length;c<d;c+=1)if(b[c]===a)return!0;return!1},e.getFileNameArray=function(){return a.getItem(g)||[]},e.addFileName=function(b){var c=e.getFileNameArray();c.push(b),a.setItem(g,c)},e.removeFileName=function(b){var c,d,f=e.getFileNameArray(),h=[];for(c=0,d=f.length;c<d;c+=1)f[c]!==b&&h.push(f[c]);a.setItem(g,h)},e.checkSecuredDocId=function(a,b,c){return a?!0:(d.error({status:403,statusText:"Method Not Allowed",error:"method_not_allowed",message:"Cannot "+c+' "'+b+'", file name is incorrect.',reason:"Cannot "+c+' "'+b+'", file name is incorrect'}),!1)},d.post=function(a){d.put(a)},d.put=function(b){setTimeout(function(){var c=e.secureDocId(b.getDocId()),f=null,g="jio/local/"+e.secured_username+"/"+e.secured_applicationname+"/"+c;if(!e.checkSecuredDocId(c,b.getDocId(),"put"))return;f=a.getItem(g),f?(f.content=b.getDocContent(),f._last_modified=Date.now()):(f={_id:b.getDocId(),content:b.getDocContent(),_creation_date:Date.now(),_last_modified:Date.now()},e.userExists(e.secured_username)||e.addUser(e.secured_username),e.addFileName(c)),a.setItem(g,f),d.success({ok:!0,id:b.getDocId()})})},d.get=function(b){setTimeout(function(){var c=e.secureDocId(b.getDocId()),f=null;if(!e.checkSecuredDocId(c,b.getDocId(),"get"))return;f=a.getItem("jio/local/"+e.secured_username+"/"+e.secured_applicationname+"/"+c),f?(b.getOption("metadata_only")&&delete f.content,d.success(f)):d.error({status:404,statusText:"Not Found.",error:"not_found",message:'Document "'+b.getDocId()+'" not found.',reason:"missing"})})},d.allDocs=function(b){setTimeout(function(){var c=[],f=[],g,h,i="key",j="jio/local/"+e.secured_username+"/"+e.secured_applicationname,k={};f=e.getFileNameArray();for(g=0,h=f.length;g<h;g+=1)k=a.getItem(j+"/"+f[g]),k&&(b.getOption("metadata_only")?c.push({id:k._id,key:k._id,value:{_creation_date:k._creation_date,_last_modified:k._last_modified}}):c.push({id:k._id,key:k._id,value:{content:k.content,_creation_date:k._creation_date,_last_modified:k._last_modified}}));d.success({total_rows:c.length,rows:c})})},d.remove=function(b){setTimeout(function(){var c=e.secureDocId(b.getDocId()),f="jio/local/"+e.secured_username+"/"+e.secured_applicationname+"/"+c;if(!e.checkSecuredDocId(c,b.getDocId(),"remove"))return;a.deleteItem(f),e.removeFileName(c),d.success({ok:!0,id:b.getDocId()})})},d};f.addStorageType("local",g);var h=function(a,d){a=a||{};var e=d.basicStorage(a,d),f={};f.secureDocId=function(a){var b=a.split("/"),c;b[0]===""&&(b=b.slice(1));for(c=0;c<b.length;c+=1)if(b[c]==="")return"";return b.join("%2F")},f.convertSlashes=function(a){return a.split("/").join("%2F")},f.restoreSlashes=function(a){return a.split("%2F").join("/")},f.username=a.username||"",f.secured_username=f.convertSlashes(f.username),f.applicationname=a.applicationname||"untitled",f.secured_applicationname=f.convertSlashes(f.applicationname),f.url=a.url||"",f.password=a.password||"";var g=e.serialized;return e.serialized=function(){var a=g();return a.username=f.username,a.applicationname=f.applicationname,a.url=f.url,a.password=f.password,a},e.validateState=function(){return f.secured_username&&f.url?"":'Need at least 2 parameters: "username" and "url".'},f.newAsyncModule=function(){var a={};return a.call=function(a,b,c){return a._wait=a._wait||{},a._wait[b]?(a._wait[b]--,function(){}):(c=c||[],a[b].apply(a[b],c))},a.neverCall=function(a,b){a._wait=a._wait||{},a._wait[b]=-1},a.wait=function(a,b,c){a._wait=a._wait||{},a._wait[b]=c},a.end=function(){a.call=function(){}},a},f.putOrPost=function(a,d){var g=f.secureDocId(a.getDocId());b.ajax({url:f.url+"/"+f.secured_username+"/"+f.secured_applicationname+"/"+g+"?_="+Date.now(),type:d,data:a.getDocContent(),async:!0,dataType:"text",headers:{Authorization:"Basic "+c.encode(f.username+":"+f.password)},success:function(){e.success({ok:!0,id:a.getDocId()})},error:function(b){b.error=b.statusText,b.reason='Cannot save "'+a.getDocId()+'"',b.message=b.reason+".",e.retry(b)}})},e.post=function(a){f.putOrPost(a,"POST")},e.put=function(a){f.putOrPost(a,"PUT")},e.get=function(a){var d=f.secureDocId(a.getDocId()),g={},h=function(){b.ajax({url:f.url+"/"+f.secured_username+"/"+f.secured_applicationname+"/"+d+"?_="+Date.now(),type:"GET",async:!0,dataType:"text",headers:{Authorization:"Basic "+c.encode(f.username+":"+f.password)},success:function(a){g.content=a,e.success(g)},error:function(b){b.error=b.statusText,b.status===404?(b.message='Document "'+a.getDocId()+'" not found.',b.reason="missing",e.error(b)):(b.reason='An error occured when trying to get "'+a.getDocId()+'"',b.message=b.reason+".",e.retry(b))}})};g._id=a.getDocId(),b.ajax({url:f.url+"/"+f.secured_username+"/"+f.secured_applicationname+"/"+d+"?_="+Date.now(),type:"PROPFIND",async:!0,dataType:"xml",headers:{Authorization:"Basic "+c.encode(f.username+":"+f.password)},success:function(c){b(c).find("lp1\\:getlastmodified, getlastmodified").each(function(){g._last_modified=(new Date(b(this).text())).getTime()}),b(c).find("lp1\\:creationdate, creationdate").each(function(){g._creation_date=(new Date(b(this).text())).getTime()}),a.getOption("metadata_only")?e.success(g):h()},error:function(b){b.status===404?(b.message='Cannot find "'+a.getDocId()+'" informations.',b.reason="missing",e.error(b)):(b.reason='Cannot get "'+a.getDocId()+'" informations',b.message=b.reason+".",e.retry(b))}})},e.allDocs=function(a){var d=[],g=f.newAsyncModule(),h={};h.getContent=function(a){b.ajax({url:f.url+"/"+f.secured_username+"/"+f.secured_applicationname+"/"+f.secureDocId(a.id)+"?_="+Date.now(),type:"GET",async:!0,dataType:"text",headers:{Authorization:"Basic "+c.encode(f.username+":"+f.password)},success:function(b){a.value.content=b,d.push(a),g.call(h,"success")},error:function(a){a.error=a.statusText,a.reason="Cannot get a document content from DAVStorage",a.message=a.message+".",g.call(h,"error",[a])}})},h.getDocumentList=function(){b.ajax({url:f.url+"/"+f.secured_username+"/"+f.secured_applicationname+"/"+"?_="+Date.now(),async:!0,type:"PROPFIND",dataType:"xml",headers:{Authorization:"Basic "+c.encode(f.username+":"+f.password),Depth:"1"},success:function(c){var e=b(c).find("D\\:response, response"),i=e.length;if(i===1)return g.call(h,"success");g.wait(h,"success",i-2),e.each(function(c,e){if(c>0){var i={value:{}};b(e).find("D\\:href, href").each(function(){var a=b(this).text().split("/");i.id=a[a.length-1],i.id=f.restoreSlashes(i.id),i.key=i.id});if(i.id===".htaccess"||i.id===".htpasswd")return;b(e).find("lp1\\:getlastmodified, getlastmodified").each(function(){i.value._last_modified=(new Date(b(this).text())).getTime()}),b(e).find("lp1\\:creationdate, creationdate").each(function(){i.value._creation_date=(new Date(b(this).text())).getTime()}),a.getOption("metadata_only")?(d.push(i),g.call(h,"success")):g.call(h,"getContent",[i])}})},error:function(a){a.status===404?(a.error="not_found",a.reason="missing",g.call(h,"error",[a])):(a.error=a.statusText,a.reason="Cannot get a document list from DAVStorage",a.message=a.reason+".",g.call(h,"retry",[a]))}})},h.retry=function(a){g.neverCall(h,"retry"),g.neverCall(h,"success"),g.neverCall(h,"error"),e.retry(a)},h.error=function(a){g.neverCall(h,"retry"),g.neverCall(h,"success"),g.neverCall(h,"error"),e.error(a)},h.success=function(){g.neverCall(h,"retry"),g.neverCall(h,"success"),g.neverCall(h,"error"),e.success({total_rows:d.length,rows:d})},g.call(h,"getDocumentList")},e.remove=function(a){var d=f.secureDocId(a.getDocId());b.ajax({url:f.url+"/"+f.secured_username+"/"+f.secured_applicationname+"/"+d+"?_="+Date.now(),type:"DELETE",async:!0,headers:{Authorization:"Basic "+c.encode(f.username+":"+f.password)},success:function(b,c,d){e.success({ok:!0,id:a.getDocId()})},error:function(a,b,c){a.status===404?(a.error="not_found",a.reason="missing",a.message="Cannot remove missing file.",e.error(a)):(a.reason='Cannot remove "'+e.getDocId()+'"',a.message=a.reason+".",e.retry(a))}})},e};f.addStorageType("dav",h);var i=function(a,b){a=a||{};var c=b.basicStorage(a,b),d={};d.return_value_array=[],d.storagelist=a.storagelist||[],d.nb_storage=d.storagelist.length;var e=c.serialized;return c.serialized=function(){var a=e();return a.storagelist=d.storagelist,a},c.validateState=function(){return d.storagelist.length===0?'Need at least one parameter: "storagelist" containing at least one storage.':""},d.isTheLast=function(a){return a.length===d.nb_storage},d.doJob=function(a,b,e){var f=!1,g=[],h,i=function(h){f||(g.push(h),d.isTheLast(g)&&c.error({status:207,statusText:"Multi-Status",error:"multi_status",message:"All "+b+(e?" ":' "'+a.getDocId()+'"')+" requests have failed.",reason:"requests fail",array:g}))},j=function(a){f||(f=!0,c.success(a))};for(h=0;h<d.nb_storage;h+=1){var k=a.cloneOption();c.addJob(a.getLabel(),d.storagelist[h],a.cloneDoc(),k,j,i)}},c.post=function(a){d.doJob(a,"post"),c.end()},c.put=function(a){d.doJob(a,"put"),c.end()},c.get=function(a){d.doJob(a,"get"),c.end()},c.allDocs=function(a){d.doJob(a,"allDocs",!0),c.end()},c.remove=function(a){d.doJob(a,"remove"),c.end()},c};f.addStorageType("replicate",i);var j=function(b,c){b=b||{};var d=c.basicStorage(b,c),e={},f=b.storage||!1;e.secondstorage_spec=b.storage||{type:"base"},e.secondstorage_string=JSON.stringify(e.secondstorage_spec);var g="jio/indexed_storage_object",h="jio/indexed_file_object/"+e.secondstorage_string,i=d.serialized;return d.serialized=function(){var a=i();return a.storage=e.secondstorage_spec,a},d.validateState=function(){return f?"":'Need at least one parameter: "storage" containing storage specifications.'},e.secureDocId=function(a){var b=a.split("/"),c;b[0]===""&&(b=b.slice(1));for(c=0;c<b.length;c+=1)if(b[c]==="")return"";return b.join("%2F")},e.indexStorage=function(){var b=a.getItem(g)||{};b[e.secondstorage_spec]=(new Date).getTime(),a.setItem(g,b)},e.formatToFileObject=function(a){var b,c={_id:a.id};for(b in a.value)c[b]=a.value[b];return c},e.allDocs=function(a){var b,c={rows:[]},d=0;for(b in a)c.rows[d]={},c.rows[d].value=a[b],c.rows[d].id=c.rows[d].key=c.rows[d].value._id,delete c.rows[d].value._id,d++;return c.total_rows=c.rows.length,c},e.setFileArray=function(b){var c,d={};for(c=0;c<b.length;c+=1)d[b[c].id]=e.formatToFileObject(b[c]);a.setItem(h,d)},e.getFileObject=function(b){var c=a.getItem(h)||{};return c[b]},e.addFile=function(b){var c=a.getItem(h)||{};c[b._id]=b,a.setItem(h,c)},e.removeFile=function(b){var c=a.getItem(h)||{};delete c[b],a.setItem(h,c)},e.update=function(){var a=function(a){e.setFileArray(a.rows)};d.addJob("allDocs",e.secondstorage_spec,null,{max_retry:3},a,function(){})},d.post=function(a){d.put(a)},d.put=function(a){var b=a.cloneDoc(),c=a.cloneOption(),f=function(a){e.update(),d.success(a)},g=function(a){d.error(a)};e.indexStorage(),d.addJob("put",e.secondstorage_spec,b,c,f,g)},d.get=function(a){var b,c=function(a){d.success(a)},f=function(a){d.error(a)},g=function(){var b=a.cloneOption();d.addJob("get",e.secondstorage_spec,a.cloneDoc(),b,c,f),d.end()};e.indexStorage(),e.update(),a.getOption("metadata_only")?setTimeout(function(){var b=e.getFileObject(a.getDocId());b&&(b._last_modified||b._creation_date)?d.success(b):g()}):g()},d.allDocs=function(b){var c=a.getItem(h);if(c)e.update(),setTimeout(function(){d.success(e.allDocs(c))});else{var f=function(a){e.setFileArray(a.rows),d.success(a)},g=function(a){d.error(a)};d.addJob("allDocs",e.secondstorage_spec,null,b.cloneOption(),f,g)}},d.remove=function(a){var b=function(b){e.removeFile(a.getDocId()),e.update(),d.success(b)},c=function(a){d.error(a)};d.addJob("remove",e.secondstorage_spec,a.cloneDoc(),a.cloneOption(),b,c)},d};f.addStorageType("indexed",j);var k=function(a,c){a=a||{};var e=c.basicStorage(a,c),f={},g=a.storage?!0:!1;f.username=a.username||"",f.password=a.password||"",f.secondstorage_spec=a.storage||{type:"base"},f.secondstorage_string=JSON.stringify(f.secondstorage_string);var h=e.serialized;return e.serialized=function(){var a=h();return a.username=f.username,a.password=f.password,a.storage=f.secondstorage_string,a},e.validateState=function(){return f.username&&g?"":'Need at least two parameters: "username" and "storage".'},f.encrypt_param_object={iv:"kaprWwY/Ucr7pumXoTHbpA",v:1,iter:1e3,ks:256,ts:128,mode:"ccm",adata:"",cipher:"aes",salt:"K4bmZG9d704"},f.decrypt_param_object={iv:"kaprWwY/Ucr7pumXoTHbpA",ks:256,ts:128,salt:"K4bmZG9d704"},f.encrypt=function(a,b){var c=d.encrypt(f.username+":"+f.password,a,f.encrypt_param_object);b(JSON.parse(c).ct)},f.decrypt=function(a,c){var e,g=b.extend(!0,{},f.decrypt_param_object);g.ct=a||"",g=JSON.stringify(g);try{e=d.decrypt(f.username+":"+f.password,g)}catch(h){c({status:403,statusText:"Forbidden",error:"forbidden",message:"Unable to decrypt.",reason:"unable to decrypt"});return}c(undefined,e)},f.newAsyncModule=function(){var a={};return a.call=function(a,b,c){a._wait=a._wait||{};if(a._wait[b])return a._wait[b]--,function(){};c=c||[],setTimeout(function(){a[b].apply(a[b],c)})},a.neverCall=function(a,b){a._wait=a._wait||{},a._wait[b]=-1},a.wait=function(a,b,c){a._wait=a._wait||{},a._wait[b]=c},a.end=function(){a.call=function(){}},a},e.post=function(a){e.put(a)},e.put=function(a){var b,c,d=f.newAsyncModule(),g={};g.encryptFilePath=function(){f.encrypt(a.getDocId(),function(a){b=a,d.call(g,"save")})},g.encryptFileContent=function(){f.encrypt(a.getDocContent(),function(a){c=a,d.call(g,"save")})},g.save=function(){var d=function(b){b.id=a.getDocId(),e.success(b)},g=function(a){e.error(a)},h=a.cloneDoc();h._id=b,h.content=c,e.addJob("put",f.secondstorage_spec,h,a.cloneOption(),d,g)},d.wait(g,"save",1),d.call(g,"encryptFilePath"),d.call(g,"encryptFileContent")},e.get=function(a){var b,c,d=f.newAsyncModule(),g={};g.encryptFilePath=function(){f.encrypt(a.getDocId(),function(a){b=a,d.call(g,"get")})},g.get=function(){e.addJob("get",f.secondstorage_spec,b,a.cloneOption(),g.success,g.error)},g.success=function(b){b._id=a.getDocId(),a.getOption("metadata_only")?e.success(b):f.decrypt(b.content,function(a,c){a?e.error(a):(b.content=c,e.success(b))})},g.error=function(a){e.error(a)},d.call(g,"encryptFilePath")},e.allDocs=function(a){var b=[],c=f.newAsyncModule(),d={};d.allDocs=function(){e.addJob("allDocs",f.secondstorage_spec,null,a.cloneOption(),d.onSuccess,d.error)},d.onSuccess=function(e){if(e.total_rows===0)return c.call(d,"success");b=e.rows;var g,h=function(e){f.decrypt(b[e].id,function(a,f){a?c.call(d,"error",[a]):(b[e].id=f,b[e].key=f,c.call(d,"success"))}),a.getOption("metadata_only")||f.decrypt(b[e].value.content,function(a,f){a?c.call(d,"error",[a]):(b[e].value.content=f,c.call(d,"success"))})};a.getOption("metadata_only")?c.wait(d,"success",e.total_rows*1-1):c.wait(d,"success",e.total_rows*2-1);for(g=0;g<b.length;g+=1)h(g)},d.error=function(a){c.end(),e.error(a)},d.success=function(){c.end(),e.success({total_rows:b.length,rows:b})},c.call(d,"allDocs")},e.remove=function(a){var b,c={};c.encryptDocId=function(){f.encrypt(a.getDocId(),function(a){b=a,c.removeDocument()})},c.removeDocument=function(){var d=a.cloneDoc();d._id=b,e.addJob("remove",f.secondstorage_spec,d,a.cloneOption(),c.success,e.error)},c.success=function(b){b.id=a.getDocId(),e.success(b)},c.encryptDocId()},e};f.addStorageType("crypt",k);var l=function(a,b){a=a||{};var c=b.basicStorage(a,b),d={},f=a.storage?!0:!1;d.secondstorage_spec=a.storage||{type:"base"},d.secondstorage_string=JSON.stringify(d.secondstorage_spec);var g="jio/conflictmanager/"+d.secondstorage_string+"/",h=function(){},i=c.serialized;return c.serialized=function(){var a=i();return a.storage=d.secondstorage_spec,a},c.validateState=function(){return f?"":'Need at least one parameter: "storage".'},d.getDistantMetadata=function(a,b,e,f){var g=a.cloneOption();g.metadata_only=!1,c.addJob("get",d.secondstorage_spec,b,g,e,f)},d.saveMetadataToDistant=function(a,b,e,f,g){c.addJob("put",d.secondstorage_spec,{_id:b,content:JSON.stringify(e)},a.cloneOption(),f,g)},d.saveNewRevision=function(a,b,e,f,g){c.addJob("post",d.secondstorage_spec,{_id:b,content:e},a.cloneOption(),f,g)},d.loadRevision=function(a,b,e,f){c.addJob("get",d.secondstorage_spec,b,a.cloneOption(),e,f)},d.deleteAFile=function(a,b,e,f){var g=a.cloneOption();c.addJob("remove",d.secondstorage_spec,{_id:b},a.cloneOption(),e,f)},d.chooseARevision=function(a){var b=0,c="",d;for(d in a)b<a[d]._last_modified&&(b=a[d]._last_modified,c=d);return c},d._revs=function(a,b){return!a||!b?null:a[b]?{start:a[b]._revisions.length,ids:a[b]._revisions}:null},d._revs_info=function(a){if(!a)return null;var b,c=[];for(b in a)c.push({rev:b,status:a[b]?a[b]._deleted?"deleted":"available":"missing"});return c},d.solveConflict=function(a,b,c){var f={},g=d.newAsyncModule(),i=c.command,j=c.docid+".metadata",k="",l="",m=null,n=!1,o={total_rows:0,rows:[]},p=c._deleted,q=c.previous_revision,r=null,s=new Date,t;f.getDistantMetadata=function(){d.getDistantMetadata(i,j,function(b){var d=parseInt(q.split("-")[0],10);m=JSON.parse(b.content),k=d+1+"-"+e(""+a.content+q+JSON.stringify(m)),l=c.docid+"."+k,r=m[q]||{},p||(g.wait(f,"saveMetadataOnDistant",1),g.call(f,"saveNewRevision")),g.call(f,"previousUpdateMetadata")},function(a){g.call(f,"error",[a])})},f.saveNewRevision=function(){d.saveNewRevision(i,l,a.content,function(a){g.call(f,"saveMetadataOnDistant")},function(a){g.call(f,"error",[a])})},f.previousUpdateMetadata=function(){var a;for(a=0;a<c.key.length;a+=1)delete m[c.key[a]];g.call(f,"checkForConflicts")},f.checkForConflicts=function(){var a;for(a in m){var b;n=!0,t={status:409,error:"conflict",statusText:"Conflict",reason:"document update conflict",message:"There is one or more conflicts"};break}g.call(f,"updateMetadata")},f.updateMetadata=function(){var a,b="";b=k.split("-"),b.shift(),b=b.join("-"),a=r._revisions,a.unshift(b),m[k]={_creation_date:r._creation_date||s.getTime(),_last_modified:s.getTime(),_revisions:a,_conflict:n,_deleted:p},n&&(o=d.createConflictObject(i,m,k)),g.call(f,"saveMetadataOnDistant")},f.saveMetadataOnDistant=function(){d.saveMetadataToDistant(i,j,m,function(a){g.call(f,"deleteAllConflictingRevision"),n?g.call(f,"error"):g.call(f,"success")},function(a){g.call(f,"error",[a])})},f.deleteAllConflictingRevision=function(){var a;for(a=0;a<c.key.length;a+=1)d.deleteAFile(i,c.docid+"."+c.key[a],h,h)},f.success=function(){var a={ok:!0,id:c.docid,rev:k};g.neverCall(f,"error"),g.neverCall(f,"success"),b.revs&&(a.revisions=d._revs(m,k)),b.revs_info&&(a.revs_info=d._revs_info(m)),b.conflicts&&(a.conflicts=o),c.success(a)},f.error=function(a){var e=a||t||{status:0,statusText:"Unknown",error:"unknown_error",message:"Unknown error.",reason:"unknown error"};k&&(e.rev=k),b.revs&&(e.revisions=d._revs(m,k)),b.revs_info&&(e.revs_info=d._revs_info(m)),b.conflicts&&(e.conflicts=o),g.neverCall(f,"error"),g.neverCall(f,"success"),c.error(e)},g.call(f,"getDistantMetadata")},d.createConflictObject=function(a,b,c){return{total_rows:1,rows:[d.createConflictRow(a,a.getDocId(),b,c)]}},d.getParam=function(a){var b={},c=0;return typeof a[c]=="string"&&(b.content=a[c],c++),typeof a[c]=="object"?(b.options=a[c],c++):b.options={},b.callback=function(a,b){},b.success=function(a){b.callback(undefined,a)},b.error=function(a){b.callback(a,undefined)},typeof a[c]=="function"&&(typeof a[c+1]=="function"?(b.success=a[c],b.error=a[c+1]):b.callback=a[c]),b},d.createConflictRow=function(a,b,c,e){var f={id:b,key:[],value:{_solveConflict:function(){var c={},g=d.getParam(arguments);return g.content===undefined?c._deleted=!0:c._deleted=!1,c.success=g.success,c.error=g.error,c.previous_revision=e,c.docid=b,c.key=f.key,c.command=a.clone(),d.solveConflict({_id:b,content:g.content,_rev:e},g.options,c)}}},g;for(g in c)f.key.push(g);return f},d.newAsyncModule=function(){var a={};return a.call=function(a,b,c){a._wait=a._wait||{};if(a._wait[b])return a._wait[b]--,h;c=c||[],setTimeout(function(){a[b].apply(a[b],c)})},a.neverCall=function(a,b){a._wait=a._wait||{},a._wait[b]=-1},a.wait=function(a,b,c){a._wait=a._wait||{},a._wait[b]=c},a.end=function(){a.call=h},a},c.post=function(a){c.put(a)},c.put=function(a){var b={},f=d.newAsyncModule(),g=a.getDocId()+".metadata",i="",j="",k=null,l=!1,m={total_rows:0,rows:[]},n=a.getDocInfo("_rev")||"0",o=a.getDocId()+"."+n,p=new Date,q;b.getDistantMetadata=function(){d.getDistantMetadata(a,g,function(c){var d=parseInt(n.split("-")[0],10);k=JSON.parse(c.content),i=d+1+"-"+e(""+a.getDocContent()+n+JSON.stringify(k)),j=a.getDocId()+"."+i,f.wait(b,"saveMetadataOnDistant",1),f.call(b,"saveNewRevision"),f.call(b,"checkForConflicts")},function(c){c.status===404?(i="1-"+e(a.getDocContent()),j=a.getDocId()+"."+i,f.wait(b,"saveMetadataOnDistant",1),f.call(b,"saveNewRevision"),f.call(b,"createMetadata")):f.call(b,"error",[c])})},b.saveNewRevision=function(){d.saveNewRevision(a,j,a.getDocContent(),function(a){f.call(b,"saveMetadataOnDistant")},function(a){f.call(b,"error",[a])})},b.checkForConflicts=function(){var a;for(a in k)if(a!==n){l=!0,q={status:409,error:"conflict",statusText:"Conflict",reason:"document update conflict",message:"Document update conflict."};break}f.call(b,"updateMetadata")},b.createMetadata=function(){var a=i;a=a.split("-"),a.shift(),a=a.join("-"),k={},k[i]={_creation_date:p.getTime(),_last_modified:p.getTime(),_revisions:[a],_conflict:!1,_deleted:!1},f.call(b,"saveMetadataOnDistant")},b.updateMetadata=function(){var c,e=[],g="";k[n]&&(c=k[n]._creation_date,e=k[n]._revisions,delete k[n]),g=i.split("-"),g.shift(),g=g.join("-"),e.unshift(g),k[i]={_creation_date:c||p.getTime(),_last_modified:p.getTime(),_revisions:e,_conflict:l,_deleted:!1},l&&(m=d.createConflictObject(a,k,i)),f.call(b,"saveMetadataOnDistant")},b.saveMetadataOnDistant=function(){d.saveMetadataToDistant(a,g,k,function(a){f.call(b,"deletePreviousRevision"),l?f.call(b,"error"):f.call(b,"success")},function(a){f.call(b,"error",[a])})},b.deletePreviousRevision=function(){n!=="0"&&d.deleteAFile(a,o,h,h)},b.success=function(){var e={ok:!0,id:a.getDocId(),rev:i};f.neverCall(b,"error"),f.neverCall(b,"success"),a.getOption("revs")&&(e.revisions=d._revs(k,i)),a.getOption("revs_info")&&(e.revs_info=d._revs_info(k)),a.getOption("conflicts")&&(e.conflicts=m),c.success(e)},b.error=function(e){var g=e||q||{status:0,statusText:"Unknown",error:"unknown_error",message:"Unknown error.",reason:"unknown error"};i&&(g.rev=i),a.getOption("revs")&&(g.revisions=d._revs(k,i)),a.getOption("revs_info")&&(g.revs_info=d._revs_info(k)),a.getOption("conflicts")&&(g.conflicts=m),f.neverCall(b,"error"),f.neverCall(b,"success"),c.error(g)},f.call(b,"getDistantMetadata")},c.get=function(a){var b={},e=d.newAsyncModule(),f=a.getDocId()+".metadata",g=a.getOption("rev")||"",h=null,i=a.getOption("metadata_only"),j=!1,k={total_rows:0,rows:[]},l=new Date,m={_id:a.getDocId()},n=function(a){e.call(b,"error",[{status:404,statusText:"Not Found",error:"not_found",message:a,reason:a}])};b.getDistantMetadata=function(){d.getDistantMetadata(a,f,function(a){h=JSON.parse(a.content),i||e.wait(b,"success",1),e.call(b,"affectMetadata"),e.call(b,"checkForConflicts")},function(a){e.call(b,"error",[a])})},b.affectMetadata=function(){if(g){if(!h[g])return n("Document revision does not exists.")}else g=d.chooseARevision(h);m._last_modified=h[g]._last_modified,m._creation_date=h[g]._creation_date,m._rev=g,i?e.call(b,"success"):e.call(b,"loadRevision")},b.loadRevision=function(){if(!g||h[g]._deleted)return n("Document has been removed.");d.loadRevision(a,m._id+"."+g,function(a){m.content=a.content,e.call(b,"success")},function(a){e.call(b,"error",[a])})},b.checkForConflicts=function(){h[g]._conflict&&(j=!0,k=d.createConflictObject(a,h,g)),e.call(b,"success")},b.success=function(){e.neverCall(b,"error"),e.neverCall(b,"success"),a.getOption("revs")&&(m._revisions=d._revs(h,g)),a.getOption("revs_info")&&(m._revs_info=d._revs_info(h)),a.getOption("conflicts")&&(m._conflicts=k),c.success(m)},b.error=function(f){var i=f||{status:0,statusText:"Unknown",message:"Unknown error."};a.getOption("revs")&&(i._revisions=d._revs(h,g)),a.getOption("revs_info")&&(i._revs_info=d._revs_info(h)),a.getOption("conflicts")&&(i._conflicts=k),e.neverCall(b,"error"),e.neverCall(b,"success"),c.error(i)},e.call(b,"getDistantMetadata")},c.allDocs=function(a){var b={},e=d.newAsyncModule(),f=a.getOption("metadata_only"),g=[],h={total_rows:0,rows:[]},i=0,j=0,k=0;b.retreiveList=function(){var f=a.cloneOption(),g=function(a){e.call(b,"filterTheList",[a])},h=function(a){e.call(b,"error",[a])};f.metadata_only=!0,c.addJob("allDocs",d.secondstorage_spec,null,f,g,h)},b.filterTheList=function(a){var c;k++;for(c=0;c<a.total_rows;c+=1){var d=a.rows[c].id.split(".")||[];d.length>0&&d[d.length-1]==="metadata"&&(k++,d.length--,e.call(b,"loadMetadataFile",[d.join(".")]))}e.call(b,"success")},b.loadMetadataFile=function(c){d.getDistantMetadata(a,c+".metadata",function(a){a=JSON.parse(a.content);var f=d.chooseARevision(a);a[f]._deleted?e.call(b,"success"):e.call(b,"loadFile",[c,f,a])},function(a){e.call(b,"error",[a])})},b.loadFile=function(c,i,j){var k={id:c,key:c,value:{_last_modified:j[i]._last_modified,_creation_date:j[i]._creation_date,_rev:i}};a.getOption("revs")&&(k.value._revisions=d._revs(j,i)),a.getOption("revs_info")&&(k.value._revs_info=d._revs_info(j,i)),a.getOption("conflicts")&&j[i]._conflict&&(h.total_rows++,h.rows.push(d.createConflictRow(a,c,j,i))),f?(g.push(k),e.call(b,"success")):d.loadRevision(a,c+"."+i,function(a){k.content=a.content,g.push(k),e.call(b,"success")},function(a){e.call(b,"error",[a])})},b.success=function(){var b;j++,j>=k&&(e.end(),b={total_rows:g.length,rows:g},a.getOption("conflicts")&&(b.conflicts=h),c.success(b))},b.error=function(a){e.end(),c.error(a)},e.call(b,"retreiveList")},c.remove=function(a){var b={},f=d.newAsyncModule(),g=a.getDocId()+".metadata",i="",j="",k=null,l=!1,m={total_rows:0,rows:[]},n=a.getOption("rev")||"0",o=a.getDocId()+"."+n,p=new Date,q;b.getDistantMetadata=function(){d.getDistantMetadata(a,g,function(c){k=JSON.parse(c.content),n==="last"&&(n=d.chooseARevision(k),o=a.getDocId()+"."+n);var g=parseInt(n.split("-")[0],10)||0;i=g+1+"-"+e(""+n+JSON.stringify(k)),j=a.getDocId()+"."+i,f.call(b,"checkForConflicts")},function(a){a.status===404?f.call(b,"error",[{status:404,statusText:"Not Found",error:"not_found",reason:"missing",message:"Document not found."}]):f.call(b,"error",[a])})},b.checkForConflicts=function(){var a;for(a in k)if(a!==n){l=!0,q={status:409,error:"conflict",statusText:"Conflict",reason:"document update conflict",message:"There is one or more conflicts"};break}f.call(b,"updateMetadata")},b.updateMetadata=function(){var c,e=[],g="";k[n]&&(c=k[n]._creation_date,e=k[n]._revisions,delete k[n]),g=i,g=g.split("-"),g.shift(),g=g.join("-"),e.unshift(g),k[i]={_creation_date:c||p.getTime(),_last_modified:p.getTime(),_revisions:e,_conflict:l,_deleted:!0},l&&(m=d.createConflictObject(a,k,i)),f.call(b,"saveMetadataOnDistant")},b.saveMetadataOnDistant=function(){d.saveMetadataToDistant(a,g,k,function(a){f.call(b,"deletePreviousRevision"),l?f.call(b,"error"):f.call(b,"success")},function(a){f.call(b,"error",[a])})},b.deletePreviousRevision=function(){n!=="0"&&d.deleteAFile(a,o,h,h)},b.success=function(e){var g={ok:!0,id:a.getDocId(),rev:e||i};f.neverCall(b,"error"),f.neverCall(b,"success"),a.getOption("revs")&&(g.revisions=d._revs(k,i)),a.getOption("revs_info")&&(g.revs_info=d._revs_info(k)),a.getOption("conflicts")&&(g.conflicts=m),c.success(g)},b.error=function(e){var g=e||q||{status:0,statusText:"Unknown",error:"unknown_error",message:"Unknown error.",reason:"unknown error"};i&&(g.rev=i),a.getOption("revs")&&(g.revisions=d._revs(k,i)),a.getOption("revs_info")&&(g.revs_info=d._revs_info(k)),a.getOption("conflicts")&&(g.conflicts=m),f.neverCall(b,"error"),f.neverCall(b,"success"),c.error(g)},f.call(b,"getDistantMetadata")},c};f.addStorageType("conflictmanager",l)})(LocalOrCookieStorage,jQuery,Base64,sjcl,hex_sha256,jio);
\ No newline at end of file \ No newline at end of file
...@@ -180,7 +180,7 @@ var newLocalStorage = function ( spec, my ) { ...@@ -180,7 +180,7 @@ var newLocalStorage = function ( spec, my ) {
} }
LocalOrCookieStorage.setItem(path, doc); LocalOrCookieStorage.setItem(path, doc);
that.success ({ok:true,id:command.getDocId()}); that.success ({ok:true,id:command.getDocId()});
},5000); });
}; // end put }; // end put
/** /**
...@@ -214,7 +214,7 @@ var newLocalStorage = function ( spec, my ) { ...@@ -214,7 +214,7 @@ var newLocalStorage = function ( spec, my ) {
} }
that.success (doc); that.success (doc);
} }
},5000); });
}; // end get }; // end get
/** /**
...@@ -250,7 +250,7 @@ var newLocalStorage = function ( spec, my ) { ...@@ -250,7 +250,7 @@ var newLocalStorage = function ( spec, my ) {
} }
} }
that.success ({total_rows:new_array.length,rows:new_array}); that.success ({total_rows:new_array.length,rows:new_array});
},5000); });
}; // end allDocs }; // end allDocs
/** /**
...@@ -271,7 +271,7 @@ var newLocalStorage = function ( spec, my ) { ...@@ -271,7 +271,7 @@ var newLocalStorage = function ( spec, my ) {
LocalOrCookieStorage.deleteItem(path); LocalOrCookieStorage.deleteItem(path);
priv.removeFileName(secured_docid); priv.removeFileName(secured_docid);
that.success ({ok:true,id:command.getDocId()}); that.success ({ok:true,id:command.getDocId()});
},5000); });
}; // end remove }; // end remove
return that; return that;
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment