Commit 540b3609 authored by lucas.parsy's avatar lucas.parsy Committed by Romain Courteaud

reimplemented jio dropbox storage.

works with the new dropbox API.
dropbox storage redesigned to have the same behavior as DAV storage.
parent cfea757e
...@@ -180,6 +180,7 @@ module.exports = function (grunt) { ...@@ -180,6 +180,7 @@ module.exports = function (grunt) {
'src/jio.storage/memorystorage.js', 'src/jio.storage/memorystorage.js',
'src/jio.storage/localstorage.js', 'src/jio.storage/localstorage.js',
'src/jio.storage/zipstorage.js', 'src/jio.storage/zipstorage.js',
'src/jio.storage/dropboxstorage.js',
'src/jio.storage/davstorage.js', 'src/jio.storage/davstorage.js',
'src/jio.storage/unionstorage.js', 'src/jio.storage/unionstorage.js',
'src/jio.storage/erp5storage.js', 'src/jio.storage/erp5storage.js',
......
...@@ -36,6 +36,7 @@ zip: ...@@ -36,6 +36,7 @@ zip:
@cp lib/require/require.js $(TMPDIR)/jio/ @cp lib/require/require.js $(TMPDIR)/jio/
@cp src/jio.storage/localstorage.js $(TMPDIR)/jio/storage/ @cp src/jio.storage/localstorage.js $(TMPDIR)/jio/storage/
@cp src/jio.storage/davstorage.js $(TMPDIR)/jio/storage/ @cp src/jio.storage/davstorage.js $(TMPDIR)/jio/storage/
@cp src/jio.storage/dropboxstorage.js $(TMPDIR)/jio/storage/
@cp src/jio.storage/erp5storage.js $(TMPDIR)/jio/storage/ @cp src/jio.storage/erp5storage.js $(TMPDIR)/jio/storage/
@cp src/jio.storage/indexstorage.js $(TMPDIR)/jio/storage/ @cp src/jio.storage/indexstorage.js $(TMPDIR)/jio/storage/
@cp src/jio.storage/gidstorage.js $(TMPDIR)/jio/storage/ @cp src/jio.storage/gidstorage.js $(TMPDIR)/jio/storage/
...@@ -68,6 +69,7 @@ zip: ...@@ -68,6 +69,7 @@ zip:
@$(UGLIFY) lib/require/require.js >$(TMPDIR)/jio/require.min.js 2>/dev/null @$(UGLIFY) lib/require/require.js >$(TMPDIR)/jio/require.min.js 2>/dev/null
@$(UGLIFY) src/jio.storage/localstorage.js >$(TMPDIR)/jio/storage/localstorage.min.js 2>/dev/null @$(UGLIFY) src/jio.storage/localstorage.js >$(TMPDIR)/jio/storage/localstorage.min.js 2>/dev/null
@$(UGLIFY) src/jio.storage/davstorage.js >$(TMPDIR)/jio/storage/davstorage.min.js 2>/dev/null @$(UGLIFY) src/jio.storage/davstorage.js >$(TMPDIR)/jio/storage/davstorage.min.js 2>/dev/null
@$(UGLIFY) src/jio.storage/dropboxstorage.js >$(TMPDIR)/jio/storage/dropboxstorage.min.js 2>/dev/null
@$(UGLIFY) src/jio.storage/erp5storage.js >$(TMPDIR)/jio/storage/erp5storage.min.js 2>/dev/null @$(UGLIFY) src/jio.storage/erp5storage.js >$(TMPDIR)/jio/storage/erp5storage.min.js 2>/dev/null
@$(UGLIFY) src/jio.storage/indexstorage.js >$(TMPDIR)/jio/storage/indexstorage.min.js 2>/dev/null @$(UGLIFY) src/jio.storage/indexstorage.js >$(TMPDIR)/jio/storage/indexstorage.min.js 2>/dev/null
@$(UGLIFY) src/jio.storage/gidstorage.js >$(TMPDIR)/jio/storage/gidstorage.min.js 2>/dev/null @$(UGLIFY) src/jio.storage/gidstorage.js >$(TMPDIR)/jio/storage/gidstorage.min.js 2>/dev/null
......
...@@ -80,6 +80,23 @@ ...@@ -80,6 +80,23 @@
// } // }
// } // }
// } // }
// });
///////////////////////////
// Dropbox storage
///////////////////////////
// return g.run({
// type: "query",
// sub_storage: {
// type: "uuid",
// sub_storage: {
// type: "drivetojiomapping",
// sub_storage: {
// "type": "dropbox",
// "access_token" : "TOKEN"
// }
// }
// }
// }); // });
/////////////////////////// ///////////////////////////
......
...@@ -7,45 +7,39 @@ ...@@ -7,45 +7,39 @@
* JIO Dropbox Storage. Type = "dropbox". * JIO Dropbox Storage. Type = "dropbox".
* Dropbox "database" storage. * Dropbox "database" storage.
*/ */
/*global FormData, btoa, Blob, define, jIO, RSVP, ProgressEvent */ /*global FormData, btoa, Blob, DOMParser, define, jIO, RSVP, ProgressEvent */
/*js2lint nomen: true, unparam: true, bitwise: true */ /*js2lint nomen: true, unparam: true, bitwise: true */
/*jslint nomen: true, unparam: true*/ /*jslint nomen: true, unparam: true*/
(function (dependencies, module) {
"use strict"; (function (jIO, RSVP, DOMParser, Blob) {
if (typeof define === 'function' && define.amd) {
return define(dependencies, module);
}
module(jIO, RSVP);
}([
'jio',
'rsvp'
], function (jIO, RSVP) {
"use strict"; "use strict";
var UPLOAD_URL = "https://content.dropboxapi.com/1/files_put/",
CREATE_DIR_URL = "https://api.dropboxapi.com/1/fileops/create_folder",
REMOVE_URL = "https://api.dropboxapi.com/1/fileops/delete/",
GET_URL = "https://content.dropboxapi.com/1/files";
//LIST_URL = 'https://api.dropboxapi.com/1/metadata/sandbox/';
/** function restrictDocumentId(id) {
* Checks if an object has no enumerable keys if (id.indexOf("/") !== 0) {
* throw new jIO.util.jIOError("id " + id + " is forbidden (no begin /)",
* @param {Object} obj The object 400);
* @return {Boolean} true if empty, else false
*/
function objectIsEmpty(obj) {
var k;
for (k in obj) {
if (obj.hasOwnProperty(k)) {
return false;
} }
if (id.lastIndexOf("/") !== (id.length - 1)) {
throw new jIO.util.jIOError("id " + id + " is forbidden (no end /)",
400);
} }
return true; return id;
} }
var UPLOAD_URL = "https://api-content.dropbox.com/1/", function restrictAttachmentId(id) {
// UPLOAD_OR_GET_URL = "https://api-content.dropbox.com/1/files/sandbox/", if (id.indexOf("/") !== -1) {
// REMOVE_URL = "https://api.dropbox.com/1/fileops/delete/", throw new jIO.util.jIOError("attachment " + id + " is forbidden",
// LIST_URL = 'https://api.dropbox.com/1/metadata/sandbox/', 400);
METADATA_FOLDER = 'metadata'; }
}
/** /**
* The JIO DropboxStorage extension * The JIO Dropbox Storage extension
* *
* @class DropboxStorage * @class DropboxStorage
* @constructor * @constructor
...@@ -55,645 +49,219 @@ ...@@ -55,645 +49,219 @@
throw new TypeError("Access Token' must be a string " + throw new TypeError("Access Token' must be a string " +
"which contains more than one character."); "which contains more than one character.");
} }
if (typeof spec.application_name !== 'string' && spec.application_name) {
throw new TypeError("'Root Folder' must be a string ");
}
if (!spec.application_name) {
spec.application_name = "default";
}
this._access_token = spec.access_token; this._access_token = spec.access_token;
this._application_name = spec.application_name; this._root = "dropbox";
} }
// Storage specific put method DropboxStorage.prototype.put = function (id, param) {
DropboxStorage.prototype._put = function (key, blob, path) { var that = this;
var data = new FormData(); id = restrictDocumentId(id);
if (path === undefined) { if (Object.getOwnPropertyNames(param).length > 0) {
path = ''; // Reject if param has some properties
throw new jIO.util.jIOError("Can not store properties: " +
Object.getOwnPropertyNames(param), 400);
} }
data.append( return new RSVP.Queue()
"file", .push(function () {
blob,
key
);
return jIO.util.ajax({ return jIO.util.ajax({
"type": "POST", "type": "POST",
"url": UPLOAD_URL + 'files/sandbox/' + "url": CREATE_DIR_URL +
this._application_name + '/' + '?access_token=' + that._access_token +
path + '?access_token=' + this._access_token, '&root=' + that._root + '&path=' + id
"data": data
}); });
};
/**
* Create a document.
*
* @method post
* @param {Object} command The JIO command
* @param {Object} metadata The metadata to store
*/
DropboxStorage.prototype.post = function (command, metadata) {
// A copy of the document is made
var doc = jIO.util.deepClone(metadata), doc_id = metadata._id,
that = this;
// An id is generated if none is provided
if (!doc_id) {
doc_id = jIO.util.generateUuid();
doc._id = doc_id;
}
// 1. get Document, if it exists abort
function getDocument() {
return that._get(METADATA_FOLDER + "/" + metadata._id)
.then(function () {
command.error(
409,
"document exists",
"Cannot create a new document"
);
throw 1;
}) })
.fail(function (event) { .push(undefined, function (err) {
if (event instanceof ProgressEvent) { if ((err.target !== undefined) &&
// If the document do not exist no problem (err.target.status === 405)) {
if (event.target.status === 404) { return;
return 0;
}
}
throw event;
});
}
// 2. Update Document
function updateDocument() {
return that._put(
doc._id,
new Blob([JSON.stringify(doc)], {
type: "application/json"
}),
METADATA_FOLDER
);
}
// onError
function onError(event) {
if (event instanceof ProgressEvent) {
command.error(
event.target.status,
event.target.statusText,
"Unable to post doc"
);
} else {
if (event !== 1) {
throw event;
}
}
} }
throw err;
// The document is pushed
return getDocument()
.then(updateDocument)
.then(function () {
command.success({
"id": doc_id
}); });
})
.fail(onError);
}; };
/** DropboxStorage.prototype.remove = function (id) {
* Update/create a document. var that = this;
* id = restrictDocumentId(id);
* @method put return new RSVP.Queue()
* @param {Object} command The JIO command .push(function () {
* @param {Object} metadata The metadata to store return that.get(id);
*/
DropboxStorage.prototype.put = function (command, metadata) {
// We put the document
var that = this,
old_document = {};
// 1. We first get the document
function getDocument() {
return that._get(METADATA_FOLDER + '/' + metadata._id)
.then(function (answer) {
old_document = JSON.parse(answer.target.responseText);
}) })
.fail(function (event) { .push(function () {
if (event instanceof ProgressEvent) { return jIO.util.ajax({
// If the document do not exist no problem "type": "POST",
if (event.target.status === 404) { "url": REMOVE_URL +
return 0; '?access_token=' + that._access_token +
} '&root=' + that._root + '&path=' + id
}
throw event;
}); });
} });
};
// 2. Update Document
function updateDocument() {
if (old_document.hasOwnProperty('_attachments')) {
metadata._attachments = old_document._attachments;
}
return that._put(
metadata._id,
new Blob([JSON.stringify(metadata)], {
type: "application/json"
}),
METADATA_FOLDER
);
}
// onError DropboxStorage.prototype.get = function (id) {
function onError(event) { var that = this,
if (event instanceof ProgressEvent) { obj;
command.error( if (id === "/") {
event.target.status, return {};
event.target.statusText,
"Unable to put doc"
);
} else {
if (event !== 1) {
throw event;
}
}
} }
id = restrictDocumentId(id);
return getDocument() return new RSVP.Queue()
.then(updateDocument) .push(function () {
.then(function () {
command.success();
// XXX should use command.success("created") when the document is created
})
.fail(onError);
};
// Storage specific get method
DropboxStorage.prototype._get = function (key) {
var download_url = 'https://api-content.dropbox.com/1/files/sandbox/' +
this._application_name + '/' +
key + '?access_token=' + this._access_token;
return jIO.util.ajax({ return jIO.util.ajax({
"type": "GET", "type": "GET",
"url": download_url "url": "https://api.dropboxapi.com/1/metadata/" +
that._root + "/" + id +
'?access_token=' + that._access_token
}); });
}; })
.push(function (xml) {
/** obj = JSON.parse(xml.target.response || xml.target.responseText);
* Get a document or attachment if (obj.is_dir === true) {
* @method get return {};
* @param {object} command The JIO command }
**/ throw new jIO.util.jIOError("cannot load" + id +
DropboxStorage.prototype.get = function (command, param) { ". Invalid HTTP", 404);
return this._get(METADATA_FOLDER + '/' + param._id) }, function (error) {
.then(function (event) { if (error !== undefined && error.target.status === 404) {
if (event.target.responseText !== undefined) { throw new jIO.util.jIOError("Cannot find document", 404);
command.success({ }
"data": JSON.parse(event.target.responseText) throw error;
});
} else {
command.error(
event.target.status,
event.target.statusText,
"Cannot find document"
);
}
}).fail(function (event) {
if (event instanceof ProgressEvent) {
command.error(
event.target.status,
event.target.statusText,
"Cannot find document"
);
} else {
command.error(event);
}
}); });
}; };
/** DropboxStorage.prototype.allAttachments = function (id) {
* Get an attachment
*
* @method getAttachment
* @param {Object} command The JIO command
* @param {Object} param The given parameters
* @param {Object} options The command options
*/
DropboxStorage.prototype.getAttachment = function (command, param) {
var that = this, document = {};
// 1. We first get the document
function getDocument() {
return that._get(METADATA_FOLDER + '/' + param._id)
.then(function (answer) {
document = JSON.parse(answer.target.responseText);
// We check the attachment is referenced var that = this,
if (document.hasOwnProperty('_attachments')) { i,
if (document._attachments.hasOwnProperty(param._attachment)) { title,
return; ret,
} obj;
}
command.error(
404,
"Not Found",
"Cannot find attachment"
);
throw 1;
})
.fail(function (event) {
if (event instanceof ProgressEvent) {
// If the document do not exist it fails
if (event.target.status === 404) {
command.error({
'status': 404,
'message': 'Unable to get attachment',
'reason': 'Missing document'
});
} else {
command.error(
event.target.status,
event.target.statusText,
"Problem while retrieving document"
);
}
throw 1;
}
throw event;
});
}
// 2. We get the Attachment id = restrictDocumentId(id);
function getAttachment() {
return that._get(param._id + "-" + param._attachment);
}
// 3. On success give attachment return new RSVP.Queue()
function onSuccess(event) { .push(function () {
var attachment_blob = new Blob([event.target.response]); return jIO.util.ajax({
command.success( "type": "GET",
event.target.status, "url": "https://api.dropboxapi.com/1/metadata/" +
{ that._root + "/" + id +
"data": attachment_blob, '?access_token=' + that._access_token
// XXX make the hash during the putAttachment and store it into the });
// metadata file. })
"digest": document._attachments[param._attachment].digest .push(function (xml) {
obj = JSON.parse(xml.target.response || xml.target.responseText);
if (obj.is_dir === false) {
throw new jIO.util.jIOError("cannot load" + id +
". Invalid HTTP", 404);
} }
); ret = {};
for (i = 0; i < obj.contents.length; i += 1) {
if (obj.contents[i].is_dir !== true) {
title = obj.contents[i].path.split("/").pop();
ret[title] = {};
} }
// 4. onError
function onError(event) {
if (event instanceof ProgressEvent) {
command.error(
event.target.status,
event.target.statusText,
"Cannot find attachment"
);
} else {
if (event !== 1) {
throw event;
} }
return ret;
}, function (error) {
if (error !== undefined && error.target.status === 404) {
throw new jIO.util.jIOError("Cannot find document", 404);
} }
} throw error;
});
return getDocument()
.then(getAttachment)
.then(onSuccess)
.fail(onError);
}; };
/** DropboxStorage.prototype.putAttachment = function (id, name, blob) {
* Add an attachment to a document var that = this;
*
* @method putAttachment
* @param {Object} command The JIO command
* @param {Object} param The given parameters
* @param {Object} options The command options
*/
DropboxStorage.prototype.putAttachment = function (command, param) {
var that = this, document = {}, digest;
// We calculate the digest string of the attachment
digest = jIO.util.makeBinaryStringDigest(param._blob);
// 1. We first get the document id = restrictDocumentId(id);
function getDocument() { restrictAttachmentId(name);
return that._get(METADATA_FOLDER + '/' + param._id)
.then(function (answer) { return new RSVP.Queue()
document = JSON.parse(answer.target.responseText); .push(function () {
return that.get(id);
})
.push(undefined, function (error) {
throw new jIO.util.jIOError("Cannot access subdocument", 404);
})
.push(function () {
return that.get(id + name + '/');
}) })
.fail(function (event) { .push(function () {
if (event instanceof ProgressEvent) { throw new jIO.util.jIOError("Cannot overwrite directory", 404);
// If the document do not exist it fails }, function (error) {
if (event.target.status === 404) { if ((error instanceof jIO.util.jIOError) &&
command.error({ ((error.message === "cannot load" + id + name + '/. Invalid HTTP')
'status': 404, || (error.message === "Cannot find document"))) {
'message': 'Impossible to add attachment', return jIO.util.ajax({
'reason': 'Missing document' "type": "PUT",
"url": UPLOAD_URL + that._root + id + name +
'?access_token=' + that._access_token,
dataType: blob.type,
data: blob
}); });
} else {
command.error(
event.target.status,
event.target.statusText,
"Problem while retrieving document"
);
}
throw 1;
} }
throw event; throw error;
}); });
}
// 2. We push the attachment
function pushAttachment() {
return that._put(
param._id + '-' + param._attachment,
param._blob
);
}
// 3. We update the document
function updateDocument() {
if (document._attachments === undefined) {
document._attachments = {};
}
document._attachments[param._attachment] = {
"content_type": param._blob.type,
"digest": digest,
"length": param._blob.size
}; };
return that._put(
param._id,
new Blob([JSON.stringify(document)], {
type: "application/json"
}),
METADATA_FOLDER
);
}
// 4. onSuccess DropboxStorage.prototype.getAttachment = function (id, name) {
function onSuccess() { var that = this;
command.success({
'digest': digest,
'status': 201,
'statusText': 'Created'
// XXX are you sure this the attachment is created?
});
}
// 5. onError id = restrictDocumentId(id);
function onError(event) { restrictAttachmentId(name);
if (event instanceof ProgressEvent) {
command.error(
event.target.status,
event.target.statusText,
"Unable to put attachment"
);
} else {
if (event !== 1) {
throw event;
}
}
}
return getDocument() return new RSVP.Queue()
.then(pushAttachment) .push(function () {
.then(updateDocument) return jIO.util.ajax({
.then(onSuccess)
.fail(onError);
};
/**
* Get all filenames belonging to a user from the document index
*
* @method allDocs
* @param {Object} command The JIO command
* @param {Object} param The given parameters
* @param {Object} options The command options
*/
DropboxStorage.prototype.allDocs = function (command, param, options) {
var list_url = '', result = [], my_storage = this,
stripping_length = 3 + my_storage._application_name.length +
METADATA_FOLDER.length;
// Too specific, should be less storage dependent
list_url = 'https://api.dropbox.com/1/metadata/sandbox/' +
this._application_name + '/' + METADATA_FOLDER + '/' +
"?list=true" +
'&access_token=' + this._access_token;
// We get a list of all documents
jIO.util.ajax({
"type": "GET", "type": "GET",
"url": list_url "url": GET_URL + "/" + that._root + "/" + id + name +
}).then(function (response) { '?access_token=' + that._access_token
var i, item, item_id, data, count, promise_list = [];
data = JSON.parse(response.target.responseText);
count = data.contents.length;
// We loop aver all documents
for (i = 0; i < count; i += 1) {
item = data.contents[i];
// If the element is a folder it is not included (storage specific)
if (!item.is_dir) {
// NOTE: the '/' at the begining of the path is stripped
item_id = item.path.substr(stripping_length);
// item.path[0] === '/' ? : item.path
// Prepare promise_list to fetch document in case of include_docs
if (options.include_docs === true) {
promise_list.push(my_storage._get(METADATA_FOLDER + '/' + item_id));
}
// Document is added to the result list
result.push({
id: item_id,
value: {}
});
}
}
// NOTE: if promise_list is empty, success is triggered directly
// else it fetch all documents and add them to the result
return RSVP.all(promise_list);
}).then(function (response_list) {
var i, response_length;
response_length = response_list.length;
for (i = 0; i < response_length; i += 1) {
result[i].doc = JSON.parse(response_list[i].target.response);
}
command.success({
"data": {
"rows": result,
"total_rows": result.length
}
}); });
}).fail(function (error) { })
if (error instanceof ProgressEvent) { .push(function (response) {
command.error( return new Blob(
"error", [response.target.response || response.target.responseText],
"did not work as expected", {"type": response.target.getResponseHeader('Content-Type') ||
"Unable to call allDocs" "application/octet-stream"}
); );
}, function (error) {
if (error !== undefined && error.target.status === 404) {
throw new jIO.util.jIOError("Cannot find attachment: " +
id + ", " + name, 404);
} }
throw error;
}); });
}; };
// Storage specific remove method DropboxStorage.prototype.removeAttachment = function (id, name) {
DropboxStorage.prototype._remove = function (key, path) { var that = this;
var DELETE_HOST, DELETE_PREFIX, DELETE_PARAMETERS, delete_url;
DELETE_HOST = "https://api.dropbox.com/1"; id = restrictDocumentId(id);
DELETE_PREFIX = "/fileops/delete/"; restrictAttachmentId(name);
if (path === undefined) { return new RSVP.Queue()
path = ''; .push(function () {
} return that.get(id + name + '/');
DELETE_PARAMETERS = "?root=sandbox&path=" + })
this._application_name + '/' + .push(function () {
path + '/' + key + "&access_token=" + this._access_token; throw new jIO.util.jIOError("Cannot remove directory", 404);
delete_url = DELETE_HOST + DELETE_PREFIX + DELETE_PARAMETERS; }, function (error) {
if (error instanceof jIO.util.jIOError &&
error.message === "Cannot find document") {
throw new jIO.util.jIOError("Cannot find attachment: " +
id + ", " + name, 404);
}
if (error instanceof jIO.util.jIOError &&
error.message === "cannot load" + id + name + '/. Invalid HTTP') {
return jIO.util.ajax({ return jIO.util.ajax({
"type": "POST", "type": "POST",
"url": delete_url "url": REMOVE_URL +
}); '?access_token=' + that._access_token +
}; '&root=' + that._root + '&path=' + id + name
/**
* Remove a document
*
* @method remove
* @param {Object} command The JIO command
* @param {Object} param The given parameters
*/
DropboxStorage.prototype.remove = function (command, param) {
var that = this, document = {};
// 1. get document
function getDocument() {
return that._get(METADATA_FOLDER + '/' + param._id)
.then(function (answer) {
document = JSON.parse(answer.target.responseText);
});
}
// 2 Remove Document
function removeDocument() {
return that._remove(METADATA_FOLDER + '/' + param._id);
}
// 3 Remove its attachments
function removeAttachments() {
var promise_list = [], attachment_list = [], attachment_count = 0, i = 0;
if (document.hasOwnProperty('_attachments')) {
attachment_list = Object.keys(document._attachments);
attachment_count = attachment_list.length;
}
for (i = 0; i < attachment_count; i += 1) {
promise_list.push(that._remove(param._id + '-' + attachment_list[i]));
}
return RSVP.all(promise_list)
// Even if it fails it is ok (no attachments)
.fail(function (event_list) {
var event_length = event_list.length, j = 0;
for (j = 0; j < event_length; j += 1) {
// If not a ProgressEvent, there is something wrong with the code.
if (!event_list[j] instanceof ProgressEvent) {
throw event_list[j];
}
}
}); });
} }
throw error;
// 4 Notify Success
function onSuccess(event) {
if (event instanceof ProgressEvent) {
command.success(
event.target.status,
event.target.statusText
);
} else {
command.success(200, "OK");
}
}
// 5 Notify Error
function onError(event) {
if (event instanceof ProgressEvent) {
if (event.target.status === 404) {
command.error(
event.target.status,
event.target.statusText,
"Document not found"
);
} else {
command.error(
event.target.status,
event.target.statusText,
"Unable to delete document"
);
}
}
}
// Remove the document
return getDocument()
.then(removeDocument)
.then(removeAttachments)
.then(onSuccess)
.fail(onError);
};
/**
* Remove a document Attachment
*
* @method remove
* @param {Object} command The JIO command
* @param {Object} param The given parameters
*/
DropboxStorage.prototype.removeAttachment = function (command, param) {
var that = this, document = {};
// Remove an attachment
// Then it should be tested
return this._get(METADATA_FOLDER + '/' + param._id)
.then(function (answer) {
document = JSON.parse(answer.target.responseText);
})
.then(function () {
return that._remove(param._id + '-' + param._attachment);
})
.then(function (event) {
delete document._attachments[param._attachment];
if (objectIsEmpty(document._attachments)) {
delete document._attachments;
}
return that._put(
param._id,
new Blob([JSON.stringify(document)], {
type: "application/json"
}),
METADATA_FOLDER
);
})
.then(function (event) {
command.success(
event.target.status,
event.target.statusText,
"Removed attachment"
);
})
.fail(function (error) {
if (error.target.status === 404) {
command.error(
error.target.status,
"missing attachment",
"Attachment not found"
);
}
command.error(
"not_found",
"missing",
"Unable to delete document Attachment"
);
}); });
}; };
jIO.addStorage('dropbox', DropboxStorage); jIO.addStorage('dropbox', DropboxStorage);
}));
}(jIO, RSVP, DOMParser, Blob));
\ No newline at end of file
/*jslint indent: 2, maxlen: 200, nomen: true, unparam: true */ /*jslint nomen: true */
/*global window, define, module, test_util, RSVP, jIO, local_storage, test, ok, /*global Blob, sinon*/
deepEqual, sinon, expect, stop, start, Blob */ (function (jIO, QUnit, Blob, sinon) {
(function (jIO, QUnit) {
"use strict"; "use strict";
// var test = QUnit.test, var test = QUnit.test,
// stop = QUnit.stop, stop = QUnit.stop,
// start = QUnit.start, start = QUnit.start,
// ok = QUnit.ok, ok = QUnit.ok,
// expect = QUnit.expect, expect = QUnit.expect,
// deepEqual = QUnit.deepEqual, deepEqual = QUnit.deepEqual,
// equal = QUnit.equal, equal = QUnit.equal,
var module = QUnit.module; module = QUnit.module,
// throws = QUnit.throws; token = "sample_token";
module("DropboxStorage"); /////////////////////////////////////////////////////////////////
// DropboxStorage constructor
/////////////////////////////////////////////////////////////////
// /** module("DropboxStorage.constructor");
// * all(promises): Promise
// * test("create storage", function () {
// * Produces a promise that is resolved when all the given promises are var jio = jIO.createJIO({
// * fulfilled. The resolved value is an array of each of the answers of the type: "dropbox",
// * given promises. access_token: token
// * });
// * @param {Array} promises The promises to use equal(jio.__type, "dropbox");
// * @return {Promise} A new promise deepEqual(jio.__storage._access_token, token);
// */ });
// function all(promises) {
// var results = [], i, count = 0; /////////////////////////////////////////////////////////////////
// // DropboxStorage.put
// function cancel() { /////////////////////////////////////////////////////////////////
// var j; module("DropboxStorage.put", {
// for (j = 0; j < promises.length; j += 1) { setup: function () {
// if (typeof promises[j].cancel === 'function') {
// promises[j].cancel(); this.server = sinon.fakeServer.create();
// } this.server.autoRespond = true;
// } this.server.autoRespondAfter = 5;
// }
// return new RSVP.Promise(function (resolve, reject, notify) { this.jio = jIO.createJIO({
// /*jslint unparam: true */ type: "dropbox",
// function succeed(j) { access_token: token
// return function (answer) { });
// results[j] = answer; },
// count += 1; teardown: function () {
// if (count !== promises.length) { this.server.restore();
// return; delete this.server;
// } }
// resolve(results); });
// };
// } test("put document", function () {
// var url = "https://api.dropboxapi.com/1/fileops/" +
// function notified(j) { "create_folder?access_token="
// return function (answer) { + token + "&root=dropbox&path=/put1/",
// notify({ server = this.server;
// "promise": promises[j], this.server.respondWith("POST", url, [201, {
// "index": j, "Content-Type": "text/xml"
// "notified": answer }, ""]);
// });
// }; stop();
// } expect(7);
// for (i = 0; i < promises.length; i += 1) {
// promises[i].then(succeed(i), succeed(i), notified(i)); this.jio.put("/put1/", {})
// } .then(function () {
// }, cancel); equal(server.requests.length, 1);
// } equal(server.requests[0].method, "POST");
// equal(server.requests[0].url, url);
// test("Post & Get", function () { equal(server.requests[0].status, 201);
// expect(6); equal(server.requests[0].requestBody, undefined);
// var jio = jIO.createJIO({ equal(server.requests[0].responseText, "");
// "type": "dropbox", deepEqual(server.requests[0].requestHeaders, {
// "access_token": "v43SQLCEoi8AAAAAAAAAAVixCoMfDelgGj3NRPfE" + "Content-Type": "text/plain;charset=utf-8"
// "nqscAuNGp2LhoS8-GiAaDD4C" });
// }, { })
// "workspace": {} .fail(function (error) {
// }); ok(false, error);
// })
// stop(); .always(function () {
// all([ start();
// });
// // get inexistent document });
// jio.get({
// "_id": "inexistent" test("don't throw error when putting existing directory", function () {
// }).always(function (answer) { var url = "https://api.dropboxapi.com/1/fileops/create_folder" +
// "?access_token=" + token + "&root=dropbox&path=/existing/",
// deepEqual(answer, { server = this.server;
// "error": "not_found", this.server.respondWith("POST", url, [405, {
// "id": "inexistent", "Content-Type": "text/xml"
// "message": "Cannot find document", }, "POST" + url + "(Forbidden)"]);
// "method": "get", stop();
// "reason": "Not Found", expect(1);
// "result": "error", this.jio.put("/existing/", {})
// "status": 404, .then(function () {
// "statusText": "Not Found" equal(server.requests[0].status, 405);
// }, "Get inexistent document"); })
// .fail(function (error) {
// }), ok(false, error);
// })
// // post without id .always(function () {
// jio.post({}) start();
// .then(function (answer) { });
// var id = answer.id; });
// delete answer.id;
// deepEqual(answer, { test("reject ID not starting with /", function () {
// "method": "post", stop();
// "result": "success", expect(3);
// "status": 201,
// "statusText": "Created" this.jio.put("put1/", {})
// }, "Post without id"); .fail(function (error) {
// ok(error instanceof jIO.util.jIOError);
// // We check directly on the document to get its own id equal(error.message, "id put1/ is forbidden (no begin /)");
// return jio.get({'_id': id}); equal(error.status_code, 400);
// }).always(function (answer) { })
// .fail(function (error) {
// var uuid = answer.data._id; ok(false, error);
// ok(util.isUuid(uuid), "Uuid should look like " + })
// "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx : " + uuid); .always(function () {
// start();
// }).then(function () { });
// return jio.remove({"_id": "post1"}) });
// }).always(function () {
// return jio.post({ test("reject ID not ending with /", function () {
// "_id": "post1", stop();
// "title": "myPost1" expect(3);
// });
// this.jio.put("/put1", {})
// }).always(function (answer) { .fail(function (error) {
// ok(error instanceof jIO.util.jIOError);
// deepEqual(answer, { equal(error.message, "id /put1 is forbidden (no end /)");
// "id": "post1", equal(error.status_code, 400);
// "method": "post", })
// "result": "success", .fail(function (error) {
// "status": 201, ok(false, error);
// "statusText": "Created" })
// }, "Post"); .always(function () {
// start();
// }).then(function () { });
// });
// return jio.get({
// "_id": "post1" test("reject to store any property", function () {
// }); stop();
// expect(3);
// }).always(function (answer) {
// this.jio.put("/put1/", {title: "foo"})
// deepEqual(answer, { .fail(function (error) {
// "data": { ok(error instanceof jIO.util.jIOError);
// "_id": "post1", equal(error.message, "Can not store properties: title");
// "title": "myPost1" equal(error.status_code, 400);
// }, })
// "id": "post1", .fail(function (error) {
// "method": "get", ok(false, error);
// "result": "success", })
// "status": 200, .always(function () {
// "statusText": "Ok" start();
// }, "Get, Check document"); });
// }).then(function () { });
//
// // post but document already exists /////////////////////////////////////////////////////////////////
// return jio.post({"_id": "post1", "title": "myPost2"}); // DropboxStorage.remove
// /////////////////////////////////////////////////////////////////
// }).always(function (answer) { module("DropboxStorage.remove", {
// setup: function () {
// deepEqual(answer, {
// "error": "conflict", this.server = sinon.fakeServer.create();
// "id": "post1", this.server.autoRespond = true;
// "message": "Cannot create a new document", this.server.autoRespondAfter = 5;
// "method": "post",
// "reason": "document exists", this.jio = jIO.createJIO({
// "result": "error", type: "dropbox",
// "status": 409, access_token: token
// "statusText": "Conflict" });
// }, "Post but document already exists"); },
// teardown: function () {
// }) this.server.restore();
// delete this.server;
// ]).always(start); }
// });
// });
// test("remove document", function () {
// test("Put & Get", function () { var url_get = "https://api.dropboxapi.com/1/metadata/dropbox" +
// expect(4); "//remove1/?access_token=" + token,
// var jio = jIO.createJIO({ url_delete = "https://api.dropboxapi.com/1/fileops/delete/?" +
// "type": "dropbox", "access_token=" + token + "&root=dropbox&path=/remove1/",
// "access_token": "v43SQLCEoi8AAAAAAAAAAVixCoMfDelgGj3NRPfE" + server = this.server;
// "nqscAuNGp2LhoS8-GiAaDD4C" this.server.respondWith("GET", url_get, [204, {
// }, { "Content-Type": "text/xml"
// "workspace": {} }, '{"is_dir": true}']);
// }); this.server.respondWith("POST", url_delete, [204, {
// "Content-Type": "text/xml"
// stop(); }, '']);
// stop();
// // put non empty document expect(13);
// jio.put({
// "_id": "put1", this.jio.remove("/remove1/")
// "title": "myPut1" .then(function () {
// }).always(function (answer) { equal(server.requests.length, 2);
// equal(server.requests[0].method, "GET");
// deepEqual(answer, { equal(server.requests[0].url, url_get);
// "id": "put1", equal(server.requests[0].status, 204);
// "method": "put", equal(server.requests[0].requestBody, undefined);
// "result": "success", equal(server.requests[0].responseText, '{"is_dir": true}');
// "status": 204, deepEqual(server.requests[0].requestHeaders, {});
// "statusText": "No Content" equal(server.requests[1].method, "POST");
// }, "Creates a document"); equal(server.requests[1].url, url_delete);
// equal(server.requests[1].status, 204);
// }).then(function () { equal(server.requests[1].requestBody, undefined);
// equal(server.requests[1].responseText, '');
// return jio.get({ deepEqual(server.requests[1].requestHeaders, {
// "_id": "put1" "Content-Type": "text/plain;charset=utf-8"
// }); });
// })
// }).always(function (answer) { .fail(function (error) {
// ok(false, error);
// deepEqual(answer, { })
// "data": { .always(function () {
// "_id": "put1", start();
// "title": "myPut1" });
// }, });
// "id": "put1",
// "method": "get", test("reject ID not starting with /", function () {
// "result": "success", stop();
// "status": 200, expect(3);
// "statusText": "Ok"
// }, "Get, Check document"); this.jio.remove("remove1/")
// .fail(function (error) {
// }).then(function () { ok(error instanceof jIO.util.jIOError);
// equal(error.message, "id remove1/ is forbidden (no begin /)");
// // put but document already exists equal(error.status_code, 400);
// return jio.put({ })
// "_id": "put1", .fail(function (error) {
// "title": "myPut2" ok(false, error);
// }); })
// .always(function () {
// }).always(function (answer) { start();
// });
// deepEqual(answer, { });
// "id": "put1",
// "method": "put", test("reject ID not ending with /", function () {
// "result": "success", stop();
// "status": 204, expect(3);
// "statusText": "No Content"
// }, "Update the document"); this.jio.remove("/remove1")
// .fail(function (error) {
// }).then(function () { ok(error instanceof jIO.util.jIOError);
// equal(error.message, "id /remove1 is forbidden (no end /)");
// return jio.get({ equal(error.status_code, 400);
// "_id": "put1" })
// }); .fail(function (error) {
// ok(false, error);
// }).always(function (answer) { })
// .always(function () {
// deepEqual(answer, { start();
// "data": { });
// "_id": "put1", });
// "title": "myPut2"
// }, /////////////////////////////////////////////////////////////////
// "id": "put1", // DropboxStorage.get
// "method": "get", /////////////////////////////////////////////////////////////////
// "result": "success", module("DropboxStorage.get", {
// "status": 200, setup: function () {
// "statusText": "Ok"
// }, "Get, Check document"); this.server = sinon.fakeServer.create();
// this.server.autoRespond = true;
// }).always(start); this.server.autoRespondAfter = 5;
//
// }); this.jio = jIO.createJIO({
// type: "dropbox",
// test("PutAttachment & Get & GetAttachment", function () { access_token: token
// expect(10); });
// var jio = jIO.createJIO({ },
// "type": "dropbox", teardown: function () {
// "access_token": "v43SQLCEoi8AAAAAAAAAAVixCoMfDelgGj3NRPfE" + this.server.restore();
// "nqscAuNGp2LhoS8-GiAaDD4C" delete this.server;
// }, { }
// "workspace": {} });
// });
// test("reject ID not starting with /", function () {
// stop(); stop();
// expect(3);
// all([
// this.jio.get("get1/")
// // get an attachment from an inexistent document .fail(function (error) {
// jio.getAttachment({ ok(error instanceof jIO.util.jIOError);
// "_id": "inexistent", equal(error.message, "id get1/ is forbidden (no begin /)");
// "_attachment": "a" equal(error.status_code, 400);
// }).always(function (answer) { })
// .fail(function (error) {
// deepEqual(answer, { ok(false, error);
// "attachment": "a", })
// "error": "not_found", .always(function () {
// "id": "inexistent", start();
// "message": "Unable to get attachment", });
// "method": "getAttachment", });
// "reason": "Missing document",
// "result": "error", test("reject ID not ending with /", function () {
// "status": 404, stop();
// "statusText": "Not Found" expect(3);
// }, "GetAttachment from inexistent document");
// this.jio.get("/get1")
// }), .fail(function (error) {
// ok(error instanceof jIO.util.jIOError);
// // put a document then get an attachment from the empty document equal(error.message, "id /get1 is forbidden (no end /)");
// jio.put({ equal(error.status_code, 400);
// "_id": "b" })
// }).then(function () { .fail(function (error) {
// return jio.getAttachment({ ok(false, error);
// "_id": "b", })
// "_attachment": "inexistent" .always(function () {
// }); start();
// });
// }).always(function (answer) { });
//
// deepEqual(answer, { test("get inexistent document", function () {
// "attachment": "inexistent", var url_get = "https://api.dropboxapi.com/1/metadata/dropbox" +
// "error": "not_found", "//inexistent/?access_token=" + token;
// "id": "b", this.server.respondWith("GET", url_get, [404, {
// "message": "Cannot find attachment", "Content-Type": "text/xml"
// "method": "getAttachment", }, '']);
// "reason": "Not Found", stop();
// "result": "error", expect(3);
// "status": 404,
// "statusText": "Not Found" this.jio.get("/inexistent/")
// }, "Get inexistent attachment"); .fail(function (error) {
// ok(error instanceof jIO.util.jIOError);
// }), equal(error.message, "Cannot find document");
// equal(error.status_code, 404);
// // put an attachment to an inexistent document })
// jio.putAttachment({ .fail(function (error) {
// "_id": "inexistent", ok(false, error);
// "_attachment": "putattmt2", })
// "_data": "" .always(function () {
// }).always(function (answer) { start();
// });
// deepEqual(answer, { });
// "attachment": "putattmt2",
// "error": "not_found", test("get document", function () {
// "id": "inexistent", var url = "https://api.dropboxapi.com/1/metadata/dropbox" +
// "message": "Impossible to add attachment", "//id1/?access_token=" + token;
// "method": "putAttachment", this.server.respondWith("GET", url, [200, {
// "reason": "Missing document", "Content-Type": "text/xml"
// "result": "error", }, '{"is_dir": true, "contents": []}'
// "status": 404, ]);
// "statusText": "Not Found" stop();
// }, "PutAttachment to inexistent document"); expect(1);
//
// }), this.jio.get("/id1/")
// .then(function (result) {
// // add a document to the storage deepEqual(result, {}, "Check document");
// // don't need to be tested })
// jio.put({ .fail(function (error) {
// "_id": "putattmt1", ok(false, error);
// "title": "myPutAttmt1" })
// }).then(function () { .always(function () {
// start();
// return jio.putAttachment({ });
// "_id": "putattmt1", });
// "_attachment": "putattmt2",
// "_data": "" /////////////////////////////////////////////////////////////////
// }); // DropboxStorage.allAttachments
// /////////////////////////////////////////////////////////////////
// }).always(function (answer) { module("DropboxStorage.allAttachments", {
// setup: function () {
// deepEqual(answer, {
// "attachment": "putattmt2", this.server = sinon.fakeServer.create();
// "digest": "sha256-4ea5c508a6566e76240543f8feb06fd45" + this.server.autoRespond = true;
// "7777be39549c4016436afda65d2330e", this.server.autoRespondAfter = 5;
// "id": "putattmt1",
// "method": "putAttachment", this.jio = jIO.createJIO({
// "result": "success", type: "dropbox",
// "status": 201, access_token: token
// "statusText": "Created" });
// }, "PutAttachment to a document, without data"); },
// teardown: function () {
// }).then(function () { this.server.restore();
// delete this.server;
// // check document and attachment }
// return all([ });
// jio.get({
// "_id": "putattmt1" test("reject ID not starting with /", function () {
// }), stop();
// jio.getAttachment({ expect(3);
// "_id": "putattmt1",
// "_attachment": "putattmt2" this.jio.allAttachments("get1/")
// }) .fail(function (error) {
// ]); ok(error instanceof jIO.util.jIOError);
// equal(error.message, "id get1/ is forbidden (no begin /)");
// // XXX check attachment with a getAttachment equal(error.status_code, 400);
// })
// }).always(function (answers) { .fail(function (error) {
// ok(false, error);
// deepEqual(answers[0], { })
// "data": { .always(function () {
// "_attachments": { start();
// "putattmt2": { });
// "content_type": "", });
// "digest": "sha256-4ea5c508a6566e76240543f8feb06fd45" +
// "7777be39549c4016436afda65d2330e", test("reject ID not ending with /", function () {
// "length": 0 stop();
// } expect(3);
// },
// "_id": "putattmt1", this.jio.allAttachments("/get1")
// "title": "myPutAttmt1" .fail(function (error) {
// }, ok(error instanceof jIO.util.jIOError);
// "id": "putattmt1", equal(error.message, "id /get1 is forbidden (no end /)");
// "method": "get", equal(error.status_code, 400);
// "result": "success", })
// "status": 200, .fail(function (error) {
// "statusText": "Ok" ok(false, error);
// }, "Get, Check document"); })
// ok(answers[1].data instanceof Blob, "Data is Blob"); .always(function () {
// deepEqual(answers[1].data.type, "", "Check mimetype"); start();
// deepEqual(answers[1].data.size, 0, "Check size"); });
// });
// delete answers[1].data;
// deepEqual(answers[1], { test("get inexistent document", function () {
// "attachment": "putattmt2", var url = "/inexistent/";
// "id": "putattmt1", this.server.respondWith("PROPFIND", url, [404, {
// "digest": "sha256-4ea5c508a6566e76240543f8feb06fd45" + "Content-Type": "text/html"
// "7777be39549c4016436afda65d2330e", }, "foo"]);
// "method": "getAttachment",
// "result": "success", stop();
// "status": 200, expect(3);
// "statusText": "Ok"
// }, "Get Attachment, Check Response"); this.jio.allAttachments("/inexistent/")
// .fail(function (error) {
// }) ok(error instanceof jIO.util.jIOError);
// equal(error.message, "Cannot find document");
// ]).then( function () { equal(error.status_code, 404);
// return jio.put({ })
// "_id": "putattmt1", .fail(function (error) {
// "foo": "bar", ok(false, error);
// "title": "myPutAttmt1" })
// }); .always(function () {
// }).then (function () { start();
// return jio.get({ });
// "_id": "putattmt1" });
// });
// }).always(function (answer) { test("get document without attachment", function () {
// var url = "https://api.dropboxapi.com/1/metadata/dropbox" +
// deepEqual(answer, { "//id1/?access_token=" + token;
// "data": { this.server.respondWith("GET", url, [200, {
// "_attachments": { "Content-Type": "text/xml"
// "putattmt2": { }, '{"is_dir": true, "contents": []}'
// "content_type": "", ]);
// "digest": "sha256-4ea5c508a6566e76240543f8feb06fd457777be39549c4016436afda65d2330e", stop();
// "length": 0 expect(1);
// }
// }, this.jio.allAttachments("/id1/")
// "_id": "putattmt1", .then(function (result) {
// "foo": "bar", deepEqual(result, {}, "Check document");
// "title": "myPutAttmt1" })
// }, .fail(function (error) {
// "id": "putattmt1", ok(false, error);
// "method": "get", })
// "result": "success", .always(function () {
// "status": 200, start();
// "statusText": "Ok" });
// }, "Get, Check put kept document attachment"); });
// })
// .always(start); test("get document with attachment", function () {
// var url = "https://api.dropboxapi.com/1/metadata/dropbox" +
// }); "//id1/?access_token=" + token;
// this.server.respondWith("GET", url, [200, {
// test("Remove & RemoveAttachment", function () { "Content-Type": "text/xml"
// expect(5); }, '{"is_dir": true, "path": "/id1", ' +
// var jio = jIO.createJIO({ '"contents": ' +
// "type": "dropbox", '[{"rev": "143bb45509", ' +
// "access_token": "v43SQLCEoi8AAAAAAAAAAVixCoMfDelgGj3NRPfE" + '"thumb_exists": false, ' +
// "nqscAuNGp2LhoS8-GiAaDD4C" '"path": "/id1/attachment1", ' +
// }, { '"is_dir": false, "bytes": 151}, ' +
// "workspace": {} '{"rev": "153bb45509", ' +
// }); '"thumb_exists": false, ' +
// '"path": "/id1/attachment2", ' +
// stop(); '"is_dir": false, "bytes": 11}, ' +
// '{"rev": "173bb45509", ' +
// jio.put({ '"thumb_exists": false, ' +
// "_id": "a" '"path": "/id1/fold1", ' +
// }).then(function () { '"is_dir": true, "bytes": 0}], ' +
// '"icon": "folder"}'
// return jio.putAttachment({ ]);
// "_id": "a", stop();
// "_attachment": "b", expect(1);
// "_data": "c"
// }); this.jio.allAttachments("/id1/")
// .then(function (result) {
// }).then(function () { deepEqual(result, {
// attachment1: {},
// return jio.removeAttachment({ attachment2: {}
// "_id": "a", }, "Check document");
// "_attachment": "b" })
// }); .fail(function (error) {
// ok(false, error);
// }).always(function (answer) { })
// .always(function () {
// deepEqual(answer, { start();
// "attachment": "b", });
// "id": "a", });
// "method": "removeAttachment",
// "result": "success", /////////////////////////////////////////////////////////////////
// "status": 200, // DropboxStorage.putAttachment
// "statusText": "Ok" /////////////////////////////////////////////////////////////////
// }, "Remove existent attachment"); module("DropboxStorage.putAttachment", {
// setup: function () {
// }).then(function () {
// return jio.get({'_id' : "a"}); this.server = sinon.fakeServer.create();
// }).always(function (answer) { this.server.autoRespond = true;
// deepEqual(answer, { this.server.autoRespondAfter = 5;
// "data": {
// "_id": "a", this.jio = jIO.createJIO({
// }, type: "dropbox",
// "id": "a", access_token: token
// "method": "get", });
// "result": "success", },
// "status": 200, teardown: function () {
// "statusText": "Ok" this.server.restore();
// }, "Attachment removed from metadata"); delete this.server;
// }
// }) });
// .then(function () {
// test("reject ID not starting with /", function () {
// // Promise.all always return success stop();
// return all([jio.removeAttachment({ expect(3);
// "_id": "a",
// "_attachment": "b" this.jio.putAttachment(
// })]); "putAttachment1/",
// "attachment1",
// }).always(function (answers) { new Blob([""])
// )
// deepEqual(answers[0], { .fail(function (error) {
// "attachment": "b", ok(error instanceof jIO.util.jIOError);
// "error": "not_found", equal(error.message, "id putAttachment1/ is forbidden (no begin /)");
// "id": "a", equal(error.status_code, 400);
// "message": "Attachment not found", })
// "method": "removeAttachment", .fail(function (error) {
// "reason": "missing attachment", ok(false, error);
// "result": "error", })
// "status": 404, .always(function () {
// "statusText": "Not Found" start();
// }, "Remove removed attachment"); });
// });
// }).then(function () {
// test("reject ID not ending with /", function () {
// return jio.remove({ stop();
// "_id": "a" expect(3);
// });
// this.jio.putAttachment(
// }).always(function (answer) { "/putAttachment1",
// "attachment1",
// deepEqual(answer, { new Blob([""])
// "id": "a", )
// "method": "remove", .fail(function (error) {
// "result": "success", ok(error instanceof jIO.util.jIOError);
// "status": 200, equal(error.message, "id /putAttachment1 is forbidden (no end /)");
// "statusText": "Ok" equal(error.status_code, 400);
// }, "Remove existent document"); })
// .fail(function (error) {
// }).then(function () { ok(false, error);
// })
// return jio.remove({ .always(function () {
// "_id": "a" start();
// }); });
// });
// }).always(function (answer) {
// test("reject attachment with / character", function () {
// deepEqual(answer, { stop();
// "error": "not_found", expect(3);
// "id": "a",
// "message": "Document not found", this.jio.putAttachment(
// "method": "remove", "/putAttachment1/",
// "reason": "Not Found", "attach/ment1",
// "result": "error", new Blob([""])
// "status": 404, )
// "statusText": "Not Found" .fail(function (error) {
// }, "Remove removed document"); ok(error instanceof jIO.util.jIOError);
// equal(error.message, "attachment attach/ment1 is forbidden");
// }).always(start); equal(error.status_code, 400);
// })
// }); .fail(function (error) {
// ok(false, error);
// test("AllDocs", function () { })
// expect(2); .always(function () {
// var shared = {}, jio; start();
// jio = jIO.createJIO({ });
// "type": "dropbox", });
// "access_token": "v43SQLCEoi8AAAAAAAAAAVixCoMfDelgGj3NRPfE" +
// "nqscAuNGp2LhoS8-GiAaDD4C", test("putAttachment to inexisting directory: expecting a 404", function () {
// "application_name": "AllDocs-test" var blob = new Blob(["foo"]),
// }, { url = "/inexistent_dir/attachment1";
// "workspace": {} this.server.respondWith("PUT", url, [405, {"": ""}, ""]);
// }); stop();
// expect(3);
// stop();
// this.jio.putAttachment(
// shared.date_a = new Date(0); "/inexistent_dir/",
// shared.date_b = new Date(); "attachment1",
// blob
// // Clean storage and put some document before listing them )
// all([ .fail(function (error) {
// jio.allDocs() ok(error instanceof jIO.util.jIOError);
// .then(function (document_list) { equal(error.message, "Cannot access subdocument");
// var promise_list = [], i; equal(error.status_code, 404);
// for (i = 0; i < document_list.data.total_rows; i += 1) { })
// promise_list.push( .always(function () {
// jio.remove({ start();
// '_id': document_list.data.rows[i].id });
// }) });
// );
// }
// return RSVP.all(promise_list); test("putAttachment document", function () {
// }) var blob = new Blob(["foo"]),
// ]) url_get_id = "https://api.dropboxapi.com/1/metadata/dropbox" +
// .then(function () { "//putAttachment1/?access_token=" + token,
// return RSVP.all([ url_get_att = "https://api.dropboxapi.com/1/metadata/dropbox" +
// jio.put({ "//putAttachment1/attachment1/?access_token=" + token,
// "_id": "a", url_put_att = "https://content.dropboxapi.com/1/files_put/dropbox/" +
// "title": "one", "putAttachment1/attachment1?access_token=" + token,
// "date": shared.date_a server = this.server;
// }).then(function () {
// return jio.putAttachment({ this.server.respondWith("GET", url_get_id, [204, {
// "_id": "a", "Content-Type": "text/xml"
// "_attachment": "aa", }, '{"is_dir": true, "contents": []}']);
// "_data": "aaa"
// }); this.server.respondWith("GET", url_get_att, [404, {
// }), "Content-Type": "text/xml"
// jio.put({ }, '']);
// "_id": "b",
// "title": "two", this.server.respondWith("PUT", url_put_att, [204, {
// "date": shared.date_a "Content-Type": "text/xml"
// }), }, ""]);
// jio.put({
// "_id": "c", stop();
// "title": "one", expect(17);
// "date": shared.date_b
// }), this.jio.putAttachment(
// jio.put({ "/putAttachment1/",
// "_id": "d", "attachment1",
// "title": "two", blob
// "date": shared.date_b )
// }) .then(function () {
// ]); equal(server.requests.length, 3);
// }).then(function () {
// equal(server.requests[0].method, "GET");
// // get a list of documents equal(server.requests[0].url, url_get_id);
// return jio.allDocs(); equal(server.requests[0].status, 204);
// equal(server.requests[0].responseText,
// }).always(function (answer) { "{\"is_dir\": true, \"contents\": []}");
// deepEqual(server.requests[0].requestHeaders, {});
// // sort answer rows for comparison equal(server.requests[1].method, "GET");
// if (answer.data && answer.data.rows) { equal(server.requests[1].url, url_get_att);
// answer.data.rows.sort(function (a, b) { equal(server.requests[1].status, 404);
// return a.id < b.id ? -1 : a.id > b.id ? 1 : 0; equal(server.requests[1].responseText, "");
// }); deepEqual(server.requests[1].requestHeaders, {});
// }
// equal(server.requests[2].method, "PUT");
// deepEqual(answer, { equal(server.requests[2].url, url_put_att);
// "data": { equal(server.requests[2].status, 204);
// "rows": [{ equal(server.requests[2].responseText, "");
// "id": "a", deepEqual(server.requests[2].requestHeaders, {
// "value": {} "Content-Type": "text/plain;charset=utf-8"
// }, { });
// "id": "b", equal(server.requests[2].requestBody, blob);
// "value": {} })
// }, { .fail(function (error) {
// "id": "c", ok(false, error);
// "value": {} })
// }, { .always(function () {
// "id": "d", start();
// "value": {} });
// }], });
// "total_rows": 4
// }, /////////////////////////////////////////////////////////////////
// "method": "allDocs", // DropboxStorage.removeAttachment
// "result": "success", /////////////////////////////////////////////////////////////////
// "status": 200, module("DropboxStorage.removeAttachment", {
// "statusText": "Ok" setup: function () {
// }, "AllDocs");
// this.server = sinon.fakeServer.create();
// }).then(function () { this.server.autoRespond = true;
// this.server.autoRespondAfter = 5;
// // get a list of documents
// return jio.allDocs({ this.jio = jIO.createJIO({
// "include_docs": true type: "dropbox",
// }); access_token: token
// });
// }).always(function (answer) { },
// teardown: function () {
// deepEqual(answer, { this.server.restore();
// "data": { delete this.server;
// "rows": [{ }
// "doc": { });
// "_attachments": {
// "aa": { test("reject ID not starting with /", function () {
// "content_type": "", stop();
// "digest": "sha256-4ea5c508a6566e76240543f8feb06fd45" + expect(3);
// "7777be39549c4016436afda65d2330e",
// "length": 3 this.jio.removeAttachment(
// } "removeAttachment1/",
// }, "attachment1"
// "_id": "a", )
// "date": shared.date_a.toJSON(), .fail(function (error) {
// "title": "one" ok(error instanceof jIO.util.jIOError);
// }, equal(error.message, "id removeAttachment1/ is forbidden (no begin /)");
// "id": "a", equal(error.status_code, 400);
// "value": {} })
// }, { .fail(function (error) {
// "doc": { ok(false, error);
// "_id": "b", })
// "date": shared.date_a.toJSON(), .always(function () {
// "title": "two" start();
// }, });
// "id": "b", });
// "value": {}
// }, { test("reject ID not ending with /", function () {
// "doc": { stop();
// "_id": "c", expect(3);
// "date": shared.date_b.toJSON(),
// "title": "one" this.jio.removeAttachment(
// }, "/removeAttachment1",
// "id": "c", "attachment1"
// "value": {} )
// }, { .fail(function (error) {
// "doc": { ok(error instanceof jIO.util.jIOError);
// "_id": "d", equal(error.message, "id /removeAttachment1 is forbidden (no end /)");
// "date": shared.date_b.toJSON(), equal(error.status_code, 400);
// "title": "two" })
// }, .fail(function (error) {
// "id": "d", ok(false, error);
// "value": {} })
// }], .always(function () {
// "total_rows": 4 start();
// }, });
// "method": "allDocs", });
// "result": "success",
// "status": 200, test("reject attachment with / character", function () {
// "statusText": "Ok" stop();
// }, "AllDocs include docs"); expect(3);
//
// }).always(start); this.jio.removeAttachment(
// "/removeAttachment1/",
// }); "attach/ment1"
)
}(jIO, QUnit)); .fail(function (error) {
ok(error instanceof jIO.util.jIOError);
equal(error.message, "attachment attach/ment1 is forbidden");
equal(error.status_code, 400);
})
.fail(function (error) {
ok(false, error);
})
.always(function () {
start();
});
});
test("removeAttachment document", function () {
var url_get_id = "https://api.dropboxapi.com/1/metadata/dropbox" +
"//removeAttachment1/attachment1/?access_token=" + token,
url_delete = "https://api.dropboxapi.com/1/fileops/delete/" +
"?access_token=" + token + "&root=dropbox" +
"&path=/removeAttachment1/attachment1",
server = this.server;
this.server.respondWith("GET", url_get_id, [204, {
"Content-Type": "text/xml"
}, '{"is_dir": false}']);
this.server.respondWith("POST", url_delete, [204, {
"Content-Type": "text/xml"
}, ""]);
stop();
expect(13);
this.jio.removeAttachment(
"/removeAttachment1/",
"attachment1"
)
.then(function () {
equal(server.requests.length, 2);
equal(server.requests[0].method, "GET");
equal(server.requests[0].url, url_get_id);
equal(server.requests[0].status, 204);
equal(server.requests[0].requestBody, undefined);
equal(server.requests[0].responseText, "{\"is_dir\": false}");
deepEqual(server.requests[0].requestHeaders, {});
equal(server.requests[1].method, "POST");
equal(server.requests[1].url, url_delete);
equal(server.requests[1].status, 204);
equal(server.requests[1].requestBody, undefined);
equal(server.requests[1].responseText, "");
deepEqual(server.requests[1].requestHeaders, {
"Content-Type": "text/plain;charset=utf-8"
});
})
.fail(function (error) {
ok(false, error);
})
.always(function () {
start();
});
});
test("remove inexistent attachment", function () {
var url_get_id = "https://api.dropboxapi.com/1/metadata/dropbox" +
"//removeAttachment1/attachment1?access_token=" + token;
this.server.respondWith("GET", url_get_id, [404, {
"Content-Type": "text/xml"
}, '']);
stop();
expect(3);
this.jio.removeAttachment(
"/removeAttachment1/",
"attachment1"
)
.then(function () {
ok(false);
})
.fail(function (error) {
ok(error instanceof jIO.util.jIOError);
equal(error.message, "Cannot find attachment: /removeAttachment1/" +
", attachment1");
equal(error.status_code, 404);
})
.always(function () {
start();
});
});
/////////////////////////////////////////////////////////////////
// DropboxStorage.getAttachment
/////////////////////////////////////////////////////////////////
module("DropboxStorage.getAttachment", {
setup: function () {
this.server = sinon.fakeServer.create();
this.server.autoRespond = true;
this.server.autoRespondAfter = 5;
this.jio = jIO.createJIO({
type: "dropbox",
access_token: token
});
},
teardown: function () {
this.server.restore();
delete this.server;
}
});
test("reject ID not starting with /", function () {
stop();
expect(3);
this.jio.getAttachment(
"getAttachment1/",
"attachment1"
)
.fail(function (error) {
ok(error instanceof jIO.util.jIOError);
equal(error.message, "id getAttachment1/ is forbidden (no begin /)");
equal(error.status_code, 400);
})
.fail(function (error) {
ok(false, error);
})
.always(function () {
start();
});
});
test("reject ID not ending with /", function () {
stop();
expect(3);
this.jio.getAttachment(
"/getAttachment1",
"attachment1"
)
.fail(function (error) {
ok(error instanceof jIO.util.jIOError);
equal(error.message, "id /getAttachment1 is forbidden (no end /)");
equal(error.status_code, 400);
})
.fail(function (error) {
ok(false, error);
})
.always(function () {
start();
});
});
test("reject attachment with / character", function () {
stop();
expect(3);
this.jio.getAttachment(
"/getAttachment1/",
"attach/ment1"
)
.fail(function (error) {
ok(error instanceof jIO.util.jIOError);
equal(error.message, "attachment attach/ment1 is forbidden");
equal(error.status_code, 400);
})
.fail(function (error) {
ok(false, error);
})
.always(function () {
start();
});
});
test("getAttachment document", function () {
var url = "https://content.dropboxapi.com/1/files/dropbox//" +
"getAttachment1/attachment1?access_token=" + token,
server = this.server;
this.server.respondWith("GET", url, [200, {
"Content-Type": "text/plain"
}, "foo\nbaré"]);
stop();
expect(9);
this.jio.getAttachment(
"/getAttachment1/",
"attachment1"
)
.then(function (result) {
equal(server.requests.length, 1);
equal(server.requests[0].method, "GET");
equal(server.requests[0].url, url);
equal(server.requests[0].status, 200);
equal(server.requests[0].requestBody, undefined);
equal(server.requests[0].responseText, "foo\nbaré");
ok(result instanceof Blob, "Data is Blob");
deepEqual(result.type, "text/plain", "Check mimetype");
return jIO.util.readBlobAsText(result);
})
.then(function (result) {
equal(result.target.result, "foo\nbaré",
"Attachment correctly fetched");
})
.fail(function (error) {
ok(false, error);
})
.always(function () {
start();
});
});
test("get inexistent attachment", function () {
var url = "https://content.dropboxapi.com/1/files/dropbox//" +
"getAttachment1/attachment1?access_token=" + token;
this.server.respondWith("GET", url, [404, {
"Content-Type": "text/xml"
}, ""]);
stop();
expect(3);
this.jio.getAttachment(
"/getAttachment1/",
"attachment1"
)
.then(function () {
ok(false);
})
.fail(function (error) {
ok(error instanceof jIO.util.jIOError);
equal(error.message, "Cannot find attachment: /getAttachment1/" +
", attachment1");
equal(error.status_code, 404);
})
.always(function () {
start();
});
});
}(jIO, QUnit, Blob, sinon));
...@@ -42,7 +42,7 @@ ...@@ -42,7 +42,7 @@
<script src="jio.storage/shastorage.tests.js"></script> <script src="jio.storage/shastorage.tests.js"></script>
<!--script src="jio.storage/indexstorage.tests.js"></script--> <!--script src="jio.storage/indexstorage.tests.js"></script-->
<!--script src="jio.storage/dropboxstorage.tests.js"></script--> <script src="jio.storage/dropboxstorage.tests.js"></script>
<script src="jio.storage/zipstorage.tests.js"></script> <script src="jio.storage/zipstorage.tests.js"></script>
<!--script src="../lib/jquery/jquery.min.js"></script> <!--script src="../lib/jquery/jquery.min.js"></script>
......
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