Commit fe765144 authored by Tristan Cavelier's avatar Tristan Cavelier Committed by Sebastien Robin

Adding Indexed storage + qunit tests.

parent 10a18668
/*! JIO - v0.1.0 - 2012-05-29
/*! JIO - v0.1.0 - 2012-06-01
* Copyright (c) 2012 Nexedi; Licensed */
var JIO =
(function () { var jio_loader_function = function ( localOrCookieStorage, $ ) {
......@@ -169,13 +168,6 @@ var JIO =
////////////////////////////////////////////////////////////////////////////
// Tools
extend = function (o1,o2) {
var key;
for (key in o2) {
o1[key] = o2[key];
}
return o1;
},
// end Tools
////////////////////////////////////////////////////////////////////////////
......@@ -229,7 +221,7 @@ var JIO =
newJob = function ( spec, my ) {
// Job constructor
var job = extend({},spec);
var job = $.extend(true,{},spec);
job['id']=0;
job['status']='initial';
job['date']=Date.now();
......@@ -441,8 +433,8 @@ var JIO =
// options.job = the job object containing at least {id:..}.
// options.where = remove values where options.where(job) === true
var settings = extend ({where:function (job) {return true;}},
options),andwhere,found=false,k='key';
var settings = $.extend ({where:function (job) {return true;}},
options),andwhere,found=false,k='key';
//// modify the job list
if (settings.job) {
......@@ -556,7 +548,7 @@ var JIO =
// It is a callback function called just before user callback.
// It is called to manage job_object according to the ended job.
var job = extend({},endedjob); // copy
var job = $.extend(true,{},endedjob); // copy
// This job is supposed terminated, we can remove it from queue.
that.removeJob ({'job':job});
......@@ -800,7 +792,7 @@ var JIO =
//// Getters Setters
that.cloneJob = function () {
return extend({},priv.job);
return $.extend(true,{},priv.job);
};
that.getUserName = function () {
return priv.job.userName || '';
......@@ -817,6 +809,9 @@ var JIO =
that.getStorageLocation = function () {
return priv.job.storage.location || '';
};
that.getSecondStorage = function () {
return priv.job.storage.storage || {};
};
that.getStorageArray = function () {
return priv.job.storage.storageArray || [];
};
......@@ -827,7 +822,7 @@ var JIO =
return priv.job.fileContent || '';
};
that.cloneOptionObject = function () {
return extend({},priv.job.options);
return $.extend(true,{},priv.job.options);
};
that.getMaxTries = function () {
return priv.job.maxtries;
......@@ -1146,7 +1141,7 @@ var JIO =
// } else { } // Error
// }});
var settings = extend ({
var settings = $.extend (true,{
'userName': priv.storage.userName,
'storage': priv.storage,
'applicant': priv.applicant,
......@@ -1179,7 +1174,7 @@ var JIO =
// } else { } // Error
// }});
var settings = extend({
var settings = $.extend(true,{
'storage': priv.storage,
'applicant': priv.applicant,
'fileContent': '',
......@@ -1217,7 +1212,7 @@ var JIO =
// fileName:'string',fileContent:'string',
// creationDate:123,lastModified:456 }
var settings = extend ({
var settings = $.extend (true,{
'storage': priv.storage,
'applicant': priv.applicant,
'method':'loadDocument',
......@@ -1251,7 +1246,7 @@ var JIO =
// result.return_value is an Array that contains documents objects.
var settings = extend ({
var settings = $.extend (true,{
'storage': priv.storage,
'applicant': priv.applicant,
'method':'getDocumentList',
......@@ -1281,7 +1276,7 @@ var JIO =
// } else { } // Not Removed
// }});
var settings = extend ({
var settings = $.extend (true,{
'storage': priv.storage,
'applicant': priv.applicant,
'method':'removeDocument',
......@@ -1296,7 +1291,7 @@ var JIO =
//// end Methods
//// Initialize
var settings = extend({'use_local_storage':true},spec.options);
var settings = $.extend(true,{'use_local_storage':true},spec.options);
// objectify storage and applicant
if(typeof spec.storage === 'string') {
......@@ -1349,7 +1344,7 @@ var JIO =
// applicant: the applicant object or json string
// options.useLocalStorage: if true, save job queue on localStorage.
var settings = extend({'use_local_storage':true},options);
var settings = $.extend(true,{'use_local_storage':true},options);
return newJioConstructor({storage:storage,
applicant:applicant,
......@@ -1380,7 +1375,7 @@ var JIO =
};
that.getConstObject = function () {
// Returns a copy of the constants
return extend({},jio_const_obj);
return $.extend(true,{},jio_const_obj);
};
return that;
};
......
/*! JIO - v0.1.0 - 2012-05-29
/*! JIO - v0.1.0 - 2012-06-01
* 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=function(a,b){var c;for(c in b)a[c]=b[c];return a},f,g,h,i,j,k,l,m;return f=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},g=function(a,b){var c=e({},a);return c.id=0,c.status="initial",c.date=Date.now(),c},h=function(b,f){var h={},i={},j="jio/idarray";return h.init=function(c){var d,e=function(){},f;i.use_local_storage&&(f=a.getItem(j)||[],b.publisher&&(i.publisher=b.publisher),i.jio_id=c.jio_id,i.job_object_name="jio/jobobject/"+i.jio_id,f.push(i.jio_id),a.setItem(j,f)),i.job_object={},h.copyJobQueueToLocalStorage();for(d in i.recovered_job_object)i.recovered_job_object[d].callback=e,h.addJob(i.recovered_job_object[d])},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(j)||[];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(j)||[];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(j,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(g(a))},h.addJob=function(a){var b=!0,c=[],e=[],f=[],g=null,j="id";for(j in i.job_object){if(d.job_managing_method.canRemoveFailOrDone(i.job_object[j],a)){f.push(j);continue}if(d.job_managing_method.canSelect(i.job_object[j],a)){if(d.job_managing_method.canEliminate(i.job_object[j],a)){c.push(j);continue}if(d.job_managing_method.canReplace(i.job_object[j],a)){g=k({queue:h,job:i.job_object[j]}),g.replace(a),b=!1;break}if(d.job_managing_method.cannotAccept(i.job_object[j],a))return!1;if(d.job_managing_method.mustWait(i.job_object[j],a)){e.push(j);continue}}}if(b){for(j=0;j<c.length;j+=1)g=k({queue:h,job:i.job_object[c[j]]}),g.eliminate();if(e.length>0){a.status="wait",a.waitingFor={jobIdArray:e};for(j=0;j<e.length;j+=1)i.job_object[e[j]]&&(i.job_object[e[j]].maxtries=1)}for(j=0;j<f.length;j+=1)h.removeJob(i.job_object[f[j]]);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 b=e({where:function(a){return!0}},a),c,d=!1,f="key";if(b.job)i.job_object[b.job.id]&&b.where(i.job_object[b.job.id])&&(delete i.job_object[b.job.id],d=!0);else for(f in i.job_object)b.where(i.job_object[f])&&(delete i.job_object[f],d=!0);d||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=k({queue:this,job:a}),b.execute()},h.ended=function(a){var b=e({},a);h.removeJob({job:b});if(!c.job_method_object[b.method])return!1;if(!h.isThereJobsWhere(function(a){return a.method===b.method&&a.status==="ongoing"||a.status==="initial"})){i.publisher.publish(c.job_method_object[b.method]["stop_"+b.method]);return}},h.clean=function(){h.removeJob(undefined,{where:function(a){return a.status==="fail"}})},i.use_local_storage=b.options.use_local_storage,i.publisher=b.publisher,i.job_id=1,i.jio_id=0,i.job_object_name="",i.job_object={},i.recovered_job_object={},h},i=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},j=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},k=function(a){var b={},c={};return c.job=a.job,c.callback=a.job.callback,c.queue=a.queue,c.res={status:"done",message:""},c.sorted=!1,c.limited=!1,c.research_done=!1,c.fail_checkNameAvailability=function(){c.res.message="Unable to check name availability."},c.done_checkNameAvailability=function(a){c.res.message=c.job.userName+" is "+(a?"":"not ")+"available.",c.res.return_value=a},c.fail_loadDocument=function(){c.res.message="Unable to load document."},c.done_loadDocument=function(a){c.res.message="Document loaded.",c.res.return_value=a,c.res.return_value.lastModified=(new Date(c.res.return_value.lastModified)).getTime(),c.res.return_value.creationDate=(new Date(c.res.return_value.creationDate)).getTime()},c.fail_saveDocument=function(){c.res.message="Unable to save document."},c.done_saveDocument=function(){c.res.message="Document saved."},c.fail_getDocumentList=function(){c.res.message="Unable to retrieve document list."},c.done_getDocumentList=function(a){var d;c.res.message="Document list received.",c.res.return_value=a;for(d=0;d<c.res.return_value.length;d+=1)typeof c.res.return_value[d].lastModified!="number"&&(c.res.return_value[d].lastModified=(new Date(c.res.return_value[d].lastModified)).getTime()),typeof c.res.return_value[d].creationDate!="number"&&(c.res.return_value[d].creationDate=(new Date(c.res.return_value[d].creationDate)).getTime());!c.sorted&&typeof c.job.sort!="undefined"&&b.sortDocumentArray(c.res.return_value),!c.limited&&typeof c.job.limit!="undefined"&&typeof c.job.limit.begin!="undefined"&&typeof c.job.limit.end!="undefined"&&(c.res.return_value=b.limitDocumentArray(c.res.return_value)),!c.research_done&&typeof c.job.search!="undefined"&&(c.res.return_value=b.searchDocumentArray(c.res.return_value))},c.fail_removeDocument=function(){c.res.message="Unable to removed document."},c.done_removeDocument=function(){c.res.message="Document removed."},c.retryLater=function(){var a=c.job.tries*c.job.tries*1e3;a>d.max_wait_time&&(a=d.max_wait_time),c.job.status="wait",c.job.waitingFor={time:Date.now()+a}},b.cloneJob=function(){return e({},c.job)},b.getUserName=function(){return c.job.userName||""},b.getApplicantID=function(){return c.job.applicant.ID||""},b.getStorageUserName=function(){return c.job.storage.userName||""},b.getStoragePassword=function(){return c.job.storage.password||""},b.getStorageLocation=function(){return c.job.storage.location||""},b.getStorageArray=function(){return c.job.storage.storageArray||[]},b.getFileName=function(){return c.job.fileName||""},b.getFileContent=function(){return c.job.fileContent||""},b.cloneOptionObject=function(){return e({},c.job.options)},b.getMaxTries=function(){return c.job.maxtries},b.getTries=function(){return c.job.tries||0},b.setMaxTries=function(a){c.job.maxtries=a},b.addJob=function(a){return c.queue.createJob(a)},b.eliminate=function(){c.job.maxtries=1,c.job.tries=1,b.fail("Job Stopped!",0)},b.replace=function(a){c.job.tries=0,c.job.date=a.date,c.job.callback=a.callback,c.res.status="fail",c.res.message="Job Stopped!",c.res.error={},c.res.error.status=0,c.res.error.statusText="Replaced",c.res.error.message="The job was replaced by a newer one.",c["fail_"+c.job.method](),c.callback(c.res)},b.fail=function(a){c.res.status="fail",c.res.error=a,c.res.error.status=c.res.error.status||0,c.res.error.statusText=c.res.error.statusText||"Unknown Error",c.res.error.array=c.res.error.array||[],c.res.error.message=c.res.error.message||"",!c.job.maxtries||c.job.tries<c.job.maxtries?c.retryLater():(c.job.status="fail",c["fail_"+c.job.method](),c.queue.ended(c.job),c.callback(c.res))},b.done=function(a){c.job.status="done",c["done_"+c.job.method](a),c.queue.ended(c.job),c.callback(c.res)},b.execute=function(){return c.job.tries=b.getTries()+1,d.storage_type_object[c.job.storage.type]?d.storage_type_object[c.job.storage.type]({job:c.job,queue:c.queue})[c.job.method]():null},b.checkNameAvailability=function(){b.fail({status:0,statusText:"Undefined Method",message:"This method must be redefined!"})},b.loadDocument=function(){b.fail({status:0,statusText:"Undefined Method",message:"This method must be redefined!"})},b.saveDocument=function(){b.fail({status:0,statusText:"Undefined Method",message:"This method must be redefined!"})},b.getDocumentList=function(){b.fail({status:0,statusText:"Undefined Method",message:"This method must be redefined!"})},b.removeDocument=function(){b.fail({status:0,statusText:"Undefined Method",message:"This method must be redefined!"})},b.sortDocumentArray=function(a){a.sort(function(a,b){var d,e;for(d in c.job.sort){var f=c.job.sort[d]==="descending"?-1:1;if(a[d]===b[d])continue;return a[d]>b[d]?f:-f}return 0}),b.sortDone()},b.sortDone=function(){c.sorted=!0},b.limitDocumentArray=function(a){return b.limitDone(),a.slice(c.job.limit.begin,c.job.limit.end)},b.limitDone=function(){c.limited=!0},b.searchDocumentArray=function(a){var d,e,f=[];for(d=0;d<a.length;d+=1)for(e in c.job.search){if(typeof a[d][e]=="undefined")continue;if(a[d][e].search(c.job.search[e])>-1){f.push(a[d]);break}}return b.researchDone(),f},b.researchDone=function(){c.research_done=!0},b},l=function(a,b){var c={},g={};g.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},c.getID=function(){return g.id},c.start=function(){return g.id!==0?!1:(g.id=g.queue.getNewQueueID(),g.queue.init({jio_id:g.id}),g.updater&&g.updater.start(g.id),g.listener.start(),g.ready=!0,c.isReady())},c.stop=function(){return g.queue.close(),g.listener.stop(),g.updater&&g.updater.stop(),g.ready=!1,g.id=0,!0},c.kill=function(){return g.queue.close(),g.listener.stop(),g.updater&&g.updater.stop(),g.ready=!1,!0},c.isReady=function(){return g.ready},c.publish=function(a,b){if(!c.isReady())return;return g.pubsub.publish(a,b)},c.subscribe=function(a,b){return g.pubsub.subscribe(a,b)},c.unsubscribe=function(a,b){return g.pubsub.unsubscribe(a,b)},c.checkNameAvailability=function(a){var b=e({userName:g.storage.userName,storage:g.storage,applicant:g.applicant,method:"checkNameAvailability",callback:function(){}},a);return c.isReady()&&b.userName&&b.storage&&b.applicant?g.queue.createJob(b):g.wrongParametersError(b)},c.saveDocument=function(a){var b=e({storage:g.storage,applicant:g.applicant,fileContent:"",method:"saveDocument",callback:function(){}},a);return c.isReady()&&b.fileName&&b.storage&&b.applicant?g.queue.createJob(b):g.wrongParametersError(b)},c.loadDocument=function(a){var b=e({storage:g.storage,applicant:g.applicant,method:"loadDocument",callback:function(){}},a);return c.isReady()&&b.fileName&&b.storage&&b.applicant?g.queue.createJob(b):g.wrongParametersError(b)},c.getDocumentList=function(a){var b=e({storage:g.storage,applicant:g.applicant,method:"getDocumentList",callback:function(){}},a);return c.isReady()&&b.storage&&b.applicant?g.queue.createJob(b):g.wrongParametersError(b)},c.removeDocument=function(a){var b=e({storage:g.storage,applicant:g.applicant,method:"removeDocument",callback:function(){}},a);return c.isReady()&&b.fileName&&b.storage&&b.applicant?g.queue.createJob(b):g.wrongParametersError(b)};var k=e({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)),g.storage=a.storage,g.applicant=a.applicant,g.id=0,g.pubsub=f({options:k}),g.queue=h({publisher:g.pubsub,options:k}),g.listener=i({queue:g.queue,options:k}),g.ready=!1,k.use_local_storage?g.updater=j({options:k}):g.updater=null,g.storage&&!d.storage_type_object[g.storage.type]&&console.error('Unknown storage type "'+g.storage.type+'"'),c.start(),c},m=function(a,b){var f={};return f.createNew=function(a,b,c){var d=e({use_local_storage:!0},c);return l({storage:a,applicant:b,options:d})},f.newBaseStorage=function(a,b){return k(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 e({},c)},f},m()};return window.requirejs?(define("JIO",["LocalOrCookieStorage","jQuery"],a),undefined):a(LocalOrCookieStorage,jQuery)}();
\ No newline at end of file
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)}();
\ No newline at end of file
/*! JIO Storage - v0.1.0 - 2012-05-24
/*! JIO Storage - v0.1.0 - 2012-06-01
* Copyright (c) 2012 Nexedi; Licensed */
// Adds 3 storages to JIO
// type:
// - local
// - dav
// - replicate
(function () {
var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
////////////////////////////////////////////////////////////////////////////
// Tools
var extend = function (o1,o2) {
var key;
for (key in o2) {
o1[key] = o2[key];
}
return o1;
},
// end Tools
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Classes
newLocalStorage,newDAVStorage,newReplicateStorage;
var newLocalStorage,newDAVStorage,newReplicateStorage,
newIndexedStorage,newCryptedStorage;
// end Classes
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Local Storage
/**
* JIO Local Storage. Type = 'local'.
* It is a database located in the browser local storage.
*/
newLocalStorage = function ( spec, my ) {
// LocalStorage constructor
var that = Jio.newBaseStorage( spec, my ), priv = {};
that.checkNameAvailability = function () {
// checks the availability of the [job.userName].
// if the name already exists, it is not available.
// this.job.userName: the name we want to check.
priv.storage_user_array_name = 'jio/localuserarray';
priv.storage_file_array_name = 'jio/localfilenamearray/' +
that.getStorageUserName() + '/' + that.getApplicantID();
/**
* Returns a list of users.
* @method getUserArray
* @return {array} The list of users.
*/
priv.getUserArray = function () {
return LocalOrCookieStorage.getItem(
priv.storage_user_array_name) || [];
};
/**
* Adds a user to the user list.
* @method addUser
* @param {string} username The user name.
*/
priv.addUser = function (username) {
var userarray = priv.getUserArray();
userarray.push(username);
LocalOrCookieStorage.setItem(priv.storage_user_array_name,
userarray);
};
/**
* Returns the file names of all existing files owned by the user.
* @method getFileNameArray
* @return {array} All the existing file paths.
*/
priv.getFileNameArray = function () {
return LocalOrCookieStorage.getItem(
priv.storage_file_array_name) || [];
};
/**
* Adds a file name to the local file name array.
* @method addFileName
* @param {string} filename The new file name.
*/
priv.addFileName = function (filename) {
var filenamearray = priv.getFileNameArray();
filenamearray.push(filename);
LocalOrCookieStorage.setItem(priv.storage_file_array_name,
filenamearray);
};
/**
* Removes a file name from the local file name array.
* @method removeFileName
* @param {string} filename The file name to remove.
*/
priv.removeFileName = function (filename) {
var i, l, array = priv.getFileNameArray(), newarray = [];
for (i = 0, l = array.length; i < l; i+= 1) {
if (array[i] !== filename) {
newarray.push(array[i]);
}
}
LocalOrCookieStorage.setItem(priv.storage_file_array_name,
newarray);
};
// wait a little in order to simulate asynchronous operation
/**
* Checks the availability of a user name set in the job.
* It will check if the user is set in the local user object
* @method checkNameAvailability
*/
that.checkNameAvailability = function () {
setTimeout(function () {
var localStorageObject = null, k, splitk;
localStorageObject = LocalOrCookieStorage.getAll();
for (k in localStorageObject) {
splitk = k.split('/');
if (splitk[0] === 'jio' &&
splitk[1] === 'local' &&
splitk[2] === that.getUserName()) {
return that.done(false);
var i, l, array = priv.getUserArray();
for (i = 0, l = array.length; i < l; i+= 1) {
if (array[i] === that.getUserName()) {
that.done(false);
return;
}
}
return that.done(true);
that.done(true);
}, 100);
}; // end checkNameAvailability
/**
* Saves a document in the local storage.
* It will store the file in 'jio/local/USR/APP/FILENAME'.
* @method saveDocument
*/
that.saveDocument = function () {
// Save a document in the local storage
// this.job.fileName: the document name.
// this.job.fileContent: the document content.
// this.job.storage: the storage information.
// this.job.storage.userName: the user name
// this.job.applicant.ID: the applicant id.
// wait a little in order to simulate asynchronous saving
setTimeout (function () {
var doc = null;
var doc = null, path =
'jio/local/'+that.getStorageUserName()+'/'+
that.getApplicantID()+'/'+
that.getFileName();
// reading
doc = LocalOrCookieStorage.getItem(
'jio/local/'+that.getStorageUserName()+'/'+
that.getApplicantID()+'/'+
that.getFileName());
doc = LocalOrCookieStorage.getItem(path);
if (!doc) {
// create document
doc = {
......@@ -82,32 +132,33 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
'creationDate': Date.now(),
'lastModified': Date.now()
};
priv.addFileName(that.getFileName());
} else {
// overwriting
doc.lastModified = Date.now();
doc.fileContent = that.getFileContent();
}
LocalOrCookieStorage.setItem(
'jio/local/'+that.getStorageUserName()+'/'+
that.getApplicantID()+'/'+
that.getFileName(), doc);
LocalOrCookieStorage.setItem(path, doc);
return that.done();
}, 100);
}; // end saveDocument
/**
* Loads a document from the local storage.
* It will load file in 'jio/local/USR/APP/FILENAME'.
* You can add an 'options' object to the job, it can contain:
* - metadata_only {boolean} default false, retrieve the file metadata
* only if true.
* - content_only {boolean} default false, retrieve the file content
* only if true.
* @method loadDocument
*/
that.loadDocument = function () {
// Load a document from the storage. It returns a document object
// containing all information of the document and its content.
// this.job.fileName : the document name we want to load.
// this.job.options.getContent: if true, also get the file content.
// document object is {'fileName':string,'fileContent':string,
// 'creationDate':date,'lastModified':date}
// wait a little in order to simulate asynchronous operation
setTimeout(function () {
var doc = null, settings = extend(
{'getContent':true},that.cloneOptionObject());
var doc = null, settings = that.cloneOptionObject();
doc = LocalOrCookieStorage.getItem(
'jio/local/'+that.getStorageUserName()+'/'+
......@@ -117,65 +168,64 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
message:'Document "'+ that.getFileName() +
'" not found in localStorage.'});
} else {
if (!settings.getContent) {
if (settings.metadata_only) {
delete doc.fileContent;
} else if (settings.content_only) {
delete doc.lastModified;
delete doc.creationDate;
}
that.done(doc);
}
}, 100);
}; // end loadDocument
/**
* Gets a document list from the local storage.
* It will retreive an array containing files meta data owned by
* the user.
* @method getDocumentList
*/
that.getDocumentList = function () {
// Get a document list from the storage. It returns a document
// array containing all the user documents informations.
// this.job.storage: the storage informations.
// this.job.storage.userName: the userName.
// this.job.storage.applicant.ID: the applicant ID.
// the list is [object,object] -> object = {'fileName':string,
// 'lastModified':date,'creationDate':date}
setTimeout(function () {
var list = [], localStorageObject = null, k = 'key',
splitk = ['splitedkey'], fileObject = {};
localStorageObject = LocalOrCookieStorage.getAll();
for (k in localStorageObject) {
splitk = k.split('/');
if (splitk[0] === 'jio' &&
splitk[1] === 'local' &&
splitk[2] === that.getStorageUserName() &&
splitk[3] === that.getApplicantID()) {
fileObject = JSON.parse(localStorageObject[k]);
list.push ({
'fileName':fileObject.fileName,
'creationDate':fileObject.creationDate,
'lastModified':fileObject.lastModified});
}
var newarray = [], array = [], i, l, k = 'key',
path = 'jio/local/'+that.getStorageUserName()+'/'+
that.getApplicantID(), fileObject = {};
array = priv.getFileNameArray();
for (i = 0, l = array.length; i < l; i += 1) {
fileObject =
LocalOrCookieStorage.getItem(path+'/'+array[i]);
newarray.push ({
'fileName':fileObject.fileName,
'creationDate':fileObject.creationDate,
'lastModified':fileObject.lastModified});
}
that.done(list);
that.done(newarray);
}, 100);
}; // end getDocumentList
/**
* Removes a document from the local storage.
* It will also remove the path from the local file array.
* @method removeDocument
*/
that.removeDocument = function () {
// Remove a document from the storage.
// this.job.storage.userName: the userName.
// this.job.applicant.ID: the applicant ID.
// this.job.fileName: the document name.
setTimeout (function () {
var path = 'jio/local/'+
that.getStorageUserName()+'/'+
that.getApplicantID()+'/'+
that.getFileName();
// deleting
LocalOrCookieStorage.deleteItem(
'jio/local/'+
that.getStorageUserName()+'/'+
that.getApplicantID()+'/'+
that.getFileName());
LocalOrCookieStorage.deleteItem(path);
priv.removeFileName(that.getFileName());
return that.done();
}, 100);
};
return that;
};
// end Local Storage
////////////////////////////////////////////////////////////////////////////
......@@ -195,7 +245,7 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
// TODO this method is not working !!!
var settings = extend ({
var settings = $.extend ({
'success':function(){},'error':function(){}},options),
splitpath = ['splitedpath'], tmppath = 'temp/path';
......@@ -328,9 +378,7 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
// 'creationDate':date,'lastModified':date}
var doc = {},
settings = extend({'getContent':true},that.cloneOptionObject()),
// TODO check if job's features are good
settings = that.cloneOptionObject(),
getContent = function () {
$.ajax ( {
url: that.getStorageLocation() + '/dav/' +
......@@ -362,6 +410,11 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
}
} );
};
doc.fileName = that.getFileName();
if (settings.content_only) {
getContent();
return;
}
// Get properties
$.ajax ( {
url: that.getStorageLocation() + '/dav/' +
......@@ -386,8 +439,7 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
).each( function () {
doc.creationDate = $(this).text();
});
doc.fileName = that.getFileName();
if (settings.getContent) {
if (!settings.metadata_only) {
getContent();
} else {
that.done(doc);
......@@ -532,7 +584,7 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
// this.job.userName: the name we want to check.
// this.job.storage.storageArray: An Array of storages.
var newjob = {}, i = 'id', done = false, errorArray = [],
var i = 'id', done = false, errorArray = [],
res = {'status':'done'}, callback = function (result) {
priv.returnsValuesArray.push(result);
if (!done) {
......@@ -575,7 +627,7 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
// this.job.fileName: the document name.
// this.job.fileContent: the document content.
var newjob = {}, res = {'status':'done'}, i = 'id',
var res = {'status':'done'}, i = 'id',
done = false, errorArray = [],
callback = function (result) {
priv.returnsValuesArray.push(result);
......@@ -612,7 +664,7 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
// this.job.storage.password: the user password.
// this.job.options.getContent: if true, also get the file content.
var newjob = {}, aredifferent = false, doc = {}, i = 'id',
var doc = {}, i = 'id',
done = false, errorArray = [],
res = {'status':'done'}, callback = function (result) {
priv.returnsValuesArray.push(result);
......@@ -646,7 +698,7 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
// this.job.storage.password: the user password.
// this.job.applicant.ID: the applicant id.
var newjob = {}, res = {'status':'done'}, i = 'id',
var res = {'status':'done'}, i = 'id',
done = false, errorArray = [],
callback = function (result) {
priv.returnsValuesArray.push(result);
......@@ -680,7 +732,7 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
// this.job.storage.password: the user password.
// this.job.applicant.ID: the applicant id.
var newjob = {}, res = {'status':'done'}, i = 'key',
var res = {'status':'done'}, i = 'key',
done = false, errorArray = [],
callback = function (result) {
priv.returnsValuesArray.push(result);
......@@ -709,17 +761,309 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
// end ReplicateStorage
////////////////////////////////////////////////////////////////////////////
// add key to storageObjectType of global jio
Jio.addStorageType('local', function (options) {
return newLocalStorage(options);
});
Jio.addStorageType('dav', function (options) {
return newDAVStorage(options);
});
Jio.addStorageType('replicate', function (options) {
return newReplicateStorage(options);
});
////////////////////////////////////////////////////////////////////////////
// Indexed Storage
/**
* JIO Indexed Storage. Type = 'indexed'.
* It retreives files metadata from another storage and keep them
* in a cache so that we can work faster.
*/
newIndexedStorage = function ( spec, my ) {
// IndexedStorage constructor
var that = Jio.newBaseStorage( spec, my ), priv = {};
priv.storage_array_name = 'jio/indexedstoragearray';
priv.storage_file_array_name = 'jio/indexedfilearray/'+
JSON.stringify (that.getSecondStorage()) + '/' +
that.getApplicantID();
/**
* Check if the indexed storage array exists.
* @method indexedStorageArrayExists
* @return {boolean} true if exists, else false
*/
priv.indexedStorageArrayExists = function () {
return (LocalOrCookieStorage.getItem(
priv.storage_array_name) ? true : false);
};
/**
* Returns a list of indexed storages.
* @method getIndexedStorageArray
* @return {array} The list of indexed storages.
*/
priv.getIndexedStorageArray = function () {
return LocalOrCookieStorage.getItem(
priv.storage_array_name) || [];
};
/**
* Adds a storage to the indexed storage list.
* @method addIndexedStorage
* @param {object} storage The new indexed storage.
*/
priv.addIndexedStorage = function (storage) {
var indexedstoragearray = priv.getIndexedStorageArray();
indexedstoragearray.push(JSON.stringify (storage));
LocalOrCookieStorage.setItem(priv.storage_array_name,
indexedstoragearray);
};
/**
* Checks if a storage exists in the indexed storage list.
* @method isAnIndexedStorage
* @param {object} storage The storage to find.
* @return {boolean} true if found, else false
*/
priv.isAnIndexedStorage = function (storage) {
var jsonstorage = JSON.stringify (storage),i,l,
array = priv.getIndexedStorageArray();
for (i = 0, l = array.length; i < l; i+= 1) {
if (JSON.stringify(array[i]) === jsonstorage) {
return true;
}
}
return false;
};
/**
* Checks if the file array exists.
* @method fileArrayExists
* @return {boolean} true if exists, else false
*/
priv.fileArrayExists = function () {
return (LocalOrCookieStorage.getItem (
priv.storage_file_array_name) ? true : false);
};
/**
* Returns the file from the indexed storage but not there content.
* @method getFileArray
* @return {array} All the existing file.
*/
priv.getFileArray = function () {
return LocalOrCookieStorage.getItem(
priv.storage_file_array_name) || [];
};
/**
* Sets the file array list.
* @method setFileArray
* @param {array} filearray The array containing files.
*/
priv.setFileArray = function (filearray) {
return LocalOrCookieStorage.setItem(
priv.storage_file_array_name,
filearray);
};
/**
* Checks if the file already exists in the array.
* @method isFileIndexed
* @param {string} filename The file we want to find.
* @return {boolean} true if found, else false
*/
priv.isFileIndexed = function (filename) {
var i, l, array = priv.getFileArray();
for (i = 0, l = array.length; i < l; i+= 1) {
if (array[i].fileName === filename){
return true;
}
}
return false;
};
/**
* Adds a file to the local file array.
* @method addFile
* @param {object} file The new file.
*/
priv.addFile = function (file) {
var filearray = priv.getFileArray();
filearray.push(file);
LocalOrCookieStorage.setItem(priv.storage_file_array_name,
filearray);
};
/**
* Removes a file from the local file array.
* @method removeFile
* @param {string} filename The file to remove.
*/
priv.removeFile = function (filename) {
var i, l, array = priv.getFileArray(), newarray = [];
for (i = 0, l = array.length; i < l; i+= 1) {
if (array[i].fileName !== filename) {
newarray.push(array[i]);
}
}
LocalOrCookieStorage.setItem(priv.storage_file_array_name,
newarray);
};
/**
* Updates the storage.
* It will retreive all files from a storage. It is an asynchronous task
* so the update can be on going even if IndexedStorage has already
* returned the result.
* @method update
*/
priv.update = function (callback) {
// retreive list before, and then retreive all files
var getlist_callback = function (result) {
if (result.status === 'done') {
if (!priv.isAnIndexedStorage(that.getSecondStorage())) {
priv.addIndexedStorage(that.getSecondStorage());
}
priv.setFileArray(result.return_value);
}
},
newjob = {
storage: that.getSecondStorage(),
applicant: {ID:that.getApplicantID()},
method: 'getDocumentList',
maxtries: 3,
callback: getlist_callback
};
that.addJob ( newjob );
};
/**
* Checks the availability of a user name set in the job.
* @method checkNameAvailability
*/
that.checkNameAvailability = function () {
var newjob = that.cloneJob();
priv.update();
newjob.storage = that.getSecondStorage();
newjob.callback = function (result) {
if (result.status === 'done') {
that.done(result.return_value);
} else {
that.fail(result.error);
}
};
that.addJob( newjob );
}; // end checkNameAvailability
/**
* Saves a document.
* @method saveDocument
*/
that.saveDocument = function () {
var newjob = that.cloneJob();
newjob.storage = that.getSecondStorage();
newjob.callback = function (result) {
if (result.status === 'done') {
if (!priv.isFileIndexed(that.getFileName())) {
priv.addFile({fileName:that.getFileName(),
lastModified:0,
creationDate:0});
}
priv.update();
that.done();
} else {
that.fail(result.error);
}
};
that.addJob ( newjob );
}; // end saveDocument
/**
* Loads a document.
* job.options.metadata_only {boolean}
* job.options.content_only {boolean}
* @method loadDocument
*/
that.loadDocument = function () {
var filearray, i, l, newjob,
loadcallback = function (result) {
if (result.status === 'done') {
// if (filearray[i].lastModified !==
// result.return_value.lastModified ||
// filearray[i].creationDate !==
// result.return_value.creationDate) {
// // the file in the index storage is different than
// // the one in the second storage. priv.update will
// // take care of refresh the indexed storage
// }
that.done(result.return_value);
} else {
that.fail(result.error);
}
},
secondLoadDocument = function () {
newjob = that.cloneJob();
newjob.storage = that.getSecondStorage();
newjob.callback = loadcallback;
console.log (newjob);
that.addJob ( newjob );
},
settings = that.cloneOptionObject();
priv.update();
if (settings.metadata_only) {
setTimeout(function () {
if (priv.fileArrayExists()) {
filearray = priv.getFileArray();
for (i = 0, l = filearray.length; i < l; i+= 1) {
if (filearray[i].fileName === that.getFileName()) {
return that.done(filearray[i]);
}
}
} else {
secondLoadDocument();
}
},100);
} else {
secondLoadDocument();
}
}; // end loadDocument
/**
* Gets a document list.
* @method getDocumentList
*/
that.getDocumentList = function () {
var id;
priv.update();
id = setInterval(function () {
if (priv.fileArrayExists()) {
that.done(priv.getFileArray());
clearInterval(id);
}
},100);
}; // end getDocumentList
/**
* Removes a document.
* @method removeDocument
*/
that.removeDocument = function () {
var newjob = that.cloneJob();
newjob.storage = that.getSecondStorage();
newjob.callback = function (result) {
if (result.status === 'done') {
priv.removeFile(that.getFileName());
priv.update();
that.done();
} else {
that.fail(result.error);
}
};
that.addJob(newjob);
};
return that;
};
// end Indexed Storage
////////////////////////////////////////////////////////////////////////////
// add key to storageObjectType of global jio
Jio.addStorageType('local', newLocalStorage);
Jio.addStorageType('dav', newDAVStorage);
Jio.addStorageType('replicate', newReplicateStorage);
Jio.addStorageType('indexed', newIndexedStorage);
};
if (window.requirejs) {
......
/*! JIO Storage - v0.1.0 - 2012-05-24
/*! JIO Storage - v0.1.0 - 2012-06-01
* Copyright (c) 2012 Nexedi; Licensed */
(function(){var a=function(a,b,c,d){var e=function(a,b){var c;for(c in b)a[c]=b[c];return a},f,g,h;f=function(b,d){var f=c.newBaseStorage(b,d),g={};return f.checkNameAvailability=function(){setTimeout(function(){var b=null,c,d;b=a.getAll();for(c in b){d=c.split("/");if(d[0]==="jio"&&d[1]==="local"&&d[2]===f.getUserName())return f.done(!1)}return f.done(!0)},100)},f.saveDocument=function(){setTimeout(function(){var b=null;return b=a.getItem("jio/local/"+f.getStorageUserName()+"/"+f.getApplicantID()+"/"+f.getFileName()),b?(b.lastModified=Date.now(),b.fileContent=f.getFileContent()):b={fileName:f.getFileName(),fileContent:f.getFileContent(),creationDate:Date.now(),lastModified:Date.now()},a.setItem("jio/local/"+f.getStorageUserName()+"/"+f.getApplicantID()+"/"+f.getFileName(),b),f.done()},100)},f.loadDocument=function(){setTimeout(function(){var b=null,c=e({getContent:!0},f.cloneOptionObject());b=a.getItem("jio/local/"+f.getStorageUserName()+"/"+f.getApplicantID()+"/"+f.getFileName()),b?(c.getContent||delete b.fileContent,f.done(b)):f.fail({status:404,statusText:"Not Found.",message:'Document "'+f.getFileName()+'" not found in localStorage.'})},100)},f.getDocumentList=function(){setTimeout(function(){var b=[],c=null,d="key",e=["splitedkey"],g={};c=a.getAll();for(d in c)e=d.split("/"),e[0]==="jio"&&e[1]==="local"&&e[2]===f.getStorageUserName()&&e[3]===f.getApplicantID()&&(g=JSON.parse(c[d]),b.push({fileName:g.fileName,creationDate:g.creationDate,lastModified:g.lastModified}));f.done(b)},100)},f.removeDocument=function(){setTimeout(function(){return a.deleteItem("jio/local/"+f.getStorageUserName()+"/"+f.getApplicantID()+"/"+f.getFileName()),f.done()},100)},f},g=function(a,f){var g=c.newBaseStorage(a,f);return g.mkcol=function(a){var c=e({success:function(){},error:function(){}},a),f=["splitedpath"],h="temp/path";if(!c.pathsteps)c.pathsteps=1,g.mkcol(c);else{f=c.path.split("/");if(c.pathsteps>=f.length-1)return c.success();f.length=c.pathsteps+1,c.pathsteps++,h=f.join("/"),d.ajax({url:c.location+h,type:"MKCOL",async:!0,headers:{Authorization:"Basic "+b.encode(c.userName+":"+c.password),Depth:"1"},success:function(){g.mkcol(c)},error:function(a){c.error()}})}},g.checkNameAvailability=function(){d.ajax({url:g.getStorageLocation()+"/dav/"+g.getStorageUserName()+"/",async:!0,type:"PROPFIND",dataType:"xml",headers:{Authorization:"Basic "+b.encode(g.getStorageUserName()+":"+g.getStoragePassword()),Depth:"1"},success:function(a){g.done(!1)},error:function(a){a.status===404?g.done(!0):(a.message='Cannot check availability of "'+g.getUserName()+'" into DAVStorage.',g.fail(a))}})},g.saveDocument=function(){d.ajax({url:g.getStorageLocation()+"/dav/"+g.getStorageUserName()+"/"+g.getApplicantID()+"/"+g.getFileName(),type:"PUT",data:g.getFileContent(),async:!0,dataType:"text",headers:{Authorization:"Basic "+b.encode(g.getStorageUserName()+":"+g.getStoragePassword())},success:function(){g.done()},error:function(a){a.message='Cannot save "'+g.getFileName()+'" into DAVStorage.',g.fail(a)}})},g.loadDocument=function(){var a={},c=e({getContent:!0},g.cloneOptionObject()),f=function(){d.ajax({url:g.getStorageLocation()+"/dav/"+g.getStorageUserName()+"/"+g.getApplicantID()+"/"+g.getFileName(),type:"GET",async:!0,dataType:"text",headers:{Authorization:"Basic "+b.encode(g.getStorageUserName()+":"+g.getStoragePassword())},success:function(b){a.fileContent=b,g.done(a)},error:function(a){a.status===404?a.message='Document "'+g.getFileName()+'" not found in localStorage.':a.message='Cannot load "'+g.getFileName()+'" from DAVStorage.',g.fail(a)}})};d.ajax({url:g.getStorageLocation()+"/dav/"+g.getStorageUserName()+"/"+g.getApplicantID()+"/"+g.getFileName(),type:"PROPFIND",async:!0,dataType:"xml",headers:{Authorization:"Basic "+b.encode(g.getStorageUserName()+":"+g.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()}),a.fileName=g.getFileName(),c.getContent?f():g.done(a)},error:function(a){a.message='Cannot load "'+g.getFileName()+'" informations from DAVStorage.',g.fail(a)}})},g.getDocumentList=function(){var a=[],c={},e=[];d.ajax({url:g.getStorageLocation()+"/dav/"+g.getStorageUserName()+"/"+g.getApplicantID()+"/",async:!0,type:"PROPFIND",dataType:"xml",headers:{Authorization:"Basic "+b.encode(g.getStorageUserName()+":"+g.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)}}),g.done(a)},error:function(a){a.message="Cannot get a document list from DAVStorage.",g.fail(a)}})},g.removeDocument=function(){d.ajax({url:g.getStorageLocation()+"/dav/"+g.getStorageUserName()+"/"+g.getApplicantID()+"/"+g.getFileName(),type:"DELETE",async:!0,headers:{Authorization:"Basic "+b.encode(g.getStorageUserName()+":"+g.getStoragePassword())},success:function(){g.done()},error:function(a){a.status===404?g.done():(a.message='Cannot remove "'+g.getFileName()+'" from DAVStorage.',g.fail(a))}})},g},h=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={},b="id",c=!1,f=[],g={status:"done"},h=function(a){e.returnsValuesArray.push(a);if(!c){if(a.status==="fail")g.status="fail",f.push(a.error);else if(a.return_value===!1){d.done(!1),c=!0;return}if(e.returnsValuesArray.length===e.length){g.status==="fail"?d.fail({status:207,statusText:"Multi-Status",message:'Some check availability of "'+d.getUserName()+'" requests have failed.',array:f}):d.done(!0),c=!0;return}}};e.execJobsFromStorageArray(h)},d.saveDocument=function(){var a={},b={status:"done"},c="id",f=!1,g=[],h=function(a){e.returnsValuesArray.push(a),f||(a.status!=="fail"?(d.done(),f=!0):(g.push(a.error),e.returnsValuesArray.length===e.length&&d.fail({status:207,statusText:"Multi-Status",message:'All save "'+d.getFileName()+'" requests have failed.',array:g})))};e.execJobsFromStorageArray(h)},d.loadDocument=function(){var a={},b=!1,c={},f="id",g=!1,h=[],i={status:"done"},j=function(a){e.returnsValuesArray.push(a),g||(a.status!=="fail"?(d.done(a.return_value),g=!0):(h.push(a.error),e.returnsValuesArray.length===e.length&&d.fail({status:207,statusText:"Multi-Status",message:'All load "'+d.getFileName()+'" requests have failed.',array:h})))};e.execJobsFromStorageArray(j)},d.getDocumentList=function(){var a={},b={status:"done"},c="id",f=!1,g=[],h=function(a){e.returnsValuesArray.push(a),f||(a.status!=="fail"?(d.done(a.return_value),f=!0):(g.push(a.error),e.returnsValuesArray.length===e.length&&d.fail({status:207,statusText:"Multi-Status",message:"All get document list requests have failed",array:g})))};e.execJobsFromStorageArray(h)},d.removeDocument=function(){var a={},b={status:"done"},c="key",f=!1,g=[],h=function(a){e.returnsValuesArray.push(a),f||(a.status!=="fail"?(d.done(),f=!0):(g.push(a.error),e.returnsValuesArray.length===e.length&&d.fail({status:207,statusText:"Multi-Status",message:'All remove "'+d.getFileName()+'" requests have failed.',array:g})))};e.execJobsFromStorageArray(h)},d},c.addStorageType("local",function(a){return f(a)}),c.addStorageType("dav",function(a){return g(a)}),c.addStorageType("replicate",function(a){return h(a)})};window.requirejs?define("JIOStorages",["LocalOrCookieStorage","Base64","JIO","jQuery"],a):a(LocalOrCookieStorage,Base64,JIO,jQuery)})();
\ No newline at end of file
(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)})();
\ No newline at end of file
/**
* Adds 3 storages to JIO.
* Adds 4 storages to JIO.
* - LocalStorage ('local')
* - DAVStorage ('dav')
* - ReplicateStorage ('replicate')
* - IndexedStorage ('indexed')
*
* @module JIOStorages
*/
......@@ -152,7 +153,10 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
* Loads a document from the local storage.
* It will load file in 'jio/local/USR/APP/FILENAME'.
* You can add an 'options' object to the job, it can contain:
* - getContent {boolean} default true, retrieve the file content or not
* - metadata_only {boolean} default false, retrieve the file metadata
* only if true.
* - content_only {boolean} default false, retrieve the file content
* only if true.
* @method loadDocument
*/
that.loadDocument = function () {
......@@ -160,8 +164,7 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
// 'creationDate':date,'lastModified':date}
setTimeout(function () {
var doc = null, settings = $.extend(
{'getContent':true},that.cloneOptionObject());
var doc = null, settings = that.cloneOptionObject();
doc = LocalOrCookieStorage.getItem(
'jio/local/'+that.getStorageUserName()+'/'+
......@@ -171,8 +174,11 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
message:'Document "'+ that.getFileName() +
'" not found in localStorage.'});
} else {
if (!settings.getContent) {
if (settings.metadata_only) {
delete doc.fileContent;
} else if (settings.content_only) {
delete doc.lastModified;
delete doc.creationDate;
}
that.done(doc);
}
......@@ -217,7 +223,7 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
var path = 'jio/local/'+
that.getStorageUserName()+'/'+
that.getApplicantID()+'/'+
that.getFileName()
that.getFileName();
// deleting
LocalOrCookieStorage.deleteItem(path);
priv.removeFileName(that.getFileName());
......@@ -378,9 +384,7 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
// 'creationDate':date,'lastModified':date}
var doc = {},
settings = $.extend({'getContent':true},that.cloneOptionObject()),
// TODO check if job's features are good
settings = that.cloneOptionObject(),
getContent = function () {
$.ajax ( {
url: that.getStorageLocation() + '/dav/' +
......@@ -412,6 +416,11 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
}
} );
};
doc.fileName = that.getFileName();
if (settings.content_only) {
getContent();
return;
}
// Get properties
$.ajax ( {
url: that.getStorageLocation() + '/dav/' +
......@@ -436,8 +445,7 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
).each( function () {
doc.creationDate = $(this).text();
});
doc.fileName = that.getFileName();
if (settings.getContent) {
if (!settings.metadata_only) {
getContent();
} else {
that.done(doc);
......@@ -582,7 +590,7 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
// this.job.userName: the name we want to check.
// this.job.storage.storageArray: An Array of storages.
var newjob = {}, i = 'id', done = false, errorArray = [],
var i = 'id', done = false, errorArray = [],
res = {'status':'done'}, callback = function (result) {
priv.returnsValuesArray.push(result);
if (!done) {
......@@ -625,7 +633,7 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
// this.job.fileName: the document name.
// this.job.fileContent: the document content.
var newjob = {}, res = {'status':'done'}, i = 'id',
var res = {'status':'done'}, i = 'id',
done = false, errorArray = [],
callback = function (result) {
priv.returnsValuesArray.push(result);
......@@ -662,7 +670,7 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
// this.job.storage.password: the user password.
// this.job.options.getContent: if true, also get the file content.
var newjob = {}, aredifferent = false, doc = {}, i = 'id',
var doc = {}, i = 'id',
done = false, errorArray = [],
res = {'status':'done'}, callback = function (result) {
priv.returnsValuesArray.push(result);
......@@ -696,7 +704,7 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
// this.job.storage.password: the user password.
// this.job.applicant.ID: the applicant id.
var newjob = {}, res = {'status':'done'}, i = 'id',
var res = {'status':'done'}, i = 'id',
done = false, errorArray = [],
callback = function (result) {
priv.returnsValuesArray.push(result);
......@@ -730,7 +738,7 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
// this.job.storage.password: the user password.
// this.job.applicant.ID: the applicant id.
var newjob = {}, res = {'status':'done'}, i = 'key',
var res = {'status':'done'}, i = 'key',
done = false, errorArray = [],
callback = function (result) {
priv.returnsValuesArray.push(result);
......@@ -759,17 +767,309 @@ var jio_storage_loader = function ( LocalOrCookieStorage, Base64, Jio, $) {
// end ReplicateStorage
////////////////////////////////////////////////////////////////////////////
// add key to storageObjectType of global jio
Jio.addStorageType('local', function (options) {
return newLocalStorage(options);
});
Jio.addStorageType('dav', function (options) {
return newDAVStorage(options);
});
Jio.addStorageType('replicate', function (options) {
return newReplicateStorage(options);
});
////////////////////////////////////////////////////////////////////////////
// Indexed Storage
/**
* JIO Indexed Storage. Type = 'indexed'.
* It retreives files metadata from another storage and keep them
* in a cache so that we can work faster.
*/
newIndexedStorage = function ( spec, my ) {
// IndexedStorage constructor
var that = Jio.newBaseStorage( spec, my ), priv = {};
priv.storage_array_name = 'jio/indexedstoragearray';
priv.storage_file_array_name = 'jio/indexedfilearray/'+
JSON.stringify (that.getSecondStorage()) + '/' +
that.getApplicantID();
/**
* Check if the indexed storage array exists.
* @method indexedStorageArrayExists
* @return {boolean} true if exists, else false
*/
priv.indexedStorageArrayExists = function () {
return (LocalOrCookieStorage.getItem(
priv.storage_array_name) ? true : false);
};
/**
* Returns a list of indexed storages.
* @method getIndexedStorageArray
* @return {array} The list of indexed storages.
*/
priv.getIndexedStorageArray = function () {
return LocalOrCookieStorage.getItem(
priv.storage_array_name) || [];
};
/**
* Adds a storage to the indexed storage list.
* @method addIndexedStorage
* @param {object} storage The new indexed storage.
*/
priv.addIndexedStorage = function (storage) {
var indexedstoragearray = priv.getIndexedStorageArray();
indexedstoragearray.push(JSON.stringify (storage));
LocalOrCookieStorage.setItem(priv.storage_array_name,
indexedstoragearray);
};
/**
* Checks if a storage exists in the indexed storage list.
* @method isAnIndexedStorage
* @param {object} storage The storage to find.
* @return {boolean} true if found, else false
*/
priv.isAnIndexedStorage = function (storage) {
var jsonstorage = JSON.stringify (storage),i,l,
array = priv.getIndexedStorageArray();
for (i = 0, l = array.length; i < l; i+= 1) {
if (JSON.stringify(array[i]) === jsonstorage) {
return true;
}
}
return false;
};
/**
* Checks if the file array exists.
* @method fileArrayExists
* @return {boolean} true if exists, else false
*/
priv.fileArrayExists = function () {
return (LocalOrCookieStorage.getItem (
priv.storage_file_array_name) ? true : false);
};
/**
* Returns the file from the indexed storage but not there content.
* @method getFileArray
* @return {array} All the existing file.
*/
priv.getFileArray = function () {
return LocalOrCookieStorage.getItem(
priv.storage_file_array_name) || [];
};
/**
* Sets the file array list.
* @method setFileArray
* @param {array} filearray The array containing files.
*/
priv.setFileArray = function (filearray) {
return LocalOrCookieStorage.setItem(
priv.storage_file_array_name,
filearray);
};
/**
* Checks if the file already exists in the array.
* @method isFileIndexed
* @param {string} filename The file we want to find.
* @return {boolean} true if found, else false
*/
priv.isFileIndexed = function (filename) {
var i, l, array = priv.getFileArray();
for (i = 0, l = array.length; i < l; i+= 1) {
if (array[i].fileName === filename){
return true;
}
}
return false;
};
/**
* Adds a file to the local file array.
* @method addFile
* @param {object} file The new file.
*/
priv.addFile = function (file) {
var filearray = priv.getFileArray();
filearray.push(file);
LocalOrCookieStorage.setItem(priv.storage_file_array_name,
filearray);
};
/**
* Removes a file from the local file array.
* @method removeFile
* @param {string} filename The file to remove.
*/
priv.removeFile = function (filename) {
var i, l, array = priv.getFileArray(), newarray = [];
for (i = 0, l = array.length; i < l; i+= 1) {
if (array[i].fileName !== filename) {
newarray.push(array[i]);
}
}
LocalOrCookieStorage.setItem(priv.storage_file_array_name,
newarray);
};
/**
* Updates the storage.
* It will retreive all files from a storage. It is an asynchronous task
* so the update can be on going even if IndexedStorage has already
* returned the result.
* @method update
*/
priv.update = function (callback) {
// retreive list before, and then retreive all files
var getlist_callback = function (result) {
if (result.status === 'done') {
if (!priv.isAnIndexedStorage(that.getSecondStorage())) {
priv.addIndexedStorage(that.getSecondStorage());
}
priv.setFileArray(result.return_value);
}
},
newjob = {
storage: that.getSecondStorage(),
applicant: {ID:that.getApplicantID()},
method: 'getDocumentList',
maxtries: 3,
callback: getlist_callback
};
that.addJob ( newjob );
};
/**
* Checks the availability of a user name set in the job.
* @method checkNameAvailability
*/
that.checkNameAvailability = function () {
var newjob = that.cloneJob();
priv.update();
newjob.storage = that.getSecondStorage();
newjob.callback = function (result) {
if (result.status === 'done') {
that.done(result.return_value);
} else {
that.fail(result.error);
}
};
that.addJob( newjob );
}; // end checkNameAvailability
/**
* Saves a document.
* @method saveDocument
*/
that.saveDocument = function () {
var newjob = that.cloneJob();
newjob.storage = that.getSecondStorage();
newjob.callback = function (result) {
if (result.status === 'done') {
if (!priv.isFileIndexed(that.getFileName())) {
priv.addFile({fileName:that.getFileName(),
lastModified:0,
creationDate:0});
}
priv.update();
that.done();
} else {
that.fail(result.error);
}
};
that.addJob ( newjob );
}; // end saveDocument
/**
* Loads a document.
* job.options.metadata_only {boolean}
* job.options.content_only {boolean}
* @method loadDocument
*/
that.loadDocument = function () {
var filearray, i, l, newjob,
loadcallback = function (result) {
if (result.status === 'done') {
// if (filearray[i].lastModified !==
// result.return_value.lastModified ||
// filearray[i].creationDate !==
// result.return_value.creationDate) {
// // the file in the index storage is different than
// // the one in the second storage. priv.update will
// // take care of refresh the indexed storage
// }
that.done(result.return_value);
} else {
that.fail(result.error);
}
},
secondLoadDocument = function () {
newjob = that.cloneJob();
newjob.storage = that.getSecondStorage();
newjob.callback = loadcallback;
console.log (newjob);
that.addJob ( newjob );
},
settings = that.cloneOptionObject();
priv.update();
if (settings.metadata_only) {
setTimeout(function () {
if (priv.fileArrayExists()) {
filearray = priv.getFileArray();
for (i = 0, l = filearray.length; i < l; i+= 1) {
if (filearray[i].fileName === that.getFileName()) {
return that.done(filearray[i]);
}
}
} else {
secondLoadDocument();
}
},100);
} else {
secondLoadDocument();
}
}; // end loadDocument
/**
* Gets a document list.
* @method getDocumentList
*/
that.getDocumentList = function () {
var id;
priv.update();
id = setInterval(function () {
if (priv.fileArrayExists()) {
that.done(priv.getFileArray());
clearInterval(id);
}
},100);
}; // end getDocumentList
/**
* Removes a document.
* @method removeDocument
*/
that.removeDocument = function () {
var newjob = that.cloneJob();
newjob.storage = that.getSecondStorage();
newjob.callback = function (result) {
if (result.status === 'done') {
priv.removeFile(that.getFileName());
priv.update();
that.done();
} else {
that.fail(result.error);
}
};
that.addJob(newjob);
};
return that;
};
// end Indexed Storage
////////////////////////////////////////////////////////////////////////////
// add key to storageObjectType of global jio
Jio.addStorageType('local', newLocalStorage);
Jio.addStorageType('dav', newDAVStorage);
Jio.addStorageType('replicate', newReplicateStorage);
Jio.addStorageType('indexed', newIndexedStorage);
};
if (window.requirejs) {
......
......@@ -871,6 +871,136 @@ test ('Remove document', function () {
mytest('DummyStorageAllOK,3tries: remove document.','done');
o.jio.stop();
});
module ('Jio IndexedStorage');
test ('Check name availability', function () {
var o = {}, clock = this.sandbox.useFakeTimers(), t = this,
mytest = function (message,value) {
o.f = function (result) {
deepEqual (result.return_value,value,message);};
t.spy(o,'f');
o.jio.checkNameAvailability({userName:'MrIndexedCheck',
callback:o.f,maxtries:3});
clock.tick(100000);
if (!o.f.calledOnce) {
ok(false, 'no response / too much results');
}
};
o.jio=JIO.createNew({type:'indexed',
storage:{type:'dummyall3tries',
userName:'indexedcheck'}},
{ID:'jiotests'});
mytest('dummy ok : name must be available', true);
o.jio.stop();
});
test ('Document load', function () {
var o = {}, clock = this.sandbox.useFakeTimers();
o.jio=JIO.createNew({type:'indexed',
storage:{type:'dummyall3tries',
userName:'indexedload'}},
{ID:'jiotests'});
// loading must take long time with dummyall3tries
o.f = function () {};
this.spy(o,'f');
o.jio.loadDocument({fileName:'memo',maxtries:3,callback:o.f,
options:{metadata_only:true}});
clock.tick(500);
ok(!o.f.calledOnce,'Callback must not be called');
// wait long time too retreive list
clock.tick(100000);
// now we can test if the document metadata are loaded faster.
o.doc = {fileName:'memo',lastModified:25000,creationDate:20000};
o.f2 = function (result) {
deepEqual (result.return_value,o.doc,'Document metadata retrieved');
};
this.spy(o,'f2');
o.jio.loadDocument({fileName:'memo',maxtries:3,callback:o.f2,
options:{metadata_only:true}});
clock.tick(500);
if (!o.f2.calledOnce) {
ok (false, 'no response / too much results');
}
// test a simple document loading
o.doc2 = {fileName:'file',lastModified:17000,
creationDate:11000,fileContent:'content2'};
o.f3 = function (result) {
deepEqual (result.return_value,o.doc2,'Simple document loading');
};
this.spy(o,'f3');
o.jio.loadDocument({fileName:'file',maxtries:3,callback:o.f3});
clock.tick(100000);
if (!o.f3.calledOnce) {
ok (false, 'no response / too much results');
}
o.jio.stop();
});
test ('Document save', function () {
var o = {}, clock = this.sandbox.useFakeTimers();
o.jio=JIO.createNew({type:'indexed',
storage:{type:'dummyall3tries',
userName:'indexedsave'}},
{ID:'jiotests'});
o.f = function (result) {
deepEqual (result.status,'done','document save');
};
this.spy(o,'f');
o.jio.saveDocument({fileName:'file',maxtries:3,callback:o.f});
clock.tick(100000);
if (!o.f.calledOnce){
ok (false, 'no response / too much results');
}
o.jio.stop();
});
test ('Get document list', function () {
var o = {}, clock = this.sandbox.useFakeTimers();
o.jio=JIO.createNew({type:'indexed',
storage:{type:'dummyall3tries',
userName:'indexedgetlist'}},
{ID:'jiotests'});
o.doc1 = {fileName:'file',lastModified:15000,creationDate:10000};
o.doc2 = {fileName:'memo',lastModified:25000,creationDate:20000};
// getting list must take long time with dummyall3tries
o.f = function () {};
this.spy(o,'f');
o.jio.getDocumentList({maxtries:3,callback:o.f});
clock.tick(500);
ok(!o.f.calledOnce,'Callback must not be called');
// wail long time too retreive list
clock.tick(100000);
// now we can test if the document list is loaded faster
o.f2 = function (result) {
deepEqual (result.return_value,[o.doc1,o.doc2],'get document list');
};
this.spy(o,'f2');
o.jio.getDocumentList({maxtries:3,callback:o.f2});
clock.tick(500);
if (!o.f2.calledOnce) {
ok (false, 'no response / too much results');
}
});
test ('Remove document', function () {
var o = {}, clock = this.sandbox.useFakeTimers();
o.jio=JIO.createNew({type:'indexed',
storage:{type:'dummyall3tries',
userName:'indexedsave'}},
{ID:'jiotests'});
o.f = function (result) {
deepEqual (result.status,'done','document remove');
};
this.spy(o,'f');
o.jio.removeDocument({fileName:'file',maxtries:3,callback:o.f});
clock.tick(100000);
if (!o.f.calledOnce){
ok (false, 'no response / too much results');
}
o.jio.stop();
});
// end require
}; // end thisfun
......
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