Commit 45ed5ca3 authored by Tristan Cavelier's avatar Tristan Cavelier

Adding conflictmanagerstorage.

Only saveDocument is implemented yet, but it is not complete.
parent 184405dc
......@@ -20,6 +20,7 @@ module.exports = function(grunt) {
'<file_strip_banner:../../src/<%= pkg.name %>/replicatestorage.js>',
'<file_strip_banner:../../src/<%= pkg.name %>/indexstorage.js>',
'<file_strip_banner:../../src/<%= pkg.name %>/cryptstorage.js>',
'<file_strip_banner:../../src/<%= pkg.name %>/conflictmanagerstorage.js>',
'<file_strip_banner:../../src/<%= pkg.name %>/outro.js>'],
dest: '../../lib/jio/<%= pkg.name %>.js'
}
......@@ -59,6 +60,7 @@ module.exports = function(grunt) {
sjcl: true,
LocalOrCookieStorage: true,
Base64: true,
MD5: true,
jio: true,
console: true,
unescape: true,
......
/*! JIO Storage - v0.1.0 - 2012-06-18
/*! JIO Storage - v0.1.0 - 2012-06-21
* Copyright (c) 2012 Nexedi; Licensed */
(function(LocalOrCookieStorage, $, Base64, sjcl, Jio) {
(function(LocalOrCookieStorage, $, Base64, sjcl, MD5, Jio) {
var newLocalStorage = function ( spec, my ) {
var that = Jio.storage( spec, my, 'base' ), priv = {};
......@@ -570,6 +570,7 @@ Jio.addStorageType('replicate', newReplicateStorage);
var newIndexStorage = function ( spec, my ) {
var that = Jio.storage( spec, my, 'handler' ), priv = {};
var validatestate_secondstorage = spec.storage || false;
priv.secondstorage_spec = spec.storage || {type:'base'};
priv.secondstorage_string = JSON.stringify (priv.secondstorage_spec);
......@@ -585,7 +586,7 @@ var newIndexStorage = function ( spec, my ) {
};
that.validateState = function () {
if (priv.secondstorage_string === JSON.stringify ({type:'base'})) {
if (!validatestate_secondstorage) {
return 'Need at least one parameter: "storage" '+
'containing storage specifications.';
}
......@@ -1097,4 +1098,246 @@ var newCryptedStorage = function ( spec, my ) {
};
Jio.addStorageType('crypt', newCryptedStorage);
}( LocalOrCookieStorage, jQuery, Base64, sjcl, jio ));
var newConflictManagerStorage = function ( spec, my ) {
var that = Jio.storage( spec, my, 'handler' ), priv = {};
var local_namespace = 'jio/conflictmanager/';
priv.username = spec.username || '';
var storage_exists = (spec.storage?true:false);
priv.secondstorage_spec = spec.storage || {type:'base'};
var super_serialized = that.serialized;
that.serialized = function () {
var o = super_serialized();
o.storage = priv.secondstorage_spec;
return o;
};
that.validateState = function () {
if (!priv.username || storage_exists) {
return 'Need at least two parameter: "owner" and "storage" '+
'.';
}
return '';
};
priv.isTheLatestVersion = function (local,distant) {
var k;
if (!distant.owner) {
return true;
}
for (k in distant.owner) {
if (k !== priv.username) {
if (local.winner.version <= distant.owner[k].last_version) {
return false;
}
}
}
return true;
};
priv.conflictResearch = function () {
// TODO : ;
};
/**
* Save a document and can manage conflicts.
* @method saveDocument
*/
that.saveDocument = function (command) {
var metadata_file_name = command.getPath() + '.metadata',
now = new Date(),
local_metadata_file_name = local_namespace + metadata_file_name,
local_file_metadata = {}, // local file.metadata
command_file_metadata = {}, // distant file.metadata
run_index = 0,
end = false, is_a_new_file = false,
previous_revision = 0,
local_file_hash = MD5 (command.getContent()),
run = function (index) {
switch (index) {
case 0:
run_index = 3;
run (2);
run (1);
break;
case 1: // update local metadata
var new_owner_object = {revision:0,hash:'',
last_modified:0,
creation_date:now.getTime()};
local_file_metadata =
LocalOrCookieStorage.getItem (local_metadata_file_name);
if ( local_file_metadata ) {
// if metadata already exists
if ( !local_file_metadata.owner[priv.username] ) {
local_file_metadata.owner[priv.username] =
new_owner_object;
}
} else {
local_file_metadata = {
winner: {},
owner: {},
conflict_list: []
};
local_file_metadata.winner = {
revision:0,owner:priv.username,hash:''};
local_file_metadata.owner[priv.username] =
new_owner_object;
}
run_index ++; run (run_index);
break;
case 2: // load metadata from distant
var cloned_option = command.cloneOption ();
cloned_option.onResponse = function () {};
cloned_option.onFail = function (error) {
if (error.status === 404) {
command_file_metadata = local_file_metadata;
run_index ++; run (run_index);
} else {
run_index = (-10);
that.fail(error);
end = true;
}
};
cloned_option.onDone = function (result) {
command_file_metadata = JSON.parse (result.content);
run_index ++; run (run_index);
};
var newcommand = that.newCommand(
'loadDocument',{path:metadata_file_name,
option:cloned_option});
that.addJob ( that.newStorage (priv.secondstorage_spec),
newcommand );
break;
// wait for 1 and 2
case 5: // check conflicts
var updateCommandMetadata = function () {
var original_creation_date;
original_creation_date = command_file_metadata.owner[
command_file_metadata.winner.owner].
creation_date || now.getTime();
if (command_file_metadata.owner[priv.username]) {
previous_revision = command_file_metadata.owner[
priv.username].revision;
} else {
command_file_metadata.owner[priv.username] = {};
}
command_file_metadata.winner.owner = priv.username;
command_file_metadata.winner.revision ++;
command_file_metadata.winner.hash = local_file_hash;
command_file_metadata.owner[priv.username].revision =
command_file_metadata.winner.revision;
command_file_metadata.owner[priv.username].
last_modified = now.getTime();
command_file_metadata.owner[priv.username].
creation_date = original_creation_date;
command_file_metadata.owner[priv.username].hash =
local_file_hash;
};
// if this is a new file
if (is_a_new_file) {
updateCommandMetadata();
LocalOrCookieStorage.setItem (local_metadata_file_name,
command_file_metadata);
run_index = (98);
run (6); // save metadata
run (7); // save document revision
break;
}
if (local_file_metadata.winner.revision ===
command_file_metadata.winner.revision &&
local_file_metadata.winner.hash ===
command_file_metadata.winner.hash) {
// OK! Now, update distant metadata, store them and save
updateCommandMetadata();
LocalOrCookieStorage.setItem (local_metadata_file_name,
command_file_metadata);
run_index = 98;
run (6); // save metadata
run (7); // save document revision
} else {
// var conflict_hash = '';
// // gen hash
// conflict_hash = MD5 (JSON.stringify ({
// path: command.getPath()
// // TODO : ;
// }));
// // TODO : ;
// command_file_metadata.conflict_list.push ({
// label:'revision',
// hash: conflict_hash,
// path: command.getPath(),
// local_owner: {
// name: priv.username,
// revision: local_file_metadata.owner[
// priv.username].revision + 1,
// hash: local_file_hash
// },
// conflict_owner: {
// name: command_file_metadata.winner.owner,
// revision: command_file_metadata.winner.revision,
// hash: command_file_metadata.winner.hash
// }
// });
command.getOption('onConflict')();
run_index = (-10);
end = true;
that.fail(); // TODO
}
break;
case 6: // save metadata
console.log ('save metadata');
break;
case 7: // save document revision
console.log ('save document revision');
break;
case 100:
if (!end) {
end = true;
that.done();
return;
}
break;
default:
break;
}
};
run (0);
command.setMaxRetry (1);
};
/**
* Load a document from several storages, and send the first retreived
* document.
* @method loadDocument
*/
that.loadDocument = function (command) {
that.fail({message:'NIY'});
};
/**
* Get a document list from several storages, and returns the first
* retreived document list.
* @method getDocumentList
*/
that.getDocumentList = function (command) {
that.fail({message:'NIY'});
};
/**
* Remove a document from several storages.
* @method removeDocument
*/
that.removeDocument = function (command) {
that.fail({message:'NIY'});
};
return that;
};
Jio.addStorageType('replicate', newReplicateStorage);
}( LocalOrCookieStorage, jQuery, Base64, sjcl, MD5, jio ));
/*! JIO Storage - v0.1.0 - 2012-06-18
/*! JIO Storage - v0.1.0 - 2012-06-21
* Copyright (c) 2012 Nexedi; Licensed */
(function(a,b,c,d,e){var f=function(b,c){var d=e.storage(b,c,"base"),f={};f.username=b.username||"",f.applicationname=b.applicationname||"untitled";var g="jio/local_user_array",h="jio/local_file_name_array/"+f.username+"/"+f.applicationname,i=d.serialized;return d.serialized=function(){var a=i();return a.applicationname=f.applicationname,a.username=f.username,a},d.validateState=function(){return f.username?"":'Need at least one parameter: "username".'},f.getUserArray=function(){return a.getItem(g)||[]},f.addUser=function(b){var c=f.getUserArray();c.push(b),a.setItem(g,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(h)||[]},f.addFileName=function(b){var c=f.getFileNameArray();c.push(b),a.setItem(h,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(h,g)},d.saveDocument=function(b){setTimeout(function(){var c=null,e="jio/local/"+f.username+"/"+f.applicationname+"/"+b.getPath();c=a.getItem(e),c?(c.last_modified=Date.now(),c.content=b.getContent()):(c={name:b.getPath(),content:b.getContent(),creation_date:Date.now(),last_modified:Date.now()},f.userExists(f.username)||f.addUser(f.username),f.addFileName(b.getPath())),a.setItem(e,c),d.done()},100)},d.loadDocument=function(b){setTimeout(function(){var c=null;c=a.getItem("jio/local/"+f.username+"/"+f.applicationname+"/"+b.getPath()),c?(b.getOption("metadata_only")&&delete c.content,d.done(c)):d.fail(b,{status:404,statusText:"Not Found.",message:'Document "'+b.getPath()+'" not found in localStorage.'})},100)},d.getDocumentList=function(b){setTimeout(function(){var c=[],e=[],g,h,i="key",j="jio/local/"+f.username+"/"+f.applicationname,k={};e=f.getFileNameArray();for(g=0,h=e.length;g<h;g+=1)k=a.getItem(j+"/"+e[g]),k&&(b.getOption("metadata_only")?c.push({name:k.name,creation_date:k.creation_date,last_modified:k.last_modified}):c.push({name:k.name,content:k.content,creation_date:k.creation_date,last_modified:k.last_modified}));d.done(c)},100)},d.removeDocument=function(b){setTimeout(function(){var c="jio/local/"+f.username+"/"+f.applicationname+"/"+b.getPath();a.deleteItem(c),f.removeFileName(b.getPath()),d.done()},100)},d};e.addStorageType("local",f);var g=function(a,d){var f=e.storage(a,d,"base"),g={};g.username=a.username||"",g.applicationname=a.applicationname||"untitled",g.url=a.url||"",g.password=a.password||"";var h=f.serialized;return f.serialized=function(){var a=h();return a.username=g.username,a.applicationname=g.applicationname,a.url=g.url,a.password=g.password,a},f.validateState=function(){return g.username&&g.url?"":'Need at least 2 parameters: "username" and "url".'},f.saveDocument=function(a){b.ajax({url:g.url+"/dav/"+g.username+"/"+g.applicationname+"/"+a.getPath(),type:"PUT",data:a.getContent(),async:!0,dataType:"text",headers:{Authorization:"Basic "+c.encode(g.username+":"+g.password)},success:function(){f.done()},error:function(b){b.message='Cannot save "'+a.getPath()+'" into DAVStorage.',f.fail(b)}})},f.loadDocument=function(a){var d={},e=function(){b.ajax({url:g.url+"/dav/"+g.username+"/"+g.applicationname+"/"+a.getPath(),type:"GET",async:!0,dataType:"text",headers:{Authorization:"Basic "+c.encode(g.username+":"+g.password)},success:function(a){d.content=a,f.done(d)},error:function(b){b.status===404?b.message='Document "'+a.getPath()+'" not found in localStorage.':b.message='Cannot load "'+a.getPath()+'" from DAVStorage.',f.fail(b)}})};d.name=a.getPath(),b.ajax({url:g.url+"/dav/"+g.username+"/"+g.applicationname+"/"+a.getPath(),type:"PROPFIND",async:!0,dataType:"xml",headers:{Authorization:"Basic "+c.encode(g.username+":"+g.password)},success:function(c){b(c).find("lp1\\:getlastmodified, getlastmodified").each(function(){d.last_modified=b(this).text()}),b(c).find("lp1\\:creationdate, creationdate").each(function(){d.creation_date=b(this).text()}),a.getOption("metadata_only")?f.done(d):e()},error:function(b){b.message='Cannot load "'+a.getPath()+'" informations from DAVStorage.',f.fail(b)}})},f.getDocumentList=function(a){var d=[],e={},h=[];b.ajax({url:g.url+"/dav/"+g.username+"/"+g.applicationname+"/",async:!0,type:"PROPFIND",dataType:"xml",headers:{Authorization:"Basic "+c.encode(g.username+":"+g.password),Depth:"1"},success:function(a){b(a).find("D\\:response, response").each(function(a,c){if(a>0){e={},b(c).find("D\\:href, href").each(function(){h=b(this).text().split("/"),e.name=h[h.length-1]?h[h.length-1]:h[h.length-2]+"/"});if(e.name===".htaccess"||e.name===".htpasswd")return;b(c).find("lp1\\:getlastmodified, getlastmodified").each(function(){e.last_modified=b(this).text()}),b(c).find("lp1\\:creationdate, creationdate").each(function(){e.creation_date=b(this).text()}),d.push(e)}}),f.done(d)},error:function(a){a.message="Cannot get a document list from DAVStorage.",f.fail(a)}})},f.removeDocument=function(a){b.ajax({url:g.url+"/dav/"+g.username+"/"+g.applicationname+"/"+a.getPath(),type:"DELETE",async:!0,headers:{Authorization:"Basic "+c.encode(g.username+":"+g.password)},success:function(){f.done()},error:function(a){a.status===404?f.done():(a.message='Cannot remove "'+f.getFileName()+'" from DAVStorage.',f.fail(a))}})},f};e.addStorageType("dav",g);var h=function(a,b){var c=e.storage(a,b,"handler"),d={};d.return_value_array=[],d.storagelist=a.storagelist||[],d.nb_storage=d.storagelist.length;var f=c.serialized;return c.serialized=function(){var a=f();return a.storagelist=d.storagelist,a},c.validateState=function(){return d.storagelist.length===0?'Need at least one parameter: "storagelist" containing at least one storage.':""},d.isTheLast=function(){return d.return_value_array.length===d.nb_storage},d.doJob=function(a,b){var e=!1,f=[],g,h=function(a){d.return_value_array.push(a)},i=function(a){e||(f.push(a),d.isTheLast()&&c.fail({status:207,statusText:"Multi-Status",message:b,array:f}))},j=function(a){e||(e=!0,c.done(a))};for(g=0;g<d.nb_storage;g+=1){var k=a.clone(),l=c.newStorage(d.storagelist[g]);k.onResponseDo(h),k.onFailDo(i),k.onDoneDo(j),c.addJob(l,k)}a.setMaxRetry(1)},c.saveDocument=function(a){d.doJob(a,'All save "'+a.getPath()+'" requests have failed.'),c.end()},c.loadDocument=function(a){d.doJob(a,'All load "'+a.getPath()+'" requests have failed.'),c.end()},c.getDocumentList=function(a){d.doJob(a,"All get document list requests have failed."),c.end()},c.removeDocument=function(a){d.doJob(a,'All remove "'+a.getPath()+'" requests have failed.'),c.end()},c};e.addStorageType("replicate",h);var i=function(b,c){var d=e.storage(b,c,"handler"),f={};f.secondstorage_spec=b.storage||{type:"base"},f.secondstorage_string=JSON.stringify(f.secondstorage_spec);var g="jio/indexed_storage_array",h="jio/indexed_file_array/"+f.secondstorage_string,i=d.serialized;return d.serialized=function(){var a=i();return a.storage=f.secondstorage_spec,a},d.validateState=function(){return f.secondstorage_string===JSON.stringify({type:"base"})?'Need at least one parameter: "storage" containing storage specifications.':""},f.isStorageArrayIndexed=function(){return a.getItem(g)?!0:!1},f.getIndexedStorageArray=function(){return a.getItem(g)||[]},f.indexStorage=function(b){var c=f.getIndexedStorageArray();c.push(typeof b=="string"?b:JSON.stringify(b)),a.setItem(g,c)},f.isAnIndexedStorage=function(a){var b=typeof a=="string"?a: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(h)?!0:!1},f.getFileArray=function(){return a.getItem(h)||[]},f.setFileArray=function(b){return a.setItem(h,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(h,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(h,g)},f.update=function(){var a=function(a){f.isAnIndexedStorage(f.secondstorage_string)||f.indexStorage(f.secondstorage_string),f.setFileArray(a)};d.addJob(d.newStorage(f.secondstorage_spec),d.newCommand("getDocumentList",{path:".",option:{onDone:a,max_retry:3}}))},d.saveDocument=function(a){var b=a.clone();b.onResponseDo(function(){}),b.onDoneDo(function(b){f.isFileIndexed(a.getPath())||f.addFile({name:a.getPath(),last_modified:0,creation_date:0}),f.update(),d.done()}),b.onFailDo(function(a){d.fail(a)}),d.addJob(d.newStorage(f.secondstorage_spec),b)},d.loadDocument=function(a){var b,c,e,g,h=function(a){d.done(a)},i=function(a){d.fail(a)},j=function(){var b=a.clone();b.onResponseDo(function(){}),b.onFailDo(i),b.onDoneDo(h),d.addJob(d.newStorage(f.secondstorage_spec),b)};f.update(),a.getOption("metadata_only")?setTimeout(function(){if(f.fileArrayExists()){b=f.getFileArray();for(c=0,e=b.length;c<e;c+=1)if(b[c].name===a.getPath())return d.done(b[c])}else j()},100):j()},d.getDocumentList=function(a){var b,c,e=!1;f.update(),a.getOption("metadata_only")?(b=setInterval(function(){e&&(d.fail({status:0,statusText:"Timeout",message:"The request has timed out."}),clearInterval(b)),f.fileArrayExists()&&(d.done(f.getFileArray()),clearInterval(b))},100),setTimeout(function(){e=!0},1e4)):(c=a.clone(),c.onDoneDo(function(a){d.done(a)}),c.onFailDo(function(a){d.fail(a)}),d.addJob(d.newStorage(f.secondstorage_spec),c))},d.removeDocument=function(a){var b=a.clone();b.onResponseDo(function(){}),b.onDoneDo(function(b){f.removeFile(a.getPath()),f.update(),d.done()}),b.onFailDo(function(a){d.fail(a)}),d.addJob(d.newStorage(f.secondstorage_spec),b)},d};e.addStorageType("indexed",i);var j=function(a,c){var f=e.storage(a,c,"handler"),g={};g.username=a.username||"",g.password=a.password||"",g.secondstorage_spec=a.storage||{type:"base"};var h=f.serialized;return f.serialized=function(){var a=h();return a.username=g.username,a.password=g.password,a},f.validateState=function(){return g.username&&JSON.stringify(g.secondstorage_spec)===JSON.stringify({type:"base"})?"":'Need at least two parameters: "username" and "storage".'},g.encrypt_param_object={iv:"kaprWwY/Ucr7pumXoTHbpA",v:1,iter:1e3,ks:256,ts:128,mode:"ccm",adata:"",cipher:"aes",salt:"K4bmZG9d704"},g.decrypt_param_object={iv:"kaprWwY/Ucr7pumXoTHbpA",ks:256,ts:128,salt:"K4bmZG9d704"},g.encrypt=function(a,b,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.saveDocument=function(a){var b,c,d=function(){g.encrypt(a.getPath(),function(a){b=a,e()})},e=function(){g.encrypt(a.getContent(),function(a){c=a,h()})},h=function(){var a=f.cloneOption(),d,e;a.onResponse=function(){},a.onDone=function(){f.done()},a.onFail=function(a){f.fail(a)},d=f.newCommand({path:b,content:c,option:a}),e=f.newStorage(g.secondstorage_spec),f.addJob(e,d)};d()},f.loadDocument=function(a){var b,c,d=function(){g.encrypt(a.getPath(),function(a){b=a,e()})},e=function(){var c=a.cloneOption(),d,e;c.onResponse=function(){},c.onFail=i,c.onDone=h,d=f.newCommand({path:b,option:c}),e=f.newStorage(g.secondstorage_spec),f.addJob(e,d)},h=function(b){b.name=a.getPath(),a.getOption("metadata_only")?f.done(b):g.decrypt(b.content,function(a){typeof a=="object"?f.fail({status:0,statusText:"Decrypt Fail",message:"Unable to decrypt"}):(b.content=a,f.done(b))})},i=function(a){f.fail(a)};d()},f.getDocumentList=function(a){var b,c,d,e=0,h,i=!0,j=function(){var c=a.clone(),d=f.newStorage(g.secondstorage_spec);c.onResponseDo(k),c.onDoneDo(function(){}),c.onFailDo(function(){}),f.addJob(b)},k=function(a){if(a.status.isDone()){h=a.return_value;for(c=0,d=h.length;c<d;c+=1)g.decrypt(h[c].name,l,c,"name")}else f.fail(a.error)},l=function(a,b,c){var g;e++;if(typeof a=="object"){i&&f.fail({status:0,statusText:"Decrypt Fail",message:"Unable to decrypt."}),i=!1;return}h[b][c]=a,e===d&&i&&f.done(h)};j()},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.onResponse=e,f.addJob(a)},e=function(a){a.status==="done"?f.done():f.fail(a.error)};c()},f};e.addStorageType("crypt",j)})(LocalOrCookieStorage,jQuery,Base64,sjcl,jio);
\ No newline at end of file
(function(a,b,c,d,e,f){var g=function(b,c){var d=f.storage(b,c,"base"),e={};e.username=b.username||"",e.applicationname=b.applicationname||"untitled";var g="jio/local_user_array",h="jio/local_file_name_array/"+e.username+"/"+e.applicationname,i=d.serialized;return d.serialized=function(){var a=i();return a.applicationname=e.applicationname,a.username=e.username,a},d.validateState=function(){return e.username?"":'Need at least one parameter: "username".'},e.getUserArray=function(){return a.getItem(g)||[]},e.addUser=function(b){var c=e.getUserArray();c.push(b),a.setItem(g,c)},e.userExists=function(a){var b=e.getUserArray(),c,d;for(c=0,d=b.length;c<d;c+=1)if(b[c]===a)return!0;return!1},e.getFileNameArray=function(){return a.getItem(h)||[]},e.addFileName=function(b){var c=e.getFileNameArray();c.push(b),a.setItem(h,c)},e.removeFileName=function(b){var c,d,f=e.getFileNameArray(),g=[];for(c=0,d=f.length;c<d;c+=1)f[c]!==b&&g.push(f[c]);a.setItem(h,g)},d.saveDocument=function(b){setTimeout(function(){var c=null,f="jio/local/"+e.username+"/"+e.applicationname+"/"+b.getPath();c=a.getItem(f),c?(c.last_modified=Date.now(),c.content=b.getContent()):(c={name:b.getPath(),content:b.getContent(),creation_date:Date.now(),last_modified:Date.now()},e.userExists(e.username)||e.addUser(e.username),e.addFileName(b.getPath())),a.setItem(f,c),d.done()},100)},d.loadDocument=function(b){setTimeout(function(){var c=null;c=a.getItem("jio/local/"+e.username+"/"+e.applicationname+"/"+b.getPath()),c?(b.getOption("metadata_only")&&delete c.content,d.done(c)):d.fail(b,{status:404,statusText:"Not Found.",message:'Document "'+b.getPath()+'" not found in localStorage.'})},100)},d.getDocumentList=function(b){setTimeout(function(){var c=[],f=[],g,h,i="key",j="jio/local/"+e.username+"/"+e.applicationname,k={};f=e.getFileNameArray();for(g=0,h=f.length;g<h;g+=1)k=a.getItem(j+"/"+f[g]),k&&(b.getOption("metadata_only")?c.push({name:k.name,creation_date:k.creation_date,last_modified:k.last_modified}):c.push({name:k.name,content:k.content,creation_date:k.creation_date,last_modified:k.last_modified}));d.done(c)},100)},d.removeDocument=function(b){setTimeout(function(){var c="jio/local/"+e.username+"/"+e.applicationname+"/"+b.getPath();a.deleteItem(c),e.removeFileName(b.getPath()),d.done()},100)},d};f.addStorageType("local",g);var h=function(a,d){var e=f.storage(a,d,"base"),g={};g.username=a.username||"",g.applicationname=a.applicationname||"untitled",g.url=a.url||"",g.password=a.password||"";var h=e.serialized;return e.serialized=function(){var a=h();return a.username=g.username,a.applicationname=g.applicationname,a.url=g.url,a.password=g.password,a},e.validateState=function(){return g.username&&g.url?"":'Need at least 2 parameters: "username" and "url".'},e.saveDocument=function(a){b.ajax({url:g.url+"/dav/"+g.username+"/"+g.applicationname+"/"+a.getPath(),type:"PUT",data:a.getContent(),async:!0,dataType:"text",headers:{Authorization:"Basic "+c.encode(g.username+":"+g.password)},success:function(){e.done()},error:function(b){b.message='Cannot save "'+a.getPath()+'" into DAVStorage.',e.fail(b)}})},e.loadDocument=function(a){var d={},f=function(){b.ajax({url:g.url+"/dav/"+g.username+"/"+g.applicationname+"/"+a.getPath(),type:"GET",async:!0,dataType:"text",headers:{Authorization:"Basic "+c.encode(g.username+":"+g.password)},success:function(a){d.content=a,e.done(d)},error:function(b){b.status===404?b.message='Document "'+a.getPath()+'" not found in localStorage.':b.message='Cannot load "'+a.getPath()+'" from DAVStorage.',e.fail(b)}})};d.name=a.getPath(),b.ajax({url:g.url+"/dav/"+g.username+"/"+g.applicationname+"/"+a.getPath(),type:"PROPFIND",async:!0,dataType:"xml",headers:{Authorization:"Basic "+c.encode(g.username+":"+g.password)},success:function(c){b(c).find("lp1\\:getlastmodified, getlastmodified").each(function(){d.last_modified=b(this).text()}),b(c).find("lp1\\:creationdate, creationdate").each(function(){d.creation_date=b(this).text()}),a.getOption("metadata_only")?e.done(d):f()},error:function(b){b.message='Cannot load "'+a.getPath()+'" informations from DAVStorage.',e.fail(b)}})},e.getDocumentList=function(a){var d=[],f={},h=[];b.ajax({url:g.url+"/dav/"+g.username+"/"+g.applicationname+"/",async:!0,type:"PROPFIND",dataType:"xml",headers:{Authorization:"Basic "+c.encode(g.username+":"+g.password),Depth:"1"},success:function(a){b(a).find("D\\:response, response").each(function(a,c){if(a>0){f={},b(c).find("D\\:href, href").each(function(){h=b(this).text().split("/"),f.name=h[h.length-1]?h[h.length-1]:h[h.length-2]+"/"});if(f.name===".htaccess"||f.name===".htpasswd")return;b(c).find("lp1\\:getlastmodified, getlastmodified").each(function(){f.last_modified=b(this).text()}),b(c).find("lp1\\:creationdate, creationdate").each(function(){f.creation_date=b(this).text()}),d.push(f)}}),e.done(d)},error:function(a){a.message="Cannot get a document list from DAVStorage.",e.fail(a)}})},e.removeDocument=function(a){b.ajax({url:g.url+"/dav/"+g.username+"/"+g.applicationname+"/"+a.getPath(),type:"DELETE",async:!0,headers:{Authorization:"Basic "+c.encode(g.username+":"+g.password)},success:function(){e.done()},error:function(a){a.status===404?e.done():(a.message='Cannot remove "'+e.getFileName()+'" from DAVStorage.',e.fail(a))}})},e};f.addStorageType("dav",h);var i=function(a,b){var c=f.storage(a,b,"handler"),d={};d.return_value_array=[],d.storagelist=a.storagelist||[],d.nb_storage=d.storagelist.length;var e=c.serialized;return c.serialized=function(){var a=e();return a.storagelist=d.storagelist,a},c.validateState=function(){return d.storagelist.length===0?'Need at least one parameter: "storagelist" containing at least one storage.':""},d.isTheLast=function(){return d.return_value_array.length===d.nb_storage},d.doJob=function(a,b){var e=!1,f=[],g,h=function(a){d.return_value_array.push(a)},i=function(a){e||(f.push(a),d.isTheLast()&&c.fail({status:207,statusText:"Multi-Status",message:b,array:f}))},j=function(a){e||(e=!0,c.done(a))};for(g=0;g<d.nb_storage;g+=1){var k=a.clone(),l=c.newStorage(d.storagelist[g]);k.onResponseDo(h),k.onFailDo(i),k.onDoneDo(j),c.addJob(l,k)}a.setMaxRetry(1)},c.saveDocument=function(a){d.doJob(a,'All save "'+a.getPath()+'" requests have failed.'),c.end()},c.loadDocument=function(a){d.doJob(a,'All load "'+a.getPath()+'" requests have failed.'),c.end()},c.getDocumentList=function(a){d.doJob(a,"All get document list requests have failed."),c.end()},c.removeDocument=function(a){d.doJob(a,'All remove "'+a.getPath()+'" requests have failed.'),c.end()},c};f.addStorageType("replicate",i);var j=function(b,c){var d=f.storage(b,c,"handler"),e={},g=b.storage||!1;e.secondstorage_spec=b.storage||{type:"base"},e.secondstorage_string=JSON.stringify(e.secondstorage_spec);var h="jio/indexed_storage_array",i="jio/indexed_file_array/"+e.secondstorage_string,j=d.serialized;return d.serialized=function(){var a=j();return a.storage=e.secondstorage_spec,a},d.validateState=function(){return g?"":'Need at least one parameter: "storage" containing storage specifications.'},e.isStorageArrayIndexed=function(){return a.getItem(h)?!0:!1},e.getIndexedStorageArray=function(){return a.getItem(h)||[]},e.indexStorage=function(b){var c=e.getIndexedStorageArray();c.push(typeof b=="string"?b:JSON.stringify(b)),a.setItem(h,c)},e.isAnIndexedStorage=function(a){var b=typeof a=="string"?a:JSON.stringify(a),c,d,f=e.getIndexedStorageArray();for(c=0,d=f.length;c<d;c+=1)if(JSON.stringify(f[c])===b)return!0;return!1},e.fileArrayExists=function(){return a.getItem(i)?!0:!1},e.getFileArray=function(){return a.getItem(i)||[]},e.setFileArray=function(b){return a.setItem(i,b)},e.isFileIndexed=function(a){var b,c,d=e.getFileArray();for(b=0,c=d.length;b<c;b+=1)if(d[b].name===a)return!0;return!1},e.addFile=function(b){var c=e.getFileArray();c.push(b),a.setItem(i,c)},e.removeFile=function(b){var c,d,f=e.getFileArray(),g=[];for(c=0,d=f.length;c<d;c+=1)f[c].name!==b&&g.push(f[c]);a.setItem(i,g)},e.update=function(){var a=function(a){e.isAnIndexedStorage(e.secondstorage_string)||e.indexStorage(e.secondstorage_string),e.setFileArray(a)};d.addJob(d.newStorage(e.secondstorage_spec),d.newCommand("getDocumentList",{path:".",option:{onDone:a,max_retry:3}}))},d.saveDocument=function(a){var b=a.clone();b.onResponseDo(function(){}),b.onDoneDo(function(b){e.isFileIndexed(a.getPath())||e.addFile({name:a.getPath(),last_modified:0,creation_date:0}),e.update(),d.done()}),b.onFailDo(function(a){d.fail(a)}),d.addJob(d.newStorage(e.secondstorage_spec),b)},d.loadDocument=function(a){var b,c,f,g,h=function(a){d.done(a)},i=function(a){d.fail(a)},j=function(){var b=a.clone();b.onResponseDo(function(){}),b.onFailDo(i),b.onDoneDo(h),d.addJob(d.newStorage(e.secondstorage_spec),b)};e.update(),a.getOption("metadata_only")?setTimeout(function(){if(e.fileArrayExists()){b=e.getFileArray();for(c=0,f=b.length;c<f;c+=1)if(b[c].name===a.getPath())return d.done(b[c])}else j()},100):j()},d.getDocumentList=function(a){var b,c,f=!1;e.update(),a.getOption("metadata_only")?(b=setInterval(function(){f&&(d.fail({status:0,statusText:"Timeout",message:"The request has timed out."}),clearInterval(b)),e.fileArrayExists()&&(d.done(e.getFileArray()),clearInterval(b))},100),setTimeout(function(){f=!0},1e4)):(c=a.clone(),c.onDoneDo(function(a){d.done(a)}),c.onFailDo(function(a){d.fail(a)}),d.addJob(d.newStorage(e.secondstorage_spec),c))},d.removeDocument=function(a){var b=a.clone();b.onResponseDo(function(){}),b.onDoneDo(function(b){e.removeFile(a.getPath()),e.update(),d.done()}),b.onFailDo(function(a){d.fail(a)}),d.addJob(d.newStorage(e.secondstorage_spec),b)},d};f.addStorageType("indexed",j);var k=function(a,c){var e=f.storage(a,c,"handler"),g={};g.username=a.username||"",g.password=a.password||"",g.secondstorage_spec=a.storage||{type:"base"};var h=e.serialized;return e.serialized=function(){var a=h();return a.username=g.username,a.password=g.password,a},e.validateState=function(){return g.username&&JSON.stringify(g.secondstorage_spec)===JSON.stringify({type:"base"})?"":'Need at least two parameters: "username" and "storage".'},g.encrypt_param_object={iv:"kaprWwY/Ucr7pumXoTHbpA",v:1,iter:1e3,ks:256,ts:128,mode:"ccm",adata:"",cipher:"aes",salt:"K4bmZG9d704"},g.decrypt_param_object={iv:"kaprWwY/Ucr7pumXoTHbpA",ks:256,ts:128,salt:"K4bmZG9d704"},g.encrypt=function(a,b,c){var f=d.encrypt(e.getStorageUserName()+":"+e.getStoragePassword(),a,g.encrypt_param_object);b(JSON.parse(f).ct,c)},g.decrypt=function(a,c,f,h){var i,j=b.extend(!0,{},g.decrypt_param_object);j.ct=a||"",j=JSON.stringify(j);try{i=d.decrypt(e.getStorageUserName()+":"+e.getStoragePassword(),j)}catch(k){c({status:0,statusText:"Decrypt Fail",message:"Unable to decrypt."},f,h);return}c(i,f,h)},e.saveDocument=function(a){var b,c,d=function(){g.encrypt(a.getPath(),function(a){b=a,f()})},f=function(){g.encrypt(a.getContent(),function(a){c=a,h()})},h=function(){var a=e.cloneOption(),d,f;a.onResponse=function(){},a.onDone=function(){e.done()},a.onFail=function(a){e.fail(a)},d=e.newCommand({path:b,content:c,option:a}),f=e.newStorage(g.secondstorage_spec),e.addJob(f,d)};d()},e.loadDocument=function(a){var b,c,d=function(){g.encrypt(a.getPath(),function(a){b=a,f()})},f=function(){var c=a.cloneOption(),d,f;c.onResponse=function(){},c.onFail=i,c.onDone=h,d=e.newCommand({path:b,option:c}),f=e.newStorage(g.secondstorage_spec),e.addJob(f,d)},h=function(b){b.name=a.getPath(),a.getOption("metadata_only")?e.done(b):g.decrypt(b.content,function(a){typeof a=="object"?e.fail({status:0,statusText:"Decrypt Fail",message:"Unable to decrypt"}):(b.content=a,e.done(b))})},i=function(a){e.fail(a)};d()},e.getDocumentList=function(a){var b,c,d,f=0,h,i=!0,j=function(){var c=a.clone(),d=e.newStorage(g.secondstorage_spec);c.onResponseDo(k),c.onDoneDo(function(){}),c.onFailDo(function(){}),e.addJob(b)},k=function(a){if(a.status.isDone()){h=a.return_value;for(c=0,d=h.length;c<d;c+=1)g.decrypt(h[c].name,l,c,"name")}else e.fail(a.error)},l=function(a,b,c){var g;f++;if(typeof a=="object"){i&&e.fail({status:0,statusText:"Decrypt Fail",message:"Unable to decrypt."}),i=!1;return}h[b][c]=a,f===d&&i&&e.done(h)};j()},e.removeDocument=function(){var a,b,c=function(){g.encrypt(e.getFileName(),function(a){b=a,d()})},d=function(){a=e.cloneJob(),a.name=b,a.storage=e.getSecondStorage(),a.onResponse=f,e.addJob(a)},f=function(a){a.status==="done"?e.done():e.fail(a.error)};c()},e};f.addStorageType("crypt",k);var l=function(b,c){var d=f.storage(b,c,"handler"),g={},h="jio/conflictmanager/";g.username=b.username||"";var i=b.storage?!0:!1;g.secondstorage_spec=b.storage||{type:"base"};var j=d.serialized;return d.serialized=function(){var a=j();return a.storage=g.secondstorage_spec,a},d.validateState=function(){return!g.username||i?'Need at least two parameter: "owner" and "storage" .':""},g.isTheLatestVersion=function(a,b){var c;if(!b.owner)return!0;for(c in b.owner)if(c!==g.username&&a.winner.version<=b.owner[c].last_version)return!1;return!0},g.conflictResearch=function(){},d.saveDocument=function(b){var c=b.getPath()+".metadata",f=new Date,i=h+c,j={},k={},l=0,m=!1,n=!1,o=0,p=e(b.getContent()),q=function(e){switch(e){case 0:l=3,q(2),q(1);break;case 1:var h={revision:0,hash:"",last_modified:0,creation_date:f.getTime()};j=a.getItem(i),j?j.owner[g.username]||(j.owner[g.username]=h):(j={winner:{},owner:{},conflict_list:[]},j.winner={revision:0,owner:g.username,hash:""},j.owner[g.username]=h),l++,q(l);break;case 2:var r=b.cloneOption();r.onResponse=function(){},r.onFail=function(a){a.status===404?(k=j,l++,q(l)):(l=-10,d.fail(a),m=!0)},r.onDone=function(a){k=JSON.parse(a.content),l++,q(l)};var s=d.newCommand("loadDocument",{path:c,option:r});d.addJob(d.newStorage(g.secondstorage_spec),s);break;case 5:var t=function(){var a;a=k.owner[k.winner.owner].creation_date||f.getTime(),k.owner[g.username]?o=k.owner[g.username].revision:k.owner[g.username]={},k.winner.owner=g.username,k.winner.revision++,k.winner.hash=p,k.owner[g.username].revision=k.winner.revision,k.owner[g.username].last_modified=f.getTime(),k.owner[g.username].creation_date=a,k.owner[g.username].hash=p};if(n){t(),a.setItem(i,k),l=98,q(6),q(7);break}j.winner.revision===k.winner.revision&&j.winner.hash===k.winner.hash?(t(),a.setItem(i,k),l=98,q(6),q(7)):(b.getOption("onConflict")(),l=-10,m=!0,d.fail());break;case 6:console.log("save metadata");break;case 7:console.log("save document revision");break;case 100:if(!m){m=!0,d.done();return}break;default:}};q(0),b.setMaxRetry(1)},d.loadDocument=function(a){d.fail({message:"NIY"})},d.getDocumentList=function(a){d.fail({message:"NIY"})},d.removeDocument=function(a){d.fail({message:"NIY"})},d};f.addStorageType("replicate",i)})(LocalOrCookieStorage,jQuery,Base64,sjcl,MD5,jio);
\ No newline at end of file
var newConflictManagerStorage = function ( spec, my ) {
var that = Jio.storage( spec, my, 'handler' ), priv = {};
var local_namespace = 'jio/conflictmanager/';
priv.username = spec.username || '';
var storage_exists = (spec.storage?true:false);
priv.secondstorage_spec = spec.storage || {type:'base'};
var super_serialized = that.serialized;
that.serialized = function () {
var o = super_serialized();
o.storage = priv.secondstorage_spec;
return o;
};
that.validateState = function () {
if (!priv.username || storage_exists) {
return 'Need at least two parameter: "owner" and "storage" '+
'.';
}
return '';
};
priv.isTheLatestVersion = function (local,distant) {
var k;
if (!distant.owner) {
return true;
}
for (k in distant.owner) {
if (k !== priv.username) {
if (local.winner.version <= distant.owner[k].last_version) {
return false;
}
}
}
return true;
};
priv.conflictResearch = function () {
// TODO : ;
};
/**
* Save a document and can manage conflicts.
* @method saveDocument
*/
that.saveDocument = function (command) {
var metadata_file_name = command.getPath() + '.metadata',
now = new Date(),
local_metadata_file_name = local_namespace + metadata_file_name,
local_file_metadata = {}, // local file.metadata
command_file_metadata = {}, // distant file.metadata
run_index = 0,
end = false, is_a_new_file = false,
previous_revision = 0,
local_file_hash = MD5 (command.getContent()),
run = function (index) {
switch (index) {
case 0:
run_index = 3;
run (2);
run (1);
break;
case 1: // update local metadata
var new_owner_object = {revision:0,hash:'',
last_modified:0,
creation_date:now.getTime()};
local_file_metadata =
LocalOrCookieStorage.getItem (local_metadata_file_name);
if ( local_file_metadata ) {
// if metadata already exists
if ( !local_file_metadata.owner[priv.username] ) {
local_file_metadata.owner[priv.username] =
new_owner_object;
}
} else {
local_file_metadata = {
winner: {},
owner: {},
conflict_list: []
};
local_file_metadata.winner = {
revision:0,owner:priv.username,hash:''};
local_file_metadata.owner[priv.username] =
new_owner_object;
}
run_index ++; run (run_index);
break;
case 2: // load metadata from distant
var cloned_option = command.cloneOption ();
cloned_option.onResponse = function () {};
cloned_option.onFail = function (error) {
if (error.status === 404) {
command_file_metadata = local_file_metadata;
run_index ++; run (run_index);
} else {
run_index = (-10);
that.fail(error);
end = true;
}
};
cloned_option.onDone = function (result) {
command_file_metadata = JSON.parse (result.content);
run_index ++; run (run_index);
};
var newcommand = that.newCommand(
'loadDocument',{path:metadata_file_name,
option:cloned_option});
that.addJob ( that.newStorage (priv.secondstorage_spec),
newcommand );
break;
// wait for 1 and 2
case 5: // check conflicts
var updateCommandMetadata = function () {
var original_creation_date;
original_creation_date = command_file_metadata.owner[
command_file_metadata.winner.owner].
creation_date || now.getTime();
if (command_file_metadata.owner[priv.username]) {
previous_revision = command_file_metadata.owner[
priv.username].revision;
} else {
command_file_metadata.owner[priv.username] = {};
}
command_file_metadata.winner.owner = priv.username;
command_file_metadata.winner.revision ++;
command_file_metadata.winner.hash = local_file_hash;
command_file_metadata.owner[priv.username].revision =
command_file_metadata.winner.revision;
command_file_metadata.owner[priv.username].
last_modified = now.getTime();
command_file_metadata.owner[priv.username].
creation_date = original_creation_date;
command_file_metadata.owner[priv.username].hash =
local_file_hash;
};
// if this is a new file
if (is_a_new_file) {
updateCommandMetadata();
LocalOrCookieStorage.setItem (local_metadata_file_name,
command_file_metadata);
run_index = (98);
run (6); // save metadata
run (7); // save document revision
break;
}
if (local_file_metadata.winner.revision ===
command_file_metadata.winner.revision &&
local_file_metadata.winner.hash ===
command_file_metadata.winner.hash) {
// OK! Now, update distant metadata, store them and save
updateCommandMetadata();
LocalOrCookieStorage.setItem (local_metadata_file_name,
command_file_metadata);
run_index = 98;
run (6); // save metadata
run (7); // save document revision
} else {
// var conflict_hash = '';
// // gen hash
// conflict_hash = MD5 (JSON.stringify ({
// path: command.getPath()
// // TODO : ;
// }));
// // TODO : ;
// command_file_metadata.conflict_list.push ({
// label:'revision',
// hash: conflict_hash,
// path: command.getPath(),
// local_owner: {
// name: priv.username,
// revision: local_file_metadata.owner[
// priv.username].revision + 1,
// hash: local_file_hash
// },
// conflict_owner: {
// name: command_file_metadata.winner.owner,
// revision: command_file_metadata.winner.revision,
// hash: command_file_metadata.winner.hash
// }
// });
command.getOption('onConflict')();
run_index = (-10);
end = true;
that.fail(); // TODO
}
break;
case 6: // save metadata
console.log ('save metadata');
break;
case 7: // save document revision
console.log ('save document revision');
break;
case 100:
if (!end) {
end = true;
that.done();
return;
}
break;
default:
break;
}
};
run (0);
command.setMaxRetry (1);
};
/**
* Load a document from several storages, and send the first retreived
* document.
* @method loadDocument
*/
that.loadDocument = function (command) {
that.fail({message:'NIY'});
};
/**
* Get a document list from several storages, and returns the first
* retreived document list.
* @method getDocumentList
*/
that.getDocumentList = function (command) {
that.fail({message:'NIY'});
};
/**
* Remove a document from several storages.
* @method removeDocument
*/
that.removeDocument = function (command) {
that.fail({message:'NIY'});
};
return that;
};
Jio.addStorageType('replicate', newReplicateStorage);
var newCryptedStorage = function ( spec, my ) {
var that = Jio.storage( spec, my, 'handler' ), priv = {};
priv.username = spec.username || '';
priv.password = spec.password || '';
priv.secondstorage_spec = spec.storage || {type:'base'};
var super_serialized = that.serialized;
that.serialized = function () {
var o = super_serialized();
o.username = priv.username;
o.password = priv.password;
return o;
};
that.validateState = function () {
if (priv.username &&
JSON.stringify (priv.secondstorage_spec) ===
JSON.stringify ({type:'base'})) {
return '';
}
return 'Need at least two parameters: "username" and "storage".';
};
// 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);
};
/**
* Saves a document.
* @method saveDocument
*/
that.saveDocument = function (command) {
var new_file_name, newfilecontent,
_1 = function () {
priv.encrypt(command.getPath(),function(res) {
new_file_name = res;
_2();
});
},
_2 = function () {
priv.encrypt(command.getContent(),function(res) {
newfilecontent = res;
_3();
});
},
_3 = function () {
var settings = that.cloneOption(), newcommand, newstorage;
settings.onResponse = function (){};
settings.onDone = function () { that.done(); };
settings.onFail = function (r) { that.fail(r); };
newcommand = that.newCommand(
{path:new_file_name,
content:newfilecontent,
option:settings});
newstorage = that.newStorage( priv.secondstorage_spec );
that.addJob ( newstorage, newcommand );
};
_1();
}; // end saveDocument
/**
* Loads a document.
* @method loadDocument
*/
that.loadDocument = function (command) {
var new_file_name, option,
_1 = function () {
priv.encrypt(command.getPath(),function(res) {
new_file_name = res;
_2();
});
},
_2 = function () {
var settings = command.cloneOption(), newcommand, newstorage;
settings.onResponse = function(){};
settings.onFail = loadOnFail;
settings.onDone = loadOnDone;
newcommand = that.newCommand (
{path:new_file_name,
option:settings});
newstorage = that.newStorage ( priv.secondstorage_spec );
that.addJob ( newstorage, newcommand );
},
loadOnDone = function (result) {
result.name = command.getPath();
if (command.getOption('metadata_only')) {
that.done(result);
} else {
priv.decrypt (result.content,function(res){
if (typeof res === 'object') {
that.fail({status:0,statusText:'Decrypt Fail',
message:'Unable to decrypt'});
} else {
result.content = res;
// content only: the second storage should
// manage content_only option, so it is not
// necessary to manage it.
that.done(result);
}
});
}
},
loadOnFail = function (result) {
// 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);
};
_1();
}; // end loadDocument
/**
* Gets a document list.
* @method getDocumentList
*/
that.getDocumentList = function (command) {
var new_job, i, l, cpt = 0, array, ok = true,
_1 = function () {
var newcommand = command.clone(),
newstorage = that.newStorage ( priv.secondstorage_spec );
newcommand.onResponseDo (getListOnResponse);
newcommand.onDoneDo (function(){});
newcommand.onFailDo (function(){});
that.addJob ( new_job );
},
getListOnResponse = function (result) {
if (result.status.isDone()) {
array = result.return_value;
for (i = 0, l = array.length; i < l; i+= 1) {
// cpt--;
priv.decrypt (array[i].name,
lastOnResponse,i,'name');
// priv.decrypt (array[i].content,
// lastOnResponse,i,'content');
}
} else {
that.fail(result.error);
}
},
lastOnResponse = 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.onResponse = removeOnResponse;
that.addJob(new_job);
},
removeOnResponse = function (result) {
if (result.status === 'done') {
that.done();
} else {
that.fail(result.error);
}
};
_1();
};
return that;
};
Jio.addStorageType('crypt', newCryptedStorage);
var newIndexStorage = function ( spec, my ) {
var that = Jio.storage( spec, my, 'handler' ), priv = {};
var validatestate_secondstorage = spec.storage || false;
priv.secondstorage_spec = spec.storage || {type:'base'};
priv.secondstorage_string = JSON.stringify (priv.secondstorage_spec);
......@@ -16,7 +17,7 @@ var newIndexStorage = function ( spec, my ) {
};
that.validateState = function () {
if (priv.secondstorage_string === JSON.stringify ({type:'base'})) {
if (!validatestate_secondstorage) {
return 'Need at least one parameter: "storage" '+
'containing storage specifications.';
}
......
/**
* Adds 5 storages to JIO.
* Adds 6 storages to JIO.
* - LocalStorage ('local')
* - DAVStorage ('dav')
* - ReplicateStorage ('replicate')
* - IndexedStorage ('indexed')
* - CryptedStorage ('crypted')
* - ConflictManagerStorage ('conflictmanager')
*
* @module JIOStorages
*/
(function(LocalOrCookieStorage, $, Base64, sjcl, Jio) {
(function(LocalOrCookieStorage, $, Base64, sjcl, MD5, Jio) {
}( LocalOrCookieStorage, jQuery, Base64, sjcl, jio ));
}( LocalOrCookieStorage, jQuery, Base64, sjcl, MD5, jio ));
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