commit fc1137b7695697c5eb13c5eb1fc79cc026a1f73e
parent 2df630e83c5158d639e9776a435713867aef51c3
Author: Dan Stillman <dstillman@zotero.org>
Date: Sun, 9 Aug 2015 04:52:14 -0400
Asyncify Zotero.Attachments.getTotalFileSize()
Diffstat:
2 files changed, 40 insertions(+), 22 deletions(-)
diff --git a/chrome/content/zotero/xpcom/attachments.js b/chrome/content/zotero/xpcom/attachments.js
@@ -1050,15 +1050,13 @@ Zotero.Attachments = new function(){
/**
- * @param {Zotero.Item} item
- * @param {Boolean} [skipHidden=FALSE] Don't count hidden files
- * @return {Integer} Total file size in bytes
+ * @param {Zotero.Item} item
+ * @param {Boolean} [skipHidden=true] - Don't count hidden files
+ * @return {Promise<Integer>} - Promise for the total file size in bytes
*/
- this.getTotalFileSize = function (item, skipHidden) {
- var funcName = "Zotero.Attachments.getTotalFileSize()";
-
+ this.getTotalFileSize = Zotero.Promise.coroutine(function* (item, skipHidden = true) {
if (!item.isAttachment()) {
- throw ("Item is not an attachment in " + funcName);
+ throw new Error("Item is not an attachment");
}
var linkMode = item.attachmentLinkMode;
@@ -1069,31 +1067,37 @@ Zotero.Attachments = new function(){
break;
default:
- throw ("Invalid attachment link mode in " + funcName);
+ throw new Error("Invalid attachment link mode");
}
- var file = item.getFile();
- if (!file) {
- throw ("File not found in " + funcName);
+ var path = yield item.getFilePathAsync();
+ if (!path) {
+ throw new Error("File not found");
}
if (linkMode == Zotero.Attachments.LINK_MODE_LINKED_FILE) {
- return item.fileSize;
+ return (yield OS.File.stat(path)).size;
}
- var parentDir = file.parent;
- var files = parentDir.directoryEntries;
var size = 0;
- while (files.hasMoreElements()) {
- file = files.getNext();
- file.QueryInterface(Components.interfaces.nsIFile);
- if (skipHidden && file.leafName.indexOf('.') == 0) {
- continue;
- }
- size += file.fileSize;
+ var parent = OS.Path.dirname(path);
+ let iterator = new OS.File.DirectoryIterator(parent);
+ try {
+ yield iterator.forEach(function (entry) {
+ if (skipHidden && entry.name.startsWith('.')) {
+ return;
+ }
+ return OS.File.stat(entry.path)
+ .then(function (info) {
+ size += info.size;
+ });
+ })
+ }
+ finally {
+ iterator.close();
}
return size;
- }
+ });
/**
diff --git a/test/tests/attachmentsTest.js b/test/tests/attachmentsTest.js
@@ -111,4 +111,18 @@ describe("Zotero.Attachments", function() {
// Should create a group library for use by all tests
})
})
+
+ describe("#getTotalFileSize", function () {
+ it("should return the size for a single-file attachment", function* () {
+ var file = getTestDataDirectory();
+ file.append('test.png');
+
+ // Create attachment and compare content
+ var item = yield Zotero.Attachments.importFromFile({
+ file: file
+ });
+
+ assert.equal((yield Zotero.Attachments.getTotalFileSize(item)), file.fileSize);
+ })
+ })
})