Commit 6e6d67b7 authored by Sven Franck's avatar Sven Franck

jslint pass davstorage.js

parent 0f3f9fa1
jIO.addStorageType('dav', function ( spec, my ) { /*jslint indent: 2, maxlen: 80, sloppy: true, nomen: true */
spec = spec || {}; /*global jIO: true, $: true, Base64: true */
var that = my.basicStorage( spec, my ), priv = {}; jIO.addStorageType('dav', function (spec, my) {
spec = spec || {};
var that = my.basicStorage(spec, my), priv = {},
super_serialized = that.serialized;
priv.secureDocId = function (string) { priv.secureDocId = function (string) {
var split = string.split('/'), i; var split = string.split('/'),
if (split[0] === '') { i;
split = split.slice(1); if (split[0] === '') {
} split = split.slice(1);
for (i = 0; i < split.length; i+= 1) { }
if (split[i] === '') { return ''; } for (i = 0; i < split.length; i += 1) {
} if (split[i] === '') {
return split.join('%2F'); return '';
}; }
priv.convertSlashes = function (string) { }
return string.split('/').join('%2F'); return split.join('%2F');
}; };
priv.convertSlashes = function (string) {
return string.split('/').join('%2F');
};
priv.restoreSlashes = function (string) { priv.restoreSlashes = function (string) {
return string.split('%2F').join('/'); return string.split('%2F').join('/');
}; };
priv.username = spec.username || ''; priv.username = spec.username || '';
priv.secured_username = priv.convertSlashes(priv.username); priv.secured_username = priv.convertSlashes(priv.username);
priv.application_name = spec.application_name || 'untitled'; priv.application_name = spec.application_name || 'untitled';
priv.secured_application_name = priv.convertSlashes(priv.application_name); priv.secured_application_name = priv.convertSlashes(priv.application_name);
priv.url = spec.url || ''; priv.url = spec.url || '';
priv.password = spec.password || ''; // TODO : is it secured ? priv.password = spec.password || ''; // TODO : is it secured ?
var super_serialized = that.serialized; that.serialized = function () {
that.serialized = function() { var o = super_serialized();
var o = super_serialized(); o.username = priv.username;
o.username = priv.username; o.application_name = priv.application_name;
o.application_name = priv.application_name; o.url = priv.url;
o.url = priv.url; o.password = priv.password; // TODO : not realy secured...
o.password = priv.password; // TODO : not realy secured... return o;
return o; };
};
/** /**
* If some other parameters is needed, it returns an error message. * If some other parameters is needed, it returns an error message.
* @method validateState * @method validateState
* @return {string} '' -> ok, 'message' -> error * @return {string} '' -> ok, 'message' -> error
*/ */
that.validateState = function() { that.validateState = function () {
if (priv.secured_username && priv.url) { if (priv.secured_username && priv.url) {
return ''; return '';
} }
return 'Need at least 2 parameters: "username" and "url".'; return 'Need at least 2 parameters: "username" and "url".';
}; };
priv.newAsyncModule = function () { priv.newAsyncModule = function () {
var async = {}; var async = {};
async.call = function (obj,function_name,arglist) { async.call = function (obj, function_name, arglist) {
obj._wait = obj._wait || {}; obj._wait = obj._wait || {};
if (obj._wait[function_name]) { if (obj._wait[function_name]) {
obj._wait[function_name]--; obj._wait[function_name] -= 1;
return function () {}; return function () {};
} }
// ok if undef or 0 // ok if undef or 0
arglist = arglist || []; arglist = arglist || [];
return obj[function_name].apply(obj[function_name],arglist); return obj[function_name].apply(obj[function_name], arglist);
};
async.neverCall = function (obj,function_name) {
obj._wait = obj._wait || {};
obj._wait[function_name] = -1;
};
async.wait = function (obj,function_name,times) {
obj._wait = obj._wait || {};
obj._wait[function_name] = times;
};
async.end = function () {
async.call = function(){};
};
return async;
}; };
async.neverCall = function (obj, function_name) {
obj._wait = obj._wait || {};
obj._wait[function_name] = -1;
};
async.wait = function (obj, function_name, times) {
obj._wait = obj._wait || {};
obj._wait[function_name] = times;
};
async.end = function () {
async.call = function () {};
};
return async;
};
priv.putOrPost = function (command,type) { priv.putOrPost = function (command, type) {
var secured_docid = priv.secureDocId(command.getDocId()); var secured_docid = priv.secureDocId(command.getDocId());
$.ajax ( { $.ajax({
url: priv.url + '/' + url: priv.url + '/' + priv.secured_username + '/' +
priv.secured_username + '/' + priv.secured_application_name + '/' + secured_docid + '?_=' +
priv.secured_application_name + '/' + Date.now(),
secured_docid + '?_=' + Date.now(), // to make url unique! // to make url unique and avoid chrome PUT on cache !
// and avoid chrome PUT on cache ! type: type,
type: type, data: command.getDocContent(),
data: command.getDocContent(), async: true,
async: true, dataType: 'text', // TODO is it necessary ?
dataType: 'text', // TODO is it necessary ? headers: {
headers: {'Authorization':'Basic '+Base64.encode( 'Authorization': 'Basic ' + Base64.encode(priv.username + ':' +
priv.username+':'+priv.password)}, priv.password)
// xhrFields: {withCredentials: 'true'}, // cross domain },
success: function () { // xhrFields: {withCredentials: 'true'}, // cross domain
that.success({ok:true,id:command.getDocId()}); success: function () {
}, that.success({
error: function (type) { ok: true,
// TODO : make statusText to lower case and add '_' id: command.getDocId()
type.error = type.statusText; });
type.reason = 'Cannot save "' + command.getDocId() + '"'; },
type.message = type.reason + '.'; error: function (type) {
that.retry(type); // TODO : make statusText to lower case and add '_'
} type.error = type.statusText;
} ); type.reason = 'Cannot save "' + command.getDocId() + '"';
}; type.message = type.reason + '.';
that.retry(type);
}
});
};
that.post = function (command) { that.post = function (command) {
priv.putOrPost (command,'POST'); priv.putOrPost(command, 'POST');
}; };
/** /**
* Saves a document in the distant dav storage. * Saves a document in the distant dav storage.
* @method put * @method put
*/ */
that.put = function (command) { that.put = function (command) {
priv.putOrPost (command,'PUT'); priv.putOrPost(command, 'PUT');
}; // end put }; // end put
/** /**
* Loads a document from a distant dav storage. * Loads a document from a distant dav storage.
* @method get * @method get
*/ */
that.get = function (command) { that.get = function (command) {
var secured_docid = priv.secureDocId(command.getDocId()), var secured_docid = priv.secureDocId(command.getDocId()),
doc = {}, getContent = function () { doc = {},
$.ajax ( { getContent = function () {
url: priv.url + '/' + $.ajax({
priv.secured_username + '/' + url: priv.url + '/' + priv.secured_username + '/' +
priv.secured_application_name + '/' + priv.secured_application_name + '/' + secured_docid + '?_=' +
secured_docid + '?_=' + Date.now(), Date.now(),
type: "GET", type: "GET",
async: true, async: true,
dataType: 'text', // TODO is it necessary ? dataType: 'text', // TODO is it necessary ?
headers: {'Authorization':'Basic '+Base64.encode( headers: {
priv.username + ':' + priv.password )}, 'Authorization': 'Basic ' + Base64.encode(priv.username + ':' +
// xhrFields: {withCredentials: 'true'}, // cross domain priv.password)
success: function (content) { },
doc.content = content; // xhrFields: {withCredentials: 'true'}, // cross domain
that.success(doc); success: function (content) {
}, doc.content = content;
error: function (type) { that.success(doc);
type.error = type.statusText; // TODO : to lower case },
if (type.status === 404) { error: function (type) {
type.message = 'Document "' + type.error = type.statusText; // TODO : to lower case
command.getDocId() + if (type.status === 404) {
'" not found.'; type.message = 'Document "' + command.getDocId() +
type.reason = 'missing'; '" not found.';
that.error(type); type.reason = 'missing';
} else { that.error(type);
type.reason = } else {
'An error occured when trying to get "' + type.reason =
command.getDocId() + '"'; 'An error occured when trying to get "' +
type.message = type.reason + '.'; command.getDocId() + '"';
that.retry(type); type.message = type.reason + '.';
} that.retry(type);
}
} );
};
doc._id = command.getDocId();
// NOTE : if (command.getOption('content_only') { return getContent(); }
// Get properties
$.ajax ( {
url: priv.url + '/' +
priv.secured_username + '/' +
priv.secured_application_name + '/' +
secured_docid + '?_=' + Date.now(),
type: "PROPFIND",
async: true,
dataType: 'xml',
headers: {'Authorization':'Basic '+Base64.encode(
priv.username + ':' + priv.password )},
success: function (xmlData) {
$(xmlData).find(
'lp1\\:getlastmodified, getlastmodified'
).each( function () {
doc._last_modified =
new Date($(this).text()).getTime();
});
$(xmlData).find(
'lp1\\:creationdate, creationdate'
).each( function () {
doc._creation_date =
new Date($(this).text()).getTime();
});
if (!command.getOption('metadata_only')) {
getContent();
} else {
that.success(doc);
}
},
error: function (type) {
if (type.status === 404) {
type.message = 'Cannot find "' + command.getDocId() +
'" informations.';
type.reason = 'missing';
that.error(type);
} else {
type.reason = 'Cannot get "' + command.getDocId() +
'" informations';
type.message = type.reason + '.';
that.retry(type);
}
} }
} ); }
}; });
};
doc._id = command.getDocId();
// NOTE : if (command.getOption('content_only') { return getContent(); }
// Get properties
$.ajax({
url: priv.url + '/' + priv.secured_username + '/' +
priv.secured_application_name + '/' +
secured_docid + '?_=' + Date.now(),
type: "PROPFIND",
async: true,
dataType: 'xml',
headers: {
'Authorization': 'Basic ' + Base64.encode(priv.username + ':' +
priv.password)
},
success: function (xmlData) {
$(xmlData).find('lp1\\:getlastmodified, getlastmodified').each(
function () {
doc._last_modified = new Date($(this).text()).getTime();
}
);
$(xmlData).find('lp1\\:creationdate, creationdate').each(
function () {
doc._creation_date = new Date($(this).text()).getTime();
}
);
if (!command.getOption('metadata_only')) {
getContent();
} else {
that.success(doc);
}
},
error: function (type) {
if (type.status === 404) {
type.message = 'Cannot find "' + command.getDocId() +
'" informations.';
type.reason = 'missing';
that.error(type);
} else {
type.reason = 'Cannot get "' + command.getDocId() +
'" informations';
type.message = type.reason + '.';
that.retry(type);
}
}
});
};
/** /**
* Gets a document list from a distant dav storage. * Gets a document list from a distant dav storage.
* @method allDocs * @method allDocs
*/ */
that.allDocs = function (command) { that.allDocs = function (command) {
var rows = [], var rows = [],
am = priv.newAsyncModule(), o = {}; am = priv.newAsyncModule(),
o = {};
o.getContent = function (file) { o.getContent = function (file) {
$.ajax ( { $.ajax({
url: priv.url + '/' + url: priv.url + '/' + priv.secured_username + '/' +
priv.secured_username + '/' + priv.secured_application_name + '/' + priv.secureDocId(file.id) +
priv.secured_application_name + '/' + '?_=' + Date.now(),
priv.secureDocId(file.id) + '?_=' + Date.now(), type: "GET",
type: "GET", async: true,
async: true, dataType: 'text', // TODO : is it necessary ?
dataType: 'text', // TODO : is it necessary ? headers: {
headers: {'Authorization':'Basic '+ 'Authorization': 'Basic ' + Base64.encode(priv.username + ':' +
Base64.encode(priv.username +':'+ priv.password)
priv.password)}, },
success: function (content) { success: function (content) {
file.value.content = content; file.value.content = content;
// WARNING : files can be disordered because // WARNING : files can be disordered because
// of asynchronous action // of asynchronous action
rows.push (file); rows.push(file);
am.call(o,'success'); am.call(o, 'success');
}, },
error: function (type) { error: function (type) {
type.error = type.statusText; // TODO : to lower case type.error = type.statusText; // TODO : to lower case
type.reason = 'Cannot get a document '+ type.reason = 'Cannot get a document ' +
'content from DAVStorage'; 'content from DAVStorage';
type.message = type.message + '.'; type.message = type.message + '.';
am.call(o,'error',[type]); am.call(o, 'error', [type]);
} }
}); });
}; };
o.getDocumentList = function () { o.getDocumentList = function () {
$.ajax ( { $.ajax({
url: priv.url + '/' + url: priv.url + '/' + priv.secured_username + '/' +
priv.secured_username + '/' + priv.secured_application_name + '/' + '?_=' + Date.now(),
priv.secured_application_name + '/' + '?_=' + Date.now(), async: true,
async: true, type: 'PROPFIND',
type: 'PROPFIND', dataType: 'xml',
dataType: 'xml', headers: {
headers: {'Authorization': 'Basic '+Base64.encode( 'Authorization': 'Basic ' + Base64.encode(
priv.username + ':' + priv.password ), Depth: '1'}, priv.username + ':' + priv.password
// xhrFields: {withCredentials: 'true'}, // cross domain ),
success: function (xmlData) { Depth: '1'
var response = $(xmlData).find( },
'D\\:response, response' // xhrFields: {withCredentials: 'true'}, // cross domain
); success: function (xmlData) {
var len = response.length; var response = $(xmlData).find('D\\:response, response'),
if (len === 1) { len = response.length;
return am.call(o,'success'); if (len === 1) {
} else { return am.call(o, 'success');
am.wait(o,'success',len-2); }
} am.wait(o, 'success', len - 2);
response.each( function(i,data){ response.each(function (i, data) {
if(i>0) { // exclude parent folder if (i > 0) { // exclude parent folder
var file = {value:{}}; var file = {
$(data).find('D\\:href, href').each(function(){ value: {}
var split = $(this).text().split('/'); };
file.id = split[split.length-1]; $(data).find('D\\:href, href').each(function () {
file.id = priv.restoreSlashes(file.id); var split = $(this).text().split('/');
file.key = file.id; file.id = split[split.length - 1];
}); file.id = priv.restoreSlashes(file.id);
if (file.id === '.htaccess' || file.key = file.id;
file.id === '.htpasswd') { return; } });
$(data).find( if (file.id === '.htaccess' || file.id === '.htpasswd') {
'lp1\\:getlastmodified, getlastmodified' return;
).each(function () { }
file.value._last_modified = $(data).find('lp1\\:getlastmodified, getlastmodified').each(
new Date($(this).text()).getTime(); function () {
}); file.value._last_modified = new Date(
$(data).find( $(this).text()
'lp1\\:creationdate, creationdate' ).getTime();
).each(function () {
file.value._creation_date =
new Date($(this).text()).getTime();
});
if (!command.getOption ('metadata_only')) {
am.call(o,'getContent',[file]);
} else {
rows.push (file);
am.call(o,'success');
}
}
});
},
error: function (type) {
if (type.status === 404) {
type.error = 'not_found';
type.reason = 'missing';
am.call(o,'error',[type]);
} else {
type.error = type.statusText; // TODO : to lower case
type.reason =
'Cannot get a document list from DAVStorage';
type.message = type.reason + '.';
am.call(o,'retry',[type]);
}
} }
} ); );
}; $(data).find('lp1\\:creationdate, creationdate').each(
o.retry = function (error) { function () {
am.neverCall(o,'retry'); file.value._creation_date = new Date(
am.neverCall(o,'success'); $(this).text()
am.neverCall(o,'error'); ).getTime();
that.retry(error);
};
o.error = function (error) {
am.neverCall(o,'retry');
am.neverCall(o,'success');
am.neverCall(o,'error');
that.error(error);
};
o.success = function () {
am.neverCall(o,'retry');
am.neverCall(o,'success');
am.neverCall(o,'error');
that.success({total_rows:rows.length,
rows:rows});
};
am.call (o,'getDocumentList');
}; // end allDocs
/**
* Removes a document from a distant dav storage.
* @method remove
*/
that.remove = function (command) {
var secured_docid = priv.secureDocId(command.getDocId());
$.ajax ( {
url: priv.url + '/' +
priv.secured_username + '/' +
priv.secured_application_name + '/' +
secured_docid + '?_=' + Date.now(),
type: "DELETE",
async: true,
headers: {'Authorization':'Basic '+Base64.encode(
priv.username + ':' + priv.password )},
// xhrFields: {withCredentials: 'true'}, // cross domain
success: function (data,state,type) {
that.success({ok:true,id:command.getDocId()});
},
error: function (type,state,statusText) {
if (type.status === 404) {
//that.success({ok:true,id:command.getDocId()});
type.error = 'not_found';
type.reason = 'missing';
type.message = 'Cannot remove missing file.';
that.error(type);
} else {
type.reason = 'Cannot remove "' + that.getDocId() + '"';
type.message = type.reason + '.';
that.retry(type);
} }
);
if (!command.getOption('metadata_only')) {
am.call(o, 'getContent', [file]);
} else {
rows.push(file);
am.call(o, 'success');
}
} }
} ); });
},
error: function (type) {
if (type.status === 404) {
type.error = 'not_found';
type.reason = 'missing';
am.call(o, 'error', [type]);
} else {
type.error = type.statusText; // TODO : to lower case
type.reason =
'Cannot get a document list from DAVStorage';
type.message = type.reason + '.';
am.call(o, 'retry', [type]);
}
}
});
};
o.retry = function (error) {
am.neverCall(o, 'retry');
am.neverCall(o, 'success');
am.neverCall(o, 'error');
that.retry(error);
};
o.error = function (error) {
am.neverCall(o, 'retry');
am.neverCall(o, 'success');
am.neverCall(o, 'error');
that.error(error);
}; };
o.success = function () {
am.neverCall(o, 'retry');
am.neverCall(o, 'success');
am.neverCall(o, 'error');
that.success({
total_rows: rows.length,
rows: rows
});
};
am.call(o, 'getDocumentList');
}; // end allDocs
/**
* Removes a document from a distant dav storage.
* @method remove
*/
that.remove = function (command) {
var secured_docid = priv.secureDocId(command.getDocId());
$.ajax({
url: priv.url + '/' + priv.secured_username + '/' +
priv.secured_application_name + '/' + secured_docid + '?_=' +
Date.now(),
type: "DELETE",
async: true,
headers: {
'Authorization': 'Basic ' + Base64.encode(
priv.username + ':' + priv.password
)
},
// xhrFields: {withCredentials: 'true'}, // cross domain
// jslint: removed params data, state, type
success: function () {
that.success({
ok: true,
id: command.getDocId()
});
},
error: function (type) {
if (type.status === 404) {
//that.success({ok:true,id:command.getDocId()});
type.error = 'not_found';
type.reason = 'missing';
type.message = 'Cannot remove missing file.';
that.error(type);
} else {
type.reason = 'Cannot remove "' + that.getDocId() + '"';
type.message = type.reason + '.';
that.retry(type);
}
}
});
};
return that; return that;
}; });
\ 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