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