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

QUnit&Sinon tests are improved!

Developping DavStorage.
parent 6cb31064
...@@ -9,6 +9,7 @@ ...@@ -9,6 +9,7 @@
<div id="qunit"></div> <div id="qunit"></div>
<script type="text/javascript" src="qunit/qunit-1.5.0.js"></script> <script type="text/javascript" src="qunit/qunit-1.5.0.js"></script>
<script type="text/javascript" src="js/jquery/jquery.js"></script> <script type="text/javascript" src="js/jquery/jquery.js"></script>
<script type="text/javascript" src="unhosted/localorcookiestorage.js"></script>
<script type="text/javascript" src="unhosted/jio.js"></script> <script type="text/javascript" src="unhosted/jio.js"></script>
<script type="text/javascript" src="unhosted/base64.js"></script> <script type="text/javascript" src="unhosted/base64.js"></script>
<script type="text/javascript" src="unhosted/jio.storage.js"></script> <script type="text/javascript" src="unhosted/jio.storage.js"></script>
......
var cookieOrLocal = null;
var browserStorage = function () {
};
browserStorage.prototype = {
getItem: function (name) {
return JSON.parse(localStorage.getItem(name));
},
setItem: function (name,value) {
if (name)
return localStorage.setItem(name,JSON.stringify(value));
},
getAll: function() {
return localStorage;
},
deleteItem: function (name) {
if (name)
delete localStorage[name];
}
};
var cookieStorage = function () {
};
cookieStorage.prototype = {
getItem: function (name) {
var cookies = document.cookie.split(';');
for (var i in cookies) {
var x = cookies[i].substr(0, cookies[i].indexOf('='));
var y = cookies[i].substr(cookies[i].indexOf('=')+1);
x = x.replace(/^\s+|\s+$/g,"");
if( x == name ) return unescape(y);
}
return null;
},
setItem: function (name,value) {
// function to store into cookies
if (value != undefined) {
document.cookie = name+'='+JSON.stringify(value)+';domain='+
window.location.hostname+
';path='+window.location.pathname;
return true;
}
return false;
},
getAll: function() {
var retObject = {};
var cookies = document.cookie.split(':');
for (var i in cookies) {
var x = cookies[i].substr(0, cookies[i].indexOf('='));
var y = cookies[i].substr(cookies[i].indexOf('=')+1);
x = x.replace(/^\s+|\s+$/g,"");
retObject[x] = unescape(y);
}
return retObject;
},
deleteItem: function (name) {
document.cookie = name+'=null;domain='+window.location.hostname+
';path='+window.location.pathname+
';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}
};
// set good localStorage
try {
if (localStorage.getItem) {
cookieOrLocal = new browserStorage();
} else {
cookieOrLocal = new cookieStorage();
}
}
catch (e) {
cookieOrLocal = new cookieStorage();
}
//// clear jio localstorage //// clear jio localstorage
for (var k in cookieOrLocal.getAll()) { for (var k in LocalOrCookieStorage.getAll()) {
var splitk = k.split('/'); var splitk = k.split('/');
if ( splitk[0] === 'jio' ) if ( splitk[0] === 'jio' )
cookieOrLocal.deleteItem(k); LocalOrCookieStorage.deleteItem(k);
} }
//// end clear jio localstorage //// end clear jio localstorage
//// QUnit Tests //// //// QUnit Tests ////
module ('Jio Global tests'); module ('Jio Global tests');
...@@ -151,11 +78,12 @@ test ('Check name availability', function () { ...@@ -151,11 +78,12 @@ test ('Check name availability', function () {
var mytest = function (value){ var mytest = function (value){
o.f = function (result) { o.f = function (result) {
deepEqual(result.isAvailable,value,'checking name availabality');}; deepEqual(result.isAvailable,value,'checking name availabality');};
var spy = t.spy(o,'f'); t.spy(o,'f');
o.jio.checkNameAvailability( o.jio.checkNameAvailability(
{'userName':'MrCheckName','callback': o.f}); {'userName':'MrCheckName','callback': o.f});
clock.tick(510); clock.tick(510);
ok (o.f.calledOnce, 'callback called once'); if (!o.f.calledOnce)
ok(false, 'no response / too much results');
}; };
// new jio // new jio
...@@ -163,11 +91,11 @@ test ('Check name availability', function () { ...@@ -163,11 +91,11 @@ test ('Check name availability', function () {
{"ID":'noid'}); {"ID":'noid'});
// name must be available // name must be available
cookieOrLocal.deleteItem ('jio/local/MrCheckName/jiotests/file'); LocalOrCookieStorage.deleteItem ('jio/local/MrCheckName/jiotests/file');
mytest(true); mytest(true);
// name must be unavailable // name must be unavailable
cookieOrLocal.setItem ('jio/local/MrCheckName/jiotests/file',{}); LocalOrCookieStorage.setItem ('jio/local/MrCheckName/jiotests/file',{});
mytest(false); mytest(false);
o.jio.stop(); o.jio.stop();
...@@ -182,20 +110,23 @@ test ('Document save', function () { ...@@ -182,20 +110,23 @@ test ('Document save', function () {
var mytest = function (value,lm,cd){ var mytest = function (value,lm,cd){
o.f = function (result) { o.f = function (result) {
deepEqual(result.isSaved,value,'saving document');}; deepEqual(result.isSaved,value,'saving document');};
var spy = t.spy(o,'f'); t.spy(o,'f');
o.jio.saveDocument( o.jio.saveDocument(
{'fileName':'file','fileContent':'content','callback': o.f}); {'fileName':'file','fileContent':'content','callback': o.f});
clock.tick(510); clock.tick(510);
ok (o.f.calledOnce, 'callback called once'); if (!o.f.calledOnce)
// check content ok(false, 'no response / too much results');
var tmp = cookieOrLocal.getItem ('jio/local/MrSaveName/jiotests/file'); else {
deepEqual (tmp,{'fileName':'file','fileContent':'content', // check content
'lastModified':lm,'creationDate':cd},'check content'); var tmp = LocalOrCookieStorage.getItem ('jio/local/MrSaveName/jiotests/file');
deepEqual (tmp,{'fileName':'file','fileContent':'content',
'lastModified':lm,'creationDate':cd},'check content');
}
}; };
o.jio = JIO.createNew({'type':'local','userName':'MrSaveName'}, o.jio = JIO.createNew({'type':'local','userName':'MrSaveName'},
{"ID":'jiotests'}); {"ID":'jiotests'});
cookieOrLocal.deleteItem ('jio/local/MrSaveName/jiotests/file'); LocalOrCookieStorage.deleteItem ('jio/local/MrSaveName/jiotests/file');
// save and check document existence // save and check document existence
clock.tick(200); clock.tick(200);
mytest(true,200,200); // value, lastmodified, creationdate mytest(true,200,200); // value, lastmodified, creationdate
...@@ -215,22 +146,23 @@ test ('Document load', function () { ...@@ -215,22 +146,23 @@ test ('Document load', function () {
var mytest = function (res,value){ var mytest = function (res,value){
o.f = function (result) { o.f = function (result) {
deepEqual(result[res],value,'loading document');}; deepEqual(result[res],value,'loading document');};
var spy = t.spy(o,'f'); t.spy(o,'f');
o.jio.loadDocument( o.jio.loadDocument(
{'fileName':'file','callback': o.f}); {'fileName':'file','callback': o.f});
clock.tick(510); clock.tick(510);
ok (o.f.calledOnce, 'callback called once'); if (!o.f.calledOnce)
ok(false, 'no response / too much results');
}; };
o.jio = JIO.createNew({'type':'local','userName':'MrLoadName'}, o.jio = JIO.createNew({'type':'local','userName':'MrLoadName'},
{"ID":'jiotests'}); {"ID":'jiotests'});
// load a non existing file // load a non existing file
cookieOrLocal.deleteItem ('jio/local/MrLoadName/jiotests/file'); LocalOrCookieStorage.deleteItem ('jio/local/MrLoadName/jiotests/file');
mytest ('status','fail'); mytest ('status','fail');
// re-load file after saving it manually // re-load file after saving it manually
var doc = {'fileName':'file','fileContent':'content', var doc = {'fileName':'file','fileContent':'content',
'lastModified':1234,'creationDate':1000}; 'lastModified':1234,'creationDate':1000};
cookieOrLocal.setItem ('jio/local/MrLoadName/jiotests/file',doc); LocalOrCookieStorage.setItem ('jio/local/MrLoadName/jiotests/file',doc);
mytest ('document',doc); mytest ('document',doc);
o.jio.stop(); o.jio.stop();
...@@ -245,21 +177,123 @@ test ('Document remove', function () { ...@@ -245,21 +177,123 @@ test ('Document remove', function () {
var mytest = function (){ var mytest = function (){
o.f = function (result) { o.f = function (result) {
deepEqual(result.isRemoved,true,'removing document');}; deepEqual(result.isRemoved,true,'removing document');};
var spy = t.spy(o,'f'); t.spy(o,'f');
o.jio.removeDocument( o.jio.removeDocument(
{'fileName':'file','callback': o.f}); {'fileName':'file','callback': o.f});
clock.tick(510); clock.tick(510);
ok (o.f.calledOnce, 'callback called once'); if (!o.f.calledOnce)
// check if the file is still there ok(false, 'no response / too much results');
var tmp = cookieOrLocal.getItem ('jio/local/MrRemoveName/jiotests/file'); else {
ok (!tmp, 'check no content'); // check if the file is still there
var tmp = LocalOrCookieStorage.getItem ('jio/local/MrRemoveName/jiotests/file');
ok (!tmp, 'check no content');
}
}; };
o.jio = JIO.createNew({'type':'local','userName':'MrRemoveName'}, o.jio = JIO.createNew({'type':'local','userName':'MrRemoveName'},
{"ID":'jiotests'}); {"ID":'jiotests'});
// test removing a file // test removing a file
cookieOrLocal.setItem ('jio/local/MrRemoveName/jiotests/file',{}); LocalOrCookieStorage.setItem ('jio/local/MrRemoveName/jiotests/file',{});
mytest (); mytest ();
o.jio.stop(); o.jio.stop();
}); });
module ('Jio DAVStorage');
test ('Check name availability', function () {
// Test if DavStorage can check the availabality of a name.
var o = {}; var clock = this.sandbox.useFakeTimers(); var t = this;
var mytest = function (value,errno) {
var server = t.sandbox.useFakeServer();
server.respondWith ("PROPFIND",
"https://ca-davstorage:8080/dav/davcheck/",
[errno, {'Content-Type': 'text/xml' },
'']);
o.f = function (result) {
deepEqual (result.isAvailable,value,'checking name availability');};
t.spy(o,'f');
o.jio.checkNameAvailability({'userName':'davcheck','callback':o.f});
clock.tick(500);
server.respond();
if (!o.f.calledOnce)
ok(false, 'no response / too much results');
};
o.jio = JIO.createNew({'type':'dav','userName':'davcheck',
'password':'checkpwd',
'location':'https://ca-davstorage:8080'},
{'ID':'jiotests'});
// 404 error, the name does not exist, name is available.
mytest (true,404);
// 200 error, responding ok, the name already exists, name is not available.
mytest (false,200);
// 405 error, random error, name is not available by default.
mytest (false,405);
o.jio.stop();
});
test ('Document save', function () {
// Test if DavStorage can save documents.
var o = {}; var clock = this.sandbox.useFakeTimers(); var t = this;
var mytest = function (message,value,errnoput,errnoget,
lastmodified,overwrite,force) {
var server = t.sandbox.useFakeServer();
server.respondWith ("PUT",
"https://ca-davstorage:8080/dav/davsave/jiotests/file",
[errnoput, {'Content-Type':'x-www-form-urlencoded'},
'content']);
server.respondWith ("MKCOL",
"https://ca-davstorage:8080/dav/davsave/jiotests/file",
[200, {'Content-Type':'x-www-form-urlencoded'},
'content']);
server.respondWith ("GET",
"https://ca-davstorage:8080/dav/davsave/jiotests/file",
[errnoget, {}, 'content']);
o.f = function (result) {
deepEqual (result.isSaved,value,message);};
t.spy(o,'f');
o.jio.saveDocument({'fileName':'file','fileContent':'content',
'options':{'force':force,'overwrite':overwrite},
'lastModified':lastmodified,
'callback':o.f});
clock.tick(500);
server.respond();
if (!o.f.calledOnce)
ok(false, 'no response / too much results');
};
o.jio = JIO.createNew({'type':'dav','userName':'davsave',
'password':'checkpwd',
'location':'https://ca-davstorage:8080'},
{'ID':'jiotests'});
// note: http errno:
// 200 OK
// 201 Created
// 204 No Content
// 403 Forbidden
// 404 Not Found
// the path does not exist, we want to create it, and save the file.
mytest('create path if not exists, and create document',
true,403,404,999);
// the document does not exist, we want to create it
mytest('create document',
true,201,404,10000);
// the document already exists, we want to overwrite it
mytest('overwrite document',
true,204,200,10100,true);
// the document already exists, we don't want to overwrite it
mytest('do not overwrite document',
false,204,200,10200,false);
// the document is already exists, it is younger than the one we want
// to save.
mytest('younger than the one we want to save',
false,204,200,900,true,false);
// the document is already exists, it is the youngest but we want to
// force overwriting
mytest('youngest but force overwrite',
true,204,200,700,true,true);
o.jio.stop();
});
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
// check dependencies // check dependencies
var errorDependencies=function(){console.error('Cannot find jQuery.');}; var errorDependencies=function(){console.error('Cannot find jQuery.');};
try{if(!jQuery){ try{if(!(jQuery && LocalOrCookieStorage)){
errorDependencies();return null; errorDependencies();return null;
}}catch(e){ }}catch(e){
errorDependencies();return null;} errorDependencies();return null;}
...@@ -25,10 +25,6 @@ ...@@ -25,10 +25,6 @@
'start_event':'start_loading', 'start_event':'start_loading',
'stop_event':'stop_loading', 'stop_event':'stop_loading',
'retvalue':'fileContent' }, // returns the file content 'string' 'retvalue':'fileContent' }, // returns the file content 'string'
'getDocument': {
'start_event':'start_gettingDocument',
'stop_event':'stop_gettingDocument',
'retvalue':'document' }, // returns the document object
'getDocumentList': { 'getDocumentList': {
'start_event':'start_gettingList', 'start_event':'start_gettingList',
'stop_event':'stop_gettingList', 'stop_event':'stop_gettingList',
...@@ -43,87 +39,13 @@ ...@@ -43,87 +39,13 @@
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
// jio globals // jio globals
var jioGlobalObj = { var jioGlobalObj = {
'localStorage': null, // where the browser stores data 'localStorage': LocalOrCookieStorage, // where the browser stores data
'queueID': 1, 'queueID': 1,
'storageTypeObject': {} // ex: {'type':'local','creator': fun ...} 'storageTypeObject': {} // ex: {'type':'local','creator': fun ...}
}; };
// end jio globals // end jio globals
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// cookies & localStorage
var browserStorage = function () {
};
browserStorage.prototype = {
getItem: function (name) {
return JSON.parse(localStorage.getItem(name));
},
setItem: function (name,value) {
if (name)
return localStorage.setItem(name,JSON.stringify(value));
},
getAll: function() {
return localStorage;
},
deleteItem: function (name) {
if (name)
delete localStorage[name];
}
};
var cookieStorage = function () {
};
cookieStorage.prototype = {
getItem: function (name) {
var cookies = document.cookie.split(';');
for (var i in cookies) {
var x = cookies[i].substr(0, cookies[i].indexOf('='));
var y = cookies[i].substr(cookies[i].indexOf('=')+1);
x = x.replace(/^\s+|\s+$/g,"");
if( x == name ) return unescape(y);
}
return null;
},
setItem: function (name,value) {
// function to store into cookies
if (value != undefined) {
document.cookie = name+'='+JSON.stringify(value)+';domain='+
window.location.hostname+
';path='+window.location.pathname;
return true;
}
return false;
},
getAll: function() {
var retObject = {};
var cookies = document.cookie.split(':');
for (var i in cookies) {
var x = cookies[i].substr(0, cookies[i].indexOf('='));
var y = cookies[i].substr(cookies[i].indexOf('=')+1);
x = x.replace(/^\s+|\s+$/g,"");
retObject[x] = unescape(y);
}
return retObject;
},
deleteItem: function (name) {
document.cookie = name+'=null;domain='+window.location.hostname+
';path='+window.location.pathname+
';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}
};
// set good localStorage
try {
if (localStorage.getItem) {
jioGlobalObj.localStorage = new browserStorage();
} else {
jioGlobalObj.localStorage = new cookieStorage();
}
}
catch (e) {
jioGlobalObj.localStorage = new cookieStorage();
}
// end cookies & localStorages
////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
// Tools // Tools
var createStorageObject = function ( options ) { var createStorageObject = function ( options ) {
...@@ -369,6 +291,9 @@ ...@@ -369,6 +291,9 @@
}, },
ended: function (job) { ended: function (job) {
// It is a callback function called just before user callback.
// It is called to manage jobObject according to the ended job.
console.log ('ended'); console.log ('ended');
switch (job.status) { switch (job.status) {
case 'done': case 'done':
...@@ -461,15 +386,17 @@ ...@@ -461,15 +386,17 @@
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
// Toucher // ActivityUpdater
var Toucher = function () { var ActivityUpdater = function () {
// The toucher is a little thread that show activity of this jio. // The activity updater is a little thread that proves activity of this
// jio instance.
this.interval = 400; this.interval = 400;
this.id = null; this.id = null;
}; };
Toucher.prototype = { ActivityUpdater.prototype = {
start: function (id) { start: function (id) {
// start the toucher // start the updater
console.log ('start touching jio/id/'+id); console.log ('start touching jio/id/'+id);
if (!this.id) { if (!this.id) {
this.touch(id); this.touch(id);
...@@ -483,7 +410,7 @@ ...@@ -483,7 +410,7 @@
} }
}, },
stop: function () { stop: function () {
// stop the toucher // stop the updater
console.log ('stop touching'); console.log ('stop touching');
if (this.id) { if (this.id) {
clearInterval (this.id); clearInterval (this.id);
...@@ -497,7 +424,7 @@ ...@@ -497,7 +424,7 @@
Date.now() ); Date.now() );
} }
}; };
// end Toucher // end ActivityUpdater
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
...@@ -522,7 +449,7 @@ ...@@ -522,7 +449,7 @@
this['pubsub'] = new PubSub(); this['pubsub'] = new PubSub();
this['queue'] = new JobQueue(this.pubsub); this['queue'] = new JobQueue(this.pubsub);
this['listener'] = new JobListener(this.queue); this['listener'] = new JobListener(this.queue);
this['toucher'] = new Toucher(); this['updater'] = new ActivityUpdater();
this['ready'] = false; this['ready'] = false;
// check storage type // check storage type
...@@ -544,7 +471,7 @@ ...@@ -544,7 +471,7 @@
// initializing objects // initializing objects
this.queue.init({'jioID':this.id}); this.queue.init({'jioID':this.id});
// start touching // start touching
this.toucher.start(this.id); this.updater.start(this.id);
// start listening // start listening
this.listener.start(); this.listener.start();
// is now ready // is now ready
...@@ -557,7 +484,7 @@ ...@@ -557,7 +484,7 @@
this.queue.close(); this.queue.close();
this.listener.stop(); this.listener.stop();
this.toucher.stop(); this.updater.stop();
this.ready = false; this.ready = false;
this.id = 0; this.id = 0;
return true; return true;
...@@ -568,7 +495,7 @@ ...@@ -568,7 +495,7 @@
this.queue.close(); this.queue.close();
this.listener.stop(); this.listener.stop();
this.toucher.stop(); this.updater.stop();
// TODO // TODO
this.ready = false; this.ready = false;
return true; return true;
......
...@@ -14,12 +14,6 @@ ...@@ -14,12 +14,6 @@
// end globals // end globals
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Tools
// end Tools
////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
// Local Storage // Local Storage
var LocalStorage = function ( options ) { var LocalStorage = function ( options ) {
...@@ -284,84 +278,95 @@ ...@@ -284,84 +278,95 @@
// create folders in dav storage, synchronously // create folders in dav storage, synchronously
// options : contains mkcol list // options : contains mkcol list
// options.location : the davstorage locations // options.location : the davstorage locations
// options.path : if path=/foo/bar then creates location/dav/foo/bar // options.path: if path=/foo/bar then creates location/dav/foo/bar
// options.success: the function called if success
var settings = $.extend ({},options); var settings = $.extend ({'success':function(){},
if (options.location && options.path) { 'error':function(){}},options);
var ok = false;
$.ajax ( {
url: options.location + '/dav/' + options.path,
type: 'MKCOL',
async: false,
// xhrFields: {withCredentials: 'true'}, // cross domain
success: function () {
// done
console.log ('ok');
ok = true;
},
error: function (type) {
switch (type.status) {
case 405: // Method Not Allowed
ok = true; // already done
break;
}
console.log ('error?');
}
} );
return ok;
} else {
return false;
}
},
checkNameAvailability: function ( job ) {
$.ajax ( { $.ajax ( {
url: job.storage.location + '/dav/' + job.userName, url: options.location + '/dav/' + options.path,
type: "HEAD", type: 'MKCOL',
async: true, async: true,
// xhrFields: {withCredentials: 'true'}, // cross domain // xhrFields: {withCredentials: 'true'}, // cross domain
success: function () { success: function () {
job.status = 'done'; // done
job.message = job.userName + ' is not available.'; settings.success();
job.isAvailable = false;
$.jio('publish',{'event':'job_done',
'job':job});
}, },
error: function (type) { error: function (type) {
switch (type.status) { switch (type.status) {
case 301: // Moved Permanantly case 405: // Method Not Allowed
job.status = 'done'; // already exists
job.message = job.userName + ' is not available.'; settings.success();
job.isAvailable = false;
$.jio('publish',{'event':'job_done',
'job':job});
break; break;
case 404: // Not Found default:
// TODO always returning 404 !! Why ?? settings.error();
console.warn ('always returning 404 ?'); break;
job.status = 'done'; }
job.message = job.userName + ' is available.'; }
job.isAvailable = true; } );
$.jio('publish',{'event':'job_done', },
'job':job}); checkNameAvailability: function ( job, jobendcallback ) {
// checks the availability of the [job.userName].
// if the name already exists, it is not available.
// job: the job object.
// job.userName: the name we want to check.
// jobendcallback: the function called at the end of the job.
// returns {'status':string,'message':string,'isAvailable':boolean}
// in the jobendcallback arguments.
$.ajax ( {
url: job.storage.location + '/dav/' + job.storage.userName + '/',
async: true,
type: 'PROPFIND',
dataType: 'xml',
headers: {'Authorization': 'Basic '+Base64.encode(
job.storage.userName + ':' +
job.storage.password ), Depth: '1'},
success: function (xmlData) {
var res = {};
res.status = job.status = 'done';
res.message = job.userName + ' is not available.';
res.isAvailable = false;
jobendcallback(job);
job.callback(res);
},
error: function (type) {
var res = {};
switch(type.status){
case 404:
res.status = job.status = 'done';
res.message = job.userName + ' is available.';
res.isAvailable = true;
break; break;
default: default:
job.status = 'fail'; res.status = job.status = 'fail';
job.message = 'Cannot check if ' + job.userName + res.message = 'Cannot check if ' + job.userName +
' is available.'; ' is available.';
job.isAvailable = false; res.isAvailable = false;
job.errno = type.status;
// $.error ( type.status ': Fail while trying to check ' +
// job.userName );
$.jio('publish',{'event':'job_fail',
'job':job});
break; break;
} }
res.errno = type.status;
jobendcallback(job);
job.callback(res);
} }
}); } );
}, },
saveDocument: function ( job ) { saveDocument: function ( job, jobendcallback ) {
// Save a document in a DAVStorage
// job: the job object
// job.options: the save options object
// job.options.overwrite: true -> overwrite
// job.options.force: true -> save even if jobdate < existingdate
// or overwrite: false
// jobendcallback: the function called at the end of the job.
// returns {'status':string,'message':string,'isSaved':boolean}
// in the jobendcallback arguments.
var settings = $.extend ({'overwrite':true, var settings = $.extend ({'overwrite':true,
'force':false},job.options); 'force':false},job.options);
var res = {};
// TODO if path of ../dav/user/applic does not exists, it won't work !! // TODO if path of ../dav/user/applic does not exists, it won't work !!
var saveOnDav = function () { var saveOnDav = function () {
//// save on dav //// save on dav
...@@ -378,19 +383,19 @@ ...@@ -378,19 +383,19 @@
job.storage.userName + ':' + job.storage.password )}, job.storage.userName + ':' + job.storage.password )},
// xhrFields: {withCredentials: 'true'}, // cross domain // xhrFields: {withCredentials: 'true'}, // cross domain
success: function () { success: function () {
job.status = 'done'; res.status = job.status = 'done';
job.message = 'Document saved.'; res.message = 'Document saved.';
job.isSaved = true; res.isSaved = true;
$.jio('publish',{'event':'job_done', jobendcallback(job);
'job':job}); job.callback(res);
}, },
error: function (type) { error: function (type) {
job.status = 'fail'; res.status = job.status = 'fail';
job.message = 'Cannot save document.'; res.message = 'Cannot save document.';
job.errno = type.status; res.errno = type.status;
job.isSaved = false; res.isSaved = false;
$.jio('publish',{'event':'job_fail', jobendcallback(job);
'job':job}); job.callback(res);
} }
} ); } );
//// end saving on dav //// end saving on dav
...@@ -399,6 +404,7 @@ ...@@ -399,6 +404,7 @@
if (settings.force) { if (settings.force) {
return saveOnDav(); return saveOnDav();
} }
var mkcol = this.mkcol;
//// start loading document //// start loading document
$.ajax ( { $.ajax ( {
url: job.storage.location + '/dav/' + url: job.storage.location + '/dav/' +
...@@ -410,43 +416,68 @@ ...@@ -410,43 +416,68 @@
headers: {'Authorization':'Basic '+Base64.encode( headers: {'Authorization':'Basic '+Base64.encode(
job.storage.userName + ':' + job.storage.password )}, job.storage.userName + ':' + job.storage.password )},
// xhrFields: {withCredentials: 'true'}, // cross domain // xhrFields: {withCredentials: 'true'}, // cross domain
success: function (content) { // TODO content ? success: function () {
// TODO merge files // TODO merge files
// Document already exists // Document already exists
if (settings.overwrite) { // overwrite if (settings.overwrite) { // overwrite
// TODO check date !!! // TODO check date !!!
// response headers contains
// Date: Mon, 30 Apr 2012 15:17:21 GMT
// Last-Modified: Mon, 30 Apr 2012 15:06:59 GMT
return saveOnDav(); return saveOnDav();
} }
// do not overwrite // do not overwrite
job.status = 'fail'; res.status = job.status = 'fail';
job.message = 'Document already exists.'; res.message = 'Document already exists.';
job.errno = 302; res.errno = 302;
job.isSaved = false; res.isSaved = false;
$.jio('publish',{'event':'job_fail', jobendcallback(job);
'job':job}); job.callback(res);
return false;
}, },
error: function (type) { error: function (type) {
switch (type.status) { switch (type.status) {
case 404: // Document not found case 404: // Document not found
// we can save on it // we can save on it
return saveOnDav(); mkcol({ // create col if not exist
location:job.storage.location,
path:'/dav/'+job.storage.userName+job.applicant.ID,
success:function(){
// and finaly save document
saveOnDav()
},
error:function(){
res.status = job.status = 'fail';
res.message = 'Cannot create document.';
res.errno = type.status;
res.isSaved = false;
jobendcallback(job);
job.callback(res);
}});
break;
default: // Unknown error default: // Unknown error
job.status = 'fail'; res.status = job.status = 'fail';
job.message = 'Unknown error.'; res.message = 'Unknown error.';
job.errno = type.status; res.errno = type.status;
job.isSaved = false; res.isSaved = false;
$.jio('publish',{'event':'job_fail', jobendcallback(job);
'job':job}); job.callback(res);
return false; break;
} }
} }
} ); } );
//// end loading document //// end loading document
}, },
loadDocument: function ( job ) { loadDocument: function ( job, jobendcallback ) {
// load the document into davstorage // Load a document from a DAVStorage. It returns a document object
// containing all information of the document and its content.
// job: the job object
// job.fileName: the document name we want to load.
// jobendcallback: the function called at the end of the job.
// returns {'status':string,'message':string,'document':object}
// in the jobendcallback arguments.
// document object is {'fileName':string,'fileContent':string,
// 'creationDate':date,'lastModified':date} //TODO!!
// TODO check if job's features are good // TODO check if job's features are good
$.ajax ( { $.ajax ( {
...@@ -462,27 +493,38 @@ ...@@ -462,27 +493,38 @@
job.storage.password )}, job.storage.password )},
// xhrFields: {withCredentials: 'true'}, // cross domain // xhrFields: {withCredentials: 'true'}, // cross domain
success: function (content) { success: function (content) {
job.status = 'done'; res.status = job.status = 'done';
job.message = 'Document loaded.'; res.message = 'Document loaded.';
job.fileContent = content; res.fileContent = content;
$.jio('publish',{'event':'job_done', jobendcallback(job);
'job':job}); job.callback(res);
}, },
error: function (type) { error: function (type) {
switch (type.status) { switch (type.status) {
case 404: case 404:
job.message = 'Document not found.'; break; res.message = 'Document not found.'; break;
default: default:
job.message = 'Cannot load "' + job.fileName + '".'; break; res.message = 'Cannot load "' + job.fileName + '".'; break;
} }
job.status = 'fail'; res.status = job.status = 'fail';
job.errno = type.status; res.errno = type.status;
$.jio('publish',{'event':'job_fail', jobendcallback(job);
'job':job}); job.callback(res);
} }
} ); } );
}, },
getDocumentList: function ( job ) { getDocumentList: function ( job, jobendcallback ) {
// Get a document list from a DAVStorage. It returns a document
// array containing all the user documents informations, but their
// content.
// job: the job object
// jobendcallback: the function called at the end of the job.
// returns {'status':string,'message':string,'list':array}
// in the jobendcallback arguments.
// the list is [object,object] -> object = {'fileName':string,
// 'lastModified':date,'creationDate':date}
$.ajax ( { $.ajax ( {
url: job.storage.location + '/dav/' + url: job.storage.location + '/dav/' +
job.storage.userName + '/' + job.applicant.ID + '/', job.storage.userName + '/' + job.applicant.ID + '/',
...@@ -512,22 +554,29 @@ ...@@ -512,22 +554,29 @@
documentArrayList.push (file); documentArrayList.push (file);
} }
}); });
job.status = 'done'; res.status = job.status = 'done';
job.message = 'List received.'; res.message = 'List received.';
job.list = documentArrayList; res.list = documentArrayList;
$.jio('publish',{'event':'job_done', jobendcallback(job);
'job':job}); job.callback(res);
}, },
error: function (type) { error: function (type) {
job.status = 'fail'; res.status = job.status = 'fail';
job.message = 'Cannot get list.'; res.message = 'Cannot get list.';
job.errno = type.status; res.errno = type.status;
$.jio('publish',{'event':'job_fail', jobendcallback(job);
'job':job}); job.callback(res);
} }
} ); } );
}, },
removeDocument: function ( job ) { removeDocument: function ( job, jobendcallback ) {
// Remove a document from a DAVStorage.
// job: the job object
// jobendcallback: the function called at the end of the job.
// returns {'status':string,'message':string,'isRemoved':boolean}
// in the jobendcallback arguments.
$.ajax ( { $.ajax ( {
url: job.storage.location + '/dav/' + url: job.storage.location + '/dav/' +
job.storage.userName + '/' + job.storage.userName + '/' +
...@@ -540,29 +589,27 @@ ...@@ -540,29 +589,27 @@
job.storage.password )}, job.storage.password )},
// xhrFields: {withCredentials: 'true'}, // cross domain // xhrFields: {withCredentials: 'true'}, // cross domain
success: function () { success: function () {
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);
}, },
error: function (type) { error: function (type) {
switch (type.status) { switch (type.status) {
case 404: case 404:
job.status = 'done'; res.stauts = job.status = 'done';
job.message = 'Document already removed.'; res.message = 'Document already removed.';
job.errno = type.status; res.errno = type.status;
$.jio('publish',{'event':'job_done',
'job':job});
break; break;
default: default:
job.status = 'fail'; res.status = job.status = 'fail';
job.message = 'Cannot remove "' + job.fileName + '".'; res.message = 'Cannot remove "' + job.fileName + '".';
job.errno = type.status; res.errno = type.status;
$.jio('publish',{'event':'job_fail',
'job':job});
break; break;
} }
jobendcallback(job);
job.callback(res);
} }
} ); } );
} }
......
;var LocalOrCookieStorage =
(function () {
// localorcookiestorage.js
// Creates an object that can store persistent information in localStorage.
// If it is not supported by the browser, it will store in cookies.
// Methods :
// - LocalOrCookieStorage.setItem('name',value);
// Sets an item with its value.
// - LocalOrCookieStorage.getItem('name');
// Returns a copy of the item.
// - LocalOrCookieStorage.deleteItem('name');
// Deletes an item forever.
// - LocalOrCookieStorage.getAll();
// Returns a new object containing all items and their values.
////////////////////////////////////////////////////////////////////////////
// cookies & localStorage
var browserStorage = function () {
};
browserStorage.prototype = {
getItem: function (name) {
return JSON.parse(localStorage.getItem(name));
},
setItem: function (name,value) {
if (name)
return localStorage.setItem(name,JSON.stringify(value));
},
getAll: function() {
return localStorage;
},
deleteItem: function (name) {
if (name)
delete localStorage[name];
}
};
var cookieStorage = function () {
};
cookieStorage.prototype = {
getItem: function (name) {
var cookies = document.cookie.split(';');
for (var i in cookies) {
var x = cookies[i].substr(0, cookies[i].indexOf('='));
var y = cookies[i].substr(cookies[i].indexOf('=')+1);
x = x.replace(/^\s+|\s+$/g,"");
if( x == name ) return unescape(y);
}
return null;
},
setItem: function (name,value) {
// function to store into cookies
if (value != undefined) {
document.cookie = name+'='+JSON.stringify(value)+';domain='+
window.location.hostname+
';path='+window.location.pathname;
return true;
}
return false;
},
getAll: function() {
var retObject = {};
var cookies = document.cookie.split(':');
for (var i in cookies) {
var x = cookies[i].substr(0, cookies[i].indexOf('='));
var y = cookies[i].substr(cookies[i].indexOf('=')+1);
x = x.replace(/^\s+|\s+$/g,"");
retObject[x] = unescape(y);
}
return retObject;
},
deleteItem: function (name) {
document.cookie = name+'=null;domain='+window.location.hostname+
';path='+window.location.pathname+
';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}
};
// set good localStorage
try {
if (localStorage.getItem) {
return new browserStorage();
} else {
return new cookieStorage();
}
}
catch (e) {
return new cookieStorage();
}
// end cookies & localStorages
////////////////////////////////////////////////////////////////////////////
})();
\ No newline at end of file
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