Commit 531ca1e8 authored by Sven Franck's avatar Sven Franck

jslint pass xwikistorage.js

parent bc17b228
(function ($,Base64) { /*jslint indent: 2, maxlen: 80, sloppy: true, nomen: true */
/*global toSend: true, jIO: true, jQuery: true, Base64: true */
/**
* JIO XWiki based storage. Type = 'xwiki'.
* Edits XWiki documents as html using html editor.
* Test this code using the following inputs:
*
{"type":"xwiki","username":"Admin","password":"admin","xwikiurl":"http://127.0.0
.1:8080/xwiki","space":"OfficeJS"}
*/
(function ($, Base64) {
var newXWikiStorage = function (spec, my) {
var that, priv, escapeDocId, restoreDocId,
doWithFormToken, getDates, super_serialized;
/**
* JIO XWiki based storage. Type = 'xwiki'.
* Edits XWiki documents as html using html editor.
* Test this code using the following inputs:
* {"type":"xwiki","username":"Admin","password":"admin","xwikiurl":"http://127.0.0.1:8080/xwiki","space":"OfficeJS"}
*/
var newXWikiStorage = function(spec, my)
{
/** The input configuration. */ /** The input configuration. */
spec = spec || {}; spec = spec || {};
/** The "public" object which will have methods called on it. */ /** The "public" object which will have methods called on it. */
var that = my.basicStorage(spec, my); that = my.basicStorage(spec, my);
/** "private" fields. */ /** "private" fields. */
var priv = { priv = {
username: spec.username || '', username: spec.username || '',
password: spec.password || '', password: spec.password || '',
xwikiurl: spec.xwikiurl || '', xwikiurl: spec.xwikiurl || '',
space: spec.space || '' space: spec.space || ''
}; };
//--------------------- Private Functions ---------------------// //--------------------- Private Functions ---------------------//
/** Escape a document ID by URL escaping all '/' characters. */ /** Escape a document ID by URL escaping all '/' characters. */
var escapeDocId = function(docId) { escapeDocId = function (docId) {
return docId.replace(/.html$/, '').split('/').join('%2F'); // jslint: replaced "." with [\w\W]
return docId.replace(/[\w\W]html$/, '').split('/').join('%2F');
}; };
/** Restore a document id from the escaped form. */ /** Restore a document id from the escaped form. */
var restoreDocId = function(escapedDocId) { restoreDocId = function (escapedDocId) {
return escapedDocId.split('%2F').join('/') + '.html'; return escapedDocId.split('%2F').join('/') + '.html';
}; };
/** /**
* Get the Anti-CSRF token and do something with it. * Get the Anti-CSRF token and do something with it.
* *
* @param docId the document id of a document which you have permission to edit. * @param docId document id of document which you have permission to edit.
* @param whatToDo a function which will be called with the form token as the parameter. * @param whatToDo function which is called with form token as parameter.
*/ */
var doWithFormToken = function(docId, whatToDo) { doWithFormToken = function (docId, whatToDo) {
var url = priv.xwikiurl + '/bin/edit/' + priv.space + '/' + escapeDocId(docId) + var url = priv.xwikiurl + '/bin/edit/' + priv.space + '/' +
'?editor=wiki&cachebuster=' + Date.now(); escapeDocId(docId) + '?editor=wiki&cachebuster=' + Date.now();
$.ajax({ $.ajax({
url: url, url: url,
type: "GET", type: "GET",
async: true, async: true,
dataType: 'text', dataType: 'text',
headers: {'Authorization':'Basic ' + Base64.encode( headers: {
priv.username + ':' + priv.password )}, 'Authorization': 'Basic ' + Base64.encode(priv.username + ':' +
success: function (html) { priv.password)
whatToDo($(html).find('input[name=form_token]').attr('value')); },
} success: function (html) {
}); whatToDo($(html).find('input[name=form_token]').attr('value'));
}
});
}; };
/** /**
* Get the creation and modification dates for a page. * Get the creation and modification dates for a page.
* *
* @param docId the ID of the document. * @param docId the ID of the document.
* @param callWhenDone a callback which will be called when this function finishes. * @param callWhenDone callback, will be called when function finishes.
*/ */
var getDates = function(docId, callWhenDone) { getDates = function (docId, callWhenDone) {
// http://127.0.0.1:8080/xwiki/rest/wikis/xwiki/spaces/Main/pages/<pageName> // http://127.0.0.1:8080/xwiki/rest/wikis/xwiki/
var map = {}; // spaces/Main/pages/<pageName>
$.ajax ( { var map = {};
url: priv.xwikiurl + '/rest/wikis/' + 'xwiki' + $.ajax({
'/spaces/' + priv.space + url: priv.xwikiurl + '/rest/wikis/' + 'xwiki' + '/spaces/' + priv.space
'/pages/' + escapeDocId(docId) + + '/pages/' + escapeDocId(docId) + '?cachebuster=' + Date.now(),
'?cachebuster=' + Date.now(), type: "GET",
type: "GET", async: true,
async: true, dataType: 'xml',
dataType: 'xml', headers: {
headers: {'Authorization':'Basic ' + Base64.encode( 'Authorization': 'Basic ' + Base64.encode(priv.username + ':' +
priv.username + ':' + priv.password )}, priv.password)
success: function (xmlData) { },
$(xmlData).find('modified').each(function() { success: function (xmlData) {
map._last_modified = Date.parse($(this).text()); $(xmlData).find('modified').each(function () {
}); map._last_modified = Date.parse($(this).text());
$(xmlData).find('created').each(function() { });
map._creation_date = Date.parse($(this).text()); $(xmlData).find('created').each(function () {
}); map._creation_date = Date.parse($(this).text());
callWhenDone(); });
} callWhenDone();
}); }
return map; });
return map;
}; };
//--------------------- Public Functions ---------------------// //--------------------- Public Functions ---------------------//
/** Get a serialized form of the module state. */ /** Get a serialized form of the module state. */
var super_serialized = that.serialized; super_serialized = that.serialized;
that.serialized = function() { that.serialized = function () {
var o = super_serialized(); var o = super_serialized(), key;
for(var key in priv) { for (key in priv) {
if (priv.hasOwnProperty(key)) { if (priv.hasOwnProperty(key)) {
o[key] = priv[key]; o[key] = priv[key];
}
} }
return o; }
return o;
}; };
/** Check that the storage module is properly setup. */ /** Check that the storage module is properly setup. */
that.validateState = function() { that.validateState = function () {
for(var key in priv) { var key;
if (priv.hasOwnProperty(key) && !priv[key]) { for (key in priv) {
return 'Must specify "' + key + '".'; if (priv.hasOwnProperty(key) && !priv[key]) {
} return 'Must specify "' + key + '".';
} }
return ''; }
return '';
}; };
/** Alias to put() */ /** Alias to put() */
that.post = function (command) { that.post = function (command) {
that.put(command); that.put(command);
}; };
/** /**
* Saves a document as an XWikiDocument. * Saves a document as an XWikiDocument.
* *
* @param command must contain document ID and document content. * @param command must contain document ID and document content.
*/ */
that.put = function (command) { that.put = function (command) {
doWithFormToken(command.getDocId(), function(formToken) { doWithFormToken(command.getDocId(), function (formToken) {
if (!formToken) { if (!formToken) {
throw Error("missing form token"); throw new Error("missing form token");
} }
$.ajax({ $.ajax({
url: priv.xwikiurl + '/bin/preview/' + priv.space + url: priv.xwikiurl + '/bin/preview/' + priv.space + '/' +
'/' + escapeDocId(command.getDocId()), escapeDocId(command.getDocId()),
type: "POST", type: "POST",
async: true, async: true,
dataType: 'text', dataType: 'text',
headers: {'Authorization':'Basic ' + Base64.encode( headers: {
priv.username + ':' + priv.password )}, 'Authorization': 'Basic ' + Base64.encode(priv.username + ':' +
data: { priv.password)
parent: '', },
title: '', data: {
xredirect: '', parent: '',
language: 'en', title: '',
RequiresHTMLConversion: 'content', xredirect: '',
content_syntax: 'xwiki/2.1', language: 'en',
content: command.getDocContent(), RequiresHTMLConversion: 'content',
xeditaction: 'edit', content_syntax: 'xwiki/2.1',
comment: 'Saved by OfficeJS', content: command.getDocContent(),
action_saveandcontinue: 'Save & Continue', xeditaction: 'edit',
syntaxId: 'xwiki/2.1', comment: 'Saved by OfficeJS',
xhidden: 0, action_saveandcontinue: 'Save & Continue',
minorEdit: 0, syntaxId: 'xwiki/2.1',
ajax: true, xhidden: 0,
form_token: formToken minorEdit: 0,
}, ajax: true,
success: function(html) { form_token: formToken
that.success({ },
ok: true, success: function () {
id: command.getDocId() that.success({
}); ok: true,
} id: command.getDocId()
}); });
}
}); });
});
}; // end put }; // end put
/** /**
* Loads a document from the XWiki storage. * Loads a document from the XWiki storage.
*/ */
that.get = function (command) { that.get = function (command) {
// /bin/view/Main/WebHomee?xpage=plain // /bin/view/Main/WebHomee?xpage=plain
/** /**
* Protocol specification: * Protocol specification:
* { * {
* "_id": "somePage", * "_id": "somePage",
* "content": "aoeu", * "content": "aoeu",
* "_creation_date": 1348154789478, * "_creation_date": 1348154789478,
* "_last_modified": 1348154789478 * "_last_modified": 1348154789478
* } * }
*/ */
var doc; var doc,
var pendingRequests = 2; pendingRequests = 2,
var finishedRequest = function() { finishedRequest = function () {
pendingRequests--; pendingRequests -= 1;
if (pendingRequests < 1) { if (pendingRequests < 1) {
that.success(doc); that.success(doc);
} }
}; };
doc = (function() { doc = (function () {
var resultMap = getDates(command.getDocId(), finishedRequest); var resultMap = getDates(command.getDocId(), finishedRequest);
$.ajax({ $.ajax({
url: priv.xwikiurl + '/bin/get/' + priv.space + url: priv.xwikiurl + '/bin/get/' + priv.space + '/' +
'/' + escapeDocId(command.getDocId()) + escapeDocId(command.getDocId()) + '?xpage=plain&cachebuster=' +
'?xpage=plain&cachebuster=' + Date.now(), Date.now(),
type: "GET", type: "GET",
async: true, async: true,
dataType: 'text', dataType: 'text',
headers: {'Authorization':'Basic ' + Base64.encode( headers: {
priv.username + ':' + priv.password )}, 'Authorization': 'Basic ' + Base64.encode(priv.username + ':' +
success: function (html) { priv.password)
resultMap.content = html; },
finishedRequest(); success: function (html) {
} resultMap.content = html;
}); finishedRequest();
return resultMap; }
})(); });
doc._id = command.getDocId(); return resultMap;
}());
doc._id = command.getDocId();
}; // end get }; // end get
/** /**
...@@ -214,120 +222,120 @@ var newXWikiStorage = function(spec, my) ...@@ -214,120 +222,120 @@ var newXWikiStorage = function(spec, my)
* @method allDocs * @method allDocs
*/ */
that.allDocs = function (command) { that.allDocs = function (command) {
// http://127.0.0.1:8080/xwiki/rest/wikis/xwiki/spaces/Main/pages // http://127.0.0.1:8080/xwiki/rest/wikis/xwiki/spaces/Main/pages
$.ajax ( { $.ajax({
url: priv.xwikiurl + '/rest/wikis/' + 'xwiki' url: priv.xwikiurl + '/rest/wikis/' + 'xwiki' + '/spaces/' +
+ '/spaces/' + priv.space priv.space + '/pages?cachebuster=' + Date.now(),
+ '/pages?cachebuster=' + Date.now(), type: "GET",
type: "GET", async: true,
async: true, dataType: 'xml',
dataType: 'xml', headers: {
headers: {'Authorization':'Basic ' + Base64.encode( 'Authorization': 'Basic ' + Base64.encode(priv.username + ':' +
priv.username + ':' + priv.password )}, priv.password)
success: function (xmlData) { },
/** Protocol definition: success: function (xmlData) {
* { /** Protocol definition:
* "total_rows":2, * {
* "rows":[{ * "total_rows":2,
* "id":"b", * "rows":[{
* "key":"b", * "id":"b",
* "value":{ * "key":"b",
* "content":"aoeu", * "value":{
* "_creation_date":1348154789478, * "content":"aoeu",
* "_last_modified":1348154789478 * "_creation_date":1348154789478,
* } * "_last_modified":1348154789478
* }, * }
* { * },
* "id":"oeau", * {
* "key":"oeau", * "id":"oeau",
* "value"{ * "key":"oeau",
* "content":"oeu", * "value"{
* "_creation_date":1348154834680, * "content":"oeu",
* "_last_modified":1348154834680 * "_creation_date":1348154834680,
* } * "_last_modified":1348154834680
* } * }
* ] * }
* } * ]
*/ * }
var totalRows = 0 */
var data = []; var totalRows = 0,
data = [],
// The number of async calls which are waiting to return. // The number of async calls which are waiting to return.
var outstandingCalls = 0; outstandingCalls = 0,
toSend;
$(xmlData).find('name').each(function() { $(xmlData).find('name').each(function () {
outstandingCalls++; outstandingCalls += 1;
var id = restoreDocId($(this).text()); var id = restoreDocId($(this).text()),
var entry = { entry = {
'id': id, 'id': id,
'key': id, 'key': id,
'value': getDates(id, function() { 'value': getDates(id, function () {
outstandingCalls--; outstandingCalls -= 1;
if (outstandingCalls < 1) { if (outstandingCalls < 1) {
that.success(toSend); that.success(toSend);
} }
}) })
}; };
data[totalRows++] = entry; data[totalRows += 1] = entry;
}); });
var toSend = { toSend = {
'total_rows': totalRows, 'total_rows': totalRows,
'rows': data 'rows': data
}; };
/* TODO: Include the content if requested. /* TODO: Include the content if requested.
if (!command.getOption('metadata_only')) { if (!command.getOption('metadata_only')) {
getContent(); getContent();
} else { } else {
that.success(toSend); that.success(toSend);
} }
*/ */
}, },
error: function (type) { error: function (type) {
if (type.status === 404) { if (type.status === 404) {
type.message = 'Cannot find "' + command.getDocId() + type.message = 'Cannot find "' + command.getDocId() +
'" informations.'; '"informations.';
type.reason = 'missing'; type.reason = 'missing';
that.error(type); that.error(type);
} else { } else {
type.reason = 'Cannot get "' + command.getDocId() + type.reason = 'Cannot get "' + command.getDocId() +
'" informations'; '"informations';
type.message = type.reason + '.'; type.message = type.reason + '.';
that.retry(type); that.retry(type);
} }
} }
} ); });
}; };
/** /**
* Removes a document from the XWiki storage. * Removes a document from the XWiki storage.
*/ */
that.remove = function (command) { that.remove = function (command) {
// http://127.0.0.1:8080/xwiki/bin/delete/Main/WebHomee?confirm=1&form_token=r7x0oGBSk2EFm2fxVULfFA // http://127.0.0.1:8080/xwiki/bin/delete/Main/WebHomee?
doWithFormToken(command.getDocId(), function(formToken) { // confirm=1&form_token= //r7x0oGBSk2EFm2fxVULfFA
$.ajax({ doWithFormToken(command.getDocId(), function (formToken) {
url: priv.xwikiurl + '/bin/delete/' + priv.space + $.ajax({
'/' + escapeDocId(command.getDocId()), url: priv.xwikiurl + '/bin/delete/' + priv.space + '/' +
type: "POST", escapeDocId(command.getDocId()),
async: true, type: "POST",
dataType: 'text', async: true,
headers: {'Authorization':'Basic ' + Base64.encode( dataType: 'text',
priv.username + ':' + priv.password )}, headers: {
data: { 'Authorization': 'Basic ' + Base64.encode(priv.username + ':' +
confirm: 1, priv.password)
form_token: formToken },
}, data: {
success: function(html) { confirm: 1,
that.success({ form_token: formToken
ok: true, },
id: command.getDocId() success: function () {
}); that.success({
} ok: true,
id: command.getDocId()
}); });
}
}); });
});
}; // end remove }; // end remove
return that; return that;
}; };
jIO.addStorageType('xwiki', newXWikiStorage); jIO.addStorageType('xwiki', newXWikiStorage);
}(jQuery, Base64));
}(jQuery,Base64)); \ 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