Commit 26de76ef authored by Tristan Cavelier's avatar Tristan Cavelier Committed by Sebastien Robin

Jio CryptedStorage completed + Qunit tests

parent 77966ec9
...@@ -50,6 +50,7 @@ module.exports = function(grunt) { ...@@ -50,6 +50,7 @@ module.exports = function(grunt) {
}, },
globals: { globals: {
jQuery: true, jQuery: true,
sjcl: true,
LocalOrCookieStorage: true, LocalOrCookieStorage: true,
Base64: true, Base64: true,
JIO: true, JIO: true,
......
...@@ -57,6 +57,7 @@ module.exports = function(grunt) { ...@@ -57,6 +57,7 @@ module.exports = function(grunt) {
}, },
globals: { globals: {
jQuery: true, jQuery: true,
sjcl:true,
LocalOrCookieStorage: true, LocalOrCookieStorage: true,
Base64: true, Base64: true,
JIO: true, JIO: true,
......
/*! JIO - v0.1.0 - 2012-06-01 /*! JIO - v0.1.0 - 2012-06-05
* Copyright (c) 2012 Nexedi; Licensed */ * Copyright (c) 2012 Nexedi; Licensed */
var JIO = var JIO =
(function () { var jio_loader_function = function ( localOrCookieStorage, $ ) { (function () { var jioLoaderFunction = function ( localOrCookieStorage, $ ) {
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
// constants // constants
...@@ -25,8 +25,8 @@ var JIO = ...@@ -25,8 +25,8 @@ var JIO =
- s: storage - s: storage
- a: applicant - a: applicant
- m: method - m: method
- n: fileName - n: name
- c: fileContent - c: content
- o: options - o: options
- =: are equal - =: are equal
- !: are not equal - !: are not equal
...@@ -94,7 +94,7 @@ var JIO = ...@@ -94,7 +94,7 @@ var JIO =
JSON.stringify (job2.storage) && JSON.stringify (job2.storage) &&
JSON.stringify (job1.applicant) === JSON.stringify (job1.applicant) ===
JSON.stringify (job2.applicant) && JSON.stringify (job2.applicant) &&
job1.fileName === job2.fileName) { job1.name === job2.name) {
return true; return true;
} }
return false; return false;
...@@ -107,7 +107,7 @@ var JIO = ...@@ -107,7 +107,7 @@ var JIO =
return false; return false;
}, },
canEliminate:function (job1,job2) { canEliminate:function (job1,job2) {
if (job1.status !== 'ongoing' && if (job1.status !== 'on_going' &&
(job1.method === 'removeDocument' && (job1.method === 'removeDocument' &&
job2.method === 'saveDocument' || job2.method === 'saveDocument' ||
job1.method === 'saveDocument' && job1.method === 'saveDocument' &&
...@@ -117,7 +117,7 @@ var JIO = ...@@ -117,7 +117,7 @@ var JIO =
return false; return false;
}, },
canReplace:function (job1,job2) { canReplace:function (job1,job2) {
if (job1.status !== 'ongoing' && if (job1.status !== 'on_going' &&
job1.method === job2.method && job1.method === job2.method &&
job1.date < job2.date) { job1.date < job2.date) {
return true; return true;
...@@ -125,7 +125,7 @@ var JIO = ...@@ -125,7 +125,7 @@ var JIO =
return false; return false;
}, },
cannotAccept:function (job1,job2) { cannotAccept:function (job1,job2) {
if (job1.status !== 'ongoing' ) { if (job1.status !== 'on_going' ) {
if (job1.method === 'removeDocument' && if (job1.method === 'removeDocument' &&
job2.method === 'loadDocument') { job2.method === 'loadDocument') {
return true; return true;
...@@ -138,7 +138,7 @@ var JIO = ...@@ -138,7 +138,7 @@ var JIO =
job2.method === 'removeDocument')) { job2.method === 'removeDocument')) {
return true; return true;
} else if (job1.method === job2.method === 'saveDocument' && } else if (job1.method === job2.method === 'saveDocument' &&
job1.fileContent === job2.fileContent) { job1.content === job2.content) {
return true; return true;
} else if (job1.method === job2.method === } else if (job1.method === job2.method ===
'getDocumentList' || 'getDocumentList' ||
...@@ -198,18 +198,18 @@ var JIO = ...@@ -198,18 +198,18 @@ var JIO =
} }
return topic; return topic;
}; };
that.publish = function (eventname,obj) { that.publish = function (event_name,obj) {
// publish an event // publish an event
priv.eventAction(eventname).publish(obj); priv.eventAction(event_name).publish(obj);
}; };
that.subscribe = function (eventname,callback) { that.subscribe = function (event_name,callback) {
// subscribe and return the callback function // subscribe and return the callback function
priv.eventAction(eventname).subscribe(callback); priv.eventAction(event_name).subscribe(callback);
return callback; return callback;
}; };
that.unsubscribe = function (eventname,callback) { that.unsubscribe = function (event_name,callback) {
// unsubscribe the callback from eventname // unsubscribe the callback from eventname
priv.eventAction(eventname).unsubscribe(callback); priv.eventAction(event_name).unsubscribe(callback);
}; };
return that; return that;
}; };
...@@ -235,14 +235,14 @@ var JIO = ...@@ -235,14 +235,14 @@ var JIO =
// spec.options.useLocalStorage: if true, save jobs into localStorage, // spec.options.useLocalStorage: if true, save jobs into localStorage,
// else only save on memory. // else only save on memory.
var that = {}, priv = {}, jio_id_array_name = 'jio/idarray'; var that = {}, priv = {}, jio_id_array_name = 'jio/id_array';
that.init = function ( options ) { that.init = function ( options ) {
// initialize the JobQueue // initialize the JobQueue
// options.publisher : is the publisher to use to send events // options.publisher : is the publisher to use to send events
// options.jio_id : the jio ID // options.jio_id : the jio ID
var k, emptyfun = function (){}, jio_id_array; var k, emptyFun = function (){}, jio_id_array;
if (priv.use_local_storage) { if (priv.use_local_storage) {
jio_id_array = localOrCookieStorage. jio_id_array = localOrCookieStorage.
getItem (jio_id_array_name)||[]; getItem (jio_id_array_name)||[];
...@@ -250,14 +250,14 @@ var JIO = ...@@ -250,14 +250,14 @@ var JIO =
priv.publisher = spec.publisher; priv.publisher = spec.publisher;
} }
priv.jio_id = options.jio_id; priv.jio_id = options.jio_id;
priv.job_object_name = 'jio/jobobject/' + priv.jio_id; priv.job_object_name = 'jio/job_object/' + priv.jio_id;
jio_id_array.push (priv.jio_id); jio_id_array.push (priv.jio_id);
localOrCookieStorage.setItem (jio_id_array_name,jio_id_array); localOrCookieStorage.setItem (jio_id_array_name,jio_id_array);
} }
priv.job_object = {}; priv.job_object = {};
that.copyJobQueueToLocalStorage(); that.copyJobQueueToLocalStorage();
for (k in priv.recovered_job_object) { for (k in priv.recovered_job_object) {
priv.recovered_job_object[k].callback = emptyfun; priv.recovered_job_object[k].callback = emptyFun;
that.addJob (priv.recovered_job_object[k]); that.addJob (priv.recovered_job_object[k]);
} }
}; };
...@@ -302,10 +302,10 @@ var JIO = ...@@ -302,10 +302,10 @@ var JIO =
jio_id_array[k]); jio_id_array[k]);
// job recovery // job recovery
priv.recovered_job_object = localOrCookieStorage. priv.recovered_job_object = localOrCookieStorage.
getItem('jio/jobobject/'+ jio_id_array[k]); getItem('jio/job_object/'+ jio_id_array[k]);
// remove ex job object // remove ex job object
localOrCookieStorage.deleteItem( localOrCookieStorage.deleteItem(
'jio/jobobject/'+ jio_id_array[k]); 'jio/job_object/'+ jio_id_array[k]);
jio_id_array_changed = true; jio_id_array_changed = true;
} else { } else {
new_jio_id_array.push (jio_id_array[k]); new_jio_id_array.push (jio_id_array[k]);
...@@ -351,8 +351,8 @@ var JIO = ...@@ -351,8 +351,8 @@ var JIO =
// It also clean fail or done jobs. // It also clean fail or done jobs.
// job = the job object // job = the job object
var newone = true, elim_array = [], wait_array = [], var new_one = true, elim_array = [], wait_array = [],
remove_array = [], basestorage = null, id = 'id'; remove_array = [], base_storage = null, id = 'id';
//// browsing current jobs //// browsing current jobs
for (id in priv.job_object) { for (id in priv.job_object) {
...@@ -370,10 +370,10 @@ var JIO = ...@@ -370,10 +370,10 @@ var JIO =
} }
if (jio_global_obj.job_managing_method.canReplace( if (jio_global_obj.job_managing_method.canReplace(
priv.job_object[id],job)) { priv.job_object[id],job)) {
basestorage = newBaseStorage( base_storage = newBaseStorage(
{'queue':that,'job':priv.job_object[id]}); {'queue':that,'job':priv.job_object[id]});
basestorage.replace(job); base_storage.replace(job);
newone = false; new_one = false;
break; break;
} }
if (jio_global_obj.job_managing_method.cannotAccept( if (jio_global_obj.job_managing_method.cannotAccept(
...@@ -392,21 +392,21 @@ var JIO = ...@@ -392,21 +392,21 @@ var JIO =
} }
//// end browsing current jobs //// end browsing current jobs
if (newone) { if (new_one) {
// if it is a new job, we can eliminate deprecated jobs and // if it is a new job, we can eliminate deprecated jobs and
// set this job dependencies. // set this job dependencies.
for (id = 0; id < elim_array.length; id += 1) { for (id = 0; id < elim_array.length; id += 1) {
basestorage = newBaseStorage( base_storage = newBaseStorage(
{'queue':that, {'queue':that,
'job':priv.job_object[elim_array[id]]}); 'job':priv.job_object[elim_array[id]]});
basestorage.eliminate(); base_storage.eliminate();
} }
if (wait_array.length > 0) { if (wait_array.length > 0) {
job.status = 'wait'; job.status = 'wait';
job.waitingFor = {'jobIdArray':wait_array}; job.waiting_for = {'job_id_array':wait_array};
for (id = 0; id < wait_array.length; id += 1) { for (id = 0; id < wait_array.length; id += 1) {
if (priv.job_object[wait_array[id]]) { if (priv.job_object[wait_array[id]]) {
priv.job_object[wait_array[id]].maxtries = 1; priv.job_object[wait_array[id]].max_tries = 1;
} }
} }
} }
...@@ -483,24 +483,24 @@ var JIO = ...@@ -483,24 +483,24 @@ var JIO =
} else if (priv.job_object[i].status === 'wait') { } else if (priv.job_object[i].status === 'wait') {
ok = true; ok = true;
// if status wait // if status wait
if (priv.job_object[i].waitingFor.jobIdArray) { if (priv.job_object[i].waiting_for.job_id_array) {
// wait job // wait job
// browsing job id array // browsing job id array
for (j = 0; for (j = 0;
j < priv.job_object[i]. j < priv.job_object[i].
waitingFor.jobIdArray.length; waiting_for.job_id_array.length;
j += 1) { j += 1) {
if (priv.job_object[priv.job_object[i]. if (priv.job_object[priv.job_object[i].
waitingFor.jobIdArray[j]]) { waiting_for.job_id_array[j]]) {
// if a job is still exist, don't invoke // if a job is still exist, don't invoke
ok = false; ok = false;
break; break;
} }
} }
} }
if (priv.job_object[i].waitingFor.time) { if (priv.job_object[i].waiting_for.time) {
// wait time // wait time
if (priv.job_object[i].waitingFor.time > Date.now()) { if (priv.job_object[i].waiting_for.time > Date.now()) {
// it is not time to restore the job! // it is not time to restore the job!
ok = false; ok = false;
} }
...@@ -519,7 +519,7 @@ var JIO = ...@@ -519,7 +519,7 @@ var JIO =
that.invoke = function (job) { that.invoke = function (job) {
// Do a job invoking the good method in the good storage. // Do a job invoking the good method in the good storage.
var basestorage; var base_storage;
//// analysing job method //// analysing job method
// if the method does not exist, do nothing // if the method does not exist, do nothing
...@@ -532,15 +532,15 @@ var JIO = ...@@ -532,15 +532,15 @@ var JIO =
return (testjob.method === job.method && return (testjob.method === job.method &&
testjob.method === 'initial'); testjob.method === 'initial');
})) { })) {
job.status = 'ongoing'; job.status = 'on_going';
priv.publisher.publish(jio_const_obj.job_method_object[ priv.publisher.publish(jio_const_obj.job_method_object[
job.method]['start_'+job.method]); job.method]['start_'+job.method]);
} else { } else {
job.status = 'ongoing'; job.status = 'on_going';
} }
// Create a storage object and use it to save,load,...! // Create a storage object and use it to save,load,...!
basestorage = newBaseStorage({'queue':this,'job':job}); base_storage = newBaseStorage({'queue':this,'job':job});
basestorage.execute(); base_storage.execute();
//// end method analyse //// end method analyse
}; };
...@@ -561,7 +561,7 @@ var JIO = ...@@ -561,7 +561,7 @@ var JIO =
if (!that.isThereJobsWhere(function(testjob){ if (!that.isThereJobsWhere(function(testjob){
return (testjob.method === job.method && return (testjob.method === job.method &&
// testjob.status === 'wait' || // TODO ? // testjob.status === 'wait' || // TODO ?
testjob.status === 'ongoing' || testjob.status === 'on_going' ||
testjob.status === 'initial'); testjob.status === 'initial');
})) { })) {
priv.publisher.publish( priv.publisher.publish(
...@@ -709,7 +709,7 @@ var JIO = ...@@ -709,7 +709,7 @@ var JIO =
priv.res.message = 'Unable to check name availability.'; priv.res.message = 'Unable to check name availability.';
}; };
priv.done_checkNameAvailability = function ( isavailable ) { priv.done_checkNameAvailability = function ( isavailable ) {
priv.res.message = priv.job.userName + ' is ' + priv.res.message = priv.job.user_name + ' is ' +
(isavailable?'':'not ') + 'available.'; (isavailable?'':'not ') + 'available.';
priv.res.return_value = isavailable; priv.res.return_value = isavailable;
}; };
...@@ -720,10 +720,10 @@ var JIO = ...@@ -720,10 +720,10 @@ var JIO =
priv.res.message = 'Document loaded.'; priv.res.message = 'Document loaded.';
priv.res.return_value = returneddocument; priv.res.return_value = returneddocument;
// transform date into ms // transform date into ms
priv.res.return_value.lastModified = priv.res.return_value.last_modified =
new Date(priv.res.return_value.lastModified).getTime(); new Date(priv.res.return_value.last_modified).getTime();
priv.res.return_value.creationDate = priv.res.return_value.creation_date =
new Date(priv.res.return_value.creationDate).getTime(); new Date(priv.res.return_value.creation_date).getTime();
}; };
priv.fail_saveDocument = function () { priv.fail_saveDocument = function () {
priv.res.message = 'Unable to save document.'; priv.res.message = 'Unable to save document.';
...@@ -741,14 +741,14 @@ var JIO = ...@@ -741,14 +741,14 @@ var JIO =
for (i = 0; i < priv.res.return_value.length; i += 1) { for (i = 0; i < priv.res.return_value.length; i += 1) {
// transform current date format into ms since 1/1/1970 // transform current date format into ms since 1/1/1970
// useful for easy comparison // useful for easy comparison
if (typeof priv.res.return_value[i].lastModified !== 'number') { if (typeof priv.res.return_value[i].last_modified !== 'number') {
priv.res.return_value[i].lastModified = priv.res.return_value[i].last_modified =
new Date(priv.res.return_value[i].lastModified). new Date(priv.res.return_value[i].last_modified).
getTime(); getTime();
} }
if (typeof priv.res.return_value[i].creationDate !== 'number') { if (typeof priv.res.return_value[i].creation_date !== 'number') {
priv.res.return_value[i].creationDate = priv.res.return_value[i].creation_date =
new Date(priv.res.return_value[i].creationDate). new Date(priv.res.return_value[i].creation_date).
getTime(); getTime();
} }
} }
...@@ -786,7 +786,7 @@ var JIO = ...@@ -786,7 +786,7 @@ var JIO =
time = jio_global_obj.max_wait_time; time = jio_global_obj.max_wait_time;
} }
priv.job.status = 'wait'; priv.job.status = 'wait';
priv.job.waitingFor = {'time':Date.now() + time}; priv.job.waiting_for = {'time':Date.now() + time};
}; };
//// end Private Methods //// end Private Methods
...@@ -795,43 +795,43 @@ var JIO = ...@@ -795,43 +795,43 @@ var JIO =
return $.extend(true,{},priv.job); return $.extend(true,{},priv.job);
}; };
that.getUserName = function () { that.getUserName = function () {
return priv.job.userName || ''; return priv.job.user_name || '';
}; };
that.getApplicantID = function () { that.getApplicantID = function () {
return priv.job.applicant.ID || ''; return priv.job.applicant.ID || '';
}; };
that.getStorageUserName = function () { that.getStorageUserName = function () {
return priv.job.storage.userName || ''; return priv.job.storage.user_name || '';
}; };
that.getStoragePassword = function () { that.getStoragePassword = function () {
return priv.job.storage.password || ''; return priv.job.storage.password || '';
}; };
that.getStorageLocation = function () { that.getStorageURL = function () {
return priv.job.storage.location || ''; return priv.job.storage.url || '';
}; };
that.getSecondStorage = function () { that.getSecondStorage = function () {
return priv.job.storage.storage || {}; return priv.job.storage.storage || {};
}; };
that.getStorageArray = function () { that.getStorageArray = function () {
return priv.job.storage.storageArray || []; return priv.job.storage.storage_array || [];
}; };
that.getFileName = function () { that.getFileName = function () {
return priv.job.fileName || ''; return priv.job.name || '';
}; };
that.getFileContent = function () { that.getFileContent = function () {
return priv.job.fileContent || ''; return priv.job.content || '';
}; };
that.cloneOptionObject = function () { that.cloneOptionObject = function () {
return $.extend(true,{},priv.job.options); return $.extend(true,{},priv.job.options);
}; };
that.getMaxTries = function () { that.getMaxTries = function () {
return priv.job.maxtries; return priv.job.max_tries;
}; };
that.getTries = function () { that.getTries = function () {
return priv.job.tries || 0; return priv.job.tries || 0;
}; };
that.setMaxTries = function (maxtries) { that.setMaxTries = function (max_tries) {
priv.job.maxtries = maxtries; priv.job.max_tries = max_tries;
}; };
//// end Getters Setters //// end Getters Setters
...@@ -842,7 +842,7 @@ var JIO = ...@@ -842,7 +842,7 @@ var JIO =
that.eliminate = function () { that.eliminate = function () {
// Stop and remove a job ! // Stop and remove a job !
priv.job.maxtries = 1; priv.job.max_tries = 1;
priv.job.tries = 1; priv.job.tries = 1;
that.fail('Job Stopped!',0); that.fail('Job Stopped!',0);
}; };
...@@ -877,8 +877,8 @@ var JIO = ...@@ -877,8 +877,8 @@ var JIO =
priv.res.error.array = priv.res.error.array || []; priv.res.error.array = priv.res.error.array || [];
priv.res.error.message = priv.res.error.message || ''; priv.res.error.message = priv.res.error.message || '';
// retry ? // retry ?
if (!priv.job.maxtries || if (!priv.job.max_tries ||
priv.job.tries < priv.job.maxtries) { priv.job.tries < priv.job.max_tries) {
priv.retryLater(); priv.retryLater();
} else { } else {
priv.job.status = 'fail'; priv.job.status = 'fail';
...@@ -1133,7 +1133,7 @@ var JIO = ...@@ -1133,7 +1133,7 @@ var JIO =
// - true if the job was added or replaced // - true if the job was added or replaced
// example : // example :
// jio.checkNameAvailability({'userName':'myName','callback': // jio.checkNameAvailability({'user_name':'myName','callback':
// function (result) { // function (result) {
// if (result.status === 'done') { // if (result.status === 'done') {
// if (result.return_value === true) { // available // if (result.return_value === true) { // available
...@@ -1142,14 +1142,14 @@ var JIO = ...@@ -1142,14 +1142,14 @@ var JIO =
// }}); // }});
var settings = $.extend (true,{ var settings = $.extend (true,{
'userName': priv.storage.userName, 'user_name': priv.storage.user_name,
'storage': priv.storage, 'storage': priv.storage,
'applicant': priv.applicant, 'applicant': priv.applicant,
'method': 'checkNameAvailability', 'method': 'checkNameAvailability',
'callback': function () {} 'callback': function () {}
},options); },options);
// check dependencies // check dependencies
if (that.isReady() && settings.userName && if (that.isReady() && settings.user_name &&
settings.storage && settings.applicant) { settings.storage && settings.applicant) {
return priv.queue.createJob ( settings ); return priv.queue.createJob ( settings );
} }
...@@ -1168,7 +1168,7 @@ var JIO = ...@@ -1168,7 +1168,7 @@ var JIO =
// - false if the job was not added // - false if the job was not added
// - true if the job was added or replaced // - true if the job was added or replaced
// jio.saveDocument({'fileName':'file','fileContent':'content', // jio.saveDocument({'name':'file','content':'content',
// 'callback': function (result) { // 'callback': function (result) {
// if (result.status === 'done') { // Saved // if (result.status === 'done') { // Saved
// } else { } // Error // } else { } // Error
...@@ -1177,12 +1177,12 @@ var JIO = ...@@ -1177,12 +1177,12 @@ var JIO =
var settings = $.extend(true,{ var settings = $.extend(true,{
'storage': priv.storage, 'storage': priv.storage,
'applicant': priv.applicant, 'applicant': priv.applicant,
'fileContent': '', 'content': '',
'method':'saveDocument', 'method':'saveDocument',
'callback': function () {} 'callback': function () {}
},options); },options);
// check dependencies // check dependencies
if (that.isReady() && settings.fileName && if (that.isReady() && settings.name &&
settings.storage && settings.applicant) { settings.storage && settings.applicant) {
return priv.queue.createJob ( settings ); return priv.queue.createJob ( settings );
} }
...@@ -1192,7 +1192,7 @@ var JIO = ...@@ -1192,7 +1192,7 @@ var JIO =
that.loadDocument = function ( options ) { that.loadDocument = function ( options ) {
// Load a document in the storage set in [options] // Load a document in the storage set in [options]
// or in the storage set at init. At the end of the job, // or in the storage set at init. At the end of the job,
// 'job_done' will be sent with this job and its 'fileContent' // 'job_done' will be sent with this job and its 'content'
// return value. // return value.
// options.storage : the storage where to load (optional) // options.storage : the storage where to load (optional)
// options.applicant : the applicant (optional) // options.applicant : the applicant (optional)
...@@ -1202,15 +1202,15 @@ var JIO = ...@@ -1202,15 +1202,15 @@ var JIO =
// - false if the job was not added // - false if the job was not added
// - true if the job was added or replaced // - true if the job was added or replaced
// jio.loadDocument({'fileName':'file','callback': // jio.loadDocument({'name':'file','callback':
// function (result) { // function (result) {
// if (result.status === 'done') { // Loaded // if (result.status === 'done') { // Loaded
// } else { } // Error // } else { } // Error
// }}); // }});
// result.return_value is a document object that looks like { // result.return_value is a document object that looks like {
// fileName:'string',fileContent:'string', // name:'string',content:'string',
// creationDate:123,lastModified:456 } // creation_date:123,last_modified:456 }
var settings = $.extend (true,{ var settings = $.extend (true,{
'storage': priv.storage, 'storage': priv.storage,
...@@ -1219,7 +1219,7 @@ var JIO = ...@@ -1219,7 +1219,7 @@ var JIO =
'callback': function(){} 'callback': function(){}
},options); },options);
// check dependencies // check dependencies
if (that.isReady() && settings.fileName && if (that.isReady() && settings.name &&
settings.storage && settings.applicant) { settings.storage && settings.applicant) {
return priv.queue.createJob ( settings ); return priv.queue.createJob ( settings );
} }
...@@ -1270,7 +1270,7 @@ var JIO = ...@@ -1270,7 +1270,7 @@ var JIO =
// - false if the job was not added // - false if the job was not added
// - true if the job was added or replaced // - true if the job was added or replaced
// jio.removeDocument({'fileName':'file','callback': // jio.removeDocument({'name':'file','callback':
// function (result) { // function (result) {
// if(result.status === 'done') { // Removed // if(result.status === 'done') { // Removed
// } else { } // Not Removed // } else { } // Not Removed
...@@ -1282,7 +1282,7 @@ var JIO = ...@@ -1282,7 +1282,7 @@ var JIO =
'method':'removeDocument', 'method':'removeDocument',
'callback':function (){} 'callback':function (){}
},options); },options);
if (that.isReady() && settings.fileName && if (that.isReady() && settings.name &&
settings.storage && settings.applicant ) { settings.storage && settings.applicant ) {
return priv.queue.createJob ( settings ); return priv.queue.createJob ( settings );
} }
...@@ -1338,7 +1338,7 @@ var JIO = ...@@ -1338,7 +1338,7 @@ var JIO =
var that = {}; var that = {};
// Jio creator object // Jio creator object
// this object permit to create jio object // this object permit to create jio object
that.createNew = function ( storage, applicant, options ) { that.newJio = function ( storage, applicant, options ) {
// Return a new instance of JIO // Return a new instance of JIO
// storage: the storage object or json string // storage: the storage object or json string
// applicant: the applicant object or json string // applicant: the applicant object or json string
...@@ -1385,10 +1385,10 @@ var JIO = ...@@ -1385,10 +1385,10 @@ var JIO =
}; };
if (window.requirejs) { if (window.requirejs) {
define ('JIO',['LocalOrCookieStorage','jQuery'],jio_loader_function); define ('JIO',['LocalOrCookieStorage','jQuery'],jioLoaderFunction);
return undefined; return undefined;
} else { } else {
return jio_loader_function ( LocalOrCookieStorage, jQuery ); return jioLoaderFunction ( LocalOrCookieStorage, jQuery );
} }
}()); }());
/*! JIO - v0.1.0 - 2012-06-01 /*! JIO - v0.1.0 - 2012-06-05
* Copyright (c) 2012 Nexedi; Licensed */ * Copyright (c) 2012 Nexedi; Licensed */
var JIO=function(){var a=function(a,b){var c={job_method_object:{checkNameAvailability:{},saveDocument:{},loadDocument:{},getDocumentList:{},removeDocument:{}}},d={job_managing_method:{canSelect:function(a,b){return JSON.stringify(a.storage)===JSON.stringify(b.storage)&&JSON.stringify(a.applicant)===JSON.stringify(b.applicant)&&a.fileName===b.fileName?!0:!1},canRemoveFailOrDone:function(a,b){return a.status==="fail"||a.status==="done"?!0:!1},canEliminate:function(a,b){return a.status!=="ongoing"&&(a.method==="removeDocument"&&b.method==="saveDocument"||a.method==="saveDocument"&&b.method==="removeDocument")?!0:!1},canReplace:function(a,b){return a.status!=="ongoing"&&a.method===b.method&&a.date<b.date?!0:!1},cannotAccept:function(a,b){if(a.status!=="ongoing"){if(a.method==="removeDocument"&&b.method==="loadDocument")return!0}else{if(a.method===b.method==="loadDocument")return!0;if(a.method==="removeDocument"&&(b.method==="loadDocument"||b.method==="removeDocument"))return!0;if(a.method===b.method==="saveDocument"&&a.fileContent===b.fileContent)return!0;if(a.method===b.method==="getDocumentList"||a.method===b.method==="checkNameAvailability")return!0}return!1},mustWait:function(a,b){return a.method==="getDocumentList"||a.method==="checkNameAvailability"||b.method==="getDocumentList"||b.method==="checkNameAvailability"?!1:!0}},queue_id:1,storage_type_object:{},max_wait_time:1e4},e,f,g,h,i,j,k,l;return e=function(a,c){var d={},e={},f={},g,h;return e.eventAction=function(a){return h=a&&f[a],h||(g=b.Callbacks(),h={publish:g.fire,subscribe:g.add,unsubscribe:g.remove},a&&(f[a]=h)),h},d.publish=function(a,b){e.eventAction(a).publish(b)},d.subscribe=function(a,b){return e.eventAction(a).subscribe(b),b},d.unsubscribe=function(a,b){e.eventAction(a).unsubscribe(b)},d},f=function(a,c){var d=b.extend(!0,{},a);return d.id=0,d.status="initial",d.date=Date.now(),d},g=function(e,g){var h={},i={},k="jio/idarray";return h.init=function(b){var c,d=function(){},f;i.use_local_storage&&(f=a.getItem(k)||[],e.publisher&&(i.publisher=e.publisher),i.jio_id=b.jio_id,i.job_object_name="jio/jobobject/"+i.jio_id,f.push(i.jio_id),a.setItem(k,f)),i.job_object={},h.copyJobQueueToLocalStorage();for(c in i.recovered_job_object)i.recovered_job_object[c].callback=d,h.addJob(i.recovered_job_object[c])},h.close=function(){JSON.stringify(i.job_object)==="{}"&&a.deleteItem(i.job_object_name)},h.getNewQueueID=function(){var b=null,c=0,e=a.getItem(k)||[];for(b=0;b<e.length;b+=1)e[b]>=d.queue_id&&(d.queue_id=e[b]+1);return c=d.queue_id,d.queue_id++,c},h.recoverOlderJobObject=function(){var b=null,c=[],d=!1,e;if(i.use_local_storage){e=a.getItem(k)||[];for(b=0;b<e.length;b+=1)a.getItem("jio/id/"+e[b])<Date.now()-1e4?(a.deleteItem("jio/id/"+e[b]),i.recovered_job_object=a.getItem("jio/jobobject/"+e[b]),a.deleteItem("jio/jobobject/"+e[b]),d=!0):c.push(e[b]);d&&a.setItem(k,c)}},h.isThereJobsWhere=function(a){var b="id";if(!a)return!0;for(b in i.job_object)if(a(i.job_object[b]))return!0;return!1},h.copyJobQueueToLocalStorage=function(){return i.use_local_storage?a.setItem(i.job_object_name,i.job_object):!1},h.createJob=function(a){return h.addJob(f(a))},h.addJob=function(a){var b=!0,c=[],e=[],f=[],g=null,k="id";for(k in i.job_object){if(d.job_managing_method.canRemoveFailOrDone(i.job_object[k],a)){f.push(k);continue}if(d.job_managing_method.canSelect(i.job_object[k],a)){if(d.job_managing_method.canEliminate(i.job_object[k],a)){c.push(k);continue}if(d.job_managing_method.canReplace(i.job_object[k],a)){g=j({queue:h,job:i.job_object[k]}),g.replace(a),b=!1;break}if(d.job_managing_method.cannotAccept(i.job_object[k],a))return!1;if(d.job_managing_method.mustWait(i.job_object[k],a)){e.push(k);continue}}}if(b){for(k=0;k<c.length;k+=1)g=j({queue:h,job:i.job_object[c[k]]}),g.eliminate();if(e.length>0){a.status="wait",a.waitingFor={jobIdArray:e};for(k=0;k<e.length;k+=1)i.job_object[e[k]]&&(i.job_object[e[k]].maxtries=1)}for(k=0;k<f.length;k+=1)h.removeJob(i.job_object[f[k]]);a.id=i.job_id,a.tries=0,i.job_id++,i.job_object[a.id]=a}return h.copyJobQueueToLocalStorage(),!0},h.removeJob=function(a){var c=b.extend({where:function(a){return!0}},a),d,e=!1,f="key";if(c.job)i.job_object[c.job.id]&&c.where(i.job_object[c.job.id])&&(delete i.job_object[c.job.id],e=!0);else for(f in i.job_object)c.where(i.job_object[f])&&(delete i.job_object[f],e=!0);e||console.error("No jobs was found, when trying to remove some."),h.copyJobQueueToLocalStorage()},h.resetAll=function(){var a="id";for(a in i.job_object)i.job_object[a].status="initial";h.copyJobQueueToLocalStorage()},h.invokeAll=function(){var a="id",b,c;for(a in i.job_object){c=!1;if(i.job_object[a].status==="initial")h.invoke(i.job_object[a]);else if(i.job_object[a].status==="wait"){c=!0;if(i.job_object[a].waitingFor.jobIdArray)for(b=0;b<i.job_object[a].waitingFor.jobIdArray.length;b+=1)if(i.job_object[i.job_object[a].waitingFor.jobIdArray[b]]){c=!1;break}i.job_object[a].waitingFor.time&&i.job_object[a].waitingFor.time>Date.now()&&(c=!1),c&&h.invoke(i.job_object[a])}}this.copyJobQueueToLocalStorage()},h.invoke=function(a){var b;if(!c.job_method_object[a.method])return!1;h.isThereJobsWhere(function(b){return b.method===a.method&&b.method==="initial"})?a.status="ongoing":(a.status="ongoing",i.publisher.publish(c.job_method_object[a.method]["start_"+a.method])),b=j({queue:this,job:a}),b.execute()},h.ended=function(a){var d=b.extend(!0,{},a);h.removeJob({job:d});if(!c.job_method_object[d.method])return!1;if(!h.isThereJobsWhere(function(a){return a.method===d.method&&a.status==="ongoing"||a.status==="initial"})){i.publisher.publish(c.job_method_object[d.method]["stop_"+d.method]);return}},h.clean=function(){h.removeJob(undefined,{where:function(a){return a.status==="fail"}})},i.use_local_storage=e.options.use_local_storage,i.publisher=e.publisher,i.job_id=1,i.jio_id=0,i.job_object_name="",i.job_object={},i.recovered_job_object={},h},h=function(a,b){var c={},d={};return d.interval=200,d.id=null,d.queue=a.queue,c.setIntervalDelay=function(a){d.interval=a},c.start=function(){return d.id?!1:(d.id=setInterval(function(){d.queue.recoverOlderJobObject(),d.queue.invokeAll()},d.interval),!0)},c.stop=function(){return d.id?(clearInterval(d.id),d.id=null,!0):!1},c},i=function(){var b={},c={};return c.interval=400,c.id=null,b.start=function(a){return c.id?!1:(b.touch(a),c.id=setInterval(function(){b.touch(a)},c.interval),!0)},b.stop=function(){return c.id?(clearInterval(c.id),c.id=null,!0):!1},b.touch=function(b){a.setItem("jio/id/"+b,Date.now())},b},j=function(a){var c={},e={};return e.job=a.job,e.callback=a.job.callback,e.queue=a.queue,e.res={status:"done",message:""},e.sorted=!1,e.limited=!1,e.research_done=!1,e.fail_checkNameAvailability=function(){e.res.message="Unable to check name availability."},e.done_checkNameAvailability=function(a){e.res.message=e.job.userName+" is "+(a?"":"not ")+"available.",e.res.return_value=a},e.fail_loadDocument=function(){e.res.message="Unable to load document."},e.done_loadDocument=function(a){e.res.message="Document loaded.",e.res.return_value=a,e.res.return_value.lastModified=(new Date(e.res.return_value.lastModified)).getTime(),e.res.return_value.creationDate=(new Date(e.res.return_value.creationDate)).getTime()},e.fail_saveDocument=function(){e.res.message="Unable to save document."},e.done_saveDocument=function(){e.res.message="Document saved."},e.fail_getDocumentList=function(){e.res.message="Unable to retrieve document list."},e.done_getDocumentList=function(a){var b;e.res.message="Document list received.",e.res.return_value=a;for(b=0;b<e.res.return_value.length;b+=1)typeof e.res.return_value[b].lastModified!="number"&&(e.res.return_value[b].lastModified=(new Date(e.res.return_value[b].lastModified)).getTime()),typeof e.res.return_value[b].creationDate!="number"&&(e.res.return_value[b].creationDate=(new Date(e.res.return_value[b].creationDate)).getTime());!e.sorted&&typeof e.job.sort!="undefined"&&c.sortDocumentArray(e.res.return_value),!e.limited&&typeof e.job.limit!="undefined"&&typeof e.job.limit.begin!="undefined"&&typeof e.job.limit.end!="undefined"&&(e.res.return_value=c.limitDocumentArray(e.res.return_value)),!e.research_done&&typeof e.job.search!="undefined"&&(e.res.return_value=c.searchDocumentArray(e.res.return_value))},e.fail_removeDocument=function(){e.res.message="Unable to removed document."},e.done_removeDocument=function(){e.res.message="Document removed."},e.retryLater=function(){var a=e.job.tries*e.job.tries*1e3;a>d.max_wait_time&&(a=d.max_wait_time),e.job.status="wait",e.job.waitingFor={time:Date.now()+a}},c.cloneJob=function(){return b.extend(!0,{},e.job)},c.getUserName=function(){return e.job.userName||""},c.getApplicantID=function(){return e.job.applicant.ID||""},c.getStorageUserName=function(){return e.job.storage.userName||""},c.getStoragePassword=function(){return e.job.storage.password||""},c.getStorageLocation=function(){return e.job.storage.location||""},c.getSecondStorage=function(){return e.job.storage.storage||{}},c.getStorageArray=function(){return e.job.storage.storageArray||[]},c.getFileName=function(){return e.job.fileName||""},c.getFileContent=function(){return e.job.fileContent||""},c.cloneOptionObject=function(){return b.extend(!0,{},e.job.options)},c.getMaxTries=function(){return e.job.maxtries},c.getTries=function(){return e.job.tries||0},c.setMaxTries=function(a){e.job.maxtries=a},c.addJob=function(a){return e.queue.createJob(a)},c.eliminate=function(){e.job.maxtries=1,e.job.tries=1,c.fail("Job Stopped!",0)},c.replace=function(a){e.job.tries=0,e.job.date=a.date,e.job.callback=a.callback,e.res.status="fail",e.res.message="Job Stopped!",e.res.error={},e.res.error.status=0,e.res.error.statusText="Replaced",e.res.error.message="The job was replaced by a newer one.",e["fail_"+e.job.method](),e.callback(e.res)},c.fail=function(a){e.res.status="fail",e.res.error=a,e.res.error.status=e.res.error.status||0,e.res.error.statusText=e.res.error.statusText||"Unknown Error",e.res.error.array=e.res.error.array||[],e.res.error.message=e.res.error.message||"",!e.job.maxtries||e.job.tries<e.job.maxtries?e.retryLater():(e.job.status="fail",e["fail_"+e.job.method](),e.queue.ended(e.job),e.callback(e.res))},c.done=function(a){e.job.status="done",e["done_"+e.job.method](a),e.queue.ended(e.job),e.callback(e.res)},c.execute=function(){return e.job.tries=c.getTries()+1,d.storage_type_object[e.job.storage.type]?d.storage_type_object[e.job.storage.type]({job:e.job,queue:e.queue})[e.job.method]():null},c.checkNameAvailability=function(){c.fail({status:0,statusText:"Undefined Method",message:"This method must be redefined!"})},c.loadDocument=function(){c.fail({status:0,statusText:"Undefined Method",message:"This method must be redefined!"})},c.saveDocument=function(){c.fail({status:0,statusText:"Undefined Method",message:"This method must be redefined!"})},c.getDocumentList=function(){c.fail({status:0,statusText:"Undefined Method",message:"This method must be redefined!"})},c.removeDocument=function(){c.fail({status:0,statusText:"Undefined Method",message:"This method must be redefined!"})},c.sortDocumentArray=function(a){a.sort(function(a,b){var c,d;for(c in e.job.sort){var f=e.job.sort[c]==="descending"?-1:1;if(a[c]===b[c])continue;return a[c]>b[c]?f:-f}return 0}),c.sortDone()},c.sortDone=function(){e.sorted=!0},c.limitDocumentArray=function(a){return c.limitDone(),a.slice(e.job.limit.begin,e.job.limit.end)},c.limitDone=function(){e.limited=!0},c.searchDocumentArray=function(a){var b,d,f=[];for(b=0;b<a.length;b+=1)for(d in e.job.search){if(typeof a[b][d]=="undefined")continue;if(a[b][d].search(e.job.search[d])>-1){f.push(a[b]);break}}return c.researchDone(),f},c.researchDone=function(){e.research_done=!0},c},k=function(a,c){var f={},j={};j.wrongParametersError=function(a){var b="Method: "+a.method+", One or some parameters are undefined.";return console.error(b),a.callback({status:"fail",error:{status:0,statusText:"Undefined Parameter",message:b}}),null},f.getID=function(){return j.id},f.start=function(){return j.id!==0?!1:(j.id=j.queue.getNewQueueID(),j.queue.init({jio_id:j.id}),j.updater&&j.updater.start(j.id),j.listener.start(),j.ready=!0,f.isReady())},f.stop=function(){return j.queue.close(),j.listener.stop(),j.updater&&j.updater.stop(),j.ready=!1,j.id=0,!0},f.kill=function(){return j.queue.close(),j.listener.stop(),j.updater&&j.updater.stop(),j.ready=!1,!0},f.isReady=function(){return j.ready},f.publish=function(a,b){if(!f.isReady())return;return j.pubsub.publish(a,b)},f.subscribe=function(a,b){return j.pubsub.subscribe(a,b)},f.unsubscribe=function(a,b){return j.pubsub.unsubscribe(a,b)},f.checkNameAvailability=function(a){var c=b.extend(!0,{userName:j.storage.userName,storage:j.storage,applicant:j.applicant,method:"checkNameAvailability",callback:function(){}},a);return f.isReady()&&c.userName&&c.storage&&c.applicant?j.queue.createJob(c):j.wrongParametersError(c)},f.saveDocument=function(a){var c=b.extend(!0,{storage:j.storage,applicant:j.applicant,fileContent:"",method:"saveDocument",callback:function(){}},a);return f.isReady()&&c.fileName&&c.storage&&c.applicant?j.queue.createJob(c):j.wrongParametersError(c)},f.loadDocument=function(a){var c=b.extend(!0,{storage:j.storage,applicant:j.applicant,method:"loadDocument",callback:function(){}},a);return f.isReady()&&c.fileName&&c.storage&&c.applicant?j.queue.createJob(c):j.wrongParametersError(c)},f.getDocumentList=function(a){var c=b.extend(!0,{storage:j.storage,applicant:j.applicant,method:"getDocumentList",callback:function(){}},a);return f.isReady()&&c.storage&&c.applicant?j.queue.createJob(c):j.wrongParametersError(c)},f.removeDocument=function(a){var c=b.extend(!0,{storage:j.storage,applicant:j.applicant,method:"removeDocument",callback:function(){}},a);return f.isReady()&&c.fileName&&c.storage&&c.applicant?j.queue.createJob(c):j.wrongParametersError(c)};var k=b.extend(!0,{use_local_storage:!0},a.options);return typeof a.storage=="string"&&(a.storage=JSON.parse(a.storage)),typeof a.applicant=="string"&&(a.applicant=JSON.parse(a.applicant)),j.storage=a.storage,j.applicant=a.applicant,j.id=0,j.pubsub=e({options:k}),j.queue=g({publisher:j.pubsub,options:k}),j.listener=h({queue:j.queue,options:k}),j.ready=!1,k.use_local_storage?j.updater=i({options:k}):j.updater=null,j.storage&&!d.storage_type_object[j.storage.type]&&console.error('Unknown storage type "'+j.storage.type+'"'),f.start(),f},l=function(a,e){var f={};return f.createNew=function(a,c,d){var e=b.extend(!0,{use_local_storage:!0},d);return k({storage:a,applicant:c,options:e})},f.newBaseStorage=function(a,b){return j(a,b)},f.addStorageType=function(a,b){return a&&b?(d.storage_type_object[a]=b,!0):!1},f.getGlobalObject=function(){return d},f.getConstObject=function(){return b.extend(!0,{},c)},f},l()};return window.requirejs?(define("JIO",["LocalOrCookieStorage","jQuery"],a),undefined):a(LocalOrCookieStorage,jQuery)}(); var JIO=function(){var a=function(a,b){var c={job_method_object:{checkNameAvailability:{},saveDocument:{},loadDocument:{},getDocumentList:{},removeDocument:{}}},d={job_managing_method:{canSelect:function(a,b){return JSON.stringify(a.storage)===JSON.stringify(b.storage)&&JSON.stringify(a.applicant)===JSON.stringify(b.applicant)&&a.name===b.name?!0:!1},canRemoveFailOrDone:function(a,b){return a.status==="fail"||a.status==="done"?!0:!1},canEliminate:function(a,b){return a.status!=="on_going"&&(a.method==="removeDocument"&&b.method==="saveDocument"||a.method==="saveDocument"&&b.method==="removeDocument")?!0:!1},canReplace:function(a,b){return a.status!=="on_going"&&a.method===b.method&&a.date<b.date?!0:!1},cannotAccept:function(a,b){if(a.status!=="on_going"){if(a.method==="removeDocument"&&b.method==="loadDocument")return!0}else{if(a.method===b.method==="loadDocument")return!0;if(a.method==="removeDocument"&&(b.method==="loadDocument"||b.method==="removeDocument"))return!0;if(a.method===b.method==="saveDocument"&&a.content===b.content)return!0;if(a.method===b.method==="getDocumentList"||a.method===b.method==="checkNameAvailability")return!0}return!1},mustWait:function(a,b){return a.method==="getDocumentList"||a.method==="checkNameAvailability"||b.method==="getDocumentList"||b.method==="checkNameAvailability"?!1:!0}},queue_id:1,storage_type_object:{},max_wait_time:1e4},e,f,g,h,i,j,k,l;return e=function(a,c){var d={},e={},f={},g,h;return e.eventAction=function(a){return h=a&&f[a],h||(g=b.Callbacks(),h={publish:g.fire,subscribe:g.add,unsubscribe:g.remove},a&&(f[a]=h)),h},d.publish=function(a,b){e.eventAction(a).publish(b)},d.subscribe=function(a,b){return e.eventAction(a).subscribe(b),b},d.unsubscribe=function(a,b){e.eventAction(a).unsubscribe(b)},d},f=function(a,c){var d=b.extend(!0,{},a);return d.id=0,d.status="initial",d.date=Date.now(),d},g=function(e,g){var h={},i={},k="jio/id_array";return h.init=function(b){var c,d=function(){},f;i.use_local_storage&&(f=a.getItem(k)||[],e.publisher&&(i.publisher=e.publisher),i.jio_id=b.jio_id,i.job_object_name="jio/job_object/"+i.jio_id,f.push(i.jio_id),a.setItem(k,f)),i.job_object={},h.copyJobQueueToLocalStorage();for(c in i.recovered_job_object)i.recovered_job_object[c].callback=d,h.addJob(i.recovered_job_object[c])},h.close=function(){JSON.stringify(i.job_object)==="{}"&&a.deleteItem(i.job_object_name)},h.getNewQueueID=function(){var b=null,c=0,e=a.getItem(k)||[];for(b=0;b<e.length;b+=1)e[b]>=d.queue_id&&(d.queue_id=e[b]+1);return c=d.queue_id,d.queue_id++,c},h.recoverOlderJobObject=function(){var b=null,c=[],d=!1,e;if(i.use_local_storage){e=a.getItem(k)||[];for(b=0;b<e.length;b+=1)a.getItem("jio/id/"+e[b])<Date.now()-1e4?(a.deleteItem("jio/id/"+e[b]),i.recovered_job_object=a.getItem("jio/job_object/"+e[b]),a.deleteItem("jio/job_object/"+e[b]),d=!0):c.push(e[b]);d&&a.setItem(k,c)}},h.isThereJobsWhere=function(a){var b="id";if(!a)return!0;for(b in i.job_object)if(a(i.job_object[b]))return!0;return!1},h.copyJobQueueToLocalStorage=function(){return i.use_local_storage?a.setItem(i.job_object_name,i.job_object):!1},h.createJob=function(a){return h.addJob(f(a))},h.addJob=function(a){var b=!0,c=[],e=[],f=[],g=null,k="id";for(k in i.job_object){if(d.job_managing_method.canRemoveFailOrDone(i.job_object[k],a)){f.push(k);continue}if(d.job_managing_method.canSelect(i.job_object[k],a)){if(d.job_managing_method.canEliminate(i.job_object[k],a)){c.push(k);continue}if(d.job_managing_method.canReplace(i.job_object[k],a)){g=j({queue:h,job:i.job_object[k]}),g.replace(a),b=!1;break}if(d.job_managing_method.cannotAccept(i.job_object[k],a))return!1;if(d.job_managing_method.mustWait(i.job_object[k],a)){e.push(k);continue}}}if(b){for(k=0;k<c.length;k+=1)g=j({queue:h,job:i.job_object[c[k]]}),g.eliminate();if(e.length>0){a.status="wait",a.waiting_for={job_id_array:e};for(k=0;k<e.length;k+=1)i.job_object[e[k]]&&(i.job_object[e[k]].max_tries=1)}for(k=0;k<f.length;k+=1)h.removeJob(i.job_object[f[k]]);a.id=i.job_id,a.tries=0,i.job_id++,i.job_object[a.id]=a}return h.copyJobQueueToLocalStorage(),!0},h.removeJob=function(a){var c=b.extend({where:function(a){return!0}},a),d,e=!1,f="key";if(c.job)i.job_object[c.job.id]&&c.where(i.job_object[c.job.id])&&(delete i.job_object[c.job.id],e=!0);else for(f in i.job_object)c.where(i.job_object[f])&&(delete i.job_object[f],e=!0);e||console.error("No jobs was found, when trying to remove some."),h.copyJobQueueToLocalStorage()},h.resetAll=function(){var a="id";for(a in i.job_object)i.job_object[a].status="initial";h.copyJobQueueToLocalStorage()},h.invokeAll=function(){var a="id",b,c;for(a in i.job_object){c=!1;if(i.job_object[a].status==="initial")h.invoke(i.job_object[a]);else if(i.job_object[a].status==="wait"){c=!0;if(i.job_object[a].waiting_for.job_id_array)for(b=0;b<i.job_object[a].waiting_for.job_id_array.length;b+=1)if(i.job_object[i.job_object[a].waiting_for.job_id_array[b]]){c=!1;break}i.job_object[a].waiting_for.time&&i.job_object[a].waiting_for.time>Date.now()&&(c=!1),c&&h.invoke(i.job_object[a])}}this.copyJobQueueToLocalStorage()},h.invoke=function(a){var b;if(!c.job_method_object[a.method])return!1;h.isThereJobsWhere(function(b){return b.method===a.method&&b.method==="initial"})?a.status="on_going":(a.status="on_going",i.publisher.publish(c.job_method_object[a.method]["start_"+a.method])),b=j({queue:this,job:a}),b.execute()},h.ended=function(a){var d=b.extend(!0,{},a);h.removeJob({job:d});if(!c.job_method_object[d.method])return!1;if(!h.isThereJobsWhere(function(a){return a.method===d.method&&a.status==="on_going"||a.status==="initial"})){i.publisher.publish(c.job_method_object[d.method]["stop_"+d.method]);return}},h.clean=function(){h.removeJob(undefined,{where:function(a){return a.status==="fail"}})},i.use_local_storage=e.options.use_local_storage,i.publisher=e.publisher,i.job_id=1,i.jio_id=0,i.job_object_name="",i.job_object={},i.recovered_job_object={},h},h=function(a,b){var c={},d={};return d.interval=200,d.id=null,d.queue=a.queue,c.setIntervalDelay=function(a){d.interval=a},c.start=function(){return d.id?!1:(d.id=setInterval(function(){d.queue.recoverOlderJobObject(),d.queue.invokeAll()},d.interval),!0)},c.stop=function(){return d.id?(clearInterval(d.id),d.id=null,!0):!1},c},i=function(){var b={},c={};return c.interval=400,c.id=null,b.start=function(a){return c.id?!1:(b.touch(a),c.id=setInterval(function(){b.touch(a)},c.interval),!0)},b.stop=function(){return c.id?(clearInterval(c.id),c.id=null,!0):!1},b.touch=function(b){a.setItem("jio/id/"+b,Date.now())},b},j=function(a){var c={},e={};return e.job=a.job,e.callback=a.job.callback,e.queue=a.queue,e.res={status:"done",message:""},e.sorted=!1,e.limited=!1,e.research_done=!1,e.fail_checkNameAvailability=function(){e.res.message="Unable to check name availability."},e.done_checkNameAvailability=function(a){e.res.message=e.job.user_name+" is "+(a?"":"not ")+"available.",e.res.return_value=a},e.fail_loadDocument=function(){e.res.message="Unable to load document."},e.done_loadDocument=function(a){e.res.message="Document loaded.",e.res.return_value=a,e.res.return_value.last_modified=(new Date(e.res.return_value.last_modified)).getTime(),e.res.return_value.creation_date=(new Date(e.res.return_value.creation_date)).getTime()},e.fail_saveDocument=function(){e.res.message="Unable to save document."},e.done_saveDocument=function(){e.res.message="Document saved."},e.fail_getDocumentList=function(){e.res.message="Unable to retrieve document list."},e.done_getDocumentList=function(a){var b;e.res.message="Document list received.",e.res.return_value=a;for(b=0;b<e.res.return_value.length;b+=1)typeof e.res.return_value[b].last_modified!="number"&&(e.res.return_value[b].last_modified=(new Date(e.res.return_value[b].last_modified)).getTime()),typeof e.res.return_value[b].creation_date!="number"&&(e.res.return_value[b].creation_date=(new Date(e.res.return_value[b].creation_date)).getTime());!e.sorted&&typeof e.job.sort!="undefined"&&c.sortDocumentArray(e.res.return_value),!e.limited&&typeof e.job.limit!="undefined"&&typeof e.job.limit.begin!="undefined"&&typeof e.job.limit.end!="undefined"&&(e.res.return_value=c.limitDocumentArray(e.res.return_value)),!e.research_done&&typeof e.job.search!="undefined"&&(e.res.return_value=c.searchDocumentArray(e.res.return_value))},e.fail_removeDocument=function(){e.res.message="Unable to removed document."},e.done_removeDocument=function(){e.res.message="Document removed."},e.retryLater=function(){var a=e.job.tries*e.job.tries*1e3;a>d.max_wait_time&&(a=d.max_wait_time),e.job.status="wait",e.job.waiting_for={time:Date.now()+a}},c.cloneJob=function(){return b.extend(!0,{},e.job)},c.getUserName=function(){return e.job.user_name||""},c.getApplicantID=function(){return e.job.applicant.ID||""},c.getStorageUserName=function(){return e.job.storage.user_name||""},c.getStoragePassword=function(){return e.job.storage.password||""},c.getStorageURL=function(){return e.job.storage.url||""},c.getSecondStorage=function(){return e.job.storage.storage||{}},c.getStorageArray=function(){return e.job.storage.storage_array||[]},c.getFileName=function(){return e.job.name||""},c.getFileContent=function(){return e.job.content||""},c.cloneOptionObject=function(){return b.extend(!0,{},e.job.options)},c.getMaxTries=function(){return e.job.max_tries},c.getTries=function(){return e.job.tries||0},c.setMaxTries=function(a){e.job.max_tries=a},c.addJob=function(a){return e.queue.createJob(a)},c.eliminate=function(){e.job.max_tries=1,e.job.tries=1,c.fail("Job Stopped!",0)},c.replace=function(a){e.job.tries=0,e.job.date=a.date,e.job.callback=a.callback,e.res.status="fail",e.res.message="Job Stopped!",e.res.error={},e.res.error.status=0,e.res.error.statusText="Replaced",e.res.error.message="The job was replaced by a newer one.",e["fail_"+e.job.method](),e.callback(e.res)},c.fail=function(a){e.res.status="fail",e.res.error=a,e.res.error.status=e.res.error.status||0,e.res.error.statusText=e.res.error.statusText||"Unknown Error",e.res.error.array=e.res.error.array||[],e.res.error.message=e.res.error.message||"",!e.job.max_tries||e.job.tries<e.job.max_tries?e.retryLater():(e.job.status="fail",e["fail_"+e.job.method](),e.queue.ended(e.job),e.callback(e.res))},c.done=function(a){e.job.status="done",e["done_"+e.job.method](a),e.queue.ended(e.job),e.callback(e.res)},c.execute=function(){return e.job.tries=c.getTries()+1,d.storage_type_object[e.job.storage.type]?d.storage_type_object[e.job.storage.type]({job:e.job,queue:e.queue})[e.job.method]():null},c.checkNameAvailability=function(){c.fail({status:0,statusText:"Undefined Method",message:"This method must be redefined!"})},c.loadDocument=function(){c.fail({status:0,statusText:"Undefined Method",message:"This method must be redefined!"})},c.saveDocument=function(){c.fail({status:0,statusText:"Undefined Method",message:"This method must be redefined!"})},c.getDocumentList=function(){c.fail({status:0,statusText:"Undefined Method",message:"This method must be redefined!"})},c.removeDocument=function(){c.fail({status:0,statusText:"Undefined Method",message:"This method must be redefined!"})},c.sortDocumentArray=function(a){a.sort(function(a,b){var c,d;for(c in e.job.sort){var f=e.job.sort[c]==="descending"?-1:1;if(a[c]===b[c])continue;return a[c]>b[c]?f:-f}return 0}),c.sortDone()},c.sortDone=function(){e.sorted=!0},c.limitDocumentArray=function(a){return c.limitDone(),a.slice(e.job.limit.begin,e.job.limit.end)},c.limitDone=function(){e.limited=!0},c.searchDocumentArray=function(a){var b,d,f=[];for(b=0;b<a.length;b+=1)for(d in e.job.search){if(typeof a[b][d]=="undefined")continue;if(a[b][d].search(e.job.search[d])>-1){f.push(a[b]);break}}return c.researchDone(),f},c.researchDone=function(){e.research_done=!0},c},k=function(a,c){var f={},j={};j.wrongParametersError=function(a){var b="Method: "+a.method+", One or some parameters are undefined.";return console.error(b),a.callback({status:"fail",error:{status:0,statusText:"Undefined Parameter",message:b}}),null},f.getID=function(){return j.id},f.start=function(){return j.id!==0?!1:(j.id=j.queue.getNewQueueID(),j.queue.init({jio_id:j.id}),j.updater&&j.updater.start(j.id),j.listener.start(),j.ready=!0,f.isReady())},f.stop=function(){return j.queue.close(),j.listener.stop(),j.updater&&j.updater.stop(),j.ready=!1,j.id=0,!0},f.kill=function(){return j.queue.close(),j.listener.stop(),j.updater&&j.updater.stop(),j.ready=!1,!0},f.isReady=function(){return j.ready},f.publish=function(a,b){if(!f.isReady())return;return j.pubsub.publish(a,b)},f.subscribe=function(a,b){return j.pubsub.subscribe(a,b)},f.unsubscribe=function(a,b){return j.pubsub.unsubscribe(a,b)},f.checkNameAvailability=function(a){var c=b.extend(!0,{user_name:j.storage.user_name,storage:j.storage,applicant:j.applicant,method:"checkNameAvailability",callback:function(){}},a);return f.isReady()&&c.user_name&&c.storage&&c.applicant?j.queue.createJob(c):j.wrongParametersError(c)},f.saveDocument=function(a){var c=b.extend(!0,{storage:j.storage,applicant:j.applicant,content:"",method:"saveDocument",callback:function(){}},a);return f.isReady()&&c.name&&c.storage&&c.applicant?j.queue.createJob(c):j.wrongParametersError(c)},f.loadDocument=function(a){var c=b.extend(!0,{storage:j.storage,applicant:j.applicant,method:"loadDocument",callback:function(){}},a);return f.isReady()&&c.name&&c.storage&&c.applicant?j.queue.createJob(c):j.wrongParametersError(c)},f.getDocumentList=function(a){var c=b.extend(!0,{storage:j.storage,applicant:j.applicant,method:"getDocumentList",callback:function(){}},a);return f.isReady()&&c.storage&&c.applicant?j.queue.createJob(c):j.wrongParametersError(c)},f.removeDocument=function(a){var c=b.extend(!0,{storage:j.storage,applicant:j.applicant,method:"removeDocument",callback:function(){}},a);return f.isReady()&&c.name&&c.storage&&c.applicant?j.queue.createJob(c):j.wrongParametersError(c)};var k=b.extend(!0,{use_local_storage:!0},a.options);return typeof a.storage=="string"&&(a.storage=JSON.parse(a.storage)),typeof a.applicant=="string"&&(a.applicant=JSON.parse(a.applicant)),j.storage=a.storage,j.applicant=a.applicant,j.id=0,j.pubsub=e({options:k}),j.queue=g({publisher:j.pubsub,options:k}),j.listener=h({queue:j.queue,options:k}),j.ready=!1,k.use_local_storage?j.updater=i({options:k}):j.updater=null,j.storage&&!d.storage_type_object[j.storage.type]&&console.error('Unknown storage type "'+j.storage.type+'"'),f.start(),f},l=function(a,e){var f={};return f.newJio=function(a,c,d){var e=b.extend(!0,{use_local_storage:!0},d);return k({storage:a,applicant:c,options:e})},f.newBaseStorage=function(a,b){return j(a,b)},f.addStorageType=function(a,b){return a&&b?(d.storage_type_object[a]=b,!0):!1},f.getGlobalObject=function(){return d},f.getConstObject=function(){return b.extend(!0,{},c)},f},l()};return window.requirejs?(define("JIO",["LocalOrCookieStorage","jQuery"],a),undefined):a(LocalOrCookieStorage,jQuery)}();
\ No newline at end of file \ No newline at end of file
/*! JIO Storage - v0.1.0 - 2012-06-01 /*! JIO Storage - v0.1.0 - 2012-06-05
* Copyright (c) 2012 Nexedi; Licensed */ * Copyright (c) 2012 Nexedi; Licensed */
(function () { (function () {
var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { var jioStorageLoader =
function ( LocalOrCookieStorage, $, Base64, sjcl, Jio) {
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
// Tools // Tools
...@@ -27,8 +28,8 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -27,8 +28,8 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
var that = Jio.newBaseStorage( spec, my ), priv = {}; var that = Jio.newBaseStorage( spec, my ), priv = {};
priv.storage_user_array_name = 'jio/localuserarray'; priv.storage_user_array_name = 'jio/local_user_array';
priv.storage_file_array_name = 'jio/localfilenamearray/' + priv.storage_file_array_name = 'jio/local_file_name_array/' +
that.getStorageUserName() + '/' + that.getApplicantID(); that.getStorageUserName() + '/' + that.getApplicantID();
/** /**
...@@ -44,13 +45,29 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -44,13 +45,29 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
/** /**
* Adds a user to the user list. * Adds a user to the user list.
* @method addUser * @method addUser
* @param {string} username The user name. * @param {string} user_name The user name.
*/ */
priv.addUser = function (username) { priv.addUser = function (user_name) {
var userarray = priv.getUserArray(); var user_array = priv.getUserArray();
userarray.push(username); user_array.push(user_name);
LocalOrCookieStorage.setItem(priv.storage_user_array_name, LocalOrCookieStorage.setItem(priv.storage_user_array_name,
userarray); user_array);
};
/**
* checks if a user exists in the user array.
* @method userExists
* @param {string} user_name The user name
* @return {boolean} true if exist, else false
*/
priv.userExists = function (user_name) {
var user_array = priv.getUserArray(), i, l;
for (i = 0, l = user_array.length; i < l; i += 1) {
if (user_array[i] === user_name) {
return true;
}
}
return false;
}; };
/** /**
...@@ -66,29 +83,29 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -66,29 +83,29 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
/** /**
* Adds a file name to the local file name array. * Adds a file name to the local file name array.
* @method addFileName * @method addFileName
* @param {string} filename The new file name. * @param {string} file_name The new file name.
*/ */
priv.addFileName = function (filename) { priv.addFileName = function (file_name) {
var filenamearray = priv.getFileNameArray(); var file_name_array = priv.getFileNameArray();
filenamearray.push(filename); file_name_array.push(file_name);
LocalOrCookieStorage.setItem(priv.storage_file_array_name, LocalOrCookieStorage.setItem(priv.storage_file_array_name,
filenamearray); file_name_array);
}; };
/** /**
* Removes a file name from the local file name array. * Removes a file name from the local file name array.
* @method removeFileName * @method removeFileName
* @param {string} filename The file name to remove. * @param {string} file_name The file name to remove.
*/ */
priv.removeFileName = function (filename) { priv.removeFileName = function (file_name) {
var i, l, array = priv.getFileNameArray(), newarray = []; var i, l, array = priv.getFileNameArray(), new_array = [];
for (i = 0, l = array.length; i < l; i+= 1) { for (i = 0, l = array.length; i < l; i+= 1) {
if (array[i] !== filename) { if (array[i] !== file_name) {
newarray.push(array[i]); new_array.push(array[i]);
} }
} }
LocalOrCookieStorage.setItem(priv.storage_file_array_name, LocalOrCookieStorage.setItem(priv.storage_file_array_name,
newarray); new_array);
}; };
/** /**
...@@ -98,20 +115,13 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -98,20 +115,13 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
*/ */
that.checkNameAvailability = function () { that.checkNameAvailability = function () {
setTimeout(function () { setTimeout(function () {
var i, l, array = priv.getUserArray(); that.done(!priv.userExists(that.getUserName()));
for (i = 0, l = array.length; i < l; i+= 1) {
if (array[i] === that.getUserName()) {
that.done(false);
return;
}
}
that.done(true);
}, 100); }, 100);
}; // end checkNameAvailability }; // end checkNameAvailability
/** /**
* Saves a document in the local storage. * Saves a document in the local storage.
* It will store the file in 'jio/local/USR/APP/FILENAME'. * It will store the file in 'jio/local/USR/APP/FILE_NAME'.
* @method saveDocument * @method saveDocument
*/ */
that.saveDocument = function () { that.saveDocument = function () {
...@@ -127,16 +137,19 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -127,16 +137,19 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
if (!doc) { if (!doc) {
// create document // create document
doc = { doc = {
'fileName': that.getFileName(), 'name': that.getFileName(),
'fileContent': that.getFileContent(), 'content': that.getFileContent(),
'creationDate': Date.now(), 'creation_date': Date.now(),
'lastModified': Date.now() 'last_modified': Date.now()
}; };
if (!priv.userExists(that.getStorageUserName())) {
priv.addUser (that.getStorageUserName());
}
priv.addFileName(that.getFileName()); priv.addFileName(that.getFileName());
} else { } else {
// overwriting // overwriting
doc.lastModified = Date.now(); doc.last_modified = Date.now();
doc.fileContent = that.getFileContent(); doc.content = that.getFileContent();
} }
LocalOrCookieStorage.setItem(path, doc); LocalOrCookieStorage.setItem(path, doc);
return that.done(); return that.done();
...@@ -145,7 +158,7 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -145,7 +158,7 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
/** /**
* Loads a document from the local storage. * Loads a document from the local storage.
* It will load file in 'jio/local/USR/APP/FILENAME'. * It will load file in 'jio/local/USR/APP/FILE_NAME'.
* You can add an 'options' object to the job, it can contain: * You can add an 'options' object to the job, it can contain:
* - metadata_only {boolean} default false, retrieve the file metadata * - metadata_only {boolean} default false, retrieve the file metadata
* only if true. * only if true.
...@@ -154,8 +167,8 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -154,8 +167,8 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
* @method loadDocument * @method loadDocument
*/ */
that.loadDocument = function () { that.loadDocument = function () {
// document object is {'fileName':string,'fileContent':string, // document object is {'name':string,'content':string,
// 'creationDate':date,'lastModified':date} // 'creation_date':date,'last_modified':date}
setTimeout(function () { setTimeout(function () {
var doc = null, settings = that.cloneOptionObject(); var doc = null, settings = that.cloneOptionObject();
...@@ -169,10 +182,10 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -169,10 +182,10 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
'" not found in localStorage.'}); '" not found in localStorage.'});
} else { } else {
if (settings.metadata_only) { if (settings.metadata_only) {
delete doc.fileContent; delete doc.content;
} else if (settings.content_only) { } else if (settings.content_only) {
delete doc.lastModified; delete doc.last_modified;
delete doc.creationDate; delete doc.creation_date;
} }
that.done(doc); that.done(doc);
} }
...@@ -186,24 +199,26 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -186,24 +199,26 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
* @method getDocumentList * @method getDocumentList
*/ */
that.getDocumentList = function () { that.getDocumentList = function () {
// the list is [object,object] -> object = {'fileName':string, // the list is [object,object] -> object = {'name':string,
// 'lastModified':date,'creationDate':date} // 'last_modified':date,'creation_date':date}
setTimeout(function () { setTimeout(function () {
var newarray = [], array = [], i, l, k = 'key', var new_array = [], array = [], i, l, k = 'key',
path = 'jio/local/'+that.getStorageUserName()+'/'+ path = 'jio/local/'+that.getStorageUserName()+'/'+
that.getApplicantID(), fileObject = {}; that.getApplicantID(), file_object = {};
array = priv.getFileNameArray(); array = priv.getFileNameArray();
for (i = 0, l = array.length; i < l; i += 1) { for (i = 0, l = array.length; i < l; i += 1) {
fileObject = file_object =
LocalOrCookieStorage.getItem(path+'/'+array[i]); LocalOrCookieStorage.getItem(path+'/'+array[i]);
newarray.push ({ if (file_object) {
'fileName':fileObject.fileName, new_array.push ({
'creationDate':fileObject.creationDate, 'name':file_object.name,
'lastModified':fileObject.lastModified}); 'creation_date':file_object.creation_date,
'last_modified':file_object.last_modified});
}
} }
that.done(newarray); that.done(new_array);
}, 100); }, 100);
}; // end getDocumentList }; // end getDocumentList
...@@ -237,17 +252,17 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -237,17 +252,17 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
that.mkcol = function ( options ) { that.mkcol = function ( options ) {
// create folders in dav storage, synchronously // create folders in dav storage, synchronously
// options : contains mkcol list // options : contains mkcol list
// options.location : the davstorage locations // options.url : the davstorage url
// options.path: if path=/foo/bar then creates location/dav/foo/bar // options.path: if path=/foo/bar then creates url/dav/foo/bar
// options.success: the function called if success // options.success: the function called if success
// options.userName: the username // options.user_name: the user name
// options.password: the password // options.password: the password
// TODO this method is not working !!! // TODO this method is not working !!!
var settings = $.extend ({ var settings = $.extend ({
'success':function(){},'error':function(){}},options), 'success':function(){},'error':function(){}},options),
splitpath = ['splitedpath'], tmppath = 'temp/path'; split_path = ['split_path'], tmp_path = 'temp/path';
// if pathstep is not defined, then split the settings.path // if pathstep is not defined, then split the settings.path
// and do mkcol recursively // and do mkcol recursively
...@@ -255,25 +270,25 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -255,25 +270,25 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
settings.pathsteps = 1; settings.pathsteps = 1;
that.mkcol(settings); that.mkcol(settings);
} else { } else {
splitpath = settings.path.split('/'); split_path = settings.path.split('/');
// // check if the path is terminated by '/' // // check if the path is terminated by '/'
// if (splitpath[splitpath.length-1] == '') { // if (split_path[split_path.length-1] == '') {
// splitpath.length --; // split_path.length --;
// } // }
// check if the pathstep is lower than the longer // check if the pathstep is lower than the longer
if (settings.pathsteps >= splitpath.length-1) { if (settings.pathsteps >= split_path.length-1) {
return settings.success(); return settings.success();
} }
splitpath.length = settings.pathsteps + 1; split_path.length = settings.pathsteps + 1;
settings.pathsteps++; settings.pathsteps++;
tmppath = splitpath.join('/'); tmp_path = split_path.join('/');
// alert(settings.location + tmppath); // alert(settings.url + tmp_path);
$.ajax ( { $.ajax ( {
url: settings.location + tmppath, url: settings.url + tmp_path,
type: 'MKCOL', type: 'MKCOL',
async: true, async: true,
headers: {'Authorization': 'Basic '+Base64.encode( headers: {'Authorization': 'Basic '+Base64.encode(
settings.userName + ':' + settings.user_name + ':' +
settings.password ), Depth: '1'}, settings.password ), Depth: '1'},
// xhrFields: {withCredentials: 'true'}, // cross domain // xhrFields: {withCredentials: 'true'}, // cross domain
success: function () { success: function () {
...@@ -297,16 +312,16 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -297,16 +312,16 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
}; };
that.checkNameAvailability = function () { that.checkNameAvailability = function () {
// checks the availability of the [job.userName]. // checks the availability of the [job.user_name].
// if the name already exists, it is not available. // if the name already exists, it is not available.
// this.job.storage: the storage informations. // this.job.storage: the storage informations.
// this.job.storage.location: the dav storage location. // this.job.storage.url: the dav storage url.
// this.job.userName: the name we want to check. // this.job.user_name: the name we want to check.
// this.job.storage.userName: the user name. // this.job.storage.user_name: the user name.
// this.job.storage.password: the user password. // this.job.storage.password: the user password.
$.ajax ( { $.ajax ( {
url: that.getStorageLocation() + '/dav/' + url: that.getStorageURL() + '/dav/' +
that.getStorageUserName() + '/', that.getStorageUserName() + '/',
async: true, async: true,
type: 'PROPFIND', type: 'PROPFIND',
...@@ -332,16 +347,16 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -332,16 +347,16 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
that.saveDocument = function () { that.saveDocument = function () {
// Save a document in a DAVStorage // Save a document in a DAVStorage
// this.job.storage: the storage informations. // this.job.storage: the storage informations.
// this.job.storage.userName: the user name. // this.job.storage.user_name: the user name.
// this.job.storage.password: the user password. // this.job.storage.password: the user password.
// this.job.applicant.ID: the applicant ID. // this.job.applicant.ID: the applicant ID.
// this.job.fileName: the document name. // this.job.name: the document name.
// this.job.fileContent: the document content. // this.job.content: the document content.
// TODO if path of /dav/user/applic does not exists, it won't work! // TODO if path of /dav/user/applic does not exists, it won't work!
//// save on dav //// save on dav
$.ajax ( { $.ajax ( {
url: that.getStorageLocation() + '/dav/' + url: that.getStorageURL() + '/dav/' +
that.getStorageUserName() + '/' + that.getStorageUserName() + '/' +
that.getApplicantID() + '/' + that.getApplicantID() + '/' +
that.getFileName(), that.getFileName(),
...@@ -367,21 +382,21 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -367,21 +382,21 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
that.loadDocument = function () { that.loadDocument = function () {
// Load a document from a DAVStorage. It returns a document object // Load a document from a DAVStorage. It returns a document object
// containing all information of the document and its content. // containing all information of the document and its content.
// this.job.fileName: the document name we want to load. // this.job.name: the document name we want to load.
// this.job.storage: the storage informations. // this.job.storage: the storage informations.
// this.job.storage.location: the dav storage location. // this.job.storage.url: the dav storage url.
// this.job.storage.userName: the user name. // this.job.storage.userName: the user name.
// this.job.storage.password: the user password. // this.job.storage.password: the user password.
// this.job.options.getContent: if true, also get the file content. // this.job.options.getContent: if true, also get the file content.
// document object is {'fileName':string,'fileContent':string, // document object is {'name':string,'content':string,
// 'creationDate':date,'lastModified':date} // 'creation_date':date,'last_modified':date}
var doc = {}, var doc = {},
settings = that.cloneOptionObject(), settings = that.cloneOptionObject(),
getContent = function () { getContent = function () {
$.ajax ( { $.ajax ( {
url: that.getStorageLocation() + '/dav/' + url: that.getStorageURL() + '/dav/' +
that.getStorageUserName() + '/' + that.getStorageUserName() + '/' +
that.getApplicantID() + '/' + that.getApplicantID() + '/' +
that.getFileName(), that.getFileName(),
...@@ -393,7 +408,7 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -393,7 +408,7 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
that.getStoragePassword() )}, that.getStoragePassword() )},
// xhrFields: {withCredentials: 'true'}, // cross domain // xhrFields: {withCredentials: 'true'}, // cross domain
success: function (content) { success: function (content) {
doc.fileContent = content; doc.content = content;
that.done(doc); that.done(doc);
}, },
error: function (type) { error: function (type) {
...@@ -410,14 +425,14 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -410,14 +425,14 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
} }
} ); } );
}; };
doc.fileName = that.getFileName(); doc.name = that.getFileName();
if (settings.content_only) { if (settings.content_only) {
getContent(); getContent();
return; return;
} }
// Get properties // Get properties
$.ajax ( { $.ajax ( {
url: that.getStorageLocation() + '/dav/' + url: that.getStorageURL() + '/dav/' +
that.getStorageUserName() + '/' + that.getStorageUserName() + '/' +
that.getApplicantID() + '/' + that.getApplicantID() + '/' +
that.getFileName(), that.getFileName(),
...@@ -428,16 +443,16 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -428,16 +443,16 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
that.getStorageUserName() + ':' + that.getStorageUserName() + ':' +
that.getStoragePassword() )}, that.getStoragePassword() )},
success: function (xmlData) { success: function (xmlData) {
// doc.lastModified = // doc.last_modified =
$(xmlData).find( $(xmlData).find(
'lp1\\:getlastmodified, getlastmodified' 'lp1\\:getlastmodified, getlastmodified'
).each( function () { ).each( function () {
doc.lastModified = $(this).text(); doc.last_modified = $(this).text();
}); });
$(xmlData).find( $(xmlData).find(
'lp1\\:creationdate, creationdate' 'lp1\\:creationdate, creationdate'
).each( function () { ).each( function () {
doc.creationDate = $(this).text(); doc.creation_date = $(this).text();
}); });
if (!settings.metadata_only) { if (!settings.metadata_only) {
getContent(); getContent();
...@@ -457,18 +472,18 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -457,18 +472,18 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
// Get a document list from a DAVStorage. It returns a document // Get a document list from a DAVStorage. It returns a document
// array containing all the user documents informations. // array containing all the user documents informations.
// this.job.storage: the storage informations. // this.job.storage: the storage informations.
// this.job.storage.location: the dav storage location. // this.job.storage.url: the dav storage url.
// this.job.storage.userName: the user name. // this.job.storage.user_name: the user name.
// this.job.storage.password: the user password. // this.job.storage.password: the user password.
// this.job.applicant.ID: the applicant id. // this.job.applicant.ID: the applicant id.
// the list is [object,object] -> object = {'fileName':string, // the list is [object,object] -> object = {'name':string,
// 'lastModified':date,'creationDate':date} // 'last_modified':date,'creation_date':date}
var documentArrayList = [], file = {}, pathArray = []; var document_array = [], file = {}, path_array = [];
$.ajax ( { $.ajax ( {
url: that.getStorageLocation() + '/dav/' + url: that.getStorageURL() + '/dav/' +
that.getStorageUserName() + '/' + that.getStorageUserName() + '/' +
that.getApplicantID() + '/', that.getApplicantID() + '/',
async: true, async: true,
...@@ -484,28 +499,28 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -484,28 +499,28 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
if(i>0) { // exclude parent folder if(i>0) { // exclude parent folder
file = {}; file = {};
$(data).find('D\\:href, href').each(function(){ $(data).find('D\\:href, href').each(function(){
pathArray = $(this).text().split('/'); path_array = $(this).text().split('/');
file.fileName = file.name =
(pathArray[pathArray.length-1] ? (path_array[path_array.length-1] ?
pathArray[pathArray.length-1] : path_array[path_array.length-1] :
pathArray[pathArray.length-2]+'/'); path_array[path_array.length-2]+'/');
}); });
if (file.fileName === '.htaccess' || if (file.name === '.htaccess' ||
file.fileName === '.htpasswd') { return; } file.name === '.htpasswd') { return; }
$(data).find( $(data).find(
'lp1\\:getlastmodified, getlastmodified' 'lp1\\:getlastmodified, getlastmodified'
).each(function () { ).each(function () {
file.lastModified = $(this).text(); file.last_modified = $(this).text();
}); });
$(data).find( $(data).find(
'lp1\\:creationdate, creationdate' 'lp1\\:creationdate, creationdate'
).each(function () { ).each(function () {
file.creationDate = $(this).text(); file.creation_date = $(this).text();
}); });
documentArrayList.push (file); document_array.push (file);
} }
}); });
that.done(documentArrayList); that.done(document_array);
}, },
error: function (type) { error: function (type) {
type.message = type.message =
...@@ -517,15 +532,15 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -517,15 +532,15 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
that.removeDocument = function () { that.removeDocument = function () {
// Remove a document from a DAVStorage. // Remove a document from a DAVStorage.
// this.job.fileName: the document name we want to remove. // this.job.name: the document name we want to remove.
// this.job.storage: the storage informations. // this.job.storage: the storage informations.
// this.job.storage.location: the dav storage location. // this.job.storage.url: the dav storage url.
// this.job.storage.userName: the user name. // this.job.storage.user_name: the user name.
// this.job.storage.password: the user password. // this.job.storage.password: the user password.
// this.job.applicant.ID: the applicant id. // this.job.applicant.ID: the applicant id.
$.ajax ( { $.ajax ( {
url: that.getStorageLocation() + '/dav/' + url: that.getStorageURL() + '/dav/' +
that.getStorageUserName() + '/' + that.getStorageUserName() + '/' +
that.getApplicantID() + '/' + that.getApplicantID() + '/' +
that.getFileName(), that.getFileName(),
...@@ -562,8 +577,8 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -562,8 +577,8 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
priv.storageArray = that.getStorageArray(); priv.storageArray = that.getStorageArray();
// TODO Add a tests that check if there is no duplicate storages. // TODO Add a tests that check if there is no duplicate storages.
priv.length = priv.storageArray.length; priv.length = priv.storageArray.length;
priv.returnsValuesArray = []; priv.return_value_array = [];
priv.maxtries = that.getMaxTries(); priv.max_tries = that.getMaxTries();
that.setMaxTries (1); that.setMaxTries (1);
...@@ -571,7 +586,7 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -571,7 +586,7 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
var newjob = {}, i; var newjob = {}, i;
for (i = 0; i < priv.storageArray.length; i += 1) { for (i = 0; i < priv.storageArray.length; i += 1) {
newjob = that.cloneJob(); newjob = that.cloneJob();
newjob.maxtries = priv.maxtries; newjob.max_tries = priv.max_tries;
newjob.storage = priv.storageArray[i]; newjob.storage = priv.storageArray[i];
newjob.callback = callback; newjob.callback = callback;
that.addJob ( newjob ) ; that.addJob ( newjob ) ;
...@@ -579,18 +594,18 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -579,18 +594,18 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
}; };
that.checkNameAvailability = function () { that.checkNameAvailability = function () {
// Checks the availability of the [job.userName]. // Checks the availability of the [job.user_name].
// if the name already exists in a storage, it is not available. // if the name already exists in a storage, it is not available.
// this.job.userName: the name we want to check. // this.job.user_name: the name we want to check.
// this.job.storage.storageArray: An Array of storages. // this.job.storage.storageArray: An Array of storages.
var i = 'id', done = false, errorArray = [], var i = 'id', done = false, error_array = [],
res = {'status':'done'}, callback = function (result) { res = {'status':'done'}, callback = function (result) {
priv.returnsValuesArray.push(result); priv.return_value_array.push(result);
if (!done) { if (!done) {
if (result.status === 'fail') { if (result.status === 'fail') {
res.status = 'fail'; res.status = 'fail';
errorArray.push(result.error); error_array.push(result.error);
} else { } else {
if (result.return_value === false) { if (result.return_value === false) {
that.done (false); that.done (false);
...@@ -598,7 +613,7 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -598,7 +613,7 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
return; return;
} }
} }
if (priv.returnsValuesArray.length === if (priv.return_value_array.length ===
priv.length) { priv.length) {
if (res.status === 'fail') { if (res.status === 'fail') {
that.fail ( that.fail (
...@@ -606,7 +621,7 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -606,7 +621,7 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
statusText:'Multi-Status', statusText:'Multi-Status',
message:'Some check availability of "' + message:'Some check availability of "' +
that.getUserName() + '" requests have failed.', that.getUserName() + '" requests have failed.',
array:errorArray}); array:error_array});
} else { } else {
that.done (true); that.done (true);
} }
...@@ -621,30 +636,30 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -621,30 +636,30 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
// Save a single document in several storages. // Save a single document in several storages.
// If a storage failed to save the document. // If a storage failed to save the document.
// this.job.storage: the storage informations. // this.job.storage: the storage informations.
// this.job.storage.userName: the user name. // this.job.storage.user_name: the user name.
// this.job.storage.password: the user password. // this.job.storage.password: the user password.
// this.job.applicant.ID: the applicant ID. // this.job.applicant.ID: the applicant ID.
// this.job.fileName: the document name. // this.job.name: the document name.
// this.job.fileContent: the document content. // this.job.content: the document content.
var res = {'status':'done'}, i = 'id', var res = {'status':'done'}, i = 'id',
done = false, errorArray = [], done = false, error_array = [],
callback = function (result) { callback = function (result) {
priv.returnsValuesArray.push(result); priv.return_value_array.push(result);
if (!done) { if (!done) {
if (result.status !== 'fail') { if (result.status !== 'fail') {
that.done (); that.done ();
done = true; done = true;
} else { } else {
errorArray.push(result.error); error_array.push(result.error);
if (priv.returnsValuesArray.length === if (priv.return_value_array.length ===
priv.length) { priv.length) {
that.fail ( that.fail (
{status:207, {status:207,
statusText:'Multi-Status', statusText:'Multi-Status',
message:'All save "' + that.getFileName() + message:'All save "' + that.getFileName() +
'" requests have failed.', '" requests have failed.',
array:errorArray}); array:error_array});
} }
} }
} }
...@@ -657,31 +672,30 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -657,31 +672,30 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
// object containing all information of the document and its // object containing all information of the document and its
// content. TODO will popup a window which will help us to choose // content. TODO will popup a window which will help us to choose
// the good file if the files are different. // the good file if the files are different.
// this.job.fileName: the document name we want to load. // this.job.name: the document name we want to load.
// this.job.storage: the storage informations. // this.job.storage: the storage informations.
// this.job.storage.location: the dav storage location. // this.job.storage.user_name: the user name.
// this.job.storage.userName: the user name.
// this.job.storage.password: the user password. // this.job.storage.password: the user password.
// this.job.options.getContent: if true, also get the file content. // this.job.options.getContent: if true, also get the file content.
var doc = {}, i = 'id', var doc = {}, i = 'id',
done = false, errorArray = [], done = false, error_array = [],
res = {'status':'done'}, callback = function (result) { res = {'status':'done'}, callback = function (result) {
priv.returnsValuesArray.push(result); priv.return_value_array.push(result);
if (!done) { if (!done) {
if (result.status !== 'fail') { if (result.status !== 'fail') {
that.done (result.return_value); that.done (result.return_value);
done = true; done = true;
} else { } else {
errorArray.push(result.error); error_array.push(result.error);
if (priv.returnsValuesArray.length === if (priv.return_value_array.length ===
priv.length) { priv.length) {
that.fail ( that.fail (
{status:207, {status:207,
statusText:'Multi-Status', statusText:'Multi-Status',
message:'All load "' + that.getFileName() + message:'All load "' + that.getFileName() +
'" requests have failed.', '" requests have failed.',
array:errorArray}); array:error_array});
} }
} }
} }
...@@ -693,29 +707,28 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -693,29 +707,28 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
// Get a document list from several storages. It returns a document // Get a document list from several storages. It returns a document
// array containing all the user documents informations. // array containing all the user documents informations.
// this.job.storage: the storage informations. // this.job.storage: the storage informations.
// this.job.storage.location: the dav storage location. // this.job.storage.user_name: the user name.
// this.job.storage.userName: the user name.
// this.job.storage.password: the user password. // this.job.storage.password: the user password.
// this.job.applicant.ID: the applicant id. // this.job.applicant.ID: the applicant id.
var res = {'status':'done'}, i = 'id', var res = {'status':'done'}, i = 'id',
done = false, errorArray = [], done = false, error_array = [],
callback = function (result) { callback = function (result) {
priv.returnsValuesArray.push(result); priv.return_value_array.push(result);
if (!done) { if (!done) {
if (result.status !== 'fail') { if (result.status !== 'fail') {
that.done (result.return_value); that.done (result.return_value);
done = true; done = true;
} else { } else {
errorArray.push(result.error); error_array.push(result.error);
if (priv.returnsValuesArray.length === if (priv.return_value_array.length ===
priv.length) { priv.length) {
that.fail ( that.fail (
{status:207, {status:207,
statusText:'Multi-Status', statusText:'Multi-Status',
message:'All get document list requests'+ message:'All get document list requests'+
' have failed', ' have failed',
array:errorArray}); array:error_array});
} }
} }
} }
...@@ -725,31 +738,30 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -725,31 +738,30 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
that.removeDocument = function () { that.removeDocument = function () {
// Remove a document from several storages. // Remove a document from several storages.
// this.job.fileName: the document name we want to remove. // this.job.name: the document name we want to remove.
// this.job.storage: the storage informations. // this.job.storage: the storage informations.
// this.job.storage.location: the dav storage location. // this.job.storage.user_name: the user name.
// this.job.storage.userName: the user name.
// this.job.storage.password: the user password. // this.job.storage.password: the user password.
// this.job.applicant.ID: the applicant id. // this.job.applicant.ID: the applicant id.
var res = {'status':'done'}, i = 'key', var res = {'status':'done'}, i = 'key',
done = false, errorArray = [], done = false, error_array = [],
callback = function (result) { callback = function (result) {
priv.returnsValuesArray.push(result); priv.return_value_array.push(result);
if (!done) { if (!done) {
if (result.status !== 'fail') { if (result.status !== 'fail') {
that.done (); that.done ();
done = true; done = true;
} else { } else {
errorArray.push(result.error); error_array.push(result.error);
if (priv.returnsValuesArray.length === if (priv.return_value_array.length ===
priv.length) { priv.length) {
that.fail ( that.fail (
{status:207, {status:207,
statusText:'Multi-Status', statusText:'Multi-Status',
message:'All remove "' + that.getFileName() + message:'All remove "' + that.getFileName() +
'" requests have failed.', '" requests have failed.',
array:errorArray}); array:error_array});
} }
} }
} }
...@@ -773,8 +785,8 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -773,8 +785,8 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
var that = Jio.newBaseStorage( spec, my ), priv = {}; var that = Jio.newBaseStorage( spec, my ), priv = {};
priv.storage_array_name = 'jio/indexedstoragearray'; priv.storage_array_name = 'jio/indexed_storage_array';
priv.storage_file_array_name = 'jio/indexedfilearray/'+ priv.storage_file_array_name = 'jio/indexed_file_array/'+
JSON.stringify (that.getSecondStorage()) + '/' + JSON.stringify (that.getSecondStorage()) + '/' +
that.getApplicantID(); that.getApplicantID();
...@@ -805,10 +817,10 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -805,10 +817,10 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
* @param {object} storage The new indexed storage. * @param {object} storage The new indexed storage.
*/ */
priv.addIndexedStorage = function (storage) { priv.addIndexedStorage = function (storage) {
var indexedstoragearray = priv.getIndexedStorageArray(); var indexed_storage_array = priv.getIndexedStorageArray();
indexedstoragearray.push(JSON.stringify (storage)); indexed_storage_array.push(JSON.stringify (storage));
LocalOrCookieStorage.setItem(priv.storage_array_name, LocalOrCookieStorage.setItem(priv.storage_array_name,
indexedstoragearray); indexed_storage_array);
}; };
/** /**
...@@ -818,10 +830,10 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -818,10 +830,10 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
* @return {boolean} true if found, else false * @return {boolean} true if found, else false
*/ */
priv.isAnIndexedStorage = function (storage) { priv.isAnIndexedStorage = function (storage) {
var jsonstorage = JSON.stringify (storage),i,l, var json_storae = JSON.stringify (storage),i,l,
array = priv.getIndexedStorageArray(); array = priv.getIndexedStorageArray();
for (i = 0, l = array.length; i < l; i+= 1) { for (i = 0, l = array.length; i < l; i+= 1) {
if (JSON.stringify(array[i]) === jsonstorage) { if (JSON.stringify(array[i]) === json_storae) {
return true; return true;
} }
} }
...@@ -851,24 +863,24 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -851,24 +863,24 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
/** /**
* Sets the file array list. * Sets the file array list.
* @method setFileArray * @method setFileArray
* @param {array} filearray The array containing files. * @param {array} file_array The array containing files.
*/ */
priv.setFileArray = function (filearray) { priv.setFileArray = function (file_array) {
return LocalOrCookieStorage.setItem( return LocalOrCookieStorage.setItem(
priv.storage_file_array_name, priv.storage_file_array_name,
filearray); file_array);
}; };
/** /**
* Checks if the file already exists in the array. * Checks if the file already exists in the array.
* @method isFileIndexed * @method isFileIndexed
* @param {string} filename The file we want to find. * @param {string} file_name The file we want to find.
* @return {boolean} true if found, else false * @return {boolean} true if found, else false
*/ */
priv.isFileIndexed = function (filename) { priv.isFileIndexed = function (file_name) {
var i, l, array = priv.getFileArray(); var i, l, array = priv.getFileArray();
for (i = 0, l = array.length; i < l; i+= 1) { for (i = 0, l = array.length; i < l; i+= 1) {
if (array[i].fileName === filename){ if (array[i].name === file_name){
return true; return true;
} }
} }
...@@ -881,26 +893,26 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -881,26 +893,26 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
* @param {object} file The new file. * @param {object} file The new file.
*/ */
priv.addFile = function (file) { priv.addFile = function (file) {
var filearray = priv.getFileArray(); var file_array = priv.getFileArray();
filearray.push(file); file_array.push(file);
LocalOrCookieStorage.setItem(priv.storage_file_array_name, LocalOrCookieStorage.setItem(priv.storage_file_array_name,
filearray); file_array);
}; };
/** /**
* Removes a file from the local file array. * Removes a file from the local file array.
* @method removeFile * @method removeFile
* @param {string} filename The file to remove. * @param {string} file_name The file to remove.
*/ */
priv.removeFile = function (filename) { priv.removeFile = function (file_name) {
var i, l, array = priv.getFileArray(), newarray = []; var i, l, array = priv.getFileArray(), new_array = [];
for (i = 0, l = array.length; i < l; i+= 1) { for (i = 0, l = array.length; i < l; i+= 1) {
if (array[i].fileName !== filename) { if (array[i].name !== file_name) {
newarray.push(array[i]); new_array.push(array[i]);
} }
} }
LocalOrCookieStorage.setItem(priv.storage_file_array_name, LocalOrCookieStorage.setItem(priv.storage_file_array_name,
newarray); new_array);
}; };
/** /**
...@@ -924,7 +936,7 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -924,7 +936,7 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
storage: that.getSecondStorage(), storage: that.getSecondStorage(),
applicant: {ID:that.getApplicantID()}, applicant: {ID:that.getApplicantID()},
method: 'getDocumentList', method: 'getDocumentList',
maxtries: 3, max_tries: 3,
callback: getlist_callback callback: getlist_callback
}; };
that.addJob ( newjob ); that.addJob ( newjob );
...@@ -935,17 +947,17 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -935,17 +947,17 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
* @method checkNameAvailability * @method checkNameAvailability
*/ */
that.checkNameAvailability = function () { that.checkNameAvailability = function () {
var newjob = that.cloneJob(); var new_job = that.cloneJob();
priv.update(); priv.update();
newjob.storage = that.getSecondStorage(); new_job.storage = that.getSecondStorage();
newjob.callback = function (result) { new_job.callback = function (result) {
if (result.status === 'done') { if (result.status === 'done') {
that.done(result.return_value); that.done(result.return_value);
} else { } else {
that.fail(result.error); that.fail(result.error);
} }
}; };
that.addJob( newjob ); that.addJob( new_job );
}; // end checkNameAvailability }; // end checkNameAvailability
/** /**
...@@ -953,14 +965,14 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -953,14 +965,14 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
* @method saveDocument * @method saveDocument
*/ */
that.saveDocument = function () { that.saveDocument = function () {
var newjob = that.cloneJob(); var new_job = that.cloneJob();
newjob.storage = that.getSecondStorage(); new_job.storage = that.getSecondStorage();
newjob.callback = function (result) { new_job.callback = function (result) {
if (result.status === 'done') { if (result.status === 'done') {
if (!priv.isFileIndexed(that.getFileName())) { if (!priv.isFileIndexed(that.getFileName())) {
priv.addFile({fileName:that.getFileName(), priv.addFile({name:that.getFileName(),
lastModified:0, last_modified:0,
creationDate:0}); creation_date:0});
} }
priv.update(); priv.update();
that.done(); that.done();
...@@ -968,7 +980,7 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -968,7 +980,7 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
that.fail(result.error); that.fail(result.error);
} }
}; };
that.addJob ( newjob ); that.addJob ( new_job );
}; // end saveDocument }; // end saveDocument
/** /**
...@@ -978,13 +990,13 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -978,13 +990,13 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
* @method loadDocument * @method loadDocument
*/ */
that.loadDocument = function () { that.loadDocument = function () {
var filearray, i, l, newjob, var file_array, i, l, new_job,
loadcallback = function (result) { loadCallback = function (result) {
if (result.status === 'done') { if (result.status === 'done') {
// if (filearray[i].lastModified !== // if (file_array[i].last_modified !==
// result.return_value.lastModified || // result.return_value.last_modified ||
// filearray[i].creationDate !== // file_array[i].creation_date !==
// result.return_value.creationDate) { // result.return_value.creation_date) {
// // the file in the index storage is different than // // the file in the index storage is different than
// // the one in the second storage. priv.update will // // the one in the second storage. priv.update will
// // take care of refresh the indexed storage // // take care of refresh the indexed storage
...@@ -995,21 +1007,20 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -995,21 +1007,20 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
} }
}, },
secondLoadDocument = function () { secondLoadDocument = function () {
newjob = that.cloneJob(); new_job = that.cloneJob();
newjob.storage = that.getSecondStorage(); new_job.storage = that.getSecondStorage();
newjob.callback = loadcallback; new_job.callback = loadCallback;
console.log (newjob); that.addJob ( new_job );
that.addJob ( newjob );
}, },
settings = that.cloneOptionObject(); settings = that.cloneOptionObject();
priv.update(); priv.update();
if (settings.metadata_only) { if (settings.metadata_only) {
setTimeout(function () { setTimeout(function () {
if (priv.fileArrayExists()) { if (priv.fileArrayExists()) {
filearray = priv.getFileArray(); file_array = priv.getFileArray();
for (i = 0, l = filearray.length; i < l; i+= 1) { for (i = 0, l = file_array.length; i < l; i+= 1) {
if (filearray[i].fileName === that.getFileName()) { if (file_array[i].name === that.getFileName()) {
return that.done(filearray[i]); return that.done(file_array[i]);
} }
} }
} else { } else {
...@@ -1041,9 +1052,9 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -1041,9 +1052,9 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
* @method removeDocument * @method removeDocument
*/ */
that.removeDocument = function () { that.removeDocument = function () {
var newjob = that.cloneJob(); var new_job = that.cloneJob();
newjob.storage = that.getSecondStorage(); new_job.storage = that.getSecondStorage();
newjob.callback = function (result) { new_job.callback = function (result) {
if (result.status === 'done') { if (result.status === 'done') {
priv.removeFile(that.getFileName()); priv.removeFile(that.getFileName());
priv.update(); priv.update();
...@@ -1052,26 +1063,263 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) { ...@@ -1052,26 +1063,263 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
that.fail(result.error); that.fail(result.error);
} }
}; };
that.addJob(newjob); that.addJob(new_job);
}; };
return that; return that;
}; };
// end Indexed Storage // end Indexed Storage
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Crypted Storage
/**
* JIO Crypted Storage. Type = 'crypted'.
* It will encrypt the file and its metadata stringified by JSON.
*/
newCryptedStorage = function ( spec, my ) {
// CryptedStorage constructor
var that = Jio.newBaseStorage( spec, my ), priv = {};
// TODO : IT IS NOT SECURE AT ALL!
// WE MUST REWORK CRYPTED STORAGE!
priv.encrypt_param_object = {
"iv":"kaprWwY/Ucr7pumXoTHbpA",
"v":1,
"iter":1000,
"ks":256,
"ts":128,
"mode":"ccm",
"adata":"",
"cipher":"aes",
"salt":"K4bmZG9d704"
};
priv.decrypt_param_object = {
"iv":"kaprWwY/Ucr7pumXoTHbpA",
"ks":256,
"ts":128,
"salt":"K4bmZG9d704"
};
priv.encrypt = function (data,callback,index) {
// end with a callback in order to improve encrypt to an
// asynchronous encryption.
var tmp = sjcl.encrypt (that.getStorageUserName()+':'+
that.getStoragePassword(), data,
priv.encrypt_param_object);
callback(JSON.parse(tmp).ct,index);
};
priv.decrypt = function (data,callback,index,key) {
var tmp, param = $.extend(true,{},priv.decrypt_param_object);
param.ct = data || '';
param = JSON.stringify (param);
try {
tmp = sjcl.decrypt (that.getStorageUserName()+':'+
that.getStoragePassword(),
param);
} catch (e) {
callback({status:0,statusText:'Decrypt Fail',
message:'Unable to decrypt.'},index,key);
return;
}
callback(tmp,index,key);
};
/**
* Checks the availability of a user name set in the job.
* @method checkNameAvailability
*/
that.checkNameAvailability = function () {
var new_job = that.cloneJob();
new_job.storage = that.getSecondStorage();
new_job.callback = function (result) {
if (result.status === 'done') {
that.done(result.return_value);
} else {
that.fail(result.error);
}
};
that.addJob( new_job );
}; // end checkNameAvailability
/**
* Saves a document.
* @method saveDocument
*/
that.saveDocument = function () {
var new_job, new_file_name, newfilecontent,
_1 = function () {
priv.encrypt(that.getFileName(),function(res) {
new_file_name = res;
_2();
});
},
_2 = function () {
priv.encrypt(that.getFileContent(),function(res) {
newfilecontent = res;
_3();
});
},
_3 = function () {
new_job = that.cloneJob();
new_job.name = new_file_name;
new_job.content = newfilecontent;
new_job.storage = that.getSecondStorage();
new_job.callback = function (result) {
if (result.status === 'done') {
that.done();
} else {
that.fail(result.error);
}
};
that.addJob ( new_job );
};
_1();
}; // end saveDocument
/**
* Loads a document.
* job.options.metadata_only {boolean}
* job.options.content_only {boolean}
* @method loadDocument
*/
that.loadDocument = function () {
var new_job, new_file_name, option = that.cloneOptionObject(),
_1 = function () {
priv.encrypt(that.getFileName(),function(res) {
new_file_name = res;
_2();
});
},
_2 = function () {
new_job = that.cloneJob();
new_job.name = new_file_name;
new_job.storage = that.getSecondStorage();
new_job.callback = loadCallback;
that.addJob ( new_job );
},
loadCallback = function (result) {
if (result.status === 'done') {
result.return_value.name = that.getFileName();
if (option.metadata_only) {
that.done(result.return_value);
} else {
priv.decrypt (result.return_value.content,function(res){
if (typeof res === 'object') {
that.fail({status:0,statusText:'Decrypt Fail',
message:'Unable to decrypt'});
} else {
result.return_value.content = res;
// content only: the second storage should
// manage content_only option, so it is not
// necessary to manage it.
that.done(result.return_value);
}
});
}
} else {
// NOTE : we can re create an error object instead of
// keep the old ex:status=404,message="document 1y59gyl8g
// not found in localStorage"...
that.fail(result.error);
}
};
_1();
}; // end loadDocument
/**
* Gets a document list.
* @method getDocumentList
*/
that.getDocumentList = function () {
var new_job, i, l, cpt = 0, array, ok = true,
_1 = function () {
new_job = that.cloneJob();
new_job.storage = that.getSecondStorage();
new_job.callback = getListCallback;
that.addJob ( new_job );
},
getListCallback = function (result) {
if (result.status === 'done') {
array = result.return_value;
for (i = 0, l = array.length; i < l; i+= 1) {
// cpt--;
priv.decrypt (array[i].name,
lastCallback,i,'name');
// priv.decrypt (array[i].content,
// lastCallback,i,'content');
}
} else {
that.fail(result.error);
}
},
lastCallback = function (res,index,key) {
var tmp;
cpt++;
if (typeof res === 'object') {
if (ok) {
that.fail({status:0,statusText:'Decrypt Fail',
message:'Unable to decrypt.'});
}
ok = false;
return;
}
array[index][key] = res;
if (cpt === l && ok) {
// this is the last callback
that.done(array);
}
};
_1();
}; // end getDocumentList
/**
* Removes a document.
* @method removeDocument
*/
that.removeDocument = function () {
var new_job, new_file_name,
_1 = function () {
priv.encrypt(that.getFileName(),function(res) {
new_file_name = res;
_2();
});
},
_2 = function () {
new_job = that.cloneJob();
new_job.name = new_file_name;
new_job.storage = that.getSecondStorage();
new_job.callback = removeCallback;
that.addJob(new_job);
},
removeCallback = function (result) {
if (result.status === 'done') {
that.done();
} else {
that.fail(result.error);
}
};
_1();
};
return that;
};
// end Crypted Storage
////////////////////////////////////////////////////////////////////////////
// add key to storageObjectType of global jio // add key to storageObjectType of global jio
Jio.addStorageType('local', newLocalStorage); Jio.addStorageType('local', newLocalStorage);
Jio.addStorageType('dav', newDAVStorage); Jio.addStorageType('dav', newDAVStorage);
Jio.addStorageType('replicate', newReplicateStorage); Jio.addStorageType('replicate', newReplicateStorage);
Jio.addStorageType('indexed', newIndexedStorage); Jio.addStorageType('indexed', newIndexedStorage);
Jio.addStorageType('crypted', newCryptedStorage);
}; };
if (window.requirejs) { if (window.requirejs) {
define ('JIOStorages', define ('JIOStorages',
['LocalOrCookieStorage','Base64','JIO','jQuery'], ['LocalOrCookieStorage','jQuery','Base64','SJCL','JIO'],
jio_storage_loader); jioStorageLoader);
} else { } else {
jio_storage_loader ( LocalOrCookieStorage, Base64, JIO, jQuery ); jioStorageLoader ( LocalOrCookieStorage, jQuery, Base64, sjcl, JIO);
} }
}()); }());
/*! JIO Storage - v0.1.0 - 2012-06-01 /*! JIO Storage - v0.1.0 - 2012-06-05
* Copyright (c) 2012 Nexedi; Licensed */ * Copyright (c) 2012 Nexedi; Licensed */
(function(){var a=function(a,b,c,d){var e,f,g,h,i;e=function(b,d){var e=c.newBaseStorage(b,d),f={};return f.storage_user_array_name="jio/localuserarray",f.storage_file_array_name="jio/localfilenamearray/"+e.getStorageUserName()+"/"+e.getApplicantID(),f.getUserArray=function(){return a.getItem(f.storage_user_array_name)||[]},f.addUser=function(b){var c=f.getUserArray();c.push(b),a.setItem(f.storage_user_array_name,c)},f.getFileNameArray=function(){return a.getItem(f.storage_file_array_name)||[]},f.addFileName=function(b){var c=f.getFileNameArray();c.push(b),a.setItem(f.storage_file_array_name,c)},f.removeFileName=function(b){var c,d,e=f.getFileNameArray(),g=[];for(c=0,d=e.length;c<d;c+=1)e[c]!==b&&g.push(e[c]);a.setItem(f.storage_file_array_name,g)},e.checkNameAvailability=function(){setTimeout(function(){var a,b,c=f.getUserArray();for(a=0,b=c.length;a<b;a+=1)if(c[a]===e.getUserName()){e.done(!1);return}e.done(!0)},100)},e.saveDocument=function(){setTimeout(function(){var b=null,c="jio/local/"+e.getStorageUserName()+"/"+e.getApplicantID()+"/"+e.getFileName();return b=a.getItem(c),b?(b.lastModified=Date.now(),b.fileContent=e.getFileContent()):(b={fileName:e.getFileName(),fileContent:e.getFileContent(),creationDate:Date.now(),lastModified:Date.now()},f.addFileName(e.getFileName())),a.setItem(c,b),e.done()},100)},e.loadDocument=function(){setTimeout(function(){var b=null,c=e.cloneOptionObject();b=a.getItem("jio/local/"+e.getStorageUserName()+"/"+e.getApplicantID()+"/"+e.getFileName()),b?(c.metadata_only?delete b.fileContent:c.content_only&&(delete b.lastModified,delete b.creationDate),e.done(b)):e.fail({status:404,statusText:"Not Found.",message:'Document "'+e.getFileName()+'" not found in localStorage.'})},100)},e.getDocumentList=function(){setTimeout(function(){var b=[],c=[],d,g,h="key",i="jio/local/"+e.getStorageUserName()+"/"+e.getApplicantID(),j={};c=f.getFileNameArray();for(d=0,g=c.length;d<g;d+=1)j=a.getItem(i+"/"+c[d]),b.push({fileName:j.fileName,creationDate:j.creationDate,lastModified:j.lastModified});e.done(b)},100)},e.removeDocument=function(){setTimeout(function(){var b="jio/local/"+e.getStorageUserName()+"/"+e.getApplicantID()+"/"+e.getFileName();return a.deleteItem(b),f.removeFileName(e.getFileName()),e.done()},100)},e},f=function(a,e){var f=c.newBaseStorage(a,e);return f.mkcol=function(a){var c=d.extend({success:function(){},error:function(){}},a),e=["splitedpath"],g="temp/path";if(!c.pathsteps)c.pathsteps=1,f.mkcol(c);else{e=c.path.split("/");if(c.pathsteps>=e.length-1)return c.success();e.length=c.pathsteps+1,c.pathsteps++,g=e.join("/"),d.ajax({url:c.location+g,type:"MKCOL",async:!0,headers:{Authorization:"Basic "+b.encode(c.userName+":"+c.password),Depth:"1"},success:function(){f.mkcol(c)},error:function(a){c.error()}})}},f.checkNameAvailability=function(){d.ajax({url:f.getStorageLocation()+"/dav/"+f.getStorageUserName()+"/",async:!0,type:"PROPFIND",dataType:"xml",headers:{Authorization:"Basic "+b.encode(f.getStorageUserName()+":"+f.getStoragePassword()),Depth:"1"},success:function(a){f.done(!1)},error:function(a){a.status===404?f.done(!0):(a.message='Cannot check availability of "'+f.getUserName()+'" into DAVStorage.',f.fail(a))}})},f.saveDocument=function(){d.ajax({url:f.getStorageLocation()+"/dav/"+f.getStorageUserName()+"/"+f.getApplicantID()+"/"+f.getFileName(),type:"PUT",data:f.getFileContent(),async:!0,dataType:"text",headers:{Authorization:"Basic "+b.encode(f.getStorageUserName()+":"+f.getStoragePassword())},success:function(){f.done()},error:function(a){a.message='Cannot save "'+f.getFileName()+'" into DAVStorage.',f.fail(a)}})},f.loadDocument=function(){var a={},c=f.cloneOptionObject(),e=function(){d.ajax({url:f.getStorageLocation()+"/dav/"+f.getStorageUserName()+"/"+f.getApplicantID()+"/"+f.getFileName(),type:"GET",async:!0,dataType:"text",headers:{Authorization:"Basic "+b.encode(f.getStorageUserName()+":"+f.getStoragePassword())},success:function(b){a.fileContent=b,f.done(a)},error:function(a){a.status===404?a.message='Document "'+f.getFileName()+'" not found in localStorage.':a.message='Cannot load "'+f.getFileName()+'" from DAVStorage.',f.fail(a)}})};a.fileName=f.getFileName();if(c.content_only){e();return}d.ajax({url:f.getStorageLocation()+"/dav/"+f.getStorageUserName()+"/"+f.getApplicantID()+"/"+f.getFileName(),type:"PROPFIND",async:!0,dataType:"xml",headers:{Authorization:"Basic "+b.encode(f.getStorageUserName()+":"+f.getStoragePassword())},success:function(b){d(b).find("lp1\\:getlastmodified, getlastmodified").each(function(){a.lastModified=d(this).text()}),d(b).find("lp1\\:creationdate, creationdate").each(function(){a.creationDate=d(this).text()}),c.metadata_only?f.done(a):e()},error:function(a){a.message='Cannot load "'+f.getFileName()+'" informations from DAVStorage.',f.fail(a)}})},f.getDocumentList=function(){var a=[],c={},e=[];d.ajax({url:f.getStorageLocation()+"/dav/"+f.getStorageUserName()+"/"+f.getApplicantID()+"/",async:!0,type:"PROPFIND",dataType:"xml",headers:{Authorization:"Basic "+b.encode(f.getStorageUserName()+":"+f.getStoragePassword()),Depth:"1"},success:function(b){d(b).find("D\\:response, response").each(function(b,f){if(b>0){c={},d(f).find("D\\:href, href").each(function(){e=d(this).text().split("/"),c.fileName=e[e.length-1]?e[e.length-1]:e[e.length-2]+"/"});if(c.fileName===".htaccess"||c.fileName===".htpasswd")return;d(f).find("lp1\\:getlastmodified, getlastmodified").each(function(){c.lastModified=d(this).text()}),d(f).find("lp1\\:creationdate, creationdate").each(function(){c.creationDate=d(this).text()}),a.push(c)}}),f.done(a)},error:function(a){a.message="Cannot get a document list from DAVStorage.",f.fail(a)}})},f.removeDocument=function(){d.ajax({url:f.getStorageLocation()+"/dav/"+f.getStorageUserName()+"/"+f.getApplicantID()+"/"+f.getFileName(),type:"DELETE",async:!0,headers:{Authorization:"Basic "+b.encode(f.getStorageUserName()+":"+f.getStoragePassword())},success:function(){f.done()},error:function(a){a.status===404?f.done():(a.message='Cannot remove "'+f.getFileName()+'" from DAVStorage.',f.fail(a))}})},f},g=function(a,b){var d=c.newBaseStorage(a,b),e={};return e.storageArray=d.getStorageArray(),e.length=e.storageArray.length,e.returnsValuesArray=[],e.maxtries=d.getMaxTries(),d.setMaxTries(1),e.execJobsFromStorageArray=function(a){var b={},c;for(c=0;c<e.storageArray.length;c+=1)b=d.cloneJob(),b.maxtries=e.maxtries,b.storage=e.storageArray[c],b.callback=a,d.addJob(b)},d.checkNameAvailability=function(){var a="id",b=!1,c=[],f={status:"done"},g=function(a){e.returnsValuesArray.push(a);if(!b){if(a.status==="fail")f.status="fail",c.push(a.error);else if(a.return_value===!1){d.done(!1),b=!0;return}if(e.returnsValuesArray.length===e.length){f.status==="fail"?d.fail({status:207,statusText:"Multi-Status",message:'Some check availability of "'+d.getUserName()+'" requests have failed.',array:c}):d.done(!0),b=!0;return}}};e.execJobsFromStorageArray(g)},d.saveDocument=function(){var a={status:"done"},b="id",c=!1,f=[],g=function(a){e.returnsValuesArray.push(a),c||(a.status!=="fail"?(d.done(),c=!0):(f.push(a.error),e.returnsValuesArray.length===e.length&&d.fail({status:207,statusText:"Multi-Status",message:'All save "'+d.getFileName()+'" requests have failed.',array:f})))};e.execJobsFromStorageArray(g)},d.loadDocument=function(){var a={},b="id",c=!1,f=[],g={status:"done"},h=function(a){e.returnsValuesArray.push(a),c||(a.status!=="fail"?(d.done(a.return_value),c=!0):(f.push(a.error),e.returnsValuesArray.length===e.length&&d.fail({status:207,statusText:"Multi-Status",message:'All load "'+d.getFileName()+'" requests have failed.',array:f})))};e.execJobsFromStorageArray(h)},d.getDocumentList=function(){var a={status:"done"},b="id",c=!1,f=[],g=function(a){e.returnsValuesArray.push(a),c||(a.status!=="fail"?(d.done(a.return_value),c=!0):(f.push(a.error),e.returnsValuesArray.length===e.length&&d.fail({status:207,statusText:"Multi-Status",message:"All get document list requests have failed",array:f})))};e.execJobsFromStorageArray(g)},d.removeDocument=function(){var a={status:"done"},b="key",c=!1,f=[],g=function(a){e.returnsValuesArray.push(a),c||(a.status!=="fail"?(d.done(),c=!0):(f.push(a.error),e.returnsValuesArray.length===e.length&&d.fail({status:207,statusText:"Multi-Status",message:'All remove "'+d.getFileName()+'" requests have failed.',array:f})))};e.execJobsFromStorageArray(g)},d},h=function(b,d){var e=c.newBaseStorage(b,d),f={};return f.storage_array_name="jio/indexedstoragearray",f.storage_file_array_name="jio/indexedfilearray/"+JSON.stringify(e.getSecondStorage())+"/"+e.getApplicantID(),f.indexedStorageArrayExists=function(){return a.getItem(f.storage_array_name)?!0:!1},f.getIndexedStorageArray=function(){return a.getItem(f.storage_array_name)||[]},f.addIndexedStorage=function(b){var c=f.getIndexedStorageArray();c.push(JSON.stringify(b)),a.setItem(f.storage_array_name,c)},f.isAnIndexedStorage=function(a){var b=JSON.stringify(a),c,d,e=f.getIndexedStorageArray();for(c=0,d=e.length;c<d;c+=1)if(JSON.stringify(e[c])===b)return!0;return!1},f.fileArrayExists=function(){return a.getItem(f.storage_file_array_name)?!0:!1},f.getFileArray=function(){return a.getItem(f.storage_file_array_name)||[]},f.setFileArray=function(b){return a.setItem(f.storage_file_array_name,b)},f.isFileIndexed=function(a){var b,c,d=f.getFileArray();for(b=0,c=d.length;b<c;b+=1)if(d[b].fileName===a)return!0;return!1},f.addFile=function(b){var c=f.getFileArray();c.push(b),a.setItem(f.storage_file_array_name,c)},f.removeFile=function(b){var c,d,e=f.getFileArray(),g=[];for(c=0,d=e.length;c<d;c+=1)e[c].fileName!==b&&g.push(e[c]);a.setItem(f.storage_file_array_name,g)},f.update=function(a){var b=function(a){a.status==="done"&&(f.isAnIndexedStorage(e.getSecondStorage())||f.addIndexedStorage(e.getSecondStorage()),f.setFileArray(a.return_value))},c={storage:e.getSecondStorage(),applicant:{ID:e.getApplicantID()},method:"getDocumentList",maxtries:3,callback:b};e.addJob(c)},e.checkNameAvailability=function(){var a=e.cloneJob();f.update(),a.storage=e.getSecondStorage(),a.callback=function(a){a.status==="done"?e.done(a.return_value):e.fail(a.error)},e.addJob(a)},e.saveDocument=function(){var a=e.cloneJob();a.storage=e.getSecondStorage(),a.callback=function(a){a.status==="done"?(f.isFileIndexed(e.getFileName())||f.addFile({fileName:e.getFileName(),lastModified:0,creationDate:0}),f.update(),e.done()):e.fail(a.error)},e.addJob(a)},e.loadDocument=function(){var a,b,c,d,g=function(a){a.status==="done"?e.done(a.return_value):e.fail(a.error)},h=function(){d=e.cloneJob(),d.storage=e.getSecondStorage(),d.callback=g,console.log(d),e.addJob(d)},i=e.cloneOptionObject();f.update(),i.metadata_only?setTimeout(function(){if(f.fileArrayExists()){a=f.getFileArray();for(b=0,c=a.length;b<c;b+=1)if(a[b].fileName===e.getFileName())return e.done(a[b])}else h()},100):h()},e.getDocumentList=function(){var a;f.update(),a=setInterval(function(){f.fileArrayExists()&&(e.done(f.getFileArray()),clearInterval(a))},100)},e.removeDocument=function(){var a=e.cloneJob();a.storage=e.getSecondStorage(),a.callback=function(a){a.status==="done"?(f.removeFile(e.getFileName()),f.update(),e.done()):e.fail(a.error)},e.addJob(a)},e},c.addStorageType("local",e),c.addStorageType("dav",f),c.addStorageType("replicate",g),c.addStorageType("indexed",h)};window.requirejs?define("JIOStorages",["LocalOrCookieStorage","Base64","JIO","jQuery"],a):a(LocalOrCookieStorage,Base64,JIO,jQuery)})(); (function(){var a=function(a,b,c,d,e){var f,g,h,i,j;f=function(b,c){var d=e.newBaseStorage(b,c),f={};return f.storage_user_array_name="jio/local_user_array",f.storage_file_array_name="jio/local_file_name_array/"+d.getStorageUserName()+"/"+d.getApplicantID(),f.getUserArray=function(){return a.getItem(f.storage_user_array_name)||[]},f.addUser=function(b){var c=f.getUserArray();c.push(b),a.setItem(f.storage_user_array_name,c)},f.userExists=function(a){var b=f.getUserArray(),c,d;for(c=0,d=b.length;c<d;c+=1)if(b[c]===a)return!0;return!1},f.getFileNameArray=function(){return a.getItem(f.storage_file_array_name)||[]},f.addFileName=function(b){var c=f.getFileNameArray();c.push(b),a.setItem(f.storage_file_array_name,c)},f.removeFileName=function(b){var c,d,e=f.getFileNameArray(),g=[];for(c=0,d=e.length;c<d;c+=1)e[c]!==b&&g.push(e[c]);a.setItem(f.storage_file_array_name,g)},d.checkNameAvailability=function(){setTimeout(function(){d.done(!f.userExists(d.getUserName()))},100)},d.saveDocument=function(){setTimeout(function(){var b=null,c="jio/local/"+d.getStorageUserName()+"/"+d.getApplicantID()+"/"+d.getFileName();return b=a.getItem(c),b?(b.last_modified=Date.now(),b.content=d.getFileContent()):(b={name:d.getFileName(),content:d.getFileContent(),creation_date:Date.now(),last_modified:Date.now()},f.userExists(d.getStorageUserName())||f.addUser(d.getStorageUserName()),f.addFileName(d.getFileName())),a.setItem(c,b),d.done()},100)},d.loadDocument=function(){setTimeout(function(){var b=null,c=d.cloneOptionObject();b=a.getItem("jio/local/"+d.getStorageUserName()+"/"+d.getApplicantID()+"/"+d.getFileName()),b?(c.metadata_only?delete b.content:c.content_only&&(delete b.last_modified,delete b.creation_date),d.done(b)):d.fail({status:404,statusText:"Not Found.",message:'Document "'+d.getFileName()+'" not found in localStorage.'})},100)},d.getDocumentList=function(){setTimeout(function(){var b=[],c=[],e,g,h="key",i="jio/local/"+d.getStorageUserName()+"/"+d.getApplicantID(),j={};c=f.getFileNameArray();for(e=0,g=c.length;e<g;e+=1)j=a.getItem(i+"/"+c[e]),j&&b.push({name:j.name,creation_date:j.creation_date,last_modified:j.last_modified});d.done(b)},100)},d.removeDocument=function(){setTimeout(function(){var b="jio/local/"+d.getStorageUserName()+"/"+d.getApplicantID()+"/"+d.getFileName();return a.deleteItem(b),f.removeFileName(d.getFileName()),d.done()},100)},d},g=function(a,d){var f=e.newBaseStorage(a,d);return f.mkcol=function(a){var d=b.extend({success:function(){},error:function(){}},a),e=["split_path"],g="temp/path";if(!d.pathsteps)d.pathsteps=1,f.mkcol(d);else{e=d.path.split("/");if(d.pathsteps>=e.length-1)return d.success();e.length=d.pathsteps+1,d.pathsteps++,g=e.join("/"),b.ajax({url:d.url+g,type:"MKCOL",async:!0,headers:{Authorization:"Basic "+c.encode(d.user_name+":"+d.password),Depth:"1"},success:function(){f.mkcol(d)},error:function(a){d.error()}})}},f.checkNameAvailability=function(){b.ajax({url:f.getStorageURL()+"/dav/"+f.getStorageUserName()+"/",async:!0,type:"PROPFIND",dataType:"xml",headers:{Authorization:"Basic "+c.encode(f.getStorageUserName()+":"+f.getStoragePassword()),Depth:"1"},success:function(a){f.done(!1)},error:function(a){a.status===404?f.done(!0):(a.message='Cannot check availability of "'+f.getUserName()+'" into DAVStorage.',f.fail(a))}})},f.saveDocument=function(){b.ajax({url:f.getStorageURL()+"/dav/"+f.getStorageUserName()+"/"+f.getApplicantID()+"/"+f.getFileName(),type:"PUT",data:f.getFileContent(),async:!0,dataType:"text",headers:{Authorization:"Basic "+c.encode(f.getStorageUserName()+":"+f.getStoragePassword())},success:function(){f.done()},error:function(a){a.message='Cannot save "'+f.getFileName()+'" into DAVStorage.',f.fail(a)}})},f.loadDocument=function(){var a={},d=f.cloneOptionObject(),e=function(){b.ajax({url:f.getStorageURL()+"/dav/"+f.getStorageUserName()+"/"+f.getApplicantID()+"/"+f.getFileName(),type:"GET",async:!0,dataType:"text",headers:{Authorization:"Basic "+c.encode(f.getStorageUserName()+":"+f.getStoragePassword())},success:function(b){a.content=b,f.done(a)},error:function(a){a.status===404?a.message='Document "'+f.getFileName()+'" not found in localStorage.':a.message='Cannot load "'+f.getFileName()+'" from DAVStorage.',f.fail(a)}})};a.name=f.getFileName();if(d.content_only){e();return}b.ajax({url:f.getStorageURL()+"/dav/"+f.getStorageUserName()+"/"+f.getApplicantID()+"/"+f.getFileName(),type:"PROPFIND",async:!0,dataType:"xml",headers:{Authorization:"Basic "+c.encode(f.getStorageUserName()+":"+f.getStoragePassword())},success:function(c){b(c).find("lp1\\:getlastmodified, getlastmodified").each(function(){a.last_modified=b(this).text()}),b(c).find("lp1\\:creationdate, creationdate").each(function(){a.creation_date=b(this).text()}),d.metadata_only?f.done(a):e()},error:function(a){a.message='Cannot load "'+f.getFileName()+'" informations from DAVStorage.',f.fail(a)}})},f.getDocumentList=function(){var a=[],d={},e=[];b.ajax({url:f.getStorageURL()+"/dav/"+f.getStorageUserName()+"/"+f.getApplicantID()+"/",async:!0,type:"PROPFIND",dataType:"xml",headers:{Authorization:"Basic "+c.encode(f.getStorageUserName()+":"+f.getStoragePassword()),Depth:"1"},success:function(c){b(c).find("D\\:response, response").each(function(c,f){if(c>0){d={},b(f).find("D\\:href, href").each(function(){e=b(this).text().split("/"),d.name=e[e.length-1]?e[e.length-1]:e[e.length-2]+"/"});if(d.name===".htaccess"||d.name===".htpasswd")return;b(f).find("lp1\\:getlastmodified, getlastmodified").each(function(){d.last_modified=b(this).text()}),b(f).find("lp1\\:creationdate, creationdate").each(function(){d.creation_date=b(this).text()}),a.push(d)}}),f.done(a)},error:function(a){a.message="Cannot get a document list from DAVStorage.",f.fail(a)}})},f.removeDocument=function(){b.ajax({url:f.getStorageURL()+"/dav/"+f.getStorageUserName()+"/"+f.getApplicantID()+"/"+f.getFileName(),type:"DELETE",async:!0,headers:{Authorization:"Basic "+c.encode(f.getStorageUserName()+":"+f.getStoragePassword())},success:function(){f.done()},error:function(a){a.status===404?f.done():(a.message='Cannot remove "'+f.getFileName()+'" from DAVStorage.',f.fail(a))}})},f},h=function(a,b){var c=e.newBaseStorage(a,b),d={};return d.storageArray=c.getStorageArray(),d.length=d.storageArray.length,d.return_value_array=[],d.max_tries=c.getMaxTries(),c.setMaxTries(1),d.execJobsFromStorageArray=function(a){var b={},e;for(e=0;e<d.storageArray.length;e+=1)b=c.cloneJob(),b.max_tries=d.max_tries,b.storage=d.storageArray[e],b.callback=a,c.addJob(b)},c.checkNameAvailability=function(){var a="id",b=!1,e=[],f={status:"done"},g=function(a){d.return_value_array.push(a);if(!b){if(a.status==="fail")f.status="fail",e.push(a.error);else if(a.return_value===!1){c.done(!1),b=!0;return}if(d.return_value_array.length===d.length){f.status==="fail"?c.fail({status:207,statusText:"Multi-Status",message:'Some check availability of "'+c.getUserName()+'" requests have failed.',array:e}):c.done(!0),b=!0;return}}};d.execJobsFromStorageArray(g)},c.saveDocument=function(){var a={status:"done"},b="id",e=!1,f=[],g=function(a){d.return_value_array.push(a),e||(a.status!=="fail"?(c.done(),e=!0):(f.push(a.error),d.return_value_array.length===d.length&&c.fail({status:207,statusText:"Multi-Status",message:'All save "'+c.getFileName()+'" requests have failed.',array:f})))};d.execJobsFromStorageArray(g)},c.loadDocument=function(){var a={},b="id",e=!1,f=[],g={status:"done"},h=function(a){d.return_value_array.push(a),e||(a.status!=="fail"?(c.done(a.return_value),e=!0):(f.push(a.error),d.return_value_array.length===d.length&&c.fail({status:207,statusText:"Multi-Status",message:'All load "'+c.getFileName()+'" requests have failed.',array:f})))};d.execJobsFromStorageArray(h)},c.getDocumentList=function(){var a={status:"done"},b="id",e=!1,f=[],g=function(a){d.return_value_array.push(a),e||(a.status!=="fail"?(c.done(a.return_value),e=!0):(f.push(a.error),d.return_value_array.length===d.length&&c.fail({status:207,statusText:"Multi-Status",message:"All get document list requests have failed",array:f})))};d.execJobsFromStorageArray(g)},c.removeDocument=function(){var a={status:"done"},b="key",e=!1,f=[],g=function(a){d.return_value_array.push(a),e||(a.status!=="fail"?(c.done(),e=!0):(f.push(a.error),d.return_value_array.length===d.length&&c.fail({status:207,statusText:"Multi-Status",message:'All remove "'+c.getFileName()+'" requests have failed.',array:f})))};d.execJobsFromStorageArray(g)},c},i=function(b,c){var d=e.newBaseStorage(b,c),f={};return f.storage_array_name="jio/indexed_storage_array",f.storage_file_array_name="jio/indexed_file_array/"+JSON.stringify(d.getSecondStorage())+"/"+d.getApplicantID(),f.indexedStorageArrayExists=function(){return a.getItem(f.storage_array_name)?!0:!1},f.getIndexedStorageArray=function(){return a.getItem(f.storage_array_name)||[]},f.addIndexedStorage=function(b){var c=f.getIndexedStorageArray();c.push(JSON.stringify(b)),a.setItem(f.storage_array_name,c)},f.isAnIndexedStorage=function(a){var b=JSON.stringify(a),c,d,e=f.getIndexedStorageArray();for(c=0,d=e.length;c<d;c+=1)if(JSON.stringify(e[c])===b)return!0;return!1},f.fileArrayExists=function(){return a.getItem(f.storage_file_array_name)?!0:!1},f.getFileArray=function(){return a.getItem(f.storage_file_array_name)||[]},f.setFileArray=function(b){return a.setItem(f.storage_file_array_name,b)},f.isFileIndexed=function(a){var b,c,d=f.getFileArray();for(b=0,c=d.length;b<c;b+=1)if(d[b].name===a)return!0;return!1},f.addFile=function(b){var c=f.getFileArray();c.push(b),a.setItem(f.storage_file_array_name,c)},f.removeFile=function(b){var c,d,e=f.getFileArray(),g=[];for(c=0,d=e.length;c<d;c+=1)e[c].name!==b&&g.push(e[c]);a.setItem(f.storage_file_array_name,g)},f.update=function(a){var b=function(a){a.status==="done"&&(f.isAnIndexedStorage(d.getSecondStorage())||f.addIndexedStorage(d.getSecondStorage()),f.setFileArray(a.return_value))},c={storage:d.getSecondStorage(),applicant:{ID:d.getApplicantID()},method:"getDocumentList",max_tries:3,callback:b};d.addJob(c)},d.checkNameAvailability=function(){var a=d.cloneJob();f.update(),a.storage=d.getSecondStorage(),a.callback=function(a){a.status==="done"?d.done(a.return_value):d.fail(a.error)},d.addJob(a)},d.saveDocument=function(){var a=d.cloneJob();a.storage=d.getSecondStorage(),a.callback=function(a){a.status==="done"?(f.isFileIndexed(d.getFileName())||f.addFile({name:d.getFileName(),last_modified:0,creation_date:0}),f.update(),d.done()):d.fail(a.error)},d.addJob(a)},d.loadDocument=function(){var a,b,c,e,g=function(a){a.status==="done"?d.done(a.return_value):d.fail(a.error)},h=function(){e=d.cloneJob(),e.storage=d.getSecondStorage(),e.callback=g,d.addJob(e)},i=d.cloneOptionObject();f.update(),i.metadata_only?setTimeout(function(){if(f.fileArrayExists()){a=f.getFileArray();for(b=0,c=a.length;b<c;b+=1)if(a[b].name===d.getFileName())return d.done(a[b])}else h()},100):h()},d.getDocumentList=function(){var a;f.update(),a=setInterval(function(){f.fileArrayExists()&&(d.done(f.getFileArray()),clearInterval(a))},100)},d.removeDocument=function(){var a=d.cloneJob();a.storage=d.getSecondStorage(),a.callback=function(a){a.status==="done"?(f.removeFile(d.getFileName()),f.update(),d.done()):d.fail(a.error)},d.addJob(a)},d},j=function(a,c){var f=e.newBaseStorage(a,c),g={};return 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,c){var e=d.encrypt(f.getStorageUserName()+":"+f.getStoragePassword(),a,g.encrypt_param_object);b(JSON.parse(e).ct,c)},g.decrypt=function(a,c,e,h){var i,j=b.extend(!0,{},g.decrypt_param_object);j.ct=a||"",j=JSON.stringify(j);try{i=d.decrypt(f.getStorageUserName()+":"+f.getStoragePassword(),j)}catch(k){c({status:0,statusText:"Decrypt Fail",message:"Unable to decrypt."},e,h);return}c(i,e,h)},f.checkNameAvailability=function(){var a=f.cloneJob();a.storage=f.getSecondStorage(),a.callback=function(a){a.status==="done"?f.done(a.return_value):f.fail(a.error)},f.addJob(a)},f.saveDocument=function(){var a,b,c,d=function(){g.encrypt(f.getFileName(),function(a){b=a,e()})},e=function(){g.encrypt(f.getFileContent(),function(a){c=a,h()})},h=function(){a=f.cloneJob(),a.name=b,a.content=c,a.storage=f.getSecondStorage(),a.callback=function(a){a.status==="done"?f.done():f.fail(a.error)},f.addJob(a)};d()},f.loadDocument=function(){var a,b,c=f.cloneOptionObject(),d=function(){g.encrypt(f.getFileName(),function(a){b=a,e()})},e=function(){a=f.cloneJob(),a.name=b,a.storage=f.getSecondStorage(),a.callback=h,f.addJob(a)},h=function(a){a.status==="done"?(a.return_value.name=f.getFileName(),c.metadata_only?f.done(a.return_value):g.decrypt(a.return_value.content,function(b){typeof b=="object"?f.fail({status:0,statusText:"Decrypt Fail",message:"Unable to decrypt"}):(a.return_value.content=b,f.done(a.return_value))})):f.fail(a.error)};d()},f.getDocumentList=function(){var a,b,c,d=0,e,h=!0,i=function(){a=f.cloneJob(),a.storage=f.getSecondStorage(),a.callback=j,f.addJob(a)},j=function(a){if(a.status==="done"){e=a.return_value;for(b=0,c=e.length;b<c;b+=1)g.decrypt(e[b].name,k,b,"name")}else f.fail(a.error)},k=function(a,b,g){var i;d++;if(typeof a=="object"){h&&f.fail({status:0,statusText:"Decrypt Fail",message:"Unable to decrypt."}),h=!1;return}e[b][g]=a,d===c&&h&&f.done(e)};i()},f.removeDocument=function(){var a,b,c=function(){g.encrypt(f.getFileName(),function(a){b=a,d()})},d=function(){a=f.cloneJob(),a.name=b,a.storage=f.getSecondStorage(),a.callback=e,f.addJob(a)},e=function(a){a.status==="done"?f.done():f.fail(a.error)};c()},f},e.addStorageType("local",f),e.addStorageType("dav",g),e.addStorageType("replicate",h),e.addStorageType("indexed",i),e.addStorageType("crypted",j)};window.requirejs?define("JIOStorages",["LocalOrCookieStorage","jQuery","Base64","SJCL","JIO"],a):a(LocalOrCookieStorage,jQuery,Base64,sjcl,JIO)})();
\ No newline at end of file \ No newline at end of file
...@@ -1089,17 +1089,47 @@ ...@@ -1089,17 +1089,47 @@
var that = Jio.newBaseStorage( spec, my ), priv = {}; var that = Jio.newBaseStorage( spec, my ), priv = {};
// TODO : IT IS NOT SECURE AT ALL!
// WE MUST REWORK CRYPTED STORAGE!
priv.encrypt_param_object = {
"iv":"kaprWwY/Ucr7pumXoTHbpA",
"v":1,
"iter":1000,
"ks":256,
"ts":128,
"mode":"ccm",
"adata":"",
"cipher":"aes",
"salt":"K4bmZG9d704"
};
priv.decrypt_param_object = {
"iv":"kaprWwY/Ucr7pumXoTHbpA",
"ks":256,
"ts":128,
"salt":"K4bmZG9d704"
};
priv.encrypt = function (data,callback,index) { priv.encrypt = function (data,callback,index) {
// end with a callback in order to improve encrypt to an // end with a callback in order to improve encrypt to an
// asynchronous encryption. // asynchronous encryption.
var tmp = sjcl.encrypt (that.getStorageUserName()+':'+ var tmp = sjcl.encrypt (that.getStorageUserName()+':'+
that.getStoragePassword(), data); that.getStoragePassword(), data,
callback(tmp,index); priv.encrypt_param_object);
callback(JSON.parse(tmp).ct,index);
}; };
priv.decrypt = function (data,callback,index) { priv.decrypt = function (data,callback,index,key) {
var tmp = sjcl.decrypt (that.getStorageUserName()+':'+ var tmp, param = $.extend(true,{},priv.decrypt_param_object);
that.getStoragePassword(), data); param.ct = data || '';
callback(tmp,index); param = JSON.stringify (param);
try {
tmp = sjcl.decrypt (that.getStorageUserName()+':'+
that.getStoragePassword(),
param);
} catch (e) {
callback({status:0,statusText:'Decrypt Fail',
message:'Unable to decrypt.'},index,key);
return;
}
callback(tmp,index,key);
}; };
/** /**
...@@ -1132,15 +1162,10 @@ ...@@ -1132,15 +1162,10 @@
}); });
}, },
_2 = function () { _2 = function () {
priv.encrypt( priv.encrypt(that.getFileContent(),function(res) {
JSON.stringify({ newfilecontent = res;
name: that.getFileName(), _3();
content:that.getFileContent() });
}),
function(res) {
newfilecontent = res;
_3();
});
}, },
_3 = function () { _3 = function () {
new_job = that.cloneJob(); new_job = that.cloneJob();
...@@ -1166,7 +1191,7 @@ ...@@ -1166,7 +1191,7 @@
* @method loadDocument * @method loadDocument
*/ */
that.loadDocument = function () { that.loadDocument = function () {
var new_job, new_file_name, var new_job, new_file_name, option = that.cloneOptionObject(),
_1 = function () { _1 = function () {
priv.encrypt(that.getFileName(),function(res) { priv.encrypt(that.getFileName(),function(res) {
new_file_name = res; new_file_name = res;
...@@ -1178,15 +1203,31 @@ ...@@ -1178,15 +1203,31 @@
new_job.name = new_file_name; new_job.name = new_file_name;
new_job.storage = that.getSecondStorage(); new_job.storage = that.getSecondStorage();
new_job.callback = loadCallback; new_job.callback = loadCallback;
console.log (new_job);
that.addJob ( new_job ); that.addJob ( new_job );
}, },
loadCallback = function (result) { loadCallback = function (result) {
if (result.status === 'done') { if (result.status === 'done') {
priv.decrypt (result.return_value.content,function(res){ result.return_value.name = that.getFileName();
that.done(JSON.parse(res)); if (option.metadata_only) {
}); that.done(result.return_value);
} else {
priv.decrypt (result.return_value.content,function(res){
if (typeof res === 'object') {
that.fail({status:0,statusText:'Decrypt Fail',
message:'Unable to decrypt'});
} else {
result.return_value.content = res;
// content only: the second storage should
// manage content_only option, so it is not
// necessary to manage it.
that.done(result.return_value);
}
});
}
} else { } else {
// NOTE : we can re create an error object instead of
// keep the old ex:status=404,message="document 1y59gyl8g
// not found in localStorage"...
that.fail(result.error); that.fail(result.error);
} }
}; };
...@@ -1198,7 +1239,7 @@ ...@@ -1198,7 +1239,7 @@
* @method getDocumentList * @method getDocumentList
*/ */
that.getDocumentList = function () { that.getDocumentList = function () {
var new_job, i, l, cpt = 0, array, var new_job, i, l, cpt = 0, array, ok = true,
_1 = function () { _1 = function () {
new_job = that.cloneJob(); new_job = that.cloneJob();
new_job.storage = that.getSecondStorage(); new_job.storage = that.getSecondStorage();
...@@ -1209,20 +1250,29 @@ ...@@ -1209,20 +1250,29 @@
if (result.status === 'done') { if (result.status === 'done') {
array = result.return_value; array = result.return_value;
for (i = 0, l = array.length; i < l; i+= 1) { for (i = 0, l = array.length; i < l; i+= 1) {
priv.decrypt (array[i], // cpt--;
lastCallback,i); priv.decrypt (array[i].name,
lastCallback,i,'name');
// priv.decrypt (array[i].content,
// lastCallback,i,'content');
} }
} else { } else {
that.fail(result.error); that.fail(result.error);
} }
}, },
lastCallback = function (res,index) { lastCallback = function (res,index,key) {
var tmp; var tmp;
cpt++; cpt++;
tmp = JSON.parse(res); if (typeof res === 'object') {
array[index] = res.name; if (ok) {
array[index] = res.content; that.fail({status:0,statusText:'Decrypt Fail',
if (cpt === l) { message:'Unable to decrypt.'});
}
ok = false;
return;
}
array[index][key] = res;
if (cpt === l && ok) {
// this is the last callback // this is the last callback
that.done(array); that.done(array);
} }
...@@ -1235,16 +1285,28 @@ ...@@ -1235,16 +1285,28 @@
* @method removeDocument * @method removeDocument
*/ */
that.removeDocument = function () { that.removeDocument = function () {
var new_job = that.cloneJob(); var new_job, new_file_name,
new_job.storage = that.getSecondStorage(); _1 = function () {
new_job.callback = function (result) { priv.encrypt(that.getFileName(),function(res) {
new_file_name = res;
_2();
});
},
_2 = function () {
new_job = that.cloneJob();
new_job.name = new_file_name;
new_job.storage = that.getSecondStorage();
new_job.callback = removeCallback;
that.addJob(new_job);
},
removeCallback = function (result) {
if (result.status === 'done') { if (result.status === 'done') {
that.done(); that.done();
} else { } else {
that.fail(result.error); that.fail(result.error);
} }
}; };
that.addJob(new_job); _1();
}; };
return that; return that;
}; };
......
...@@ -24,6 +24,13 @@ var getXML = function (url) { ...@@ -24,6 +24,13 @@ var getXML = function (url) {
dataType:'text',success:function(xml){tmp=xml;}}); dataType:'text',success:function(xml){tmp=xml;}});
return tmp; return tmp;
}, },
objectifyDocumentArray = function (array) {
var obj = {}, k;
for (k = 0; k < array.length; k += 1) {
obj[array[k].name] = array[k];
}
return obj;
},
addFile = function (user,appid,file) { addFile = function (user,appid,file) {
var i, l, found = false, filenamearray, var i, l, found = false, filenamearray,
userarray = LocalOrCookieStorage.getItem('jio/local_user_array') || []; userarray = LocalOrCookieStorage.getItem('jio/local_user_array') || [];
...@@ -408,13 +415,6 @@ test ('Get document list', function () { ...@@ -408,13 +415,6 @@ test ('Get document list', function () {
doc1 = {}, doc2 = {}, doc1 = {}, doc2 = {},
mytest = function (value){ mytest = function (value){
o.f = function (result) { o.f = function (result) {
var objectifyDocumentArray = function (array) {
var obj = {}, k;
for (k = 0; k < array.length; k+=1) {
obj[array[k].name] = array[k];
}
return obj;
};
deepEqual (objectifyDocumentArray(result.return_value), deepEqual (objectifyDocumentArray(result.return_value),
objectifyDocumentArray(value),'getting list'); objectifyDocumentArray(value),'getting list');
}; };
...@@ -625,13 +625,6 @@ test ('Get Document List', function () { ...@@ -625,13 +625,6 @@ test ('Get Document List', function () {
[errnoprop,{'Content-Type':'text/xml; charset="utf-8"'}, [errnoprop,{'Content-Type':'text/xml; charset="utf-8"'},
davlist]); davlist]);
o.f = function (result) { o.f = function (result) {
var objectifyDocumentArray = function (array) {
var obj = {}, k;
for (k = 0; k < array.length; k += 1) {
obj[array[k].name] = array[k];
}
return obj;
};
if (result.status === 'fail') { if (result.status === 'fail') {
deepEqual (result.return_value, value, message); deepEqual (result.return_value, value, message);
} else { } else {
...@@ -824,13 +817,6 @@ test ('Get Document List', function () { ...@@ -824,13 +817,6 @@ test ('Get Document List', function () {
var o = {}, clock = this.sandbox.useFakeTimers(), t = this, var o = {}, clock = this.sandbox.useFakeTimers(), t = this,
mytest = function (message,value) { mytest = function (message,value) {
o.f = function (result) { o.f = function (result) {
var objectifyDocumentArray = function (array) {
var obj = {}, k;
for (k = 0; k < array.length; k += 1) {
obj[array[k].name] = array[k];
}
return obj;
};
deepEqual (objectifyDocumentArray(result.return_value), deepEqual (objectifyDocumentArray(result.return_value),
objectifyDocumentArray(value),'getting list'); objectifyDocumentArray(value),'getting list');
}; };
...@@ -1028,10 +1014,11 @@ test ('Check name availability' , function () { ...@@ -1028,10 +1014,11 @@ test ('Check name availability' , function () {
test ('Document save' , function () { test ('Document save' , function () {
var o = {}, clock = this.sandbox.useFakeTimers(); var o = {}, clock = this.sandbox.useFakeTimers();
o.jio=JIO.newJio({type:'crypted', o.jio=JIO.newJio({type:'crypted',
password:'mypwd', user_name:'cryptsave',
storage:{type:'local', password:'mypwd',
user_name:'cryptsave'}}, storage:{type:'local',
{ID:'jiotests'}); user_name:'cryptsavelocal'}},
{ID:'jiotests'});
o.f = function (result) { o.f = function (result) {
deepEqual (result.status,'done','save ok'); deepEqual (result.status,'done','save ok');
}; };
...@@ -1042,16 +1029,28 @@ test ('Document save' , function () { ...@@ -1042,16 +1029,28 @@ test ('Document save' , function () {
if (!o.f.calledOnce) { if (!o.f.calledOnce) {
ok (false, 'no response / too much results'); ok (false, 'no response / too much results');
} }
// encrypt 'testsave' with 'cryptsave:mypwd' password
o.tmp = LocalOrCookieStorage.getItem(
'jio/local/cryptsavelocal/jiotests/rZx5PJxttlf9QpZER/5x354bfX54QFa1');
if (o.tmp) {
delete o.tmp.last_modified;
delete o.tmp.creation_date;
}
deepEqual (o.tmp,
{name:'rZx5PJxttlf9QpZER/5x354bfX54QFa1',
content:'upZkPIpitF3QMT/DU5jM3gP0SEbwo1n81rMOfLE'},
'Check if the document is realy crypted');
o.jio.stop(); o.jio.stop();
}); });
test ('Document Load' , function () { test ('Document Load' , function () {
var o = {}, clock = this.sandbox.useFakeTimers(); var o = {}, clock = this.sandbox.useFakeTimers();
o.jio=JIO.newJio({type:'crypted', o.jio=JIO.newJio({type:'crypted',
password:'mypwd', user_name:'cryptload',
storage:{type:'local', password:'mypwd',
user_name:'cryptload'}}, storage:{type:'local',
{ID:'jiotests'}); user_name:'cryptloadlocal'}},
{ID:'jiotests'});
o.f = function (result) { o.f = function (result) {
if (result.status === 'done') { if (result.status === 'done') {
deepEqual (result.return_value,{name:'testload', deepEqual (result.return_value,{name:'testload',
...@@ -1064,6 +1063,13 @@ test ('Document Load' , function () { ...@@ -1064,6 +1063,13 @@ test ('Document Load' , function () {
} }
}; };
this.spy(o,'f'); this.spy(o,'f');
// encrypt 'testload' with 'cryptload:mypwd' password
// and 'contentoftest' with 'cryptload:mypwd'
LocalOrCookieStorage.setItem(
'jio/local/cryptloadlocal/jiotests/hiG4H80pwkXCCrlLl1X0BD0BfWLZwDUX',
{name:'mRyQFcUvUKq6tLGUjBo34P3oc2LPxEju',
content:'kSulH8Qo105dSKHcY2hEBXWXC9b+3PCEFSm1k7k',
last_modified:500,creation_date:500});
o.jio.loadDocument({name:'testload', o.jio.loadDocument({name:'testload',
max_tries:1,callback:o.f}); max_tries:1,callback:o.f});
clock.tick(1000); clock.tick(1000);
...@@ -1071,8 +1077,90 @@ test ('Document Load' , function () { ...@@ -1071,8 +1077,90 @@ test ('Document Load' , function () {
ok (false, 'no response / too much results'); ok (false, 'no response / too much results');
} }
o.jio.stop(); o.jio.stop();
LocalOrCookieStorage.deleteItem(
'jio/local/cryptloadlocal/jiotests/hiG4H80pwkXCCrlLl1X0BD0BfWLZwDUX');
});
test ('Get Document List', function () {
var o = {}, clock = this.sandbox.useFakeTimers();
o.jio=JIO.newJio({type:'crypted',
user_name:'cryptgetlist',
password:'mypwd',
storage:{type:'local',
user_name:'cryptgetlistlocal'}},
{ID:'jiotests'});
o.f = function (result) {
if (result.status === 'done') {
deepEqual (objectifyDocumentArray(result.return_value),
objectifyDocumentArray(o.doc_list),'Getting list');
} else {
console.warn (result);
ok (false, 'Cannot get list');
}
};
this.spy(o,'f');
o.doc_list = [
{name:'testgetlist1',last_modified:500,creation_date:200},
{name:'testgetlist2',last_modified:300,creation_date:300}
];
o.doc_encrypt_list = [
{name:'541eX0WTMDw7rqIP7Ofxd1nXlPOtejxGnwOzMw',
content:'/4dBPUdmLolLfUaDxPPrhjRPdA',
last_modified:500,creation_date:200},
{name:'541eX0WTMDw7rqIMyJ5tx4YHWSyxJ5UjYvmtqw',
content:'/4FBALhweuyjxxD53eFQDSm4VA',
last_modified:300,creation_date:300}
];
// encrypt with 'cryptgetlist:mypwd' as password
LocalOrCookieStorage.setItem(
'jio/local_file_name_array/cryptgetlistlocal/jiotests',
[o.doc_encrypt_list[0].name,o.doc_encrypt_list[1].name]);
LocalOrCookieStorage.setItem(
'jio/local/cryptgetlistlocal/jiotests/'+o.doc_encrypt_list[0].name,
o.doc_encrypt_list[0]);
LocalOrCookieStorage.setItem(
'jio/local/cryptgetlistlocal/jiotests/'+o.doc_encrypt_list[1].name,
o.doc_encrypt_list[1]);
o.jio.getDocumentList({max_tries:1,callback:o.f});
clock.tick (2000);
if (!o.f.calledOnce) {
ok (false, 'no response / too much results');
}
clock.tick(1000);
o.jio.stop();
}); });
// end require
test ('Remove document', function () {
var o = {}, clock = this.sandbox.useFakeTimers();
o.jio=JIO.newJio({type:'crypted',
user_name:'cryptremove',
password:'mypwd',
storage:{type:'local',
user_name:'cryptremovelocal'}},
{ID:'jiotests'});
o.f = function (result) {
deepEqual (result.status,'done','Document remove');
};
this.spy(o,'f');
// encrypt with 'cryptremove:mypwd' as password
LocalOrCookieStorage.setItem(
'jio/local_file_name_array/cryptremovelocal/jiotests',
["JqCLTjyxQqO9jwfxD/lyfGIX+qA"]);
LocalOrCookieStorage.setItem(
'jio/local/cryptremovelocal/jiotests/JqCLTjyxQqO9jwfxD/lyfGIX+qA',
{"name":"JqCLTjyxQqO9jwfxD/lyfGIX+qA",
"content":"LKaLZopWgML6IxERqoJ2mUyyO",
"creation_date":500,
"last_modified":500});
o.jio.removeDocument({name:'file',max_tries:1,callback:o.f});
clock.tick(1000);
if (!o.f.calledOnce){
ok (false, 'no response / too much results');
}
o.jio.stop();
});
}; // end thisfun }; // end thisfun
if (window.requirejs) { if (window.requirejs) {
......
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