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

Events are no longer necessary to use JIO, and doesn't exist anymore (for now).

Publisher, Subscriber and Unsubscriber works.
We can now create most than one instance of JIO with "var j=JIO.createNew()".
Doc strings can realy help us to use JIO now.
Qunit tests for localStorage are not completly finished yet.
DavStorage have to be modified a little to make it complete.
ReplicateStorage does not exist yet.
parent 741a9b4f
...@@ -15,24 +15,28 @@ var globalID = setInterval (function (){ ...@@ -15,24 +15,28 @@ var globalID = setInterval (function (){
case 1: globalTestIndex = globalIndex; case 1: globalTestIndex = globalIndex;
test ( "Jio simple methods", function () { test ( "Jio simple methods", function () {
ok ( $.jio('addStorageType',{'type':'qunit','creator':function(){}}) var ca = $.Callbacks();
, "storage type qunit added."); console.log (ca);
var tmp = $.jio('isReady'); o.jio = JIO.createNew();
ok ( tmp === false, 'isReady === ' +tmp); ok ( o.jio, 'a new jio -> 1');
var tmp = $.jio({'storage':{'type':'local','userName':'myName'}, o.jio2 = JIO.createNew();
'applicant':{'ID':'myID'}}); ok ( o.jio2, 'another new jio -> 2');
ok ( tmp === true, 'initialized ? ' + tmp ); ok ( JIO.addStorageType('qunit', function(){}) ,
var tmp = $.jio('isReady'); "adding storage type.");
ok ( tmp === true, 'isReady === ' +tmp); deepEqual ( o.jio.isReady(), false, '1 must be not ready');
var tmp = $.jio('getApplicant'); deepEqual ( o.jio.start(), true, '1 must be ready now');
deepEqual ( tmp , {'ID':'myID'}, o.jio2.start();
'get the good applicant.' ); ok ( o.jio2.id !== o.jio.id, '1 and 2 must be different');
deepEqual ( o.jio.stop(), true, '1 must be stopped');
o.jio2.stop();
globalIndex++; globalIndex++;
}); });
break; break;
case 2: globalTestIndex = globalIndex; case 2: globalTestIndex = globalIndex;
o.local = {}; o.local = {};
o.local.jio = JIO.createNew();
o.local.jio.start();
test ( 'Jio Pub/Sub methods', function () { test ( 'Jio Pub/Sub methods', function () {
stop(); stop();
var i = 1, ti = 0, m = 10; var i = 1, ti = 0, m = 10;
...@@ -43,14 +47,12 @@ var globalID = setInterval (function (){ ...@@ -43,14 +47,12 @@ var globalID = setInterval (function (){
break; break;
case 1: // if(i===ti)return;ti=i; // force do only one time case 1: // if(i===ti)return;ti=i; // force do only one time
o.local.pubsub_test = false; o.local.pubsub_test = false;
$.jio('subscribe', o.local.pubsub_callback = o.local.jio.subscribe(
{'event':'pubsub_test', 'func': 'pubsub_test',function () {
function () {
o.local.pubsub_test = true; o.local.pubsub_test = true;
}}); });
$.jio('publish',{'event':'pubsub_test'}); o.local.jio.publish('pubsub_test');
i++; i++; break;
break;
case 5: // wait a little case 5: // wait a little
deepEqual (o.local.pubsub_test, true, deepEqual (o.local.pubsub_test, true,
'subscribe & publish'); 'subscribe & publish');
...@@ -63,16 +65,19 @@ var globalID = setInterval (function (){ ...@@ -63,16 +65,19 @@ var globalID = setInterval (function (){
break; break;
case 6: case 6:
o.local.pubsub_test = false; o.local.pubsub_test = false;
$.jio('unsubscribe',{'event':'pubsub_test'}); o.local.jio.unsubscribe('pubsub_test',
$.jio('publish',{'event':'pubsub_test'}); o.local.pubsub_callback);
o.local.jio.publish('pubsub_test');
i ++; i ++;
break; break;
case 9: // wait a little case 9: // wait a little
deepEqual (o.local.pubsub_test, false, deepEqual (o.local.pubsub_test, false,
'unsubscribe'); 'unsubscribe');
o.local.pubsub_test = !o.local.pubsub_test;
i++; i++;
break; break;
case m: case m:
o.local.jio.stop();
start(); start();
globalIndex++; globalIndex++;
clearInterval(id); clearInterval(id);
...@@ -84,199 +89,90 @@ var globalID = setInterval (function (){ ...@@ -84,199 +89,90 @@ var globalID = setInterval (function (){
case 3: globalTestIndex = globalIndex; case 3: globalTestIndex = globalIndex;
test ( 'LocalStorage' , function () { test ( 'LocalStorage' , function () {
stop(); stop();
var i = 1, ti = 0, m = 31; var i = 0, ti = -1, m = 20;
var id = setInterval(function (){ var id = setInterval(function (){
switch(i){ switch(i){
default: default:
i++; i++;
break; break;
case 1: case 0:
o.local.start_check = false; o.local.jio = JIO.createNew({
o.local.stop_check = false; 'type':'local',
o.local.ret_check = false; 'userName':'myName'
o.start_check_func = function () { },{'ID':'myApp'});
o.local.start_check = true; o.local.jio.start();
};
o.stop_check_func = function (e) {
o.local.ret_check = e.job.isAvailable;
o.local.stop_check = true;
};
$.jio('subscribe',{'event':'start_checkingNameAvailability',
'func':function (e) {
o.start_check_func(e);
}})
$.jio('subscribe',{'event':'stop_checkingNameAvailability',
'func':function (e) {
o.stop_check_func(e);
}})
$.jio('checkNameAvailability',{'userName':'myName'});
i++;
break;
case 5: // wait a little
deepEqual ( [o.local.start_check,
o.local.stop_check,
o.local.ret_check],
[true,true,true],
'checking name availability');
i++;
break;
case 6:
o.local.start_save = false;
o.local.stop_save = false;
o.local.ret_save = false;
o.start_save_func = function () {
o.local.start_save = true;
};
o.job_done_func = function (e) {
o.local.ret_save = e.job.isSaved;
};
o.stop_save_func = function () {
o.local.stop_save = true;
};
$.jio('subscribe',{'event':'start_saving',
'func':function (e) {
o.start_save_func(e);
}})
$.jio('subscribe',{'event':'job_done',
'func':function(e){
o.job_done_func(e);}
});
$.jio('subscribe',{'event':'stop_saving',
'func':function (e) {
o.stop_save_func(e);
}})
$.jio('saveDocument',{'fileName':'file',
'fileContent':'content'});
i++;
break;
case 10: // wait a little
deepEqual ( [o.local.start_save,
o.local.stop_save,
o.local.ret_save],
[true,true,true],
'saving');
i++;
break;
case 11:
o.local.start_check = false;
o.local.stop_check = false;
o.local.ret_check = true;
// already subscribed
$.jio('checkNameAvailability',{'userName':'myName'});
i++; i++;
break; break;
case 15: // wait a little case 1:i++;
deepEqual ( [o.local.start_check, //// test check name
o.local.stop_check, o.local.check_test = null;
o.local.ret_check], o.local.jio.checkNameAvailability(
[true,true,false], {'userName':'myName','callback': function (result) {
'checking name availability'); o.local.check_test = result.isAvailable;
i++; i = 3;
break; }});
case 16:
o.local.start_load = false;
o.local.stop_load = false;
o.local.ret_load = null;
o.start_load_func = function () {
o.local.start_load = true;
};
o.job_done_func = function (e) {
o.local.ret_load = e.job.fileContent;
};
o.stop_load_func = function () {
o.local.stop_load = true;
};
$.jio('subscribe',{'event':'start_loading',
'func':function (e) {
o.start_load_func(e);
}})
$.jio('subscribe',{'event':'stop_loading',
'func':function (e) {
o.stop_load_func(e);
}})
$.jio('loadDocument',{'fileName':'file'});
i++;
break; break;
case 20: // wait a little case 2: break;
deepEqual ( [o.local.start_load, case 3: i++;
o.local.stop_load, deepEqual (o.local.check_test, true,
o.local.ret_load], 'name must be available');
[true,true,'content'], //// test save document
'loading'); o.local.jio.save_test = null;
i++; o.local.jio.saveDocument(
{'fileName':'file','fileContent':'content','callback':
function (result) {
o.local.save_test = result.isSaved;
i = 5;
}});
break; break;
case 21: case 4: break;
o.local.start_getlist = false; case 5: i++;
o.local.stop_getlist = false; deepEqual (o.local.save_test, true,
o.local.ret_getlist_at_job = []; 'document must be saved');
o.local.ret_getlist_at_stop = []; //// test check name
o.start_getlist_func = function () { o.local.check_test = null;
o.local.start_getlist = true; o.local.jio.checkNameAvailability(
}; {'userName':'myName','callback': function (result) {
o.job_done_func = function (e) { o.local.check_test = result.isAvailable;
o.local.ret_getlist_at_job = e.job.list; i = 7;
}; }});
o.stop_getlist_func = function (e) {
o.local.ret_getlist_at_stop = e.job.list;
o.local.stop_getlist = true;
};
$.jio('subscribe',{'event':'start_gettingList',
'func':function (e) {
o.start_getlist_func(e);
}})
$.jio('subscribe',{'event':'stop_gettingList',
'func':function (e) {
o.stop_getlist_func(e);
}})
$.jio('getDocumentList');
i++;
break; break;
case 25: // wait a little case 6: break;
var expected = JSON.parse( case 7: i++;
localStorage['jio/local/myName/myID/file']); deepEqual (o.local.check_test, false,
delete expected.fileContent; 'name must be unavailable');
expected = [expected]; //// test get list
deepEqual ( [o.local.start_getlist, o.local.getlist_test = null;
o.local.stop_getlist, o.local.jio.getDocumentList(
o.local.ret_getlist_at_job, {'callback': function (result) {
o.local.ret_getlist_at_stop], o.local.getlist_test = result.list;
[true,true,expected,expected], i = 9;
'get list'); }});
i++;
break; break;
case 26: case 8: break;
o.local.start_remove = false; case 9: i++;
o.local.stop_remove = false; if (o.local.getlist_test) {
o.local.ret_remove = false; delete o.local.getlist_test[0].lastModified;
o.start_remove_func = function () { delete o.local.getlist_test[0].creationDate;
o.local.start_remove = true; }
}; deepEqual (o.local.getlist_test,
o.job_done_func = function (e) { [{'fileName':'file'}],
o.local.ret_remove = e.job.isRemoved; 'list must contain one file');
}; //// test remove document
o.stop_remove_func = function () { o.local.remove_test = null;
o.local.stop_remove = true; o.local.jio.removeDocument(
}; {'fileName':'file','callback': function (result) {
$.jio('subscribe',{'event':'start_removing', o.local.remove_test = result.isRemoved;
'func':function (e) { i = 11;
o.start_remove_func(e); }});
}})
$.jio('subscribe',{'event':'stop_removing',
'func':function (e) {
o.stop_remove_func(e);
}})
$.jio('removeDocument',{'fileName':'file'});
i++;
break; break;
case 30: // wait a little case 10: break;
deepEqual ( [o.local.start_remove, case 11: i++;
o.local.stop_remove, deepEqual (o.local.remove_test, true,
o.local.ret_remove], 'file must be removed');
[true,true,true],
'remove');
i++;
break; break;
case m: case m:
o.local.jio.stop();
start(); start();
globalIndex++; globalIndex++;
clearInterval(id); clearInterval(id);
......
;(function ( $ ) { ;var JIO =
(function () {
// check dependencies
var errorDependencies=function(){console.error('Cannot find jQuery.');};
try{if(!jQuery){
errorDependencies();return null;
}}catch(e){
errorDependencies();return null;}
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
// constants // constants
var jioAttributeObject = { var jioConstObj = {
'jobMethodObject': { 'jobMethodObject': {
'checkNameAvailability': { 'checkNameAvailability': {
'start_event':'start_checkingNameAvailability', 'start_event':'start_checkingNameAvailability',
...@@ -25,25 +33,24 @@ ...@@ -25,25 +33,24 @@
'start_event':'start_removing', 'start_event':'start_removing',
'stop_event':'stop_removing', 'stop_event':'stop_removing',
'retvalue':'isRemoved' } // returns 'boolean' 'retvalue':'isRemoved' } // returns 'boolean'
}, }
};
// end constants
////////////////////////////////////////////////////////////////////////////
// jio globals
var jioGlobalObj = {
'localStorage': null, // where the browser stores data 'localStorage': null, // where the browser stores data
'tabid': 0, // this jio id 'queueID': 1,
'queue': null, // the job manager
'storage': null, // the storage given at init
'applicant': null, // the applicant given at init
'listener': null, // the job listener
'pubsub': null, // publisher subscriber
'isReady': false, // check if jio is ready
'storageTypeObject': {} // ex: {'type':'local','creator': fun ...} 'storageTypeObject': {} // ex: {'type':'local','creator': fun ...}
}; };
// end constants // end jio globals
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
// cookies & localStorage // cookies & localStorage
var myLocalStorage = function () { var browserStorage = function () {
}; };
myLocalStorage.prototype = { browserStorage.prototype = {
getItem: function (name) { getItem: function (name) {
return JSON.parse(localStorage.getItem(name)); return JSON.parse(localStorage.getItem(name));
}, },
...@@ -102,13 +109,13 @@ ...@@ -102,13 +109,13 @@
// set good localStorage // set good localStorage
try { try {
if (localStorage.getItem) { if (localStorage.getItem) {
jioAttributeObject.localStorage = new myLocalStorage(); jioGlobalObj.localStorage = new browserStorage();
} else { } else {
jioAttributeObject.localStorage = new cookieStorage(); jioGlobalObj.localStorage = new cookieStorage();
} }
} }
catch (e) { catch (e) {
jioAttributeObject.localStorage = new cookieStorage(); jioGlobalObj.localStorage = new cookieStorage();
} }
// end cookies & localStorages // end cookies & localStorages
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
...@@ -118,18 +125,36 @@ ...@@ -118,18 +125,36 @@
var createStorageObject = function ( options ) { var createStorageObject = function ( options ) {
// Create a storage thanks to storages types set with 'addStorageType'. // Create a storage thanks to storages types set with 'addStorageType'.
if (!jioAttributeObject.storageTypeObject[ options.storage.type ]) if (!jioGlobalObj.storageTypeObject[ options.storage.type ])
return null; // error! return null; // error!
return jioAttributeObject.storageTypeObject[ return jioGlobalObj.storageTypeObject[
options.storage.type ](options); options.storage.type ](options);
}; };
var getNewQueueID = function () {
// Returns a new queueID
var localStor = jioGlobalObj.localStorage.getAll();
for (var k in localStor) {
var splitk = k.split('/');
if (splitk[0] === 'jio' &&
splitk[1] === 'id') {
if (JSON.parse(localStor[k]) < Date.now() - 10000) { // 10 sec ?
jioGlobalObj.localStorage.deleteItem(k);
}
if (JSON.parse(splitk[2]) >= jioGlobalObj.queueID) {
jioGlobalObj.queueID = JSON.parse(splitk[2]) + 1;
}
}
}
var id = jioGlobalObj.queueID;
jioGlobalObj.queueID ++;
return id;
};
// end Tools // end Tools
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
// Publisher Subcriber // Publisher Subcriber
var PubSub = function () { var PubSub = function () {
if (!this.eventAction) {
var topics = {}; var topics = {};
this.eventAction = function (id) { this.eventAction = function (id) {
var callbacks; var callbacks;
...@@ -147,20 +172,22 @@ ...@@ -147,20 +172,22 @@
} }
return topic; return topic;
}; };
}
}; };
PubSub.prototype = { PubSub.prototype = {
publish: function (eventname,obj) { publish: function (eventname,obj) {
// publish an event
this.eventAction(eventname).publish(obj); this.eventAction(eventname).publish(obj);
}, },
subscribe: function (eventname,func) { subscribe: function (eventname,callback) {
this.eventAction(eventname).subscribe(func); // subscribe and return the callback function
this.eventAction(eventname).subscribe(callback);
return callback;
}, },
unsubscribe: function (eventname) { unsubscribe: function (eventname,callback) {
this.eventAction(eventname).unsubscribe(); // unsubscribe the callback from eventname
this.eventAction(eventname).unsubscribe(callback);
} }
}; };
jioAttributeObject.pubsub = new PubSub();
// end Publisher Subcriber // end Publisher Subcriber
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
...@@ -176,93 +203,44 @@ ...@@ -176,93 +203,44 @@
return job; return job;
}; };
var JobQueue = function () { var JobQueue = function ( publisher ) {
// JobQueue is a queue of jobs. It will regulary copy this queue // JobQueue is a queue of jobs. It will regulary copy this queue
// into localStorage to resume undone tasks. // into localStorage to resume undone tasks.
// pubsub: the publisher to use to send event
// restore job list from local storage, if it exists this.publisher = publisher;
this.jobObject = jioAttributeObject.localStorage.getItem(
'jio/jobObject/' + jioAttributeObject.tabid);
if (!this.jobObject) this.jobObject = {};
//// set first job ID
console.log ('Queue');
this.jobid = 1; this.jobid = 1;
for (var id in this.jobObject) { this.jioID = 0;
if ( this.jobObject[id].id > this.jobid ) { this.jobObjectName = '';
this.jobid = this.jobObject[id].id; this.jobObject = {};
}
}
this.jobid++;
// reset all jobs' status to initial // reset all jobs' status to initial
this.resetAll(); this.resetAll();
var t = this;
var returnedJobAnalyse = function ( job ) {
// analyse the [job]
// if the job method does not exists, return false
if (!jioAttributeObject.jobMethodObject[job.method])
return false;
// if there isn't some job to do, then send stop event
if (!t.isThereJobsWhere(function(testjob){
return (testjob.method === job.method &&
testjob.status !== 'fail');
})) {
switch (job.method) {
// TODO merging is done with jio? or by the user's scripts?
case 'checkNameAvailability':
// TODO merge name availability between storages
// TODO send job ?
$.jio('publish',{'event':
jioAttributeObject.jobMethodObject[
job.method].stop_event, 'job':job});
return;
case 'getDocumentList':
// TODO merge list if necessary (we can create
// this.getList, deleted after sending the event,
// filled with done event) -> merge here or show
// possible actions (manually, auto, ...)
$.jio('publish',{'event':
jioAttributeObject.jobMethodObject[
job.method].stop_event , 'job':job});
///*, 'retvalue': merged list */});
// delete list
return;
default:
$.jio('publish',{'event':
jioAttributeObject.jobMethodObject[
job.method].stop_event});
return;
}
}
}; // end returnedJobAnalyse
//// sebscribe an event
var t = this;
$.jio('subscribe',{'event':'job_done','func':function (o) {
setTimeout (function () {
if (methods.isReady()) {
t.done(o.job);
returnedJobAnalyse (o.job);
t.copyJobQueueToLocalStorage();
}
},50);
}});
$.jio('subscribe',{'event':'job_fail','func':function (o) {
setTimeout (function () {
if (methods.isReady()) {
t.fail(o.job);
returnedJobAnalyse (o.job);
t.copyJobQueueToLocalStorage();
}
},50);
}});
//// end subscribing
}; };
JobQueue.prototype = { JobQueue.prototype = {
init: function ( options ) {
// initialize the JobQueue
// options.publisher : is the publisher to use to send events
// options.jioID : the jio ID
if (options.publisher)
this.publisher = publisher;
this.jioID = options.jioID;
this.jobObjectName = 'jio/jobObject/'+options.jioID;
this.jobObject = {};
this.copyJobQueueToLocalStorage();
},
close: function () {
// close the job queue.
// it also deletes from local storage only if the job list is
// empty.
if (JSON.stringify(this.jobObject) === '{}') {
jioGlobalObj.localStorage.deleteItem(this.jobObjectName);
}
},
isThereJobsWhere: function( func ) { isThereJobsWhere: function( func ) {
// Check if there is jobs, in the queue, // Check if there is jobs, in the queue,
// where [func](job) == true. // where [func](job) == true.
...@@ -278,28 +256,19 @@ ...@@ -278,28 +256,19 @@
copyJobQueueToLocalStorage: function () { copyJobQueueToLocalStorage: function () {
// Copy job queue into localStorage. // Copy job queue into localStorage.
return jioAttributeObject.localStorage.setItem( return jioGlobalObj.localStorage.setItem(
'jio/jobObject/' + jioAttributeObject.tabid, this.jobObjectName,this.jobObject);
this.jobObject);
}, },
addJob: function ( options ) { addJob: function ( job ) {
// Add a job to the queue // Add a job to the queue
// options.storage : the storage object // job : the job object
// options.job : the job object (may be a 'string')
console.log ('addJob'); console.log ('addJob');
// transforming job/storage to an object
if (typeof options.job === 'string')
options.job = JSON.parse(options.job);
if (typeof options.storage === 'string')
options.storage=JSON.parse(options.storage);
// set job id // set job id
options.job.id = this.jobid; job.id = this.jobid;
this.jobid ++; this.jobid ++;
// save the new job into the queue // save the new job into the queue
this.jobObject[this.jobid] = options.job; this.jobObject[job.id] = job;
// save into localStorage // save into localStorage
this.copyJobQueueToLocalStorage(); this.copyJobQueueToLocalStorage();
}, // end addJob }, // end addJob
...@@ -367,45 +336,65 @@ ...@@ -367,45 +336,65 @@
invoke: function (job) { invoke: function (job) {
// Do a job invoking the good method in the good storage. // Do a job invoking the good method in the good storage.
console.log ('invoke'); console.log ('invoke ' + JSON.stringify(job));
//// analysing job method //// analysing job method
// if the method does not exist, do nothing // if the method does not exist, do nothing
if (!jioAttributeObject.jobMethodObject[job.method]) if (!jioConstObj.jobMethodObject[job.method])
return false; // suppose never happen return false; // suppose never happen
// test if a similar job is on going, in order to publish a start // test if a similar job is on going, in order to publish a start
// event if it is the first of his kind (method). // event if it is the first of his kind (method).
if (!this.isThereJobsWhere(function (testjob){ if (!this.isThereJobsWhere(function (testjob){
return (testjob.method === job.method && return (testjob.method === job.method &&
testjob.method === 'ongoing'); testjob.method === 'initial');
})) { })) {
job.status = 'ongoing'; job.status = 'ongoing';
$.jio('publish', this.publisher.publish(jioConstObj.jobMethodObject[
{'event': job.method].start_event);
jioAttributeObject.jobMethodObject[
job.method].start_event,
'job':job});
} else { } else {
job.status = 'ongoing'; job.status = 'ongoing';
} }
// Create a storage object and use it to save,load,...! // Create a storage object and use it to save,load,...!
var t = this;
createStorageObject( createStorageObject(
{'storage':job.storage, {'storage':job.storage,
'applicant':jioAttributeObject.applicant})[job.method](job); 'applicant':jioGlobalObj.applicant})[job.method](
job,function (endedjob){
t.ended(endedjob);
});
//// end method analyse //// end method analyse
}, },
done: function (job) { ended: function (job) {
console.log ('ended');
switch (job.status) {
case 'done':
// This job is supposed done, we can remove it from queue. // This job is supposed done, we can remove it from queue.
this.removeJob ({'job':job}); this.removeJob ({'job':job});
}, break;
case 'fail':
fail: function (job) { // This job cannot be done.
// This job cannot be done, change its status.
this.jobObject[job.id] = job;
// save to local storage // save to local storage
this.copyJobQueueToLocalStorage (); this.copyJobQueueToLocalStorage ();
break;
default:
break;
}
//// ended job analyse
// if the job method does not exists, return false
if (!jioConstObj.jobMethodObject[job.method])
return false;
// if there isn't some job to do, then send stop event
if (!this.isThereJobsWhere(function(testjob){
return (testjob.method === job.method &&
testjob.status !== 'fail');
})) {
this.publisher.publish(
jioConstObj.jobMethodObject[
job.method].stop_event);
return;
}
//// end returnedJobAnalyse
}, },
clean: function () { clean: function () {
// Clean the job list, removing all jobs that have failed. // Clean the job list, removing all jobs that have failed.
...@@ -422,12 +411,12 @@ ...@@ -422,12 +411,12 @@
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
// jio job listener // jio job listener
var JobListener = function ( options ) { var JobListener = function ( queue ) {
// A little daemon which will start jobs from the joblist // A little daemon which will start jobs from the joblist
var settings = $.extend({'interval': 100},options); this.interval = 200;
this.interval = settings.interval;
this.id = null; this.id = null;
this.queue = queue;
}; };
JobListener.prototype = { JobListener.prototype = {
...@@ -441,12 +430,11 @@ ...@@ -441,12 +430,11 @@
// queue // queue
if (!this.id) { if (!this.id) {
var queue = this.queue;
this.id = setInterval (function () { this.id = setInterval (function () {
// if there are jobs // if there is jobs
if (jioAttributeObject.localStorage.getItem( if (JSON.stringify(queue.jobObject) !== '{}') {
'jio/jobObject/'+jioAttributeObject.tabid) && queue.invokeAll();
localStorage.joblist !== '{}') {
jioAttributeObject.queue.invokeAll();
} }
},this.interval); },this.interval);
console.log ('listener started'); console.log ('listener started');
...@@ -460,146 +448,153 @@ ...@@ -460,146 +448,153 @@
console.log ('listener stopped'); console.log ('listener stopped');
clearInterval (this.id); clearInterval (this.id);
this.id = null; this.id = null;
return true;
} }
return false;
} }
} }
// end jio job listener // end jio job listener
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
// jio methods // Toucher
var methods = { var Toucher = function () {
init: function ( options ) { // The toucher is a little thread that show activity of this jio.
// Initialize jio. Create/Update all jio attributes and start this.interval = 400;
// listening to jobs. If jio is already initialized, arguments this.id = null;
// will be given to 'doMethod' which will treat them as a 'job'. };
Toucher.prototype = {
var settings = $.extend({},options); start: function (id) {
// if already initialized // start the toucher
if (methods.isReady()) { console.log ('start touching jio/id/'+id);
methods.doMethod(settings); if (!this.id) {
return false; this.touch(id);
} var t = this;
console.log ('initializing'); this.id = setInterval (function () {
// check settings t.touch(id);
if (!settings.storage || },this.interval);
!settings.applicant) { return true;
$.error ('Storage or applicant are not correctly set.'); } else {
return false; return false;
} }
// objectify settings if there are strings },
try {jioAttributeObject.storage=JSON.parse(settings.storage);} stop: function () {
catch(e){jioAttributeObject.storage=settings.storage;} // stop the toucher
try{jioAttributeObject.applicant=JSON.parse(settings.applicant);} console.log ('stop touching');
catch(e){jioAttributeObject.applicant=settings.applicant;} if (this.id) {
clearInterval (this.id);
// check if key exists in jioAttributeObject.storageTypeObject this.id = null;
if (!settings.storage.type) { return true;
$.error ('Storage incomplete.');
return false;
} }
if(!jioAttributeObject.storageTypeObject[settings.storage.type]) {
$.error ('Unknown storage type "' +
settings.storage.type + '".');
return false; return false;
},
touch: function (id) {
jioGlobalObj.localStorage.setItem ('jio/id/' + id,
Date.now() );
} }
};
// end Toucher
////////////////////////////////////////////////////////////////////////////
// TODO set a tab id for THIS jio ? ////////////////////////////////////////////////////////////////////////////
// set a tab id to every jobs ? // JIO Constructor
// see todo from methods.close var JioCons = function ( storage , applicant ) {
// JIO Constructor, create a new JIO object.
// set tab id // It just initializes values.
// storage : the storage that contains {type:..,[storageinfos]}
var localStor = jioAttributeObject.localStorage.getAll(); // applicant : the applicant that contains {ID:...}
for (var key in localStor) { // these parameters are optional and may be 'string' or 'object'
var splitedkey = key.split('/');
if (splitedkey[0] === 'jio' && splitedkey[1] === 'tab' && // objectify storage and applicant
JSON.parse(splitedkey[2]) > jioAttributeObject.tabid) { if(typeof storage === 'string')
jioAttributeObject.tabid = JSON.parse(splitedkey[2]); storage = JSON.parse(options.storage);
} if(typeof applicant === 'string')
} applicant = JSON.parse(options.applicant);
jioAttributeObject.tabid ++;
// set init values
//jioAttributeObject.pubsub = new PubSub(); this['storage'] = storage;
if (!jioAttributeObject.queue) this['applicant'] = applicant;
jioAttributeObject.queue = new JobQueue(); this['id'] = 0;
if (!jioAttributeObject.listener) this['pubsub'] = new PubSub();
jioAttributeObject.listener = new JobListener(); this['queue'] = new JobQueue(this.pubsub);
jioAttributeObject.listener.start(); this['listener'] = new JobListener(this.queue);
jioAttributeObject.isReady = true; this['toucher'] = new Toucher();
return true; this['ready'] = false;
// check storage type
if (this.storage)
if (!jioGlobalObj.storageTypeObject[this.storage.type])
$.error('Unknown storage type "' + this.storage.type +'"');
};
// JIO Prototype
JioCons.prototype = {
start: function () {
// Start JIO: start listening to jobs and make it ready
// set a new jio id
this.id = getNewQueueID();
console.log (this.id);
// initializing objects
this.queue.init({'jioID':this.id});
// start touching
this.toucher.start(this.id);
// start listening
this.listener.start();
// is now ready
this.ready = true;
return this.isReady();
}, },
isReady: function () { stop: function () {
// Check if jio is ready to use. // Finish some job if possible and stop listening.
// It can be restarted later
return jioAttributeObject.isReady; this.queue.close();
this.listener.stop();
this.toucher.stop();
this.ready = false;
return true;
}, },
addStorageType: function ( options ) { kill: function () {
// Add a storage type to jio. Jio must have keys/types which are // kill this JIO, job listening and job operation (event if they
// bound to a storage creation function. ex: 'local', will // are on going!)
// create a LocalStorage (in jio.storage.js).
// It can replace a older type with a newer creation function.
// options.type : the type of the storage.
// options.creator : the function to create a storage object.
var settings = $.extend({},options); this.queue.close();
if (settings.type && settings.creator) { this.listener.stop();
jioAttributeObject.storageTypeObject[ this.toucher.stop();
settings.type] = settings.creator; // TODO
this.ready = false;
return true; return true;
}
return false;
}, },
getApplicant: function () { isReady: function () {
// return applicant set at init of jio // Check if Jio is ready to use.
return this.ready;
return jioAttributeObject.applicant;
}, },
publish: function ( options ) { publish: function (eventname, obj) {
// publish a jio event // publish an event on this jio
// options.event : contains the event name. // eventname : the event name
// options[*] : are the arguments sent with this event. // obj : is an object containing some parameters for example
if (!methods.isReady()) return null; if (!this.isReady()) return ;
console.log ('publish ' + options.event); console.log ('publish ' + eventname);
var tmp = $.extend({},options); return this.pubsub.publish(eventname,obj);
tmp.event = undefined;
jioAttributeObject.pubsub.publish(options.event,tmp);
}, },
subscribe: function ( options ) { subscribe: function (eventname, callback) {
// subscribe to a jio event. We can subscribe to jio event even // subscribe to an event on this jio. We can subscribe to jio event
// if jio is not initialized. // even if jio is not started. Returns the callback function in
// options.event : contains the event name. // order to unsubscribe it.
// options.func : will call this function after receiving event. // eventname : the event name.
// callback : called after receiving event.
console.log ('subscribe'); console.log ('subscribe ' +eventname);
jioAttributeObject.pubsub.subscribe(options.event,options.func); return this.pubsub.subscribe(eventname,callback);
}, },
unsubscribe: function ( options ) { unsubscribe: function (eventname,callback) {
// unsubscribe to a jio event. // unsubscribe callback from an event
// options.event : contains the event name.
// TODO I wonder if it works.. ?
console.log ('unsubscribe'); console.log ('unsubscribe ' +eventname);
jioAttributeObject.pubsub.unsubscribe(options.event); return this.pubsub.unsubscribe(eventname,callback);
}, },
doMethod: function ( options ) {
// Do a method in jio. The method is set in [options.method],
// it can be everything but itself.
// $.jio({'fileName':'a','fileContent':'b','method':'save'}
if (options.method) {
if (options.method === 'doMethod') {
$.error ('Cannot do method "doMethod" recursively.');
return null;
}
if (methods[options.method]) {
return methods[options.method]( options );
}
$.error ('Method ' + options.method + ' not found.')
}
return null;
},
checkNameAvailability: function ( options ) { checkNameAvailability: function ( options ) {
// Check the user availability in the storage set in [options] // Check the user availability in the storage set in [options]
// or in the storage set at init. At the end of the job, // or in the storage set at init. At the end of the job,
...@@ -607,47 +602,57 @@ ...@@ -607,47 +602,57 @@
// return value. // return value.
// options.storage : the storage where to remove (optional) // options.storage : the storage where to remove (optional)
// options.applicant : the applicant (optional) // options.applicant : the applicant (optional)
// options.callback(result) : called to get the result.
// example :
// jio.checkNameAvailability({'userName':'myName','callback':
// function (result) { alert('is available? ' +
// result.isAvailable); }});
// $.jio('checkNameAvailability',{'userName':'toto'}); if (!this.isReady()) return null;
console.log ('isAvailable');
if (!methods.isReady()) return null;
var settings = $.extend ({ var settings = $.extend ({
'userName': jioAttributeObject.storage.userName, 'userName': this.storage.userName,
'storage': jioAttributeObject.storage, 'storage': this.storage,
'applicant': jioAttributeObject.applicant, 'applicant': this.applicant,
'method': 'checkNameAvailability' 'method': 'checkNameAvailability',
'callback': function () {}
},options); },options);
// check dependencies // check dependencies
if (settings.userName) { if (settings.userName && settings.storage && settings.applicant) {
return jioAttributeObject.queue.addJob ( return this.queue.addJob ( new Job ( settings ) );
{'job':(new Job ( settings ))} ) ;
} }
return null; return null;
}, },
saveDocument: function ( options ) { saveDocument: function ( options ) {
// Load a document in the storage set in [options] // Load a document in the storage set in [options]
// or in the storage set at init. At the end of the job, // or in the storage set at init. At the end of the job,
// 'job_done' will be sent with this job. // 'job_done' will be sent with this job.
// options.storage : the storage where to remove (optional) // options.storage : the storage where to remove (optional)
// options.applicant : the applicant (optional) // options.applicant : the applicant (optional)
// options.callback(result) : called to get the result.
// jio.saveDocument({'fileName':'file','fileContent':'content',
// 'callback': function (result) { alert('saved?' +
// result.isSaved); }});
// $.jio('saveDocument',{'fileName':'a','fileContent':'b','options':{
// 'overwrite':false}}
console.log ('saveDocument'); console.log ('saveDocument');
if (!methods.isReady()) return null; if (!this.isReady()) return null;
var settings = $.extend({ var settings = $.extend({
'storage': jioAttributeObject.storage, 'storage': this.storage,
'applicant': jioAttributeObject.applicant,
'lastModified': Date.now(), 'lastModified': Date.now(),
'method':'saveDocument' 'method':'saveDocument',
'applicant': this.applicant,
'callback': function () {}
},options); },options);
// check dependencies // check dependencies
if (settings.fileName && settings.fileContent) { if (settings.fileName && settings.fileContent &&
return jioAttributeObject.queue.addJob ( settings.storage && settings.applicant) {
{'job':(new Job ( settings ))} ) ; return this.queue.addJob ( new Job ( settings ) );
} }
return null; return null;
}, },
loadDocument: function ( options ) { loadDocument: function ( options ) {
// Load a document in the storage set in [options] // Load a document in the storage set in [options]
// or in the storage set at init. At the end of the job, // or in the storage set at init. At the end of the job,
...@@ -655,98 +660,119 @@ ...@@ -655,98 +660,119 @@
// return value. // return value.
// options.storage : the storage where to remove (optional) // options.storage : the storage where to remove (optional)
// options.applicant : the applicant (optional) // options.applicant : the applicant (optional)
// options.callback(result) : called to get the result.
// jio.loadDocument({'fileName':'file','callback':
// function (result) { alert('content: '+
// result.fileContent); }});
// $.jio('loadDocument',{'fileName':'a'});
console.log ('load'); console.log ('load');
if (!methods.isReady()) return null; if (!this.isReady()) return null;
var settings = $.extend ({ var settings = $.extend ({
'storage':jioAttributeObject.storage, 'storage': this.storage,
'applicant':jioAttributeObject.applicant, 'applicant': this.applicant,
'method':'loadDocument' 'method':'loadDocument',
'callback': function(){}
},options); },options);
// check dependencies // check dependencies
if ( settings.fileName ) { if ( settings.fileName && settings.storage && settings.applicant) {
return jioAttributeObject.queue.addJob ( return jioGlobalObj.queue.addJob ( new Job ( settings ) );
{'job':(new Job ( settings ))} ) ;
} }
return null; return null;
}, },
getDocument: function ( options ) { getDocument: function ( options ) {
// TODO // TODO (don't forgot to add this method to constants)
}, },
getDocumentList: function ( options ) { getDocumentList: function ( options ) {
// Get a document list of the user in the storage set in [options] // Get a document list of the user in the storage set in [options]
// or in the storage set at init. At the end of the job, // or in the storage set at init.
// 'job_done' will be sent with this job and its 'list'
// return value.
// options.storage : the storage where to remove (optional) // options.storage : the storage where to remove (optional)
// options.applicant : the applicant (optional) // options.applicant : the applicant (optional)
// options.callback(result) : called to get the result.
// jio.getDocumentList({'callback':
// function (result) { alert('list: '+result.list); }});
// $.jio('getDocumentList');
console.log ('getList'); console.log ('getList');
if (!methods.isReady()) return null; if (!this.isReady()) return null;
var settings = $.extend ({ var settings = $.extend ({
'storage': jioAttributeObject.storage, 'storage': this.storage,
'applicant': jioAttributeObject.applicant, 'applicant': this.applicant,
'method':'getDocumentList' 'method':'getDocumentList',
'callback':function(){}
},options); },options);
return jioAttributeObject.queue.addJob ( // check dependencies
{'job':(new Job ( settings ))} ); if ( settings.storage && settings.applicant ) {
return this.queue.addJob ( new Job ( settings ) );
}
return null;
}, },
removeDocument: function ( options ) { removeDocument: function ( options ) {
// Remove a document in the storage set in [options] // Remove a document in the storage set in [options]
// or in the storage set at init. At the end of the job, // or in the storage set at init.
// 'job_done' will be sent with this job.
// options.storage : the storage where to remove (optional) // options.storage : the storage where to remove (optional)
// options.applicant : the applicant (optional) // options.applicant : the applicant (optional)
// options.callback(result) : called to get the result.
// jio.removeDocument({'fileName':'file','callback':
// function (result) { alert('removed? '+result.isRemoved); }});
// $.jio('removeDocument',{'fileName':'a'});
console.log ('removeDocument'); console.log ('removeDocument');
if (!methods.isReady()) return null; if (!this.isReady()) return null;
var settings = $.extend ({ var settings = $.extend ({
'storage': jioAttributeObject.storage, 'storage': this.storage,
'applicant': jioAttributeObject.applicant, 'applicant': this.applicant,
'method':'removeDocument' 'method':'removeDocument',
'callback':function (){}
},options); },options);
if ( settings.fileName ) { if ( settings.fileName && settings.storage && settings.applicant ) {
return jioAttributeObject.queue.addJob ( return this.queue.addJob ( new Job( settings ) );
{'job':(new Job( settings ))} );
} }
return null; return null;
}, }
start: function ( options ) { };
// TODO // end JIO Prototype
}, ////////////////////////////////////////////////////////////////////////////
close: function ( options ) {
// Finish some job if possible and close jio.
// It can be re-init later.
// TODO if someone is managing the browser closure or go to previous ////////////////////////////////////////////////////////////////////////////
// page, $.jio('close') will close tab id (if any) to free its jobs, // Jio creator
// so that other tabs may do them. var Jio = function () {
// Jio creator object
// this object permit to create jio object
};
Jio.prototype = {
createNew: function ( storage, applicant) {
// return a new instance of JIO
jioAttributeObject.listener.stop(); return new JioCons(storage,applicant);
jioAttributeObject.isReady = false;
return true;
}, },
getJioAttributes: function ( options ) { addStorageType: function ( type, constructor ) {
return $.extend({},jioAttributeObject); // Add a storage type to jio. Jio must have keys/types which are
// bound to a storage creation function. ex: 'local', will
// create a LocalStorage (in jio.storage.js).
// It can replace a older type with a newer creation function.
// type : the type of the storage.
// constructor : the function which returns a new storage object.
if (type && constructor) {
jioGlobalObj.storageTypeObject[type] = constructor;
return true;
} }
}; return false;
// end JIO methods },
//////////////////////////////////////////////////////////////////////////// getGlobalObject: function () {
// JIO arguments manager // Returns the global jio values
$.jio = function ( method ) { return jioGlobalObj;
if ( methods[method] ) { },
return methods[method].apply( this, Array.prototype.slice.call ( getConstObject: function () {
arguments, 1)); // Returns a copy of the constants
} else if ( typeof method === 'object' || ! method ) { return $.extend({},jioConstObj);
return methods.init.apply( this, arguments );
} else {
$.error ('Method ' + method + ' does not exists on JQuery.jio' );
} }
}; };
// end JIO arguments manager return new Jio();
// end Jio Creator
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
})();
})( jQuery );
;(function ( $ ) { ;(function ( Jio ) {
// TODO do we realy need to check dependencies ? // check dependencies
// test dependencies var errorDependencies=function(){$.error('Cannot find Jio or Base64');};
try { try{if (!Jio || !Base64){
if ($.jio && Base64) {} errorDependencies();return;
else {return false;} }} catch (e){
} catch (e) { errorDependencies();return;}
$.error('jio.js and base64.js '+
' are required by jio.storage.js');
return false;
};
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
// private vars // globals
var jioAttributeObject = $.jio('getJioAttributes'); var jioGlobalObj = Jio.getGlobalObject();
// end private vars // end globals
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
...@@ -33,7 +29,7 @@ ...@@ -33,7 +29,7 @@
this.userName = options.storage.userName; this.userName = options.storage.userName;
}; };
LocalStorage.prototype = { LocalStorage.prototype = {
checkNameAvailability: function ( job ) { checkNameAvailability: function ( job , jobendcallback) {
// checks the availability of the [job.userName]. // checks the availability of the [job.userName].
// if the name already exists, it is not available. // if the name already exists, it is not available.
// job: the job object // job: the job object
...@@ -42,31 +38,35 @@ ...@@ -42,31 +38,35 @@
// wait a little in order to simulate asynchronous operation // wait a little in order to simulate asynchronous operation
setTimeout(function () { setTimeout(function () {
var available = true; var available = true;
var localStor = jioAttributeObject.localStorage.getAll(); var localStor = jioGlobalObj.localStorage.getAll();
for (var k in localStor) { for (var k in localStor) {
var splitk = k.split('/'); var splitk = k.split('/');
if (splitk[0] === 'jio' && splitk[1] === job.userName) { if (splitk[0] === 'jio' &&
splitk[1] === 'local' &&
splitk[2] === job.userName) {
available = false; available = false;
break; break;
} }
} }
if (!available) { if (!available) {
job.status = 'done'; job.status = 'done';
job.message = ''+ job.userName + ' is not available.'; jobendcallback(job);
job.isAvailable = false; job.callback({'status':'done',
$.jio('publish',{'event': 'job_done', 'message':''+job.userName+
'job': job}); ' is not available.',
'isAvailable':false});
} else { } else {
job.status = 'done'; job.status = 'done';
job.message = ''+ job.userName + ' is available.'; jobendcallback(job);
job.isAvailable = true; job.callback({'status':'done',
$.jio('publish',{'event': 'job_done', 'message':''+job.userName+
'job': job}); ' is available.',
'isAvailable':true});
} }
}, 100); }, 100);
}, // end userNameAvailable }, // end userNameAvailable
saveDocument: function ( job ) { saveDocument: function ( job, jobendcallback ) {
// Save a document in the local storage // Save a document in the local storage
// job : the job object // job : the job object
// job.options : the save options object // job.options : the save options object
...@@ -79,8 +79,9 @@ ...@@ -79,8 +79,9 @@
var t = this; var t = this;
// wait a little in order to simulate asynchronous saving // wait a little in order to simulate asynchronous saving
setTimeout (function () { setTimeout (function () {
var res = {};
// reading // reading
var doc = jioAttributeObject.localStorage.getItem( var doc = jioGlobalObj.localStorage.getItem(
'jio/local/'+job.storage.userName+'/'+job.applicant.ID+'/'+ 'jio/local/'+job.storage.userName+'/'+job.applicant.ID+'/'+
job.fileName); job.fileName);
if (!doc) { // create document if (!doc) { // create document
...@@ -91,85 +92,91 @@ ...@@ -91,85 +92,91 @@
'lastModified': Date.now () 'lastModified': Date.now ()
} }
// writing // writing
jioAttributeObject.localStorage.setItem( jioGlobalObj.localStorage.setItem(
'jio/local/'+job.storage.userName+'/'+job.applicant.ID+'/'+ 'jio/local/'+job.storage.userName+'/'+job.applicant.ID+'/'+
job.fileName, doc); job.fileName, doc);
job.status = 'done'; // return
job.message = 'Document saved.'; res.status = job.status = 'done';
job.isSaved = true; res.message = 'Document saved.';
$.jio('publish',{'event':'job_done', res.isSaved = true;
'job':job}); jobendcallback(job);
return true; job.callback(res);
return;
} }
if ( settings.overwrite || settings.force ) { // overwrite if ( settings.overwrite || settings.force ) {
if ( ! settings.force ) { // force write // if it doesn't force writing
// checking modification date // checking modification date
if ( doc.lastModified >= job.lastModified ) { if ( ! settings.force &&
doc.lastModified >= job.lastModified ) {
// date problem! // date problem!
job.status = 'fail'; // return
job.message = 'Modification date is earlier than ' + res.status = job.status = 'fail';
res.message = 'Modification date is earlier than ' +
'existing modification date.'; 'existing modification date.';
job.isSaved = false; res.isSaved = false;
$.jio('publish',{'event':'job_fail', jobendcallback(job);
'job':job}); job.callback(res);
return false; return;
}
} }
// overwriting
doc.lastModified = Date.now(); doc.lastModified = Date.now();
doc.fileContent = job.fileContent; doc.fileContent = job.fileContent;
// writing // writing
jioAttributeObject.localStorage.setItem( jioGlobalObj.localStorage.setItem(
'jio/local/'+job.storage.userName+'/'+job.applicant.ID+'/'+ 'jio/local/'+job.storage.userName+'/'+job.applicant.ID+'/'+
job.fileName, doc); job.fileName, doc);
job.status = 'done'; // return
job.message = 'Document saved'; res.status = job.status = 'done';
job.isSaved = true; res.message = 'Document saved';
$.jio('publish',{'event':'job_done', res.isSaved = true;
'job':job}); jobendcallback(job);
return true; job.callback(res);
return;
} }
// already exists // already exists
job.status = 'fail'; res.status = job.status = 'fail';
job.message = 'Document already exists.'; res.message = 'Document already exists.';
job.errno = 403; res.errno = 403;
job.isSaved = false; res.isSaved = false;
$.jio('publish',{'event':'job_fail', jobendcallback(job);
'job': job}); job.callback(res);
return false; return;
}, 100); }, 100);
}, // end saveDocument }, // end saveDocument
loadDocument: function ( job ) { loadDocument: function ( job, jobendcallback ) {
// load a document in the storage, copy the content into the job // load a document in the storage, copy the content into the job
// job : the job // job : the job
var t = this; var t = this;
// wait a little in order to simulate asynchronous operation // wait a little in order to simulate asynchronous operation
setTimeout(function () { setTimeout(function () {
var doc = jioAttributeObject.localStorage.getItem( var res = {};
var doc = jioGlobalObj.localStorage.getItem(
'jio/local/'+job.storage.userName+'/'+job.applicant.ID+'/'+ 'jio/local/'+job.storage.userName+'/'+job.applicant.ID+'/'+
job.fileName); job.fileName);
if (!doc) { if (!doc) {
job.status = 'fail'; res.status = job.status = 'fail';
job.errno = 404; res.errno = 404;
job.message = 'Document not found.'; res.message = 'Document not found.';
$.jio('publish',{'event':'job_fail', jobendcallback(job);
'job':job}); job.callback(res);
} else { } else {
job.status = 'done'; res.status = job.status = 'done';
job.message = 'Document loaded.'; res.message = 'Document loaded.';
job.fileContent = doc.fileContent; res.fileContent = doc.fileContent;
$.jio('publish',{'event':'job_done', jobendcallback(job);
'job':job}); job.callback(res);
} }
}, 100); }, 100);
}, // end loadDocument }, // end loadDocument
getDocumentList: function (job) { getDocumentList: function ( job, jobendcallback) {
var t = this; var t = this;
setTimeout(function () { setTimeout(function () {
var localStor = jioAttributeObject.localStorage.getAll(); var res = {};
job.list = []; var localStor = jioGlobalObj.localStorage.getAll();
res.list = [];
for (var k in localStor) { for (var k in localStor) {
var splitk = k.split('/'); var splitk = k.split('/');
if (splitk[0] === 'jio' && if (splitk[0] === 'jio' &&
...@@ -177,57 +184,54 @@ ...@@ -177,57 +184,54 @@
splitk[2] === job.storage.userName && splitk[2] === job.storage.userName &&
splitk[3] === job.applicant.ID) { splitk[3] === job.applicant.ID) {
fileObject = JSON.parse(localStor[k]); fileObject = JSON.parse(localStor[k]);
job.list.push ({ res.list.push ({
'fileName':fileObject.fileName, 'fileName':fileObject.fileName,
'creationDate':fileObject.creationDate, 'creationDate':fileObject.creationDate,
'lastModified':fileObject.lastModified}); 'lastModified':fileObject.lastModified});
} }
} }
console.log (JSON.stringify (job.list)); res.status = job.status = 'done';
job.status = 'done'; res.message = 'List received.';
job.message = 'List received.'; jobendcallback(job);
$.jio('publish',{'event':'job_done', job.callback(res);
'job':job});
}, 100); }, 100);
}, // end getDocumentList }, // end getDocumentList
removeDocument: function ( job ) { removeDocument: function ( job, jobendcallback ) {
var t = this; var t = this;
setTimeout (function () { setTimeout (function () {
var doc = jioAttributeObject.localStorage.getItem( var res = {};
var doc = jioGlobalObj.localStorage.getItem(
'jio/local/'+job.storage.userName+'/'+job.applicant.ID+'/'+ 'jio/local/'+job.storage.userName+'/'+job.applicant.ID+'/'+
job.fileName); job.fileName);
// already deleted
if (!doc) { if (!doc) {
// job.status = 'fail'; res.status = job.status = 'done';
// job.errno = 404; res.message = 'Document already removed.';
// job.message = 'Document not found.'; res.isRemoved = true;
// job.isRemoved = false; jobendcallback(job);
// $.jio('publish',{'event':'job_fail', job.callback(res);
// 'job':job}); return;
job.status = 'done'; }
job.message = 'Document already removed.'; // deleting
job.isRemoved = true; jioGlobalObj.localStorage.deleteItem(
$.jio('publish',{'event':'job_done',
'job':job});
} else {
jioAttributeObject.localStorage.deleteItem(
'jio/local/'+ 'jio/local/'+
job.storage.userName+'/'+job.applicant.ID+'/'+ job.storage.userName+'/'+job.applicant.ID+'/'+
job.fileName); job.fileName);
job.status = 'done'; res.status = job.status = 'done';
job.message = 'Document removed.'; res.message = 'Document removed.';
job.isRemoved = true; res.isRemoved = true;
$.jio('publish',{'event':'job_done', jobendcallback(job);
'job':job}); job.callback(res);
} return;
}, 100); }, 100);
} }
}; };
// add key to storageObject // add key to storageObject
$.jio('addStorageType',{'type':'local','creator':function (options) { Jio.addStorageType('local', function (options) {
return new LocalStorage(options); return new LocalStorage(options);
}}); });
// end Local Storage // end Local Storage
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
...@@ -527,11 +531,11 @@ ...@@ -527,11 +531,11 @@
}; };
// add key to storageObject // add key to storageObject
$.jio('addStorageType',{'type':'dav','creator':function (options) { Jio.addStorageType('dav', function (options) {
return new DAVStorage(options); return new DAVStorage(options);
}}); });
// end DAVStorage // end DAVStorage
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
})( jQuery ); })( 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