Commit 1159af90 authored by Junming Liu's avatar Junming Liu

Merge branch 'master' of https://lab.nexedi.com/Junming/jio into ljm_qiniu_branch

Conflicts:
	examples/scenario.js
parents 374c1b07 391e48d5
...@@ -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
......
...@@ -7863,6 +7863,274 @@ Query.searchTextToRegExp = searchTextToRegExp; ...@@ -7863,6 +7863,274 @@ Query.searchTextToRegExp = searchTextToRegExp;
jIO.addStorage('zip', ZipStorage); jIO.addStorage('zip', ZipStorage);
}(RSVP, Blob, LZString, DOMException)); }(RSVP, Blob, LZString, DOMException));
;/*
* Copyright 2013, Nexedi SA
* Released under the LGPL license.
* http://www.gnu.org/licenses/lgpl.html
*/
/**
* JIO Dropbox Storage. Type = "dropbox".
* Dropbox "database" storage.
*/
/*global Blob, jIO, RSVP, UriTemplate*/
/*jslint nomen: true*/
(function (jIO, RSVP, Blob, UriTemplate) {
"use strict";
var UPLOAD_URL = "https://content.dropboxapi.com/1/files_put/" +
"{+root}{+id}{+name}{?access_token}",
upload_template = UriTemplate.parse(UPLOAD_URL),
CREATE_DIR_URL = "https://api.dropboxapi.com/1/fileops/create_folder" +
"{?access_token,root,path}",
create_dir_template = UriTemplate.parse(CREATE_DIR_URL),
REMOVE_URL = "https://api.dropboxapi.com/1/fileops/delete/" +
"{?access_token,root,path}",
remote_template = UriTemplate.parse(REMOVE_URL),
GET_URL = "https://content.dropboxapi.com/1/files" +
"{/root,id}{+name}{?access_token}",
get_template = UriTemplate.parse(GET_URL),
//LIST_URL = 'https://api.dropboxapi.com/1/metadata/sandbox/';
METADATA_URL = "https://api.dropboxapi.com/1/metadata" +
"{/root}{+id}{?access_token}",
metadata_template = UriTemplate.parse(METADATA_URL);
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;
}
function restrictAttachmentId(id) {
if (id.indexOf("/") !== -1) {
throw new jIO.util.jIOError("attachment " + id + " is forbidden",
400);
}
}
/**
* The JIO Dropbox Storage extension
*
* @class DropboxStorage
* @constructor
*/
function DropboxStorage(spec) {
if (typeof spec.access_token !== 'string' || !spec.access_token) {
throw new TypeError("Access Token' must be a string " +
"which contains more than one character.");
}
if (typeof spec.root !== 'string' || !spec.root ||
(spec.root !== "dropbox" && spec.root !== "sandbox")) {
throw new TypeError("root must be 'dropbox' or 'sandbox'");
}
this._access_token = spec.access_token;
this._root = spec.root;
}
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);
}
return new RSVP.Queue()
.push(function () {
return jIO.util.ajax({
type: "POST",
url: create_dir_template.expand({
access_token: that._access_token,
root: that._root,
path: id
})
});
})
.push(undefined, function (err) {
if ((err.target !== undefined) &&
(err.target.status === 405)) {
// Directory already exists, no need to fail
return;
}
throw err;
});
};
DropboxStorage.prototype.remove = function (id) {
id = restrictDocumentId(id);
return jIO.util.ajax({
type: "POST",
url: remote_template.expand({
access_token: this._access_token,
root: this._root,
path: id
})
});
};
DropboxStorage.prototype.get = function (id) {
var that = this;
if (id === "/") {
return {};
}
id = restrictDocumentId(id);
return new RSVP.Queue()
.push(function () {
return jIO.util.ajax({
type: "GET",
url: metadata_template.expand({
access_token: that._access_token,
root: that._root,
id: id
})
});
})
.push(function (evt) {
var obj = JSON.parse(evt.target.response ||
evt.target.responseText);
if (obj.is_dir) {
return {};
}
throw new jIO.util.jIOError("Not a directory: " + id, 404);
}, function (error) {
if (error.target !== undefined && error.target.status === 404) {
throw new jIO.util.jIOError("Cannot find document: " + id, 404);
}
throw error;
});
};
DropboxStorage.prototype.allAttachments = function (id) {
var that = this;
id = restrictDocumentId(id);
return new RSVP.Queue()
.push(function () {
return jIO.util.ajax({
type: "GET",
url: metadata_template.expand({
access_token: that._access_token,
root: that._root,
id: id
})
});
})
.push(function (evt) {
var obj = JSON.parse(evt.target.response || evt.target.responseText),
i,
result = {};
if (!obj.is_dir) {
throw new jIO.util.jIOError("Not a directory: " + id, 404);
}
for (i = 0; i < obj.contents.length; i += 1) {
if (!obj.contents[i].is_dir) {
result[obj.contents[i].path.split("/").pop()] = {};
}
}
return result;
}, function (error) {
if (error.target !== undefined && error.target.status === 404) {
throw new jIO.util.jIOError("Cannot find document: " + id, 404);
}
throw error;
});
};
//currently, putAttachment will fail with files larger than 150MB,
//due to the Dropbox API. the API provides the "chunked_upload" method
//to pass this limit, but upload process becomes more complex to implement.
//
//putAttachment will also create a folder if you try to put an attachment
//to an inexisting foler.
DropboxStorage.prototype.putAttachment = function (id, name, blob) {
id = restrictDocumentId(id);
restrictAttachmentId(name);
return jIO.util.ajax({
type: "PUT",
url: upload_template.expand({
root: this._root,
id: id,
name: name,
access_token: this._access_token
}),
dataType: blob.type,
data: blob
});
};
DropboxStorage.prototype.getAttachment = function (id, name) {
var that = this;
id = restrictDocumentId(id);
restrictAttachmentId(name);
return new RSVP.Queue()
.push(function () {
return jIO.util.ajax({
type: "GET",
dataType: "blob",
url: get_template.expand({
root: that._root,
id: id,
name: name,
access_token: that._access_token
})
});
})
.push(function (evt) {
return new Blob(
[evt.target.response || evt.target.responseText],
{"type": evt.target.getResponseHeader('Content-Type') ||
"application/octet-stream"}
);
}, function (error) {
if (error.target !== undefined && error.target.status === 404) {
throw new jIO.util.jIOError("Cannot find attachment: " +
id + ", " + name, 404);
}
throw error;
});
};
//removeAttachment removes also directories.(due to Dropbox API)
DropboxStorage.prototype.removeAttachment = function (id, name) {
var that = this;
id = restrictDocumentId(id);
restrictAttachmentId(name);
return new RSVP.Queue()
.push(function () {
return jIO.util.ajax({
type: "POST",
url: remote_template.expand({
access_token: that._access_token,
root: that._root,
path: id + name
})
});
}).push(undefined, function (error) {
if (error.target !== undefined && error.target.status === 404) {
throw new jIO.util.jIOError("Cannot find attachment: " +
id + ", " + name, 404);
}
throw error;
});
};
jIO.addStorage('dropbox', DropboxStorage);
}(jIO, RSVP, Blob, UriTemplate));
;/* ;/*
* Copyright 2013, Nexedi SA * Copyright 2013, Nexedi SA
* Released under the LGPL license. * Released under the LGPL license.
...@@ -8492,7 +8760,8 @@ Query.searchTextToRegExp = searchTextToRegExp; ...@@ -8492,7 +8760,8 @@ Query.searchTextToRegExp = searchTextToRegExp;
}, },
form_data_json = {}, form_data_json = {},
field, field,
key; key,
prefix_length;
form_data_json.form_id = { form_data_json.form_id = {
"key": [form.form_id.key], "key": [form.form_id.key],
...@@ -8502,15 +8771,20 @@ Query.searchTextToRegExp = searchTextToRegExp; ...@@ -8502,15 +8771,20 @@ Query.searchTextToRegExp = searchTextToRegExp;
for (key in form) { for (key in form) {
if (form.hasOwnProperty(key)) { if (form.hasOwnProperty(key)) {
field = form[key]; field = form[key];
if ((key.indexOf('my_') === 0) && prefix_length = 0;
(field.editable) && if (key.indexOf('my_') === 0 && field.editable) {
prefix_length = 3;
}
if (key.indexOf('your_') === 0) {
prefix_length = 5;
}
if ((prefix_length !== 0) &&
(allowed_field_dict.hasOwnProperty(field.type))) { (allowed_field_dict.hasOwnProperty(field.type))) {
form_data_json[key.substring(prefix_length)] = {
form_data_json[key.substring(3)] = {
"default": field["default"], "default": field["default"],
"key": field.key "key": field.key
}; };
converted_json[key.substring(3)] = field["default"]; converted_json[key.substring(prefix_length)] = field["default"];
} }
} }
} }
......
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -37,35 +37,53 @@ ...@@ -37,35 +37,53 @@
/////////////////////////// ///////////////////////////
// Memory storage // Memory storage
/////////////////////////// ///////////////////////////
return g.run({
type: "query",
sub_storage: {
type: "uuid",
sub_storage: {
type: "union",
storage_list: [{
type: "memory"
}]
}
}
});
///////////////////////////
// IndexedDB storage
///////////////////////////
// return g.run({ // return g.run({
// type: "query", // type: "query",
// sub_storage: { // sub_storage: {
// type: "uuid", // type: "uuid",
// sub_storage: { // sub_storage: {
// type: "union", // "type": "indexeddb",
// storage_list: [{ // "database": "test"
// type: "memory"
// }]
// } // }
// } // }
// }); // });
/////////////////////////// ///////////////////////////
// IndexedDB storage // DAV storage
/////////////////////////// ///////////////////////////
// return g.run({ // return g.run({
// type: "query", // type: "query",
// sub_storage: { // sub_storage: {
// type: "uuid", // type: "uuid",
// sub_storage: { // sub_storage: {
// "type": "indexeddb", // type: "drivetojiomapping",
// "database": "test" // sub_storage: {
// "type": "dav",
// "url": "DAVURL",
// "basic_login": btoa("LOGIN:PASSWD")
// }
// } // }
// } // }
// }); // });
/////////////////////////// ///////////////////////////
// DAV storage // Dropbox storage
/////////////////////////// ///////////////////////////
// return g.run({ // return g.run({
// type: "query", // type: "query",
...@@ -74,9 +92,9 @@ ...@@ -74,9 +92,9 @@
// sub_storage: { // sub_storage: {
// type: "drivetojiomapping", // type: "drivetojiomapping",
// sub_storage: { // sub_storage: {
// "type": "dav", // "type": "dropbox",
// "url": "DAVURL", // "access_token" : "TOKEN",
// "basic_login": btoa("LOGIN:PASSWD") // "root" : "dropbox"
// } // }
// } // }
// } // }
...@@ -85,18 +103,18 @@ ...@@ -85,18 +103,18 @@
/////////////////////////// ///////////////////////////
// Qiniu storage // Qiniu storage
/////////////////////////// ///////////////////////////
return g.run({ // return g.run({
type: "query", // type: "query",
sub_storage: { // sub_storage: {
type: "uuid", // type: "uuid",
sub_storage: { // sub_storage: {
"type": "qiniu", // "type": "qiniu",
"bucket": "7xn150.com1.z0.glb.clouddn.com", // "bucket": "BUCKET",
"access_key": "s90kGV3JYDDQPivaPVpwxrHMi9RCpncLgLctGDJQ", // "access_key": "ACCESSKEY",
"secret_key": "hfqndzXIfqP6aMpTOdgT_UjiUjARkiFXz98Cthjx" // "secret_key": "SECRETKEY"
} // }
} // }
}); // });
/////////////////////////// ///////////////////////////
// Replicate storage // Replicate storage
...@@ -159,10 +177,7 @@ ...@@ -159,10 +177,7 @@
deepEqual(doc, {"title": "I don't have ID éà&\n"}, deepEqual(doc, {"title": "I don't have ID éà&\n"},
"Document correctly fetched"); "Document correctly fetched");
// Remove the doc // Remove the doc
return jio.remove(doc_id) return jio.remove(doc_id);
.fail(function (error) {
console.log("remove error", error);
});
}) })
.then(function (doc_id) { .then(function (doc_id) {
ok(doc_id, "Document removed"); ok(doc_id, "Document removed");
...@@ -229,20 +244,20 @@ ...@@ -229,20 +244,20 @@
}) })
.then(function () { .then(function () {
return jio.put("test.txt", {}); return jio.put("foo❤/test.txt", {});
}) })
.then(function () { .then(function () {
return jio.putAttachment( return jio.putAttachment(
"test.txt", "foo❤/test.txt",
"enclosure", "enclosure",
new Blob(["fooé\nbar"], {type: "text/plain"}) new Blob(["fooé\nbar测试四😈"], {type: "text/plain"})
); );
}) })
.then(function () { .then(function () {
ok(true, "Attachment stored"); ok(true, "Attachment stored");
return jio.getAttachment("test.txt", "enclosure"); return jio.getAttachment("foo❤/test.txt", "enclosure");
}) })
.then(function (blob) { .then(function (blob) {
...@@ -250,13 +265,14 @@ ...@@ -250,13 +265,14 @@
}) })
.then(function (result) { .then(function (result) {
equal(result.target.result, "fooé\nbar", "Attachment correctly fetched"); equal(result.target.result, "fooé\nbar测试四😈", "Attachment correctly fetched");
return jio.get("test.txt"); return jio.get("foo❤/test.txt");
}) })
.then(function (doc) { .then(function (doc) {
deepEqual(doc, {}, "Document correctly fetched"); deepEqual(doc, {}, "Document correctly fetched");
return jio.allAttachments("test.txt"); return jio.allAttachments("foo❤/test.txt");
}) })
.then(function (doc) { .then(function (doc) {
deepEqual(doc, { deepEqual(doc, {
...@@ -264,7 +280,7 @@ ...@@ -264,7 +280,7 @@
}, },
"Attachment list correctly fetched"); "Attachment list correctly fetched");
return jio.removeAttachment("test.txt", "enclosure"); return jio.removeAttachment("foo❤/test.txt", "enclosure");
}) })
.then(function () { .then(function () {
......
{ {
"name": "jio", "name": "jio",
"version": "v3.3.0", "version": "v3.4.0",
"license": "LGPLv3", "license": "LGPLv3",
"author": "Nexedi SA", "author": "Nexedi SA",
"contributors": [ "contributors": [
......
...@@ -7,45 +7,49 @@ ...@@ -7,45 +7,49 @@
* 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 Blob, jIO, RSVP, UriTemplate*/
/*js2lint nomen: true, unparam: true, bitwise: true */ /*jslint nomen: true*/
/*jslint nomen: true, unparam: true*/
(function (dependencies, module) {
"use strict";
if (typeof define === 'function' && define.amd) {
return define(dependencies, module);
}
module(jIO, RSVP);
}([
'jio',
'rsvp'
], function (jIO, RSVP) {
"use strict";
/** (function (jIO, RSVP, Blob, UriTemplate) {
* Checks if an object has no enumerable keys "use strict";
* var UPLOAD_URL = "https://content.dropboxapi.com/1/files_put/" +
* @param {Object} obj The object "{+root}{+id}{+name}{?access_token}",
* @return {Boolean} true if empty, else false upload_template = UriTemplate.parse(UPLOAD_URL),
*/ CREATE_DIR_URL = "https://api.dropboxapi.com/1/fileops/create_folder" +
function objectIsEmpty(obj) { "{?access_token,root,path}",
var k; create_dir_template = UriTemplate.parse(CREATE_DIR_URL),
for (k in obj) { REMOVE_URL = "https://api.dropboxapi.com/1/fileops/delete/" +
if (obj.hasOwnProperty(k)) { "{?access_token,root,path}",
return false; remote_template = UriTemplate.parse(REMOVE_URL),
} GET_URL = "https://content.dropboxapi.com/1/files" +
"{/root,id}{+name}{?access_token}",
get_template = UriTemplate.parse(GET_URL),
//LIST_URL = 'https://api.dropboxapi.com/1/metadata/sandbox/';
METADATA_URL = "https://api.dropboxapi.com/1/metadata" +
"{/root}{+id}{?access_token}",
metadata_template = UriTemplate.parse(METADATA_URL);
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;
}
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 * @class DropboxStorage
* @constructor * @constructor
...@@ -55,645 +59,210 @@ ...@@ -55,645 +59,210 @@
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) { if (typeof spec.root !== 'string' || !spec.root ||
throw new TypeError("'Root Folder' must be a string "); (spec.root !== "dropbox" && spec.root !== "sandbox")) {
} throw new TypeError("root must be 'dropbox' or 'sandbox'");
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 = spec.root;
} }
// 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_template.expand({
this._application_name + '/' + access_token: that._access_token,
path + '?access_token=' + this._access_token, root: that._root,
"data": data path: id
});
};
/**
* 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;
}); });
})
.push(undefined, function (err) {
if ((err.target !== undefined) &&
(err.target.status === 405)) {
// Directory already exists, no need to fail
return;
} }
throw err;
// 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;
}
}
}
// 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. id = restrictDocumentId(id);
* return jIO.util.ajax({
* @method put type: "POST",
* @param {Object} command The JIO command url: remote_template.expand({
* @param {Object} metadata The metadata to store access_token: this._access_token,
*/ root: this._root,
DropboxStorage.prototype.put = function (command, metadata) { path: id
// 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) {
if (event instanceof ProgressEvent) {
// If the document do not exist no problem
if (event.target.status === 404) {
return 0;
}
}
throw event;
}); });
} };
// 2. Update Document DropboxStorage.prototype.get = function (id) {
function updateDocument() { var that = this;
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 if (id === "/") {
function onError(event) { return {};
if (event instanceof ProgressEvent) {
command.error(
event.target.status,
event.target.statusText,
"Unable to put doc"
);
} else {
if (event !== 1) {
throw event;
}
} }
} id = restrictDocumentId(id);
return getDocument()
.then(updateDocument)
.then(function () {
command.success();
// XXX should use command.success("created") when the document is created
})
.fail(onError);
};
// Storage specific get method return new RSVP.Queue()
DropboxStorage.prototype._get = function (key) { .push(function () {
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: metadata_template.expand({
}); access_token: that._access_token,
}; root: that._root,
id: id
/** })
* 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( .push(function (evt) {
event.target.status, var obj = JSON.parse(evt.target.response ||
event.target.statusText, evt.target.responseText);
"Cannot find document" if (obj.is_dir) {
); return {};
} }
}).fail(function (event) { throw new jIO.util.jIOError("Not a directory: " + id, 404);
if (event instanceof ProgressEvent) { }, function (error) {
command.error( if (error.target !== undefined && error.target.status === 404) {
event.target.status, throw new jIO.util.jIOError("Cannot find document: " + id, 404);
event.target.statusText, }
"Cannot find document" throw error;
);
} 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 var that = this;
function getDocument() { id = restrictDocumentId(id);
return that._get(METADATA_FOLDER + '/' + param._id)
.then(function (answer) {
document = JSON.parse(answer.target.responseText);
// We check the attachment is referenced return new RSVP.Queue()
if (document.hasOwnProperty('_attachments')) { .push(function () {
if (document._attachments.hasOwnProperty(param._attachment)) { return jIO.util.ajax({
return; type: "GET",
} url: metadata_template.expand({
} access_token: that._access_token,
command.error( root: that._root,
404, id: id
"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;
}); });
})
.push(function (evt) {
var obj = JSON.parse(evt.target.response || evt.target.responseText),
i,
result = {};
if (!obj.is_dir) {
throw new jIO.util.jIOError("Not a directory: " + id, 404);
} }
for (i = 0; i < obj.contents.length; i += 1) {
// 2. We get the Attachment if (!obj.contents[i].is_dir) {
function getAttachment() { result[obj.contents[i].path.split("/").pop()] = {};
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;
} }
} }
return result;
}, function (error) {
if (error.target !== undefined && error.target.status === 404) {
throw new jIO.util.jIOError("Cannot find document: " + id, 404);
} }
throw error;
return getDocument() });
.then(getAttachment)
.then(onSuccess)
.fail(onError);
}; };
/** //currently, putAttachment will fail with files larger than 150MB,
* Add an attachment to a document //due to the Dropbox API. the API provides the "chunked_upload" method
* //to pass this limit, but upload process becomes more complex to implement.
* @method putAttachment //
* @param {Object} command The JIO command //putAttachment will also create a folder if you try to put an attachment
* @param {Object} param The given parameters //to an inexisting foler.
* @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;
}
throw event;
});
}
// 2. We push the attachment DropboxStorage.prototype.putAttachment = function (id, name, blob) {
function pushAttachment() { id = restrictDocumentId(id);
return that._put( restrictAttachmentId(name);
param._id + '-' + param._attachment,
param._blob
);
}
// 3. We update the document return jIO.util.ajax({
function updateDocument() { type: "PUT",
if (document._attachments === undefined) { url: upload_template.expand({
document._attachments = {}; root: this._root,
} id: id,
document._attachments[param._attachment] = { name: name,
"content_type": param._blob.type, access_token: this._access_token
"digest": digest,
"length": param._blob.size
};
return that._put(
param._id,
new Blob([JSON.stringify(document)], {
type: "application/json"
}), }),
METADATA_FOLDER dataType: blob.type,
); data: blob
}
// 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);
}; };
/** DropboxStorage.prototype.getAttachment = function (id, name) {
* Get all filenames belonging to a user from the document index var that = this;
*
* @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;
// 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) id = restrictDocumentId(id);
if (!item.is_dir) { restrictAttachmentId(name);
// 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; return new RSVP.Queue()
for (i = 0; i < response_length; i += 1) { .push(function () {
result[i].doc = JSON.parse(response_list[i].target.response); return jIO.util.ajax({
} type: "GET",
command.success({ dataType: "blob",
"data": { url: get_template.expand({
"rows": result, root: that._root,
"total_rows": result.length id: id,
} name: name,
access_token: that._access_token
})
}); });
}).fail(function (error) { })
if (error instanceof ProgressEvent) { .push(function (evt) {
command.error( return new Blob(
"error", [evt.target.response || evt.target.responseText],
"did not work as expected", {"type": evt.target.getResponseHeader('Content-Type') ||
"Unable to call allDocs" "application/octet-stream"}
); );
}, function (error) {
if (error.target !== undefined && error.target.status === 404) {
throw new jIO.util.jIOError("Cannot find attachment: " +
id + ", " + name, 404);
} }
throw error;
}); });
}; };
// Storage specific remove method //removeAttachment removes also directories.(due to Dropbox API)
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
});
};
/**
* 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 DropboxStorage.prototype.removeAttachment = function (id, name) {
function removeAttachments() { var that = this;
var promise_list = [], attachment_list = [], attachment_count = 0, i = 0; id = restrictDocumentId(id);
if (document.hasOwnProperty('_attachments')) { restrictAttachmentId(name);
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];
}
}
});
}
// 4 Notify Success return new RSVP.Queue()
function onSuccess(event) { .push(function () {
if (event instanceof ProgressEvent) { return jIO.util.ajax({
command.success( type: "POST",
event.target.status, url: remote_template.expand({
event.target.statusText access_token: that._access_token,
); root: that._root,
} else { path: id + name
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) { }).push(undefined, function (error) {
command.error( if (error.target !== undefined && error.target.status === 404) {
error.target.status, throw new jIO.util.jIOError("Cannot find attachment: " +
"missing attachment", id + ", " + name, 404);
"Attachment not found"
);
} }
command.error( throw error;
"not_found",
"missing",
"Unable to delete document Attachment"
);
}); });
}; };
jIO.addStorage('dropbox', DropboxStorage); jIO.addStorage('dropbox', DropboxStorage);
}));
}(jIO, RSVP, Blob, UriTemplate));
...@@ -79,7 +79,8 @@ ...@@ -79,7 +79,8 @@
}, },
form_data_json = {}, form_data_json = {},
field, field,
key; key,
prefix_length;
form_data_json.form_id = { form_data_json.form_id = {
"key": [form.form_id.key], "key": [form.form_id.key],
...@@ -89,15 +90,20 @@ ...@@ -89,15 +90,20 @@
for (key in form) { for (key in form) {
if (form.hasOwnProperty(key)) { if (form.hasOwnProperty(key)) {
field = form[key]; field = form[key];
if ((key.indexOf('my_') === 0) && prefix_length = 0;
(field.editable) && if (key.indexOf('my_') === 0 && field.editable) {
prefix_length = 3;
}
if (key.indexOf('your_') === 0) {
prefix_length = 5;
}
if ((prefix_length !== 0) &&
(allowed_field_dict.hasOwnProperty(field.type))) { (allowed_field_dict.hasOwnProperty(field.type))) {
form_data_json[key.substring(prefix_length)] = {
form_data_json[key.substring(3)] = {
"default": field["default"], "default": field["default"],
"key": field.key "key": field.key
}; };
converted_json[key.substring(3)] = field["default"]; converted_json[key.substring(prefix_length)] = field["default"];
} }
} }
} }
......
/*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; throws = QUnit.throws,
token = "sample_token";
module("DropboxStorage");
/////////////////////////////////////////////////////////////////
// DropboxStorage constructor
// /** /////////////////////////////////////////////////////////////////
// * all(promises): Promise module("DropboxStorage.constructor");
// *
// * Produces a promise that is resolved when all the given promises are test("create storage", function () {
// * fulfilled. The resolved value is an array of each of the answers of the var jio = jIO.createJIO({
// * given promises. type: "dropbox",
// * access_token: token,
// * @param {Array} promises The promises to use root : "sandbox"
// * @return {Promise} A new promise });
// */ equal(jio.__type, "dropbox");
// function all(promises) { deepEqual(jio.__storage._access_token, token);
// var results = [], i, count = 0; deepEqual(jio.__storage._root, "sandbox");
// });
// function cancel() {
// var j; test("reject invalid root", function () {
// for (j = 0; j < promises.length; j += 1) {
// if (typeof promises[j].cancel === 'function') { throws(
// promises[j].cancel(); function () {
// } jIO.createJIO({
// } type: "dropbox",
// } access_token: token,
// return new RSVP.Promise(function (resolve, reject, notify) { root : "foobar"
// /*jslint unparam: true */ });
// function succeed(j) { },
// return function (answer) { function (error) {
// results[j] = answer; ok(error instanceof TypeError);
// count += 1; equal(error.message,
// if (count !== promises.length) { "root must be 'dropbox' or 'sandbox'");
// return; return true;
// } }
// resolve(results); );
// }; });
// }
// /////////////////////////////////////////////////////////////////
// function notified(j) { // DropboxStorage.put
// return function (answer) { /////////////////////////////////////////////////////////////////
// notify({ module("DropboxStorage.put", {
// "promise": promises[j], setup: function () {
// "index": j,
// "notified": answer this.server = sinon.fakeServer.create();
// }); this.server.autoRespond = true;
// }; this.server.autoRespondAfter = 5;
// }
// for (i = 0; i < promises.length; i += 1) { this.jio = jIO.createJIO({
// promises[i].then(succeed(i), succeed(i), notified(i)); type: "dropbox",
// } access_token: token,
// }, cancel); root : "dropbox"
// } });
// },
// test("Post & Get", function () { teardown: function () {
// expect(6); this.server.restore();
// var jio = jIO.createJIO({ delete this.server;
// "type": "dropbox", }
// "access_token": "v43SQLCEoi8AAAAAAAAAAVixCoMfDelgGj3NRPfE" + });
// "nqscAuNGp2LhoS8-GiAaDD4C"
// }, { test("put document", function () {
// "workspace": {} var url = "https://api.dropboxapi.com/1/fileops/create_folder?access_token="
// }); + token + "&root=dropbox&path=%2Fput1%2F",
// server = this.server;
// stop(); this.server.respondWith("POST", url, [201, {
// all([ "Content-Type": "text/xml"
// }, ""]);
// // get inexistent document
// jio.get({ stop();
// "_id": "inexistent" expect(7);
// }).always(function (answer) {
// this.jio.put("/put1/", {})
// deepEqual(answer, { .then(function () {
// "error": "not_found", equal(server.requests.length, 1);
// "id": "inexistent", equal(server.requests[0].method, "POST");
// "message": "Cannot find document", equal(server.requests[0].url, url);
// "method": "get", equal(server.requests[0].status, 201);
// "reason": "Not Found", equal(server.requests[0].requestBody, undefined);
// "result": "error", equal(server.requests[0].responseText, "");
// "status": 404, deepEqual(server.requests[0].requestHeaders, {
// "statusText": "Not Found" "Content-Type": "text/plain;charset=utf-8"
// }, "Get inexistent document"); });
// })
// }), .fail(function (error) {
// ok(false, error);
// // post without id })
// jio.post({}) .always(function () {
// .then(function (answer) { start();
// var id = answer.id; });
// delete answer.id; });
// deepEqual(answer, {
// "method": "post", test("don't throw error when putting existing directory", function () {
// "result": "success", var url = "https://api.dropboxapi.com/1/fileops/create_folder?access_token="
// "status": 201, + token + "&root=dropbox&path=%2Fexisting%2F",
// "statusText": "Created" server = this.server;
// }, "Post without id"); this.server.respondWith("POST", url, [405, {
// "Content-Type": "text/xml"
// // We check directly on the document to get its own id }, "POST" + url + "(Forbidden)"]);
// return jio.get({'_id': id}); stop();
// }).always(function (answer) { expect(1);
// this.jio.put("/existing/", {})
// var uuid = answer.data._id; .then(function () {
// ok(util.isUuid(uuid), "Uuid should look like " + equal(server.requests[0].status, 405);
// "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx : " + uuid); })
// .fail(function (error) {
// }).then(function () { ok(false, error);
// return jio.remove({"_id": "post1"}) })
// }).always(function () { .always(function () {
// return jio.post({ start();
// "_id": "post1", });
// "title": "myPost1" });
// });
// test("reject ID not starting with /", function () {
// }).always(function (answer) { stop();
// expect(3);
// deepEqual(answer, {
// "id": "post1", this.jio.put("put1/", {})
// "method": "post", .fail(function (error) {
// "result": "success", ok(error instanceof jIO.util.jIOError);
// "status": 201, equal(error.message, "id put1/ is forbidden (no begin /)");
// "statusText": "Created" equal(error.status_code, 400);
// }, "Post"); })
// .fail(function (error) {
// }).then(function () { ok(false, error);
// })
// return jio.get({ .always(function () {
// "_id": "post1" start();
// }); });
// });
// }).always(function (answer) {
// test("reject ID not ending with /", function () {
// deepEqual(answer, { stop();
// "data": { expect(3);
// "_id": "post1",
// "title": "myPost1" this.jio.put("/put1", {})
// }, .fail(function (error) {
// "id": "post1", ok(error instanceof jIO.util.jIOError);
// "method": "get", equal(error.message, "id /put1 is forbidden (no end /)");
// "result": "success", equal(error.status_code, 400);
// "status": 200, })
// "statusText": "Ok" .fail(function (error) {
// }, "Get, Check document"); ok(false, error);
// }).then(function () { })
// .always(function () {
// // post but document already exists start();
// return jio.post({"_id": "post1", "title": "myPost2"}); });
// });
// }).always(function (answer) {
// test("reject to store any property", function () {
// deepEqual(answer, { stop();
// "error": "conflict", expect(3);
// "id": "post1",
// "message": "Cannot create a new document", this.jio.put("/put1/", {title: "foo"})
// "method": "post", .fail(function (error) {
// "reason": "document exists", ok(error instanceof jIO.util.jIOError);
// "result": "error", equal(error.message, "Can not store properties: title");
// "status": 409, equal(error.status_code, 400);
// "statusText": "Conflict" })
// }, "Post but document already exists"); .fail(function (error) {
// ok(false, error);
// }) })
// .always(function () {
// ]).always(start); start();
// });
// }); });
//
// test("Put & Get", function () { /////////////////////////////////////////////////////////////////
// expect(4); // DropboxStorage.remove
// var jio = jIO.createJIO({ /////////////////////////////////////////////////////////////////
// "type": "dropbox", module("DropboxStorage.remove", {
// "access_token": "v43SQLCEoi8AAAAAAAAAAVixCoMfDelgGj3NRPfE" + setup: function () {
// "nqscAuNGp2LhoS8-GiAaDD4C"
// }, { this.server = sinon.fakeServer.create();
// "workspace": {} this.server.autoRespond = true;
// }); this.server.autoRespondAfter = 5;
//
// stop(); this.jio = jIO.createJIO({
// type: "dropbox",
// // put non empty document access_token: token,
// jio.put({ root : "dropbox"
// "_id": "put1", });
// "title": "myPut1" },
// }).always(function (answer) { teardown: function () {
// this.server.restore();
// deepEqual(answer, { delete this.server;
// "id": "put1", }
// "method": "put", });
// "result": "success", test("remove document", function () {
// "status": 204, var url_delete = "https://api.dropboxapi.com/1/fileops/delete/?" +
// "statusText": "No Content" "access_token=" + token + "&root=dropbox&path=%2Fremove1%2F",
// }, "Creates a document"); server = this.server;
// this.server.respondWith("POST", url_delete, [204, {
// }).then(function () { "Content-Type": "text/xml"
// }, '']);
// return jio.get({ stop();
// "_id": "put1" expect(7);
// });
// this.jio.remove("/remove1/")
// }).always(function (answer) { .then(function () {
// equal(server.requests.length, 1);
// deepEqual(answer, { equal(server.requests[0].method, "POST");
// "data": { equal(server.requests[0].url, url_delete);
// "_id": "put1", equal(server.requests[0].status, 204);
// "title": "myPut1" equal(server.requests[0].requestBody, undefined);
// }, equal(server.requests[0].responseText, '');
// "id": "put1", deepEqual(server.requests[0].requestHeaders, {
// "method": "get", "Content-Type": "text/plain;charset=utf-8"
// "result": "success", });
// "status": 200, })
// "statusText": "Ok" .fail(function (error) {
// }, "Get, Check document"); ok(false, error);
// })
// }).then(function () { .always(function () {
// start();
// // put but document already exists });
// return jio.put({ });
// "_id": "put1",
// "title": "myPut2" test("reject ID not starting with /", function () {
// }); stop();
// expect(3);
// }).always(function (answer) {
// this.jio.remove("remove1/")
// deepEqual(answer, { .fail(function (error) {
// "id": "put1", ok(error instanceof jIO.util.jIOError);
// "method": "put", equal(error.message, "id remove1/ is forbidden (no begin /)");
// "result": "success", equal(error.status_code, 400);
// "status": 204, })
// "statusText": "No Content" .fail(function (error) {
// }, "Update the document"); ok(false, error);
// })
// }).then(function () { .always(function () {
// start();
// return jio.get({ });
// "_id": "put1" });
// });
// test("reject ID not ending with /", function () {
// }).always(function (answer) { stop();
// expect(3);
// deepEqual(answer, {
// "data": { this.jio.remove("/remove1")
// "_id": "put1", .fail(function (error) {
// "title": "myPut2" ok(error instanceof jIO.util.jIOError);
// }, equal(error.message, "id /remove1 is forbidden (no end /)");
// "id": "put1", equal(error.status_code, 400);
// "method": "get", })
// "result": "success", .fail(function (error) {
// "status": 200, ok(false, error);
// "statusText": "Ok" })
// }, "Get, Check document"); .always(function () {
// start();
// }).always(start); });
// });
// });
// /////////////////////////////////////////////////////////////////
// test("PutAttachment & Get & GetAttachment", function () { // DropboxStorage.get
// expect(10); /////////////////////////////////////////////////////////////////
// var jio = jIO.createJIO({ module("DropboxStorage.get", {
// "type": "dropbox", setup: function () {
// "access_token": "v43SQLCEoi8AAAAAAAAAAVixCoMfDelgGj3NRPfE" +
// "nqscAuNGp2LhoS8-GiAaDD4C" this.server = sinon.fakeServer.create();
// }, { this.server.autoRespond = true;
// "workspace": {} this.server.autoRespondAfter = 5;
// });
// this.jio = jIO.createJIO({
// stop(); type: "dropbox",
// access_token: token,
// all([ root : "dropbox"
// });
// // get an attachment from an inexistent document },
// jio.getAttachment({ teardown: function () {
// "_id": "inexistent", this.server.restore();
// "_attachment": "a" delete this.server;
// }).always(function (answer) { }
// });
// deepEqual(answer, {
// "attachment": "a", test("reject ID not starting with /", function () {
// "error": "not_found", stop();
// "id": "inexistent", expect(3);
// "message": "Unable to get attachment",
// "method": "getAttachment", this.jio.get("get1/")
// "reason": "Missing document", .fail(function (error) {
// "result": "error", ok(error instanceof jIO.util.jIOError);
// "status": 404, equal(error.message, "id get1/ is forbidden (no begin /)");
// "statusText": "Not Found" equal(error.status_code, 400);
// }, "GetAttachment from inexistent document"); })
// .fail(function (error) {
// }), ok(false, error);
// })
// // put a document then get an attachment from the empty document .always(function () {
// jio.put({ start();
// "_id": "b" });
// }).then(function () { });
// return jio.getAttachment({
// "_id": "b", test("reject ID not ending with /", function () {
// "_attachment": "inexistent" stop();
// }); expect(3);
//
// }).always(function (answer) { this.jio.get("/get1")
// .fail(function (error) {
// deepEqual(answer, { ok(error instanceof jIO.util.jIOError);
// "attachment": "inexistent", equal(error.message, "id /get1 is forbidden (no end /)");
// "error": "not_found", equal(error.status_code, 400);
// "id": "b", })
// "message": "Cannot find attachment", .fail(function (error) {
// "method": "getAttachment", ok(false, error);
// "reason": "Not Found", })
// "result": "error", .always(function () {
// "status": 404, start();
// "statusText": "Not Found" });
// }, "Get inexistent attachment"); });
//
// }), test("get inexistent document", function () {
// stop();
// // put an attachment to an inexistent document expect(3);
// jio.putAttachment({
// "_id": "inexistent", this.jio.get("/inexistent/")
// "_attachment": "putattmt2", .fail(function (error) {
// "_data": "" ok(error instanceof jIO.util.jIOError);
// }).always(function (answer) { equal(error.message, "Cannot find document: /inexistent/");
// equal(error.status_code, 404);
// deepEqual(answer, { })
// "attachment": "putattmt2", .fail(function (error) {
// "error": "not_found", ok(false, error);
// "id": "inexistent", })
// "message": "Impossible to add attachment", .always(function () {
// "method": "putAttachment", start();
// "reason": "Missing document", });
// "result": "error", });
// "status": 404,
// "statusText": "Not Found" test("get directory", function () {
// }, "PutAttachment to inexistent document"); var url = "https://api.dropboxapi.com/1/metadata/dropbox" +
// "/id1/?access_token=" + token;
// }), this.server.respondWith("GET", url, [200, {
// "Content-Type": "text/xml"
// // add a document to the storage }, '{"is_dir": true, "contents": []}'
// // don't need to be tested ]);
// jio.put({ stop();
// "_id": "putattmt1", expect(1);
// "title": "myPutAttmt1"
// }).then(function () { this.jio.get("/id1/")
// .then(function (result) {
// return jio.putAttachment({ deepEqual(result, {}, "Check document");
// "_id": "putattmt1", })
// "_attachment": "putattmt2", .fail(function (error) {
// "_data": "" ok(false, error);
// }); })
// .always(function () {
// }).always(function (answer) { start();
// });
// deepEqual(answer, { });
// "attachment": "putattmt2",
// "digest": "sha256-4ea5c508a6566e76240543f8feb06fd45" + test("get file", function () {
// "7777be39549c4016436afda65d2330e", var url = "https://api.dropboxapi.com/1/metadata/dropbox" +
// "id": "putattmt1", "/id1/?access_token=" + token;
// "method": "putAttachment", this.server.respondWith("GET", url, [200, {
// "result": "success", "Content-Type": "text/xml"
// "status": 201, }, '{"is_dir": false, "contents": []}'
// "statusText": "Created" ]);
// }, "PutAttachment to a document, without data"); stop();
// expect(3);
// }).then(function () {
// this.jio.get("/id1/")
// // check document and attachment .fail(function (error) {
// return all([ ok(error instanceof jIO.util.jIOError);
// jio.get({ equal(error.message, "Not a directory: /id1/");
// "_id": "putattmt1" equal(error.status_code, 404);
// }), })
// jio.getAttachment({ .fail(function (error) {
// "_id": "putattmt1", ok(false, error);
// "_attachment": "putattmt2" })
// }) .always(function () {
// ]); start();
// });
// // XXX check attachment with a getAttachment });
//
// }).always(function (answers) { /////////////////////////////////////////////////////////////////
// // DropboxStorage.allAttachments
// deepEqual(answers[0], { /////////////////////////////////////////////////////////////////
// "data": { module("DropboxStorage.allAttachments", {
// "_attachments": { setup: function () {
// "putattmt2": {
// "content_type": "", this.server = sinon.fakeServer.create();
// "digest": "sha256-4ea5c508a6566e76240543f8feb06fd45" + this.server.autoRespond = true;
// "7777be39549c4016436afda65d2330e", this.server.autoRespondAfter = 5;
// "length": 0
// } this.jio = jIO.createJIO({
// }, type: "dropbox",
// "_id": "putattmt1", access_token: token,
// "title": "myPutAttmt1" root : "dropbox"
// }, });
// "id": "putattmt1", },
// "method": "get", teardown: function () {
// "result": "success", this.server.restore();
// "status": 200, delete this.server;
// "statusText": "Ok" }
// }, "Get, Check document"); });
// ok(answers[1].data instanceof Blob, "Data is Blob");
// deepEqual(answers[1].data.type, "", "Check mimetype"); test("reject ID not starting with /", function () {
// deepEqual(answers[1].data.size, 0, "Check size"); stop();
// expect(3);
// delete answers[1].data;
// deepEqual(answers[1], { this.jio.allAttachments("get1/")
// "attachment": "putattmt2", .fail(function (error) {
// "id": "putattmt1", ok(error instanceof jIO.util.jIOError);
// "digest": "sha256-4ea5c508a6566e76240543f8feb06fd45" + equal(error.message, "id get1/ is forbidden (no begin /)");
// "7777be39549c4016436afda65d2330e", equal(error.status_code, 400);
// "method": "getAttachment", })
// "result": "success", .fail(function (error) {
// "status": 200, ok(false, error);
// "statusText": "Ok" })
// }, "Get Attachment, Check Response"); .always(function () {
// start();
// }) });
// });
// ]).then( function () {
// return jio.put({ test("reject ID not ending with /", function () {
// "_id": "putattmt1", stop();
// "foo": "bar", expect(3);
// "title": "myPutAttmt1"
// }); this.jio.allAttachments("/get1")
// }).then (function () { .fail(function (error) {
// return jio.get({ ok(error instanceof jIO.util.jIOError);
// "_id": "putattmt1" equal(error.message, "id /get1 is forbidden (no end /)");
// }); equal(error.status_code, 400);
// }).always(function (answer) { })
// .fail(function (error) {
// deepEqual(answer, { ok(false, error);
// "data": { })
// "_attachments": { .always(function () {
// "putattmt2": { start();
// "content_type": "", });
// "digest": "sha256-4ea5c508a6566e76240543f8feb06fd457777be39549c4016436afda65d2330e", });
// "length": 0
// } test("get file", function () {
// }, var url = "https://api.dropboxapi.com/1/metadata/dropbox" +
// "_id": "putattmt1", "/id1/?access_token=" + token;
// "foo": "bar", this.server.respondWith("GET", url, [200, {
// "title": "myPutAttmt1" "Content-Type": "text/xml"
// }, }, '{"is_dir": false, "contents": []}'
// "id": "putattmt1", ]);
// "method": "get", stop();
// "result": "success", expect(3);
// "status": 200,
// "statusText": "Ok" this.jio.allAttachments("/id1/")
// }, "Get, Check put kept document attachment"); .fail(function (error) {
// }) ok(error instanceof jIO.util.jIOError);
// .always(start); equal(error.message, "Not a directory: /id1/");
// equal(error.status_code, 404);
// }); })
// .fail(function (error) {
// test("Remove & RemoveAttachment", function () { ok(false, error);
// expect(5); })
// var jio = jIO.createJIO({ .always(function () {
// "type": "dropbox", start();
// "access_token": "v43SQLCEoi8AAAAAAAAAAVixCoMfDelgGj3NRPfE" + });
// "nqscAuNGp2LhoS8-GiAaDD4C" });
// }, {
// "workspace": {} test("get inexistent document", function () {
// }); stop();
// expect(3);
// stop();
// this.jio.allAttachments("/inexistent/")
// jio.put({ .fail(function (error) {
// "_id": "a" ok(error instanceof jIO.util.jIOError);
// }).then(function () { equal(error.message, "Cannot find document: /inexistent/");
// equal(error.status_code, 404);
// return jio.putAttachment({ })
// "_id": "a", .fail(function (error) {
// "_attachment": "b", ok(false, error);
// "_data": "c" })
// }); .always(function () {
// start();
// }).then(function () { });
// });
// return jio.removeAttachment({
// "_id": "a", test("get document without attachment", function () {
// "_attachment": "b" var url = "https://api.dropboxapi.com/1/metadata/dropbox" +
// }); "/id1/?access_token=" + token;
// this.server.respondWith("GET", url, [200, {
// }).always(function (answer) { "Content-Type": "text/xml"
// }, '{"is_dir": true, "contents": []}'
// deepEqual(answer, { ]);
// "attachment": "b", stop();
// "id": "a", expect(1);
// "method": "removeAttachment",
// "result": "success", this.jio.allAttachments("/id1/")
// "status": 200, .then(function (result) {
// "statusText": "Ok" deepEqual(result, {}, "Check document");
// }, "Remove existent attachment"); })
// .fail(function (error) {
// }).then(function () { ok(false, error);
// return jio.get({'_id' : "a"}); })
// }).always(function (answer) { .always(function () {
// deepEqual(answer, { start();
// "data": { });
// "_id": "a", });
// },
// "id": "a", test("get document with attachment", function () {
// "method": "get", var url = "https://api.dropboxapi.com/1/metadata/dropbox" +
// "result": "success", "/id1/?access_token=" + token;
// "status": 200, this.server.respondWith("GET", url, [200, {
// "statusText": "Ok" "Content-Type": "text/xml"
// }, "Attachment removed from metadata"); }, '{"is_dir": true, "path": "/id1", ' +
// '"contents": ' +
// }) '[{"rev": "143bb45509", ' +
// .then(function () { '"thumb_exists": false, ' +
// '"path": "/id1/attachment1", ' +
// // Promise.all always return success '"is_dir": false, "bytes": 151}, ' +
// return all([jio.removeAttachment({ '{"rev": "153bb45509", ' +
// "_id": "a", '"thumb_exists": false, ' +
// "_attachment": "b" '"path": "/id1/attachment2", ' +
// })]); '"is_dir": false, "bytes": 11}, ' +
// '{"rev": "173bb45509", ' +
// }).always(function (answers) { '"thumb_exists": false, ' +
// '"path": "/id1/fold1", ' +
// deepEqual(answers[0], { '"is_dir": true, "bytes": 0}], ' +
// "attachment": "b", '"icon": "folder"}'
// "error": "not_found", ]);
// "id": "a", stop();
// "message": "Attachment not found", expect(1);
// "method": "removeAttachment",
// "reason": "missing attachment", this.jio.allAttachments("/id1/")
// "result": "error", .then(function (result) {
// "status": 404, deepEqual(result, {
// "statusText": "Not Found" attachment1: {},
// }, "Remove removed attachment"); attachment2: {}
// }, "Check document");
// }).then(function () { })
// .fail(function (error) {
// return jio.remove({ ok(false, error);
// "_id": "a" })
// }); .always(function () {
// start();
// }).always(function (answer) { });
// });
// deepEqual(answer, {
// "id": "a", /////////////////////////////////////////////////////////////////
// "method": "remove", // DropboxStorage.putAttachment
// "result": "success", /////////////////////////////////////////////////////////////////
// "status": 200, module("DropboxStorage.putAttachment", {
// "statusText": "Ok" setup: function () {
// }, "Remove existent document");
// this.server = sinon.fakeServer.create();
// }).then(function () { this.server.autoRespond = true;
// this.server.autoRespondAfter = 5;
// return jio.remove({
// "_id": "a" this.jio = jIO.createJIO({
// }); type: "dropbox",
// access_token: token,
// }).always(function (answer) { root : "dropbox"
// });
// deepEqual(answer, { },
// "error": "not_found", teardown: function () {
// "id": "a", this.server.restore();
// "message": "Document not found", delete this.server;
// "method": "remove", }
// "reason": "Not Found", });
// "result": "error",
// "status": 404, test("reject ID not starting with /", function () {
// "statusText": "Not Found" stop();
// }, "Remove removed document"); expect(3);
//
// }).always(start); this.jio.putAttachment(
// "putAttachment1/",
// }); "attachment1",
// new Blob([""])
// test("AllDocs", function () { )
// expect(2); .fail(function (error) {
// var shared = {}, jio; ok(error instanceof jIO.util.jIOError);
// jio = jIO.createJIO({ equal(error.message, "id putAttachment1/ is forbidden (no begin /)");
// "type": "dropbox", equal(error.status_code, 400);
// "access_token": "v43SQLCEoi8AAAAAAAAAAVixCoMfDelgGj3NRPfE" + })
// "nqscAuNGp2LhoS8-GiAaDD4C", .fail(function (error) {
// "application_name": "AllDocs-test" ok(false, error);
// }, { })
// "workspace": {} .always(function () {
// }); start();
// });
// stop(); });
//
// shared.date_a = new Date(0); test("reject ID not ending with /", function () {
// shared.date_b = new Date(); stop();
// expect(3);
// // Clean storage and put some document before listing them
// all([ this.jio.putAttachment(
// jio.allDocs() "/putAttachment1",
// .then(function (document_list) { "attachment1",
// var promise_list = [], i; new Blob([""])
// for (i = 0; i < document_list.data.total_rows; i += 1) { )
// promise_list.push( .fail(function (error) {
// jio.remove({ ok(error instanceof jIO.util.jIOError);
// '_id': document_list.data.rows[i].id equal(error.message, "id /putAttachment1 is forbidden (no end /)");
// }) equal(error.status_code, 400);
// ); })
// } .fail(function (error) {
// return RSVP.all(promise_list); ok(false, error);
// }) })
// ]) .always(function () {
// .then(function () { start();
// return RSVP.all([ });
// jio.put({ });
// "_id": "a",
// "title": "one", test("reject attachment with / character", function () {
// "date": shared.date_a stop();
// }).then(function () { expect(3);
// return jio.putAttachment({
// "_id": "a", this.jio.putAttachment(
// "_attachment": "aa", "/putAttachment1/",
// "_data": "aaa" "attach/ment1",
// }); new Blob([""])
// }), )
// jio.put({ .fail(function (error) {
// "_id": "b", ok(error instanceof jIO.util.jIOError);
// "title": "two", equal(error.message, "attachment attach/ment1 is forbidden");
// "date": shared.date_a equal(error.status_code, 400);
// }), })
// jio.put({ .fail(function (error) {
// "_id": "c", ok(false, error);
// "title": "one", })
// "date": shared.date_b .always(function () {
// }), start();
// jio.put({ });
// "_id": "d", });
// "title": "two",
// "date": shared.date_b test("putAttachment document", function () {
// }) var blob = new Blob(["foo"]),
// ]); url_put_att = "https://content.dropboxapi.com/1/files_put/dropbox"
// }).then(function () { + "/putAttachment1/"
// + "attachment1?access_token=" + token,
// // get a list of documents server = this.server;
// return jio.allDocs();
// this.server.respondWith("PUT", url_put_att, [204, {
// }).always(function (answer) { "Content-Type": "text/xml"
// }, ""]);
// // sort answer rows for comparison
// if (answer.data && answer.data.rows) { stop();
// answer.data.rows.sort(function (a, b) { expect(7);
// return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
// }); this.jio.putAttachment(
// } "/putAttachment1/",
// "attachment1",
// deepEqual(answer, { blob
// "data": { )
// "rows": [{ .then(function () {
// "id": "a", equal(server.requests.length, 1);
// "value": {}
// }, { equal(server.requests[0].method, "PUT");
// "id": "b", equal(server.requests[0].url, url_put_att);
// "value": {} equal(server.requests[0].status, 204);
// }, { equal(server.requests[0].responseText, "");
// "id": "c", deepEqual(server.requests[0].requestHeaders, {
// "value": {} "Content-Type": "text/plain;charset=utf-8"
// }, { });
// "id": "d", equal(server.requests[0].requestBody, blob);
// "value": {} })
// }], .fail(function (error) {
// "total_rows": 4 ok(false, error);
// }, })
// "method": "allDocs", .always(function () {
// "result": "success", start();
// "status": 200, });
// "statusText": "Ok" });
// }, "AllDocs");
// /////////////////////////////////////////////////////////////////
// }).then(function () { // DropboxStorage.removeAttachment
// /////////////////////////////////////////////////////////////////
// // get a list of documents module("DropboxStorage.removeAttachment", {
// return jio.allDocs({ setup: function () {
// "include_docs": true
// }); this.server = sinon.fakeServer.create();
// this.server.autoRespond = true;
// }).always(function (answer) { this.server.autoRespondAfter = 5;
//
// deepEqual(answer, { this.jio = jIO.createJIO({
// "data": { type: "dropbox",
// "rows": [{ access_token: token,
// "doc": { root : "dropbox"
// "_attachments": { });
// "aa": { },
// "content_type": "", teardown: function () {
// "digest": "sha256-4ea5c508a6566e76240543f8feb06fd45" + this.server.restore();
// "7777be39549c4016436afda65d2330e", delete this.server;
// "length": 3 }
// } });
// },
// "_id": "a", test("reject ID not starting with /", function () {
// "date": shared.date_a.toJSON(), stop();
// "title": "one" expect(3);
// },
// "id": "a", this.jio.removeAttachment(
// "value": {} "removeAttachment1/",
// }, { "attachment1"
// "doc": { )
// "_id": "b", .fail(function (error) {
// "date": shared.date_a.toJSON(), ok(error instanceof jIO.util.jIOError);
// "title": "two" equal(error.message, "id removeAttachment1/ is forbidden (no begin /)");
// }, equal(error.status_code, 400);
// "id": "b", })
// "value": {} .fail(function (error) {
// }, { ok(false, error);
// "doc": { })
// "_id": "c", .always(function () {
// "date": shared.date_b.toJSON(), start();
// "title": "one" });
// }, });
// "id": "c",
// "value": {} test("reject ID not ending with /", function () {
// }, { stop();
// "doc": { expect(3);
// "_id": "d",
// "date": shared.date_b.toJSON(), this.jio.removeAttachment(
// "title": "two" "/removeAttachment1",
// }, "attachment1"
// "id": "d", )
// "value": {} .fail(function (error) {
// }], ok(error instanceof jIO.util.jIOError);
// "total_rows": 4 equal(error.message, "id /removeAttachment1 is forbidden (no end /)");
// }, equal(error.status_code, 400);
// "method": "allDocs", })
// "result": "success", .fail(function (error) {
// "status": 200, ok(false, error);
// "statusText": "Ok" })
// }, "AllDocs include docs"); .always(function () {
// start();
// }).always(start); });
// });
// });
test("reject attachment with / character", function () {
}(jIO, QUnit)); 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_delete = "https://api.dropboxapi.com/1/fileops/delete/" +
"?access_token=" + token + "&root=dropbox" +
"&path=%2FremoveAttachment1%2Fattachment1",
server = this.server;
this.server.respondWith("POST", url_delete, [204, {
"Content-Type": "text/xml"
}, ""]);
stop();
expect(7);
this.jio.removeAttachment(
"/removeAttachment1/",
"attachment1"
)
.then(function () {
equal(server.requests.length, 1);
equal(server.requests[0].method, "POST");
equal(server.requests[0].url, url_delete);
equal(server.requests[0].status, 204);
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("remove inexistent attachment", function () {
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,
root : "dropbox"
});
},
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/" +
"%2FgetAttachment1%2Fattachment1?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 () {
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));
...@@ -212,11 +212,17 @@ ...@@ -212,11 +212,17 @@
type: "DateTimeField" type: "DateTimeField"
}, },
your_reference: { your_reference: {
key: "field_your_title", key: "field_your_reference",
"default": "bar", "default": "bar",
editable: true, editable: true,
type: "StringField" type: "StringField"
}, },
your_reference_non_editable: {
key: "field_your_reference_non_editable",
"default": "bar",
editable: false,
type: "StringField"
},
sort_index: { sort_index: {
key: "field_sort_index", key: "field_sort_index",
"default": "foobar", "default": "foobar",
...@@ -247,6 +253,8 @@ ...@@ -247,6 +253,8 @@
.then(function (result) { .then(function (result) {
deepEqual(result, { deepEqual(result, {
portal_type: "Person", portal_type: "Person",
reference: "bar",
reference_non_editable: "bar",
title: "foo" title: "foo"
}, "Check document"); }, "Check document");
equal(server.requests.length, 2); equal(server.requests.length, 2);
...@@ -1150,11 +1158,17 @@ ...@@ -1150,11 +1158,17 @@
type: "DateTimeField" type: "DateTimeField"
}, },
your_reference: { your_reference: {
key: "field_your_title", key: "field_your_reference",
"default": "bar", "default": "bar",
editable: true, editable: true,
type: "StringField" type: "StringField"
}, },
your_reference_non_editable: {
key: "field_your_reference_non_editable",
"default": "bar",
editable: false,
type: "StringField"
},
sort_index: { sort_index: {
key: "field_sort_index", key: "field_sort_index",
"default": "foobar", "default": "foobar",
...@@ -1182,9 +1196,9 @@ ...@@ -1182,9 +1196,9 @@
}, ""]); }, ""]);
stop(); stop();
expect(21); expect(23);
this.jio.put(id, {title: "barè", id: "foo"}) this.jio.put(id, {title: "barè", id: "foo", reference: "bar2"})
.then(function (result) { .then(function (result) {
equal(result, id); equal(result, id);
equal(server.requests.length, 3); equal(server.requests.length, 3);
...@@ -1201,7 +1215,7 @@ ...@@ -1201,7 +1215,7 @@
ok(server.requests[2].requestBody instanceof FormData); ok(server.requests[2].requestBody instanceof FormData);
equal(server.requests[2].withCredentials, true); equal(server.requests[2].withCredentials, true);
equal(context.spy.callCount, 3, "FormData.append count"); equal(context.spy.callCount, 4, "FormData.append count");
equal(context.spy.firstCall.args[0], "form_id", "First append call"); equal(context.spy.firstCall.args[0], "form_id", "First append call");
equal(context.spy.firstCall.args[1], "Base_view", "First append call"); equal(context.spy.firstCall.args[1], "Base_view", "First append call");
equal(context.spy.secondCall.args[0], "field_my_title", equal(context.spy.secondCall.args[0], "field_my_title",
...@@ -1210,6 +1224,9 @@ ...@@ -1210,6 +1224,9 @@
equal(context.spy.thirdCall.args[0], "field_my_id", equal(context.spy.thirdCall.args[0], "field_my_id",
"Third append call"); "Third append call");
equal(context.spy.thirdCall.args[1], "foo", "Third append call"); equal(context.spy.thirdCall.args[1], "foo", "Third append call");
equal(context.spy.getCall(3).args[0], "field_your_reference",
"Fourth append call");
equal(context.spy.getCall(3).args[1], "bar2", "Fourth append call");
}) })
.fail(function (error) { .fail(function (error) {
ok(false, error); ok(false, error);
...@@ -1265,11 +1282,17 @@ ...@@ -1265,11 +1282,17 @@
type: "DateTimeField" type: "DateTimeField"
}, },
your_reference: { your_reference: {
key: "field_your_title", key: "field_your_reference",
"default": "bar", "default": "bar",
editable: true, editable: true,
type: "StringField" type: "StringField"
}, },
your_reference_non_editable: {
key: "field_your_reference_non_editable",
"default": "bar",
editable: false,
type: "StringField"
},
sort_index: { sort_index: {
key: "field_sort_index", key: "field_sort_index",
"default": "foobar", "default": "foobar",
...@@ -1389,7 +1412,7 @@ ...@@ -1389,7 +1412,7 @@
type: "DateTimeField" type: "DateTimeField"
}, },
your_reference: { your_reference: {
key: "field_your_title", key: "field_your_reference",
"default": "bar", "default": "bar",
editable: true, editable: true,
type: "StringField" type: "StringField"
...@@ -1425,13 +1448,14 @@ ...@@ -1425,13 +1448,14 @@
}, ""]); }, ""]);
stop(); stop();
expect(33); expect(35);
this.jio.post({ this.jio.post({
title: "barè", title: "barè",
id: "foo", id: "foo",
portal_type: "Foo", portal_type: "Foo",
parent_relative_url: "foo_module" parent_relative_url: "foo_module",
reference: "bar2"
}) })
.then(function (result) { .then(function (result) {
equal(result, id); equal(result, id);
...@@ -1462,7 +1486,7 @@ ...@@ -1462,7 +1486,7 @@
ok(server.requests[4].requestBody instanceof FormData); ok(server.requests[4].requestBody instanceof FormData);
equal(server.requests[4].withCredentials, true); equal(server.requests[4].withCredentials, true);
equal(context.spy.callCount, 5, "FormData.append count"); equal(context.spy.callCount, 6, "FormData.append count");
equal(context.spy.firstCall.args[0], "portal_type", equal(context.spy.firstCall.args[0], "portal_type",
"First append call"); "First append call");
...@@ -1480,6 +1504,9 @@ ...@@ -1480,6 +1504,9 @@
equal(context.spy.getCall(4).args[0], "field_my_id", equal(context.spy.getCall(4).args[0], "field_my_id",
"Fifth append call"); "Fifth append call");
equal(context.spy.getCall(4).args[1], "foo", "Fifth append call"); equal(context.spy.getCall(4).args[1], "foo", "Fifth append call");
equal(context.spy.getCall(5).args[0], "field_your_reference",
"Sixth append call");
equal(context.spy.getCall(5).args[1], "bar2", "Sixth append call");
}) })
.fail(function (error) { .fail(function (error) {
ok(false, error); ok(false, error);
...@@ -1560,11 +1587,17 @@ ...@@ -1560,11 +1587,17 @@
type: "DateTimeField" type: "DateTimeField"
}, },
your_reference: { your_reference: {
key: "field_your_title", key: "field_your_reference",
"default": "bar", "default": "bar",
editable: true, editable: true,
type: "StringField" type: "StringField"
}, },
your_reference_non_editable: {
key: "field_your_reference_non_editable",
"default": "bar",
editable: false,
type: "StringField"
},
sort_index: { sort_index: {
key: "field_sort_index", key: "field_sort_index",
"default": "foobar", "default": "foobar",
...@@ -1661,6 +1694,8 @@ ...@@ -1661,6 +1694,8 @@
equal(result_list.length, 2); equal(result_list.length, 2);
deepEqual(result, { deepEqual(result, {
portal_type: "Person", portal_type: "Person",
reference: "bar",
reference_non_editable: "bar",
title: "foo" title: "foo"
}, "Check document"); }, "Check document");
deepEqual(result2, { deepEqual(result2, {
......
...@@ -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