Replace Bluebird with async in xpcom/

This commit is contained in:
Abe Jellinek 2025-06-30 12:59:33 -04:00 • committed by Dan Stillman
parent 8d0923f119
commit 05d19fc6aa
88 changed files with 2736 additions and 2742 deletions

View file

@ -38,7 +38,7 @@ Zotero.API = {
/**
* @return {(Zotero.Collection|Zotero.Search|Zotero.Item)[]}
*/
getResultsFromParams: Zotero.Promise.coroutine(function* (params) {
getResultsFromParams: async function (params) {
if (!params.objectType) {
throw new Error("objectType not specified");
}
@ -93,7 +93,7 @@ Zotero.API = {
var s2 = new Zotero.Search();
s2.setScope(s);
var ids = yield s2.search();
var ids = await s2.search();
if (params.objectKey) {
let id = Zotero.Items.getIDFromLibraryAndKey(s.libraryID, params.objectKey);
ids = ids.includes(id) ? [id] : [];
@ -128,7 +128,7 @@ Zotero.API = {
s.addCondition('noChildren', 'true');
}*/
var ids = yield s.search();
var ids = await s.search();
}
let itemKeys = new Set(params.itemKey || []);
@ -146,7 +146,7 @@ Zotero.API = {
return itemKeys.has(key);
});
}
results = yield Zotero.Items.getAsync(ids);
results = await Zotero.Items.getAsync(ids);
}
}
else {
@ -154,7 +154,7 @@ Zotero.API = {
}
return results;
}),
},
getLibraryPrefix: function (libraryID) {

View file

@ -56,7 +56,7 @@ Zotero.Attachments = new function () {
* @param {Object} [options.saveOptions] - Options to pass to Zotero.Item::save()
* @return {Promise<Zotero.Item>}
*/
this.importFromFile = Zotero.Promise.coroutine(function* (options) {
this.importFromFile = async function (options) {
Zotero.debug('Importing attachment from file');
var libraryID = options.libraryID;
@ -88,7 +88,7 @@ Zotero.Attachments = new function () {
var attachmentItem, newFile, destDir;
try {
yield Zotero.DB.executeTransaction(async function () {
await Zotero.DB.executeTransaction(async function () {
// Create a new attachment
attachmentItem = new Zotero.Item('attachment');
if (parentItemID) {
@ -143,7 +143,7 @@ Zotero.Attachments = new function () {
await attachmentItem.save(saveOptions);
}.bind(this));
try {
yield _postProcessFile(attachmentItem);
await _postProcessFile(attachmentItem);
}
catch (e) {
Zotero.logError(e);
@ -155,8 +155,8 @@ Zotero.Attachments = new function () {
// Clean up
try {
if (destDir && (yield OS.File.exists(destDir))) {
yield OS.File.removeDir(destDir);
if (destDir && ((await OS.File.exists(destDir)))) {
await OS.File.removeDir(destDir);
}
}
catch (e) {
@ -167,7 +167,7 @@ Zotero.Attachments = new function () {
}
return attachmentItem;
});
};
/**
@ -180,14 +180,14 @@ Zotero.Attachments = new function () {
* @param {Object} [options.saveOptions] - Options to pass to Zotero.Item::save()
* @return {Promise<Zotero.Item>}
*/
this.linkFromFile = Zotero.Promise.coroutine(function* (options) {
this.linkFromFile = async function (options) {
Zotero.debug('Linking attachment from file');
var file = Zotero.File.pathToFile(options.file);
var parentItemID = options.parentItemID;
var title = options.title;
var collections = options.collections;
var contentType = options.contentType || (yield Zotero.MIME.getMIMETypeFromFile(file));
var contentType = options.contentType || ((await Zotero.MIME.getMIMETypeFromFile(file)));
var charset = options.charset;
var saveOptions = options.saveOptions;
@ -195,7 +195,7 @@ Zotero.Attachments = new function () {
throw new Error("parentItemID and collections cannot both be provided");
}
var item = yield _addToDB({
var item = await _addToDB({
file,
title,
linkMode: this.LINK_MODE_LINKED_FILE,
@ -206,13 +206,13 @@ Zotero.Attachments = new function () {
saveOptions
});
try {
yield _postProcessFile(item);
await _postProcessFile(item);
}
catch (e) {
Zotero.logError(e);
}
return item;
});
};
/**
@ -268,7 +268,7 @@ Zotero.Attachments = new function () {
// If the file is found (which requires a base directory being set and the file existing),
// index it
var file = this.resolveRelativePath(path);
if (file && await OS.File.exists(file)) {
if (file && (await OS.File.exists(file))) {
try {
await _postProcessFile(item);
}
@ -286,7 +286,7 @@ Zotero.Attachments = new function () {
* @param {Object} [options.saveOptions] - Options to pass to Zotero.Item::save()
* @return {Promise<Zotero.Item>}
*/
this.importSnapshotFromFile = Zotero.Promise.coroutine(function* (options) {
this.importSnapshotFromFile = async function (options) {
Zotero.debug('Importing snapshot from file');
var file = Zotero.File.pathToFile(options.file);
@ -317,7 +317,7 @@ Zotero.Attachments = new function () {
var attachmentItem, itemID, destDir, newPath;
try {
yield Zotero.DB.executeTransaction(async function () {
await Zotero.DB.executeTransaction(async function () {
// Create a new attachment
attachmentItem = new Zotero.Item('attachment');
if (libraryID) {
@ -356,7 +356,7 @@ Zotero.Attachments = new function () {
}
}.bind(this));
try {
yield _postProcessFile(attachmentItem);
await _postProcessFile(attachmentItem);
}
catch (e) {
Zotero.logError(e);
@ -378,7 +378,7 @@ Zotero.Attachments = new function () {
throw e;
}
return attachmentItem;
});
};
/**
@ -489,7 +489,7 @@ Zotero.Attachments = new function () {
throw new Error("'attachment' must be an embedded image");
}
if (!await attachment.fileExists()) {
if (!(await attachment.fileExists())) {
throw new Error("Image attachment file doesn't exist");
}
@ -522,7 +522,7 @@ Zotero.Attachments = new function () {
* @param {Object} [options.saveOptions] - Options to pass to Zotero.Item::save()
* @return {Promise<Zotero.Item>} - A promise for the created attachment item
*/
this.importFromURL = Zotero.Promise.coroutine(function* (options) {
this.importFromURL = async function (options) {
var libraryID = options.libraryID;
var url = options.url;
var parentItemID = options.parentItemID;
@ -654,9 +654,9 @@ Zotero.Attachments = new function () {
return process(contentType, Zotero.MIME.hasNativeHandler(contentType));
}
var args = yield Zotero.MIME.getMIMETypeFromURL(url, cookieSandbox);
var args = await Zotero.MIME.getMIMETypeFromURL(url, cookieSandbox);
return process(...args);
});
};
/**
@ -743,7 +743,7 @@ Zotero.Attachments = new function () {
* @param {Object} [options.saveOptions] - Options to pass to Zotero.Item::save()
* @return {Promise<Zotero.Item>} - A promise for the created attachment item
*/
this.linkFromURL = Zotero.Promise.coroutine(function* (options) {
this.linkFromURL = async function (options) {
Zotero.debug('Linking attachment from URL');
var url = options.url;
@ -807,7 +807,7 @@ Zotero.Attachments = new function () {
collections,
saveOptions,
});
});
};
/**
@ -817,7 +817,7 @@ Zotero.Attachments = new function () {
* @param {Object} [options.saveOptions] - Options to pass to Zotero.Item::save()
* @return {Promise<Zotero.Item>}
*/
this.linkFromDocument = Zotero.Promise.coroutine(function* (options) {
this.linkFromDocument = async function (options) {
Zotero.debug('Linking attachment from document');
var document = options.document;
@ -833,7 +833,7 @@ Zotero.Attachments = new function () {
var title = document.title; // TODO: don't use Mozilla-generated title for images, etc.
var contentType = document.contentType;
var item = yield _addToDB({
var item = await _addToDB({
url,
title,
linkMode: this.LINK_MODE_LINKED_URL,
@ -845,11 +845,11 @@ Zotero.Attachments = new function () {
});
if (Zotero.MIME.isTextType(document.contentType)) {
yield Zotero.Fulltext.indexDocument(document, item.id);
await Zotero.Fulltext.indexDocument(document, item.id);
}
return item;
});
};
/**
@ -859,7 +859,7 @@ Zotero.Attachments = new function () {
* @param {Object} [options.saveOptions] - Options to pass to Zotero.Item::save()
* @return {Promise<Zotero.Item>} - A promise for the created attachment item
*/
this.importFromDocument = Zotero.Promise.coroutine(function* (options) {
this.importFromDocument = async function (options) {
Zotero.debug('Importing attachment from ' + (options.document ? 'document' : 'browser'));
var libraryID = options.libraryID;
@ -885,7 +885,7 @@ Zotero.Attachments = new function () {
contentType = "application/pdf";
}
var tmpDir = (yield this.createTemporaryStorageDirectory()).path;
var tmpDir = ((await this.createTemporaryStorageDirectory())).path;
try {
var fileName = Zotero.File.truncateFileName(this._getFileNameFromURL(url, contentType), 100);
var tmpFile = OS.Path.join(tmpDir, fileName);
@ -909,24 +909,24 @@ Zotero.Attachments = new function () {
if (browser) {
// If we have a full hidden browser, use SingleFile
Zotero.debug('Getting snapshot with HiddenBrowser.snapshot()');
let snapshotContent = yield browser.snapshot();
let snapshotContent = await browser.snapshot();
// Write main HTML file to disk
yield Zotero.File.putContentsAsync(tmpFile, snapshotContent);
await Zotero.File.putContentsAsync(tmpFile, snapshotContent);
}
else {
// Fallback to nsIWebBrowserPersist
Zotero.debug('Saving document with saveDocument()');
yield Zotero.Utilities.Internal.saveDocument(document, tmpFile);
await Zotero.Utilities.Internal.saveDocument(document, tmpFile);
}
}
else {
yield Zotero.HTTP.download(url, tmpFile);
await Zotero.HTTP.download(url, tmpFile);
}
var attachmentItem;
var destDir;
yield Zotero.DB.executeTransaction(async function () {
await Zotero.DB.executeTransaction(async function () {
// Create a new attachment
attachmentItem = new Zotero.Item('attachment');
if (libraryID) {
@ -954,7 +954,7 @@ Zotero.Attachments = new function () {
await OS.File.move(tmpDir, destDir);
}.bind(this));
yield Zotero.FullText.queueItem(attachmentItem);
await Zotero.FullText.queueItem(attachmentItem);
}
catch (e) {
Zotero.debug(e, 1);
@ -962,10 +962,10 @@ Zotero.Attachments = new function () {
// Clean up
try {
if (tmpDir) {
yield OS.File.removeDir(tmpDir, { ignoreAbsent: true });
await OS.File.removeDir(tmpDir, { ignoreAbsent: true });
}
if (destDir) {
yield OS.File.removeDir(destDir, { ignoreAbsent: true });
await OS.File.removeDir(destDir, { ignoreAbsent: true });
}
}
catch (e) {
@ -976,7 +976,7 @@ Zotero.Attachments = new function () {
}
return attachmentItem;
});
};
/**
* Save an attachment from a nsIInputStream
@ -1238,7 +1238,7 @@ Zotero.Attachments = new function () {
}
this.InvalidPDFException = function() {
this.InvalidPDFException = function () {
this.message = "Downloaded file was not a supported type (PDF or EPUB)";
this.stack = new Error().stack;
};
@ -2630,7 +2630,7 @@ Zotero.Attachments = new function () {
* @param {Number} itemID - Item id
* @return {Promise<String>} - Path of new directory
*/
this.createDirectoryForItem = Zotero.Promise.coroutine(function* (item) {
this.createDirectoryForItem = async function (item) {
if (!(item instanceof Zotero.Item)) {
throw new Error("'item' must be a Zotero.Item");
}
@ -2643,11 +2643,11 @@ Zotero.Attachments = new function () {
}
}
else {
yield OS.File.removeDir(dir, { ignoreAbsent: true });
await OS.File.removeDir(dir, { ignoreAbsent: true });
}
yield Zotero.File.createDirectoryIfMissingAsync(dir);
await Zotero.File.createDirectoryIfMissingAsync(dir);
return dir;
});
};
this.getStorageDirectory = function (item) {
@ -2686,14 +2686,14 @@ Zotero.Attachments = new function () {
}
this.createTemporaryStorageDirectory = Zotero.Promise.coroutine(function* () {
this.createTemporaryStorageDirectory = async function () {
var tmpDir = Zotero.getStorageDirectory();
tmpDir.append("tmp-" + Zotero.Utilities.randomString(6));
yield OS.File.makeDir(tmpDir.path, {
await OS.File.makeDir(tmpDir.path, {
unixMode: 0o755
});
return tmpDir;
});
};
/**
@ -2758,7 +2758,7 @@ Zotero.Attachments = new function () {
}
this.hasMultipleFiles = Zotero.Promise.coroutine(function* (item) {
this.hasMultipleFiles = async function (item) {
if (!item.isAttachment()) {
throw new Error("Item is not an attachment");
}
@ -2780,7 +2780,7 @@ Zotero.Attachments = new function () {
return false;
}
var path = yield item.getFilePathAsync();
var path = await item.getFilePathAsync();
if (!path) {
throw new Error("File not found");
}
@ -2789,7 +2789,7 @@ Zotero.Attachments = new function () {
var parent = PathUtils.parent(path);
var iterator = new OS.File.DirectoryIterator(parent);
try {
yield iterator.forEach((entry) => {
await iterator.forEach((entry) => {
if (entry.name.startsWith('.')) {
return;
}
@ -2803,7 +2803,7 @@ Zotero.Attachments = new function () {
iterator.close();
}
return numFiles > 1;
});
};
/**
@ -2813,7 +2813,7 @@ Zotero.Attachments = new function () {
*
* @param {Zotero.Item} item Attachment item
*/
this.getNumFiles = Zotero.Promise.coroutine(function* (item) {
this.getNumFiles = async function (item) {
if (!item.isAttachment()) {
throw new Error("Item is not an attachment");
}
@ -2832,7 +2832,7 @@ Zotero.Attachments = new function () {
return 1;
}
var path = yield item.getFilePathAsync();
var path = await item.getFilePathAsync();
if (!path) {
throw new Error("File not found");
}
@ -2841,7 +2841,7 @@ Zotero.Attachments = new function () {
var parent = PathUtils.parent(path);
var iterator = new OS.File.DirectoryIterator(parent);
try {
yield iterator.forEach(function (entry) {
await iterator.forEach(function (entry) {
if (entry.name.startsWith('.')) {
return;
}
@ -2852,7 +2852,7 @@ Zotero.Attachments = new function () {
iterator.close();
}
return numFiles;
});
};
/**
@ -2860,7 +2860,7 @@ Zotero.Attachments = new function () {
* @param {Boolean} [skipHidden=true] - Don't count hidden files
* @return {Promise<Integer>} - Promise for the total file size in bytes
*/
this.getTotalFileSize = Zotero.Promise.coroutine(function* (item, skipHidden = true) {
this.getTotalFileSize = async function (item, skipHidden = true) {
if (!item.isAttachment()) {
throw new Error("Item is not an attachment");
}
@ -2876,20 +2876,20 @@ Zotero.Attachments = new function () {
throw new Error("Invalid attachment link mode");
}
var path = yield item.getFilePathAsync();
var path = await item.getFilePathAsync();
if (!path) {
throw new Error("File not found");
}
if (linkMode == Zotero.Attachments.LINK_MODE_LINKED_FILE) {
return (yield OS.File.stat(path)).size;
return ((await OS.File.stat(path))).size;
}
var size = 0;
var parent = PathUtils.parent(path);
let iterator = new OS.File.DirectoryIterator(parent);
try {
yield iterator.forEach(function (entry) {
await iterator.forEach(function (entry) {
if (skipHidden && entry.name.startsWith('.')) {
return;
}
@ -2914,7 +2914,7 @@ Zotero.Attachments = new function () {
iterator.close();
}
return size;
});
};
/**
@ -2986,7 +2986,7 @@ Zotero.Attachments = new function () {
*
* @return {Zotero.Item} - The new attachment
*/
this.copyAttachmentToLibrary = Zotero.Promise.coroutine(function* (attachment, libraryID, parentItemID) {
this.copyAttachmentToLibrary = async function (attachment, libraryID, parentItemID) {
if (attachment.libraryID == libraryID) {
throw new Error("Attachment is already in library " + libraryID);
}
@ -3001,18 +3001,18 @@ Zotero.Attachments = new function () {
if (parentItemID) {
newAttachment.parentID = parentItemID;
}
yield newAttachment.save();
await newAttachment.save();
// Copy over files if they exist
if (newAttachment.isStoredFileAttachment() && (yield attachment.fileExists())) {
if (newAttachment.isStoredFileAttachment() && ((await attachment.fileExists()))) {
let dir = Zotero.Attachments.getStorageDirectory(attachment);
let newDir = yield Zotero.Attachments.createDirectoryForItem(newAttachment);
yield Zotero.File.copyDirectory(dir, newDir);
let newDir = await Zotero.Attachments.createDirectoryForItem(newAttachment);
await Zotero.File.copyDirectory(dir, newDir);
}
yield newAttachment.addLinkedItem(attachment);
await newAttachment.addLinkedItem(attachment);
return newAttachment;
});
};
this.convertLinkedFileToStoredFile = async function (item, options = {}) {
@ -3102,7 +3102,7 @@ Zotero.Attachments = new function () {
};
this._getFileNameFromURL = function(url, contentType) {
this._getFileNameFromURL = function (url, contentType) {
url = Zotero.Utilities.Internal.parseURL(url);
var fileBaseName = url.fileBaseName;
@ -3243,7 +3243,7 @@ Zotero.Attachments = new function () {
* Determines if a given document is an instance of PDFJS
* @return {Boolean}
*/
this.isPDFJSDocument = function(doc) {
this.isPDFJSDocument = function (doc) {
// pdf.js HACK
// This may no longer be necessary (as of Fx 23)
if(doc.contentType === "text/html") {

View file

@ -150,7 +150,7 @@ Zotero.BrowserDownload = {
}, Ci.nsIWebProgress.NOTIFY_LOCATION);
hiddenBrowser.load(url);
let blob = await Zotero.Promise.race([
let blob = await Promise.race([
onLoadTimeoutDeferred.promise,
Zotero.Promise.delay(downloadTimeout).then(() => {
if (!pdfLoaded) {
@ -235,7 +235,7 @@ Zotero.BrowserDownload = {
Zotero.MIMETypeHandler.addHandlers("application/pdf", pdfMIMETypeHandler, true);
Zotero.debug(`BrowserDownload: Awaiting the user to clear the captcha or timeout after ${downloadTimeout}`);
let pdfBlob = await Zotero.Promise.race([
let pdfBlob = await Promise.race([
Zotero.Promise.delay(downloadTimeout).then(() => {
if (!pdfFound) {
throw new Error(`BrowserDownload: Loading PDF via document viewer timed out after ${downloadTimeout}ms`);

View file

@ -136,7 +136,7 @@ Zotero.Cite = {
* @param {bib} citeproc-js bibliography object
* @param {Set} itemsToRemove Set of items to remove
*/
"removeFromBibliography":function(bib, itemsToRemove) {
"removeFromBibliography":function (bib, itemsToRemove) {
var removeItems = [];
for(let i in bib[0].entry_ids) {
for(let j in bib[0].entry_ids[i]) {
@ -189,7 +189,7 @@ Zotero.Cite = {
* @param {String} format The format of the output (html, text, or rtf)
* @return {String} Bibliography or item list in specified format
*/
"makeFormattedBibliographyOrCitationList":function(cslEngine, items, format, asCitationList) {
"makeFormattedBibliographyOrCitationList":function (cslEngine, items, format, asCitationList) {
cslEngine.setOutputFormat(format);
cslEngine.updateItems(items.map(item => item.id));
@ -442,7 +442,7 @@ Zotero.Cite = {
/**
* Get a CSL abbreviation in the format expected by citeproc-js
*/
Zotero.Cite.getAbbreviation = new function() {
Zotero.Cite.getAbbreviation = new function () {
var abbreviations,
abbreviationCategories;
@ -618,7 +618,7 @@ Zotero.Cite.System = function ({ automaticJournalAbbreviations, uppercaseSubtitl
this.getAbbreviation = Zotero.Cite.getAbbreviation;
}
if (uppercaseSubtitles) {
this.uppercase_subtitles = true; // eslint-disable-line camelcase
this.uppercase_subtitles = true;
}
};

View file

@ -91,12 +91,12 @@ Zotero.CollectionTreeRow.prototype.isLibrary = function (includeGlobal)
return this.type == 'library';
}
Zotero.CollectionTreeRow.prototype.isCollection = function()
Zotero.CollectionTreeRow.prototype.isCollection = function ()
{
return this.type == 'collection';
}
Zotero.CollectionTreeRow.prototype.isSearch = function()
Zotero.CollectionTreeRow.prototype.isSearch = function ()
{
return this.type == 'search';
}
@ -113,7 +113,7 @@ Zotero.CollectionTreeRow.prototype.isRetracted = function () {
return this.type == 'retracted';
}
Zotero.CollectionTreeRow.prototype.isTrash = function()
Zotero.CollectionTreeRow.prototype.isTrash = function ()
{
return this.type == 'trash';
}
@ -122,23 +122,23 @@ Zotero.CollectionTreeRow.prototype.isHeader = function () {
return this.type == 'header';
}
Zotero.CollectionTreeRow.prototype.isPublications = function() {
Zotero.CollectionTreeRow.prototype.isPublications = function () {
return this.type == 'publications';
}
Zotero.CollectionTreeRow.prototype.isGroup = function() {
Zotero.CollectionTreeRow.prototype.isGroup = function () {
return this.type == 'group';
}
Zotero.CollectionTreeRow.prototype.isFeed = function() {
Zotero.CollectionTreeRow.prototype.isFeed = function () {
return this.type == 'feed';
}
Zotero.CollectionTreeRow.prototype.isFeeds = function() {
Zotero.CollectionTreeRow.prototype.isFeeds = function () {
return this.type == 'feeds';
}
Zotero.CollectionTreeRow.prototype.isFeedsOrFeed = function() {
Zotero.CollectionTreeRow.prototype.isFeedsOrFeed = function () {
return this.isFeeds() || this.isFeed();
}
@ -146,17 +146,17 @@ Zotero.CollectionTreeRow.prototype.isSeparator = function () {
return this.type == 'separator';
}
Zotero.CollectionTreeRow.prototype.isBucket = function()
Zotero.CollectionTreeRow.prototype.isBucket = function ()
{
return this.type == 'bucket';
}
Zotero.CollectionTreeRow.prototype.isShare = function()
Zotero.CollectionTreeRow.prototype.isShare = function ()
{
return this.type == 'share';
}
Zotero.CollectionTreeRow.prototype.isContainer = function() {
Zotero.CollectionTreeRow.prototype.isContainer = function () {
return this.isLibrary(true) || this.isCollection() || this.isPublications() || this.isBucket() || this.isFeeds();
}
@ -226,12 +226,12 @@ Zotero.CollectionTreeRow.prototype.__defineGetter__('filesEditable', function ()
Zotero.CollectionTreeRow.visibilityGroups = {'feed': 'feed', 'feeds': 'feeds'};
Zotero.CollectionTreeRow.prototype.__defineGetter__('visibilityGroup', function() {
Zotero.CollectionTreeRow.prototype.__defineGetter__('visibilityGroup', function () {
return Zotero.CollectionTreeRow.visibilityGroups[this.type] || 'default';
});
Zotero.CollectionTreeRow.prototype.getName = function()
Zotero.CollectionTreeRow.prototype.getName = function ()
{
switch (this.type) {
case 'library':
@ -285,8 +285,7 @@ Zotero.CollectionTreeRow.prototype.getTrashedCollections = async function () {
};
Zotero.CollectionTreeRow.prototype.getItems = Zotero.Promise.coroutine(function* ()
{
Zotero.CollectionTreeRow.prototype.getItems = async function () {
switch (this.type) {
// Fake results if this is a shared library
case 'share':
@ -296,7 +295,7 @@ Zotero.CollectionTreeRow.prototype.getItems = Zotero.Promise.coroutine(function*
return this.ref.getItems();
}
var ids = yield this.getSearchResults();
var ids = await this.getSearchResults();
// Filter out items that exist in the items table (where search results come from) but that haven't
// yet been registered. This helps prevent unloaded-data crashes when switching collections while
@ -313,18 +312,18 @@ Zotero.CollectionTreeRow.prototype.getItems = Zotero.Promise.coroutine(function*
}
return Zotero.Items.getAsync(ids);
});
};
Zotero.CollectionTreeRow.prototype.getSearchResults = Zotero.Promise.coroutine(function* (asTempTable) {
Zotero.CollectionTreeRow.prototype.getSearchResults = async function (asTempTable) {
if (Zotero.CollectionTreeCache.lastTreeRow && Zotero.CollectionTreeCache.lastTreeRow.id !== this.id) {
Zotero.CollectionTreeCache.clear();
}
if(!Zotero.CollectionTreeCache.lastResults) {
let s = yield this.getSearchObject();
let s = await this.getSearchObject();
Zotero.CollectionTreeCache.error = false;
try {
Zotero.CollectionTreeCache.lastResults = yield s.search();
Zotero.CollectionTreeCache.lastResults = await s.search();
}
catch (e) {
Zotero.logError(e);
@ -337,19 +336,19 @@ Zotero.CollectionTreeRow.prototype.getSearchResults = Zotero.Promise.coroutine(f
if(asTempTable) {
if(!Zotero.CollectionTreeCache.lastTempTable) {
Zotero.CollectionTreeCache.lastTempTable = yield Zotero.Search.idsToTempTable(Zotero.CollectionTreeCache.lastResults);
Zotero.CollectionTreeCache.lastTempTable = await Zotero.Search.idsToTempTable(Zotero.CollectionTreeCache.lastResults);
}
return Zotero.CollectionTreeCache.lastTempTable;
}
return Zotero.CollectionTreeCache.lastResults;
});
};
/*
* Returns the search object for the currently display
*
* This accounts for the collection, saved search, quicksearch, tags, etc.
*/
Zotero.CollectionTreeRow.prototype.getSearchObject = Zotero.Promise.coroutine(function* () {
Zotero.CollectionTreeRow.prototype.getSearchObject = async function () {
if (Zotero.CollectionTreeCache.lastTreeRow && Zotero.CollectionTreeCache.lastTreeRow.id !== this.id) {
Zotero.CollectionTreeCache.clear();
}
@ -365,7 +364,7 @@ Zotero.CollectionTreeRow.prototype.getSearchObject = Zotero.Promise.coroutine(fu
var s = this.ref;
}
else if (this.isDuplicates()) {
var s = yield this.ref.getSearchObject();
var s = await this.ref.getSearchObject();
let tmpTable;
for (let id in s.conditions) {
let c = s.conditions[id];
@ -442,7 +441,7 @@ Zotero.CollectionTreeRow.prototype.getSearchObject = Zotero.Promise.coroutine(fu
Zotero.CollectionTreeCache.lastTreeRow = this;
Zotero.CollectionTreeCache.lastSearch = s2;
return s2;
});
};
Zotero.CollectionTreeRow.prototype.getChildTags = function () {
Zotero.warn("Zotero.CollectionTreeRow::getChildTags() is deprecated -- use getTags() instead");
@ -485,7 +484,7 @@ Zotero.CollectionTreeRow.prototype.setTags = function (tags) {
/*
* Returns TRUE if saved search, quicksearch or tag filter
*/
Zotero.CollectionTreeRow.prototype.isSearchMode = function() {
Zotero.CollectionTreeRow.prototype.isSearchMode = function () {
switch (this.type) {
case 'search':
case 'publications':

View file

@ -68,7 +68,7 @@ Zotero.CookieSandbox.init = function () {
* Normalizes the host string: lower-case, remove leading period, some more cleanup
* @param {String} host;
*/
Zotero.CookieSandbox.normalizeHost = function(host) {
Zotero.CookieSandbox.normalizeHost = function (host) {
return host.trim().toLowerCase().replace(/^\.+|[:\/].*/g, '');
}
@ -76,7 +76,7 @@ Zotero.CookieSandbox.normalizeHost = function(host) {
* Normalizes the path string
* @param {String} path;
*/
Zotero.CookieSandbox.normalizePath = function(path) {
Zotero.CookieSandbox.normalizePath = function (path) {
return '/' + path.trim().replace(/^\/+|[?#].*/g, '');
}
@ -84,7 +84,7 @@ Zotero.CookieSandbox.normalizePath = function(path) {
* Generates a semicolon-separated string of cookie values from a list of cookies
* @param {Object} cookies Object containing key: value cookie pairs
*/
Zotero.CookieSandbox.generateCookieString = function(cookies) {
Zotero.CookieSandbox.generateCookieString = function (cookies) {
var str = '';
for(var key in cookies) {
str += '; ' + key + '=' + cookies[key];
@ -106,7 +106,7 @@ Zotero.CookieSandbox.prototype = {
* @param {nsIURI} [uri] URI of the header origin.
Used to verify same origin. If omitted validation is not performed
*/
"addCookiesFromHeader":function(cookieString, uri) {
"addCookiesFromHeader":function (cookieString, uri) {
var cookies = cookieString.split("\n");
if(uri) {
var validDomain = '.' + Zotero.CookieSandbox.normalizeHost(uri.host);
@ -164,7 +164,7 @@ Zotero.CookieSandbox.prototype = {
* Attach CookieSandbox to a specific browser
* @param {Browser} browser
*/
"attachToBrowser":function(browser) {
"attachToBrowser":function (browser) {
Zotero.CookieSandbox.Observer.trackedBrowsers.set(browser, this);
},
@ -172,7 +172,7 @@ Zotero.CookieSandbox.prototype = {
* Attach CookieSandbox to a specific XMLHttpRequest
* @param {nsIInterfaceRequestor} ir
*/
"attachToInterfaceRequestor": function(ir) {
"attachToInterfaceRequestor": function (ir) {
if (typeof ir.QueryInterface === 'function') {
ir = ir.QueryInterface(Components.interfaces.nsIInterfaceRequestor);
}
@ -188,7 +188,7 @@ Zotero.CookieSandbox.prototype = {
* @param {Boolean} [secure] Whether the cookie has the secure attribute set
* @param {Boolean} [hostOnly] Whether the cookie is a host-only cookie
*/
"setCookie": function(cookiePair, host, path, secure, hostOnly) {
"setCookie": function (cookiePair, host, path, secure, hostOnly) {
var splitAt = cookiePair.indexOf('=');
if(splitAt === -1) {
Zotero.debug("CookieSandbox: Not setting invalid cookie.");
@ -230,7 +230,7 @@ Zotero.CookieSandbox.prototype = {
* Returns a list of cookies that should be sent to the given URI
* @param {nsIURI} uri
*/
"getCookiesForURI": function(uri) {
"getCookiesForURI": function (uri) {
var hostParts = Zotero.CookieSandbox.normalizeHost(uri.host).split('.'),
pathParts = Zotero.CookieSandbox.normalizePath(uri.filePath || uri.pathQueryRef).split('/'),
cookies = {}, found = false, secure = uri.scheme.toUpperCase() == 'HTTPS';
@ -250,7 +250,7 @@ Zotero.CookieSandbox.prototype = {
return found ? cookies : null;
},
"_getCookiesForPath": function(cookies, cookiePaths, pathParts, secure, isHost) {
"_getCookiesForPath": function (cookies, cookiePaths, pathParts, secure, isHost) {
var found = false;
var path = '';
for(var i=0, n=pathParts.length; i<n; i++) {
@ -286,7 +286,7 @@ Zotero.CookieSandbox.prototype = {
/**
* nsIObserver implementation for adding, clearing, and slurping cookies
*/
Zotero.CookieSandbox.Observer = new function() {
Zotero.CookieSandbox.Observer = new function () {
const observeredTopics = ["http-on-examine-response", "http-on-modify-request"];
var observerService = Components.classes["@mozilla.org/observer-service;1"].

View file

@ -48,7 +48,7 @@
*
* And add .init() to zotero.js
*/
Zotero.CachedTypes = function() {
Zotero.CachedTypes = function () {
this._types = null;
this._typesArray = null;
var self = this;
@ -63,15 +63,15 @@ Zotero.CachedTypes = function() {
this._hasCustom = false;
this.init = Zotero.Promise.coroutine(function* () {
this.init = async function () {
this._types = {};
this._typesArray = [];
var types = yield this._getTypesFromDB();
var types = await this._getTypesFromDB();
for (let i=0; i<types.length; i++) {
this._cacheTypeData(types[i]);
}
});
};
this.getName = function (idOrName) {
@ -138,7 +138,7 @@ Zotero.CachedTypes = function() {
* @param {String} name - Type name to add
* @return {Integer|False} - The type id (new or existing), or false if invalid type name
*/
this.add = Zotero.Promise.coroutine(function* (name) {
this.add = async function (name) {
if (!this._allowAdd) {
throw new Error("New " + this._typeDescPlural + " cannot be added");
}
@ -162,10 +162,10 @@ Zotero.CachedTypes = function() {
}
var sql = "INSERT INTO " + this._table + " (" + this._nameCol + ") VALUES (?)";
yield Zotero.DB.queryAsync(sql, name);
await Zotero.DB.queryAsync(sql, name);
sql = "SELECT " + this._idCol + " FROM " + this._table + " WHERE " + this._nameCol + "=?";
var id = yield Zotero.DB.valueQueryAsync(sql, name);
var id = await Zotero.DB.valueQueryAsync(sql, name);
this._cacheTypeData({
id: id,
@ -173,7 +173,7 @@ Zotero.CachedTypes = function() {
});
return id;
});
};
this._valueCheck = function (name) {
@ -215,7 +215,7 @@ Zotero.CachedTypes = function() {
}
Zotero.CreatorTypes = new function() {
Zotero.CreatorTypes = new function () {
Zotero.CachedTypes.apply(this, arguments);
this.constructor.prototype = new Zotero.CachedTypes();
@ -233,12 +233,12 @@ Zotero.CreatorTypes = new function() {
var _isValidForItemType = {};
this.init = Zotero.Promise.coroutine(function* () {
yield this.constructor.prototype.init.apply(this);
this.init = async function () {
await this.constructor.prototype.init.apply(this);
var sql = "SELECT itemTypeID, creatorTypeID AS id, creatorType AS name, primaryField "
+ "FROM itemTypeCreatorTypes NATURAL JOIN creatorTypes";
var rows = yield Zotero.DB.queryAsync(sql);
var rows = await Zotero.DB.queryAsync(sql);
_creatorTypesByItemType = {};
for (let i=0; i<rows.length; i++) {
let row = rows[i];
@ -269,12 +269,12 @@ Zotero.CreatorTypes = new function() {
_primaryIDCache = {};
var sql = "SELECT itemTypeID, creatorTypeID FROM itemTypeCreatorTypes "
+ "WHERE primaryField=1";
var rows = yield Zotero.DB.queryAsync(sql);
var rows = await Zotero.DB.queryAsync(sql);
for (let i=0; i<rows.length; i++) {
let row = rows[i];
_primaryIDCache[row.itemTypeID] = row.creatorTypeID;
}
});
};
this.getTypesForItemType = function (itemTypeID) {
@ -307,7 +307,7 @@ Zotero.CreatorTypes = new function() {
}
this.getLocalizedString = function(idOrName) {
this.getLocalizedString = function (idOrName) {
var name = this.getName(idOrName);
return Zotero.Schema.globalSchemaLocale.creatorTypes[name];
}
@ -338,7 +338,7 @@ Zotero.CreatorTypes = new function() {
}
Zotero.ItemTypes = new function() {
Zotero.ItemTypes = new function () {
Zotero.CachedTypes.apply(this, arguments);
this.constructor.prototype = new Zotero.CachedTypes();
@ -360,24 +360,24 @@ Zotero.ItemTypes = new function() {
var _customLabels = {};
this.init = Zotero.Promise.coroutine(function* () {
yield this.constructor.prototype.init.apply(this);
this.init = async function () {
await this.constructor.prototype.init.apply(this);
// Hidden types
_hiddenTypes = yield this._getTypesFromDB(
_hiddenTypes = await this._getTypesFromDB(
`WHERE typeName IN ('${_hiddenTypeNames.join("', '")}')`
);
// Custom labels and icons
var sql = "SELECT customItemTypeID AS id, label, icon FROM customItemTypes";
var rows = yield Zotero.DB.queryAsync(sql);
var rows = await Zotero.DB.queryAsync(sql);
for (let i=0; i<rows.length; i++) {
let row = rows[i];
let id = row.id;
_customLabels[id] = row.label;
_customImages[id] = row.icon;
}
});
};
this.getPrimaryTypes = function () {
@ -513,7 +513,7 @@ Zotero.ItemTypes = new function() {
}
Zotero.FileTypes = new function() {
Zotero.FileTypes = new function () {
Zotero.CachedTypes.apply(this, arguments);
this.constructor.prototype = new Zotero.CachedTypes();
@ -533,7 +533,7 @@ Zotero.FileTypes = new function() {
}
Zotero.CharacterSets = new function() {
Zotero.CharacterSets = new function () {
Zotero.CachedTypes.apply(this, arguments);
this.constructor.prototype = new Zotero.CachedTypes();

View file

@ -23,7 +23,7 @@
***** END LICENSE BLOCK *****
*/
Zotero.Collection = function(params = {}) {
Zotero.Collection = function (params = {}) {
Zotero.Collection._super.apply(this);
this._name = null;
@ -44,39 +44,39 @@ Zotero.Collection.prototype._dataTypes = Zotero.Collection._super.prototype._dat
]);
Zotero.defineProperty(Zotero.Collection.prototype, 'ChildObjects', {
get: function() { return Zotero.Items; }
get: function () { return Zotero.Items; }
});
Zotero.defineProperty(Zotero.Collection.prototype, 'id', {
get: function() { return this._get('id'); },
set: function(val) { return this._set('id', val); }
get: function () { return this._get('id'); },
set: function (val) { return this._set('id', val); }
});
Zotero.defineProperty(Zotero.Collection.prototype, 'libraryID', {
get: function() { return this._get('libraryID'); },
set: function(val) { return this._set('libraryID', val); }
get: function () { return this._get('libraryID'); },
set: function (val) { return this._set('libraryID', val); }
});
Zotero.defineProperty(Zotero.Collection.prototype, 'key', {
get: function() { return this._get('key'); },
set: function(val) { return this._set('key', val); }
get: function () { return this._get('key'); },
set: function (val) { return this._set('key', val); }
});
Zotero.defineProperty(Zotero.Collection.prototype, 'name', {
get: function() { return this._get('name'); },
set: function(val) { return this._set('name', val); }
get: function () { return this._get('name'); },
set: function (val) { return this._set('name', val); }
});
Zotero.defineProperty(Zotero.Collection.prototype, 'version', {
get: function() { return this._get('version'); },
set: function(val) { return this._set('version', val); }
get: function () { return this._get('version'); },
set: function (val) { return this._set('version', val); }
});
Zotero.defineProperty(Zotero.Collection.prototype, 'synced', {
get: function() { return this._get('synced'); },
set: function(val) { return this._set('synced', val); }
get: function () { return this._get('synced'); },
set: function (val) { return this._set('synced', val); }
});
Zotero.defineProperty(Zotero.Collection.prototype, 'parent', {
get: function() {
get: function () {
Zotero.debug("WARNING: Zotero.Collection.prototype.parent has been deprecated -- use .parentID or .parentKey", 2);
return this.parentID;
},
set: function(val) {
set: function (val) {
Zotero.debug("WARNING: Zotero.Collection.prototype.parent has been deprecated -- use .parentID or .parentKey", 2);
this.parentID = val;
},
@ -96,12 +96,12 @@ Zotero.defineProperty(Zotero.Collection.prototype, 'treeViewImage', {
}
});
Zotero.Collection.prototype.getID = function() {
Zotero.Collection.prototype.getID = function () {
Zotero.debug('Collection.getID() deprecated -- use Collection.id');
return this.id;
}
Zotero.Collection.prototype.getName = function() {
Zotero.Collection.prototype.getName = function () {
Zotero.debug('Collection.getName() deprecated -- use Collection.name');
return this.name;
}
@ -112,7 +112,7 @@ Object.assign(Zotero.Collection.prototype, Zotero.DataObjectUtilities.itemTreeMo
/*
* Populate collection data from a database row
*/
Zotero.Collection.prototype.loadFromRow = function(row) {
Zotero.Collection.prototype.loadFromRow = function (row) {
var primaryFields = this._ObjectsClass.primaryFields;
for (let i=0; i<primaryFields.length; i++) {
let col = primaryFields[i];
@ -184,7 +184,7 @@ Zotero.Collection.prototype.hasChildCollections = function (includeTrashed) {
return !this.getChildCollections().every(c => c.deleted);
}
Zotero.Collection.prototype.hasChildItems = function() {
Zotero.Collection.prototype.hasChildItems = function () {
this._requireData('childItems');
return this._childItems.size > 0;
}
@ -247,17 +247,17 @@ Zotero.Collection.prototype.getChildItems = function (asIDs, includeTrashed) {
return childItems.slice();
}
Zotero.Collection.prototype._initSave = Zotero.Promise.coroutine(function* (env) {
Zotero.Collection.prototype._initSave = async function (env) {
if (!this.name) {
throw new Error(this._ObjectType + ' name is empty');
}
var proceed = yield Zotero.Collection._super.prototype._initSave.apply(this, arguments);
var proceed = await Zotero.Collection._super.prototype._initSave.apply(this, arguments);
if (!proceed) return false;
// Verify parent
if (this._parentKey) {
let newParent = yield this.ObjectsClass.getByLibraryAndKeyAsync(
let newParent = await this.ObjectsClass.getByLibraryAndKeyAsync(
this.libraryID, this._parentKey
);
@ -280,9 +280,9 @@ Zotero.Collection.prototype._initSave = Zotero.Promise.coroutine(function* (env)
}
return true;
});
};
Zotero.Collection.prototype._saveData = Zotero.Promise.coroutine(function* (env) {
Zotero.Collection.prototype._saveData = async function (env) {
var isNew = env.isNew;
var options = env.options;
@ -307,13 +307,13 @@ Zotero.Collection.prototype._saveData = Zotero.Promise.coroutine(function* (env)
let placeholders = env.sqlColumns.map(() => '?').join();
let sql = "INSERT INTO collections (" + env.sqlColumns.join(', ') + ") "
+ "VALUES (" + placeholders + ")";
yield Zotero.DB.queryAsync(sql, env.sqlValues);
await Zotero.DB.queryAsync(sql, env.sqlValues);
}
else {
let sql = 'UPDATE collections SET '
+ env.sqlColumns.map(x => x + '=?').join(', ') + ' WHERE collectionID=?';
env.sqlValues.push(collectionID ? { int: collectionID } : null);
yield Zotero.DB.queryAsync(sql, env.sqlValues);
await Zotero.DB.queryAsync(sql, env.sqlValues);
}
}
@ -342,20 +342,20 @@ Zotero.Collection.prototype._saveData = Zotero.Promise.coroutine(function* (env)
if (this._changedData.deleted !== undefined) {
if (this._changedData.deleted) {
yield this.trash({ ...env, isNew: isNew });
await this.trash({ ...env, isNew: isNew });
}
else {
let sql = "DELETE FROM deletedCollections WHERE collectionID=?";
yield Zotero.DB.queryAsync(sql, collectionID);
await Zotero.DB.queryAsync(sql, collectionID);
}
this._clearChanged('deleted');
this._markForReload('primaryData');
}
});
};
Zotero.Collection.prototype._finalizeSave = Zotero.Promise.coroutine(function* (env) {
Zotero.Collection.prototype._finalizeSave = async function (env) {
if (!env.options.skipNotifier) {
if (env.isNew) {
Zotero.Notifier.queue(
@ -370,7 +370,7 @@ Zotero.Collection.prototype._finalizeSave = Zotero.Promise.coroutine(function* (
}
if (!env.skipCache) {
yield this.reload();
await this.reload();
// If new, there's no other data we don't have, so we can mark everything as loaded
if (env.isNew) {
this._markAllDataTypeLoadStates(true);
@ -379,11 +379,11 @@ Zotero.Collection.prototype._finalizeSave = Zotero.Promise.coroutine(function* (
}
if (env.isNew) {
yield Zotero.Libraries.get(this.libraryID).updateCollections();
await Zotero.Libraries.get(this.libraryID).updateCollections();
}
return env.isNew ? this.id : true;
});
};
/**
@ -404,7 +404,7 @@ Zotero.Collection.prototype.addItem = function (itemID, options) {
* @param {Number[]} itemIDs
* @return {Promise}
*/
Zotero.Collection.prototype.addItems = Zotero.Promise.coroutine(function* (itemIDs, options = {}) {
Zotero.Collection.prototype.addItems = async function (itemIDs, options = {}) {
options.skipDateModifiedUpdate = true;
if (!itemIDs || !itemIDs.length) {
@ -424,11 +424,11 @@ Zotero.Collection.prototype.addItems = Zotero.Promise.coroutine(function* (itemI
let item = this.ChildObjects.get(itemID);
item.addToCollection(this.id);
yield item.save(options);
await item.save(options);
}
yield this.loadDataType('childItems');
});
await this.loadDataType('childItems');
};
/**
* Remove a item from the collection. The item is not deleted from the library.
@ -449,7 +449,7 @@ Zotero.Collection.prototype.removeItem = function (itemID, options = {}) {
*
* Does not require a separate save()
*/
Zotero.Collection.prototype.removeItems = Zotero.Promise.coroutine(function* (itemIDs, options = {}) {
Zotero.Collection.prototype.removeItems = async function (itemIDs, options = {}) {
if (!itemIDs || !itemIDs.length) {
return;
}
@ -465,14 +465,14 @@ Zotero.Collection.prototype.removeItems = Zotero.Promise.coroutine(function* (it
continue;
}
let item = yield this.ChildObjects.getAsync(itemID);
let item = await this.ChildObjects.getAsync(itemID);
item.removeFromCollection(this.id);
yield item.save({
await item.save({
skipDateModifiedUpdate: true,
skipEditCheck: options.skipEditCheck
})
}
});
};
/**
@ -592,7 +592,7 @@ Zotero.Collection.prototype.clone = function (libraryID) {
/**
* Moves the collection and all descendent collections (and optionally items) to trash
**/
Zotero.Collection.prototype.trash = Zotero.Promise.coroutine(function* (env) {
Zotero.Collection.prototype.trash = async function (env) {
Zotero.DB.requireTransaction();
var collections = [this.id];
@ -605,7 +605,7 @@ Zotero.Collection.prototype.trash = Zotero.Promise.coroutine(function* (env) {
// Descendent collections
if (descendents[i].type == 'collection') {
collections.push(descendents[i].id);
var c = yield this.ObjectsClass.getAsync(descendents[i].id);
var c = await this.ObjectsClass.getAsync(descendents[i].id);
if (c) {
env.notifierData[c.id] = {
libraryID: c.libraryID,
@ -629,7 +629,7 @@ Zotero.Collection.prototype.trash = Zotero.Promise.coroutine(function* (env) {
}
if (del.length) {
if (libraryHasTrash) {
yield this.ChildObjects.trash(del);
await this.ChildObjects.trash(del);
}
// If library doesn't have trash, just erase
else {
@ -639,13 +639,13 @@ Zotero.Collection.prototype.trash = Zotero.Promise.coroutine(function* (env) {
Object.assign(options, env.options);
options.tx = false;
for (let i=0; i<del.length; i++) {
let obj = yield this.ChildObjects.getAsync(del[i]);
yield obj.erase(options);
let obj = await this.ChildObjects.getAsync(del[i]);
await obj.erase(options);
}
}
}
yield Zotero.Utilities.Internal.forEachChunkAsync(
await Zotero.Utilities.Internal.forEachChunkAsync(
collections,
Zotero.DB.MAX_BOUND_PARAMETERS,
async function (chunk) {
@ -662,19 +662,19 @@ Zotero.Collection.prototype.trash = Zotero.Promise.coroutine(function* (env) {
// Reload collection data to show/restore deleted collections from trash
for (let collectionID of collections) {
let collection = Zotero.Collections.get(collectionID);
yield collection.loadDataType('primaryData', true);
yield collection.loadDataType('childCollections', true);
await collection.loadDataType('primaryData', true);
await collection.loadDataType('childCollections', true);
}
});
};
/**
* Completely erase the collection and its descendants.
**/
Zotero.Collection.prototype._eraseData = Zotero.Promise.coroutine(function* (env) {
Zotero.Collection.prototype._eraseData = async function (env) {
Zotero.DB.requireTransaction();
if (!this.deleted) {
yield this.trash(env);
await this.trash(env);
}
var collections = [this.id];
@ -686,7 +686,7 @@ Zotero.Collection.prototype._eraseData = Zotero.Promise.coroutine(function* (env
// Make sure all descendant collections will be unloaded in this._finalizeErase()
env.deletedObjectIDs = collections;
yield Zotero.Utilities.Internal.forEachChunkAsync(
await Zotero.Utilities.Internal.forEachChunkAsync(
collections,
Zotero.DB.MAX_BOUND_PARAMETERS,
async function (chunk) {
@ -723,16 +723,16 @@ Zotero.Collection.prototype._eraseData = Zotero.Promise.coroutine(function* (env
let item = Zotero.Items.get(itemID);
item._collections = item._collections.filter(c => !deletedCollections.has(c));
});
});
};
Zotero.Collection.prototype._finalizeErase = Zotero.Promise.coroutine(function* (env) {
yield Zotero.Collection._super.prototype._finalizeErase.call(this, env);
Zotero.Collection.prototype._finalizeErase = async function (env) {
await Zotero.Collection._super.prototype._finalizeErase.call(this, env);
yield Zotero.Libraries.get(this.libraryID).updateCollections();
});
await Zotero.Libraries.get(this.libraryID).updateCollections();
};
Zotero.Collection.prototype.serialize = function(nested) {
Zotero.Collection.prototype.serialize = function (nested) {
var childCollections = this.getChildCollections(true);
var childItems = this.getChildItems(true);
var obj = {
@ -935,9 +935,9 @@ Zotero.Collection.prototype.getLinkedCollection = function (libraryID, bidrectio
*
* Does not require a separate save()
*/
Zotero.Collection.prototype.addLinkedCollection = Zotero.Promise.coroutine(function* (collection) {
Zotero.Collection.prototype.addLinkedCollection = async function (collection) {
return this._addLinkedObject(collection);
});
};
//

View file

@ -27,7 +27,7 @@
/*
* Primary interface for accessing Zotero collection
*/
Zotero.Collections = function() {
Zotero.Collections = function () {
this.constructor = null;
this._ZDO_object = 'collection';
@ -159,7 +159,7 @@ Zotero.Collections = function() {
}
this._loadChildCollections = Zotero.Promise.coroutine(function* (libraryID, ids, idSQL) {
this._loadChildCollections = async function (libraryID, ids, idSQL) {
var sql = "SELECT C1.collectionID, C2.collectionID AS childCollectionID "
+ "FROM collections C1 LEFT JOIN collections C2 ON (C1.collectionID=C2.parentCollectionID) "
+ "WHERE C1.libraryID=?"
@ -178,7 +178,7 @@ Zotero.Collections = function() {
collection._clearChanged('childCollections');
}.bind(this);
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
sql,
params,
{
@ -205,10 +205,10 @@ Zotero.Collections = function() {
if (lastID) {
setRows(lastID, rows);
}
});
};
this._loadChildItems = Zotero.Promise.coroutine(function* (libraryID, ids, idSQL) {
this._loadChildItems = async function (libraryID, ids, idSQL) {
var sql = "SELECT collectionID, itemID FROM collections "
+ "LEFT JOIN collectionItems USING (collectionID) "
+ "WHERE libraryID=?" + idSQL;
@ -226,7 +226,7 @@ Zotero.Collections = function() {
collection._clearChanged('childItems');
}.bind(this);
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
sql,
params,
{
@ -253,7 +253,7 @@ Zotero.Collections = function() {
if (lastID) {
setRows(lastID, rows);
}
});
};
this.registerChildCollection = function (collectionID, childCollectionID) {

View file

@ -24,16 +24,16 @@
*/
Zotero.Creators = new function() {
Zotero.Creators = new function () {
this.fields = ['firstName', 'lastName', 'fieldMode'];
this.totes = 0;
var _cache = {};
this.init = Zotero.Promise.coroutine(function* () {
this.init = async function () {
var repaired = false;
var sql = "SELECT * FROM creators";
var rows = yield Zotero.DB.queryAsync(sql);
var rows = await Zotero.DB.queryAsync(sql);
for (let i = 0; i < rows.length; i++) {
let row = rows[i];
try {
@ -49,9 +49,9 @@ Zotero.Creators = new function() {
if (!repaired) {
Zotero.logError(e);
Zotero.logError("Trying integrity check to fix creator error");
yield Zotero.Schema.integrityCheck(true);
await Zotero.Schema.integrityCheck(true);
repaired = true;
rows = yield Zotero.DB.queryAsync(sql);
rows = await Zotero.DB.queryAsync(sql);
i = -1;
continue;
}
@ -59,7 +59,7 @@ Zotero.Creators = new function() {
throw e;
}
}
});
};
/*
* Returns creator data in internal format for a given creatorID
@ -98,29 +98,29 @@ Zotero.Creators = new function() {
* @param {Boolean} [create=false] If no matching creator, create one
* @return {Promise<Integer>} creatorID
*/
this.getIDFromData = Zotero.Promise.coroutine(function* (data, create) {
this.getIDFromData = async function (data, create) {
Zotero.DB.requireTransaction();
data = this.cleanData(data);
var sql = "SELECT creatorID FROM creators WHERE "
+ "firstName=? AND lastName=? AND fieldMode=?";
var id = yield Zotero.DB.valueQueryAsync(
var id = await Zotero.DB.valueQueryAsync(
sql, [data.firstName, data.lastName, data.fieldMode]
);
if (!id && create) {
id = Zotero.ID.get('creators');
let sql = "INSERT INTO creators (creatorID, firstName, lastName, fieldMode) "
+ "VALUES (?, ?, ?, ?)";
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
sql, [id, data.firstName, data.lastName, data.fieldMode]
);
_cache[id] = data;
}
return id;
});
};
this.updateCreator = Zotero.Promise.coroutine(function* (creatorID, creatorData) {
var creator = yield this.get(creatorID);
this.updateCreator = async function (creatorID, creatorData) {
var creator = await this.get(creatorID);
if (!creator) {
throw new Error("Creator " + creatorID + " doesn't exist");
}
@ -128,7 +128,7 @@ Zotero.Creators = new function() {
creator.firstName = creatorData.firstName;
creator.lastName = creatorData.lastName;
return creator.save();
});
};
/**
@ -136,7 +136,7 @@ Zotero.Creators = new function() {
*
* @return {Promise}
*/
this.purge = Zotero.Promise.coroutine(function* () {
this.purge = async function () {
if (!Zotero.Prefs.get('purge.creators')) {
return;
}
@ -145,7 +145,7 @@ Zotero.Creators = new function() {
var sql = 'SELECT creatorID FROM creators WHERE creatorID NOT IN '
+ '(SELECT creatorID FROM itemCreators)';
var toDelete = yield Zotero.DB.columnQueryAsync(sql);
var toDelete = await Zotero.DB.columnQueryAsync(sql);
if (toDelete.length) {
// Clear creator entries in internal array
for (let i=0; i<toDelete.length; i++) {
@ -154,11 +154,11 @@ Zotero.Creators = new function() {
var sql = "DELETE FROM creators WHERE creatorID NOT IN "
+ "(SELECT creatorID FROM itemCreators)";
yield Zotero.DB.queryAsync(sql);
await Zotero.DB.queryAsync(sql);
}
Zotero.Prefs.set('purge.creators', false);
});
};
this.equals = function (data1, data2) {

View file

@ -67,13 +67,13 @@ Zotero.DataObject.prototype._objectType = 'dataObject';
Zotero.DataObject.prototype._dataTypes = ['primaryData'];
Zotero.defineProperty(Zotero.DataObject.prototype, 'objectType', {
get: function() { return this._objectType; }
get: function () { return this._objectType; }
});
Zotero.defineProperty(Zotero.DataObject.prototype, 'id', {
get: function() { return this._id; }
get: function () { return this._id; }
});
Zotero.defineProperty(Zotero.DataObject.prototype, 'libraryID', {
get: function() { return this._libraryID; }
get: function () { return this._libraryID; }
});
Zotero.defineProperty(Zotero.DataObject.prototype, 'library', {
get: function () {
@ -81,18 +81,18 @@ Zotero.defineProperty(Zotero.DataObject.prototype, 'library', {
}
});
Zotero.defineProperty(Zotero.DataObject.prototype, 'key', {
get: function() { return this._key; }
get: function () { return this._key; }
});
Zotero.defineProperty(Zotero.DataObject.prototype, 'libraryKey', {
get: function() { return this._libraryID + "/" + this._key; }
get: function () { return this._libraryID + "/" + this._key; }
});
Zotero.defineProperty(Zotero.DataObject.prototype, 'parentKey', {
get: function () { return this._getParentKey(); },
set: function(v) { return this._setParentKey(v); }
set: function (v) { return this._setParentKey(v); }
});
Zotero.defineProperty(Zotero.DataObject.prototype, 'parentID', {
get: function() { return this._getParentID(); },
set: function(v) { return this._setParentID(v); }
get: function () { return this._getParentID(); },
set: function (v) { return this._setParentID(v); }
});
Zotero.defineProperty(Zotero.DataObject.prototype, '_canHaveParent', {
@ -103,7 +103,7 @@ Zotero.defineProperty(Zotero.DataObject.prototype, '_canHaveParent', {
for (let name of ['deleted']) {
let prop = '_' + name;
Zotero.defineProperty(Zotero.DataObject.prototype, name, {
get: function() {
get: function () {
if (!this.id) {
return false;
}
@ -113,7 +113,7 @@ for (let name of ['deleted']) {
}
this._requireData('primaryData');
},
set: function(val) {
set: function (val) {
val = !!val;
var oldVal = this._getLatestField(name);
if (oldVal == val) {
@ -127,7 +127,7 @@ for (let name of ['deleted']) {
}
Zotero.defineProperty(Zotero.DataObject.prototype, 'ObjectsClass', {
get: function() { return this._ObjectsClass; }
get: function () { return this._ObjectsClass; }
});
@ -290,7 +290,7 @@ Zotero.DataObject.prototype._getParentKey = function () {
* @param {String|false} [key=false]
* @return {Boolean} True if changed, false if stayed the same
*/
Zotero.DataObject.prototype._setParentKey = function(key) {
Zotero.DataObject.prototype._setParentKey = function (key) {
if (!this._canHaveParent) {
throw new Error("Cannot set parent key for " + this._objectType);
}
@ -492,7 +492,7 @@ Zotero.DataObject.prototype.setRelations = function (newRelations) {
* @param {Integer} [libraryID]
* @return {Promise<Zotero.DataObject|false>} Linked object, or false if not found
*/
Zotero.DataObject.prototype._getLinkedObject = Zotero.Promise.coroutine(function* (libraryID, bidirectional) {
Zotero.DataObject.prototype._getLinkedObject = async function (libraryID, bidirectional) {
if (!libraryID) {
throw new Error("libraryID not provided");
}
@ -510,7 +510,7 @@ Zotero.DataObject.prototype._getLinkedObject = Zotero.Promise.coroutine(function
for (let i = 0; i < uris.length; i++) {
let uri = uris[i];
if (uri.startsWith(libraryObjectPrefix)) {
let obj = yield Zotero.URI['getURI' + this._ObjectType](uri);
let obj = await Zotero.URI['getURI' + this._ObjectType](uri);
if (!obj) {
Zotero.debug("Referenced linked " + this._objectType + " '" + uri + "' not found "
+ "in Zotero." + this._ObjectType + "::getLinked" + this._ObjectType + "()", 2);
@ -527,7 +527,7 @@ Zotero.DataObject.prototype._getLinkedObject = Zotero.Promise.coroutine(function
// Then try relations with this as an object
if (bidirectional) {
var thisURI = Zotero.URI['get' + this._ObjectType + 'URI'](this);
let objects = yield Zotero.Relations.getByPredicateAndObject(
let objects = await Zotero.Relations.getByPredicateAndObject(
this._objectType, predicate, thisURI
);
for (let i = 0; i < objects.length; i++) {
@ -548,7 +548,7 @@ Zotero.DataObject.prototype._getLinkedObject = Zotero.Promise.coroutine(function
}
return false;
});
};
/**
@ -559,7 +559,7 @@ Zotero.DataObject.prototype._getLinkedObject = Zotero.Promise.coroutine(function
* @param {Zotero.DataObject} object
* @param {Promise<Boolean>}
*/
Zotero.DataObject.prototype._addLinkedObject = Zotero.Promise.coroutine(function* (object) {
Zotero.DataObject.prototype._addLinkedObject = async function (object) {
if (object.libraryID == this._libraryID) {
throw new Error("Can't add linked " + this._objectType + " in same library");
}
@ -581,21 +581,21 @@ Zotero.DataObject.prototype._addLinkedObject = Zotero.Promise.coroutine(function
var userLibraryID = Zotero.Libraries.userLibraryID;
if (this.libraryID == userLibraryID || object.libraryID != userLibraryID) {
this.addRelation(predicate, objectURI);
yield this.save({
await this.save({
skipDateModifiedUpdate: true,
skipSelect: true
});
}
else {
object.addRelation(predicate, thisURI);
yield object.save({
await object.save({
skipDateModifiedUpdate: true,
skipSelect: true
});
}
return true;
});
};
//
@ -603,7 +603,7 @@ Zotero.DataObject.prototype._addLinkedObject = Zotero.Promise.coroutine(function
//
// These are called by Zotero.DataObjects.prototype.loadDataType().
//
Zotero.DataObject.prototype.loadPrimaryData = Zotero.Promise.coroutine(function* (reload, failOnMissing) {
Zotero.DataObject.prototype.loadPrimaryData = async function (reload, failOnMissing) {
if (this._loaded.primaryData && !reload) return;
var id = this._id;
@ -640,7 +640,7 @@ Zotero.DataObject.prototype.loadPrimaryData = Zotero.Promise.coroutine(function*
var params = [key, libraryID];
}
sql += (where.length ? ' AND ' + where.join(' AND ') : '');
var row = yield Zotero.DB.rowQueryAsync(sql, params);
var row = await Zotero.DB.rowQueryAsync(sql, params);
if (!row) {
if (failOnMissing) {
@ -655,7 +655,7 @@ Zotero.DataObject.prototype.loadPrimaryData = Zotero.Promise.coroutine(function*
}
this.loadFromRow(row, reload);
});
};
/**
@ -666,7 +666,7 @@ Zotero.DataObject.prototype.loadPrimaryData = Zotero.Promise.coroutine(function*
* This should be set to true for data that was
* changed externally (e.g., globally renamed tags).
*/
Zotero.DataObject.prototype.reload = Zotero.Promise.coroutine(function* (dataTypes, reloadUnchanged) {
Zotero.DataObject.prototype.reload = async function (dataTypes, reloadUnchanged) {
if (!this._id) {
return;
}
@ -682,11 +682,11 @@ Zotero.DataObject.prototype.reload = Zotero.Promise.coroutine(function* (dataTyp
|| (!reloadUnchanged && !this._changed[dataType] && !this._dataTypesToReload.has(dataType))) {
continue;
}
yield this.loadDataType(dataType, true);
await this.loadDataType(dataType, true);
this._dataTypesToReload.delete(dataType);
}
}
});
};
/**
* Checks whether a given data type has been loaded
@ -727,14 +727,14 @@ Zotero.DataObject.prototype.loadDataType = function (dataType, reload) {
return this._ObjectsClass._loadDataTypeInLibrary(dataType, this.libraryID, [this.id]);
}
Zotero.DataObject.prototype.loadAllData = Zotero.Promise.coroutine(function* (reload) {
Zotero.DataObject.prototype.loadAllData = async function (reload) {
for (let i=0; i<this._dataTypes.length; i++) {
let type = this._dataTypes[i];
if (!this._skipDataTypeLoad[type]) {
yield this.loadDataType(type, reload);
await this.loadDataType(type, reload);
}
}
});
};
Zotero.DataObject.prototype._markAllDataTypeLoadStates = function (loaded) {
for (let i = 0; i < this._dataTypes.length; i++) {
@ -798,7 +798,7 @@ Zotero.DataObject.prototype._markFieldChange = function (field, value) {
}
Zotero.DataObject.prototype.hasChanged = function() {
Zotero.DataObject.prototype.hasChanged = function () {
var changed = Object.keys(this._changed).filter(dataType => this._changed[dataType])
.concat(Object.keys(this._changedData));
if (changed.length == 1
@ -905,7 +905,7 @@ Zotero.DataObject.prototype.isEditable = function (_op = 'edit') {
* @return {Promise<Integer|Boolean>} Promise for itemID of new item,
* TRUE on item update, or FALSE if item was unchanged
*/
Zotero.DataObject.prototype.save = Zotero.Promise.coroutine(function* (options = {}) {
Zotero.DataObject.prototype.save = async function (options = {}) {
var env = {
options: Object.assign({}, options),
transactionOptions: {}
@ -929,7 +929,7 @@ Zotero.DataObject.prototype.save = Zotero.Promise.coroutine(function* (options =
].forEach(x => env.options[x] = true);
}
var proceed = yield this._initSave(env);
var proceed = await this._initSave(env);
if (!proceed) return false;
if (env.isNew) {
@ -968,7 +968,7 @@ Zotero.DataObject.prototype.save = Zotero.Promise.coroutine(function* (options =
// Create transaction
let result
if (env.options.tx) {
result = yield Zotero.DB.executeTransaction(async function () {
result = await Zotero.DB.executeTransaction(async function () {
Zotero.DataObject.prototype._saveData.call(this, env);
await this._saveData(env);
await Zotero.DataObject.prototype._finalizeSave.call(this, env);
@ -979,8 +979,8 @@ Zotero.DataObject.prototype.save = Zotero.Promise.coroutine(function* (options =
else {
Zotero.DB.requireTransaction();
Zotero.DataObject.prototype._saveData.call(this, env);
yield this._saveData(env);
yield Zotero.DataObject.prototype._finalizeSave.call(this, env);
await this._saveData(env);
await Zotero.DataObject.prototype._finalizeSave.call(this, env);
result = this._finalizeSave(env);
}
this._postSave(env);
@ -988,10 +988,10 @@ Zotero.DataObject.prototype.save = Zotero.Promise.coroutine(function* (options =
}
catch(e) {
return this._recoverFromSaveError(env, e)
.catch(function(e2) {
.catch(function (e2) {
Zotero.debug(e2, 1);
})
.then(function() {
.then(function () {
if (env.options.errorHandler) {
env.options.errorHandler(e);
}
@ -1001,7 +1001,7 @@ Zotero.DataObject.prototype.save = Zotero.Promise.coroutine(function* (options =
throw e;
})
}
});
};
Zotero.DataObject.prototype.saveTx = function (options = {}) {
@ -1011,7 +1011,7 @@ Zotero.DataObject.prototype.saveTx = function (options = {}) {
}
Zotero.DataObject.prototype._initSave = Zotero.Promise.coroutine(function* (env) {
Zotero.DataObject.prototype._initSave = async function (env) {
// Default to user library if not specified
if (this.libraryID === null) {
this._libraryID = Zotero.Libraries.userLibraryID;
@ -1053,7 +1053,7 @@ Zotero.DataObject.prototype._initSave = Zotero.Promise.coroutine(function* (env)
env.relationsToUnregister = [];
return true;
});
};
Zotero.DataObject.prototype._saveData = function (env) {
var libraryID = env.libraryID = this.libraryID || Zotero.Libraries.userLibraryID;
@ -1101,7 +1101,7 @@ Zotero.DataObject.prototype._saveData = function (env) {
}
};
Zotero.DataObject.prototype._finalizeSave = Zotero.Promise.coroutine(function* (env) {
Zotero.DataObject.prototype._finalizeSave = async function (env) {
// Relations
if (this._changed.relations) {
let toAdd, toRemove;
@ -1123,13 +1123,13 @@ Zotero.DataObject.prototype._finalizeSave = Zotero.Promise.coroutine(function* (
// Convert predicates to ids
let toAddConverted = [];
for (let rel of toAdd) {
let predicateID = yield Zotero.RelationPredicates.add(rel[0]);
let predicateID = await Zotero.RelationPredicates.add(rel[0]);
let object = rel[1];
toAddConverted.push([predicateID, object]);
}
let sql = "INSERT INTO " + this._objectType + "Relations "
+ "(" + this._ObjectsClass.idColumn + ", predicateID, object) VALUES ";
yield Zotero.Utilities.Internal.forEachChunkAsync(
await Zotero.Utilities.Internal.forEachChunkAsync(
toAddConverted,
Math.floor(Zotero.DB.MAX_BOUND_PARAMETERS / 3),
async function (chunk) {
@ -1147,11 +1147,11 @@ Zotero.DataObject.prototype._finalizeSave = Zotero.Promise.coroutine(function* (
for (let i = 0; i < toRemove.length; i++) {
let sql = "DELETE FROM " + this._objectType + "Relations "
+ "WHERE " + this._ObjectsClass.idColumn + "=? AND predicateID=? AND object=?";
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
sql,
[
this.id,
(yield Zotero.RelationPredicates.add(toRemove[i][0])),
((await Zotero.RelationPredicates.add(toRemove[i][0]))),
toRemove[i][1]
]
);
@ -1174,7 +1174,7 @@ Zotero.DataObject.prototype._finalizeSave = Zotero.Promise.coroutine(function* (
else if (env.skipCache) {
Zotero.logError("skipCache is only for new objects");
}
});
};
/**
@ -1193,10 +1193,10 @@ Zotero.DataObject.prototype._postSave = function (env) {
};
Zotero.DataObject.prototype._recoverFromSaveError = Zotero.Promise.coroutine(function* (env) {
yield this.reload(null, true);
Zotero.DataObject.prototype._recoverFromSaveError = async function (env) {
await this.reload(null, true);
this._clearChanged();
});
};
/**
@ -1207,7 +1207,7 @@ Zotero.DataObject.prototype._recoverFromSaveError = Zotero.Promise.coroutine(fun
* @param {Integer} version
* @param {Boolean} [skipDB=false]
*/
Zotero.DataObject.prototype.updateVersion = Zotero.Promise.coroutine(function* (version, skipDB) {
Zotero.DataObject.prototype.updateVersion = async function (version, skipDB) {
if (!this.id) {
throw new Error("Cannot update version of unsaved " + this._objectType);
}
@ -1220,7 +1220,7 @@ Zotero.DataObject.prototype.updateVersion = Zotero.Promise.coroutine(function* (
if (!skipDB) {
var cl = this.ObjectsClass;
var sql = "UPDATE " + cl.table + " SET version=? WHERE " + cl.idColumn + "=?";
yield Zotero.DB.queryAsync(sql, [parseInt(version), this.id]);
await Zotero.DB.queryAsync(sql, [parseInt(version), this.id]);
}
if (this._changed.primaryData && this._changed.primaryData.version) {
@ -1231,7 +1231,7 @@ Zotero.DataObject.prototype.updateVersion = Zotero.Promise.coroutine(function* (
delete this._changed.primaryData.version;
}
}
});
};
/**
* Update object sync status, efficiently
@ -1241,7 +1241,7 @@ Zotero.DataObject.prototype.updateVersion = Zotero.Promise.coroutine(function* (
* @param {Boolean} synced
* @param {Boolean} [skipDB=false]
*/
Zotero.DataObject.prototype.updateSynced = Zotero.Promise.coroutine(function* (synced, skipDB) {
Zotero.DataObject.prototype.updateSynced = async function (synced, skipDB) {
if (!this.id) {
throw new Error("Cannot update sync status of unsaved " + this._objectType);
}
@ -1254,7 +1254,7 @@ Zotero.DataObject.prototype.updateSynced = Zotero.Promise.coroutine(function* (s
if (!skipDB) {
var cl = this.ObjectsClass;
var sql = "UPDATE " + cl.table + " SET synced=? WHERE " + cl.idColumn + "=?";
yield Zotero.DB.queryAsync(sql, [synced ? 1 : 0, this.id]);
await Zotero.DB.queryAsync(sql, [synced ? 1 : 0, this.id]);
}
if (this._changed.primaryData && this._changed.primaryData.synced) {
@ -1265,7 +1265,7 @@ Zotero.DataObject.prototype.updateSynced = Zotero.Promise.coroutine(function* (s
delete this._changed.primaryData.synced;
}
}
});
};
/**
* Delete object from database
@ -1274,7 +1274,7 @@ Zotero.DataObject.prototype.updateSynced = Zotero.Promise.coroutine(function* (s
* @param {Boolean} [options.deleteItems] - Move descendant items to trash (Collection only)
* @param {Boolean} [options.skipDeleteLog] - Don't add to sync delete log
*/
Zotero.DataObject.prototype.erase = Zotero.Promise.coroutine(function* (options = {}) {
Zotero.DataObject.prototype.erase = async function (options = {}) {
if (!options || typeof options != 'object') {
throw new Error("'options' must be an object (" + typeof options + ")");
}
@ -1290,7 +1290,7 @@ Zotero.DataObject.prototype.erase = Zotero.Promise.coroutine(function* (options
env.options.tx = true;
}
let proceed = yield this._initErase(env);
let proceed = await this._initErase(env);
if (!proceed) return false;
Zotero.debug('Deleting ' + this.objectType + ' ' + this.id);
@ -1303,10 +1303,10 @@ Zotero.DataObject.prototype.erase = Zotero.Promise.coroutine(function* (options
}
else {
Zotero.DB.requireTransaction();
yield this._eraseData(env);
yield this._finalizeErase(env);
await this._eraseData(env);
await this._finalizeErase(env);
}
});
};
Zotero.DataObject.prototype.eraseTx = function (options) {
options = options || {};
@ -1314,7 +1314,7 @@ Zotero.DataObject.prototype.eraseTx = function (options) {
return this.erase(options);
};
Zotero.DataObject.prototype._initErase = Zotero.Promise.method(function (env) {
Zotero.DataObject.prototype._initErase = function (env) {
env.notifierData = {};
env.notifierData[this.id] = {
libraryID: this.libraryID,
@ -1329,12 +1329,12 @@ Zotero.DataObject.prototype._initErase = Zotero.Promise.method(function (env) {
}
return true;
});
};
Zotero.DataObject.prototype._finalizeErase = Zotero.Promise.coroutine(function* (env) {
Zotero.DataObject.prototype._finalizeErase = async function (env) {
// Delete versions from sync cache
if (this._objectType != 'feedItem') {
yield Zotero.Sync.Data.Local.deleteCacheObjectVersions(
await Zotero.Sync.Data.Local.deleteCacheObjectVersions(
this.objectType, this._libraryID, this._key
);
}
@ -1356,7 +1356,7 @@ Zotero.DataObject.prototype._finalizeErase = Zotero.Promise.coroutine(function*
env.options.notifierQueue
);
}
});
};
Zotero.DataObject.prototype.toResponseJSON = function (options = {}) {

View file

@ -62,14 +62,14 @@ Zotero.DataObjects.prototype._ZDO_idOnly = false;
// Public properties
Zotero.defineProperty(Zotero.DataObjects.prototype, 'idColumn', {
get: function() { return this._ZDO_id; }
get: function () { return this._ZDO_id; }
});
Zotero.defineProperty(Zotero.DataObjects.prototype, 'table', {
get: function() { return this._ZDO_table; }
get: function () { return this._ZDO_table; }
});
Zotero.defineProperty(Zotero.DataObjects.prototype, 'relationsTable', {
get: function() { return this._ZDO_object + 'Relations'; }
get: function () { return this._ZDO_object + 'Relations'; }
});
Zotero.defineProperty(Zotero.DataObjects.prototype, 'primaryFields', {
@ -81,10 +81,10 @@ Zotero.defineProperty(Zotero.DataObjects.prototype, "_primaryDataSQLWhere", {
});
Zotero.defineProperty(Zotero.DataObjects.prototype, 'primaryDataSQLFrom', {
get: function() { return " " + this._primaryDataSQLFrom + " " + this._primaryDataSQLWhere; }
get: function () { return " " + this._primaryDataSQLFrom + " " + this._primaryDataSQLWhere; }
}, {lateInit: true});
Zotero.DataObjects.prototype.init = function() {
Zotero.DataObjects.prototype.init = function () {
return this._loadIDsAndKeys();
}
@ -150,7 +150,7 @@ Zotero.DataObjects.prototype.get = function (ids) {
* @return {Promise<Zotero.DataObject|Zotero.DataObject[]>} - A promise for either a data object,
* if a scalar id was passed, or an array of data objects, if an array of ids was passed
*/
Zotero.DataObjects.prototype.getAsync = Zotero.Promise.coroutine(function* (ids, options) {
Zotero.DataObjects.prototype.getAsync = async function (ids, options) {
var toLoad = [];
var toReturn = [];
@ -194,12 +194,12 @@ Zotero.DataObjects.prototype.getAsync = Zotero.Promise.coroutine(function* (ids,
if (toLoad.length) {
// Serialize loads
if (this._loadPromise && this._loadPromise.isPending()) {
yield this._loadPromise;
await this._loadPromise;
}
let deferred = Zotero.Promise.defer();
this._loadPromise = deferred.promise;
let loaded = yield this._load(null, toLoad, options);
let loaded = await this._load(null, toLoad, options);
for (let i=0; i<toLoad.length; i++) {
let id = toLoad[i];
let obj = loaded[id];
@ -218,7 +218,7 @@ Zotero.DataObjects.prototype.getAsync = Zotero.Promise.coroutine(function* (ids,
}
return toReturn;
});
};
/**
@ -345,13 +345,13 @@ Zotero.DataObjects.prototype.getByLibraryAndKey = function (libraryID, key, opti
* @param {Boolean} [options.noCache=false] - Don't add object to cache after loading
* @return {Promise<Zotero.DataObject>} - Promise for a data object, or FALSE if not found
*/
Zotero.DataObjects.prototype.getByLibraryAndKeyAsync = Zotero.Promise.method(function (libraryID, key, options) {
Zotero.DataObjects.prototype.getByLibraryAndKeyAsync = function (libraryID, key, options) {
var id = this.getIDFromLibraryAndKey(libraryID, key);
if (!id) {
return false;
}
return Zotero[this._ZDO_Objects].getAsync(id, options);
});
};
Zotero.DataObjects.prototype.exists = function (id) {
@ -383,7 +383,7 @@ Zotero.DataObjects.prototype.getIDFromLibraryAndKey = function (libraryID, key)
}
Zotero.DataObjects.prototype.getOlder = Zotero.Promise.method(function (libraryID, date) {
Zotero.DataObjects.prototype.getOlder = function (libraryID, date) {
if (!date || date.constructor.name != 'Date') {
throw ("date must be a JS Date in "
+ "Zotero." + this._ZDO_Objects + ".getOlder()")
@ -392,10 +392,10 @@ Zotero.DataObjects.prototype.getOlder = Zotero.Promise.method(function (libraryI
var sql = "SELECT ROWID FROM " + this._ZDO_table
+ " WHERE libraryID=? AND clientDateModified<?";
return Zotero.DB.columnQueryAsync(sql, [libraryID, Zotero.Date.dateToSQL(date, true)]);
});
};
Zotero.DataObjects.prototype.getNewer = Zotero.Promise.method(function (libraryID, date, ignoreFutureDates) {
Zotero.DataObjects.prototype.getNewer = function (libraryID, date, ignoreFutureDates) {
if (!date || date.constructor.name != 'Date') {
throw ("date must be a JS Date in "
+ "Zotero." + this._ZDO_Objects + ".getNewer()")
@ -407,7 +407,7 @@ Zotero.DataObjects.prototype.getNewer = Zotero.Promise.method(function (libraryI
sql += " AND clientDateModified<=CURRENT_TIMESTAMP";
}
return Zotero.DB.columnQueryAsync(sql, [libraryID, Zotero.Date.dateToSQL(date, true)]);
});
};
/**
@ -416,27 +416,27 @@ Zotero.DataObjects.prototype.getNewer = Zotero.Promise.method(function (libraryI
* @return {Promise<Object>} - A promise for an object with object keys as keys and versions
* as properties
*/
Zotero.DataObjects.prototype.getObjectVersions = Zotero.Promise.coroutine(function* (libraryID, keys = null) {
Zotero.DataObjects.prototype.getObjectVersions = async function (libraryID, keys = null) {
var versions = {};
if (keys) {
yield Zotero.Utilities.Internal.forEachChunkAsync(
await Zotero.Utilities.Internal.forEachChunkAsync(
keys,
Zotero.DB.MAX_BOUND_PARAMETERS - 1,
Zotero.Promise.coroutine(function* (chunk) {
async function (chunk) {
var sql = "SELECT key, version FROM " + this._ZDO_table
+ " WHERE libraryID=? AND key IN (" + chunk.map(key => '?').join(', ') + ")";
var rows = yield Zotero.DB.queryAsync(sql, [libraryID].concat(chunk));
var rows = await Zotero.DB.queryAsync(sql, [libraryID].concat(chunk));
for (let i = 0; i < rows.length; i++) {
let row = rows[i];
versions[row.key] = row.version;
}
}.bind(this))
}.bind(this)
);
}
else {
let sql = "SELECT key, version FROM " + this._ZDO_table + " WHERE libraryID=?";
let rows = yield Zotero.DB.queryAsync(sql, [libraryID]);
let rows = await Zotero.DB.queryAsync(sql, [libraryID]);
for (let i = 0; i < rows.length; i++) {
let row = rows[i];
versions[row.key] = row.version;
@ -444,7 +444,7 @@ Zotero.DataObjects.prototype.getObjectVersions = Zotero.Promise.coroutine(functi
}
return versions;
});
};
/**
@ -457,7 +457,7 @@ Zotero.DataObjects.prototype.getObjectVersions = Zotero.Promise.coroutine(functi
* @param {String[]} [dataTypes] - Data types to load, defaulting to all types
* @return {Promise}
*/
Zotero.DataObjects.prototype.loadDataTypes = Zotero.Promise.coroutine(function* (objects, dataTypes) {
Zotero.DataObjects.prototype.loadDataTypes = async function (objects, dataTypes) {
if (!dataTypes) {
dataTypes = this.ObjectClass.prototype._dataTypes;
}
@ -473,10 +473,10 @@ Zotero.DataObjects.prototype.loadDataTypes = Zotero.Promise.coroutine(function*
typeIDsByLibrary[obj.libraryID].push(obj.id);
}
for (let libraryID in typeIDsByLibrary) {
yield this._loadDataTypeInLibrary(dataType, parseInt(libraryID), typeIDsByLibrary[libraryID]);
await this._loadDataTypeInLibrary(dataType, parseInt(libraryID), typeIDsByLibrary[libraryID]);
}
}
});
};
/**
@ -485,7 +485,7 @@ Zotero.DataObjects.prototype.loadDataTypes = Zotero.Promise.coroutine(function*
* @param {Integer} libraryID
* @param {Integer[]} [ids]
*/
Zotero.DataObjects.prototype._loadDataTypeInLibrary = Zotero.Promise.coroutine(function* (dataType, libraryID, ids) {
Zotero.DataObjects.prototype._loadDataTypeInLibrary = async function (dataType, libraryID, ids) {
// note → loadNotes
// itemData → loadItemData
// annotationDeferred → loadAnnotationsDeferred
@ -516,12 +516,12 @@ Zotero.DataObjects.prototype._loadDataTypeInLibrary = Zotero.Promise.coroutine(f
: this._ZDO_objects)
+ " in " + libraryName);
yield this[funcName](libraryID, ids ? ids : [], idSQL);
await this[funcName](libraryID, ids ? ids : [], idSQL);
Zotero.debug(`Loaded ${dataType} in ${libraryName} in ${new Date() - t} ms`);
});
};
Zotero.DataObjects.prototype.loadAll = Zotero.Promise.coroutine(function* (libraryID, ids) {
Zotero.DataObjects.prototype.loadAll = async function (libraryID, ids) {
var t = new Date();
var library = Zotero.Libraries.get(libraryID)
@ -536,7 +536,7 @@ Zotero.DataObjects.prototype.loadAll = Zotero.Promise.coroutine(function* (libra
let dataTypes = this.ObjectClass.prototype._dataTypes;
for (let i = 0; i < dataTypes.length; i++) {
yield this._loadDataTypeInLibrary(dataTypes[i], libraryID, ids);
await this._loadDataTypeInLibrary(dataTypes[i], libraryID, ids);
}
Zotero.debug(`Loaded ${this._ZDO_objects} in ${library.name} in ${new Date() - t} ms`);
@ -544,10 +544,10 @@ Zotero.DataObjects.prototype.loadAll = Zotero.Promise.coroutine(function* (libra
if (!ids) {
library.setDataLoaded(this._ZDO_object);
}
});
};
Zotero.DataObjects.prototype._loadPrimaryData = Zotero.Promise.coroutine(function* (libraryID, ids, idSQL, options) {
Zotero.DataObjects.prototype._loadPrimaryData = async function (libraryID, ids, idSQL, options) {
var loaded = {};
// If library isn't an integer (presumably false or null), skip it
@ -565,7 +565,7 @@ Zotero.DataObjects.prototype._loadPrimaryData = Zotero.Promise.coroutine(functio
sql += ' AND O.' + this._ZDO_id + ' IN (' + ids.join(',') + ')';
}
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
sql,
params,
{
@ -617,10 +617,10 @@ Zotero.DataObjects.prototype._loadPrimaryData = Zotero.Promise.coroutine(functio
}
return loaded;
});
};
Zotero.DataObjects.prototype._loadRelations = Zotero.Promise.coroutine(function* (libraryID, ids, idSQL) {
Zotero.DataObjects.prototype._loadRelations = async function (libraryID, ids, idSQL) {
if (!this._relationsTable) {
throw new Error("Relations not supported for " + this._ZDO_objects);
}
@ -679,7 +679,7 @@ Zotero.DataObjects.prototype._loadRelations = Zotero.Promise.coroutine(function*
obj._clearChanged('relations');
}.bind(this);
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
sql,
params,
{
@ -709,7 +709,7 @@ Zotero.DataObjects.prototype._loadRelations = Zotero.Promise.coroutine(function*
if (lastID) {
setRows(lastID, rows);
}
});
};
/**
@ -895,7 +895,7 @@ Zotero.DataObjects.prototype.flattenRelations = function (relations) {
* This should be set to true for data that was
* changed externally (e.g., globally renamed tags).
*/
Zotero.DataObjects.prototype.reload = Zotero.Promise.coroutine(function* (ids, dataTypes, reloadUnchanged) {
Zotero.DataObjects.prototype.reload = async function (ids, dataTypes, reloadUnchanged) {
ids = Zotero.flattenArguments(ids);
Zotero.debug('Reloading ' + (dataTypes ? '[' + dataTypes.join(', ') + '] for ' : '')
@ -906,7 +906,7 @@ Zotero.DataObjects.prototype.reload = Zotero.Promise.coroutine(function* (ids, d
if (!dataTypes) {
for (let i=0; i<ids.length; i++) {
if (this._objectCache[ids[i]]) {
yield this._objectCache[ids[i]].reload(dataTypes, reloadUnchanged);
await this._objectCache[ids[i]].reload(dataTypes, reloadUnchanged);
}
}
return;
@ -926,12 +926,12 @@ Zotero.DataObjects.prototype.reload = Zotero.Promise.coroutine(function* (ids, d
typeIDsByLibrary[obj.libraryID].push(id);
}
for (let libraryID in typeIDsByLibrary) {
yield this._loadDataTypeInLibrary(dataType, parseInt(libraryID), typeIDsByLibrary[libraryID]);
await this._loadDataTypeInLibrary(dataType, parseInt(libraryID), typeIDsByLibrary[libraryID]);
}
}
return true;
});
};
Zotero.DataObjects.prototype.reloadAll = function (libraryID) {
@ -974,7 +974,7 @@ Zotero.DataObjects.prototype.registerObject = function (obj) {
obj._inCache = true;
}
Zotero.DataObjects.prototype.dropDeadObjectsFromCache = function() {
Zotero.DataObjects.prototype.dropDeadObjectsFromCache = function () {
let ids = [];
for (let libraryID in this._objectIDs) {
if (Zotero.Libraries.exists(libraryID)) continue;
@ -1011,7 +1011,7 @@ Zotero.DataObjects.prototype.unload = function () {
* @param {Integer[]} ids - Ids of objects to update
* @param {Boolean} version
*/
Zotero.DataObjects.prototype.updateVersion = Zotero.Promise.method(function (ids, version) {
Zotero.DataObjects.prototype.updateVersion = function (ids, version) {
if (version != parseInt(version)) {
throw new Error("'version' must be an integer ('" + version + "' given)");
}
@ -1022,8 +1022,8 @@ Zotero.DataObjects.prototype.updateVersion = Zotero.Promise.method(function (ids
return Zotero.Utilities.Internal.forEachChunkAsync(
ids,
Zotero.DB.MAX_BOUND_PARAMETERS,
Zotero.Promise.coroutine(function* (chunk) {
yield Zotero.DB.queryAsync(sql + chunk.map(() => '?').join(', ') + ')', chunk);
async function (chunk) {
await Zotero.DB.queryAsync(sql + chunk.map(() => '?').join(', ') + ')', chunk);
// Update the internal 'version' property of any loaded objects
for (let i = 0; i < chunk.length; i++) {
let id = chunk[i];
@ -1032,9 +1032,9 @@ Zotero.DataObjects.prototype.updateVersion = Zotero.Promise.method(function (ids
obj.updateVersion(version, true);
}
}
}.bind(this))
}.bind(this)
);
});
};
/**
@ -1043,14 +1043,14 @@ Zotero.DataObjects.prototype.updateVersion = Zotero.Promise.method(function (ids
* @param {Integer[]} ids - Ids of objects to update
* @param {Boolean} synced
*/
Zotero.DataObjects.prototype.updateSynced = Zotero.Promise.method(function (ids, synced) {
Zotero.DataObjects.prototype.updateSynced = function (ids, synced) {
let sql = "UPDATE " + this.table + " SET synced=" + (synced ? 1 : 0) + " "
+ "WHERE " + this.idColumn + " IN (";
return Zotero.Utilities.Internal.forEachChunkAsync(
ids,
Zotero.DB.MAX_BOUND_PARAMETERS,
Zotero.Promise.coroutine(function* (chunk) {
yield Zotero.DB.queryAsync(sql + chunk.map(() => '?').join(', ') + ')', chunk);
async function (chunk) {
await Zotero.DB.queryAsync(sql + chunk.map(() => '?').join(', ') + ')', chunk);
// Update the internal 'synced' property of any loaded objects
for (let i = 0; i < chunk.length; i++) {
let id = chunk[i];
@ -1059,9 +1059,9 @@ Zotero.DataObjects.prototype.updateSynced = Zotero.Promise.method(function (ids,
obj.updateSynced(!!synced, true);
}
}
}.bind(this))
}.bind(this)
);
});
};
Zotero.DataObjects.prototype.isEditable = function (obj) {
@ -1108,9 +1108,9 @@ Zotero.DataObjects.prototype.getPrimaryDataSQLPart = function (part) {
* @param {Function} [options.onProgress] - f(progress, progressMax)
* @return {Promise}
*/
Zotero.DataObjects.prototype.erase = Zotero.Promise.coroutine(function* (ids, options = {}) {
Zotero.DataObjects.prototype.erase = async function (ids, options = {}) {
ids = Zotero.flattenArguments(ids);
yield Zotero.DB.executeTransaction(async function () {
await Zotero.DB.executeTransaction(async function () {
for (let i = 0; i < ids.length; i++) {
let obj = await this.getAsync(ids[i]);
if (!obj) {
@ -1123,11 +1123,11 @@ Zotero.DataObjects.prototype.erase = Zotero.Promise.coroutine(function* (ids, op
}
this.unload(ids);
}.bind(this));
});
};
// TEMP: remove
Zotero.DataObjects.prototype._load = Zotero.Promise.coroutine(function* (libraryID, ids, options) {
Zotero.DataObjects.prototype._load = async function (libraryID, ids, options) {
var loaded = {};
// If library isn't an integer (presumably false or null), skip it
@ -1154,7 +1154,7 @@ Zotero.DataObjects.prototype._load = Zotero.Promise.coroutine(function* (library
}
var t = new Date();
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
sql,
params,
{
@ -1206,17 +1206,17 @@ Zotero.DataObjects.prototype._load = Zotero.Promise.coroutine(function* (library
}
return loaded;
});
};
Zotero.DataObjects.prototype._getObjectForRow = function(row) {
Zotero.DataObjects.prototype._getObjectForRow = function (row) {
return new Zotero[this._ZDO_Object];
};
Zotero.DataObjects.prototype._loadIDsAndKeys = Zotero.Promise.coroutine(function* () {
Zotero.DataObjects.prototype._loadIDsAndKeys = async function () {
var sql = "SELECT ROWID AS id, libraryID, key FROM " + this._ZDO_table;
var rows = yield Zotero.DB.queryAsync(sql);
var rows = await Zotero.DB.queryAsync(sql);
for (let i=0; i<rows.length; i++) {
let row = rows[i];
this._objectKeys[row.id] = [row.libraryID, row.key];
@ -1225,4 +1225,4 @@ Zotero.DataObjects.prototype._loadIDsAndKeys = Zotero.Promise.coroutine(function
}
this._objectIDs[row.libraryID][row.key] = row.id;
}
});
};

View file

@ -37,7 +37,7 @@
* @returns Zotero.Feed
* @constructor
*/
Zotero.Feed = function(params = {}) {
Zotero.Feed = function (params = {}) {
params.libraryType = 'feed';
Zotero.Feed._super.call(this, params);
@ -51,13 +51,13 @@ Zotero.Feed = function(params = {}) {
// Feeds are not editable by the user. Remove the setter
this.editable = false;
Zotero.defineProperty(this, 'editable', {
get: function() { return this._get('_libraryEditable'); }
get: function () { return this._get('_libraryEditable'); }
});
// Feeds are not filesEditable by the user. Remove the setter
this.filesEditable = false;
Zotero.defineProperty(this, 'filesEditable', {
get: function() { return this._get('_libraryFilesEditable'); }
get: function () { return this._get('_libraryFilesEditable'); }
});
Zotero.Utilities.Internal.assignProps(this, params,
@ -65,7 +65,7 @@ Zotero.Feed = function(params = {}) {
// Return a proxy so that we can disable the object once it's deleted
return new Proxy(this, {
get: function(obj, prop) {
get: function (obj, prop) {
if (obj._disabled && !(prop == 'libraryID' || prop == 'id' || prop == 'treeViewID' || prop == 'name')) {
throw new Error("Feed " + obj.libraryID + " has been disabled");
}
@ -74,7 +74,7 @@ Zotero.Feed = function(params = {}) {
});
}
Zotero.Feed._colToProp = function(c) {
Zotero.Feed._colToProp = function (c) {
return "_feed" + Zotero.Utilities.capitalize(c);
}
@ -124,21 +124,21 @@ Zotero.defineProperty(Zotero.Feed.prototype, 'libraryTypeID', {
});
Zotero.defineProperty(Zotero.Feed.prototype, 'unreadCount', {
get: function() { return this._feedUnreadCount; }
get: function () { return this._feedUnreadCount; }
});
Zotero.defineProperty(Zotero.Feed.prototype, 'updating', {
get: function() { return !!this._updating; }
get: function () { return !!this._updating; }
});
(function() {
(function () {
// Create accessors
let accessors = ['name', 'url', 'refreshInterval', 'cleanupUnreadAfter', 'cleanupReadAfter'];
for (let i=0; i<accessors.length; i++) {
let name = accessors[i];
let prop = Zotero.Feed._colToProp(name);
Zotero.defineProperty(Zotero.Feed.prototype, name, {
get: function() { return this._get(prop); },
set: function(v) { return this._set(prop, v); }
get: function () { return this._get(prop); },
set: function (v) { return this._set(prop, v); }
})
}
let getters = ['lastCheck', 'lastUpdate', 'lastCheckError'];
@ -146,12 +146,12 @@ for (let i=0; i<getters.length; i++) {
let name = getters[i];
let prop = Zotero.Feed._colToProp(name);
Zotero.defineProperty(Zotero.Feed.prototype, name, {
get: function() { return this._get(prop); }
get: function () { return this._get(prop); }
})
}
})()
Zotero.Feed.prototype._isValidFeedProp = function(prop) {
Zotero.Feed.prototype._isValidFeedProp = function (prop) {
let preffix = '_feed';
if (prop.indexOf(preffix) != 0 || prop.length == preffix.length) {
return false;
@ -163,7 +163,7 @@ Zotero.Feed.prototype._isValidFeedProp = function(prop) {
return Zotero.Feed._dbColumns.indexOf(col) != -1;
}
Zotero.Feed.prototype._isValidProp = function(prop) {
Zotero.Feed.prototype._isValidProp = function (prop) {
return this._isValidFeedProp(prop)
|| Zotero.Feed._super.prototype._isValidProp.call(this, prop);
}
@ -217,7 +217,7 @@ Zotero.Feed.prototype._set = function (prop, val) {
return Zotero.Feed._super.prototype._set.call(this, prop, val);
}
Zotero.Feed.prototype._loadDataFromRow = function(row) {
Zotero.Feed.prototype._loadDataFromRow = function (row) {
Zotero.Feed._super.prototype._loadDataFromRow.call(this, row);
this._feedName = row._feedName;
@ -231,18 +231,18 @@ Zotero.Feed.prototype._loadDataFromRow = function(row) {
this._feedUnreadCount = parseInt(row._feedUnreadCount);
}
Zotero.Feed.prototype._reloadFromDB = Zotero.Promise.coroutine(function* () {
Zotero.Feed.prototype._reloadFromDB = async function () {
let sql = Zotero.Feed._rowSQL + " WHERE F.libraryID=?";
let row = yield Zotero.DB.rowQueryAsync(sql, [this.libraryID]);
let row = await Zotero.DB.rowQueryAsync(sql, [this.libraryID]);
this._loadDataFromRow(row);
});
};
Zotero.defineProperty(Zotero.Feed.prototype, '_childObjectTypes', {
value: Object.freeze(['feedItem', 'item'])
});
Zotero.Feed.prototype._initSave = Zotero.Promise.coroutine(function* (env) {
let proceed = yield Zotero.Feed._super.prototype._initSave.call(this, env);
Zotero.Feed.prototype._initSave = async function (env) {
let proceed = await Zotero.Feed._super.prototype._initSave.call(this, env);
if (!proceed) return false;
if (!this._feedName) throw new Error("Feed name not set");
@ -259,10 +259,10 @@ Zotero.Feed.prototype._initSave = Zotero.Promise.coroutine(function* (env) {
}
return true;
});
};
Zotero.Feed.prototype._saveData = Zotero.Promise.coroutine(function* (env) {
yield Zotero.Feed._super.prototype._saveData.apply(this, arguments);
Zotero.Feed.prototype._saveData = async function (env) {
await Zotero.Feed._super.prototype._saveData.apply(this, arguments);
Zotero.debug("Saving feed data for library " + this.id);
@ -283,7 +283,7 @@ Zotero.Feed.prototype._saveData = Zotero.Promise.coroutine(function* (env) {
let sql = "INSERT INTO feeds (" + changedCols.join(', ') + ") "
+ "VALUES (" + Array(params.length).fill('?').join(', ') + ")";
yield Zotero.DB.queryAsync(sql, params);
await Zotero.DB.queryAsync(sql, params);
Zotero.Notifier.queue(
'add', 'feed', this.libraryID, env.notifierData, env.options.notifierQueue
@ -293,7 +293,7 @@ Zotero.Feed.prototype._saveData = Zotero.Promise.coroutine(function* (env) {
let sql = "UPDATE feeds SET " + changedCols.map(v => v + '=?').join(', ')
+ " WHERE libraryID=?";
params.push(this.libraryID);
yield Zotero.DB.queryAsync(sql, params);
await Zotero.DB.queryAsync(sql, params);
if (!env.options.skipNotifier) {
Zotero.Notifier.queue(
@ -304,13 +304,13 @@ Zotero.Feed.prototype._saveData = Zotero.Promise.coroutine(function* (env) {
else {
Zotero.debug("Feed data did not change for feed " + this.libraryID, 5);
}
});
};
Zotero.Feed.prototype._finalizeSave = Zotero.Promise.coroutine(function* (env) {
Zotero.Feed.prototype._finalizeSave = async function (env) {
let syncedDataChanged =
['_feedName', '_feedCleanupReadAfter', '_feedCleanupUnreadAfter', '_feedRefreshInterval'].some((val) => this._changed[val]);
yield Zotero.Feed._super.prototype._finalizeSave.apply(this, arguments);
await Zotero.Feed._super.prototype._finalizeSave.apply(this, arguments);
if (!env.isNew && this._previousURL) {
// Re-register library if URL changed
@ -318,19 +318,19 @@ Zotero.Feed.prototype._finalizeSave = Zotero.Promise.coroutine(function* (env) {
let syncedFeeds = Zotero.SyncedSettings.get(Zotero.Libraries.userLibraryID, 'feeds') || {};
delete syncedFeeds[this._previousURL];
yield Zotero.SyncedSettings.set(Zotero.Libraries.userLibraryID, 'feeds', syncedFeeds);
await Zotero.SyncedSettings.set(Zotero.Libraries.userLibraryID, 'feeds', syncedFeeds);
}
if (syncedDataChanged || env.isNew || this._previousURL) {
yield this.storeSyncedSettings();
await this.storeSyncedSettings();
if (env.isNew || this._previousURL) {
Zotero.Feeds.register(this);
}
}
this._previousURL = null;
});
};
Zotero.Feed.prototype._finalizeErase = Zotero.Promise.coroutine(function* (env) {
Zotero.Feed.prototype._finalizeErase = async function (env) {
let notifierData = {};
notifierData[this.libraryID] = {
libraryID: this.libraryID
@ -341,28 +341,28 @@ Zotero.Feed.prototype._finalizeErase = Zotero.Promise.coroutine(function* (env)
let syncedFeeds = Zotero.SyncedSettings.get(Zotero.Libraries.userLibraryID, 'feeds') || {};
delete syncedFeeds[this.url];
if (Object.keys(syncedFeeds).length == 0) {
yield Zotero.SyncedSettings.clear(Zotero.Libraries.userLibraryID, 'feeds');
await Zotero.SyncedSettings.clear(Zotero.Libraries.userLibraryID, 'feeds');
} else {
yield Zotero.SyncedSettings.set(Zotero.Libraries.userLibraryID, 'feeds', syncedFeeds);
await Zotero.SyncedSettings.set(Zotero.Libraries.userLibraryID, 'feeds', syncedFeeds);
}
return Zotero.Feed._super.prototype._finalizeErase.apply(this, arguments);
});
};
Zotero.Feed.prototype.erase = Zotero.Promise.coroutine(function* (options = {}) {
let childItemIDs = yield Zotero.FeedItems.getAll(this.id, false, false, true);
yield Zotero.FeedItems.erase(childItemIDs);
Zotero.Feed.prototype.erase = async function (options = {}) {
let childItemIDs = await Zotero.FeedItems.getAll(this.id, false, false, true);
await Zotero.FeedItems.erase(childItemIDs);
yield Zotero.Feed._super.prototype.erase.call(this, options);
});
await Zotero.Feed._super.prototype.erase.call(this, options);
};
Zotero.Feed.prototype.storeSyncedSettings = Zotero.Promise.coroutine(function* () {
Zotero.Feed.prototype.storeSyncedSettings = async function () {
let syncedFeeds = Zotero.SyncedSettings.get(Zotero.Libraries.userLibraryID, 'feeds') || {};
syncedFeeds[this.url] = [this.name, this.cleanupReadAfter, this.cleanupUnreadAfter, this.refreshInterval];
return Zotero.SyncedSettings.set(Zotero.Libraries.userLibraryID, 'feeds', syncedFeeds);
});
};
Zotero.Feed.prototype.getExpiredFeedItemIDs = Zotero.Promise.coroutine(function* () {
Zotero.Feed.prototype.getExpiredFeedItemIDs = async function () {
let sql = "SELECT itemID AS id FROM feedItems "
+ "LEFT JOIN items I USING (itemID) "
+ "WHERE I.libraryID=? "
@ -371,7 +371,7 @@ Zotero.Feed.prototype.getExpiredFeedItemIDs = Zotero.Promise.coroutine(function*
+ "OR (readTime IS NULL AND julianday('now', 'utc') - (julianday(dateModified, 'utc') + ?) > 0)"
+ ")";
return Zotero.DB.columnQueryAsync(sql, [this.id, {int: this.cleanupReadAfter}, {int: this.cleanupUnreadAfter}]);
});
};
/**
* Clearing conditions for an item:
@ -381,11 +381,11 @@ Zotero.Feed.prototype.getExpiredFeedItemIDs = Zotero.Promise.coroutine(function*
* If we clear items once they've been read, we may potentially end up
* with empty feeds for those that do not update very frequently.
*/
Zotero.Feed.prototype.clearExpiredItems = Zotero.Promise.coroutine(function* (itemsInFeedIDs) {
Zotero.Feed.prototype.clearExpiredItems = async function (itemsInFeedIDs) {
itemsInFeedIDs = itemsInFeedIDs || new Set();
try {
// Clear expired items
let expiredItems = yield this.getExpiredFeedItemIDs();
let expiredItems = await this.getExpiredFeedItemIDs();
let toClear = expiredItems;
if (itemsInFeedIDs.size) {
toClear = [];
@ -398,7 +398,7 @@ Zotero.Feed.prototype.clearExpiredItems = Zotero.Promise.coroutine(function* (it
Zotero.debug("Clearing up read feed items...");
if (toClear.length) {
Zotero.debug(toClear.join(', '));
yield Zotero.FeedItems.erase(toClear);
await Zotero.FeedItems.erase(toClear);
} else {
Zotero.debug("No expired feed items");
}
@ -406,24 +406,24 @@ Zotero.Feed.prototype.clearExpiredItems = Zotero.Promise.coroutine(function* (it
Zotero.debug("Error clearing expired feed items");
Zotero.debug(e);
}
});
};
Zotero.Feed.prototype._updateFeed = Zotero.Promise.coroutine(function* () {
Zotero.Feed.prototype._updateFeed = async function () {
var toSave = [], attachmentsToAdd = [], feedItemIDs = new Set();
if (this._updating) {
return this._updating;
}
let deferred = Zotero.Promise.defer();
this._updating = deferred.promise;
yield Zotero.Notifier.trigger('statusChanged', 'feed', this.id);
await Zotero.Notifier.trigger('statusChanged', 'feed', this.id);
this._set('_feedLastCheckError', null);
try {
let fr = new Zotero.FeedReader(this.url);
yield fr.process();
await fr.process();
let itemIterator = new fr.ItemIterator();
let item, processedGUIDs = new Set();
while (item = yield itemIterator.next().value) {
while (item = await itemIterator.next().value) {
if (processedGUIDs.has(item.guid)) {
Zotero.debug("Feed item " + item.guid + " already processed from feed");
continue;
@ -433,7 +433,7 @@ Zotero.Feed.prototype._updateFeed = Zotero.Promise.coroutine(function* () {
Zotero.debug("Feed item retrieved:", 5);
Zotero.debug(item, 5);
let feedItem = yield Zotero.FeedItems.getAsyncByGUID(item.guid);
let feedItem = await Zotero.FeedItems.getAsyncByGUID(item.guid);
if (feedItem) {
feedItemIDs.add(feedItem.id);
}
@ -487,7 +487,7 @@ Zotero.Feed.prototype._updateFeed = Zotero.Promise.coroutine(function* () {
this._set('_feedLastCheckError', e.message || 'Error processing feed');
}
if (toSave.length) {
yield Zotero.DB.executeTransaction(async function () {
await Zotero.DB.executeTransaction(async function () {
// Save in reverse order
for (let i=toSave.length-1; i>=0; i--) {
await toSave[i].save();
@ -500,35 +500,35 @@ Zotero.Feed.prototype._updateFeed = Zotero.Promise.coroutine(function* () {
if (attachment.url.indexOf('pdf') != -1 || attachment.contentType.indexOf('pdf') != -1) {
attachment.parentItemID = attachment.parentItem.id;
attachment.title = Zotero.getString('file-type-pdf');
yield Zotero.Attachments.linkFromURL(attachment);
await Zotero.Attachments.linkFromURL(attachment);
}
}
yield this.clearExpiredItems(feedItemIDs);
await this.clearExpiredItems(feedItemIDs);
this._set('_feedLastCheck', Zotero.Date.dateToSQL(new Date(), true));
yield this.saveTx();
yield this.updateUnreadCount();
await this.saveTx();
await this.updateUnreadCount();
deferred.resolve();
this._updating = false;
yield Zotero.Notifier.trigger('statusChanged', 'feed', this.id);
});
await Zotero.Notifier.trigger('statusChanged', 'feed', this.id);
};
Zotero.Feed.prototype.updateFeed = Zotero.Promise.coroutine(function* () {
Zotero.Feed.prototype.updateFeed = async function () {
try {
let result = yield this._updateFeed();
let result = await this._updateFeed();
return result;
} finally {
Zotero.Feeds.scheduleNextFeedCheck();
}
});
};
Zotero.Feed.prototype.updateUnreadCount = Zotero.Promise.coroutine(function* () {
Zotero.Feed.prototype.updateUnreadCount = async function () {
let sql = "SELECT " + Zotero.Feed._unreadCountSQL
+ " FROM feeds F JOIN libraries L USING (libraryID)"
+ " WHERE L.libraryID=?";
let newCount = yield Zotero.DB.valueQueryAsync(sql, [this.id]);
let newCount = await Zotero.DB.valueQueryAsync(sql, [this.id]);
if (newCount != this._feedUnreadCount) {
this._feedUnreadCount = newCount;
yield Zotero.Notifier.trigger('unreadCountUpdated', 'feed', this.id);
await Zotero.Notifier.trigger('unreadCountUpdated', 'feed', this.id);
}
});
};

View file

@ -27,7 +27,7 @@
/*
* Constructor for FeedItem object
*/
Zotero.FeedItem = function(itemTypeOrID, params = {}) {
Zotero.FeedItem = function (itemTypeOrID, params = {}) {
Zotero.FeedItem._super.call(this, itemTypeOrID);
this._feedItemReadTime = null;
@ -46,8 +46,8 @@ Zotero.defineProperty(Zotero.FeedItem.prototype, 'isFeedItem', {
});
Zotero.defineProperty(Zotero.FeedItem.prototype, 'guid', {
get: function() { return this._feedItemGUID; },
set: function(val) {
get: function () { return this._feedItemGUID; },
set: function (val) {
if (this.id) throw new Error('Cannot set GUID after item ID is already set');
if (typeof val != 'string') throw new Error('GUID must be a non-empty string');
this._feedItemGUID = val;
@ -55,10 +55,10 @@ Zotero.defineProperty(Zotero.FeedItem.prototype, 'guid', {
});
Zotero.defineProperty(Zotero.FeedItem.prototype, 'isRead', {
get: function() {
get: function () {
return !!this._feedItemReadTime;
},
set: function(read) {
set: function (read) {
if (!read != !this._feedItemReadTime) {
// changed
if (read) {
@ -72,10 +72,10 @@ Zotero.defineProperty(Zotero.FeedItem.prototype, 'isRead', {
});
//
Zotero.defineProperty(Zotero.FeedItem.prototype, 'isTranslated', {
get: function() {
get: function () {
return !!this._feedItemTranslatedTime;
},
set: function(state) {
set: function (state) {
if (state != !!this._feedItemTranslatedTime) {
if (state) {
this._feedItemTranslatedTime = Zotero.Date.dateToSQL(new Date(), true);
@ -87,15 +87,15 @@ Zotero.defineProperty(Zotero.FeedItem.prototype, 'isTranslated', {
}
});
Zotero.FeedItem.prototype.loadPrimaryData = Zotero.Promise.coroutine(function* (reload, failOnMissing) {
Zotero.FeedItem.prototype.loadPrimaryData = async function (reload, failOnMissing) {
if (this.guid && !this.id) {
// fill in item ID
this.id = yield this.ObjectsClass.getIDFromGUID(this.guid);
this.id = await this.ObjectsClass.getIDFromGUID(this.guid);
}
yield Zotero.FeedItem._super.prototype.loadPrimaryData.apply(this, arguments);
});
await Zotero.FeedItem._super.prototype.loadPrimaryData.apply(this, arguments);
};
Zotero.FeedItem.prototype.setField = function(field, value) {
Zotero.FeedItem.prototype.setField = function (field, value) {
if (field == 'libraryID') {
// Ensure that it references a feed
if (!Zotero.Libraries.get(value).isFeed) {
@ -106,7 +106,7 @@ Zotero.FeedItem.prototype.setField = function(field, value) {
return Zotero.FeedItem._super.prototype.setField.apply(this, arguments);
}
Zotero.FeedItem.prototype.fromJSON = function(json) {
Zotero.FeedItem.prototype.fromJSON = function (json) {
// Spaghetti to handle weird date formats in feedItems
let val = json.date;
if (val) {
@ -133,17 +133,17 @@ Zotero.FeedItem.prototype.fromJSON = function(json) {
Zotero.FeedItem._super.prototype.fromJSON.apply(this, arguments);
}
Zotero.FeedItem.prototype._initSave = Zotero.Promise.coroutine(function* (env) {
Zotero.FeedItem.prototype._initSave = async function (env) {
if (!this.guid) {
throw new Error('GUID must be set before saving ' + this._ObjectType);
}
let proceed = yield Zotero.FeedItem._super.prototype._initSave.apply(this, arguments);
let proceed = await Zotero.FeedItem._super.prototype._initSave.apply(this, arguments);
if (!proceed) return proceed;
if (env.isNew) {
// verify that GUID doesn't already exist for a new item
var item = yield this.ObjectsClass.getIDFromGUID(this.guid);
var item = await this.ObjectsClass.getIDFromGUID(this.guid);
if (item) {
throw new Error('Cannot create new item with GUID ' + this.guid + '. Item already exists.');
}
@ -158,14 +158,14 @@ Zotero.FeedItem.prototype._initSave = Zotero.Promise.coroutine(function* (env) {
}
return proceed;
});
};
Zotero.FeedItem.prototype._saveData = Zotero.Promise.coroutine(function* (env) {
yield Zotero.FeedItem._super.prototype._saveData.apply(this, arguments);
Zotero.FeedItem.prototype._saveData = async function (env) {
await Zotero.FeedItem._super.prototype._saveData.apply(this, arguments);
if (this._changed.feedItemData || env.isNew) {
var sql = "REPLACE INTO feedItems VALUES (?,?,?,?)";
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
sql,
[
this.id,
@ -177,27 +177,27 @@ Zotero.FeedItem.prototype._saveData = Zotero.Promise.coroutine(function* (env) {
this._clearChanged('feedItemData');
}
});
};
Zotero.FeedItem.prototype._finalizeErase = Zotero.Promise.coroutine(function* () {
Zotero.FeedItem.prototype._finalizeErase = async function () {
// Set for syncing
let feed = Zotero.Feeds.get(this.libraryID);
return Zotero.FeedItem._super.prototype._finalizeErase.apply(this, arguments);
});
};
Zotero.FeedItem.prototype.toggleRead = Zotero.Promise.coroutine(function* (state) {
Zotero.FeedItem.prototype.toggleRead = async function (state) {
state = state !== undefined ? !!state : !this.isRead;
let changed = this.isRead != state;
if (changed) {
this.isRead = state;
yield this.saveTx();
await this.saveTx();
let feed = Zotero.Feeds.get(this.libraryID);
yield feed.updateUnreadCount();
await feed.updateUnreadCount();
}
});
};
/**
* Uses the item url to translate an existing feed item.
@ -217,7 +217,7 @@ Zotero.FeedItem.prototype.translate = async function (libraryID, collectionID) {
return;
}
let error = function(e) { };
let error = function (e) { };
let translate = new RemoteTranslate();
var win = Services.wm.getMostRecentWindow("navigator:browser");
let progressWindow = win.ZoteroPane.progressWindow;
@ -300,23 +300,23 @@ Zotero.FeedItem.prototype.translate = async function (libraryID, collectionID) {
* @param {Browser} [browser]
* @return {Promise<FeedItem|Item>} translated feed item
*/
Zotero.FeedItem.prototype.clone = Zotero.Promise.coroutine(function* (libraryID, collectionID, browser) {
Zotero.FeedItem.prototype.clone = async function (libraryID, collectionID, browser) {
let dbItem = Zotero.Item.prototype.clone.call(this, libraryID);
if (collectionID) {
dbItem.addToCollection(collectionID);
}
yield dbItem.saveTx();
await dbItem.saveTx();
let item = {title: dbItem.getField('title'), itemType: dbItem.itemType, attachments: []};
// Add snapshot
if (Zotero.Libraries.get(libraryID).filesEditable && browser) {
item.attachments = [{title: "Snapshot"}];
yield Zotero.Attachments.importFromDocument({
await Zotero.Attachments.importFromDocument({
browser,
parentItemID: dbItem.id
});
}
return item;
});
};

View file

@ -27,7 +27,7 @@
/*
* Primary interface for accessing Zotero feed items
*/
Zotero.FeedItems = new Proxy(function() {
Zotero.FeedItems = new Proxy(function () {
let _idCache = {},
_guidCache = {};
@ -36,7 +36,7 @@ Zotero.FeedItems = new Proxy(function() {
// This one is a lazy getter, so we don't patch it up until first access
let zi_primaryDataSQLParts = Object.getOwnPropertyDescriptor(Zotero.Items, '_primaryDataSQLParts').get;
Zotero.defineProperty(Zotero.Items, '_primaryDataSQLParts', {
get: function() {
get: function () {
let obj = zi_primaryDataSQLParts.call(this);
obj.feedItemGUID = "FI.guid AS feedItemGUID";
obj.feedItemReadTime = "FI.readTime AS feedItemReadTime";
@ -47,7 +47,7 @@ Zotero.FeedItems = new Proxy(function() {
Zotero.Items._primaryDataSQLFrom += " LEFT JOIN feedItems FI ON (FI.itemID=O.itemID)";
let zi_getObjectForRow = Zotero.Items._getObjectForRow;
Zotero.Items._getObjectForRow = function(row) {
Zotero.Items._getObjectForRow = function (row) {
if (row.feedItemGUID) {
return new Zotero.FeedItem();
}
@ -55,22 +55,22 @@ Zotero.FeedItems = new Proxy(function() {
return zi_getObjectForRow.apply(Zotero.Items, arguments);
}
this.getIDFromGUID = Zotero.Promise.coroutine(function* (guid) {
this.getIDFromGUID = async function (guid) {
if (_idCache[guid] !== undefined) return _idCache[guid];
let id = yield Zotero.DB.valueQueryAsync('SELECT itemID FROM feedItems WHERE guid=?', [guid]);
let id = await Zotero.DB.valueQueryAsync('SELECT itemID FROM feedItems WHERE guid=?', [guid]);
if (!id) return false;
this._setGUIDMapping(guid, id);
return id;
});
};
this._setGUIDMapping = function(guid, id) {
this._setGUIDMapping = function (guid, id) {
_idCache[guid] = id;
_guidCache[id] = guid;
};
this._deleteGUIDMapping = function(guid, id) {
this._deleteGUIDMapping = function (guid, id) {
if (!id) id = _idCache[guid];
if (!guid) guid = _guidCache[id];
@ -80,7 +80,7 @@ Zotero.FeedItems = new Proxy(function() {
delete _guidCache[id];
};
this.unload = function() {
this.unload = function () {
Zotero.Items.unload.apply(Zotero.Items, arguments);
let ids = Zotero.flattenArguments(arguments);
for (let i=0; i<ids.length; i++) {
@ -88,30 +88,30 @@ Zotero.FeedItems = new Proxy(function() {
}
};
this.getAsyncByGUID = Zotero.Promise.coroutine(function* (guid) {
let id = yield this.getIDFromGUID(guid);
this.getAsyncByGUID = async function (guid) {
let id = await this.getIDFromGUID(guid);
if (id === false) return false;
return this.getAsync(id);
});
};
this.getMarkedAsRead = Zotero.Promise.coroutine(function* (libraryID, onlyGUIDs=false) {
this.getMarkedAsRead = async function (libraryID, onlyGUIDs=false) {
let sql = "SELECT " + (onlyGUIDs ? "guid " : "itemID ") +
"FROM feedItems FI " +
"JOIN items I USING (itemID) " +
"WHERE libraryID=? AND readTime IS NOT NULL";
let ids = yield Zotero.DB.columnQueryAsync(sql, [libraryID]);
let ids = await Zotero.DB.columnQueryAsync(sql, [libraryID]);
if (onlyGUIDs) {
return ids;
}
return Zotero.FeedItems.getAsync(ids);
});
};
/**
* Currently not used
*/
this.markAsReadByGUID = Zotero.Promise.coroutine(function* (guids) {
this.markAsReadByGUID = async function (guids) {
if (! Array.isArray(guids)) {
throw new Error('guids must be an array in Zotero.FeedItems.toggleReadByID');
}
@ -119,15 +119,15 @@ Zotero.FeedItems = new Proxy(function() {
Zotero.debug("Marking items as read");
Zotero.debug(guids);
for (let guid of guids) {
let id = yield this.getIDFromGUID(guid);
let id = await this.getIDFromGUID(guid);
if (id) {
ids.push(id);
}
}
return this.toggleReadByID(ids, true);
});
};
this.toggleReadByID = Zotero.Promise.coroutine(function* (ids, state) {
this.toggleReadByID = async function (ids, state) {
if (!Array.isArray(ids)) {
if (typeof ids != 'string') throw new Error('ids must be a string or array in Zotero.FeedItems.toggleReadByID');
@ -137,7 +137,7 @@ Zotero.FeedItems = new Proxy(function() {
throw new Error("No ids passed");
}
let items = yield this.getAsync(ids);
let items = await this.getAsync(ids);
if (state == undefined) {
// If state undefined, toggle read if at least one unread
@ -159,25 +159,25 @@ Zotero.FeedItems = new Proxy(function() {
feedsToUpdate.add(feed);
}
yield Zotero.DB.queryAsync(`UPDATE feedItems SET readTime=? WHERE itemID IN (${ids.join(', ')})`, readTime);
yield Zotero.Notifier.trigger('modify', 'item', ids, {});
await Zotero.DB.queryAsync(`UPDATE feedItems SET readTime=? WHERE itemID IN (${ids.join(', ')})`, readTime);
await Zotero.Notifier.trigger('modify', 'item', ids, {});
for (let feed of feedsToUpdate) {
yield feed.updateUnreadCount();
await feed.updateUnreadCount();
}
});
};
return this;
}.call({}),
// Proxy handler
{
get: function(target, name) {
get: function (target, name) {
return name in target
? target[name]
: Zotero.Items[name];
},
has: function(target, name) {
has: function (target, name) {
return name in target || name in Zotero.Items;
}
});

View file

@ -26,7 +26,7 @@
"use strict";
// Mimics Zotero.Libraries
Zotero.Feeds = new function() {
Zotero.Feeds = new function () {
var _initPromise;
var _updating;
@ -69,13 +69,14 @@ Zotero.Feeds = new function() {
this.uninit = function () {
// Cancel initialization if in progress
if (_initPromise) {
// FIXME: fx140: replace call to Zotero.Promise instance method 'cancel()'
_initPromise.cancel();
}
};
this._cache = null;
this._makeCache = function() {
this._makeCache = function () {
return {
libraryIDByURL: {},
urlByLibraryID: {}
@ -117,7 +118,7 @@ Zotero.Feeds = new function() {
delete this._cache.libraryIDByURL[url];
}
this.importFromOPML = Zotero.Promise.coroutine(function* (opmlString) {
this.importFromOPML = async function (opmlString) {
var parser = new DOMParser();
var doc = parser.parseFromString(opmlString, "application/xml");
// Per some random spec (https://developer.mozilla.org/en-US/docs/Web/API/DOMParser),
@ -145,7 +146,7 @@ Zotero.Feeds = new function() {
newFeeds.push(feed);
}
// This could potentially be a massive list, so we save in a transaction.
yield Zotero.DB.executeTransaction(async function () {
await Zotero.DB.executeTransaction(async function () {
for (let feed of newFeeds) {
await feed.save({
skipSelect: true
@ -153,11 +154,11 @@ Zotero.Feeds = new function() {
}
});
// Finally, update
yield Zotero.Feeds.updateFeeds();
await Zotero.Feeds.updateFeeds();
return true;
});
};
this.restoreFromJSON = Zotero.Promise.coroutine(function* (json, merge=false) {
this.restoreFromJSON = async function (json, merge=false) {
Zotero.debug("Restoring feeds from remote JSON");
Zotero.debug(json);
if (merge) {
@ -170,7 +171,7 @@ Zotero.Feeds = new function() {
json = syncedFeeds;
}
json = this._compactifyFeedJSON(json);
yield Zotero.SyncedSettings.set(Zotero.Libraries.userLibraryID, 'feeds', json);
await Zotero.SyncedSettings.set(Zotero.Libraries.userLibraryID, 'feeds', json);
let feeds = Zotero.Feeds.getAll();
for (let feed of feeds) {
if (json[feed.url]) {
@ -185,7 +186,7 @@ Zotero.Feeds = new function() {
delete json[feed.url];
} else {
Zotero.debug("Feed " + feed.url + " does not exist in remote JSON. Deleting");
yield feed.erase();
await feed.erase();
}
}
// Because existing json[feed.url] got deleted, `json` now only contains new feeds
@ -202,13 +203,13 @@ Zotero.Feeds = new function() {
obj.cleanupUnreadAfter = json[url][2];
}
let feed = new Zotero.Feed(obj);
yield feed.saveTx({
await feed.saveTx({
skipSelect: true
});
}
});
};
this.getByURL = function(urls) {
this.getByURL = function (urls) {
if (!this._cache) throw new Error("Zotero.Feeds cache is not initialized");
let asArray = true;
@ -230,25 +231,25 @@ Zotero.Feeds = new function() {
return asArray ? feeds : feeds[0];
}
this.existsByURL = function(url) {
this.existsByURL = function (url) {
if (!this._cache) throw new Error("Zotero.Feeds cache is not initialized");
return this._cache.libraryIDByURL[url] !== undefined;
}
this.getAll = function() {
this.getAll = function () {
if (!this._cache) throw new Error("Zotero.Feeds cache is not initialized");
return Object.keys(this._cache.urlByLibraryID)
.map(id => Zotero.Libraries.get(id));
}
this.get = function(libraryID) {
this.get = function (libraryID) {
let library = Zotero.Libraries.get(libraryID);
return library.isFeed ? library : undefined;
}
this.haveFeeds = function() {
this.haveFeeds = function () {
if (!this._cache) throw new Error("Zotero.Feeds cache is not initialized");
return !!Object.keys(this._cache.urlByLibraryID).length
@ -258,8 +259,8 @@ Zotero.Feeds = new function() {
return this.getAll().reduce((prev, feed) => prev + feed.unreadCount, 0);
};
let globalFeedCheckDelay = Zotero.Promise.resolve();
this.scheduleNextFeedCheck = Zotero.Promise.coroutine(function* () {
let globalFeedCheckDelay = Promise.resolve();
this.scheduleNextFeedCheck = async function () {
// Don't schedule if already updating, since another check is scheduled at the end
if (_updating) {
return;
@ -272,7 +273,7 @@ Zotero.Feeds = new function() {
+ "END ) AS nextCheck "
+ "FROM feeds WHERE refreshInterval IS NOT NULL "
+ "ORDER BY nextCheck ASC LIMIT 1";
var nextCheck = yield Zotero.DB.valueQueryAsync(sql);
var nextCheck = await Zotero.DB.valueQueryAsync(sql);
if (this._nextFeedCheck) {
this._nextFeedCheck.cancel();
@ -283,7 +284,7 @@ Zotero.Feeds = new function() {
nextCheck = nextCheck > 0 ? nextCheck * 1000 : 0;
Zotero.debug("Next feed check in " + (nextCheck / 1000) + " seconds");
this._nextFeedCheck = Zotero.Promise.delay(nextCheck);
Zotero.Promise.all([this._nextFeedCheck, globalFeedCheckDelay])
Promise.all([this._nextFeedCheck, globalFeedCheckDelay])
.then(() => {
this._nextFeedCheck = null;
globalFeedCheckDelay = Zotero.Promise.delay(60000); // Don't perform auto-updates more than once per minute
@ -299,9 +300,9 @@ Zotero.Feeds = new function() {
} else {
Zotero.debug("No feeds with auto-update");
}
});
};
this.updateFeeds = Zotero.Promise.coroutine(function* () {
this.updateFeeds = async function () {
if (_updating) {
Zotero.debug("Feed update already in progress");
return;
@ -316,12 +317,12 @@ Zotero.Feeds = new function() {
+ "WHERE refreshInterval IS NOT NULL "
+ "AND ( lastCheck IS NULL "
+ "OR (julianday(lastCheck, 'utc') + (refreshInterval/1440.0) - julianday('now', 'utc')) <= 0 )";
let needUpdate = (yield Zotero.DB.queryAsync(sql)).map(row => row.id);
let needUpdate = ((await Zotero.DB.queryAsync(sql))).map(row => row.id);
Zotero.debug("Running update for feeds: " + needUpdate.join(', '));
for (let i=0; i<needUpdate.length; i++) {
let feed = Zotero.Feeds.get(needUpdate[i]);
yield feed.waitForDataLoad('item');
yield feed._updateFeed();
await feed.waitForDataLoad('item');
await feed._updateFeed();
}
}
finally {
@ -329,11 +330,11 @@ Zotero.Feeds = new function() {
}
Zotero.debug("All feed updates done");
this.scheduleNextFeedCheck();
});
};
// Conversion from expansive to compact format sync json
// TODO: Remove after beta
this._compactifyFeedJSON = function(json) {
this._compactifyFeedJSON = function (json) {
for (let url in json) {
if(Array.isArray(json[url])) {
continue;

View file

@ -34,7 +34,7 @@ Zotero.Group = function (params = {}) {
// Return a proxy so that we can disable the object once it's deleted
return new Proxy(this, {
get: function(obj, prop) {
get: function (obj, prop) {
if (obj._disabled && !(prop == 'libraryID' || prop == 'id' || prop == 'name')) {
throw new Error("Group (" + obj.libraryID + ") has been disabled");
}
@ -52,7 +52,7 @@ Zotero.defineProperty(Zotero.Group, '_dbColumns', {
value: Object.freeze(['name', 'description', 'version'])
});
Zotero.Group._colToProp = function(c) {
Zotero.Group._colToProp = function (c) {
return "_group" + Zotero.Utilities.capitalize(c);
}
@ -77,13 +77,13 @@ Zotero.defineProperty(Zotero.Group.prototype, 'libraryTypes', {
});
Zotero.defineProperty(Zotero.Group.prototype, 'groupID', {
get: function() { return this._groupID; },
set: function(v) { return this._groupID = v; }
get: function () { return this._groupID; },
set: function (v) { return this._groupID = v; }
});
Zotero.defineProperty(Zotero.Group.prototype, 'id', {
get: function() { return this.groupID; },
set: function(v) { return this.groupID = v; }
get: function () { return this.groupID; },
set: function (v) { return this.groupID = v; }
});
Zotero.defineProperty(Zotero.Group.prototype, 'allowsLinkedFiles', {
@ -91,19 +91,19 @@ Zotero.defineProperty(Zotero.Group.prototype, 'allowsLinkedFiles', {
});
// Create accessors
(function() {
(function () {
let accessors = ['name', 'description', 'version'];
for (let i=0; i<accessors.length; i++) {
let name = accessors[i];
let prop = Zotero.Group._colToProp(name);
Zotero.defineProperty(Zotero.Group.prototype, name, {
get: function() { return this._get(prop); },
set: function(v) { return this._set(prop, v); }
get: function () { return this._get(prop); },
set: function (v) { return this._set(prop, v); }
})
}
})();
Zotero.Group.prototype._isValidGroupProp = function(prop) {
Zotero.Group.prototype._isValidGroupProp = function (prop) {
let preffix = '_group';
if (prop.indexOf(preffix) !== 0 || prop.length == preffix.length) {
return false;
@ -115,7 +115,7 @@ Zotero.Group.prototype._isValidGroupProp = function(prop) {
return Zotero.Group._dbColumns.indexOf(col) != -1;
}
Zotero.Group.prototype._isValidProp = function(prop) {
Zotero.Group.prototype._isValidProp = function (prop) {
return this._isValidGroupProp(prop)
|| Zotero.Group._super.prototype._isValidProp.call(this, prop);
}
@ -123,7 +123,7 @@ Zotero.Group.prototype._isValidProp = function(prop) {
/*
* Populate group data from a database row
*/
Zotero.Group.prototype._loadDataFromRow = function(row) {
Zotero.Group.prototype._loadDataFromRow = function (row) {
Zotero.Group._super.prototype._loadDataFromRow.call(this, row);
this._groupID = row.groupID;
@ -132,7 +132,7 @@ Zotero.Group.prototype._loadDataFromRow = function(row) {
this._groupVersion = row._groupVersion;
}
Zotero.Group.prototype._set = function(prop, val) {
Zotero.Group.prototype._set = function (prop, val) {
switch(prop) {
case '_groupVersion':
let newVal = Number.parseInt(val, 10);
@ -162,14 +162,14 @@ Zotero.Group.prototype._set = function(prop, val) {
return Zotero.Group._super.prototype._set.call(this, prop, val);
}
Zotero.Group.prototype._reloadFromDB = Zotero.Promise.coroutine(function* () {
Zotero.Group.prototype._reloadFromDB = async function () {
let sql = Zotero.Group._rowSQL + " WHERE G.groupID=?";
let row = yield Zotero.DB.rowQueryAsync(sql, [this.groupID]);
let row = await Zotero.DB.rowQueryAsync(sql, [this.groupID]);
this._loadDataFromRow(row);
});
};
Zotero.Group.prototype._initSave = Zotero.Promise.coroutine(function* (env) {
let proceed = yield Zotero.Group._super.prototype._initSave.call(this, env);
Zotero.Group.prototype._initSave = async function (env) {
let proceed = await Zotero.Group._super.prototype._initSave.call(this, env);
if (!proceed) return false;
if (!this._groupName) throw new Error("Group name not set");
@ -178,10 +178,10 @@ Zotero.Group.prototype._initSave = Zotero.Promise.coroutine(function* (env) {
if (!this._groupID) throw new Error("Group ID not set");
return true;
});
};
Zotero.Group.prototype._saveData = Zotero.Promise.coroutine(function* (env) {
yield Zotero.Group._super.prototype._saveData.call(this, env);
Zotero.Group.prototype._saveData = async function (env) {
await Zotero.Group._super.prototype._saveData.call(this, env);
let changedCols = [], params = [];
for (let i=0; i<Zotero.Group._dbColumns.length; i++) {
@ -200,7 +200,7 @@ Zotero.Group.prototype._saveData = Zotero.Promise.coroutine(function* (env) {
let sql = "INSERT INTO groups (" + changedCols.join(', ') + ") "
+ "VALUES (" + Array(params.length).fill('?').join(', ') + ")";
yield Zotero.DB.queryAsync(sql, params);
await Zotero.DB.queryAsync(sql, params);
Zotero.Notifier.queue('add', 'group', this.groupID, env.notifierData);
}
@ -208,7 +208,7 @@ Zotero.Group.prototype._saveData = Zotero.Promise.coroutine(function* (env) {
let sql = "UPDATE groups SET " + changedCols.map(v => v + '=?').join(', ')
+ " WHERE groupID=?";
params.push(this.groupID);
yield Zotero.DB.queryAsync(sql, params);
await Zotero.DB.queryAsync(sql, params);
if (!env.options.skipNotifier) {
Zotero.Notifier.queue('modify', 'group', this.groupID, env.notifierData);
@ -217,17 +217,17 @@ Zotero.Group.prototype._saveData = Zotero.Promise.coroutine(function* (env) {
else {
Zotero.debug("Group data did not change for group " + this.groupID, 5);
}
});
};
Zotero.Group.prototype._finalizeSave = Zotero.Promise.coroutine(function* (env) {
yield Zotero.Group._super.prototype._finalizeSave.call(this, env);
Zotero.Group.prototype._finalizeSave = async function (env) {
await Zotero.Group._super.prototype._finalizeSave.call(this, env);
if (env.isNew) {
Zotero.Groups.register(this);
}
});
};
Zotero.Group.prototype._finalizeErase = Zotero.Promise.coroutine(function* (env) {
Zotero.Group.prototype._finalizeErase = async function (env) {
let notifierData = {};
notifierData[this.groupID] = {
libraryID: this.libraryID
@ -236,8 +236,8 @@ Zotero.Group.prototype._finalizeErase = Zotero.Promise.coroutine(function* (env)
Zotero.Groups.unregister(this.groupID);
yield Zotero.Group._super.prototype._finalizeErase.call(this, env);
});
await Zotero.Group._super.prototype._finalizeErase.call(this, env);
};
Zotero.Group.prototype.toResponseJSON = function (options = {}) {
if (options.includeGroupDetails) {

View file

@ -31,7 +31,7 @@ Zotero.Groups = new function () {
this._cache = null;
this._makeCache = function() {
this._makeCache = function () {
return {
groupIDByLibraryID: {},
libraryIDByGroupID: {}
@ -57,9 +57,9 @@ Zotero.Groups = new function () {
delete this._cache.libraryIDByGroupID[groupID];
}
this.init = Zotero.Promise.method(function() {
this.init = function () {
// Cache initialized in Zotero.Libraries
})
}
/**
* @param {Integer} id - Group id
@ -81,7 +81,7 @@ Zotero.Groups = new function () {
var groups = Object.keys(this._cache.groupIDByLibraryID)
.map(id => Zotero.Libraries.get(id));
var collation = Zotero.getLocaleCollation();
groups.sort(function(a, b) {
groups.sort(function (a, b) {
return collation.compareString(1, a.name, b.name);
});
return groups;

File diff suppressed because it is too large Load diff

View file

@ -24,7 +24,7 @@
*/
Zotero.ItemFields = new function() {
Zotero.ItemFields = new function () {
// Private members
var _fields = {};
var _allFields = [];
@ -56,11 +56,11 @@ Zotero.ItemFields = new function() {
/*
* Load all fields into an internal hash array
*/
this.init = Zotero.Promise.coroutine(function* () {
this.init = async function () {
_fields = {};
_fieldsFormats = [];
var result = yield Zotero.DB.queryAsync('SELECT * FROM fieldFormats');
var result = await Zotero.DB.queryAsync('SELECT * FROM fieldFormats');
for (var i=0; i<result.length; i++) {
_fieldFormats[result[i]['fieldFormatID']] = {
@ -69,12 +69,12 @@ Zotero.ItemFields = new function() {
};
}
var fields = yield Zotero.DB.queryAsync('SELECT * FROM fieldsCombined');
var fields = await Zotero.DB.queryAsync('SELECT * FROM fieldsCombined');
var fieldItemTypes = yield _getFieldItemTypes();
var fieldItemTypes = await _getFieldItemTypes();
var sql = "SELECT DISTINCT baseFieldID FROM baseFieldMappingsCombined";
var baseFields = yield Zotero.DB.columnQueryAsync(sql);
var baseFields = await Zotero.DB.columnQueryAsync(sql);
for (let field of fields) {
let label = field.label || Zotero.Schema.globalSchemaLocale.fields[field.fieldName];
@ -102,9 +102,9 @@ Zotero.ItemFields = new function() {
}
_fieldsLoaded = true;
yield _loadBaseTypeFields();
yield _loadItemTypeFields();
});
await _loadBaseTypeFields();
await _loadItemTypeFields();
};
/*
@ -500,9 +500,9 @@ Zotero.ItemFields = new function() {
/*
* Returns hash array of itemTypeIDs for which a given field is valid
*/
var _getFieldItemTypes = Zotero.Promise.coroutine(function* () {
var _getFieldItemTypes = async function () {
var sql = 'SELECT fieldID, itemTypeID FROM itemTypeFieldsCombined';
var results = yield Zotero.DB.queryAsync(sql);
var results = await Zotero.DB.queryAsync(sql);
if (!results) {
throw ('No fields in itemTypeFields!');
@ -515,13 +515,13 @@ Zotero.ItemFields = new function() {
fields[results[i].fieldID][results[i].itemTypeID] = true;
}
return fields;
});
};
/*
* Build a lookup table for base field mappings
*/
var _loadBaseTypeFields = Zotero.Promise.coroutine(function* () {
var _loadBaseTypeFields = async function () {
_typeFieldIDsByBase = {};
_typeFieldNamesByBase = {};
@ -530,10 +530,10 @@ Zotero.ItemFields = new function() {
+ "FROM itemTypesCombined IT LEFT JOIN fieldsCombined F "
+ "LEFT JOIN baseFieldMappingsCombined BFM"
+ " ON (IT.itemTypeID=BFM.itemTypeID AND F.fieldID=BFM.baseFieldID)";
var rows = yield Zotero.DB.queryAsync(sql);
var rows = await Zotero.DB.queryAsync(sql);
var sql = "SELECT DISTINCT baseFieldID FROM baseFieldMappingsCombined";
var baseFields = yield Zotero.DB.columnQueryAsync(sql);
var baseFields = await Zotero.DB.columnQueryAsync(sql);
var fields = [];
for (let row of rows) {
@ -558,7 +558,7 @@ Zotero.ItemFields = new function() {
var sql = "SELECT itemTypeID, baseFieldID, fieldID, fieldName "
+ "FROM baseFieldMappingsCombined JOIN fieldsCombined USING (fieldID)";
var rows = yield Zotero.DB.queryAsync(sql);
var rows = await Zotero.DB.queryAsync(sql);
for (let i = 0; i < rows.length; i++) {
let row = rows[i];
// Type fields by base
@ -579,15 +579,15 @@ Zotero.ItemFields = new function() {
// Get all fields mapped to base types
sql = "SELECT DISTINCT fieldID FROM baseFieldMappingsCombined";
_baseMappedFields = yield Zotero.DB.columnQueryAsync(sql);
_baseMappedFields = await Zotero.DB.columnQueryAsync(sql);
_baseTypeFieldsLoaded = true;
});
};
var _loadItemTypeFields = Zotero.Promise.coroutine(function* () {
var _loadItemTypeFields = async function () {
var sql = 'SELECT itemTypeID, fieldID FROM itemTypeFieldsCombined ORDER BY orderIndex';
var rows = yield Zotero.DB.queryAsync(sql);
var rows = await Zotero.DB.queryAsync(sql);
_itemTypeFields = {
// Notes and annotations have no fields
@ -605,5 +605,5 @@ Zotero.ItemFields = new function() {
}
_itemTypeFieldsLoaded = true;
});
};
}

View file

@ -27,7 +27,7 @@
/*
* Primary interface for accessing Zotero items
*/
Zotero.Items = function() {
Zotero.Items = function () {
this.constructor = null;
this._ZDO_object = 'item';
@ -102,10 +102,10 @@ Zotero.Items = function() {
* @param {Integer} libraryID
* @return {Promise<Boolean>} - True if library has items in trash, false otherwise
*/
this.hasDeleted = Zotero.Promise.coroutine(function* (libraryID) {
this.hasDeleted = async function (libraryID) {
var sql = "SELECT COUNT(*) > 0 FROM items JOIN deletedItems USING (itemID) WHERE libraryID=?";
return !!(yield Zotero.DB.valueQueryAsync(sql, [libraryID]));
});
return !!((await Zotero.DB.valueQueryAsync(sql, [libraryID])));
};
/**
@ -117,7 +117,7 @@ Zotero.Items = function() {
* @param {Boolean} [asIDs=false] If true, resolves only with IDs
* @return {Promise<Array<Zotero.Item|Integer>>}
*/
this.getAll = Zotero.Promise.coroutine(function* (libraryID, onlyTopLevel, includeDeleted, asIDs=false) {
this.getAll = async function (libraryID, onlyTopLevel, includeDeleted, asIDs=false) {
var sql = 'SELECT A.itemID FROM items A';
if (onlyTopLevel) {
sql += ' LEFT JOIN itemNotes B USING (itemID) '
@ -131,12 +131,12 @@ Zotero.Items = function() {
sql += " AND A.itemID NOT IN (SELECT itemID FROM deletedItems)";
}
sql += " AND libraryID=?";
var ids = yield Zotero.DB.columnQueryAsync(sql, libraryID);
var ids = await Zotero.DB.columnQueryAsync(sql, libraryID);
if (asIDs) {
return ids;
}
return this.getAsync(ids);
});
};
//
@ -144,7 +144,7 @@ Zotero.Items = function() {
//
// These are called by Zotero.DataObjects.prototype._loadDataType().
//
this._loadItemData = Zotero.Promise.coroutine(function* (libraryID, ids, idSQL) {
this._loadItemData = async function (libraryID, ids, idSQL) {
var missingItems = {};
var itemFieldsCached = {};
@ -152,7 +152,7 @@ Zotero.Items = function() {
+ "JOIN itemData USING (itemID) "
+ "JOIN itemDataValues USING (valueID) WHERE libraryID=? AND itemTypeID!=?" + idSQL;
var params = [libraryID, Zotero.ItemTypes.getID('note')];
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
sql,
params,
{
@ -186,7 +186,7 @@ Zotero.Items = function() {
var sql = "SELECT itemID FROM items WHERE libraryID=?" + idSQL;
var params = [libraryID];
var allItemIDs = [];
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
sql,
params,
{
@ -218,7 +218,7 @@ Zotero.Items = function() {
+ "WHERE libraryID=? AND itemID NOT IN (SELECT itemID FROM itemAttachments)" + idSQL;
var params = [libraryID];
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
sql,
params,
{
@ -259,9 +259,9 @@ Zotero.Items = function() {
// Instead of making updateDisplayTitle() async and loading conditionally, just catch the error
// and load on demand
if (e instanceof Zotero.Exception.UnloadedDataException) {
yield item.loadDataType('creators');
yield item.loadDataType('annotation');
yield item.loadDataType('tags');
await item.loadDataType('creators');
await item.loadDataType('annotation');
await item.loadDataType('tags');
item.updateDisplayTitle()
}
else {
@ -269,15 +269,15 @@ Zotero.Items = function() {
}
}
}
});
};
this._loadCreators = Zotero.Promise.coroutine(function* (libraryID, ids, idSQL) {
this._loadCreators = async function (libraryID, ids, idSQL) {
var sql = 'SELECT itemID, creatorID, creatorTypeID, orderIndex '
+ 'FROM items LEFT JOIN itemCreators USING (itemID) '
+ 'WHERE libraryID=?' + idSQL + " ORDER BY itemID, orderIndex";
var params = [libraryID];
var rows = yield Zotero.DB.queryAsync(sql, params, { noCache: true });
var rows = await Zotero.DB.queryAsync(sql, params, { noCache: true });
// Mark creator indexes above the number of creators as changed,
// so that they're cleared if the item is saved
@ -342,17 +342,17 @@ Zotero.Items = function() {
if (index <= maxOrderIndex) {
fixIncorrectIndexes(item, index, maxOrderIndex);
}
});
};
this._loadNotes = Zotero.Promise.coroutine(function* (libraryID, ids, idSQL) {
this._loadNotes = async function (libraryID, ids, idSQL) {
var notesToUpdate = [];
var sql = "SELECT itemID, note FROM items "
+ "JOIN itemNotes USING (itemID) "
+ "WHERE libraryID=?" + idSQL;
var params = [libraryID];
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
sql,
params,
{
@ -402,7 +402,7 @@ Zotero.Items = function() {
);
if (notesToUpdate.length) {
yield Zotero.DB.executeTransaction(async function () {
await Zotero.DB.executeTransaction(async function () {
for (let i = 0; i < notesToUpdate.length; i++) {
let row = notesToUpdate[i];
let sql = "UPDATE itemNotes SET note=? WHERE itemID=?";
@ -415,7 +415,7 @@ Zotero.Items = function() {
sql = "SELECT itemID FROM items WHERE libraryID=?" + idSQL
+ " AND itemTypeID IN (?, ?) AND itemID NOT IN (SELECT itemID FROM itemNotes)";
params = [libraryID, Zotero.ItemTypes.getID('note'), Zotero.ItemTypes.getID('attachment')];
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
sql,
params,
{
@ -433,7 +433,7 @@ Zotero.Items = function() {
}.bind(this)
}
);
});
};
this._loadAnnotations = async function (libraryID, ids, idSQL) {
@ -506,7 +506,7 @@ Zotero.Items = function() {
}
catch (e) {
if (e.message.includes('no such column: IA.authorName')
&& await Zotero.DB.valueQueryAsync("SELECT COUNT(*) FROM version WHERE schema='userdata' AND version IN (120, 121, 122)")) {
&& (await Zotero.DB.valueQueryAsync("SELECT COUNT(*) FROM version WHERE schema='userdata' AND version IN (120, 121, 122)"))) {
await Zotero.DB.queryAsync("UPDATE version SET version=119 WHERE schema='userdata'");
Zotero.crash();
}
@ -544,7 +544,7 @@ Zotero.Items = function() {
};
this._loadChildItems = Zotero.Promise.coroutine(function* (libraryID, ids, idSQL) {
this._loadChildItems = async function (libraryID, ids, idSQL) {
var params = [libraryID];
var rows = [];
var onRow = function (row, setFunc) {
@ -598,7 +598,7 @@ Zotero.Items = function() {
};
}.bind(this);
var lastItemID = null;
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
sql,
params,
{
@ -652,7 +652,7 @@ Zotero.Items = function() {
}.bind(this);
lastItemID = null;
rows = [];
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
sql,
params,
{
@ -697,7 +697,7 @@ Zotero.Items = function() {
}.bind(this);
lastItemID = null;
rows = [];
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
sql,
params,
{
@ -721,7 +721,7 @@ Zotero.Items = function() {
if (idSQL) {
sql += idSQL;
}
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
sql,
params,
{
@ -737,10 +737,10 @@ Zotero.Items = function() {
}.bind(this)
}
);
});
};
this._loadTags = Zotero.Promise.coroutine(function* (libraryID, ids, idSQL) {
this._loadTags = async function (libraryID, ids, idSQL) {
var sql = "SELECT itemID, name, type FROM items "
+ "LEFT JOIN itemTags USING (itemID) "
+ "LEFT JOIN tags USING (tagID) WHERE libraryID=?" + idSQL;
@ -763,7 +763,7 @@ Zotero.Items = function() {
item._loaded.tags = true;
}.bind(this);
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
sql,
params,
{
@ -794,10 +794,10 @@ Zotero.Items = function() {
if (lastItemID) {
setRows(lastItemID, rows);
}
});
};
this._loadCollections = Zotero.Promise.coroutine(function* (libraryID, ids, idSQL) {
this._loadCollections = async function (libraryID, ids, idSQL) {
var sql = "SELECT itemID, collectionID FROM items "
+ "LEFT JOIN collectionItems USING (itemID) "
+ "WHERE libraryID=?" + idSQL;
@ -816,7 +816,7 @@ Zotero.Items = function() {
item._clearChanged('collections');
}.bind(this);
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
sql,
params,
{
@ -842,7 +842,7 @@ Zotero.Items = function() {
if (lastItemID) {
setRows(lastItemID, rows);
}
});
};
/**
@ -1047,7 +1047,7 @@ Zotero.Items = function() {
if (!hashesIncludeText) {
masterAttachmentHashes = new Map([
...masterAttachmentHashes,
...await this._hashItem(item, 'text')
...(await this._hashItem(item, 'text'))
]);
hashesIncludeText = true;
}
@ -1369,7 +1369,7 @@ Zotero.Items = function() {
};
this.trash = Zotero.Promise.coroutine(function* (ids) {
this.trash = async function (ids) {
Zotero.DB.requireTransaction();
var libraryIDs = new Set();
@ -1403,28 +1403,28 @@ Zotero.Items = function() {
parentItemIDs.add(item.parentItemID);
}
});
yield Zotero.Utilities.Internal.forEachChunkAsync(ids, 250, Zotero.Promise.coroutine(function* (chunk) {
yield Zotero.DB.queryAsync(
await Zotero.Utilities.Internal.forEachChunkAsync(ids, 250, async function (chunk) {
await Zotero.DB.queryAsync(
"UPDATE items SET synced=0, clientDateModified=CURRENT_TIMESTAMP "
+ `WHERE itemID IN (${chunk.map(id => parseInt(id)).join(", ")})`
);
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
"INSERT OR IGNORE INTO deletedItems (itemID) VALUES "
+ chunk.map(id => "(" + id + ")").join(", ")
);
}.bind(this)));
}.bind(this));
// Keep in sync with Zotero.Item::saveData()
for (let parentItemID of parentItemIDs) {
let parentItem = yield Zotero.Items.getAsync(parentItemID);
yield parentItem.reload(['primaryData', 'childItems'], true);
let parentItem = await Zotero.Items.getAsync(parentItemID);
await parentItem.reload(['primaryData', 'childItems'], true);
}
Zotero.Notifier.queue('modify', 'item', ids);
Zotero.Notifier.queue('trash', 'item', ids);
Array.from(libraryIDs).forEach(libraryID => {
Zotero.Notifier.queue('refresh', 'trash', libraryID);
});
});
};
this.trashTx = function (ids) {
@ -1599,20 +1599,20 @@ Zotero.Items = function() {
}
}
await Zotero.Utilities.Internal.forEachChunkAsync(allItems, 250, Zotero.Promise.coroutine(function* (chunk) {
await Zotero.Utilities.Internal.forEachChunkAsync(allItems, 250, async function (chunk) {
for (let item of chunk) {
item.setPublications(true);
item.synced = false;
}
let ids = chunk.map(item => item.id);
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
`UPDATE items SET synced=0, clientDateModified=? WHERE itemID IN (${ids.join(", ")})`,
timestamp
);
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
`INSERT OR IGNORE INTO publicationsItems VALUES (${ids.join("), (")})`
);
}.bind(this)));
}.bind(this));
Zotero.Notifier.queue('modify', 'item', allItems.map(item => item.id));
}.bind(this));
};
@ -1640,14 +1640,14 @@ Zotero.Items = function() {
});
var timestamp = Zotero.DB.transactionTimestamp;
await Zotero.Utilities.Internal.forEachChunkAsync(allItems, 250, Zotero.Promise.coroutine(function* (chunk) {
await Zotero.Utilities.Internal.forEachChunkAsync(allItems, 250, async function (chunk) {
let idStr = chunk.map(item => item.id).join(", ");
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
`UPDATE items SET synced=0, clientDateModified=? WHERE itemID IN (${idStr})`,
timestamp
);
yield Zotero.DB.queryAsync(`DELETE FROM publicationsItems WHERE itemID IN (${idStr})`);
}.bind(this)));
await Zotero.DB.queryAsync(`DELETE FROM publicationsItems WHERE itemID IN (${idStr})`);
}.bind(this));
Zotero.Notifier.queue('modify', 'item', items.map(item => item.id));
}.bind(this));
};
@ -2142,7 +2142,7 @@ Zotero.Items = function() {
let ids = await Zotero.DB.columnQueryAsync(sql, [Zotero.DB.escapeSQLExpression(pathPrefix) + '%', libraryID]);
let items = await this.getAsync(ids);
let missingItems = await Promise.all(
items.map(async item => (await item.fileExists() ? false : item))
items.map(async item => ((await item.fileExists()) ? false : item))
);
return missingItems.filter(Boolean);
};

View file

@ -26,7 +26,7 @@
Zotero.Libraries = new function () {
let _userLibraryID;
Zotero.defineProperty(this, 'userLibraryID', {
get: function() {
get: function () {
if (_userLibraryID === undefined) {
throw new Error("Library data not yet loaded");
}
@ -45,22 +45,22 @@ Zotero.Libraries = new function () {
*/
this._cache = null;
this._makeCache = function() {
this._makeCache = function () {
return {};
}
this.register = function(library) {
this.register = function (library) {
if (!this._cache) throw new Error("Zotero.Libraries cache is not initialized");
Zotero.debug("Zotero.Libraries: Registering library " + library.libraryID, 5);
this._addToCache(this._cache, library);
};
this._addToCache = function(cache, library) {
this._addToCache = function (cache, library) {
if (!library.libraryID) throw new Error("Cannot register an unsaved library");
cache[library.libraryID] = library;
}
this.unregister = function(libraryID) {
this.unregister = function (libraryID) {
if (!this._cache) throw new Error("Zotero.Libraries cache is not initialized");
Zotero.debug("Zotero.Libraries: Unregistering library " + libraryID, 5);
delete this._cache[libraryID];
@ -70,7 +70,7 @@ Zotero.Libraries = new function () {
* Loads all libraries from DB. Groups, Feeds, etc. should not maintain an
* independent cache.
*/
this.init = Zotero.Promise.coroutine(function* () {
this.init = async function () {
let specialLoading = ['feed', 'group'];
// Invalidate caches until we're done loading everything
@ -87,7 +87,7 @@ Zotero.Libraries = new function () {
// Exclude libraries that require special loading
+ " WHERE type NOT IN "
+ "(" + Array(specialLoading.length).fill('?').join(',') + ")";
let rows = yield Zotero.DB.queryAsync(sql, specialLoading);
let rows = await Zotero.DB.queryAsync(sql, specialLoading);
for (let i=0; i<rows.length; i++) {
let row = rows[i];
@ -114,7 +114,7 @@ Zotero.Libraries = new function () {
let libType = specialLoading[i];
let LibType = Zotero.Utilities.capitalize(libType);
let libs = yield Zotero.DB.queryAsync(Zotero[LibType]._rowSQL);
let libs = await Zotero.DB.queryAsync(Zotero[LibType]._rowSQL);
for (let j=0; j<libs.length; j++) {
let lib = new Zotero[LibType]();
lib._loadDataFromRow(libs[j]);
@ -129,19 +129,19 @@ Zotero.Libraries = new function () {
Zotero.DataObjectUtilities.getObjectsClassForObjectType(libType)
._cache = newCaches[libType];
}
});
};
/**
* @param {Integer} libraryID
* @return {Boolean}
*/
this.exists = function(libraryID) {
this.exists = function (libraryID) {
if (!this._cache) throw new Error("Zotero.Libraries cache is not initialized");
return this._cache[libraryID] !== undefined;
}
this._ensureExists = function(libraryID) {
this._ensureExists = function (libraryID) {
if (!this.exists(libraryID)) {
throw new Error("Invalid library ID " + libraryID);
}
@ -171,7 +171,7 @@ Zotero.Libraries = new function () {
* @param {Integer} libraryID
* @return {Zotero.Library[] | Zotero.Library}
*/
this.get = function(libraryID) {
this.get = function (libraryID) {
return this._cache[libraryID] || false;
}
@ -216,14 +216,14 @@ Zotero.Libraries = new function () {
* @param {Integer} version
* @return {Promise}
*/
this.setVersion = Zotero.Promise.method(function(libraryID, version) {
this.setVersion = function (libraryID, version) {
Zotero.debug("Zotero.Libraries.setVersion() is deprecated. Use Zotero.Library.prototype.libraryVersion instead");
this._ensureExists(libraryID);
let library = Zotero.Libraries.get(libraryID);
library.libraryVersion = version;
return library.saveTx();
});
};
/**
* @deprecated
@ -242,14 +242,14 @@ Zotero.Libraries = new function () {
* @param {Date} lastSyncTime
* @return {Promise}
*/
this.setLastSyncTime = Zotero.Promise.method(function (libraryID, lastSyncTime) {
this.setLastSyncTime = function (libraryID, lastSyncTime) {
Zotero.debug("Zotero.Libraries.setLastSyncTime() is deprecated. Use Zotero.Library.prototype.lastSync instead");
this._ensureExists(libraryID);
let library = Zotero.Libraries.get(libraryID);
library.lastSync = lastSyncTime;
return library.saveTx();
});
};
/**
* @deprecated
@ -265,14 +265,14 @@ Zotero.Libraries = new function () {
*
* @return {Promise}
*/
this.setEditable = Zotero.Promise.method(function(libraryID, editable) {
this.setEditable = function (libraryID, editable) {
Zotero.debug("Zotero.Libraries.setEditable() is deprecated. Use Zotero.Library.prototype.editable instead");
this._ensureExists(libraryID);
let library = Zotero.Libraries.get(libraryID);
library.editable = editable;
return library.saveTx();
});
};
/**
* @deprecated
@ -288,14 +288,14 @@ Zotero.Libraries = new function () {
*
* @return {Promise}
*/
this.setFilesEditable = Zotero.Promise.coroutine(function* (libraryID, filesEditable) {
this.setFilesEditable = async function (libraryID, filesEditable) {
Zotero.debug("Zotero.Libraries.setFilesEditable() is deprecated. Use Zotero.Library.prototype.filesEditable instead");
this._ensureExists(libraryID);
let library = Zotero.Libraries.get(libraryID);
library.filesEditable = filesEditable;
return library.saveTx();
});
};
/**
* @deprecated
@ -318,7 +318,7 @@ Zotero.Libraries = new function () {
/**
* @deprecated
*/
this.updateLastSyncTime = Zotero.Promise.method(function(libraryID) {
this.updateLastSyncTime = function (libraryID) {
Zotero.debug("Zotero.Libraries.updateLastSyncTime() is deprecated. Use Zotero.Library.prototype.updateLastSyncTime instead");
this._ensureExists(libraryID);
@ -326,5 +326,5 @@ Zotero.Libraries = new function () {
library.updateLastSyncTime();
return library.saveTx()
.return();
})
}
}

View file

@ -23,7 +23,7 @@
***** END LICENSE BLOCK *****
*/
Zotero.Library = function(params = {}) {
Zotero.Library = function (params = {}) {
let objectType = this._objectType;
this._ObjectType = Zotero.Utilities.capitalize(objectType);
this._objectTypePlural = Zotero.DataObjectUtilities.getObjectTypePlural(objectType);
@ -54,7 +54,7 @@ Zotero.Library = function(params = {}) {
// Return a proxy so that we can disable the object once it's deleted
return new Proxy(this, {
get: function(obj, prop) {
get: function (obj, prop) {
if (obj._disabled && !(prop == 'libraryID' || prop == 'id' || prop == 'name')) {
throw new Error("Library (" + obj.libraryID + ") has been disabled");
}
@ -74,7 +74,7 @@ Zotero.defineProperty(Zotero.Library, '_dbColumns', {
});
// Converts DB column name to (internal) object property
Zotero.Library._colToProp = function(c) {
Zotero.Library._colToProp = function (c) {
return "_library" + Zotero.Utilities.capitalize(c);
}
@ -112,18 +112,18 @@ Zotero.defineProperty(Zotero.Library.prototype, 'fixedLibraries', {
});
Zotero.defineProperty(Zotero.Library.prototype, 'libraryID', {
get: function() { return this._libraryID; },
set: function(id) { throw new Error("Cannot change library ID"); }
get: function () { return this._libraryID; },
set: function (id) { throw new Error("Cannot change library ID"); }
});
Zotero.defineProperty(Zotero.Library.prototype, 'id', {
get: function() { return this.libraryID; },
set: function(val) { return this.libraryID = val; }
get: function () { return this.libraryID; },
set: function (val) { return this.libraryID = val; }
});
Zotero.defineProperty(Zotero.Library.prototype, 'libraryType', {
get: function() { return this._get('_libraryType'); },
set: function(v) { return this._set('_libraryType', v); }
get: function () { return this._get('_libraryType'); },
set: function (v) { return this._set('_libraryType', v); }
});
/**
@ -154,8 +154,8 @@ Zotero.defineProperty(Zotero.Library.prototype, 'isGroup', {
});
Zotero.defineProperty(Zotero.Library.prototype, 'libraryVersion', {
get: function() { return this._get('_libraryVersion'); },
set: function(v) { return this._set('_libraryVersion', v); }
get: function () { return this._get('_libraryVersion'); },
set: function (v) { return this._set('_libraryVersion', v); }
});
@ -165,12 +165,12 @@ Zotero.defineProperty(Zotero.Library.prototype, 'syncable', {
Zotero.defineProperty(Zotero.Library.prototype, 'lastSync', {
get: function() { return this._get('_libraryLastSync'); }
get: function () { return this._get('_libraryLastSync'); }
});
Zotero.defineProperty(Zotero.Library.prototype, 'name', {
get: function() {
get: function () {
if (this._libraryType == 'user') {
return Zotero.getString('pane.collections.library');
}
@ -201,13 +201,13 @@ Zotero.defineProperty(Zotero.Library.prototype, 'allowsLinkedFiles', {
});
// Create other accessors
(function() {
(function () {
let accessors = ['editable', 'filesEditable', 'storageVersion', 'archived'];
for (let i=0; i<accessors.length; i++) {
let prop = Zotero.Library._colToProp(accessors[i]);
Zotero.defineProperty(Zotero.Library.prototype, accessors[i], {
get: function() { return this._get(prop); },
set: function(v) { return this._set(prop, v); }
get: function () { return this._get(prop); },
set: function (v) { return this._set(prop, v); }
})
}
})()
@ -217,7 +217,7 @@ Zotero.defineProperty(Zotero.Library.prototype, 'storageDownloadNeeded', {
set: function (val) { this._storageDownloadNeeded = !!val; },
})
Zotero.Library.prototype._isValidProp = function(prop) {
Zotero.Library.prototype._isValidProp = function (prop) {
let prefix = '_library';
if (prop.indexOf(prefix) !== 0 || prop.length == prefix.length) {
return false;
@ -229,7 +229,7 @@ Zotero.Library.prototype._isValidProp = function(prop) {
return Zotero.Library._dbColumns.indexOf(col) != -1;
}
Zotero.Library.prototype._get = function(prop) {
Zotero.Library.prototype._get = function (prop) {
if (!this._isValidProp(prop)) {
throw new Error('Unknown property "' + prop + '"');
}
@ -237,7 +237,7 @@ Zotero.Library.prototype._get = function(prop) {
return this[prop];
}
Zotero.Library.prototype._set = function(prop, val) {
Zotero.Library.prototype._set = function (prop, val) {
if (!this._isValidProp(prop)) {
throw new Error('Unknown property "' + prop + '"');
}
@ -332,7 +332,7 @@ Zotero.Library.prototype._set = function(prop, val) {
this[prop] = val;
}
Zotero.Library.prototype._loadDataFromRow = function(row) {
Zotero.Library.prototype._loadDataFromRow = function (row) {
if (this._libraryID !== undefined && this._libraryID !== row.libraryID) {
Zotero.debug("Warning: library ID changed in Zotero.Library._loadDataFromRow", 2, true);
}
@ -353,21 +353,21 @@ Zotero.Library.prototype._loadDataFromRow = function(row) {
this._changed = {};
}
Zotero.Library.prototype._reloadFromDB = Zotero.Promise.coroutine(function* () {
Zotero.Library.prototype._reloadFromDB = async function () {
let sql = Zotero.Library._rowSQL + ' WHERE libraryID=?';
let row = yield Zotero.DB.rowQueryAsync(sql, [this.libraryID]);
let row = await Zotero.DB.rowQueryAsync(sql, [this.libraryID]);
this._loadDataFromRow(row);
});
};
/**
* Load object data in this library
*/
Zotero.Library.prototype.loadAllDataTypes = Zotero.Promise.coroutine(function* () {
yield Zotero.SyncedSettings.loadAll(this.libraryID);
yield Zotero.Collections.loadAll(this.libraryID);
yield Zotero.Searches.loadAll(this.libraryID);
yield Zotero.Items.loadAll(this.libraryID);
});
Zotero.Library.prototype.loadAllDataTypes = async function () {
await Zotero.SyncedSettings.loadAll(this.libraryID);
await Zotero.Collections.loadAll(this.libraryID);
await Zotero.Searches.loadAll(this.libraryID);
await Zotero.Items.loadAll(this.libraryID);
};
//
// Methods to handle promises that are resolved when object data is loaded for the library
@ -396,36 +396,36 @@ Zotero.Library.prototype.setDataLoaded = function (objectType) {
/**
* Wait for a given data type to load, loading it now if necessary
*/
Zotero.Library.prototype.waitForDataLoad = Zotero.Promise.coroutine(function* (objectType) {
Zotero.Library.prototype.waitForDataLoad = async function (objectType) {
if (this.getDataLoaded(objectType)) return;
let promise = this.getDataLoadedPromise(objectType);
// If items are already being loaded, wait for them
if (promise) {
yield promise;
await promise;
}
// Otherwise load them now
else {
let objectsClass = Zotero.DataObjectUtilities.getObjectsClassForObjectType(objectType);
yield objectsClass.loadAll(this.libraryID);
await objectsClass.loadAll(this.libraryID);
}
});
};
Zotero.Library.prototype.isChildObjectAllowed = function(type) {
Zotero.Library.prototype.isChildObjectAllowed = function (type) {
return this._childObjectTypes.indexOf(type) != -1;
};
Zotero.Library.prototype.updateLastSyncTime = function() {
Zotero.Library.prototype.updateLastSyncTime = function () {
this._set('_libraryLastSync', new Date());
};
Zotero.Library.prototype.saveTx = function(options) {
Zotero.Library.prototype.saveTx = function (options) {
options = options || {};
options.tx = true;
return this.save(options);
}
Zotero.Library.prototype.save = Zotero.Promise.coroutine(function* (options) {
Zotero.Library.prototype.save = async function (options) {
options = options || {};
var env = {
options: options,
@ -438,14 +438,14 @@ Zotero.Library.prototype.save = Zotero.Promise.coroutine(function* (options) {
env.options.tx = true;
}
var proceed = yield this._initSave(env)
.catch(Zotero.Promise.coroutine(function* (e) {
var proceed = await this._initSave(env)
.catch(async function (e) {
if (!env.isNew && Zotero.Libraries.exists(this.libraryID)) {
// Reload from DB and reset this._changed, so this is not a permanent failure
yield this._reloadFromDB();
await this._reloadFromDB();
}
throw e;
}).bind(this));
}.bind(this));
if (!proceed) return false;
@ -472,16 +472,16 @@ Zotero.Library.prototype.save = Zotero.Promise.coroutine(function* (options) {
// Use existing transaction
else {
Zotero.DB.requireTransaction();
yield this._saveData(env);
yield this._finalizeSave(env);
await this._saveData(env);
await this._finalizeSave(env);
}
} catch(e) {
Zotero.debug(e, 1);
throw e;
}
});
};
Zotero.Library.prototype._initSave = Zotero.Promise.method(function(env) {
Zotero.Library.prototype._initSave = function (env) {
if (this._libraryID === undefined) {
env.isNew = true;
@ -506,9 +506,9 @@ Zotero.Library.prototype._initSave = Zotero.Promise.method(function(env) {
}
return true;
});
};
Zotero.Library.prototype._saveData = Zotero.Promise.coroutine(function* (env) {
Zotero.Library.prototype._saveData = async function (env) {
// Collect changed columns
let changedCols = [],
params = [];
@ -539,14 +539,14 @@ Zotero.Library.prototype._saveData = Zotero.Promise.coroutine(function* (env) {
let sql = "INSERT INTO libraries (" + changedCols.join(", ") + ") "
+ "VALUES (" + Array(params.length).fill("?").join(", ") + ")";
yield Zotero.DB.queryAsync(sql, params);
await Zotero.DB.queryAsync(sql, params);
this._libraryID = id;
} else if (changedCols.length) {
params.push(this.libraryID);
let sql = "UPDATE libraries SET " + changedCols.map(v => v + "=?").join(", ")
+ " WHERE libraryID=?";
yield Zotero.DB.queryAsync(sql, params);
await Zotero.DB.queryAsync(sql, params);
// Since these are Zotero.Library properties, the 'modify' for the inheriting object may not
// get triggered, so call it here too
@ -556,28 +556,28 @@ Zotero.Library.prototype._saveData = Zotero.Promise.coroutine(function* (env) {
} else {
Zotero.debug("Library data did not change for " + this._objectType + " " + this.id, 5);
}
});
};
Zotero.Library.prototype._finalizeSave = Zotero.Promise.coroutine(function* (env) {
Zotero.Library.prototype._finalizeSave = async function (env) {
this._changed = {};
if (env.isNew) {
// Re-fetch from DB to get auto-filled defaults
yield this._reloadFromDB();
await this._reloadFromDB();
Zotero.Libraries.register(this);
yield this.loadAllDataTypes();
await this.loadAllDataTypes();
}
});
};
Zotero.Library.prototype.eraseTx = function(options) {
Zotero.Library.prototype.eraseTx = function (options) {
options = options || {};
options.tx = true;
return this.erase(options);
};
Zotero.Library.prototype.erase = Zotero.Promise.coroutine(function* (options) {
Zotero.Library.prototype.erase = async function (options) {
options = options || {};
var env = {
options: options,
@ -591,7 +591,7 @@ Zotero.Library.prototype.erase = Zotero.Promise.coroutine(function* (options) {
env.options.tx = true;
}
var proceed = yield this._initErase(env);
var proceed = await this._initErase(env);
if (!proceed) return false;
Zotero.debug('Deleting ' + this._objectType + ' ' + this.id);
@ -600,22 +600,22 @@ Zotero.Library.prototype.erase = Zotero.Promise.coroutine(function* (options) {
env.notifierData = {};
if (env.options.tx) {
yield Zotero.DB.executeTransaction(async function () {
await Zotero.DB.executeTransaction(async function () {
await this._eraseData(env);
await this._finalizeErase(env);
}.bind(this), env.transactionOptions);
} else {
Zotero.DB.requireTransaction();
yield this._eraseData(env);
yield this._finalizeErase(env);
await this._eraseData(env);
await this._finalizeErase(env);
}
} catch(e) {
Zotero.debug(e, 1);
throw e;
}
});
};
Zotero.Library.prototype._initErase = Zotero.Promise.method(function(env) {
Zotero.Library.prototype._initErase = function (env) {
if (this.libraryID === undefined) {
throw new Error("Attempting to erase an unsaved library");
}
@ -627,7 +627,7 @@ Zotero.Library.prototype._initErase = Zotero.Promise.method(function(env) {
}
return true;
});
};
Zotero.Library.prototype._eraseData = async function (env) {
// Delete attachment files
@ -667,7 +667,7 @@ Zotero.Library.prototype._eraseData = async function (env) {
await Zotero.Fulltext.clearLibraryVersion(this.libraryID);
};
Zotero.Library.prototype._finalizeErase = Zotero.Promise.coroutine(function* (env) {
Zotero.Library.prototype._finalizeErase = async function (env) {
Zotero.Libraries.unregister(this.libraryID);
// Clear cached child objects
@ -678,7 +678,7 @@ Zotero.Library.prototype._finalizeErase = Zotero.Promise.coroutine(function* (en
}
this._disabled = true;
});
};
Zotero.Library.prototype.toResponseJSON = function (options = {}) {
let uri = Zotero.URI.getLibraryURI(this.libraryID);
@ -707,10 +707,10 @@ Zotero.Library.prototype.hasCollections = function () {
return this._hasCollections;
}
Zotero.Library.prototype.updateCollections = Zotero.Promise.coroutine(function* () {
Zotero.Library.prototype.updateCollections = async function () {
let sql = 'SELECT COUNT(*)>0 FROM collections WHERE libraryID=?';
this._hasCollections = !!(yield Zotero.DB.valueQueryAsync(sql, this.libraryID));
});
this._hasCollections = !!((await Zotero.DB.valueQueryAsync(sql, this.libraryID)));
};
Zotero.Library.prototype.hasSearches = function () {
if (this._hasSearches === null) {
@ -720,12 +720,12 @@ Zotero.Library.prototype.hasSearches = function () {
return this._hasSearches;
}
Zotero.Library.prototype.updateSearches = Zotero.Promise.coroutine(function* () {
Zotero.Library.prototype.updateSearches = async function () {
let sql = 'SELECT COUNT(*)>0 FROM savedSearches WHERE libraryID=?';
this._hasSearches = !!(yield Zotero.DB.valueQueryAsync(sql, this.libraryID));
});
this._hasSearches = !!((await Zotero.DB.valueQueryAsync(sql, this.libraryID)));
};
Zotero.Library.prototype.hasItems = Zotero.Promise.coroutine(function* () {
Zotero.Library.prototype.hasItems = async function () {
if (!this.id) {
throw new Error("Library is not saved yet");
}
@ -734,8 +734,8 @@ Zotero.Library.prototype.hasItems = Zotero.Promise.coroutine(function* () {
if (this.libraryID == Zotero.Libraries.userLibraryID) {
sql += "AND key NOT IN ('ABCD2345', 'ABCD3456')";
}
return !!(yield Zotero.DB.valueQueryAsync(sql, this.libraryID));
});
return !!((await Zotero.DB.valueQueryAsync(sql, this.libraryID)));
};
Zotero.Library.prototype.hasItem = function (item) {
if (!(item instanceof Zotero.Item)) {

View file

@ -24,10 +24,10 @@
*/
Zotero.Notes = new function() {
Zotero.Notes = new function () {
this.AUTO_SYNC_DELAY = 15;
// Keep in sync with utilities_item.js::noteToTitle() in zotero/utilities
this.__defineGetter__("MAX_TITLE_LENGTH", function() { return 120; });
this.__defineGetter__("MAX_TITLE_LENGTH", function () { return 120; });
this.__defineGetter__("defaultNote", function () { return '<div class="zotero-note znv1"></div>'; });
this.__defineGetter__("notePrefix", function () { return '<div class="zotero-note znv1">'; });
this.__defineGetter__("noteSuffix", function () { return '</div>'; });
@ -35,16 +35,16 @@ Zotero.Notes = new function() {
this._editorInstances = [];
this._downloadInProgressPromise = null;
this.noteToTitle = function(text) {
this.noteToTitle = function (text) {
Zotero.debug(`Zotero.Note.noteToTitle() is deprecated -- use Zotero.Utilities.Item.noteToTitle() instead`);
return Zotero.Utilities.Item.noteToTitle(text);
};
this.registerEditorInstance = function(instance) {
this.registerEditorInstance = function (instance) {
this._editorInstances.push(instance);
};
this.unregisterEditorInstance = async function(instance) {
this.unregisterEditorInstance = async function (instance) {
// Make sure the editor instance is not unregistered while
// Zotero.Notes.updateUser is in progress, otherwise the
// instance might not get the`disableSaving` flag set
@ -126,7 +126,7 @@ Zotero.Notes = new function() {
this.replaceAllItemKeys(item, new Map([[fromItemKey, toItemKey]]));
};
this.getExportableNote = async function(item) {
this.getExportableNote = async function (item) {
if (!item.isNote()) {
throw new Error('Item is not a note');
}

View file

@ -42,7 +42,7 @@ Zotero.Relations = new function () {
var _subjectPredicatesByObject = {};
this.init = Zotero.Promise.coroutine(function* () {
this.init = async function () {
// Load relations for different types
for (let type of _types) {
let t = new Date();
@ -50,7 +50,7 @@ Zotero.Relations = new function () {
let sql = "SELECT * FROM " + type + "Relations "
+ "JOIN relationPredicates USING (predicateID)";
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
sql,
false,
{
@ -67,7 +67,7 @@ Zotero.Relations = new function () {
Zotero.debug(`Loaded ${type} relations in ${new Date() - t} ms`);
}
});
};
this.register = function (objectType, subjectID, predicate, object) {
@ -148,7 +148,7 @@ Zotero.Relations = new function () {
* @return {Object[]} - An array of objects with a Zotero.DataObject as 'subject'
* and a predicate string as 'predicate'
*/
this.getByObject = Zotero.Promise.coroutine(function* (objectType, object) {
this.getByObject = async function (objectType, object) {
var objectsClass = Zotero.DataObjectUtilities.getObjectsClassForObjectType(objectType);
var predicateIDs = [];
var o = _subjectPredicatesByObject[objectType]
@ -159,7 +159,7 @@ Zotero.Relations = new function () {
var toReturn = [];
for (let predicateID in o) {
for (let subjectID of o[predicateID]) {
var subject = yield objectsClass.getAsync(subjectID);
var subject = await objectsClass.getAsync(subjectID);
toReturn.push({
subject: subject,
predicate: Zotero.RelationPredicates.getName(predicateID)
@ -167,7 +167,7 @@ Zotero.Relations = new function () {
};
}
return toReturn;
});
};
/**
@ -199,7 +199,7 @@ Zotero.Relations = new function () {
};
this.updateUser = Zotero.Promise.coroutine(function* (fromUserID, toUserID) {
this.updateUser = async function (fromUserID, toUserID) {
if (!fromUserID) {
fromUserID = "local/" + Zotero.Users.getLocalUserKey();
}
@ -210,7 +210,7 @@ Zotero.Relations = new function () {
Zotero.DB.requireTransaction();
for (let type of _types) {
let sql = `SELECT DISTINCT object FROM ${type}Relations WHERE object LIKE ?`;
let objects = yield Zotero.DB.columnQueryAsync(
let objects = await Zotero.DB.columnQueryAsync(
sql, 'http://zotero.org/users/' + fromUserID + '/%'
);
Zotero.DB.addCurrentCallback("commit", function* () {
@ -230,18 +230,18 @@ Zotero.Relations = new function () {
sql = "UPDATE " + type + "Relations SET "
+ "object=REPLACE(object, 'zotero.org/users/" + fromUserID + "/', "
+ "'zotero.org/users/" + toUserID + "/')";
yield Zotero.DB.queryAsync(sql);
await Zotero.DB.queryAsync(sql);
var objectsClass = Zotero.DataObjectUtilities.getObjectsClassForObjectType(type);
let loadedObjects = objectsClass.getLoaded();
for (let object of loadedObjects) {
yield object.reload(['relations'], true);
await object.reload(['relations'], true);
}
}
});
};
this.purge = Zotero.Promise.coroutine(function* () {
this.purge = async function () {
Zotero.debug("Purging relations");
Zotero.DB.requireTransaction();
@ -256,7 +256,7 @@ Zotero.Relations = new function () {
let sql = "SELECT " + objectsClass.idColumn + " AS id, predicate, object "
+ "FROM " + objectsClass.relationsTable
+ " JOIN relationPredicates USING (predicateID) WHERE predicate != ?";
let rows = yield Zotero.DB.queryAsync(sql, [this.replacedItemPredicate]);
let rows = await Zotero.DB.queryAsync(sql, [this.replacedItemPredicate]);
for (let i = 0; i < rows.length; i++) {
let row = rows[i];
let uri = row.object;
@ -266,23 +266,23 @@ Zotero.Relations = new function () {
// removing
if (uri.indexOf(prefix) != -1
&& uri.indexOf("/" + type + "s/") != -1
&& !(yield Zotero.URI[getFunc](uri))) {
&& !((await Zotero.URI[getFunc](uri)))) {
if (!objects[row.id]) {
objects[row.id] = yield objectsClass.getAsync(row.id, { noCache: true });
objects[row.id] = await objectsClass.getAsync(row.id, { noCache: true });
}
objects[row.id].removeRelation(row.predicate, uri);
}
for (let i in objects) {
yield objects[i].save();
await objects[i].save();
}
}
Zotero.debug("Purged relations in " + ((new Date) - t) + "ms");
}
});
};
this._getPrefixAndValue = function(uri) {
this._getPrefixAndValue = function (uri) {
var [prefix, value] = uri.split(':');
if (prefix && value) {
if (!this._namespaces[prefix]) {

View file

@ -23,7 +23,7 @@
***** END LICENSE BLOCK *****
*/
Zotero.Search = function(params = {}) {
Zotero.Search = function (params = {}) {
Zotero.Search._super.apply(this);
this._name = null;
@ -46,35 +46,35 @@ Zotero.Search.prototype._dataTypes = Zotero.Search._super.prototype._dataTypes.c
'conditions'
]);
Zotero.Search.prototype.getID = function(){
Zotero.Search.prototype.getID = function (){
Zotero.debug('Zotero.Search.getName() is deprecated -- use Search.id');
return this._id;
}
Zotero.Search.prototype.getName = function() {
Zotero.Search.prototype.getName = function () {
Zotero.debug('Zotero.Search.getName() is deprecated -- use Search.name');
return this.name;
}
Zotero.Search.prototype.setName = function(val) {
Zotero.Search.prototype.setName = function (val) {
Zotero.debug('Zotero.Search.setName() is deprecated -- use Search.name');
this.name = val;
}
Zotero.defineProperty(Zotero.Search.prototype, 'id', {
get: function() { return this._get('id'); },
set: function(val) { return this._set('id', val); }
get: function () { return this._get('id'); },
set: function (val) { return this._set('id', val); }
});
Zotero.defineProperty(Zotero.Search.prototype, 'libraryID', {
get: function() { return this._get('libraryID'); },
set: function(val) { return this._set('libraryID', val); }
get: function () { return this._get('libraryID'); },
set: function (val) { return this._set('libraryID', val); }
});
Zotero.defineProperty(Zotero.Search.prototype, 'key', {
get: function() { return this._get('key'); },
set: function(val) { return this._set('key', val); }
get: function () { return this._get('key'); },
set: function (val) { return this._set('key', val); }
});
Zotero.defineProperty(Zotero.Search.prototype, 'name', {
get: function() { return this._get('name'); },
get: function () { return this._get('name'); },
set: function (val) {
if (!val) {
throw new Error("Saved search name cannot be empty");
@ -83,15 +83,15 @@ Zotero.defineProperty(Zotero.Search.prototype, 'name', {
}
});
Zotero.defineProperty(Zotero.Search.prototype, 'version', {
get: function() { return this._get('version'); },
set: function(val) { return this._set('version', val); }
get: function () { return this._get('version'); },
set: function (val) { return this._set('version', val); }
});
Zotero.defineProperty(Zotero.Search.prototype, 'synced', {
get: function() { return this._get('synced'); },
set: function(val) { return this._set('synced', val); }
get: function () { return this._get('synced'); },
set: function (val) { return this._set('synced', val); }
});
Zotero.defineProperty(Zotero.Search.prototype, 'conditions', {
get: function() { return this.getConditions(); }
get: function () { return this.getConditions(); }
});
Zotero.defineProperty(Zotero.Search.prototype, '_canHaveParent', {
value: false
@ -157,14 +157,14 @@ Zotero.Search.prototype.loadFromRow = function (row) {
this._identified = true;
}
Zotero.Search.prototype._initSave = Zotero.Promise.coroutine(function* (env) {
Zotero.Search.prototype._initSave = async function (env) {
if (!this.name) {
throw new Error('Name not provided for saved search');
}
return Zotero.Search._super.prototype._initSave.apply(this, arguments);
});
};
Zotero.Search.prototype._saveData = Zotero.Promise.coroutine(function* (env) {
Zotero.Search.prototype._saveData = async function (env) {
var isNew = env.isNew;
var options = env.options;
@ -185,20 +185,20 @@ Zotero.Search.prototype._saveData = Zotero.Promise.coroutine(function* (env) {
let placeholders = env.sqlColumns.map(() => '?').join();
let sql = "INSERT INTO savedSearches (" + env.sqlColumns.join(', ') + ") "
+ "VALUES (" + placeholders + ")";
yield Zotero.DB.queryAsync(sql, env.sqlValues);
await Zotero.DB.queryAsync(sql, env.sqlValues);
}
else {
let sql = 'UPDATE savedSearches SET '
+ env.sqlColumns.map(x => x + '=?').join(', ') + ' WHERE savedSearchID=?';
env.sqlValues.push(searchID ? { int: searchID } : null);
yield Zotero.DB.queryAsync(sql, env.sqlValues);
await Zotero.DB.queryAsync(sql, env.sqlValues);
}
}
if (this._changed.conditions) {
if (!isNew) {
var sql = "DELETE FROM savedSearchConditions WHERE savedSearchID=?";
yield Zotero.DB.queryAsync(sql, this.id);
await Zotero.DB.queryAsync(sql, this.id);
}
var i = 0;
@ -221,7 +221,7 @@ Zotero.Search.prototype._saveData = Zotero.Promise.coroutine(function* (env) {
condition.value ? condition.value : null,
condition.required ? 1 : null
];
yield Zotero.DB.queryAsync(sql, sqlParams);
await Zotero.DB.queryAsync(sql, sqlParams);
i++;
}
}
@ -234,17 +234,17 @@ Zotero.Search.prototype._saveData = Zotero.Promise.coroutine(function* (env) {
else {
sql = "DELETE FROM deletedSearches WHERE savedSearchID=?";
}
yield Zotero.DB.queryAsync(sql, searchID);
await Zotero.DB.queryAsync(sql, searchID);
this._clearChanged('deleted');
this._markForReload('primaryData');
}
});
};
Zotero.Search.prototype._finalizeSave = Zotero.Promise.coroutine(function* (env) {
Zotero.Search.prototype._finalizeSave = async function (env) {
if (env.isNew) {
// Update library searches status
yield Zotero.Libraries.get(this.libraryID).updateSearches();
await Zotero.Libraries.get(this.libraryID).updateSearches();
Zotero.Notifier.queue('add', 'search', this.id, env.notifierData, env.options.notifierQueue);
}
@ -253,7 +253,7 @@ Zotero.Search.prototype._finalizeSave = Zotero.Promise.coroutine(function* (env)
}
if (!env.skipCache) {
yield this.reload();
await this.reload();
// If new, there's no other data we don't have, so we can mark everything as loaded
if (env.isNew) {
this._markAllDataTypeLoadStates(true);
@ -262,7 +262,7 @@ Zotero.Search.prototype._finalizeSave = Zotero.Promise.coroutine(function* (env)
}
return env.isNew ? this.id : true;
});
};
Zotero.Search.prototype.clone = function (libraryID) {
@ -273,22 +273,22 @@ Zotero.Search.prototype.clone = function (libraryID) {
};
Zotero.Search.prototype._eraseData = Zotero.Promise.coroutine(function* (env) {
Zotero.Search.prototype._eraseData = async function (env) {
Zotero.DB.requireTransaction();
var sql = "DELETE FROM savedSearchConditions WHERE savedSearchID=?";
yield Zotero.DB.queryAsync(sql, this.id);
await Zotero.DB.queryAsync(sql, this.id);
var sql = "DELETE FROM savedSearches WHERE savedSearchID=?";
yield Zotero.DB.queryAsync(sql, this.id);
});
await Zotero.DB.queryAsync(sql, this.id);
};
Zotero.Search.prototype._finalizeErase = Zotero.Promise.coroutine(function* (env) {
yield Zotero.Search._super.prototype._finalizeErase.call(this, env);
Zotero.Search.prototype._finalizeErase = async function (env) {
await Zotero.Search._super.prototype._finalizeErase.call(this, env);
// Update library searches status
yield Zotero.Libraries.get(this.libraryID).updateSearches();
});
await Zotero.Libraries.get(this.libraryID).updateSearches();
};
Zotero.Search.prototype.addCondition = function (condition, operator, value, required) {
@ -489,7 +489,7 @@ Zotero.Search.prototype.removeCondition = function (searchConditionID) {
* Returns an array with 'condition', 'operator', 'value', 'required'
* for the given searchConditionID
*/
Zotero.Search.prototype.getCondition = function(searchConditionID){
Zotero.Search.prototype.getCondition = function (searchConditionID){
this._requireData('conditions');
return this._conditions[searchConditionID];
}
@ -499,7 +499,7 @@ Zotero.Search.prototype.getCondition = function(searchConditionID){
* Returns an object of conditions/operator/value sets used in the search,
* indexed by searchConditionID
*/
Zotero.Search.prototype.getConditions = function(){
Zotero.Search.prototype.getConditions = function (){
this._requireData('conditions');
var conditions = {};
for (let id in this._conditions) {
@ -517,7 +517,7 @@ Zotero.Search.prototype.getConditions = function(){
}
Zotero.Search.prototype.hasPostSearchFilter = function() {
Zotero.Search.prototype.hasPostSearchFilter = function () {
this._requireData('conditions');
for (let i of Object.values(this._conditions)) {
if (i.condition == 'fulltextContent'){
@ -534,7 +534,7 @@ Zotero.Search.prototype.hasPostSearchFilter = function() {
* @param {Boolean} [asTempTable=false]
* @return {Promise}
*/
Zotero.Search.prototype.search = Zotero.Promise.coroutine(function* (asTempTable) {
Zotero.Search.prototype.search = async function (asTempTable) {
var tmpTable;
// Mark conditions as loaded
@ -544,7 +544,7 @@ Zotero.Search.prototype.search = Zotero.Promise.coroutine(function* (asTempTable
}
try {
if (!this._sql){
yield this._buildQuery();
await this._buildQuery();
}
// Set some variables for conditions to avoid further lookups
@ -582,20 +582,20 @@ Zotero.Search.prototype.search = Zotero.Promise.coroutine(function* (asTempTable
if (this._scope) {
// If subsearch has post-search filter, run and insert ids into temp table
if (this._scope.hasPostSearchFilter()) {
var ids = yield this._scope.search();
var ids = await this._scope.search();
if (!ids) {
return [];
}
tmpTable = yield Zotero.Search.idsToTempTable(ids);
tmpTable = await Zotero.Search.idsToTempTable(ids);
}
// Otherwise, just copy to temp table directly
else {
tmpTable = "tmpSearchResults_" + Zotero.randomString(8);
var sql = "CREATE TEMPORARY TABLE " + tmpTable + " AS "
+ (yield this._scope.getSQL());
yield Zotero.DB.queryAsync(sql, yield this._scope.getSQLParams(), { noCache: true });
+ ((await this._scope.getSQL()));
await Zotero.DB.queryAsync(sql, await this._scope.getSQLParams(), { noCache: true });
var sql = "CREATE INDEX " + tmpTable + "_itemID ON " + tmpTable + "(itemID)";
yield Zotero.DB.queryAsync(sql, false, { noCache: true });
await Zotero.DB.queryAsync(sql, false, { noCache: true });
}
// Search ids in temp table
@ -614,7 +614,7 @@ Zotero.Search.prototype.search = Zotero.Promise.coroutine(function* (asTempTable
}
sql += ")";
var res = yield Zotero.DB.valueQueryAsync(sql, this._sqlParams, { noCache: true });
var res = await Zotero.DB.valueQueryAsync(sql, this._sqlParams, { noCache: true });
var ids = res ? res.split(",").map(id => parseInt(id)) : [];
/*
// DEBUG: Should this be here?
@ -628,7 +628,7 @@ Zotero.Search.prototype.search = Zotero.Promise.coroutine(function* (asTempTable
}
// Or just run main search
else {
var ids = yield Zotero.DB.columnQueryAsync(this._sql, this._sqlParams, { noCache: true });
var ids = await Zotero.DB.columnQueryAsync(this._sql, this._sqlParams, { noCache: true });
}
//Zotero.debug('IDs from main search or subsearch: ');
@ -666,15 +666,15 @@ Zotero.Search.prototype.search = Zotero.Promise.coroutine(function* (asTempTable
// In ANY mode, include items that haven't already been found, as long as they're in
// the right library
if (joinModeAny) {
let tmpTable = yield Zotero.Search.idsToTempTable(fullTextResults);
let tmpTable = await Zotero.Search.idsToTempTable(fullTextResults);
let sql = "SELECT GROUP_CONCAT(itemID) FROM items WHERE "
+ "itemID NOT IN (SELECT itemID FROM " + tmpTable + ")";
if (this.libraryID) {
sql += " AND libraryID=?";
}
let res = yield Zotero.DB.valueQueryAsync(sql, this.libraryID, { noCache: true });
let res = await Zotero.DB.valueQueryAsync(sql, this.libraryID, { noCache: true });
scopeIDs = res ? res.split(",").map(id => parseInt(id)) : [];
yield Zotero.DB.queryAsync("DROP TABLE " + tmpTable, false, { noCache: true });
await Zotero.DB.queryAsync("DROP TABLE " + tmpTable, false, { noCache: true });
}
// In ALL mode, include remaining items from the main search
else {
@ -698,7 +698,7 @@ Zotero.Search.prototype.search = Zotero.Promise.coroutine(function* (asTempTable
s.setScope(this._scope, true);
}
numSplits = splits.length;
let wordMatches = yield s.search();
let wordMatches = await s.search();
//Zotero.debug("Word index matches");
//Zotero.debug(wordMatches);
@ -724,7 +724,7 @@ Zotero.Search.prototype.search = Zotero.Promise.coroutine(function* (asTempTable
// Search the full-text content
else if (scopeIDs.length) {
let found = new Set(
yield Zotero.Fulltext.findTextInItems(
await Zotero.Fulltext.findTextInItems(
scopeIDs,
condition.value,
condition.mode
@ -765,7 +765,7 @@ Zotero.Search.prototype.search = Zotero.Promise.coroutine(function* (asTempTable
if (this.hasPostSearchFilter() &&
(includeParentsAndChildren || includeParents || includeChildren)) {
var tmpTable = yield Zotero.Search.idsToTempTable(ids);
var tmpTable = await Zotero.Search.idsToTempTable(ids);
if (includeParentsAndChildren || includeParents) {
//Zotero.debug("Adding parent items to result set");
@ -793,7 +793,7 @@ Zotero.Search.prototype.search = Zotero.Promise.coroutine(function* (asTempTable
}
sql = "SELECT GROUP_CONCAT(itemID) FROM items WHERE itemID IN (" + sql + ")";
var res = yield Zotero.DB.valueQueryAsync(sql, false, { noCache: true });
var res = await Zotero.DB.valueQueryAsync(sql, false, { noCache: true });
var parentChildIDs = res ? res.split(",").map(id => parseInt(id)) : [];
// Add parents and children to main ids
@ -806,7 +806,7 @@ Zotero.Search.prototype.search = Zotero.Promise.coroutine(function* (asTempTable
}
finally {
if (tmpTable && !asTempTable) {
yield Zotero.DB.queryAsync("DROP TABLE IF EXISTS " + tmpTable, false, { noCache: true });
await Zotero.DB.queryAsync("DROP TABLE IF EXISTS " + tmpTable, false, { noCache: true });
}
}
@ -821,7 +821,7 @@ Zotero.Search.prototype.search = Zotero.Promise.coroutine(function* (asTempTable
return Zotero.Search.idsToTempTable(ids);
}
return ids;
});
};
/**
@ -896,26 +896,26 @@ Zotero.Search.prototype.toJSON = function (options = {}) {
/*
* Get the SQL string for the search
*/
Zotero.Search.prototype.getSQL = Zotero.Promise.coroutine(function* () {
Zotero.Search.prototype.getSQL = async function () {
if (!this._sql) {
yield this._buildQuery();
await this._buildQuery();
}
return this._sql;
});
};
Zotero.Search.prototype.getSQLParams = Zotero.Promise.coroutine(function* () {
Zotero.Search.prototype.getSQLParams = async function () {
if (!this._sql) {
yield this._buildQuery();
await this._buildQuery();
}
return this._sqlParams;
});
};
/*
* Batch insert
*/
Zotero.Search.idsToTempTable = Zotero.Promise.coroutine(function* (ids) {
Zotero.Search.idsToTempTable = async function (ids) {
var tmpTable = "tmpSearchResults_" + Zotero.randomString(8);
Zotero.debug(`Creating ${tmpTable} with ${ids.length} item${ids.length != 1 ? 's' : ''}`);
@ -930,9 +930,9 @@ Zotero.Search.idsToTempTable = Zotero.Promise.coroutine(function* (ids) {
else {
sql += " (itemID INTEGER PRIMARY KEY)";
}
yield Zotero.DB.queryAsync(sql, false, { debug: false, noCache: true });
await Zotero.DB.queryAsync(sql, false, { debug: false, noCache: true });
if (ids.length) {
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
`CREATE UNIQUE INDEX ${tmpTable}_itemID ON ${tmpTable}(itemID)`,
false,
{
@ -942,13 +942,13 @@ Zotero.Search.idsToTempTable = Zotero.Promise.coroutine(function* (ids) {
}
return tmpTable;
});
};
/*
* Build the SQL query for the search
*/
Zotero.Search.prototype._buildQuery = Zotero.Promise.coroutine(function* () {
Zotero.Search.prototype._buildQuery = async function () {
this._requireData('conditions');
var sql = 'SELECT itemID FROM items';
@ -1308,7 +1308,7 @@ Zotero.Search.prototype._buildQuery = Zotero.Promise.coroutine(function* () {
for (let c of Object.values(this._conditions)) {
if (c.condition == 'libraryID' && c.operator == 'is') {
foundLibraryID = true;
obj = yield objectTypeClass.getByLibraryAndKeyAsync(
obj = await objectTypeClass.getByLibraryAndKeyAsync(
c.value, objKey
);
if (obj) {
@ -1322,7 +1322,7 @@ Zotero.Search.prototype._buildQuery = Zotero.Promise.coroutine(function* () {
}
}
else {
obj = yield objectTypeClass.getByLibraryAndKeyAsync(
obj = await objectTypeClass.getByLibraryAndKeyAsync(
objLibraryID, objKey
);
}
@ -1367,7 +1367,7 @@ Zotero.Search.prototype._buildQuery = Zotero.Promise.coroutine(function* () {
// or that this slows things down with large libraries
// -- should probably use a temporary table instead
if (hasFilter){
let subids = yield obj.search();
let subids = await obj.search();
condSQL += "itemID ";
if (condition.operator == 'isNot') {
condSQL += "NOT ";
@ -1381,8 +1381,8 @@ Zotero.Search.prototype._buildQuery = Zotero.Promise.coroutine(function* () {
condSQL += "NOT ";
}
condSQL += "IN (";
condSQL += yield obj.getSQL();
let subpar = yield obj.getSQLParams();
condSQL += await obj.getSQL();
let subpar = await obj.getSQLParams();
for (let k in subpar){
condSQLParams.push(subpar[k]);
}
@ -1403,7 +1403,7 @@ Zotero.Search.prototype._buildQuery = Zotero.Promise.coroutine(function* () {
+ 'WHERE fileTypeID IN ('
+ 'SELECT fileTypeID FROM fileTypes WHERE '
+ 'fileTypeID=?)';
var patterns = yield Zotero.DB.columnQueryAsync(ftSQL, { int: condition.value });
var patterns = await Zotero.DB.columnQueryAsync(ftSQL, { int: condition.value });
if (patterns) {
for (let str of patterns) {
condSQL += 'contentType LIKE ? OR ';
@ -1816,4 +1816,4 @@ Zotero.Search.prototype._buildQuery = Zotero.Promise.coroutine(function* () {
this._sql = sql;
this._sqlParams = sqlParams.length ? sqlParams : false;
});
};

View file

@ -23,7 +23,7 @@
***** END LICENSE BLOCK *****
*/
Zotero.SearchConditions = new function(){
Zotero.SearchConditions = new function () {
this.get = get;
this.getStandardConditions = getStandardConditions;
this.hasOperator = hasOperator;
@ -69,7 +69,7 @@ Zotero.SearchConditions = new function(){
* - template (special handling)
* - noLoad (can't load from saved search)
*/
this.init = Zotero.Promise.coroutine(function* () {
this.init = async function () {
var conditions = [
//
// Special conditions
@ -462,7 +462,7 @@ Zotero.SearchConditions = new function(){
},
table: 'itemData',
field: 'value',
aliases: yield Zotero.DB.columnQueryAsync("SELECT fieldName FROM fieldsCombined "
aliases: await Zotero.DB.columnQueryAsync("SELECT fieldName FROM fieldsCombined "
+ "WHERE fieldName NOT IN ('accessDate', 'date', 'pages', "
+ "'section','seriesNumber','issue')"),
template: true // mark for special handling
@ -671,14 +671,14 @@ Zotero.SearchConditions = new function(){
}
var collation = Zotero.getLocaleCollation();
_standardConditions.sort(function(a, b) {
_standardConditions.sort(function (a, b) {
// Sort Any Field to the top
if (a.name == 'anyField') {
return -1;
}
return collation.compareString(1, a.localized, b.localized);
});
});
};
/*

View file

@ -23,7 +23,7 @@
***** END LICENSE BLOCK *****
*/
Zotero.Searches = function() {
Zotero.Searches = function () {
this.constructor = null;
this._ZDO_object = 'search';
@ -43,10 +43,10 @@ Zotero.Searches = function() {
this._primaryDataSQLFrom = "FROM savedSearches O "
+ "LEFT JOIN deletedSearches DS ON (O.savedSearchID=DS.savedSearchID)";
this.init = Zotero.Promise.coroutine(function* () {
yield Zotero.DataObjects.prototype.init.apply(this);
yield Zotero.SearchConditions.init();
});
this.init = async function () {
await Zotero.DataObjects.prototype.init.apply(this);
await Zotero.SearchConditions.init();
};
this.getByLibrary = function (libraryID) {
@ -72,9 +72,9 @@ Zotero.Searches = function() {
*
* @param {Integer} [libraryID]
*/
this.getAll = Zotero.Promise.coroutine(function* (libraryID) {
this.getAll = async function (libraryID) {
var sql = "SELECT savedSearchID FROM savedSearches WHERE libraryID=?";
var ids = yield Zotero.DB.columnQueryAsync(sql, libraryID);
var ids = await Zotero.DB.columnQueryAsync(sql, libraryID);
if (!ids.length) {
return []
}
@ -86,7 +86,7 @@ Zotero.Searches = function() {
return collation.compareString(1, a.name, b.name);
});
return searches;
});
};
this.getPrimaryDataSQL = function () {
@ -121,7 +121,7 @@ Zotero.Searches = function() {
};
this._loadConditions = Zotero.Promise.coroutine(function* (libraryID, ids, idSQL) {
this._loadConditions = async function (libraryID, ids, idSQL) {
var sql = "SELECT savedSearchID, searchConditionID, condition, operator, value, required "
+ "FROM savedSearches LEFT JOIN savedSearchConditions USING (savedSearchID) "
+ "WHERE libraryID=?" + idSQL
@ -187,7 +187,7 @@ Zotero.Searches = function() {
search._clearChanged('conditions');
}.bind(this);
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
sql,
params,
{
@ -219,7 +219,7 @@ Zotero.Searches = function() {
if (lastID) {
setRows(lastID, rows);
}
});
};
Zotero.DataObjects.call(this);

View file

@ -27,7 +27,7 @@
/*
* Same structure as Zotero.Creators -- make changes in both places if possible
*/
Zotero.Tags = new function() {
Zotero.Tags = new function () {
this.MAX_COLORED_TAGS = 9;
this.MAX_SYNC_LENGTH = 255;
@ -39,8 +39,8 @@ Zotero.Tags = new function() {
var _itemsListImagePromises = {};
this.init = Zotero.Promise.coroutine(function* () {
yield Zotero.DB.queryAsync(
this.init = async function () {
await Zotero.DB.queryAsync(
"SELECT tagID, name FROM tags",
false,
{
@ -53,7 +53,7 @@ Zotero.Tags = new function() {
}
);
_initialized = true;
});
};
/**
@ -102,7 +102,7 @@ Zotero.Tags = new function() {
* @param {String} name - Tag name
* @return {Promise<Integer>} tagID
*/
this.create = Zotero.Promise.coroutine(function* (name) {
this.create = async function (name) {
if (!_initialized) {
throw new Zotero.Exception.UnloadedDataException("Tags not yet loaded");
}
@ -115,21 +115,21 @@ Zotero.Tags = new function() {
if (!id) {
id = Zotero.ID.get('tags');
let sql = "INSERT INTO tags (tagID, name) VALUES (?, ?)";
yield Zotero.DB.queryAsync(sql, [id, data.tag]);
await Zotero.DB.queryAsync(sql, [id, data.tag]);
_tagsByID.set(id, data.tag);
_idsByTag.set(data.tag, id);
}
return id;
});
};
this.getLongTagsInLibrary = Zotero.Promise.coroutine(function* (libraryID) {
this.getLongTagsInLibrary = async function (libraryID) {
var sql = "SELECT DISTINCT tagID FROM tags "
+ "JOIN itemTags USING (tagID) "
+ "JOIN items USING (itemID) "
+ "WHERE libraryID=? AND LENGTH(name)>?"
return yield Zotero.DB.columnQueryAsync(sql, [libraryID, this.MAX_SYNC_LENGTH]);
});
return await Zotero.DB.columnQueryAsync(sql, [libraryID, this.MAX_SYNC_LENGTH]);
};
/**
@ -211,14 +211,14 @@ Zotero.Tags = new function() {
}
this.search = Zotero.Promise.coroutine(function* (str) {
this.search = async function (str) {
var sql = 'SELECT name AS tag, type FROM tags';
if (str) {
sql += ' WHERE name LIKE ?';
}
var rows = yield Zotero.DB.queryAsync(sql, str ? '%' + str + '%' : undefined);
var rows = await Zotero.DB.queryAsync(sql, str ? '%' + str + '%' : undefined);
return rows.map((row) => this.cleanData(row));
});
};
/**
@ -274,7 +274,7 @@ Zotero.Tags = new function() {
* @param {String} newName
* @return {Promise}
*/
this.rename = Zotero.Promise.coroutine(function* (libraryID, oldName, newName) {
this.rename = async function (libraryID, oldName, newName) {
Zotero.debug("Renaming tag '" + oldName + "' to '" + newName + "' in library " + libraryID);
oldName = oldName.trim();
@ -294,31 +294,31 @@ Zotero.Tags = new function() {
// we can assign it to the new name
var oldColorData = this.getColor(libraryID, oldName);
yield Zotero.DB.executeTransaction(async function () {
await Zotero.DB.executeTransaction(async function () {
var oldItemIDs = await this.getTagItems(libraryID, oldTagID);
var newTagID = await this.create(newName);
await Zotero.Utilities.Internal.forEachChunkAsync(
oldItemIDs,
Zotero.DB.MAX_BOUND_PARAMETERS - 2,
Zotero.Promise.coroutine(function* (chunk) {
async function (chunk) {
let placeholders = chunk.map(() => '?').join(',');
// This is ugly, but it's much faster than doing replaceTag() for each item
let sql = 'UPDATE OR REPLACE itemTags SET tagID=?, type=0 '
+ 'WHERE tagID=? AND itemID IN (' + placeholders + ')';
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
sql, [newTagID, oldTagID].concat(chunk), { noCache: true }
);
sql = 'UPDATE items SET synced=0, clientDateModified=? '
+ 'WHERE itemID IN (' + placeholders + ')'
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
sql, [Zotero.DB.transactionDateTime].concat(chunk), { noCache: true }
);
yield Zotero.Items.reload(oldItemIDs, ['primaryData', 'tags'], true);
})
await Zotero.Items.reload(oldItemIDs, ['primaryData', 'tags'], true);
}
);
var notifierData = {};
@ -342,7 +342,7 @@ Zotero.Tags = new function() {
}.bind(this));
if (oldColorData) {
yield Zotero.DB.executeTransaction(async function () {
await Zotero.DB.executeTransaction(async function () {
// Remove color from old tag
await this.setColor(libraryID, oldName);
@ -355,7 +355,7 @@ Zotero.Tags = new function() {
);
}.bind(this));
}
});
};
/**
@ -365,7 +365,7 @@ Zotero.Tags = new function() {
* @param {Integer[]} [types]
* @return {Promise}
*/
this.removeFromLibrary = Zotero.Promise.coroutine(function* (libraryID, tagIDs, onProgress, types) {
this.removeFromLibrary = async function (libraryID, tagIDs, onProgress, types) {
var d = new Date();
if (!Array.isArray(tagIDs)) {
@ -378,7 +378,7 @@ Zotero.Tags = new function() {
var colors = this.getColors(libraryID);
var done = 0;
yield Zotero.Utilities.Internal.forEachChunkAsync(
await Zotero.Utilities.Internal.forEachChunkAsync(
tagIDs,
100,
async function (chunk) {
@ -458,7 +458,7 @@ Zotero.Tags = new function() {
Zotero.debug(`Removed ${tagIDs.length} ${Zotero.Utilities.pluralize(tagIDs.length, 'tag')} `
+ `in ${new Date() - d} ms`);
});
};
/**
@ -491,7 +491,7 @@ Zotero.Tags = new function() {
* @param {Number|Number[]} [tagIDs] - tagID or array of tagIDs to purge
* @return {Promise}
*/
this.purge = Zotero.Promise.coroutine(function* (tagIDs) {
this.purge = async function (tagIDs) {
var d = new Date();
if (!_initialized) {
@ -517,8 +517,8 @@ Zotero.Tags = new function() {
// Use given tags, as long as they're orphaned
if (tagIDs) {
sql = "CREATE TEMPORARY TABLE tagDelete (tagID INT PRIMARY KEY)";
yield Zotero.DB.queryAsync(sql);
yield Zotero.Utilities.Internal.forEachChunkAsync(
await Zotero.DB.queryAsync(sql);
await Zotero.Utilities.Internal.forEachChunkAsync(
tagIDs,
Zotero.DB.MAX_BOUND_PARAMETERS,
function (chunk) {
@ -535,22 +535,22 @@ Zotero.Tags = new function() {
// Skip tags that are still linked to items
sql = "DELETE FROM tagDelete WHERE tagID IN (SELECT tagID FROM itemTags)";
yield Zotero.DB.queryAsync(sql);
await Zotero.DB.queryAsync(sql);
sql = "SELECT tagID AS id, name FROM tagDelete JOIN tags USING (tagID)";
var toDelete = yield Zotero.DB.queryAsync(sql);
var toDelete = await Zotero.DB.queryAsync(sql);
}
// Look for orphaned tags
else {
sql = "CREATE TEMPORARY TABLE tagDelete AS "
+ "SELECT tagID FROM tags WHERE tagID NOT IN (SELECT tagID FROM itemTags)";
yield Zotero.DB.queryAsync(sql);
await Zotero.DB.queryAsync(sql);
sql = "CREATE INDEX tagDelete_tagID ON tagDelete(tagID)";
yield Zotero.DB.queryAsync(sql);
await Zotero.DB.queryAsync(sql);
sql = "SELECT tagID AS id, name FROM tagDelete JOIN tags USING (tagID)";
var toDelete = yield Zotero.DB.queryAsync(sql);
var toDelete = await Zotero.DB.queryAsync(sql);
}
if (!toDelete.length) {
@ -576,10 +576,10 @@ Zotero.Tags = new function() {
}
sql = "DELETE FROM tags WHERE tagID IN (SELECT tagID FROM tagDelete);";
yield Zotero.DB.queryAsync(sql);
await Zotero.DB.queryAsync(sql);
sql = "DROP TABLE tagDelete";
yield Zotero.DB.queryAsync(sql);
await Zotero.DB.queryAsync(sql);
Zotero.Notifier.queue('delete', 'tag', ids, notifierData);
@ -587,7 +587,7 @@ Zotero.Tags = new function() {
Zotero.debug(`Purged ${toDelete.length} ${Zotero.Utilities.pluralize(toDelete.length, 'tag')} `
+ `in ${new Date() - d} ms`);
});
};
//
@ -660,7 +660,7 @@ Zotero.Tags = new function() {
*
* @return {Promise}
*/
this.setColor = Zotero.Promise.coroutine(function* (libraryID, name, color, position) {
this.setColor = async function (libraryID, name, color, position) {
if (!Number.isInteger(libraryID)) {
throw new Error("libraryID must be an integer");
}
@ -722,14 +722,14 @@ Zotero.Tags = new function() {
else {
return Zotero.SyncedSettings.clear(libraryID, 'tagColors');
}
});
};
/**
* Update caches and trigger redrawing of items in the items list
* when a 'tagColors' setting is modified
*/
this.notify = Zotero.Promise.coroutine(function* (event, type, ids, extraData) {
this.notify = async function (event, type, ids, extraData) {
if (type != 'setting') {
return;
}
@ -771,17 +771,17 @@ Zotero.Tags = new function() {
// Colored tags may not exist
if (tagID) {
affectedItems = affectedItems.concat(
yield this.getTagItems(libraryID, tagID)
await this.getTagItems(libraryID, tagID)
);
}
};
}
if (affectedItems.length) {
yield Zotero.Notifier.trigger('redraw', 'item', affectedItems, { column: 'title' });
await Zotero.Notifier.trigger('redraw', 'item', affectedItems, { column: 'title' });
}
}
});
};
this.toggleItemsListTags = async function (items, tagName) {
@ -929,7 +929,7 @@ Zotero.Tags = new function() {
}
if (retracted) {
let [img1, img2] = await Zotero.Promise.all([
let [img1, img2] = await Promise.all([
_itemsListImagePromises[extraImage],
_itemsListImagePromises[retractionImage]
]);
@ -949,7 +949,7 @@ Zotero.Tags = new function() {
}
var dataURI = canvas.toDataURL("image/png");
_itemsListImagePromises[hash] = Zotero.Promise.resolve(dataURI);
_itemsListImagePromises[hash] = Promise.resolve(dataURI);
return dataURI;
};

View file

@ -53,7 +53,7 @@ Zotero.DataDirectory = {
_warnOnUnsafeLocation: true,
init: Zotero.Promise.coroutine(function* () {
init: async function () {
var dataDir;
var dbFilename = this.getDatabaseFilename();
// Handle directory specified on command line
@ -73,7 +73,7 @@ Zotero.DataDirectory = {
}
// Require parent directory to exist
if (!(yield OS.File.exists(PathUtils.parent(dir)))) {
if (!((await OS.File.exists(PathUtils.parent(dir))))) {
throw `Parent directory of -datadir ${dir} not found`;
}
@ -113,8 +113,8 @@ Zotero.DataDirectory = {
let migrationMarker = OS.Path.join(prefVal, this.MIGRATION_MARKER);
let dbFile = OS.Path.join(prefVal, dbFilename);
if ((yield OS.File.exists(migrationMarker)) && !(yield OS.File.exists(dbFile))) {
let contents = yield Zotero.File.getContentsAsync(migrationMarker);
if (((await OS.File.exists(migrationMarker))) && !((await OS.File.exists(dbFile)))) {
let contents = await Zotero.File.getContentsAsync(migrationMarker);
try {
let { sourceDir } = JSON.parse(contents);
dataDir = OS.Path.normalize(sourceDir);
@ -139,7 +139,7 @@ Zotero.DataDirectory = {
}
}
if (!(yield OS.File.exists(dataDir)) && dataDir != this.defaultDir) {
if (!((await OS.File.exists(dataDir))) && dataDir != this.defaultDir) {
// If set to a legacy directory that doesn't exist, forget about it and just use the
// new default location, which will either exist or be created below. The most likely
// cause of this is a migration, so don't bother looking in other-app profiles.
@ -161,13 +161,13 @@ Zotero.DataDirectory = {
try {
if (dataDir != this.defaultDir
&& this.isLegacy(dataDir)
&& (yield OS.File.exists(OS.Path.join(this.defaultDir, 'move-to-old')))) {
&& ((await OS.File.exists(OS.Path.join(this.defaultDir, 'move-to-old'))))) {
let newPath = this.defaultDir + '-Old';
if (yield OS.File.exists(newPath)) {
if (await OS.File.exists(newPath)) {
newPath += "-1";
}
yield Zotero.File.moveDirectory(this.defaultDir, newPath);
yield OS.File.remove(OS.Path.join(newPath, 'move-to-old'));
await Zotero.File.moveDirectory(this.defaultDir, newPath);
await OS.File.remove(OS.Path.join(newPath, 'move-to-old'));
}
}
catch (e) {
@ -190,11 +190,11 @@ Zotero.DataDirectory = {
// data directory named after the profile, as long as one either doesn't exist yet or
// one does and it contains a database
try {
if ((yield Zotero.Profile.findOtherProfilesUsingDataDirectory(dataDir, false)).length) {
if (((await Zotero.Profile.findOtherProfilesUsingDataDirectory(dataDir, false))).length) {
let profileName = PathUtils.filename(Zotero.Profile.dir).match(/[^.]+\.(.+)/)[1];
let newDataDir = this.defaultDir + ' ' + profileName;
if (!(yield OS.File.exists(newDataDir))
|| (yield OS.File.exists(OS.Path.join(newDataDir, dbFilename)))) {
if (!((await OS.File.exists(newDataDir)))
|| ((await OS.File.exists(OS.Path.join(newDataDir, dbFilename))))) {
dataDir = newDataDir;
dataDirNamedAfterProfile = true;
}
@ -206,7 +206,7 @@ Zotero.DataDirectory = {
// Check for ~/Zotero/zotero.sqlite
let dbFile = OS.Path.join(dataDir, dbFilename);
if (yield OS.File.exists(dbFile)) {
if (await OS.File.exists(dbFile)) {
Zotero.debug("Using data directory " + dataDir);
this._cache(dataDir);
@ -221,7 +221,7 @@ Zotero.DataDirectory = {
try {
let dir = OS.Path.join(Zotero.Profile.dir, this.legacyDirName);
let dbFile = OS.Path.join(dir, dbFilename);
profileSubdirModTime = new Date((yield IOUtils.stat(dbFile)).lastModified);
profileSubdirModTime = new Date(((await IOUtils.stat(dbFile))).lastModified);
Zotero.debug(`Database found at ${dbFile}, last modified ${profileSubdirModTime}`);
dataDir = dir;
useProfile = true;
@ -243,7 +243,7 @@ Zotero.DataDirectory = {
if (profilesParent) {
Zotero.debug("Looking for Firefox profile in " + profilesParent);
try {
defProfile = yield Zotero.Profile.getDefaultInProfilesDir(profilesParent);
defProfile = await Zotero.Profile.getDefaultInProfilesDir(profilesParent);
}
catch (e) {
Zotero.debug("An error occurred locating the Firefox profile; "
@ -258,8 +258,8 @@ Zotero.DataDirectory = {
// Read in prefs
let prefsFile = OS.Path.join(profileDir, "prefs.js");
if (yield OS.File.exists(prefsFile)) {
let prefs = yield Zotero.Profile.readPrefsFromFile(prefsFile);
if (await OS.File.exists(prefsFile)) {
let prefs = await Zotero.Profile.readPrefsFromFile(prefsFile);
// Check for data dir pref
if (prefs['extensions.zotero.dataDir'] && prefs['extensions.zotero.useDataDir']) {
@ -281,7 +281,7 @@ Zotero.DataDirectory = {
}
try {
let dbFile = OS.Path.join(nsIFile.path, dbFilename);
let mtime = new Date((yield IOUtils.stat(dbFile)).lastModified);
let mtime = new Date(((await IOUtils.stat(dbFile))).lastModified);
Zotero.debug(`Database found at ${dbFile}, last modified ${mtime}`);
// If custom location has a newer DB, use that
if (!useProfile || mtime > profileSubdirModTime) {
@ -309,7 +309,7 @@ Zotero.DataDirectory = {
try {
let dir = OS.Path.join(profileDir, this.legacyDirName);
let dbFile = OS.Path.join(dir, dbFilename);
let mtime = new Date((yield IOUtils.stat(dbFile)).lastModified);
let mtime = new Date(((await IOUtils.stat(dbFile))).lastModified);
Zotero.debug(`Database found at ${dbFile}, last modified ${mtime}`);
// If newer than Zotero profile directory, use this one
if (!useProfile || mtime > profileSubdirModTime) {
@ -353,7 +353,7 @@ Zotero.DataDirectory = {
Zotero.debug("Using data directory " + dataDir);
try {
yield Zotero.File.createDirectoryIfMissingAsync(dataDir);
await Zotero.File.createDirectoryIfMissingAsync(dataDir);
}
catch (e) {
// TEMP: OS.Constants.Win.ERROR_ACCESS_DENIED no longer available, but we should
@ -386,7 +386,7 @@ Zotero.DataDirectory = {
null, null, {}
);
if (index == 0) {
let changed = yield Zotero.DataDirectory.choose(true);
let changed = await Zotero.DataDirectory.choose(true);
if (!changed) {
Zotero.Utilities.Internal.quit();
}
@ -413,7 +413,7 @@ Zotero.DataDirectory = {
Zotero.Utilities.Internal.quit();
}
else if (index == 2) {
let changed = yield Zotero.DataDirectory.choose(true);
let changed = await Zotero.DataDirectory.choose(true);
if (!changed) {
Zotero.Utilities.Internal.quit();
return;
@ -424,7 +424,7 @@ Zotero.DataDirectory = {
}
}
this._cache(dataDir);
}),
},
_cache: function (dir) {
@ -468,7 +468,7 @@ Zotero.DataDirectory = {
fp.init(win, Zotero.getString('dataDir.selectDir'), fp.modeGetFolder);
fp.displayDirectory = this._dir ? this._dir : PathUtils.parent(this.defaultDir);
fp.appendFilters(fp.filterAll);
if (await fp.show() == fp.returnOK) {
if ((await fp.show()) == fp.returnOK) {
let file = Zotero.File.pathToFile(fp.file);
let dialogText = '';
let dialogTitle = '';
@ -599,7 +599,7 @@ Zotero.DataDirectory = {
fp.init(win, Zotero.getString('dataDir.selectNewDir', Zotero.clientName), fp.modeGetFolder);
fp.displayDirectory = this.dir;
fp.appendFilters(fp.filterAll);
if (await fp.show() == fp.returnOK) {
if ((await fp.show()) == fp.returnOK) {
let file = Zotero.File.pathToFile(fp.file);
if (file.directoryEntries.hasMoreElements()) {
@ -620,7 +620,7 @@ Zotero.DataDirectory = {
},
checkForUnsafeLocation: Zotero.Promise.coroutine(function* (path) {
checkForUnsafeLocation: async function (path) {
if (!this._warnOnUnsafeLocation || !Zotero.Prefs.get('warnOnUnsafeDataDir')) {
return;
}
@ -645,7 +645,7 @@ Zotero.DataDirectory = {
// Yes - display dialog.
if (index == 0) {
yield this.choose(true);
await this.choose(true);
}
else if (index == 2) {
Zotero.launchURL('https://www.zotero.org/support/kb/data_directory_in_cloud_storage_folder');
@ -654,7 +654,7 @@ Zotero.DataDirectory = {
Zotero.Prefs.set('warnOnUnsafeDataDir', false);
}
}
}),
},
isLegacy: function (dir) {
@ -667,16 +667,16 @@ Zotero.DataDirectory = {
},
isNewDirOnDifferentDrive: Zotero.Promise.coroutine(function* (oldDir, newDir) {
isNewDirOnDifferentDrive: async function (oldDir, newDir) {
var filename = 'zotero-migration.tmp';
var tmpFile = OS.Path.join(Zotero.getTempDirectory().path, filename);
yield Zotero.File.putContentsAsync(tmpFile, ' ');
await Zotero.File.putContentsAsync(tmpFile, ' ');
var testPath = OS.Path.normalize(OS.Path.join(newDir, '..', filename));
try {
// Attempt moving the marker with noCopy
yield OS.File.move(tmpFile, testPath, { noCopy: true });
await OS.File.move(tmpFile, testPath, { noCopy: true });
} catch(e) {
yield OS.File.remove(tmpFile);
await OS.File.remove(tmpFile);
if (e instanceof OS.File.Error) {
if (e.unixErrno != undefined && e.unixErrno == ChromeUtils.getLibcConstants().EXDEV) {
@ -690,9 +690,9 @@ Zotero.DataDirectory = {
}
throw e;
}
yield OS.File.remove(testPath);
await OS.File.remove(testPath);
return false;
}),
},
isStorageDirectory: async function (dir) {
@ -876,14 +876,14 @@ Zotero.DataDirectory = {
* @param {String} targetDir - Target directory, which may be the same; except in tests, this is
* the default data directory
*/
checkForMigration: Zotero.Promise.coroutine(function* (dataDir, newDir) {
checkForMigration: async function (dataDir, newDir) {
if (!this.canMigrate(dataDir)) {
return false;
}
let migrationMarker = OS.Path.join(dataDir, this.MIGRATION_MARKER);
try {
var exists = yield OS.File.exists(migrationMarker)
var exists = await OS.File.exists(migrationMarker)
}
catch (e) {
Zotero.logError(e);
@ -894,7 +894,7 @@ Zotero.DataDirectory = {
// Skip automatic migration if there's a non-empty directory at the new location
// TODO: Notify user
if ((yield OS.File.exists(newDir)) && !(yield Zotero.File.directoryIsEmpty(newDir))) {
if (((await OS.File.exists(newDir))) && !((await Zotero.File.directoryIsEmpty(newDir)))) {
Zotero.debug(`${newDir} exists and is non-empty -- skipping migration`);
return false;
}
@ -902,7 +902,7 @@ Zotero.DataDirectory = {
// Skip migration if new dir on different drive and prompt
try {
if (yield this.isNewDirOnDifferentDrive(dataDir, newDir)) {
if (await this.isNewDirOnDifferentDrive(dataDir, newDir)) {
Zotero.debug(`New dataDir ${newDir} is on a different drive from ${dataDir} -- skipping migration`);
Zotero.DataDirectory.newDirOnDifferentDrive = true;
@ -921,11 +921,11 @@ Zotero.DataDirectory = {
// If there are other profiles pointing to the old directory, make sure we can edit the prefs.js
// file before doing anything, or else we risk orphaning a 4.0 installation
try {
let otherProfiles = yield Zotero.Profile.findOtherProfilesUsingDataDirectory(dataDir);
let otherProfiles = await Zotero.Profile.findOtherProfilesUsingDataDirectory(dataDir);
// 'touch' each prefs.js file to make sure we can access it
for (let dir of otherProfiles) {
let prefsFile = OS.Path.join(dir, "prefs.js");
yield IOUtils.setModificationTime(prefsFile);
await IOUtils.setModificationTime(prefsFile);
}
}
catch (e) {
@ -938,7 +938,7 @@ Zotero.DataDirectory = {
}
if (automatic) {
yield this.markForMigration(dataDir, true);
await this.markForMigration(dataDir, true);
}
let sourceDir;
@ -948,7 +948,7 @@ Zotero.DataDirectory = {
// Check whether this is an automatic or manual migration
let contents;
try {
contents = yield Zotero.File.getContentsAsync(migrationMarker);
contents = await Zotero.File.getContentsAsync(migrationMarker);
({ sourceDir, automatic } = JSON.parse(contents));
}
catch (e) {
@ -992,7 +992,7 @@ Zotero.DataDirectory = {
Zotero.logError(e);
}
try {
errors = yield this.migrate(oldDir, newDir, partial, progressHandler);
errors = await this.migrate(oldDir, newDir, partial, progressHandler);
}
catch (e) {
// Complete failure (failed to create new directory, copy marker, or move database)
@ -1004,7 +1004,7 @@ Zotero.DataDirectory = {
+ e
+ "\n\n"
+ Zotero.getString(`dataDir.migration.failure.full.${mode}.text2`, Zotero.appName);
yield this.fullMigrationFailurePrompt(oldDir, newDir, error);
await this.fullMigrationFailurePrompt(oldDir, newDir, error);
// Clear status line from progress meter
try {
@ -1048,15 +1048,15 @@ Zotero.DataDirectory = {
else if (index == 2) {
try {
let firstEntry;
yield Zotero.File.iterateDirectory(oldDir, function (entry, index, iterator) {
await Zotero.File.iterateDirectory(oldDir, function (entry, index, iterator) {
firstEntry = entry;
iterator.close();
});
if (firstEntry) {
yield Zotero.File.reveal(firstEntry.path);
await Zotero.File.reveal(firstEntry.path);
}
// Focus the database file in the new directory
yield Zotero.File.reveal(OS.Path.join(newDir, this.getDatabaseFilename()));
await Zotero.File.reveal(OS.Path.join(newDir, this.getDatabaseFilename()));
}
catch (e) {
Zotero.logError(e);
@ -1067,10 +1067,10 @@ Zotero.DataDirectory = {
return;
}
}
}),
},
fullMigrationFailurePrompt: Zotero.Promise.coroutine(function* (oldDir, newDir, error) {
fullMigrationFailurePrompt: async function (oldDir, newDir, error) {
let ps = Services.prompt;
let buttonFlags = (ps.BUTTON_POS_0) * (ps.BUTTON_TITLE_IS_STRING)
+ (ps.BUTTON_POS_1) * (ps.BUTTON_TITLE_IS_STRING);
@ -1086,11 +1086,11 @@ Zotero.DataDirectory = {
null, null, {}
);
if (index == 0) {
yield Zotero.File.reveal(oldDir);
await Zotero.File.reveal(oldDir);
Zotero.skipLoading = true;
Zotero.Utilities.Internal.quitZotero();
}
}),
},
/**
@ -1104,7 +1104,7 @@ Zotero.DataDirectory = {
* @param {String} newDir
* @return {Error[]}
*/
migrate: Zotero.Promise.coroutine(function* (oldDir, newDir, partial) {
migrate: async function (oldDir, newDir, partial) {
var dbName = this.getDatabaseFilename();
var errors = [];
@ -1113,12 +1113,12 @@ Zotero.DataDirectory = {
Zotero.logError(e);
}
if (!(yield OS.File.exists(oldDir))) {
if (!((await OS.File.exists(oldDir)))) {
Zotero.debug(`Old directory ${oldDir} doesn't exist -- nothing to migrate`);
try {
let newMigrationMarker = OS.Path.join(newDir, this.MIGRATION_MARKER);
Zotero.debug("Removing " + newMigrationMarker);
yield OS.File.remove(newMigrationMarker);
await OS.File.remove(newMigrationMarker);
}
catch (e) {
Zotero.logError(e);
@ -1135,7 +1135,7 @@ Zotero.DataDirectory = {
// Create the new directory
if (!partial) {
yield IOUtils.makeDirectory(
await IOUtils.makeDirectory(
newDir,
{
ignoreExisting: false,
@ -1147,8 +1147,8 @@ Zotero.DataDirectory = {
// Copy marker
let oldMarkerFile = OS.Path.join(oldDir, this.MIGRATION_MARKER);
// Marker won't exist on subsequent attempts after partial failure
if (yield OS.File.exists(oldMarkerFile)) {
yield OS.File.copy(oldMarkerFile, OS.Path.join(newDir, this.MIGRATION_MARKER));
if (await OS.File.exists(oldMarkerFile)) {
await OS.File.copy(oldMarkerFile, OS.Path.join(newDir, this.MIGRATION_MARKER));
}
// Update the data directory setting first so that a failure immediately after the move won't
@ -1159,7 +1159,7 @@ Zotero.DataDirectory = {
if (!partial) {
Zotero.debug("Moving " + dbName);
try {
yield OS.File.move(OS.Path.join(oldDir, dbName), OS.Path.join(newDir, dbName));
await OS.File.move(OS.Path.join(oldDir, dbName), OS.Path.join(newDir, dbName));
}
// If moving the database failed, revert to the old data directory and clear marker files
catch (e) {
@ -1171,14 +1171,14 @@ Zotero.DataDirectory = {
this.set(oldDir);
}
try {
yield OS.File.remove(oldMarkerFile, { ignoreAbsent: true });
await OS.File.remove(oldMarkerFile, { ignoreAbsent: true });
}
catch (e) {
Zotero.logError(e);
}
try {
yield OS.File.remove(OS.Path.join(newDir, this.MIGRATION_MARKER));
yield OS.File.removeEmptyDir(newDir);
await OS.File.remove(OS.Path.join(newDir, this.MIGRATION_MARKER));
await OS.File.removeEmptyDir(newDir);
}
catch (e) {
Zotero.logError(e);
@ -1191,13 +1191,13 @@ Zotero.DataDirectory = {
// If the migration is interrupted after this, it can be continued later based on the migration
// marker in the new directory.
try {
yield OS.File.remove(OS.Path.join(oldDir, this.MIGRATION_MARKER));
await OS.File.remove(OS.Path.join(oldDir, this.MIGRATION_MARKER));
}
catch (e) {
addError(e);
}
errors = errors.concat(yield Zotero.File.moveDirectory(
errors = errors.concat(await Zotero.File.moveDirectory(
oldDir,
newDir,
{
@ -1216,7 +1216,7 @@ Zotero.DataDirectory = {
try {
let newMigrationMarker = OS.Path.join(newDir, this.MIGRATION_MARKER);
Zotero.debug("Removing " + newMigrationMarker);
yield OS.File.remove(newMigrationMarker);
await OS.File.remove(newMigrationMarker);
Zotero.debug("Migration successful");
}
@ -1227,10 +1227,10 @@ Zotero.DataDirectory = {
// Update setting in other profiles that point to this data directory
try {
let otherProfiles = yield Zotero.Profile.findOtherProfilesUsingDataDirectory(oldDir);
let otherProfiles = await Zotero.Profile.findOtherProfilesUsingDataDirectory(oldDir);
for (let dir of otherProfiles) {
try {
yield Zotero.Profile.updateProfileDataDirectory(dir, oldDir, newDir);
await Zotero.Profile.updateProfileDataDirectory(dir, oldDir, newDir);
}
catch (e) {
Zotero.logError("Error updating " + OS.Path.join(dir.path, "prefs.js"));
@ -1243,7 +1243,7 @@ Zotero.DataDirectory = {
}
return errors;
}),
},
getDatabaseFilename: function (name) {

View file

@ -31,7 +31,7 @@
// the same database is accessed simultaneously by multiple Zotero instances.
const DB_LOCK_EXCLUSIVE = true;
Zotero.DBConnection = function(dbNameOrPath) {
Zotero.DBConnection = function (dbNameOrPath) {
if (!dbNameOrPath) {
throw ('DB name not provided in Zotero.DBConnection()');
}
@ -508,7 +508,7 @@ Zotero.DBConnection.prototype.executeTransaction = async function (func, options
// Run temporary commit callbacks
var f;
while (f = this._callbacks.current.commit.shift()) {
await Zotero.Promise.resolve(f(id));
await Promise.resolve(f(id));
}
// Run commit callbacks
@ -541,13 +541,13 @@ Zotero.DBConnection.prototype.executeTransaction = async function (func, options
// Run temporary commit callbacks
var f;
while (f = this._callbacks.current.rollback.shift()) {
await Zotero.Promise.resolve(f(id));
await Promise.resolve(f(id));
}
// Run rollback callbacks
for (var i=0; i<this._callbacks.rollback.length; i++) {
if (this._callbacks.rollback[i]) {
await Zotero.Promise.resolve(this._callbacks.rollback[i](id));
await Promise.resolve(this._callbacks.rollback[i](id));
}
}
@ -569,7 +569,7 @@ Zotero.DBConnection.prototype.inTransaction = function () {
Zotero.DBConnection.prototype.waitForTransaction = function (id) {
if (!this._transactionID) {
return Zotero.Promise.resolve();
return Promise.resolve();
}
if (Zotero.Debug.enabled) {
Zotero.debug(`Waiting for DB transaction ${this._transactionID} to finish`
@ -646,7 +646,7 @@ Zotero.DBConnection.prototype.queryAsync = async function (sql, params, options
}
// Fake an associative array with a proxy
let handler = {
get: function(target, name) {
get: function (target, name) {
// Ignore promise check
if (name == 'then') {
return undefined;
@ -662,7 +662,7 @@ Zotero.DBConnection.prototype.queryAsync = async function (sql, params, options
throw new Error(msg);
}
},
has: function(target, name) {
has: function (target, name) {
try {
return !!target.getResultByName(name);
} catch (e) {
@ -854,7 +854,7 @@ Zotero.DBConnection.prototype.indexExists = async function (index, db) {
await this._getConnectionAsync();
var prefix = db ? db + '.' : '';
var sql = `SELECT COUNT(*) FROM ${prefix}sqlite_master WHERE type='index' AND name=?`;
return !!await this.valueQueryAsync(sql, [index]);
return !!(await this.valueQueryAsync(sql, [index]));
};
@ -898,7 +898,7 @@ Zotero.DBConnection.prototype.executeSQLFile = async function (sql) {
/*
* Implements nsIObserver
*/
Zotero.DBConnection.prototype.observe = function(subject, topic, data) {
Zotero.DBConnection.prototype.observe = function (subject, topic, data) {
switch (topic) {
case 'idle':
this.backUpDatabase({ online: true });
@ -1243,7 +1243,7 @@ Zotero.DBConnection.prototype._getConnectionAsync = async function () {
if (await OS.File.exists(corruptMarker)) {
throw new Error(this.DB_CORRUPTION_STRINGS[0]);
}
this._connection = await Zotero.Promise.resolve(this.Sqlite.openConnection({
this._connection = await Promise.resolve(this.Sqlite.openConnection({
path: file
}));
}
@ -1366,7 +1366,7 @@ Zotero.DBConnection.prototype._handleCorruptionMarker = async function () {
this._debug(`Database file '${fileName}' corrupted`, 1);
// No backup file! Eek!
if (!await OS.File.exists(backupFile)) {
if (!(await OS.File.exists(backupFile))) {
this._debug("No backup file for DB '" + this._dbName + "' exists", 1);
let damagedFile;
@ -1383,7 +1383,7 @@ Zotero.DBConnection.prototype._handleCorruptionMarker = async function () {
}
// Create new main database
this._connection = await Zotero.Promise.resolve(this.Sqlite.openConnection({
this._connection = await Promise.resolve(this.Sqlite.openConnection({
path: file
}));
@ -1412,7 +1412,7 @@ Zotero.DBConnection.prototype._handleCorruptionMarker = async function () {
// Test the backup file
try {
Zotero.debug("Asynchronously opening DB connection");
this._connection = await Zotero.Promise.resolve(this.Sqlite.openConnection({
this._connection = await Promise.resolve(this.Sqlite.openConnection({
path: backupFile
}));
await this.closeDatabase();
@ -1420,7 +1420,7 @@ Zotero.DBConnection.prototype._handleCorruptionMarker = async function () {
// Can't open backup either
catch (e) {
// Create new main database
this._connection = await Zotero.Promise.resolve(this.Sqlite.openConnection({
this._connection = await Promise.resolve(this.Sqlite.openConnection({
path: file
}));
@ -1453,7 +1453,7 @@ Zotero.DBConnection.prototype._handleCorruptionMarker = async function () {
}
// Open restored database
this._connection = await Zotero.Promise.resolve(this.Sqlite.openConnection({
this._connection = await Promise.resolve(this.Sqlite.openConnection({
path: file
}));
this._debug('Database restored', 1);

View file

@ -191,7 +191,7 @@ Zotero.Debug = new function () {
}
this.get = Zotero.Promise.method(function(maxChars, maxLineLength) {
this.get = function (maxChars, maxLineLength) {
var output = _output;
var total = output.length;
@ -218,13 +218,13 @@ Zotero.Debug = new function () {
}
}
return Zotero.getSystemInfo().then(function(sysInfo) {
return Zotero.getSystemInfo().then(function (sysInfo) {
return Zotero.getErrors(true).join('\n\n') +
"\n\n" + sysInfo + "\n\n" +
"=========================================================\n\n" +
output;
});
});
};
this.addListener = function (listener) {

View file

@ -201,7 +201,7 @@ Zotero.Dictionaries = new function () {
*/
this.getAvailableUpdates = async function (dictionaries) {
var updates = [];
let availableDictionaries = dictionaries || await this.fetchDictionariesList();
let availableDictionaries = dictionaries || (await this.fetchDictionariesList());
for (let dictionary of _dictionaries) {
let availableDictionary = availableDictionaries.find((x) => {
return x.id === dictionary.id || x.locale == dictionary.locale;

View file

@ -98,7 +98,7 @@ Zotero.Duplicates.prototype._getObjectFromID = function (id) {
}
Zotero.Duplicates.prototype._findDuplicates = Zotero.Promise.coroutine(function* () {
Zotero.Duplicates.prototype._findDuplicates = async function () {
Zotero.debug("Finding duplicates");
var start = Date.now();
@ -196,7 +196,7 @@ Zotero.Duplicates.prototype._findDuplicates = Zotero.Promise.coroutine(function*
+ "JOIN itemDataValues USING (valueID) "
+ "WHERE libraryID=? AND itemTypeID=? AND fieldID=? "
+ "AND itemID NOT IN (SELECT itemID FROM deletedItems)";
var rows = yield Zotero.DB.queryAsync(
var rows = await Zotero.DB.queryAsync(
sql,
[
this._libraryID,
@ -226,7 +226,7 @@ Zotero.Duplicates.prototype._findDuplicates = Zotero.Promise.coroutine(function*
+ "JOIN itemDataValues USING (valueID) "
+ "WHERE libraryID=? AND fieldID=? AND value LIKE ? "
+ "AND itemID NOT IN (SELECT itemID FROM deletedItems)";
var rows = yield Zotero.DB.queryAsync(
var rows = await Zotero.DB.queryAsync(
sql,
[
this._libraryID,
@ -263,7 +263,7 @@ Zotero.Duplicates.prototype._findDuplicates = Zotero.Promise.coroutine(function*
+ "AND SUBSTR(value, 1, 4) != '0000' "
+ "AND itemID NOT IN (SELECT itemID FROM deletedItems) "
+ "ORDER BY value";
var rows = yield Zotero.DB.queryAsync(sql, [this._libraryID].concat(dateFields));
var rows = await Zotero.DB.queryAsync(sql, [this._libraryID].concat(dateFields));
var yearCache = {};
for (let i = 0; i < rows.length; i++) {
let row = rows[i];
@ -282,10 +282,10 @@ Zotero.Duplicates.prototype._findDuplicates = Zotero.Promise.coroutine(function*
+ "(" + titleIDs.join(', ') + ") "
+ `AND itemTypeID NOT IN (${itemTypeAttachment}, ${itemTypeNote}) `
+ "AND itemID NOT IN (SELECT itemID FROM deletedItems)";
var rows = yield Zotero.DB.queryAsync(sql, [this._libraryID]);
var rows = await Zotero.DB.queryAsync(sql, [this._libraryID]);
if (rows.length) {
//normalize all values ahead of time
rows = rows.map(function(row) {
rows = rows.map(function (row) {
return {
itemID: row.itemID,
value: normalizeString(row.value)
@ -305,7 +305,7 @@ Zotero.Duplicates.prototype._findDuplicates = Zotero.Promise.coroutine(function*
+ `WHERE libraryID=? AND itemTypeID NOT IN (${itemTypeAttachment}, ${itemTypeNote}) AND `
+ "itemID NOT IN (SELECT itemID FROM deletedItems)"
+ "ORDER BY itemID, orderIndex";
let creatorRows = yield Zotero.DB.queryAsync(sql, this._libraryID);
let creatorRows = await Zotero.DB.queryAsync(sql, this._libraryID);
let lastItemID;
let itemCreators = [];
for (let i = 0; i < creatorRows.length; i++) {
@ -414,7 +414,7 @@ Zotero.Duplicates.prototype._findDuplicates = Zotero.Promise.coroutine(function*
}*/
Zotero.debug("Found duplicates in " + (Date.now() - start) + " ms");
});
};

View file

@ -237,7 +237,7 @@ class EditorInstance {
if (type === 'file' && event === 'download') {
let items = await Zotero.Items.getAsync(ids);
for (let item of items) {
if (item.isAttachment() && await item.getFilePathAsync()) {
if (item.isAttachment() && (await item.getFilePathAsync())) {
let subscription = this._subscriptions.find(x => x.data.attachmentKey === item.key);
if (subscription) {
await this._feedSubscription(subscription);
@ -345,7 +345,7 @@ class EditorInstance {
let items = await Zotero.Items.getAsync(ids);
for (let item of items) {
if (item.isNote()
&& !await Zotero.Notes.ensureEmbeddedImagesAreAvailable(item)
&& !(await Zotero.Notes.ensureEmbeddedImagesAreAvailable(item))
&& !Zotero.Notes.promptToIgnoreMissingImage()) {
return null;
}
@ -431,7 +431,7 @@ class EditorInstance {
if (!this._filesReadOnly) {
let attachments = Zotero.Items.get(item.getAttachments());
for (let attachment of attachments) {
if (!await attachment.fileExists()) {
if (!(await attachment.fileExists())) {
continue;
}
await Zotero.DB.executeTransaction(async () => {
@ -1028,7 +1028,7 @@ class EditorInstance {
u8arr[n] = bstr.charCodeAt(n);
}
return new (Zotero.getMainWindow()).Blob([u8arr], { type: mime });
return new ((Zotero.getMainWindow()).Blob)([u8arr], { type: mime });
}
return null;
}
@ -1331,7 +1331,7 @@ class EditorInstance {
for (let annotation of annotations) {
if (annotation.annotationType === 'image'
&& !await Zotero.Annotations.hasCacheImage(annotation)) {
&& !(await Zotero.Annotations.hasCacheImage(annotation))) {
try {
await Zotero.PDFWorker.renderAttachmentAnnotations(annotation.parentID);
}

View file

@ -117,7 +117,7 @@ Zotero.FeedReader = function (url) {
}.bind(this)).catch(function (e) {
Zotero.debug("Feed processing failed " + e.message);
this._feedProcessed.reject(e);
// eslint-disable-next-line newline-per-chained-call
}.bind(this)).finally(function () {
// Make sure the last promise gets resolved to null
let lastItem = this._feedItems[this._feedItems.length - 1];
@ -211,9 +211,9 @@ Zotero.FeedReader = function (url) {
* The constructor initiates async feed processing, but _feedProcessed
* needs to be resolved before proceeding.
*/
Zotero.FeedReader.prototype.process = Zotero.Promise.coroutine(function* () {
Zotero.FeedReader.prototype.process = async function () {
return this._feedProcessed.promise;
});
};
/*
* Terminate feed processing at any given time
@ -261,7 +261,7 @@ Zotero.defineProperty(Zotero.FeedReader.prototype, 'feedProperties', {
Zotero.defineProperty(Zotero.FeedReader.prototype, 'ItemIterator', {
get: function () {
let items = this._feedItems;
// eslint-disable-next-line consistent-this
let feedReader = this;
let iterator = function () {

View file

@ -27,7 +27,7 @@
* Functions for reading files
* @namespace
*/
Zotero.File = new function(){
Zotero.File = new function () {
Components.utils.import("resource://gre/modules/NetUtil.jsm");
Components.utils.import("resource://gre/modules/FileUtils.jsm");
@ -69,7 +69,7 @@ Zotero.File = new function(){
* @param {String} path File path
* @return {String} Encoded file path
*/
this.encodeFilePath = function(path) {
this.encodeFilePath = function (path) {
var parts = path.split(/([\\\/:]+)/);
// Every other item is the separator
for (var i=0, n=parts.length; i<n; i+=2) {
@ -109,7 +109,7 @@ Zotero.File = new function(){
}
var dir = PathUtils.parent(file);
while (dir && dir != '/' && !await OS.File.exists(dir)) {
while (dir && dir != '/' && !(await OS.File.exists(dir))) {
dir = PathUtils.parent(dir);
}
@ -132,7 +132,7 @@ Zotero.File = new function(){
/**
* Get contents of a binary file
*/
this.getBinaryContents = function(file) {
this.getBinaryContents = function (file) {
Zotero.debug("Zotero.File.getBinaryContents() is deprecated -- "
+ "use Zotero.File.getBinaryContentsAsync() when possible", 2);
var iStream = Components.classes["@mozilla.org/network/file-input-stream;1"]
@ -234,7 +234,7 @@ Zotero.File = new function(){
|| source instanceof Components.interfaces.nsIChannel) {
var deferred = Zotero.Promise.defer();
try {
NetUtil.asyncFetch(source, function(inputStream, status) {
NetUtil.asyncFetch(source, function (inputStream, status) {
if (!Components.isSuccessCode(status)) {
deferred.reject(new Components.Exception("File read operation failed", status));
return;
@ -310,7 +310,7 @@ Zotero.File = new function(){
* @param {Integer} [maxLength] Maximum length to fetch, in bytes
* @return {Promise<String>} A promise for the contents of the source as a binary string
*/
this.getBinaryContentsAsync = Zotero.Promise.coroutine(function* (source, maxLength) {
this.getBinaryContentsAsync = async function (source, maxLength) {
// Use OS.File for files
if (source instanceof Components.interfaces.nsIFile) {
source = source.path;
@ -322,9 +322,9 @@ Zotero.File = new function(){
if (maxLength) {
options.bytes = maxLength;
}
var buf = yield OS.File.read(source, options);
var buf = await OS.File.read(source, options);
return [...buf].map(x => String.fromCharCode(x)).join("");
});
};
/*
@ -365,7 +365,7 @@ Zotero.File = new function(){
/*
* Return a promise for the contents of a URL as a string
*/
function getContentsFromURLAsync (url, options={}) {
function getContentsFromURLAsync(url, options={}) {
return Zotero.HTTP.request("GET", url, Object.assign(options, { responseType: "text" }))
.then(function (xmlhttp) {
return xmlhttp.response;
@ -407,7 +407,7 @@ Zotero.File = new function(){
}
if (typeof data == 'string') {
return Zotero.Promise.resolve(OS.File.writeAtomic(
return Promise.resolve(OS.File.writeAtomic(
path,
data,
{
@ -423,7 +423,7 @@ Zotero.File = new function(){
if (typeof data.size != 'undefined' && typeof data.slice == 'function') {
let arrayBuffer = await new Zotero.Promise(function (resolve) {
let fr = new FileReader();
fr.addEventListener("loadend", function() {
fr.addEventListener("loadend", function () {
resolve(fr.result);
});
fr.readAsArrayBuffer(data);
@ -436,7 +436,7 @@ Zotero.File = new function(){
await new Zotero.Promise(function (resolve, reject) {
var os = FileUtils.openSafeFileOutputStream(new FileUtils.File(path));
NetUtil.asyncCopy(data, os, function(inputStream, status) {
NetUtil.asyncCopy(data, os, function (inputStream, status) {
if (!Components.isSuccessCode(status)) {
reject(new Components.Exception("File write operation failed", status));
return;
@ -564,7 +564,7 @@ Zotero.File = new function(){
}
});
NetUtil.asyncCopy(pipe.inputStream, outputChannel, function(aResult) {
NetUtil.asyncCopy(pipe.inputStream, outputChannel, function (aResult) {
deferred.resolve();
});
inputChannel.asyncOpen(listener, null);
@ -661,7 +661,7 @@ Zotero.File = new function(){
* @return {Promise<Boolean>} A promise for TRUE if file was deleted, FALSE if missing
*/
this.removeIfExists = function (path) {
return Zotero.Promise.resolve(OS.File.remove(path))
return Promise.resolve(OS.File.remove(path))
.return(true)
.catch(function (e) {
if (e instanceof OS.File.Error && e.becauseNoSuchFile) {
@ -737,13 +737,13 @@ Zotero.File = new function(){
* @param {Function} options.noOverwrite - Function that returns true if the file at the given
* path should throw an error rather than overwrite an existing file in the target
*/
this.moveDirectory = Zotero.Promise.coroutine(function* (oldDir, newDir, options = {}) {
this.moveDirectory = async function (oldDir, newDir, options = {}) {
var maxDepth = options.maxDepth || 10;
var cmd = "/bin/mv";
var useCmd = this.canMoveDirectoryWithCommand();
var useFunction = this.canMoveDirectoryWithFunction();
if (!options.allowExistingTarget && (yield OS.File.exists(newDir))) {
if (!options.allowExistingTarget && ((await OS.File.exists(newDir)))) {
throw new Error(newDir + " exists");
}
@ -766,12 +766,12 @@ Zotero.File = new function(){
}
var rootDir = oldDir;
var moveSubdirs = Zotero.Promise.coroutine(function* (oldDir, depth) {
var moveSubdirs = async function (oldDir, depth) {
if (!depth) return;
// Create target directory
try {
yield Zotero.File.createDirectoryIfMissingAsync(newDir + oldDir.substr(rootDir.length));
await Zotero.File.createDirectoryIfMissingAsync(newDir + oldDir.substr(rootDir.length));
}
catch (e) {
addError(e);
@ -780,7 +780,7 @@ Zotero.File = new function(){
Zotero.debug("Moving files in " + oldDir);
yield Zotero.File.iterateDirectory(oldDir, async function (entry) {
await Zotero.File.iterateDirectory(oldDir, async function (entry) {
var dest = newDir + entry.path.substr(rootDir.length);
// entry.isDir can be false for some reason on Travis, causing spurious test failures
@ -830,7 +830,7 @@ Zotero.File = new function(){
// If can't use command, try moving with IOUtils.move()
if (!moved && useFunction) {
Zotero.debug(`Moving ${entry.path} with IOUtils`);
if (!await IOUtils.exists(dest)) {
if (!(await IOUtils.exists(dest))) {
try {
await IOUtils.move(entry.path, dest);
moved = true;
@ -862,17 +862,17 @@ Zotero.File = new function(){
if (!errors.length || oldDir != rootDir) {
Zotero.debug("Removing " + oldDir);
try {
yield OS.File.removeEmptyDir(oldDir);
await OS.File.removeEmptyDir(oldDir);
}
catch (e) {
addError(e);
}
}
});
};
yield moveSubdirs(oldDir, maxDepth);
await moveSubdirs(oldDir, maxDepth);
return errors;
});
};
/**
@ -1075,11 +1075,11 @@ Zotero.File = new function(){
* @param {String|nsIFile} source - Source directory
* @param {String|nsIFile} target - Target directory
*/
this.copyDirectory = Zotero.Promise.coroutine(function* (source, target) {
this.copyDirectory = async function (source, target) {
if (source instanceof Ci.nsIFile) source = source.path;
if (target instanceof Ci.nsIFile) target = target.path;
yield OS.File.makeDir(target, {
await OS.File.makeDir(target, {
ignoreExisting: true,
unixMode: 0o755
});
@ -1089,7 +1089,7 @@ Zotero.File = new function(){
? this.copyDirectory(entry.path, OS.Path.join(target, entry.name))
: OS.File.copy(entry.path, OS.Path.join(target, entry.name));
}.bind(this))
});
};
this.createDirectoryIfMissing = function (dir) {
@ -1237,15 +1237,15 @@ Zotero.File = new function(){
* @param {nsIRequestObserver} [observer]
* @return {Promise}
*/
this.zipDirectory = Zotero.Promise.coroutine(function* (dirPath, zipPath, observer) {
this.zipDirectory = async function (dirPath, zipPath, observer) {
var zw = Components.classes["@mozilla.org/zipwriter;1"]
.createInstance(Components.interfaces.nsIZipWriter);
zw.open(this.pathToFile(zipPath), 0x04 | 0x08 | 0x20); // open rw, create, truncate
var entries = yield _addZipEntries(dirPath, dirPath, zw);
var entries = await _addZipEntries(dirPath, dirPath, zw);
if (entries.length == 0) {
Zotero.debug('No files to add -- removing ZIP file');
zw.close();
yield OS.File.remove(zipPath);
await OS.File.remove(zipPath);
return false;
}
@ -1288,17 +1288,17 @@ Zotero.File = new function(){
{}
);
return deferred.promise;
});
};
var _addZipEntries = Zotero.Promise.coroutine(function* (rootPath, path, zipWriter) {
var _addZipEntries = async function (rootPath, path, zipWriter) {
var entries = [];
let iterator;
try {
iterator = new OS.File.DirectoryIterator(path);
yield iterator.forEach(Zotero.Promise.coroutine(function* (entry) {
await iterator.forEach(async function (entry) {
// entry.isDir can be false for some reason on Travis, causing spurious test failures
if (Zotero.automatedTest && !entry.isDir && (yield OS.File.stat(entry.path)).isDir) {
if (Zotero.automatedTest && !entry.isDir && ((await OS.File.stat(entry.path))).isDir) {
Zotero.debug("Overriding isDir for " + entry.path);
entry.isDir = true;
}
@ -1308,7 +1308,7 @@ Zotero.File = new function(){
return;
}
if (entry.isDir) {
entries.concat(yield _addZipEntries(rootPath, entry.path, zipWriter));
entries.concat(await _addZipEntries(rootPath, entry.path, zipWriter));
return;
}
if (entry.name.startsWith('.')) {
@ -1328,13 +1328,13 @@ Zotero.File = new function(){
name: entry.name,
path: entry.path
});
}));
});
}
finally {
iterator.close();
}
return entries;
});
};
/**
@ -1528,8 +1528,8 @@ Zotero.File = new function(){
};
this.reveal = Zotero.Promise.coroutine(function* (file) {
if (!(yield OS.File.exists(file))) {
this.reveal = async function (file) {
if (!((await OS.File.exists(file)))) {
throw new Error(file + " does not exist");
}
@ -1546,7 +1546,7 @@ Zotero.File = new function(){
let zp = Zotero.getActiveZoteroPane();
if (zp) {
try {
let info = yield OS.File.stat(file);
let info = await OS.File.stat(file);
// Launch parent directory for files
if (!info.isDir) {
file = PathUtils.parent(file);
@ -1562,5 +1562,5 @@ Zotero.File = new function(){
Zotero.logError(e);
}
}
});
};
}

View file

@ -23,7 +23,7 @@
***** END LICENSE BLOCK *****
*/
/* eslint-disable array-element-newline */
Zotero.FileHandlers = {
async open(item, params) {
@ -512,7 +512,7 @@ Zotero.FileHandlers = {
async _checkAndExecWithoutBlocking(command, args) {
// Run the same checks that exec() runs so that we reject if the
// executable doesn't exist or isn't actually executable
if (!await OS.File.exists(command)) {
if (!(await OS.File.exists(command))) {
throw new Error(`${command} not found`);
}
if (!Zotero.File.pathToFile(command).isExecutable()) {

View file

@ -23,7 +23,7 @@
***** END LICENSE BLOCK *****
*/
Zotero.Fulltext = Zotero.FullText = new function(){
Zotero.Fulltext = Zotero.FullText = new function () {
this.__defineGetter__("fulltextCacheFile", function () { return '.zotero-ft-cache'; });
this.INDEX_STATE_UNAVAILABLE = 0;
@ -60,9 +60,9 @@ Zotero.Fulltext = Zotero.FullText = new function(){
var _upgradeCheck = true;
var _syncLibraryVersion = 0;
this.init = Zotero.Promise.coroutine(function* () {
yield Zotero.DB.queryAsync("ATTACH ':memory:' AS 'indexing'");
yield Zotero.DB.queryAsync('CREATE TABLE indexing.fulltextWords (word NOT NULL)');
this.init = async function () {
await Zotero.DB.queryAsync("ATTACH ':memory:' AS 'indexing'");
await Zotero.DB.queryAsync('CREATE TABLE indexing.fulltextWords (word NOT NULL)');
let pdfConverterFileName = "pdftotext";
let pdfInfoFileName = "pdfinfo";
@ -110,34 +110,34 @@ Zotero.Fulltext = Zotero.FullText = new function(){
// Stop content processor during syncs
Zotero.Notifier.registerObserver(
{
notify: Zotero.Promise.method(function (event, type, ids, extraData) {
notify: function (event, type, ids, extraData) {
if (event == 'start') {
this.unregisterContentProcessor();
}
else if (event == 'stop') {
this.registerContentProcessor();
}
}.bind(this))
}.bind(this)
},
['sync'],
'fulltext'
);
});
});
};
this.setPDFConverterPath = function(path) {
this.setPDFConverterPath = function (path) {
_pdfConverter = Zotero.File.pathToFile(path);
};
this.setPDFInfoPath = function(path) {
this.setPDFInfoPath = function (path) {
_pdfInfo = Zotero.File.pathToFile(path);
};
this.setPDFDataPath = function(path) {
this.setPDFDataPath = function (path) {
_pdfData = path;
};
@ -150,12 +150,12 @@ Zotero.Fulltext = Zotero.FullText = new function(){
};
this.setLibraryVersion = Zotero.Promise.coroutine(function* (libraryID, version) {
this.setLibraryVersion = async function (libraryID, version) {
if (!libraryID) throw new Error("libraryID not provided");
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
"REPLACE INTO version VALUES (?, ?)", ["fulltext_" + libraryID, version]
);
});
};
this.clearLibraryVersion = function (libraryID) {
@ -163,11 +163,11 @@ Zotero.Fulltext = Zotero.FullText = new function(){
};
this.getItemVersion = Zotero.Promise.coroutine(function* (itemID) {
this.getItemVersion = async function (itemID) {
return Zotero.DB.valueQueryAsync(
"SELECT version FROM fulltextItems WHERE itemID=?", itemID
)
});
};
this.setItemSynced = function (itemID, version) {
@ -236,17 +236,17 @@ Zotero.Fulltext = Zotero.FullText = new function(){
* @param {Array<string>} words
* @return {Promise}
*/
var indexWords = Zotero.Promise.coroutine(function* (itemID, words, stats, version, synced) {
var indexWords = async function (itemID, words, stats, version, synced) {
Zotero.DB.requireTransaction();
let chunk;
yield Zotero.DB.queryAsync("DELETE FROM indexing.fulltextWords");
await Zotero.DB.queryAsync("DELETE FROM indexing.fulltextWords");
while (words.length > 0) {
chunk = words.splice(0, 100);
yield Zotero.DB.queryAsync('INSERT INTO indexing.fulltextWords (word) ' + chunk.map(x => 'SELECT ?').join(' UNION '), chunk);
await Zotero.DB.queryAsync('INSERT INTO indexing.fulltextWords (word) ' + chunk.map(x => 'SELECT ?').join(' UNION '), chunk);
}
yield Zotero.DB.queryAsync('INSERT OR IGNORE INTO fulltextWords (word) SELECT word FROM indexing.fulltextWords');
yield Zotero.DB.queryAsync('DELETE FROM fulltextItemWords WHERE itemID = ?', [itemID]);
yield Zotero.DB.queryAsync('INSERT OR IGNORE INTO fulltextItemWords (wordID, itemID) SELECT wordID, ? FROM fulltextWords JOIN indexing.fulltextWords USING(word)', [itemID]);
await Zotero.DB.queryAsync('INSERT OR IGNORE INTO fulltextWords (word) SELECT word FROM indexing.fulltextWords');
await Zotero.DB.queryAsync('DELETE FROM fulltextItemWords WHERE itemID = ?', [itemID]);
await Zotero.DB.queryAsync('INSERT OR IGNORE INTO fulltextItemWords (wordID, itemID) SELECT wordID, ? FROM fulltextWords JOIN indexing.fulltextWords USING(word)', [itemID]);
var cols = ['itemID', 'version', 'synced'];
var params = [
@ -262,16 +262,16 @@ Zotero.Fulltext = Zotero.FullText = new function(){
}
var sql = `REPLACE INTO fulltextItems (${cols.join(', ')}) `
+ `VALUES (${cols.map(_ => '?').join(', ')})`;
yield Zotero.DB.queryAsync(sql, params);
await Zotero.DB.queryAsync(sql, params);
yield Zotero.DB.queryAsync("DELETE FROM indexing.fulltextWords");
});
await Zotero.DB.queryAsync("DELETE FROM indexing.fulltextWords");
};
/**
* @return {Promise}
*/
var indexString = Zotero.Promise.coroutine(function* (text, itemID, stats, version, synced) {
var indexString = async function (text, itemID, stats, version, synced) {
if (itemID != parseInt(itemID)) {
throw new Error("itemID not provided");
}
@ -279,10 +279,10 @@ Zotero.Fulltext = Zotero.FullText = new function(){
var words = this.semanticSplitter(text);
while (Zotero.DB.inTransaction()) {
yield Zotero.DB.waitForTransaction('indexString()');
await Zotero.DB.waitForTransaction('indexString()');
}
yield Zotero.DB.executeTransaction(async function () {
await Zotero.DB.executeTransaction(async function () {
this.clearItemWords(itemID, true);
await indexWords(itemID, words, stats, version, synced);
@ -296,12 +296,12 @@ Zotero.Fulltext = Zotero.FullText = new function(){
}.bind(this));
// If there's a processor cache file, delete it (whether or not we just used it)
var item = yield Zotero.Items.getAsync(itemID);
var item = await Zotero.Items.getAsync(itemID);
var cacheFile = this.getItemProcessorCacheFile(item);
if (cacheFile.exists()) {
cacheFile.remove(false);
}
}.bind(this));
}.bind(this);
/**
@ -309,7 +309,7 @@ Zotero.Fulltext = Zotero.FullText = new function(){
* @param {Number} itemID
* @return {Promise}
*/
this.indexDocument = Zotero.Promise.coroutine(function* (document, itemID) {
this.indexDocument = async function (document, itemID) {
if (!itemID){
throw ('Item ID not provided to indexDocument()');
}
@ -339,7 +339,7 @@ Zotero.Fulltext = Zotero.FullText = new function(){
var totalChars = text.length;
var item = Zotero.Items.get(itemID);
if (document.contentType == 'text/html') {
yield writeCacheFile(item, text, maxLength);
await writeCacheFile(item, text, maxLength);
}
if (totalChars > maxLength) {
@ -347,12 +347,12 @@ Zotero.Fulltext = Zotero.FullText = new function(){
+ itemID + ' in indexDocument()');
}
yield indexString(
await indexString(
text,
itemID,
{ indexedChars: text.length, totalChars }
);
});
};
/**
@ -511,7 +511,7 @@ Zotero.Fulltext = Zotero.FullText = new function(){
var indexItem = async function (item, path, complete) {
if (!await OS.File.exists(path)) {
if (!(await OS.File.exists(path))) {
Zotero.debug(`${path} does not exist in indexItem()`, 2);
return false;
}
@ -665,7 +665,7 @@ Zotero.Fulltext = Zotero.FullText = new function(){
* @param {Integer} [options.lastItemID] - Only return content for items above this id
* @return {Promise<Array<Object>>}
*/
this.getUnsyncedContent = Zotero.Promise.coroutine(function* (libraryID, options = {}) {
this.getUnsyncedContent = async function (libraryID, options = {}) {
var contentItems = [];
var sql = "SELECT itemID, indexedChars, totalChars, indexedPages, totalPages "
+ "FROM fulltextItems FI JOIN items I USING (itemID) WHERE libraryID=? AND "
@ -676,22 +676,22 @@ Zotero.Fulltext = Zotero.FullText = new function(){
params.push(options.lastItemID);
}
sql += "ORDER BY itemID";
var rows = yield Zotero.DB.queryAsync(sql, params);
var rows = await Zotero.DB.queryAsync(sql, params);
var contentSize = 0;
for (let i = 0; i < rows.length; i++) {
let row = rows[i];
let content;
let itemID = row.itemID;
let item = yield Zotero.Items.getAsync(itemID);
let item = await Zotero.Items.getAsync(itemID);
let libraryKey = item.libraryKey;
let contentType = item.attachmentContentType;
if (contentType && (this.isCachedMIMEType(contentType) || Zotero.MIME.isTextType(contentType))) {
try {
let cacheFile = this.getItemCacheFile(item).path;
if (yield OS.File.exists(cacheFile)) {
if (await OS.File.exists(cacheFile)) {
Zotero.debug("Getting full-text content from cache "
+ "file for item " + libraryKey);
content = yield Zotero.File.getContentsAsync(cacheFile);
content = await Zotero.File.getContentsAsync(cacheFile);
}
else {
// If a cache file is required, mark the full text as missing
@ -699,22 +699,22 @@ Zotero.Fulltext = Zotero.FullText = new function(){
Zotero.debug("Full-text content cache file doesn't exist for item "
+ libraryKey, 2);
let sql = "UPDATE fulltextItems SET synced=? WHERE itemID=?";
yield Zotero.DB.queryAsync(sql, [this.SYNC_STATE_MISSING, item.id]);
await Zotero.DB.queryAsync(sql, [this.SYNC_STATE_MISSING, item.id]);
continue;
}
// Same for missing attachments
let path = yield item.getFilePathAsync();
let path = await item.getFilePathAsync();
if (!path) {
Zotero.debug("File doesn't exist getting full-text content for item "
+ libraryKey, 2);
let sql = "UPDATE fulltextItems SET synced=? WHERE itemID=?";
yield Zotero.DB.queryAsync(sql, [this.SYNC_STATE_MISSING, item.id]);
await Zotero.DB.queryAsync(sql, [this.SYNC_STATE_MISSING, item.id]);
continue;
}
Zotero.debug("Getting full-text content from file for item " + libraryKey);
content = yield Zotero.File.getContentsAsync(path, item.attachmentCharset);
content = await Zotero.File.getContentsAsync(path, item.attachmentCharset);
// Include only as many characters as we've indexed
content = content.substr(0, row.indexedChars);
@ -730,7 +730,7 @@ Zotero.Fulltext = Zotero.FullText = new function(){
+ `${libraryKey} (contentType: ${contentType})`, 2);
// Delete rows for items that weren't supposed to be indexed
yield Zotero.DB.executeTransaction(async function () {
await Zotero.DB.executeTransaction(async function () {
await this.clearItemWords(itemID);
}.bind(this));
continue;
@ -757,30 +757,30 @@ Zotero.Fulltext = Zotero.FullText = new function(){
contentSize += content.length;
}
return contentItems;
});
};
/**
* @return {String} PHP-formatted POST data for items not yet downloaded
*/
this.getUndownloadedPostData = Zotero.Promise.coroutine(function* () {
this.getUndownloadedPostData = async function () {
// TODO: Redo for API syncing
// On upgrade, get all content
var sql = "SELECT value FROM settings WHERE setting='fulltext' AND key='downloadAll'";
if (yield Zotero.DB.valueQueryAsync(sql)) {
if (await Zotero.DB.valueQueryAsync(sql)) {
return "&ftkeys=all";
}
var sql = "SELECT itemID FROM fulltextItems WHERE synced=" + this.SYNC_STATE_TO_DOWNLOAD;
var itemIDs = yield Zotero.DB.columnQueryAsync(sql);
var itemIDs = await Zotero.DB.columnQueryAsync(sql);
if (!itemIDs) {
return "";
}
var undownloaded = {};
for (let i=0; i<itemIDs.length; i++) {
let itemID = itemIDs[i];
let item = yield Zotero.Items.getAsync(itemID);
let item = await Zotero.Items.getAsync(itemID);
let libraryID = item.libraryID
if (!undownloaded[libraryID]) {
undownloaded[libraryID] = [];
@ -795,7 +795,7 @@ Zotero.Fulltext = Zotero.FullText = new function(){
}
}
return data;
});
};
/**
@ -812,7 +812,7 @@ Zotero.Fulltext = Zotero.FullText = new function(){
* @param {Integer} version
* @return {Promise}
*/
this.setItemContent = Zotero.Promise.coroutine(function* (libraryID, key, data, version) {
this.setItemContent = async function (libraryID, key, data, version) {
var libraryKey = libraryID + "/" + key;
var item = Zotero.Items.getByLibraryAndKey(libraryID, key);
if (!item) {
@ -821,21 +821,21 @@ Zotero.Fulltext = Zotero.FullText = new function(){
return;
}
var itemID = item.id;
var currentVersion = yield this.getItemVersion(itemID)
var currentVersion = await this.getItemVersion(itemID)
var processorCacheFile = this.getItemProcessorCacheFile(item).path; // .zotero-ft-unprocessed
var itemCacheFile = this.getItemCacheFile(item).path; // .zotero-ft-cache
// If a storage directory doesn't exist, create it
if (!(yield OS.File.exists(PathUtils.parent(processorCacheFile)))) {
yield Zotero.Attachments.createDirectoryForItem(item);
if (!((await OS.File.exists(PathUtils.parent(processorCacheFile))))) {
await Zotero.Attachments.createDirectoryForItem(item);
}
// If indexed previously and the existing extracted text matches the new text,
// just update the version
if (currentVersion !== false
&& (yield OS.File.exists(itemCacheFile))
&& (yield Zotero.File.getContentsAsync(itemCacheFile)) == data.content) {
&& ((await OS.File.exists(itemCacheFile)))
&& ((await Zotero.File.getContentsAsync(itemCacheFile))) == data.content) {
Zotero.debug("Current full-text content matches remote for item "
+ libraryKey + " -- updating version");
return Zotero.DB.queryAsync(
@ -847,7 +847,7 @@ Zotero.Fulltext = Zotero.FullText = new function(){
// Otherwise save data to -unprocessed file
Zotero.debug("Writing full-text content and data for item " + libraryKey
+ " to " + processorCacheFile);
yield Zotero.File.putContentsAsync(processorCacheFile, JSON.stringify({
await Zotero.File.putContentsAsync(processorCacheFile, JSON.stringify({
indexedChars: data.indexedChars,
totalChars: data.totalChars,
indexedPages: data.indexedPages,
@ -858,18 +858,18 @@ Zotero.Fulltext = Zotero.FullText = new function(){
var synced = this.SYNC_STATE_TO_PROCESS;
// If indexed previously, update the sync state
if (currentVersion !== false) {
yield Zotero.DB.queryAsync("UPDATE fulltextItems SET synced=? WHERE itemID=?", [synced, itemID]);
await Zotero.DB.queryAsync("UPDATE fulltextItems SET synced=? WHERE itemID=?", [synced, itemID]);
}
// If not yet indexed, add an empty row
else {
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
"REPLACE INTO fulltextItems (itemID, version, synced) VALUES (?, 0, ?)",
[itemID, synced]
);
}
this.registerContentProcessor();
});
};
/**
@ -923,7 +923,7 @@ Zotero.Fulltext = Zotero.FullText = new function(){
* to find unprocessed content
* @return {Boolean} TRUE if there's more content to process; FALSE otherwise
*/
this.processUnprocessedContent = Zotero.Promise.coroutine(function* (itemIDs) {
this.processUnprocessedContent = async function (itemIDs) {
// Idle observer can take a little while to trigger and may not cancel the setTimeout()
// in time, so check idle time directly
var idleService = Components.classes["@mozilla.org/widget/useridleservice;1"]
@ -935,7 +935,7 @@ Zotero.Fulltext = Zotero.FullText = new function(){
if (!itemIDs) {
Zotero.debug("Checking for unprocessed full-text content");
let sql = "SELECT itemID FROM fulltextItems WHERE synced=" + this.SYNC_STATE_TO_PROCESS;
itemIDs = yield Zotero.DB.columnQueryAsync(sql);
itemIDs = await Zotero.DB.columnQueryAsync(sql);
}
var origLen = itemIDs.length;
@ -956,11 +956,11 @@ Zotero.Fulltext = Zotero.FullText = new function(){
}
let itemID = itemIDs.shift();
let item = yield Zotero.Items.getAsync(itemID);
let item = await Zotero.Items.getAsync(itemID);
Zotero.debug("Processing full-text content for item " + item.libraryKey);
yield Zotero.Fulltext.indexFromProcessorCache(itemID);
await Zotero.Fulltext.indexFromProcessorCache(itemID);
if (!itemIDs.length || idleService.idleTime < _idleObserverDelay * 1000) {
return;
@ -970,7 +970,7 @@ Zotero.Fulltext = Zotero.FullText = new function(){
// for processing to be interrupted if the user returns from idle. At least on macOS,
// when Zotero is in the background this can be throttled to 10 seconds.
_processorTimeoutID = setTimeout(() => this.processUnprocessedContent(itemIDs), 200);
});
};
this.idleObserver = {
observe: function (subject, topic, data) {
@ -990,29 +990,29 @@ Zotero.Fulltext = Zotero.FullText = new function(){
* @param {Number} itemID
* @return {Promise<Boolean>}
*/
this.indexFromProcessorCache = Zotero.Promise.coroutine(function* (itemID) {
this.indexFromProcessorCache = async function (itemID) {
try {
var item = yield Zotero.Items.getAsync(itemID);
var item = await Zotero.Items.getAsync(itemID);
var cacheFile = this.getItemProcessorCacheFile(item).path;
if (!(yield OS.File.exists(cacheFile))) {
if (!((await OS.File.exists(cacheFile)))) {
Zotero.debug("Full-text content processor cache file doesn't exist for item " + itemID);
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
"UPDATE fulltextItems SET synced=? WHERE itemID=?",
[this.SYNC_STATE_UNSYNCED, itemID]
);
return false;
}
var json = yield Zotero.File.getContentsAsync(cacheFile);
var json = await Zotero.File.getContentsAsync(cacheFile);
var data = JSON.parse(json);
// Write the text content to the regular cache file
var item = yield Zotero.Items.getAsync(itemID);
var item = await Zotero.Items.getAsync(itemID);
cacheFile = this.getItemCacheFile(item).path;
Zotero.debug("Writing full-text content to " + cacheFile);
yield Zotero.File.putContentsAsync(cacheFile, data.text);
await Zotero.File.putContentsAsync(cacheFile, data.text);
yield indexString(
await indexString(
data.text,
itemID,
{
@ -1031,7 +1031,7 @@ Zotero.Fulltext = Zotero.FullText = new function(){
Zotero.logError(e);
return false;
};
});
};
//
// End full-text content syncing
@ -1115,12 +1115,12 @@ Zotero.Fulltext = Zotero.FullText = new function(){
* @return {Promise<Array<Object>>} A promise for an array of match objects, with 'id' containing
* an itemID and 'match' containing a string snippet
*/
this.findTextInItems = Zotero.Promise.coroutine(function* (items, searchText, mode){
this.findTextInItems = async function (items, searchText, mode) {
if (!searchText){
return [];
}
var items = yield Zotero.Items.getAsync(items);
var items = await Zotero.Items.getAsync(items);
var found = [];
for (let i=0; i<items.length; i++) {
@ -1137,7 +1137,7 @@ Zotero.Fulltext = Zotero.FullText = new function(){
if (this.isCachedMIMEType(mimeType)) {
let file = this.getItemCacheFile(item).path;
if (!(yield OS.File.exists(file))) {
if (!((await OS.File.exists(file)))) {
Zotero.debug("No cache file at " + file, 2);
// TODO: Index on-demand?
// What about a cleared full-text index?
@ -1145,7 +1145,7 @@ Zotero.Fulltext = Zotero.FullText = new function(){
}
Zotero.debug("Searching for text '" + searchText + "' in " + file);
content = yield Zotero.File.getContentsAsync(file, 'utf-8', maxLength);
content = await Zotero.File.getContentsAsync(file, 'utf-8', maxLength);
}
else {
// If not binary mode, only scan plaintext files
@ -1156,13 +1156,13 @@ Zotero.Fulltext = Zotero.FullText = new function(){
}
}
let path = yield item.getFilePathAsync();
let path = await item.getFilePathAsync();
if (!path) {
continue;
}
Zotero.debug("Searching for text '" + searchText + "' in " + path);
content = yield Zotero.File.getContentsAsync(path, item.attachmentCharset, maxLength);
content = await Zotero.File.getContentsAsync(path, item.attachmentCharset, maxLength);
}
let match = findTextInString(content, searchText, mode);
@ -1175,7 +1175,7 @@ Zotero.Fulltext = Zotero.FullText = new function(){
}
return found;
});
};
this.transferItemIndex = async function (fromItem, toItem) {
@ -1214,14 +1214,14 @@ Zotero.Fulltext = Zotero.FullText = new function(){
/**
* @requireTransaction
*/
this.clearItemWords = Zotero.Promise.coroutine(function* (itemID, skipCacheClear) {
this.clearItemWords = async function (itemID, skipCacheClear) {
Zotero.DB.requireTransaction();
var sql = "SELECT rowid FROM fulltextItems WHERE itemID=? LIMIT 1";
var indexed = yield Zotero.DB.valueQueryAsync(sql, itemID);
var indexed = await Zotero.DB.valueQueryAsync(sql, itemID);
if (indexed) {
yield Zotero.DB.queryAsync("DELETE FROM fulltextItemWords WHERE itemID=?", itemID);
yield Zotero.DB.queryAsync("DELETE FROM fulltextItems WHERE itemID=?", itemID);
await Zotero.DB.queryAsync("DELETE FROM fulltextItemWords WHERE itemID=?", itemID);
await Zotero.DB.queryAsync("DELETE FROM fulltextItems WHERE itemID=?", itemID);
}
if (indexed) {
@ -1230,9 +1230,9 @@ Zotero.Fulltext = Zotero.FullText = new function(){
if (!skipCacheClear) {
// Delete fulltext cache file if there is one
yield clearCacheFile(itemID);
await clearCacheFile(itemID);
}
});
};
/**
@ -1260,29 +1260,29 @@ Zotero.Fulltext = Zotero.FullText = new function(){
*
* @return {Promise}
*/
var getTotalCharsFromFile = Zotero.Promise.coroutine(function* (itemID) {
var item = yield Zotero.Items.getAsync(itemID);
var getTotalCharsFromFile = async function (itemID) {
var item = await Zotero.Items.getAsync(itemID);
switch (item.attachmentContentType) {
case 'application/pdf':
var file = OS.Path.join(
Zotero.Attachments.getStorageDirectory(item).path,
this.fulltextCacheFile
);
if (!(yield OS.File.exists(file))) {
if (!((await OS.File.exists(file)))) {
return false;
}
break;
default:
var file = yield item.getFilePathAsync();
var file = await item.getFilePathAsync();
if (!file) {
return false;
}
}
var contents = yield Zotero.File.getContentsAsync(file);
var contents = await Zotero.File.getContentsAsync(file);
return contents.length;
});
};
/**
@ -1322,13 +1322,13 @@ Zotero.Fulltext = Zotero.FullText = new function(){
/*
* Gets the indexed state of an item,
*/
this.getIndexedState = Zotero.Promise.coroutine(function* (item) {
this.getIndexedState = async function (item) {
if (!item.isAttachment()) {
throw new Error('Item is not an attachment');
}
// If the file or cache file wasn't available during syncing, mark as unindexed
var synced = yield Zotero.DB.valueQueryAsync(
var synced = await Zotero.DB.valueQueryAsync(
"SELECT synced FROM fulltextItems WHERE itemID=?", item.id
);
if (synced === false || synced == this.SYNC_STATE_MISSING) {
@ -1340,7 +1340,7 @@ Zotero.Fulltext = Zotero.FullText = new function(){
switch (item.attachmentContentType) {
// Use pages for PDFs
case 'application/pdf':
var o = yield this.getPages(itemID);
var o = await this.getPages(itemID);
if (o) {
var stats = {
indexed: o.indexedPages,
@ -1350,7 +1350,7 @@ Zotero.Fulltext = Zotero.FullText = new function(){
break;
default:
var o = yield getChars(itemID);
var o = await getChars(itemID);
if (o) {
var stats = {
indexed: o.indexedChars,
@ -1363,7 +1363,7 @@ Zotero.Fulltext = Zotero.FullText = new function(){
if (!stats.total && !stats.indexed) {
let queued = false;
try {
queued = yield OS.File.exists(this.getItemProcessorCacheFile(item).path);
queued = await OS.File.exists(this.getItemProcessorCacheFile(item).path);
}
catch (e) {
Zotero.logError(e);
@ -1381,38 +1381,38 @@ Zotero.Fulltext = Zotero.FullText = new function(){
}
}
return state;
});
};
this.isFullyIndexed = Zotero.Promise.coroutine(function* (item) {
return (yield this.getIndexedState(item)) == this.INDEX_STATE_INDEXED;
});
this.isFullyIndexed = async function (item) {
return ((await this.getIndexedState(item))) == this.INDEX_STATE_INDEXED;
};
/**
* @return {Promise}
*/
this.getIndexStats = Zotero.Promise.coroutine(function* () {
this.getIndexStats = async function () {
var sql = "SELECT COUNT(*) FROM fulltextItems WHERE synced != ? AND "
+ "((indexedPages IS NOT NULL AND indexedPages=totalPages) OR "
+ "(indexedChars IS NOT NULL AND indexedChars=totalChars))"
var indexed = yield Zotero.DB.valueQueryAsync(sql, this.SYNC_STATE_MISSING);
var indexed = await Zotero.DB.valueQueryAsync(sql, this.SYNC_STATE_MISSING);
var sql = "SELECT COUNT(*) FROM fulltextItems WHERE "
+ "(indexedPages IS NOT NULL AND indexedPages<totalPages) OR "
+ "(indexedChars IS NOT NULL AND indexedChars<totalChars)"
var partial = yield Zotero.DB.valueQueryAsync(sql);
var partial = await Zotero.DB.valueQueryAsync(sql);
var sql = "SELECT COUNT(*) FROM itemAttachments WHERE itemID NOT IN "
+ "(SELECT itemID FROM fulltextItems WHERE synced != ? AND "
+ "(indexedPages IS NOT NULL OR indexedChars IS NOT NULL))";
var unindexed = yield Zotero.DB.valueQueryAsync(sql, this.SYNC_STATE_MISSING);
var unindexed = await Zotero.DB.valueQueryAsync(sql, this.SYNC_STATE_MISSING);
var sql = "SELECT COUNT(*) FROM fulltextWords";
var words = yield Zotero.DB.valueQueryAsync(sql);
var words = await Zotero.DB.valueQueryAsync(sql);
return { indexed, partial, unindexed, words };
});
};
this.getItemCacheFile = function (item) {
@ -1447,11 +1447,11 @@ Zotero.Fulltext = Zotero.FullText = new function(){
*
* Item must be a non-web-link attachment that isn't already fully indexed
*/
this.canReindex = Zotero.Promise.coroutine(function* (item) {
this.canReindex = async function (item) {
if (!this.canIndex(item)) {
return false;
}
switch (yield this.getIndexedState(item)) {
switch (await this.getIndexedState(item)) {
case this.INDEX_STATE_UNAVAILABLE:
case this.INDEX_STATE_UNINDEXED:
case this.INDEX_STATE_PARTIAL:
@ -1461,7 +1461,7 @@ Zotero.Fulltext = Zotero.FullText = new function(){
return true;
}
return false;
});
};
/**
@ -1541,8 +1541,8 @@ Zotero.Fulltext = Zotero.FullText = new function(){
/*
* Clears cache file for an item
*/
var clearCacheFile = Zotero.Promise.coroutine(function* (itemID) {
var item = yield Zotero.Items.getAsync(itemID);
var clearCacheFile = async function (itemID) {
var item = await Zotero.Items.getAsync(itemID);
if (!item) {
return;
}
@ -1562,22 +1562,22 @@ Zotero.Fulltext = Zotero.FullText = new function(){
Zotero.File.checkFileAccessError(e, cacheFile, 'delete');
}
}
});
};
/*
* Clear cache files for all attachments
*/
var clearCacheFiles = Zotero.Promise.coroutine(function* (skipLinkedURLs) {
var clearCacheFiles = async function (skipLinkedURLs) {
var sql = "SELECT itemID FROM itemAttachments";
if (skipLinkedURLs) {
sql += " WHERE linkMode != " + Zotero.Attachments.LINK_MODE_LINKED_URL;
}
var items = yield Zotero.DB.columnQueryAsync(sql);
var items = await Zotero.DB.columnQueryAsync(sql);
for (var i=0; i<items.length; i++) {
yield clearCacheFile(items[i]);
await clearCacheFile(items[i]);
}
});
};
/*
@ -1590,17 +1590,17 @@ Zotero.Fulltext = Zotero.FullText = new function(){
/**
* @return {Promise}
*/
this.purgeUnusedWords = Zotero.Promise.coroutine(function* () {
this.purgeUnusedWords = async function () {
if (!Zotero.Prefs.get('purge.fulltext')) {
return;
}
var sql = "DELETE FROM fulltextWords WHERE wordID NOT IN "
+ "(SELECT wordID FROM fulltextItemWords)";
yield Zotero.DB.queryAsync(sql);
await Zotero.DB.queryAsync(sql);
Zotero.Prefs.set('purge.fulltext', false)
});
};
async function getPageData(path, contentType) {
@ -1641,7 +1641,7 @@ Zotero.Fulltext = Zotero.FullText = new function(){
}
var cacheFile = this.getItemCacheFile(item).path;
Zotero.debug("Writing converted full-text content to " + cacheFile);
if (!await OS.File.exists(PathUtils.parent(cacheFile))) {
if (!(await OS.File.exists(PathUtils.parent(cacheFile)))) {
await Zotero.Attachments.createDirectoryForItem(item);
}
try {

View file

@ -23,7 +23,7 @@
***** END LICENSE BLOCK *****
*/
Zotero.History = new function(){
Zotero.History = new function () {
this.begin = begin;
this.setAssociatedID = setAssociatedID;
this.add = add;

View file

@ -2,7 +2,7 @@
* Functions for performing HTTP requests, both via XMLHTTPRequest and using a hidden browser
* @namespace
*/
Zotero.HTTP = new function() {
Zotero.HTTP = new function () {
this.disableErrorRetry = false;
var _errorDelayIntervals = [2500, 5000, 10000, 20000, 40000, 60000, 120000, 240000, 300000];
var _errorDelayMax = 60 * 60 * 1000; // 1 hour
@ -77,7 +77,7 @@ Zotero.HTTP = new function() {
* Exception returned if the browser is offline when promise* is used
* @constructor
*/
this.BrowserOfflineException = function() {
this.BrowserOfflineException = function () {
this.message = `Request could not be completed because ${Zotero.appName} is offline`;
this.stack = new Error().stack;
};
@ -89,7 +89,7 @@ Zotero.HTTP = new function() {
};
this.CancelledException.prototype = Object.create(Error.prototype);
this.TimeoutException = function(ms) {
this.TimeoutException = function (ms) {
this.message = "Request timed out" + (ms ? ` after ${ms} ms` : "");
this.stack = new Error().stack;
};
@ -166,7 +166,7 @@ Zotero.HTTP = new function() {
if (e.is5xx()) {
Zotero.logError(e);
// Check for Retry-After header on 503 and wait the specified amount of time
if (e.xmlhttp.status == 503 && await _checkRetry(e.xmlhttp)) {
if (e.xmlhttp.status == 503 && (await _checkRetry(e.xmlhttp))) {
continue;
}
// Don't retry if errorDelayMax is 0
@ -428,7 +428,7 @@ Zotero.HTTP = new function() {
if (requestTimeout) {
xmlhttp.timeout = requestTimeout;
xmlhttp.ontimeout = function() {
xmlhttp.ontimeout = function () {
deferred.reject(new Zotero.HTTP.TimeoutException(requestTimeout));
};
}
@ -457,7 +457,7 @@ Zotero.HTTP = new function() {
};
}
xmlhttp.onloadend = async function() {
xmlhttp.onloadend = async function () {
clearConnectTimer();
clearTimeout(inactivityTimerID);
@ -664,7 +664,7 @@ Zotero.HTTP = new function() {
* @param {String} path - Path to save file to
* @param {Object} [options] - See `Zotero.HTTP.request()`
*/
this.download = async function(uri, path, options = {}) {
this.download = async function (uri, path, options = {}) {
// TODO: Convert request() to fetch() and use ReadableStream
var req = await this.request(
'GET',
@ -701,7 +701,7 @@ Zotero.HTTP = new function() {
* false if the browser is offline
* @deprecated Use {@link Zotero.HTTP.request}
*/
this.doGet = function(url, onDone, responseCharset, cookieSandbox, requestHeaders) {
this.doGet = function (url, onDone, responseCharset, cookieSandbox, requestHeaders) {
if (url instanceof Components.interfaces.nsIURI) {
// Don't display password in console
var disp = this.getDisplayURI(url);
@ -743,7 +743,7 @@ Zotero.HTTP = new function() {
var useMethodjit = Components.utils.methodjit;
/** @ignore */
xmlhttp.onreadystatechange = function() {
xmlhttp.onreadystatechange = function () {
_stateChange(xmlhttp, onDone);
};
@ -766,7 +766,7 @@ Zotero.HTTP = new function() {
* false if the browser is offline
* @deprecated Use {@link Zotero.HTTP.request}
*/
this.doPost = function(url, body, onDone, headers, responseCharset, cookieSandbox) {
this.doPost = function (url, body, onDone, headers, responseCharset, cookieSandbox) {
if (url instanceof Components.interfaces.nsIURI) {
// Don't display password in console
var disp = this.getDisplayURI(url);
@ -826,7 +826,7 @@ Zotero.HTTP = new function() {
var useMethodjit = Components.utils.methodjit;
/** @ignore */
xmlhttp.onreadystatechange = function() {
xmlhttp.onreadystatechange = function () {
_stateChange(xmlhttp, onDone);
};
@ -847,7 +847,7 @@ Zotero.HTTP = new function() {
* false if the browser is offline
* @deprecated Use {@link Zotero.HTTP.request}
*/
this.doHead = function(url, onDone, requestHeaders, cookieSandbox) {
this.doHead = function (url, onDone, requestHeaders, cookieSandbox) {
if (url instanceof Components.interfaces.nsIURI) {
// Don't display password in console
var disp = this.getDisplayURI(url);
@ -885,7 +885,7 @@ Zotero.HTTP = new function() {
var useMethodjit = Components.utils.methodjit;
/** @ignore */
xmlhttp.onreadystatechange = function() {
xmlhttp.onreadystatechange = function () {
_stateChange(xmlhttp, onDone);
};
@ -919,7 +919,7 @@ Zotero.HTTP = new function() {
var useMethodjit = Components.utils.methodjit;
/** @ignore */
xmlhttp.onreadystatechange = function() {
xmlhttp.onreadystatechange = function () {
_stateChange(xmlhttp, callback);
};
xmlhttp.send(null);
@ -1097,13 +1097,14 @@ Zotero.HTTP = new function() {
this.triggerProxyAuth = function () {
if (!Zotero.Prefs.get("triggerProxyAuthentication")
|| Zotero.HTTP.browserIsOffline()) {
Zotero.proxyAuthComplete = Zotero.Promise.resolve();
Zotero.proxyAuthComplete = Promise.resolve();
return false;
}
var deferred = Zotero.Promise.defer();
Zotero.proxyAuthComplete = deferred.promise;
// FIXME: fx140: replace call to Zotero.Promise.try()
Zotero.Promise.try(function () {
var uris = Zotero.Prefs.get('proxyAuthenticationURLs').split(',');
uris = Zotero.Utilities.arrayShuffle(uris);
@ -1119,7 +1120,8 @@ Zotero.HTTP = new function() {
// For non-Zotero URLs, wait for PAC initialization,
// in a rather ugly and inefficient manner
if (i == 1) {
let installed = yield Zotero.Promise.try(_pacInstalled)
let installed = yield // FIXME: fx140: replace call to Zotero.Promise.try()
Zotero.Promise.try(_pacInstalled)
.then(function (installed) {
if (installed) throw true;
})
@ -1214,7 +1216,7 @@ Zotero.HTTP = new function() {
Components.interfaces.nsIProtocolProxyCallback,
Components.interfaces.nsISupports
];
if (!interfaces.some(function(v) { return iid.equals(v) })) {
if (!interfaces.some(function (v) { return iid.equals(v) })) {
throw Components.results.NS_ERROR_NO_INTERFACE;
}
return this;
@ -1277,7 +1279,7 @@ Zotero.HTTP = new function() {
*
* @type Boolean
*/
this.browserIsOffline = function() {
this.browserIsOffline = function () {
return Services.io.offline;
}
@ -1469,7 +1471,7 @@ Zotero.HTTP = new function() {
* Mimics the window.location/document.location interface, given an nsIURL
* @param {nsIURL} url
*/
this.Location = function(url) {
this.Location = function (url) {
this._url = url;
this.hash = url.ref ? "#"+url.ref : "";
this.host = url.hostPort;
@ -1481,7 +1483,7 @@ Zotero.HTTP = new function() {
this.search = url.query ? "?"+url.query : "";
};
this.Location.prototype = {
"toString":function() {
"toString":function () {
return this.href;
},
"__exposedProps__":{
@ -1501,7 +1503,7 @@ Zotero.HTTP = new function() {
* Mimics an HTMLWindow given an nsIURL
* @param {nsIURL} url
*/
this.Window = function(url) {
this.Window = function (url) {
this._url = url;
this.top = this;
this.location = Zotero.HTTP.Location(url);
@ -1517,7 +1519,7 @@ Zotero.HTTP = new function() {
* @param {HTMLDocument} doc Document returned by
* @param {nsIURL|String} url
*/
this.wrapDocument = function(doc, url) {
this.wrapDocument = function (doc, url) {
if(typeof url !== "object") {
url = Services.io.newURI(url, null, null).QueryInterface(Components.interfaces.nsIURL);
}

View file

@ -30,8 +30,8 @@
*/
Zotero.HTTPIntegrationClient = {
deferredResponse: null,
sendCommandPromise: Zotero.Promise.resolve(),
sendCommand: async function(command, args=[]) {
sendCommandPromise: Promise.resolve(),
sendCommand: async function (command, args=[]) {
let payload = JSON.stringify({command, arguments: args});
function sendCommand() {
Zotero.HTTPIntegrationClient.deferredResponse = Zotero.Promise.defer();
@ -54,7 +54,7 @@ Zotero.HTTPIntegrationClient = {
}
};
Zotero.HTTPIntegrationClient.Application = function() {
Zotero.HTTPIntegrationClient.Application = function () {
this.primaryFieldType = "Http";
this.secondaryFieldType = "Http";
this.outputFormat = 'html';
@ -65,7 +65,7 @@ Zotero.HTTPIntegrationClient.Application = function() {
this.processorName = "HTTP Integration";
};
Zotero.HTTPIntegrationClient.Application.prototype = {
getActiveDocument: async function() {
getActiveDocument: async function () {
let result = await Zotero.HTTPIntegrationClient.sendCommand('Application.getActiveDocument');
this.outputFormat = result.outputFormat || this.outputFormat;
this.supportedNotes = result.supportedNotes || this.supportedNotes;
@ -80,21 +80,21 @@ Zotero.HTTPIntegrationClient.Application.prototype = {
/**
* See integrationTests.js
*/
Zotero.HTTPIntegrationClient.Document = function(documentID, processorName) {
Zotero.HTTPIntegrationClient.Document = function (documentID, processorName) {
this._documentID = documentID;
this.processorName = processorName;
};
for (let method of ["activate", "canInsertField", "displayAlert", "getDocumentData",
"setDocumentData", "setBibliographyStyle", "importDocument", "exportDocument",
"insertText"]) {
Zotero.HTTPIntegrationClient.Document.prototype[method] = async function() {
Zotero.HTTPIntegrationClient.Document.prototype[method] = async function () {
return Zotero.HTTPIntegrationClient.sendCommand("Document."+method,
[this._documentID].concat(Array.prototype.slice.call(arguments)));
};
}
// @NOTE Currently unused, prompts are done using the connector
Zotero.HTTPIntegrationClient.Document.prototype._displayAlert = async function(dialogText, icon, buttons) {
Zotero.HTTPIntegrationClient.Document.prototype._displayAlert = async function (dialogText, icon, buttons) {
var ps = Services.prompt;
var buttonFlags = (ps.BUTTON_POS_0) * (ps.BUTTON_TITLE_OK)
+ (ps.BUTTON_POS_1) * (ps.BUTTON_TITLE_IS_STRING);
@ -134,29 +134,29 @@ Zotero.HTTPIntegrationClient.Document.prototype._displayAlert = async function(d
await this.activate();
return result;
}
Zotero.HTTPIntegrationClient.Document.prototype.cleanup = async function() {};
Zotero.HTTPIntegrationClient.Document.prototype.cursorInField = async function(fieldType) {
Zotero.HTTPIntegrationClient.Document.prototype.cleanup = async function () {};
Zotero.HTTPIntegrationClient.Document.prototype.cursorInField = async function (fieldType) {
var retVal = await Zotero.HTTPIntegrationClient.sendCommand("Document.cursorInField", [this._documentID, fieldType]);
if (!retVal) return null;
return new Zotero.HTTPIntegrationClient.Field(this._documentID, retVal);
};
Zotero.HTTPIntegrationClient.Document.prototype.insertField = async function(fieldType, noteType) {
Zotero.HTTPIntegrationClient.Document.prototype.insertField = async function (fieldType, noteType) {
var retVal = await Zotero.HTTPIntegrationClient.sendCommand("Document.insertField", [this._documentID, fieldType, parseInt(noteType) || 0]);
return new Zotero.HTTPIntegrationClient.Field(this._documentID, retVal);
};
Zotero.HTTPIntegrationClient.Document.prototype.getFields = async function(fieldType) {
Zotero.HTTPIntegrationClient.Document.prototype.getFields = async function (fieldType) {
var retVal = await Zotero.HTTPIntegrationClient.sendCommand("Document.getFields", [this._documentID, fieldType]);
return retVal.map(field => new Zotero.HTTPIntegrationClient.Field(this._documentID, field));
};
Zotero.HTTPIntegrationClient.Document.prototype.convert = async function(fields, fieldType, noteTypes) {
Zotero.HTTPIntegrationClient.Document.prototype.convert = async function (fields, fieldType, noteTypes) {
fields = fields.map((f) => f._id);
await Zotero.HTTPIntegrationClient.sendCommand("Document.convert", [this._documentID, fields, fieldType, noteTypes]);
};
Zotero.HTTPIntegrationClient.Document.prototype.convertPlaceholdersToFields = async function(codes, placeholderIDs, noteType) {
Zotero.HTTPIntegrationClient.Document.prototype.convertPlaceholdersToFields = async function (codes, placeholderIDs, noteType) {
var retVal = await Zotero.HTTPIntegrationClient.sendCommand("Document.convertPlaceholdersToFields", [this._documentID, codes, placeholderIDs, noteType]);
return retVal.map(field => new Zotero.HTTPIntegrationClient.Field(this._documentID, field));
}
Zotero.HTTPIntegrationClient.Document.prototype.complete = async function() {
Zotero.HTTPIntegrationClient.Document.prototype.complete = async function () {
Zotero.HTTPIntegrationClient.inProgress = false;
Zotero.HTTPIntegrationClient.sendCommand("Document.complete", [this._documentID]);
};
@ -164,7 +164,7 @@ Zotero.HTTPIntegrationClient.Document.prototype.complete = async function() {
/**
* See integrationTests.js
*/
Zotero.HTTPIntegrationClient.Field = function(documentID, json) {
Zotero.HTTPIntegrationClient.Field = function (documentID, json) {
this._documentID = documentID;
this._id = json.id;
this._code = json.code;
@ -178,15 +178,15 @@ Zotero.HTTPIntegrationClient.Field = function(documentID, json) {
Zotero.HTTPIntegrationClient.Field.prototype = {};
for (let method of ["delete", "select", "removeCode"]) {
Zotero.HTTPIntegrationClient.Field.prototype[method] = async function() {
Zotero.HTTPIntegrationClient.Field.prototype[method] = async function () {
return Zotero.HTTPIntegrationClient.sendCommand("Field."+method,
[this._documentID, this._id].concat(Array.prototype.slice.call(arguments)));
};
}
Zotero.HTTPIntegrationClient.Field.prototype.getText = async function() {
Zotero.HTTPIntegrationClient.Field.prototype.getText = async function () {
return this._text;
};
Zotero.HTTPIntegrationClient.Field.prototype.setText = async function(text, isRich) {
Zotero.HTTPIntegrationClient.Field.prototype.setText = async function (text, isRich) {
// The HTML will be stripped by Google Docs and and since we're
// caching this value, we need to strip it ourselves
var parser = new DOMParser();
@ -194,19 +194,19 @@ Zotero.HTTPIntegrationClient.Field.prototype.setText = async function(text, isRi
this._text = doc.documentElement.textContent;
return Zotero.HTTPIntegrationClient.sendCommand("Field.setText", [this._documentID, this._id, text, true]);
};
Zotero.HTTPIntegrationClient.Field.prototype.getCode = async function() {
Zotero.HTTPIntegrationClient.Field.prototype.getCode = async function () {
return this._code;
};
Zotero.HTTPIntegrationClient.Field.prototype.setCode = async function(code) {
Zotero.HTTPIntegrationClient.Field.prototype.setCode = async function (code) {
this._code = code;
return Zotero.HTTPIntegrationClient.sendCommand("Field.setCode", [this._documentID, this._id, code]);
};
Zotero.HTTPIntegrationClient.Field.prototype.getNoteIndex = async function() {
Zotero.HTTPIntegrationClient.Field.prototype.getNoteIndex = async function () {
return this._noteIndex;
};
Zotero.HTTPIntegrationClient.Field.prototype.equals = async function(arg) {
Zotero.HTTPIntegrationClient.Field.prototype.equals = async function (arg) {
return this._id === arg._id;
};
Zotero.HTTPIntegrationClient.Field.prototype._isAdjacentToNextField = async function() {
Zotero.HTTPIntegrationClient.Field.prototype._isAdjacentToNextField = async function () {
return this._adjacent;
}

View file

@ -42,11 +42,11 @@ Zotero.ID_Tracker = function () {
var _nextIDs = {};
this.init = Zotero.Promise.coroutine(function* () {
this.init = async function () {
for (let table of _tables) {
_nextIDs[table] = yield _getNext(table);
_nextIDs[table] = await _getNext(table);
}
});
};
/**

View file

@ -78,11 +78,11 @@ const PLUGIN_PATHS = {
};
Zotero.Integration = new function() {
Zotero.Integration = new function () {
Components.utils.import("resource://gre/modules/AddonManager.jsm");
this.currentWindow = false;
this.currentCommandPromise = Zotero.Promise.resolve();
this.currentCommandPromise = Promise.resolve();
this.sessions = {};
var upgradeTemplateNotNowTime = 0;
@ -115,7 +115,7 @@ Zotero.Integration = new function() {
* @param {Function} callback The callback to call on pipe read
*/
this.initPipe = function (pipe, callback) {
Zotero.IPC.Pipe.initPipeListener(pipe, function(string) {
Zotero.IPC.Pipe.initPipeListener(pipe, function (string) {
if(string != "") {
if (typeof callback == 'function') callback(string);
// exec command if possible
@ -136,7 +136,7 @@ Zotero.Integration = new function() {
/**
* Deletes a defunct pipe on OS X
*/
this.deletePipe = function(pipe) {
this.deletePipe = function (pipe) {
try {
if(pipe.exists()) {
pipe.remove(false);
@ -220,12 +220,12 @@ Zotero.Integration = new function() {
return false;
};
this.resetSessionStyles = Zotero.Promise.coroutine(function* (){
this.resetSessionStyles = async function () {
for (let sessionID in Zotero.Integration.sessions) {
let session = Zotero.Integration.sessions[sessionID];
yield session.setData(session.data, true);
await session.setData(session.data, true);
}
});
};
this.getApplication = function (agent, command, docId) {
if (agent == 'http') {
@ -242,7 +242,7 @@ Zotero.Integration = new function() {
/**
* Executes an integration command, first checking to make sure that versions are compatible
*/
this.execCommand = async function(agent, command, docId, templateVersion=0) {
this.execCommand = async function (agent, command, docId, templateVersion=0) {
var document, session, documentImported;
Zotero.debug(`Integration: ${agent}-${command}${docId ? `:'${docId}'` : ''} invoked`)
if (Zotero.Integration.warnOutdatedTemplate(agent, templateVersion)) return;
@ -492,7 +492,7 @@ Zotero.Integration = new function() {
Zotero.Utilities.Internal.activate(window);
var deferred = Zotero.Promise.defer();
var listener = function() {
var listener = function () {
if(window.location.toString() === "about:blank") return;
if(window.newWindow) {
@ -601,7 +601,7 @@ Zotero.Integration = new function() {
/^https?:\/\/(www\.)?(zotero\.org|citationstyles\.org)/.test(data.style.styleID);
let errorString = Zotero.getString("integration.error.styleMissing", data.style.styleID);
if (trustedSource ||
await doc.displayAlert(errorString, DIALOG_ICON_WARNING, DIALOG_BUTTONS_YES_NO)) {
(await doc.displayAlert(errorString, DIALOG_ICON_WARNING, DIALOG_BUTTONS_YES_NO))) {
let installed = false;
try {
@ -649,7 +649,7 @@ Zotero.Integration = new function() {
}
Zotero.Integration.confirmExportDocument = function() {
Zotero.Integration.confirmExportDocument = function () {
const documentationURL = "https://www.zotero.org/support/kb/moving_documents_between_word_processors";
var ps = Services.prompt;
@ -677,11 +677,11 @@ Zotero.Integration.confirmExportDocument = function() {
/**
* An exception thrown when a document contains an item that no longer exists in the current document.
*/
Zotero.Integration.MissingItemException = function(item) {this.item = item;};
Zotero.Integration.MissingItemException = function (item) {this.item = item;};
Zotero.Integration.MissingItemException.prototype = {
"name":"MissingItemException",
"message":`An item in this document is missing from your Zotero library.}`,
"toString":function() { return this.message + `\n ${JSON.stringify(this.item)}` }
"toString":function () { return this.message + `\n ${JSON.stringify(this.item)}` }
};
Zotero.Integration.NO_ACTION = 0;
@ -693,7 +693,7 @@ Zotero.Integration.REMOVE_CODE = 3;
* All methods for interacting with a document
* @constructor
*/
Zotero.Integration.Interface = function(app, doc, session) {
Zotero.Integration.Interface = function (app, doc, session) {
this._app = app;
this._doc = doc;
this._session = session;
@ -721,15 +721,15 @@ Zotero.Integration.Interface.prototype.addCitation = async function () {
* Edits the citation at the cursor position.
* @return {Promise}
*/
Zotero.Integration.Interface.prototype.editCitation = Zotero.Promise.coroutine(function* () {
yield this._session.init(true, false);
var docField = yield this._doc.cursorInField(this._session.data.prefs['fieldType']);
Zotero.Integration.Interface.prototype.editCitation = async function () {
await this._session.init(true, false);
var docField = await this._doc.cursorInField(this._session.data.prefs['fieldType']);
if(!docField) {
throw new Zotero.Exception.Alert("integration.error.notInCitation", [],
"integration.error.title");
}
return this.addEditCitation(docField);
});
};
/**
* Edits the citation at the cursor position if one exists, or else adds a new one.
@ -737,7 +737,7 @@ Zotero.Integration.Interface.prototype.editCitation = Zotero.Promise.coroutine(f
*/
Zotero.Integration.Interface.prototype.addEditCitation = async function (docField) {
await this._session.init(false, false);
docField = docField || await this._doc.cursorInField(this._session.data.prefs['fieldType']);
docField = docField || (await this._doc.cursorInField(this._session.data.prefs['fieldType']));
let citations = await this._session.cite(docField);
if (this._session.data.prefs.delayCitationUpdates) {
@ -756,7 +756,7 @@ Zotero.Integration.Interface.prototype.addEditCitation = async function (docFiel
Zotero.Integration.Interface.prototype.addNote = async function () {
await this._session.init(false, false);
if ((!await this._doc.canInsertField(this._session.data.prefs['fieldType']))) {
if ((!(await this._doc.canInsertField(this._session.data.prefs['fieldType'])))) {
throw new Zotero.Exception.Alert("integration.error.cannotInsertHere", [],
"integration.error.title");
}
@ -776,39 +776,39 @@ Zotero.Integration.Interface.prototype.addNote = async function () {
* Adds a bibliography to the current document.
* @return {Promise}
*/
Zotero.Integration.Interface.prototype.addBibliography = Zotero.Promise.coroutine(function* () {
Zotero.Integration.Interface.prototype.addBibliography = async function () {
var me = this;
yield this._session.init(true, false);
await this._session.init(true, false);
// Make sure we can have a bibliography
if(!me._session.data.style.hasBibliography) {
throw new Zotero.Exception.Alert("integration.error.noBibliography", [],
"integration.error.title");
}
let field = new Zotero.Integration.BibliographyField(yield this._session.addField());
let field = new Zotero.Integration.BibliographyField(await this._session.addField());
var citationsMode = FORCE_CITATIONS_FALSE;
yield field.clearCode();
await field.clearCode();
if(this._session.data.prefs.delayCitationUpdates) {
// Refreshes citeproc state before proceeding
this._session.rebuildCiteprocState = true;
citationsMode = FORCE_CITATIONS_REGENERATE;
}
yield this._session.updateFromDocument(citationsMode);
yield this._session.updateDocument(citationsMode, true, false);
})
await this._session.updateFromDocument(citationsMode);
await this._session.updateDocument(citationsMode, true, false);
}
/**
* Edits bibliography metadata.
* @return {Promise}
*/
Zotero.Integration.Interface.prototype.editBibliography = Zotero.Promise.coroutine(function*() {
Zotero.Integration.Interface.prototype.editBibliography = async function () {
// Make sure we have a bibliography
yield this._session.init(true, false);
var fields = yield this._session.getFields();
await this._session.init(true, false);
var fields = await this._session.getFields();
var bibliographyField;
for (let i = fields.length-1; i >= 0; i--) {
let field = yield Zotero.Integration.Field.loadExisting(fields[i]);
let field = await Zotero.Integration.Field.loadExisting(fields[i]);
if (field.type == INTEGRATION_TYPE_BIBLIOGRAPHY) {
bibliographyField = field;
break;
@ -819,33 +819,33 @@ Zotero.Integration.Interface.prototype.editBibliography = Zotero.Promise.corouti
throw new Zotero.Exception.Alert("integration.error.mustInsertBibliography",
[], "integration.error.title");
}
let bibliography = new Zotero.Integration.Bibliography(bibliographyField, yield bibliographyField.unserialize());
let bibliography = new Zotero.Integration.Bibliography(bibliographyField, await bibliographyField.unserialize());
var citationsMode = FORCE_CITATIONS_FALSE;
if(this._session.data.prefs.delayCitationUpdates) {
// Refreshes citeproc state before proceeding
this._session.rebuildCiteprocState = true;
citationsMode = FORCE_CITATIONS_REGENERATE;
}
yield this._session.updateFromDocument(citationsMode);
yield this._session.editBibliography(bibliography);
yield this._session.updateDocument(citationsMode, true, false);
});
await this._session.updateFromDocument(citationsMode);
await this._session.editBibliography(bibliography);
await this._session.updateDocument(citationsMode, true, false);
};
Zotero.Integration.Interface.prototype.addEditBibliography = Zotero.Promise.coroutine(function *() {
Zotero.Integration.Interface.prototype.addEditBibliography = async function () {
// Check if we have a bibliography
yield this._session.init(true, false);
await this._session.init(true, false);
if (!this._session.data.style.hasBibliography) {
throw new Zotero.Exception.Alert("integration.error.noBibliography", [],
"integration.error.title");
}
var fields = yield this._session.getFields();
var fields = await this._session.getFields();
var bibliographyField;
for (let i = fields.length-1; i >= 0; i--) {
let field = yield Zotero.Integration.Field.loadExisting(fields[i]);
let field = await Zotero.Integration.Field.loadExisting(fields[i]);
if (field.type == INTEGRATION_TYPE_BIBLIOGRAPHY) {
bibliographyField = field;
break;
@ -854,23 +854,23 @@ Zotero.Integration.Interface.prototype.addEditBibliography = Zotero.Promise.coro
var newBibliography = !bibliographyField;
if (!bibliographyField) {
bibliographyField = new Zotero.Integration.BibliographyField(yield this._session.addField());
yield bibliographyField.clearCode();
bibliographyField = new Zotero.Integration.BibliographyField(await this._session.addField());
await bibliographyField.clearCode();
}
let bibliography = new Zotero.Integration.Bibliography(bibliographyField, yield bibliographyField.unserialize());
let bibliography = new Zotero.Integration.Bibliography(bibliographyField, await bibliographyField.unserialize());
var citationsMode = FORCE_CITATIONS_FALSE;
if(this._session.data.prefs.delayCitationUpdates) {
// Refreshes citeproc state before proceeding
this._session.rebuildCiteprocState = true;
citationsMode = FORCE_CITATIONS_REGENERATE;
}
yield this._session.updateFromDocument(citationsMode);
await this._session.updateFromDocument(citationsMode);
if (!newBibliography) {
yield this._session.editBibliography(bibliography);
await this._session.editBibliography(bibliography);
}
yield this._session.updateDocument(citationsMode, true, false);
});
await this._session.updateDocument(citationsMode, true, false);
};
Zotero.Integration.Interface.prototype.citationExplorer = async function () {
await this._session.init(true, false);
@ -891,7 +891,7 @@ Zotero.Integration.Interface.prototype.citationExplorer = async function () {
* Updates the citation data for all citations and bibliography entries.
* @return {Promise}
*/
Zotero.Integration.Interface.prototype.refresh = async function() {
Zotero.Integration.Interface.prototype.refresh = async function () {
await this._session.init(true, false);
this._session._shouldMerge = true;
@ -904,32 +904,32 @@ Zotero.Integration.Interface.prototype.refresh = async function() {
* Deletes field codes.
* @return {Promise}
*/
Zotero.Integration.Interface.prototype.removeCodes = Zotero.Promise.coroutine(function* () {
yield this._session.init(true, false)
let fields = yield this._session.getFields()
var result = yield this._doc.displayAlert(Zotero.getString("integration.removeCodesWarning"),
Zotero.Integration.Interface.prototype.removeCodes = async function () {
await this._session.init(true, false)
let fields = await this._session.getFields()
var result = await this._doc.displayAlert(Zotero.getString("integration.removeCodesWarning"),
DIALOG_ICON_WARNING, DIALOG_BUTTONS_OK_CANCEL);
if (result) {
for(var i=fields.length-1; i>=0; i--) {
yield fields[i].removeCode();
await fields[i].removeCode();
}
}
})
}
/**
* Displays a dialog to set document preferences (style, footnotes/endnotes, etc.)
* @return {Promise}
*/
Zotero.Integration.Interface.prototype.setDocPrefs = Zotero.Promise.coroutine(function* () {
Zotero.Integration.Interface.prototype.setDocPrefs = async function () {
var oldData;
let haveSession = yield this._session.init(false, true);
let haveSession = await this._session.init(false, true);
if(!haveSession) {
// This is a brand new document; don't try to get fields
oldData = yield this._session.setDocPrefs(true);
oldData = await this._session.setDocPrefs(true);
} else {
// Can get fields while dialog is open
oldData = yield Zotero.Promise.all([
oldData = await Promise.all([
this._session.getFields(),
this._session.setDocPrefs(true)
]).spread(function (fields, setDocPrefs) {
@ -943,7 +943,7 @@ Zotero.Integration.Interface.prototype.setDocPrefs = Zotero.Promise.coroutine(fu
if (!oldData) return false;
// Perform noteType or fieldType conversion
let fields = yield this._session.getFields();
let fields = await this._session.getFields();
const styleHasChanged = oldData.style.styleID != this._session.data.style.styleID;
var convertBibliographies = oldData.prefs.fieldType != this._session.data.prefs.fieldType;
@ -952,10 +952,10 @@ Zotero.Integration.Interface.prototype.setDocPrefs = Zotero.Promise.coroutine(fu
var fieldsToConvert = new Array();
var fieldNoteTypes = new Array();
for (var i=0, n=fields.length; i<n; i++) {
let field = yield Zotero.Integration.Field.loadExisting(fields[i]);
let field = await Zotero.Integration.Field.loadExisting(fields[i]);
if (convertItems && field.type === INTEGRATION_TYPE_ITEM) {
var citation = yield field.unserialize();
var citation = await field.unserialize();
if (!citation.properties.dontUpdate) {
fieldsToConvert.push(fields[i]);
fieldNoteTypes.push(this._session.data.prefs.noteType);
@ -969,7 +969,7 @@ Zotero.Integration.Interface.prototype.setDocPrefs = Zotero.Promise.coroutine(fu
if(fieldsToConvert.length) {
// Pass to conversion function
yield this._doc.convert(fieldsToConvert,
await this._doc.convert(fieldsToConvert,
this._session.data.prefs.fieldType, fieldNoteTypes,
fieldNoteTypes.length);
}
@ -980,9 +980,9 @@ Zotero.Integration.Interface.prototype.setDocPrefs = Zotero.Promise.coroutine(fu
if (this._session.data.prefs.delayCitationUpdates && !fieldsToConvert.length && !styleHasChanged) return;
yield this._session.updateFromDocument(FORCE_CITATIONS_RESET_TEXT);
await this._session.updateFromDocument(FORCE_CITATIONS_RESET_TEXT);
return this._session.updateDocument(FORCE_CITATIONS_RESET_TEXT, true, true);
});
};
/**
* Exports the citations in the document to a format importable in other word processors
@ -998,20 +998,20 @@ Zotero.Integration.Interface.prototype.exportDocument = async function () {
/**
* An exceedingly simple nsISimpleEnumerator implementation
*/
Zotero.Integration.JSEnumerator = function(objArray) {
Zotero.Integration.JSEnumerator = function (objArray) {
this.objArray = objArray;
}
Zotero.Integration.JSEnumerator.prototype.hasMoreElements = function() {
Zotero.Integration.JSEnumerator.prototype.hasMoreElements = function () {
return this.objArray.length;
}
Zotero.Integration.JSEnumerator.prototype.getNext = function() {
Zotero.Integration.JSEnumerator.prototype.getNext = function () {
return this.objArray.shift();
}
/**
* Keeps track of all session-specific variables
*/
Zotero.Integration.Session = function(doc, app) {
Zotero.Integration.Session = function (doc, app) {
this.embeddedItems = {};
this.embeddedZoteroItems = {};
this.embeddedItemsByURI = {};
@ -1052,19 +1052,19 @@ Zotero.Integration.Session = function(doc, app) {
* Checks that it is appropriate to add fields to the current document at the current
* position, then adds one.
*/
Zotero.Integration.Session.prototype.addField = async function(note, fieldIndex=-1) {
Zotero.Integration.Session.prototype.addField = async function (note, fieldIndex=-1) {
// Get citation types if necessary
if (!await this._doc.canInsertField(this.data.prefs['fieldType'])) {
return Zotero.Promise.reject(new Zotero.Exception.Alert("integration.error.cannotInsertHere",
if (!(await this._doc.canInsertField(this.data.prefs['fieldType']))) {
return Promise.reject(new Zotero.Exception.Alert("integration.error.cannotInsertHere",
[], "integration.error.title"));
}
var field = await this._doc.cursorInField(this.data.prefs['fieldType']);
if (field) {
if (!await this.displayAlert(Zotero.getString("integration.replace"),
if (!(await this.displayAlert(Zotero.getString("integration.replace"),
DIALOG_ICON_STOP,
DIALOG_BUTTONS_OK_CANCEL)) {
return Zotero.Promise.reject(new Zotero.Exception.UserCancelled("inserting citation"));
DIALOG_BUTTONS_OK_CANCEL))) {
return Promise.reject(new Zotero.Exception.UserCancelled("inserting citation"));
}
}
@ -1093,9 +1093,9 @@ Zotero.Integration.Session.prototype.addField = async function(note, fieldIndex=
* Gets all fields for a document
* @return {Promise} Promise resolved with field list.
*/
Zotero.Integration.Session.prototype.getFields = new function() {
Zotero.Integration.Session.prototype.getFields = new function () {
var deferred;
return async function(force=false) {
return async function (force=false) {
// If we already have fields, just return them
if(!force && this._fields != undefined) {
return this._fields;
@ -1131,11 +1131,11 @@ Zotero.Integration.Session.prototype.getFields = new function() {
/**
* Updates Zotero.Integration.Session citations from the session document
*/
Zotero.Integration.Session.prototype.updateFromDocument = Zotero.Promise.coroutine(function* (forceUpdateAllCitations) {
Zotero.Integration.Session.prototype.updateFromDocument = async function (forceUpdateAllCitations) {
if (this._transactionUpToDate) {
return;
}
yield this.getFields();
await this.getFields();
this.resetRequest(this._doc);
this._removeCodeFields = {};
@ -1152,9 +1152,9 @@ Zotero.Integration.Session.prototype.updateFromDocument = Zotero.Promise.corouti
this.rebuildCiteprocState = true;
}
}
yield this._processFields();
await this._processFields();
try {
yield this.handleRetractedItems();
await this.handleRetractedItems();
}
catch (e) {
Zotero.debug('Retracted item handling failed', 2);
@ -1172,7 +1172,7 @@ Zotero.Integration.Session.prototype.updateFromDocument = Zotero.Promise.corouti
this.rebuildCiteprocState = false;
}
this._sessionUpToDate = this._transactionUpToDate = true;
});
};
/**
* Keep processing fields until all have been processed
@ -1191,7 +1191,7 @@ Zotero.Integration.Session.prototype._processFields = async function () {
citation = new Zotero.Integration.Citation(field, data, noteIndex);
citation.fieldIndex = i;
if (this._shouldMerge && typeof field.isAdjacentToNextField === 'function' && await field.isAdjacentToNextField()) {
if (this._shouldMerge && typeof field.isAdjacentToNextField === 'function' && (await field.isAdjacentToNextField())) {
adjacentCitations.push(citation);
this._deleteFields[i] = true;
continue;
@ -1228,16 +1228,15 @@ Zotero.Integration.Session.prototype._processFields = async function () {
* modified since they were created, instead of showing a warning
* @return {Promise} A promise resolved when the document is updated
*/
Zotero.Integration.Session.prototype.updateDocument = Zotero.Promise.coroutine(function* (forceCitations, forceBibliography,
ignoreCitationChanges) {
Zotero.Integration.Session.prototype.updateDocument = async function (forceCitations, forceBibliography, ignoreCitationChanges) {
this.timer = new Zotero.Integration.Timer();
this.timer.start();
this.progressBar.start();
yield this._updateCitations();
await this._updateCitations();
this.progressBar.finishSegment();
this.progressBar.start();
yield this._updateDocument(forceCitations, forceBibliography, ignoreCitationChanges)
await this._updateDocument(forceCitations, forceBibliography, ignoreCitationChanges)
this.progressBar.finishSegment();
var diff = this.timer.stop();
@ -1245,14 +1244,14 @@ Zotero.Integration.Session.prototype.updateDocument = Zotero.Promise.coroutine(f
Zotero.debug(`Integration: updateDocument complete in ${diff}s`)
// If the update takes longer than 5s suggest delaying citation updates
if (diff > DELAY_CITATIONS_PROMPT_TIMEOUT && !this.data.prefs.dontAskDelayCitationUpdates && !this.data.prefs.delayCitationUpdates) {
yield this._doc.activate();
await this._doc.activate();
var interfaceType = 'tab';
if (['MacWord2008', 'OpenOffice'].includes(this.agent)) {
interfaceType = 'toolbar';
}
var result = yield this.displayAlert(
var result = await this.displayAlert(
Zotero.getString('integration.delayCitationUpdates.alert.text1')
+ "\n\n"
+ Zotero.getString(`integration.delayCitationUpdates.alert.text2.${interfaceType}`)
@ -1269,7 +1268,7 @@ Zotero.Integration.Session.prototype.updateDocument = Zotero.Promise.coroutine(f
// yield this.setDocPrefs(true);
}
}
});
};
/**
* Helper function to update bibliographys and fields within a document
@ -1278,7 +1277,7 @@ Zotero.Integration.Session.prototype.updateDocument = Zotero.Promise.coroutine(f
* @param {Boolean} [ignoreCitationChanges] Whether to ignore changes to citations that have been
* modified since they were created, instead of showing a warning
*/
Zotero.Integration.Session.prototype._updateDocument = async function(forceCitations, forceBibliography,
Zotero.Integration.Session.prototype._updateDocument = async function (forceCitations, forceBibliography,
ignoreCitationChanges) {
if(this.progressCallback) {
var nFieldUpdates = Object.keys(this.processIndices).length;
@ -1345,7 +1344,7 @@ Zotero.Integration.Session.prototype._updateDocument = async function(forceCitat
if (!citation.properties.dontUpdate) {
var formattedCitation = citation.properties.custom
? citation.properties.custom : citation.text;
var plainCitation = citation.properties.plainCitation && await citationField.getText();
var plainCitation = citation.properties.plainCitation && (await citationField.getText());
var plaintextChanged = citation.properties.plainCitation
&& plainCitation !== citation.properties.plainCitation;
@ -1510,8 +1509,8 @@ Zotero.Integration.Session.prototype.cite = async function (field, addNote=false
var fieldIndexPromise, citationsByItemIDPromise;
const citationDataLoadedFromDocument = Object.keys(this.citationsByItemID).length;
if (this.data.prefs.delayCitationUpdates && citationDataLoadedFromDocument) {
fieldIndexPromise = Zotero.Promise.resolve(-1);
citationsByItemIDPromise = Zotero.Promise.resolve(this.citationsByItemID);
fieldIndexPromise = Promise.resolve(-1);
citationsByItemIDPromise = Promise.resolve(this.citationsByItemID);
}
else {
fieldIndexPromise = this.getFields().then(async function (fields) {
@ -1721,7 +1720,7 @@ Zotero.Integration.Session.prototype._insertItemsIntoDocument = async function (
/**
* Citation editing functions and propertiesaccessible to citationDialog.js
*/
Zotero.Integration.CitationEditInterface = function(items, sortable, fieldIndexPromise,
Zotero.Integration.CitationEditInterface = function (items, sortable, fieldIndexPromise,
citationsByItemIDPromise, previewFn){
this.citation = items;
this.sortable = sortable;
@ -1736,7 +1735,7 @@ Zotero.Integration.CitationEditInterface = function(items, sortable, fieldIndexP
this.promise = this._acceptDeferred.promise;
// Resolve when all data needed to run getItems() or sort() is loaded
this.allCitedDataLoadedPromise = Zotero.Promise.all([fieldIndexPromise, citationsByItemIDPromise]);
this.allCitedDataLoadedPromise = Promise.all([fieldIndexPromise, citationsByItemIDPromise]);
}
Zotero.Integration.CitationEditInterface.prototype = {
@ -1744,7 +1743,7 @@ Zotero.Integration.CitationEditInterface.prototype = {
* Execute a callback with a preview of the given citation
* @return {Promise} A promise resolved with the previewed citation string
*/
preview: function() {
preview: function () {
return this.previewFn(this.citation);
},
@ -1752,7 +1751,7 @@ Zotero.Integration.CitationEditInterface.prototype = {
* Sort the citationItems within citation (depends on this.citation.properties.unsorted)
* @return {Promise} A promise resolved with the previewed citation string
*/
sort: function() {
sort: function () {
return this.preview();
},
@ -1761,7 +1760,7 @@ Zotero.Integration.CitationEditInterface.prototype = {
* @param {Function} [progressCallback] A callback to be run when progress has changed.
* Receives a number from 0 to 100 indicating current status.
*/
accept: function(progressCallback) {
accept: function (progressCallback) {
if (!this._acceptDeferred.promise.isFulfilled()) {
this._acceptDeferred.resolve(progressCallback);
}
@ -1791,7 +1790,7 @@ Zotero.Integration.CitationEditInterface.prototype = {
});
// Sort all previously cited items at top, and all items cited later at bottom
ids.sort(function(a, b) {
ids.sort(function (a, b) {
var indexA = citationsByItemID[a][0].properties.zoteroIndex,
indexB = citationsByItemID[b][0].properties.zoteroIndex;
@ -1811,7 +1810,7 @@ Zotero.Integration.CitationEditInterface.prototype = {
/**
* Resets per-request variables in the CitationSet
*/
Zotero.Integration.Session.prototype.resetRequest = function(doc) {
Zotero.Integration.Session.prototype.resetRequest = function (doc) {
this.uriMap = new Zotero.Integration.URIMap(this);
this.bibliographyHasChanged = false;
@ -1857,7 +1856,7 @@ Zotero.Integration.Session.prototype.resetRequest = function(doc) {
* @param dontRunSetDocPrefs {Boolean} Whether to show the Document Preferences window if no preferences exist
* @return {Promise{Boolean}} true if session ready to, false if preferences dialog needs to be displayed first
*/
Zotero.Integration.Session.prototype.init = Zotero.Promise.coroutine(function *(require, dontRunSetDocPrefs) {
Zotero.Integration.Session.prototype.init = async function (require, dontRunSetDocPrefs) {
var data = this.data;
var haveFields = false;
@ -1870,7 +1869,7 @@ Zotero.Integration.Session.prototype.init = Zotero.Promise.coroutine(function *(
if (require) {
// check to see if fields already exist
for (let fieldType of fieldTypes) {
var fields = yield this._doc.getFields(fieldType);
var fields = await this._doc.getFields(fieldType);
if (fields.length) {
haveFields = true;
break;
@ -1880,7 +1879,7 @@ Zotero.Integration.Session.prototype.init = Zotero.Promise.coroutine(function *(
if (require && !haveFields) {
// If required but no fields throw an error
return Zotero.Promise.reject(new Zotero.Exception.Alert(
return Promise.reject(new Zotero.Exception.Alert(
"integration.error.mustInsertCitation",
[], "integration.error.title"));
}
@ -1889,13 +1888,13 @@ Zotero.Integration.Session.prototype.init = Zotero.Promise.coroutine(function *(
if (dontRunSetDocPrefs) return false;
// Show the doc prefs dialogue
yield this.setDocPrefs();
await this.setDocPrefs();
}
return true;
});
};
Zotero.Integration.Session.prototype.displayAlert = async function() {
Zotero.Integration.Session.prototype.displayAlert = async function () {
if (this.timer) {
this.timer.pause();
}
@ -1949,7 +1948,7 @@ Zotero.Integration.Session.prototype.setData = async function (data, resetStyle)
* cancelled.
*/
Zotero.Integration.Session.prototype.setDocPrefs = async function (showImportExport=false) {
var io = new function() { this.wrappedJSObject = this; };
var io = new function () { this.wrappedJSObject = this; };
io.primaryFieldType = this.primaryFieldType;
io.secondaryFieldType = this.secondaryFieldType;
io.showImportExport = false;
@ -2015,7 +2014,7 @@ Zotero.Integration.Session.prototype.setDocPrefs = async function (showImportExp
return oldData || null;
}
Zotero.Integration.Session.prototype.exportDocument = async function() {
Zotero.Integration.Session.prototype.exportDocument = async function () {
Zotero.debug("Integration: Exporting the document");
var timer = new Zotero.Integration.Timer();
timer.start();
@ -2030,7 +2029,7 @@ Zotero.Integration.Session.prototype.exportDocument = async function() {
}
Zotero.Integration.Session.prototype.importDocument = async function() {
Zotero.Integration.Session.prototype.importDocument = async function () {
const documentationURL = "https://www.zotero.org/support/kb/moving_documents_between_word_processors";
var ps = Services.prompt;
@ -2166,7 +2165,7 @@ Zotero.Integration.Session.prototype.addCitation = async function (index, noteIn
this.documentCitationIDs[citation.citationID] = index;
};
Zotero.Integration.Session.prototype.getCiteprocLists = function() {
Zotero.Integration.Session.prototype.getCiteprocLists = function () {
var citations = [];
var fieldToCitationIdxMapping = {};
var citationToFieldIdxMapping = {};
@ -2282,7 +2281,7 @@ Zotero.Integration.Session.prototype._updateCitationsCiteprocRs = async function
/**
* Restores processor state from document, without requesting citation updates
*/
Zotero.Integration.Session.prototype.restoreProcessorState = function() {
Zotero.Integration.Session.prototype.restoreProcessorState = function () {
if (this._bibliographyFields.length && !this.bibliography) {
throw new Error ("Attempting to restore processor state without loading bibliography");
}
@ -2310,7 +2309,7 @@ Zotero.Integration.Session.prototype.restoreProcessorState = function() {
}
Zotero.Integration.Session.prototype.writeDelayedCitation = Zotero.Promise.coroutine(function* (field, citation) {
Zotero.Integration.Session.prototype.writeDelayedCitation = async function (field, citation) {
try {
var text = citation.properties.custom || this.style.previewCitationCluster(citation, [], [], this.outputFormat);
}
@ -2326,13 +2325,13 @@ Zotero.Integration.Session.prototype.writeDelayedCitation = Zotero.Promise.corou
// Make sure we'll prompt for manually edited citations
if (!citation.properties.dontUpdate) {
yield field.setText(text);
await field.setText(text);
citation.properties.formattedCitation = text;
citation.properties.plainCitation = yield field._field.getText();
citation.properties.plainCitation = await field._field.getText();
}
yield field.setCode(citation.serialize());
await field.setCode(citation.serialize());
// Update citationsByItemID for later cited item display
for (var i=0; i<citation.citationItems.length; i++) {
@ -2348,25 +2347,25 @@ Zotero.Integration.Session.prototype.writeDelayedCitation = Zotero.Promise.corou
// Note: fields._fields will only contain items upon first delayed insert
// after a full update
if (this._sessionUpToDate) {
var fields = yield this.getFields();
var fields = await this.getFields();
for (let i = fields.length - 1; i >= 0; i--) {
let field = yield Zotero.Integration.Field.loadExisting(fields[i]);
let field = await Zotero.Integration.Field.loadExisting(fields[i]);
if (field.type == INTEGRATION_TYPE_BIBLIOGRAPHY) {
var interfaceType = 'tab';
if (['MacWord2008', 'OpenOffice'].includes(this.agent)) {
interfaceType = 'toolbar';
}
yield field.setText(Zotero.getString(`integration.delayCitationUpdates.bibliography.${interfaceType}`), false);
await field.setText(Zotero.getString(`integration.delayCitationUpdates.bibliography.${interfaceType}`), false);
break;
}
}
}
this._sessionUpToDate = false;
});
};
Zotero.Integration.Session.prototype.getItems = function(itemIDs) {
Zotero.Integration.Session.prototype.getItems = function (itemIDs) {
itemIDs = itemIDs || Object.keys(this.citationsByItemID);
return Zotero.Cite.getItem(itemIDs);
}
@ -2505,7 +2504,7 @@ Zotero.Integration.Session.prototype.editBibliography = async function (bibliogr
* Creates a new bibliography editor interface
* @param bibliography {Zotero.Integration.Bibliography}
*/
Zotero.Integration.BibliographyEditInterface = function(bibliography, citationsByItemID, citeproc) {
Zotero.Integration.BibliographyEditInterface = function (bibliography, citationsByItemID, citeproc) {
this.bibliography = bibliography;
this.citeproc = citeproc;
this.wrappedJSObject = this;
@ -2521,7 +2520,7 @@ Zotero.Integration.BibliographyEditInterface.prototype._update = function () {
/**
* Reverts the text of an individual bibliography entry
*/
Zotero.Integration.BibliographyEditInterface.prototype.revert = function(itemID) {
Zotero.Integration.BibliographyEditInterface.prototype.revert = function (itemID) {
delete this.bibliography.customEntryText[itemID];
return this._update();
}
@ -2539,28 +2538,28 @@ Zotero.Integration.BibliographyEditInterface.prototype.revertAll = function () {
/**
* Reverts bibliography to condition before BibliographyEditInterface was opened
*/
Zotero.Integration.BibliographyEditInterface.prototype.cancel = function() {
Zotero.Integration.BibliographyEditInterface.prototype.cancel = function () {
this.cancelled = true;
};
/**
* Checks whether a given reference is cited within the main document text
*/
Zotero.Integration.BibliographyEditInterface.prototype.isCited = function(item) {
Zotero.Integration.BibliographyEditInterface.prototype.isCited = function (item) {
return this._citationsByItemID[item];
}
/**
* Checks whether an item ID is cited in the bibliography being edited
*/
Zotero.Integration.BibliographyEditInterface.prototype.isEdited = function(itemID) {
Zotero.Integration.BibliographyEditInterface.prototype.isEdited = function (itemID) {
return itemID in this.bibliography.customEntryText;
}
/**
* Checks whether any citations in the bibliography have been edited
*/
Zotero.Integration.BibliographyEditInterface.prototype.isAnyEdited = function() {
Zotero.Integration.BibliographyEditInterface.prototype.isAnyEdited = function () {
return Object.keys(this.bibliography.customEntryText).length ||
this.bibliography.uncitedItemIDs.size ||
this.bibliography.omittedItemIDs.size;
@ -2569,7 +2568,7 @@ Zotero.Integration.BibliographyEditInterface.prototype.isAnyEdited = function()
/**
* Adds an item to the bibliography
*/
Zotero.Integration.BibliographyEditInterface.prototype.add = function(itemID) {
Zotero.Integration.BibliographyEditInterface.prototype.add = function (itemID) {
if (this.bibliography.omittedItemIDs.has(`${itemID}`)) {
this.bibliography.omittedItemIDs.delete(`${itemID}`);
} else {
@ -2581,7 +2580,7 @@ Zotero.Integration.BibliographyEditInterface.prototype.add = function(itemID) {
/**
* Removes an item from the bibliography being edited
*/
Zotero.Integration.BibliographyEditInterface.prototype.remove = function(itemID) {
Zotero.Integration.BibliographyEditInterface.prototype.remove = function (itemID) {
if (this.bibliography.uncitedItemIDs.has(`${itemID}`)) {
this.bibliography.uncitedItemIDs.delete(`${itemID}`);
} else {
@ -2593,7 +2592,7 @@ Zotero.Integration.BibliographyEditInterface.prototype.remove = function(itemID)
/**
* Sets custom bibliography text for a given item
*/
Zotero.Integration.BibliographyEditInterface.prototype.setCustomText = function(itemID, text) {
Zotero.Integration.BibliographyEditInterface.prototype.setCustomText = function (itemID, text) {
this.bibliography.customEntryText[itemID] = text;
return this._update();
}
@ -2601,7 +2600,7 @@ Zotero.Integration.BibliographyEditInterface.prototype.setCustomText = function(
/**
* A class for parsing and passing around document-specific data
*/
Zotero.Integration.DocumentData = function(string) {
Zotero.Integration.DocumentData = function (string) {
this.style = {};
this.prefs = {};
this.sessionID = null;
@ -2613,7 +2612,7 @@ Zotero.Integration.DocumentData = function(string) {
/**
* Serializes document-specific data as JSON
*/
Zotero.Integration.DocumentData.prototype.serialize = function() {
Zotero.Integration.DocumentData.prototype.serialize = function () {
// If we've retrieved data with version 4 (JSON), serialize back to JSON
if (this.dataVersion == 4) {
// Filter style properties
@ -2650,7 +2649,7 @@ Zotero.Integration.DocumentData.prototype.serialize = function() {
/**
* Unserializes document-specific XML
*/
Zotero.Integration.DocumentData.prototype.unserializeXML = function(xmlData) {
Zotero.Integration.DocumentData.prototype.unserializeXML = function (xmlData) {
var parser = new DOMParser(),
doc = parser.parseFromString(xmlData, "application/xml");
@ -2683,7 +2682,7 @@ Zotero.Integration.DocumentData.prototype.unserializeXML = function(xmlData) {
/**
* Unserializes document-specific data, either as XML or as the string form used previously
*/
Zotero.Integration.DocumentData.prototype.unserialize = function(input) {
Zotero.Integration.DocumentData.prototype.unserialize = function (input) {
try {
return Object.assign(this, JSON.parse(input))
} catch (e) {
@ -2725,7 +2724,7 @@ Zotero.Integration.DocumentData.prototype.unserialize = function(input) {
/**
* Handles mapping of item IDs to URIs
*/
Zotero.Integration.URIMap = function(session) {
Zotero.Integration.URIMap = function (session) {
this.itemIDURIs = {};
this.session = session;
}
@ -2733,14 +2732,14 @@ Zotero.Integration.URIMap = function(session) {
/**
* Adds a given mapping to the URI map
*/
Zotero.Integration.URIMap.prototype.add = function(id, uris) {
Zotero.Integration.URIMap.prototype.add = function (id, uris) {
this.itemIDURIs[id] = uris;
}
/**
* Gets URIs for a given item ID, and adds to map
*/
Zotero.Integration.URIMap.prototype.getURIsForItemID = function(id) {
Zotero.Integration.URIMap.prototype.getURIsForItemID = function (id) {
if(typeof id === "string" && id.indexOf("/") !== -1) {
return Zotero.Cite.getItem(id).cslURIs;
}
@ -2803,7 +2802,7 @@ Zotero.Integration.URIMap.prototype.getZoteroItemForURIs = async function (uris)
// or user having imported their library with the new version of importer
else if (!(this.session.dontPromptForMendeley
|| Zotero.Prefs.get('integration.dontPromptMendeleyImport')
|| await Zotero.DB.valueQueryAsync("SELECT value FROM settings WHERE setting='mendeleyImport' AND key='version'")
|| (await Zotero.DB.valueQueryAsync("SELECT value FROM settings WHERE setting='mendeleyImport' AND key='version'"))
)) {
// Prompt user to (re)import their mendeley database which might make us recognize
// these items
@ -2929,7 +2928,7 @@ Zotero.Integration.Field.INTERFACE = ['delete', 'removeCode', 'select', 'setText
* @param idx
* @returns {Zotero.Integration.Field|Zotero.Integration.CitationField|Zotero.Integration.BibliographyField}
*/
Zotero.Integration.Field.loadExisting = async function(docField) {
Zotero.Integration.Field.loadExisting = async function (docField) {
var field;
// Already loaded
if (docField instanceof Zotero.Integration.Field) return docField;
@ -3317,7 +3316,7 @@ Zotero.Integration.Citation = class {
}
// Yes - prompt to reselect
var io = new function() { this.wrappedJSObject = this; };
var io = new function () { this.wrappedJSObject = this; };
io.addBorder = Zotero.isWin;
io.singleSelection = true;
@ -3334,7 +3333,7 @@ Zotero.Integration.Citation = class {
// Check for modified field text or dontUpdate flag
if (this.properties.dontUpdate
|| (this.properties.plainCitation
&& await this.field.getText() !== this.properties.plainCitation)) {
&& (await this.field.getText()) !== this.properties.plainCitation)) {
await Zotero.Integration.currentDoc.activate();
var fieldText = await this.field.getText();
Zotero.debug("[addEditCitation] Attempting to update manually modified citation.\n"
@ -3342,11 +3341,11 @@ Zotero.Integration.Citation = class {
+ "Original: " + this.properties.plainCitation + "\n"
+ "Current: " + fieldText
);
if (!await Zotero.Integration.currentDoc.displayAlert(
if (!(await Zotero.Integration.currentDoc.displayAlert(
Zotero.getString("integration.citationChanged.edit")+"\n\n"
+ Zotero.getString("integration.citationChanged.original", this.properties.plainCitation)+"\n"
+ Zotero.getString("integration.citationChanged.modified", fieldText)+"\n",
DIALOG_ICON_WARNING, DIALOG_BUTTONS_OK_CANCEL)) {
DIALOG_ICON_WARNING, DIALOG_BUTTONS_OK_CANCEL))) {
throw new Zotero.Exception.UserCancelled("editing citation");
}
}
@ -3427,7 +3426,7 @@ Zotero.Integration.Bibliography = class {
}
loadItemData() {
return Zotero.Promise.coroutine(function* () {
return async function () {
// set uncited
var needUpdate = false;
if (this.data.uncited) {
@ -3435,7 +3434,7 @@ Zotero.Integration.Bibliography = class {
// new style array of arrays with URIs
let zoteroItem, itemNeedsUpdate;
for (let uris of this.data.uncited) {
[zoteroItem, itemNeedsUpdate] = yield Zotero.Integration.currentSession.uriMap.getZoteroItemForURIs(uris);
[zoteroItem, itemNeedsUpdate] = await Zotero.Integration.currentSession.uriMap.getZoteroItemForURIs(uris);
var id = zoteroItem.cslItemID ? zoteroItem.cslItemID : zoteroItem.id;
if(zoteroItem && !Zotero.Integration.currentSession.citationsByItemID[id]) {
this.uncitedItemIDs.add(`${id}`);
@ -3462,7 +3461,7 @@ Zotero.Integration.Bibliography = class {
// new style array of arrays with URIs
var zoteroItem, itemNeedsUpdate;
for (let custom of this.data.custom) {
[zoteroItem, itemNeedsUpdate] = yield Zotero.Integration.currentSession.uriMap.getZoteroItemForURIs(custom[0]);
[zoteroItem, itemNeedsUpdate] = await Zotero.Integration.currentSession.uriMap.getZoteroItemForURIs(custom[0]);
if (!zoteroItem) continue;
if (needUpdate) needUpdate = true;
@ -3490,7 +3489,7 @@ Zotero.Integration.Bibliography = class {
if (this.data.omitted) {
let zoteroItem, itemNeedsUpdate;
for (let uris of this.data.omitted) {
[zoteroItem, itemNeedsUpdate] = yield Zotero.Integration.currentSession.uriMap.getZoteroItemForURIs(uris);
[zoteroItem, itemNeedsUpdate] = await Zotero.Integration.currentSession.uriMap.getZoteroItemForURIs(uris);
var id = zoteroItem.cslItemID ? zoteroItem.cslItemID : zoteroItem.id;
if (zoteroItem && Zotero.Integration.currentSession.citationsByItemID[id]) {
this.omittedItemIDs.add(`${id}`);
@ -3502,7 +3501,7 @@ Zotero.Integration.Bibliography = class {
}
this.dataLoaded = true;
return needUpdate;
}).apply(this, arguments);
}.apply(this, arguments);
}
getCiteprocBibliography(citeproc) {
@ -3628,7 +3627,7 @@ Zotero.Integration.Progress = class {
// without this, Firefox gets raised with our windows under Compiz
if (Zotero.isLinux) options += ',dialog=no';
var io = {onLoad: function(onProgress) {
var io = {onLoad: function (onProgress) {
this.onProgress = onProgress;
this.update();
}.bind(this)};
@ -3650,15 +3649,15 @@ Zotero.Integration.Progress = class {
}
}
Zotero.Integration.LegacyPluginWrapper = function(application) {
Zotero.Integration.LegacyPluginWrapper = function (application) {
return {
getDocument:
async function() {
async function () {
return Zotero.Integration.LegacyPluginWrapper.wrapDocument(
application.getDocument.apply(application, arguments))
},
getActiveDocument:
async function() {
async function () {
return Zotero.Integration.LegacyPluginWrapper.wrapDocument(
application.getActiveDocument.apply(application, arguments))
},
@ -3674,11 +3673,11 @@ Zotero.Integration.LegacyPluginWrapper.wrapField = function (field) {
var fns = ['getNoteIndex', 'setCode', 'getCode', 'setText',
'getText', 'removeCode', 'delete', 'select'];
for (let fn of fns) {
wrapped[fn] = async function() {
wrapped[fn] = async function () {
return field[fn].apply(field, arguments);
}
}
wrapped.equals = async function(other) {
wrapped.equals = async function (other) {
return field.equals(other.rawField);
}
return wrapped;
@ -3688,19 +3687,19 @@ Zotero.Integration.LegacyPluginWrapper.wrapDocument = function wrapDocument(doc)
var fns = ['complete', 'cleanup', 'setBibliographyStyle', 'setDocumentData',
'getDocumentData', 'canInsertField', 'activate', 'displayAlert'];
for (let fn of fns) {
wrapped[fn] = async function() {
wrapped[fn] = async function () {
return doc[fn].apply(doc, arguments);
}
}
// Should return an async array
wrapped.getFields = async function(fieldType, progressCallback) {
wrapped.getFields = async function (fieldType, progressCallback) {
if ('getFieldsAsync' in doc) {
var deferred = Zotero.Promise.defer();
var promise = deferred.promise;
var me = this;
doc.getFieldsAsync(fieldType,
{"observe":function(subject, topic, data) {
{"observe":function (subject, topic, data) {
if(topic === "fields-available") {
if(progressCallback) {
try {
@ -3759,15 +3758,15 @@ Zotero.Integration.LegacyPluginWrapper.wrapDocument = function wrapDocument(doc)
return fields;
}
}
wrapped.insertField = async function() {
wrapped.insertField = async function () {
return Zotero.Integration.LegacyPluginWrapper.wrapField(doc.insertField.apply(doc, arguments));
}
wrapped.cursorInField = async function() {
wrapped.cursorInField = async function () {
var result = doc.cursorInField.apply(doc, arguments);
return !result ? result : Zotero.Integration.LegacyPluginWrapper.wrapField(result);
}
// Should take an arrayOfFields instead of an enumerator
wrapped.convert = async function(arrayOfFields) {
wrapped.convert = async function (arrayOfFields) {
arguments[0] = new Zotero.Integration.JSEnumerator(arrayOfFields.map(f => f.rawField));
return doc.convert.apply(doc, arguments);
}

View file

@ -23,7 +23,7 @@
***** END LICENSE BLOCK *****
*/
Zotero.IPC = new function() {
Zotero.IPC = new function () {
var _libc, _libcPath, _instancePipe, _user32, open, write, close;
/**
@ -35,7 +35,7 @@ Zotero.IPC = new function() {
* @param {Boolean} [block] Whether we should block. Usually, we don't want this.
* @return {Boolean} True if write succeeded; false otherwise
*/
this.safePipeWrite = function(pipe, string, block) {
this.safePipeWrite = function (pipe, string, block) {
if(!open) {
// safely write to instance pipes
var lib = Zotero.IPC.getLibc();
@ -65,7 +65,7 @@ Zotero.IPC = new function() {
/**
* Gets the path to libc as a string
*/
this.getLibcPath = function() {
this.getLibcPath = function () {
if(_libcPath) return _libcPath;
Components.utils.import("resource://gre/modules/ctypes.jsm");
@ -106,7 +106,7 @@ Zotero.IPC = new function() {
/**
* Gets standard C library via ctypes
*/
this.getLibc = function() {
this.getLibc = function () {
if(!_libc) this.getLibcPath();
return _libc;
}
@ -115,7 +115,7 @@ Zotero.IPC = new function() {
/**
* Methods for reading from and writing to a pipe
*/
Zotero.IPC.Pipe = new function() {
Zotero.IPC.Pipe = new function () {
var _mkfifo, _pipeClass;
/**
@ -124,7 +124,7 @@ Zotero.IPC.Pipe = new function() {
* @param {nsIFile} file The location where the pipe should be created
* @param {Function} callback A function to be passed any data received on the pipe
*/
this.initPipeListener = function(file, callback) {
this.initPipeListener = function (file, callback) {
Zotero.debug("IPC: Initializing pipe at "+file.path);
// make new pipe
@ -135,7 +135,7 @@ Zotero.IPC.Pipe = new function() {
* Makes a fifo
* @param {nsIFile} file Location to create the fifo
*/
this.mkfifo = function(file) {
this.mkfifo = function (file) {
// int mkfifo(const char *path, mode_t mode);
if(!_mkfifo) {
var libc = Zotero.IPC.getLibc();
@ -152,7 +152,7 @@ Zotero.IPC.Pipe = new function() {
* Adds a shutdown listener for a pipe that writes "Zotero shutdown\n" to the pipe and then
* deletes it
*/
this.remove = function(pipe, file) {
this.remove = function (pipe, file) {
// Make sure pipe actually exists
if(!file.exists()) {
Zotero.debug("IPC: Not closing pipe "+file.path+": already deleted");
@ -173,7 +173,7 @@ Zotero.IPC.Pipe = new function() {
*
* Used to read from pipe on Gecko 5+
*/
Zotero.IPC.Pipe.DeferredOpen = function(file, callback) {
Zotero.IPC.Pipe.DeferredOpen = function (file, callback) {
this._file = file;
this._callback = callback;
@ -186,8 +186,8 @@ Zotero.IPC.Pipe.DeferredOpen = function(file, callback) {
}
Zotero.IPC.Pipe.DeferredOpen.prototype = {
"onStartRequest":function() {},
"onStopRequest":function() {},
"onStartRequest":function () {},
"onStopRequest":function () {},
onDataAvailable: function (request, inputStream, offset, count) {
// read from pipe
var converterInputStream = Components.classes["@mozilla.org/intl/converter-input-stream;1"]
@ -209,7 +209,7 @@ Zotero.IPC.Pipe.DeferredOpen.prototype = {
*
* Used after reading from file on Gecko 5+
*/
"_initPump":function() {
"_initPump":function () {
var fifoStream = Components.classes["@mozilla.org/network/file-input-stream;1"].
createInstance(Components.interfaces.nsIFileInputStream);
fifoStream.QueryInterface(Components.interfaces.nsIFileInputStream);

View file

@ -23,7 +23,7 @@
***** END LICENSE BLOCK *****
*/
Zotero.LocateManager = new function() {
Zotero.LocateManager = new function () {
const LOCATE_FILE_NAME = "engines.json";
const LOCATE_DIR_NAME = "locate";
@ -34,7 +34,7 @@ Zotero.LocateManager = new function() {
/**
* Read locateEngines JSON file to initialize locate manager
*/
this.init = async function() {
this.init = async function () {
_jsonFile = _getLocateFile();
try {
@ -60,12 +60,12 @@ Zotero.LocateManager = new function() {
* Adds a new search engine
* confirm parameter is currently ignored
*/
this.addEngine = function(engineURL, dataType, iconURL, confirm) {
this.addEngine = function (engineURL, dataType, iconURL, confirm) {
if(dataType !== Components.interfaces.nsISearchEngine.TYPE_OPENSEARCH) {
throw new Error("LocateManager supports only OpenSearch engines");
}
Zotero.HTTP.doGet(engineURL, function(xmlhttp) {
Zotero.HTTP.doGet(engineURL, function (xmlhttp) {
var engine = new LocateEngine();
engine.initWithXML(xmlhttp.responseText, iconURL);
});
@ -82,7 +82,7 @@ Zotero.LocateManager = new function() {
/**
* Returns an array of all search engines
*/
this.getEngines = function() { return _locateEngines.slice(0); }
this.getEngines = function () { return _locateEngines.slice(0); }
/**
* Returns an array of all search engines visible that should be visible in the dropdown
@ -94,7 +94,7 @@ Zotero.LocateManager = new function() {
/**
* Returns an engine with a specific name
*/
this.getEngineByName = function(engineName) {
this.getEngineByName = function (engineName) {
engineName = engineName.toLowerCase();
for (let engine of _locateEngines) if(engine.name.toLowerCase() == engineName) return engine;
return null;
@ -103,7 +103,7 @@ Zotero.LocateManager = new function() {
/**
* Returns the first engine with a specific alias
*/
this.getEngineByAlias = function(engineAlias) {
this.getEngineByAlias = function (engineAlias) {
engineAlias = engineAlias.toLowerCase();
for (let engine of _locateEngines) if(engine.alias.toLowerCase() == engineAlias) return engine;
return null;
@ -112,7 +112,7 @@ Zotero.LocateManager = new function() {
/**
* Moves an engine in the list
*/
this.moveEngine = function(engine, newIndex) {
this.moveEngine = function (engine, newIndex) {
this.removeEngine(engine);
_locateEngines.splice(newIndex, engine);
}
@ -120,7 +120,7 @@ Zotero.LocateManager = new function() {
/**
* Removes an engine from the list
*/
this.removeEngine = function(engine) {
this.removeEngine = function (engine) {
var oldIndex = _locateEngines.indexOf(engine);
if(oldIndex === -1) throw new Error("Engine is not currently listed");
_locateEngines.splice(oldIndex, 1);
@ -293,7 +293,7 @@ Zotero.LocateManager = new function() {
/**
* Theoretically implements nsISearchSubmission
*/
var LocateSubmission = function(uri, postData) {
var LocateSubmission = function (uri, postData) {
this.uri = Services.io.newURI(uri, null, null);
this.postData = postData;
}
@ -303,7 +303,7 @@ Zotero.LocateManager = new function() {
* Constructs a new LocateEngine
* @param {Object} [obj] The locate engine, in parsed form, as it was serialized to JSON
*/
var LocateEngine = function(obj) {
var LocateEngine = function (obj) {
this._alias = this._name = "Untitled";
this._description = null;
this._icon = null;
@ -318,7 +318,7 @@ Zotero.LocateManager = new function() {
/**
* Initializes an engine with a string and an iconURL to use if none is defined in the file
*/
"initWithXML":function(xmlStr, iconURL) {
"initWithXML":function (xmlStr, iconURL) {
const OPENSEARCH_NAMESPACES = [
// These are the official namespaces
"http://a9.com/-/spec/opensearch/1.1/",
@ -400,7 +400,7 @@ Zotero.LocateManager = new function() {
_serializeLocateEngines();
},
"getItemSubmission":function(item, responseType) {
"getItemSubmission":function (item, responseType) {
if(responseType && responseType !== "text/html") {
throw new Error("LocateManager supports only responseType text/html");
}
@ -414,7 +414,7 @@ Zotero.LocateManager = new function() {
// do substitutions
var me = this;
var abort = false;
var url = this._urlTemplate.replace(/{(?:([^}:]+):)?([^}:?]+)(\?)?}/g, function(all, nsPrefix, param, required) {
var url = this._urlTemplate.replace(/{(?:([^}:]+):)?([^}:?]+)(\?)?}/g, function (all, nsPrefix, param, required) {
var result = _lookupParam(item, itemAsOpenURL, me, nsPrefix, param, required);
if(result) {
return result[0];
@ -464,7 +464,7 @@ Zotero.LocateManager = new function() {
return new LocateSubmission(url, postData);
},
"_removeIcon":function() {
"_removeIcon":function () {
if(!this.icon) return;
var uri = Services.io.newURI(this.icon, null, null);
var file = uri.QueryInterface(Components.interfaces.nsIFileURL).file;

View file

@ -23,7 +23,7 @@
***** END LICENSE BLOCK *****
*/
Zotero.MIME = new function(){
Zotero.MIME = new function () {
this.isTextType = isTextType;
this.getPrimaryExtension = getPrimaryExtension;
this.sniffForBinary = sniffForBinary;
@ -137,7 +137,7 @@ Zotero.MIME = new function(){
return mimeType.substr(0, 5) == 'text/' || mimeType in _textTypes;
}
this.isWebPageType = function(mimeType) {
this.isWebPageType = function (mimeType) {
return _webPageTypes.indexOf(mimeType) != -1;
}
@ -330,12 +330,12 @@ Zotero.MIME = new function(){
* Try to determine the MIME type of the file, using a few different
* techniques
*/
this.getMIMETypeFromFile = Zotero.Promise.coroutine(function* (file) {
var str = yield Zotero.File.getSample(file);
this.getMIMETypeFromFile = async function (file) {
var str = await Zotero.File.getSample(file);
var ext = Zotero.File.getExtension(file);
return this.getMIMETypeFromData(str, ext);
});
};
/**

View file

@ -49,14 +49,14 @@ Zotero.MIMETypeHandler = new function () {
/**
* Registers nsIObserver to handle MIME types
*/
this.init = function() {
this.init = function () {
Zotero.debug("Registering nsIObserver");
// register our nsIObserver
Components.classes["@mozilla.org/observer-service;1"].
getService(Components.interfaces.nsIObserverService).
addObserver(_Observer, "http-on-examine-response", false);
this.initializeHandlers();
Zotero.addShutdownListener(function() {
Zotero.addShutdownListener(function () {
Components.classes["@mozilla.org/observer-service;1"].
getService(Components.interfaces.nsIObserverService).
removeObserver(_Observer, "http-on-examine-response", false);
@ -143,7 +143,7 @@ Zotero.MIMETypeHandler = new function () {
/**
* Adds an observer to inspect and possibly modify page headers
*/
this.addObserver = function(fn) {
this.addObserver = function (fn) {
_observers.push(fn);
}
@ -216,7 +216,7 @@ Zotero.MIMETypeHandler = new function () {
/**
* Standard QI definition
*/
_StreamListener.prototype.QueryInterface = function(iid) {
_StreamListener.prototype.QueryInterface = function (iid) {
if (iid.equals(Components.interfaces.nsISupports)
|| iid.equals(Components.interfaces.nsIRequestObserver)
|| iid.equals(Components.interfaces.nsIStreamListener)) {
@ -225,7 +225,7 @@ Zotero.MIMETypeHandler = new function () {
throw Components.results.NS_ERROR_NO_INTERFACE;
}
_StreamListener.prototype.onStartRequest = async function(channel) {
_StreamListener.prototype.onStartRequest = async function (channel) {
this._onStartRequestCalled = true;
this._dataBuffer = new StorageStream(4096, 0xffffffff);
this._stream = new BufferedOutputStream(this._dataBuffer.getOutputStream(0), 8192);

View file

@ -128,7 +128,7 @@ Zotero.Notifier = new function () {
*
* - New events and types should be added to the order arrays in commit()
**/
this.trigger = Zotero.Promise.coroutine(function* (event, type, ids, extraData, force) {
this.trigger = async function (event, type, ids, extraData, force) {
if (_transactionID && !force) {
return this.queue(event, type, ids, extraData);
}
@ -163,7 +163,7 @@ Zotero.Notifier = new function () {
// one throws an error
try {
let t = new Date;
yield Zotero.Promise.resolve(ref.notify(event, type, ids, extraData));
await Promise.resolve(ref.notify(event, type, ids, extraData));
t = new Date - t;
if (t > 5) {
//Zotero.debug(id + " observer finished in " + t + " ms", 5);
@ -175,7 +175,7 @@ Zotero.Notifier = new function () {
}
return true;
});
};
/**
@ -330,7 +330,7 @@ Zotero.Notifier = new function () {
* instead of the internal queue
* @param {String} [transactionID]
*/
this.commit = Zotero.Promise.coroutine(function* (queues, transactionID = true) {
this.commit = async function (queues, transactionID = true) {
let queue;
if (queues) {
if (!Array.isArray(queues)) {
@ -405,10 +405,10 @@ Zotero.Notifier = new function () {
// Don't send modify on nonexistent items or tags
if (event == 'modify') {
if (type == 'item' && !(yield Zotero.Items.getAsync(id))) {
if (type == 'item' && !((await Zotero.Items.getAsync(id)))) {
continue;
}
else if (type == 'tag' && !(yield Zotero.Tags.getAsync(id))) {
else if (type == 'tag' && !((await Zotero.Tags.getAsync(id)))) {
continue;
}
}
@ -440,7 +440,7 @@ Zotero.Notifier = new function () {
for (let type in runQueue) {
for (let event in runQueue[type]) {
if (runQueue[type][event].ids.length || event == 'refresh') {
yield this.trigger(
await this.trigger(
event,
type,
runQueue[type][event].ids,
@ -451,7 +451,7 @@ Zotero.Notifier = new function () {
}
}
}
});
};
/*

View file

@ -291,7 +291,7 @@ class PDFWorker {
throw new Error('Item must be a PDF attachment');
}
let mtime = Math.floor(await attachment.attachmentModificationTime / 1000);
let mtime = Math.floor((await attachment.attachmentModificationTime) / 1000);
if (!transfer && attachment.attachmentLastProcessedModificationTime === mtime) {
Zotero.debug("File hasn't changed since last-processed time -- skipping annotations import");
return false;
@ -364,7 +364,7 @@ class PDFWorker {
if (transfer) {
if (modifiedBuf) {
await IOUtils.write(path, new Uint8Array(modifiedBuf));
mtime = Math.floor(await attachment.attachmentModificationTime / 1000);
mtime = Math.floor((await attachment.attachmentModificationTime) / 1000);
}
}
@ -554,7 +554,7 @@ class PDFWorker {
await Zotero.Notifier.trigger('modify', 'item', ids, {});
await IOUtils.write(path, new Uint8Array(modifiedBuf));
let mtime = Math.floor(await attachment.attachmentModificationTime / 1000);
let mtime = Math.floor((await attachment.attachmentModificationTime) / 1000);
attachment.attachmentLastProcessedModificationTime = mtime;
await attachment.saveTx({
skipAll: true
@ -607,7 +607,7 @@ class PDFWorker {
}
await IOUtils.write(path, new Uint8Array(modifiedBuf));
let mtime = Math.floor(await attachment.attachmentModificationTime / 1000);
let mtime = Math.floor((await attachment.attachmentModificationTime) / 1000);
attachment.attachmentLastProcessedModificationTime = mtime;
await attachment.saveTx({
skipAll: true
@ -720,7 +720,7 @@ class PDFWorker {
let annotations = [];
for (let annotation of attachment.getAnnotations()) {
if (['image', 'ink'].includes(annotation.annotationType)
&& !await Zotero.Annotations.hasCacheImage(annotation)) {
&& !(await Zotero.Annotations.hasCacheImage(annotation))) {
annotations.push({
id: annotation.key,
color: annotation.annotationColor,

View file

@ -136,9 +136,9 @@ Zotero.PreferencePanes = {
id: options.id || `plugin-pane-${Zotero.Utilities.randomString()}-${options.pluginID}`,
pluginID: options.pluginID,
parent: options.parent,
rawLabel: options.label || await Zotero.Plugins.getName(options.pluginID),
image: options.image && await Zotero.Plugins.resolveURI(options.pluginID, options.image)
|| await Zotero.Plugins.getIconURI(options.pluginID, 24),
rawLabel: options.label || (await Zotero.Plugins.getName(options.pluginID)),
image: options.image && (await Zotero.Plugins.resolveURI(options.pluginID, options.image))
|| (await Zotero.Plugins.getIconURI(options.pluginID, 24)),
src: await Zotero.Plugins.resolveURI(options.pluginID, options.src),
scripts: await Promise.all(options.scripts.map(uri => Zotero.Plugins.resolveURI(options.pluginID, uri))),
stylesheets: await Promise.all(options.stylesheets.map(uri => Zotero.Plugins.resolveURI(options.pluginID, uri))),

View file

@ -22,7 +22,7 @@
***** END LICENSE BLOCK *****
*/
Zotero.Prefs = new function() {
Zotero.Prefs = new function () {
// Privileged methods
this.get = get;
this.set = set;
@ -307,7 +307,7 @@ Zotero.Prefs = new function() {
// Handlers for some Zotero preferences
var _handlers = [
[ "automaticScraperUpdates", function(val) {
[ "automaticScraperUpdates", function (val) {
if (val){
Zotero.Schema.updateFromRepository(1);
}
@ -321,18 +321,18 @@ Zotero.Prefs = new function() {
["uiDensity", function () {
Zotero.UIProperties.setAll();
}],
["recursiveCollections", function() {
["recursiveCollections", function () {
Zotero.getActiveZoteroPane().itemsView.refreshAndMaintainSelection();
}],
[ "layout", function(val) {
[ "layout", function (val) {
Zotero.getActiveZoteroPane().updateLayout();
}],
[ "note.fontSize", function(val) {
[ "note.fontSize", function (val) {
if (val < 6) {
Zotero.Prefs.set('note.fontSize', 11);
}
}],
[ "sync.autoSync", function(val) {
[ "sync.autoSync", function (val) {
if (val) {
Zotero.Sync.EventListeners.AutoSyncListener.register();
Zotero.Sync.EventListeners.IdleListener.register();
@ -351,7 +351,7 @@ Zotero.Prefs = new function() {
Zotero.logError(e);
}
}],
[ "search.quicksearch-mode", function(val) {
[ "search.quicksearch-mode", function (val) {
var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
var enumerator = wm.getEnumerator("navigator:browser");
@ -368,7 +368,7 @@ Zotero.Prefs = new function() {
Zotero.updateQuickSearchBox(win.document);
}
}],
[ "cite.useCiteprocRs", function(val) {
[ "cite.useCiteprocRs", function (val) {
val && Zotero.CiteprocRs.init();
}]
];

View file

@ -29,11 +29,11 @@ var { OS } = ChromeUtils.importESModule("chrome://zotero/content/osfile.mjs");
Zotero.Profile = {
dir: OS.Constants.Path.profileDir,
getDefaultInProfilesDir: Zotero.Promise.coroutine(function* (profilesDir) {
getDefaultInProfilesDir: async function (profilesDir) {
var profilesIni = OS.Path.join(profilesDir, "profiles.ini");
try {
var iniContents = yield Zotero.File.getContentsAsync(profilesIni);
var iniContents = await Zotero.File.getContentsAsync(profilesIni);
}
catch (e) {
if (e.name == 'NotFoundError') {
@ -71,7 +71,7 @@ Zotero.Profile = {
try {
// Note: exists() returns false on no access, so use stat() instead
yield OS.File.stat(defaultProfile);
await OS.File.stat(defaultProfile);
}
catch (e) {
if (e instanceof OS.File.Error) {
@ -82,7 +82,7 @@ Zotero.Profile = {
}
}
return [defaultProfile, nSections > 1];
}),
},
getProfilesDir: function () {
@ -122,13 +122,14 @@ Zotero.Profile = {
* @param {Boolean} [includeOtherApps=false] - Check Firefox profiles
* @return {String[]}
*/
findOtherProfilesUsingDataDirectory: Zotero.Promise.coroutine(function* (dataDir, includeOtherApps = true) {
let otherAppProfiles = includeOtherApps ? (yield this._findOtherAppProfiles()) : [];
let otherProfiles = (yield this._findOtherProfiles()).concat(otherAppProfiles);
findOtherProfilesUsingDataDirectory: async function (dataDir, includeOtherApps = true) {
let otherAppProfiles = includeOtherApps ? ((await this._findOtherAppProfiles())) : [];
let otherProfiles = ((await this._findOtherProfiles())).concat(otherAppProfiles);
// First get profiles pointing at this directory
otherProfiles = yield Zotero.Promise.filter(otherProfiles, Zotero.Promise.coroutine(function* (dir) {
let prefs = yield Zotero.File.getContentsAsync(OS.Path.join(dir, "prefs.js"));
otherProfiles = await // FIXME: fx140: replace call to Zotero.Promise.filter()
Zotero.Promise.filter(otherProfiles, async function (dir) {
let prefs = await Zotero.File.getContentsAsync(OS.Path.join(dir, "prefs.js"));
prefs = prefs.trim().split(/(?:\r\n|\r|\n)/);
return prefs.some(line => {
@ -136,7 +137,7 @@ Zotero.Profile = {
}) && prefs.some(line => {
return line.match(/extensions\.zotero\.(lastD|d)ataDir/) && line.includes(dataDir)
});
}));
});
// If the parent of the source directory is a profile directory from the other app, add that
// to the list, which addresses the situation where the source directory is a custom
@ -156,14 +157,14 @@ Zotero.Profile = {
}
return otherProfiles;
}),
},
updateProfileDataDirectory: Zotero.Promise.coroutine(function* (profileDir, oldDir, newDir) {
updateProfileDataDirectory: async function (profileDir, oldDir, newDir) {
let prefsFile = OS.Path.join(profileDir, "prefs.js");
let prefsFileTmp = OS.Path.join(profileDir, "prefs.js.tmp");
Zotero.debug("Updating " + prefsFile + " to point to new data directory");
let contents = yield Zotero.File.getContentsAsync(prefsFile);
let contents = await Zotero.File.getContentsAsync(prefsFile);
contents = contents
.trim()
.split(/(?:\r\n|\r|\n)/)
@ -178,7 +179,7 @@ Zotero.Profile = {
);
let lineSep = Zotero.isWin ? "\r\n" : "\n";
contents = contents.join(lineSep) + lineSep;
yield OS.File.writeAtomic(
await OS.File.writeAtomic(
prefsFile,
contents,
{
@ -186,7 +187,7 @@ Zotero.Profile = {
encoding: 'utf-8'
}
);
}),
},
/**
@ -274,9 +275,9 @@ Zotero.Profile = {
*
* @return {String[]} - Array of paths
*/
_getProfilesInDir: Zotero.Promise.coroutine(function* (profilesDir) {
_getProfilesInDir: async function (profilesDir) {
var dirs = [];
yield Zotero.File.iterateDirectory(profilesDir, async function (entry) {
await Zotero.File.iterateDirectory(profilesDir, async function (entry) {
// entry.isDir can be false for some reason on Travis, causing spurious test failures
if (Zotero.automatedTest && !entry.isDir && (await OS.File.stat(entry.path)).isDir) {
Zotero.debug("Overriding isDir for " + entry.path);
@ -287,7 +288,7 @@ Zotero.Profile = {
}
});
return dirs;
}),
},
/**
@ -295,11 +296,11 @@ Zotero.Profile = {
*
* @return {String[]} - Array of paths
*/
_findOtherProfiles: Zotero.Promise.coroutine(function* () {
_findOtherProfiles: async function () {
var profileDir = this.dir;
var profilesDir = this.getProfilesDir();
return this._getProfilesInDir(profilesDir).filter(dir => dir != profileDir);
}),
},
/**
@ -309,6 +310,6 @@ Zotero.Profile = {
*/
_findOtherAppProfiles: async function () {
var dir = this.getOtherAppProfilesDir();
return dir && await OS.File.exists(dir) ? this._getProfilesInDir(dir) : [];
return dir && (await OS.File.exists(dir)) ? this._getProfilesInDir(dir) : [];
}
};

View file

@ -45,7 +45,7 @@ Zotero.ProgressQueue = function (options) {
/**
* @return {Zotero.ProgressQueueDialog}
*/
this.getDialog = function() {
this.getDialog = function () {
if(!_dialog) {
_dialog = new Zotero.ProgressQueueDialog(_progressQueue);
}
@ -148,7 +148,7 @@ Zotero.ProgressQueue = function (options) {
* Add item for processing
* @param {Zotero.Item} item
*/
this.addRow = function(item) {
this.addRow = function (item) {
this.deleteRow(item.id);
let row = {
@ -171,7 +171,7 @@ Zotero.ProgressQueue = function (options) {
* @param {Number} status
* @param {String} message
*/
this.updateRow = function(itemID, status, message) {
this.updateRow = function (itemID, status, message) {
Zotero.debug(`ProgressQueue: updating row ${itemID}, ${status}, ${message}`);
for (let row of _rows) {
if (row.id === itemID) {
@ -192,7 +192,7 @@ Zotero.ProgressQueue = function (options) {
* Delete row
* @param {Number} itemID
*/
this.deleteRow = function(itemID) {
this.deleteRow = function (itemID) {
let row = _rows.find(x => x.id === itemID);
if (row) {
_rows.splice(_rows.indexOf(row), 1);

View file

@ -24,7 +24,7 @@
*/
Zotero.ProgressWindowSet = new function() {
Zotero.ProgressWindowSet = new function () {
this.add = add;
this.tile = tile;
this.remove = remove;
@ -100,7 +100,7 @@ Zotero.ProgressWindowSet = new function() {
*
* Pass the active window into the constructor
*/
Zotero.ProgressWindow = function(options = {}) {
Zotero.ProgressWindow = function (options = {}) {
var _window = options.window || null;
var _closeOnClick = typeof options.closeOnClick == 'undefined' ? true : options.closeOnClick;
var self = this,
@ -282,7 +282,7 @@ Zotero.ProgressWindow = function(options = {}) {
* Creates a new object representing a line in the progressWindow. This is the OO
* version of addLines() above.
*/
this.ItemProgress = _deferUntilWindowLoad(function(itemType, text, parentItemProgress) {
this.ItemProgress = _deferUntilWindowLoad(function (itemType, text, parentItemProgress) {
this.setText(text);
this._image = _progressWindow.document.createXULElement("hbox");
@ -322,7 +322,7 @@ Zotero.ProgressWindow = function(options = {}) {
* Sets the current save progress for this item.
* @param {Integer} percent A percentage from 0 to 100.
*/
this.ItemProgress.prototype.setProgress = _deferUntilWindowLoad(function(percent) {
this.ItemProgress.prototype.setProgress = _deferUntilWindowLoad(function (percent) {
if(percent != 0 && percent != 100) {
// Indication of partial progress, so we will use the circular indicator
var nArcs = 20;
@ -346,7 +346,7 @@ Zotero.ProgressWindow = function(options = {}) {
* @param {String} [itemType]
* @param {String} [cssIcon]
*/
this.ItemProgress.prototype.setItemTypeAndIcon = _deferUntilWindowLoad(function(itemType, cssIcon = 'item-type') {
this.ItemProgress.prototype.setItemTypeAndIcon = _deferUntilWindowLoad(function (itemType, cssIcon = 'item-type') {
// No getCSSItemTypeIcon() without a window context
this._image.className = this._iconClassName = `icon icon-16 icon-css icon-${cssIcon}`;
this._image.dataset.itemType = itemType;
@ -368,7 +368,7 @@ Zotero.ProgressWindow = function(options = {}) {
/**
* Indicates that an error occurred saving this item.
*/
this.ItemProgress.prototype.setError = _deferUntilWindowLoad(function() {
this.ItemProgress.prototype.setError = _deferUntilWindowLoad(function () {
this._image.style.backgroundImage = "url('chrome://zotero/skin/cross.png')";
this._image.style.backgroundPosition = "";
this._itemText.style.color = "red";
@ -378,7 +378,7 @@ Zotero.ProgressWindow = function(options = {}) {
this.Translation = {};
this.Translation.operationInProgress = function() {
this.Translation.operationInProgress = function () {
var desc = [
Zotero.getString('general.operationInProgress'),
Zotero.getString('general.operationInProgress.waitUntilFinishedAndTryAgain')
@ -386,7 +386,7 @@ Zotero.ProgressWindow = function(options = {}) {
self.Translation._scrapeError(desc);
};
this.Translation.cannotEditCollection = function() {
this.Translation.cannotEditCollection = function () {
var desc = Zotero.getString('save.error.cannotMakeChangesToCollection');
self.Translation._scrapeError(desc);
};
@ -396,12 +396,12 @@ Zotero.ProgressWindow = function(options = {}) {
self.Translation._scrapeError(desc);
};
this.Translation.cannotAddToFeed = function() {
this.Translation.cannotAddToFeed = function () {
var desc = Zotero.getString('save.error.cannotAddToFeed');
self.Translation._scrapeError(desc);
};
this.Translation.scrapingTo = function(libraryID, collection) {
this.Translation.scrapingTo = function (libraryID, collection) {
var name;
if(collection) {
name = collection.name;
@ -418,7 +418,7 @@ Zotero.ProgressWindow = function(options = {}) {
);
};
this.Translation.doneHandler = function(obj, returnValue) {
this.Translation.doneHandler = function (obj, returnValue) {
if(!returnValue) {
// Include link to translator troubleshooting page
var url = "https://www.zotero.org/support/troubleshooting_translator_issues";
@ -431,9 +431,9 @@ Zotero.ProgressWindow = function(options = {}) {
}
};
this.Translation.itemDoneHandler = function(_attachmentsMap) {
this.Translation.itemDoneHandler = function (_attachmentsMap) {
_attachmentsMap = _attachmentsMap || new WeakMap();
return function(obj, dbItem, item) {
return function (obj, dbItem, item) {
self.show();
var itemProgress = new self.ItemProgress(dbItem?.getItemTypeIconName() ?? item.itemType, item.title);
itemProgress.setProgress(100);
@ -452,7 +452,7 @@ Zotero.ProgressWindow = function(options = {}) {
}
};
this.Translation._scrapeError = function(description) {
this.Translation._scrapeError = function (description) {
self.changeHeadline(Zotero.getString("ingester.scrapeError"));
self.addDescription(description);
self.show();
@ -534,7 +534,7 @@ Zotero.ProgressWindow = function(options = {}) {
* Wraps a function to ensure it isn't called until the window is loaded
*/
function _deferUntilWindowLoad(fn) {
return function() {
return function () {
if(_window && _window.closed) return;
if(_windowLoaded) {

View file

@ -32,7 +32,7 @@ Components.utils.importGlobalProperties(["URL"]);
* @property proxies {Zotero.Proxy[]} All loaded proxies
* @property hosts {Zotero.Proxy{}} Object mapping hosts to proxies
*/
Zotero.Proxies = new function() {
Zotero.Proxies = new function () {
this.proxies = false;
this.transparent = false;
this.hosts = {};
@ -41,10 +41,10 @@ Zotero.Proxies = new function() {
/**
* Initializes http-on-examine-response observer to intercept page loads and gets preferences
*/
this.init = Zotero.Promise.coroutine(function* () {
this.init = async function () {
if(!this.proxies) {
var rows = yield Zotero.DB.queryAsync("SELECT * FROM proxies");
Zotero.Proxies.proxies = yield Zotero.Promise.all(
var rows = await Zotero.DB.queryAsync("SELECT * FROM proxies");
Zotero.Proxies.proxies = await Promise.all(
rows.map(row => this.newProxyFromRow(row))
);
@ -66,25 +66,25 @@ Zotero.Proxies = new function() {
Zotero.Proxies.disabledByDomain = false;
Zotero.Proxies.showRedirectNotification = Zotero.Prefs.get("proxies.showRedirectNotification");
});
};
/**
* @param {Object} row - Database row with proxy data
* @return {Promise<Zotero.Proxy>}
*/
this.newProxyFromRow = Zotero.Promise.coroutine(function* (row) {
this.newProxyFromRow = async function (row) {
var proxy = new Zotero.Proxy(row);
yield proxy.loadHosts();
await proxy.loadHosts();
return proxy;
});
};
/**
* Removes a proxy object from the list of proxy objects
* @returns {Boolean} True if the proxy was in the list, false if it was not
*/
this.remove = function(proxy) {
this.remove = function (proxy) {
var index = Zotero.Proxies.proxies.indexOf(proxy);
if(index == -1) return false;
// remove proxy from proxy list
@ -101,7 +101,7 @@ Zotero.Proxies = new function() {
/**
* Inserts a proxy into the host map; necessary when proxies are added
*/
this.save = function(proxy) {
this.save = function (proxy) {
// add to list of proxies
if(Zotero.Proxies.proxies.indexOf(proxy) == -1) Zotero.Proxies.proxies.push(proxy);
@ -117,7 +117,7 @@ Zotero.Proxies = new function() {
/**
* Refreshes host map; necessary when proxies are changed or deleted
*/
this.refreshHostMap = function(proxy) {
this.refreshHostMap = function (proxy) {
// if there is no proxyID, then return immediately, since there is no need to update
if(!proxy.proxyID) return;
@ -139,7 +139,7 @@ Zotero.Proxies = new function() {
* function will return "false" if the given URL is unproxied.
* @type String
*/
this.proxyToProper = function(url, onlyReturnIfProxied) {
this.proxyToProper = function (url, onlyReturnIfProxied) {
// make sure url has a trailing slash
url = new URL(url).href;
for (let proxy of Zotero.Proxies.proxies) {
@ -163,7 +163,7 @@ Zotero.Proxies = new function() {
* function will return "false" if the given URL is unproxied.
* @type String
*/
this.properToProxy = function(url, onlyReturnIfProxied) {
this.properToProxy = function (url, onlyReturnIfProxied) {
var uri = Services.io.newURI(url, null, null);
if(Zotero.Proxies.hosts[uri.hostPort] && Zotero.Proxies.hosts[uri.hostPort].proxyID) {
var toProxy = Zotero.Proxies.hosts[uri.hostPort].toProxy(uri);
@ -180,7 +180,7 @@ Zotero.Proxies = new function() {
* @param url
* @returns {Object} Unproxied url to proxy object
*/
this.getPotentialProxies = function(url) {
this.getPotentialProxies = function (url) {
// make sure url has a trailing slash
url = new URL(url).href;
var urlToProxy = {};
@ -260,7 +260,7 @@ Zotero.Proxy.prototype._loadFromRow = function (row) {
}
};
Zotero.Proxy.prototype.toJSON = function() {
Zotero.Proxy.prototype.toJSON = function () {
if (!this.scheme) {
throw Error('Cannot convert proxy to JSON - no scheme');
}
@ -294,7 +294,7 @@ const Zotero_Proxy_schemeParameterRegexps = {
* Compiles the regular expression against which we match URLs to determine if this proxy is in use
* and saves it in this.regexp
*/
Zotero.Proxy.prototype.compileRegexp = function() {
Zotero.Proxy.prototype.compileRegexp = function () {
// take host only if flagged as multiHost
var parametersToCheck = Zotero_Proxy_schemeParameters;
if(this.multiHost) parametersToCheck["%h"] = "([a-zA-Z0-9]+[.\\-][a-zA-Z0-9.\\-]+)";
@ -317,7 +317,7 @@ Zotero.Proxy.prototype.compileRegexp = function() {
}
// sort params by index
this.parameters = this.parameters.sort(function(a, b) {
this.parameters = this.parameters.sort(function (a, b) {
return indices[a]-indices[b];
})
@ -341,7 +341,7 @@ Zotero.Proxy.prototype.compileRegexp = function() {
* @returns {String|Boolean} An error type if a validation error occurred, or "false" if there was
* no error.
*/
Zotero.Proxy.prototype.validate = function() {
Zotero.Proxy.prototype.validate = function () {
if(this.scheme.length < 8 || (this.scheme.substr(0, 7) != "http://" && this.scheme.substr(0, 8) != "https://")) {
return ["scheme.noHTTP"];
}
@ -377,7 +377,7 @@ Zotero.Proxy.prototype.validate = function() {
*
* @param {Boolean} transparent True if proxy should be saved as a persisting, transparent proxy
*/
Zotero.Proxy.prototype.save = Zotero.Promise.coroutine(function* (transparent) {
Zotero.Proxy.prototype.save = async function (transparent) {
// ensure this proxy is valid
var hasErrors = this.validate();
if(hasErrors) throw new Error("Proxy: could not be saved because it is invalid: error "+hasErrors[0]);
@ -389,7 +389,7 @@ Zotero.Proxy.prototype.save = Zotero.Promise.coroutine(function* (transparent) {
this.compileRegexp();
if(transparent) {
yield Zotero.DB.executeTransaction(async function () {
await Zotero.DB.executeTransaction(async function () {
if(this.proxyID) {
await Zotero.DB.queryAsync(
"UPDATE proxies SET multiHost = ?, autoAssociate = ?, scheme = ? WHERE proxyID = ?",
@ -423,31 +423,31 @@ Zotero.Proxy.prototype.save = Zotero.Promise.coroutine(function* (transparent) {
Zotero.Proxies.refreshHostMap(this);
if(!transparent) throw new Error("Proxy: cannot save transparent proxy without transparent param");
}
});
};
/**
* Reverts to the previously saved version of this proxy
*/
Zotero.Proxy.prototype.revert = Zotero.Promise.coroutine(function* () {
Zotero.Proxy.prototype.revert = async function () {
if (!this.proxyID) throw new Error("Cannot revert an unsaved proxy");
var row = yield Zotero.DB.rowQueryAsync("SELECT * FROM proxies WHERE proxyID = ?", [this.proxyID]);
var row = await Zotero.DB.rowQueryAsync("SELECT * FROM proxies WHERE proxyID = ?", [this.proxyID]);
this._loadFromRow(row);
yield this.loadHosts();
});
await this.loadHosts();
};
/**
* Deletes this proxy
*/
Zotero.Proxy.prototype.erase = Zotero.Promise.coroutine(function* () {
Zotero.Proxy.prototype.erase = async function () {
Zotero.Proxies.remove(this);
if(this.proxyID) {
yield Zotero.DB.executeTransaction(async function () {
await Zotero.DB.executeTransaction(async function () {
await Zotero.DB.queryAsync("DELETE FROM proxyHosts WHERE proxyID = ?", [this.proxyID]);
await Zotero.DB.queryAsync("DELETE FROM proxies WHERE proxyID = ?", [this.proxyID]);
}.bind(this));
}
});
};
/**
* Converts a proxied URL to an unproxied URL using this proxy
@ -455,7 +455,7 @@ Zotero.Proxy.prototype.erase = Zotero.Promise.coroutine(function* () {
* @param m {String|Array} The URL or the match from running this proxy's regexp against a URL spec
* @return {String} The unproxified URL if was proxified or the unchanged URL
*/
Zotero.Proxy.prototype.toProper = function(m) {
Zotero.Proxy.prototype.toProper = function (m) {
if (!Array.isArray(m)) {
// make sure url has a trailing slash
m = new URL(m).href;
@ -497,7 +497,7 @@ Zotero.Proxy.prototype.toProper = function(m) {
* @param {String|nsIURI} uri The URL as a string or the nsIURI corresponding to the unproxied URL
* @return {String} The proxified URL if was unproxified or the unchanged url
*/
Zotero.Proxy.prototype.toProxy = function(uri) {
Zotero.Proxy.prototype.toProxy = function (uri) {
if (typeof uri == "string") {
uri = Services.io.newURI(uri, null, null);
}
@ -525,26 +525,26 @@ Zotero.Proxy.prototype.toProxy = function(uri) {
return proxyURL;
}
Zotero.Proxy.prototype.loadHosts = Zotero.Promise.coroutine(function* () {
Zotero.Proxy.prototype.loadHosts = async function () {
if (!this.proxyID) {
throw Error("Cannot load hosts without a proxyID")
}
this.hosts = yield Zotero.DB.columnQueryAsync(
this.hosts = await Zotero.DB.columnQueryAsync(
"SELECT hostname FROM proxyHosts WHERE proxyID = ? ORDER BY hostname", this.proxyID
);
});
};
Zotero.Proxies.DNS = new function() {
this.getHostnames = function() {
if (!Zotero.isWin && !Zotero.isMac && !Zotero.isLinux) return Zotero.Promise.resolve([]);
Zotero.Proxies.DNS = new function () {
this.getHostnames = function () {
if (!Zotero.isWin && !Zotero.isMac && !Zotero.isLinux) return Promise.resolve([]);
var deferred = Zotero.Promise.defer();
var worker = new ChromeWorker("chrome://zotero/content/xpcom/dns_worker.js");
Zotero.debug("Proxies.DNS: Performing reverse lookup");
worker.onmessage = function(e) {
worker.onmessage = function (e) {
Zotero.debug("Proxies.DNS: Got hostnames "+e.data);
deferred.resolve(e.data);
};
worker.onerror = function(e) {
worker.onerror = function (e) {
Zotero.debug("Proxies.DNS: Reverse lookup failed");
deferred.reject(e.message);
};

View file

@ -25,7 +25,7 @@
"use strict";
Zotero.QuickCopy = new function() {
Zotero.QuickCopy = new function () {
this.lastActiveURL = null;
var _initTimeoutID
@ -35,7 +35,7 @@ Zotero.QuickCopy = new function() {
var _siteSettings;
var _formattedNames;
this.init = Zotero.Promise.coroutine(function* () {
this.init = async function () {
Zotero.debug("Initializing Quick Copy");
if (!_initialized) {
@ -60,32 +60,31 @@ Zotero.QuickCopy = new function() {
// if an export format is selected
if (Zotero.test) return;
_initPromise = Zotero.Promise.each(
[
() => _loadOutputFormat(),
() => _loadNoteOutputFormat(),
() => this.loadSiteSettings()
],
f => f()
);
_initPromise = // FIXME: fx140: replace call to Zotero.Promise.each()
Zotero.Promise.each([
() => _loadOutputFormat(),
() => _loadNoteOutputFormat(),
() => this.loadSiteSettings()
], f => f());
}.bind(this));
});
};
this.uninit = function () {
_initCancelled = true;
// Cancel load if in progress
if (_initPromise) {
// FIXME: fx140: replace call to Zotero.Promise instance method 'cancel()'
_initPromise.cancel();
}
Zotero.Prefs.unregisterObserver(this._prefObserverID);
};
this.loadSiteSettings = Zotero.Promise.coroutine(function* () {
this.loadSiteSettings = async function () {
var sql = "SELECT key AS domainPath, value AS format FROM settings "
+ "WHERE setting='quickCopySite'";
var rows = yield Zotero.DB.queryAsync(sql);
var rows = await Zotero.DB.queryAsync(sql);
// Unproxify storage row
_siteSettings = rows.map(row => {
return {
@ -93,8 +92,9 @@ Zotero.QuickCopy = new function() {
format: row.format
};
});
yield Zotero.Promise.map(rows, row => _preloadFormat(row.format));
});
await // FIXME: fx140: replace call to Zotero.Promise.map()
Zotero.Promise.map(rows, row => _preloadFormat(row.format));
};
this.hasSiteSettings = function () {
@ -140,19 +140,19 @@ Zotero.QuickCopy = new function() {
};
this.getFormattedNameFromSetting = Zotero.Promise.coroutine(function* (setting) {
this.getFormattedNameFromSetting = async function (setting) {
if (!_formattedNames) {
yield _loadFormattedNames();
await _loadFormattedNames();
}
var format = this.unserializeSetting(setting);
var name = _formattedNames[format.mode + "=" + format.id];
return name ? name : '';
});
};
this.getSettingFromFormattedName = Zotero.Promise.coroutine(function* (name) {
this.getSettingFromFormattedName = async function (name) {
if (!_formattedNames) {
yield _loadFormattedNames();
await _loadFormattedNames();
}
for (var setting in _formattedNames) {
if (_formattedNames[setting] == name) {
@ -160,7 +160,7 @@ Zotero.QuickCopy = new function() {
}
}
return '';
});
};
this.getNoteFormat = function () {
var pref = Zotero.Prefs.get('export.noteQuickCopy.setting');
@ -168,7 +168,7 @@ Zotero.QuickCopy = new function() {
return pref;
};
this.getFormatFromURL = function(url) {
this.getFormatFromURL = function (url) {
var quickCopyPref = Zotero.Prefs.get("export.quickCopy.setting");
quickCopyPref = JSON.stringify(this.unserializeSetting(quickCopyPref));
@ -211,7 +211,7 @@ Zotero.QuickCopy = new function() {
}
// Give priority to longer domains, then longer paths
var sort = function(a, b) {
var sort = function (a, b) {
if (a.domainLength > b.domainLength) {
return -1;
}
@ -351,10 +351,10 @@ Zotero.QuickCopy = new function() {
*
* @return {Promise}
*/
var _loadOutputFormat = Zotero.Promise.coroutine(function* () {
var _loadOutputFormat = async function () {
var format = Zotero.Prefs.get("export.quickCopy.setting");
return _preloadFormat(format);
});
};
var _loadNoteOutputFormat = async function () {
@ -403,13 +403,12 @@ Zotero.QuickCopy = new function() {
return format.locale || Zotero.Prefs.get('export.quickCopy.locale');
}
var _loadFormattedNames = Zotero.Promise.coroutine(function* () {
var _loadFormattedNames = async function () {
var t = new Date;
Zotero.debug("Loading formatted names for Quick Copy");
var translation = new Zotero.Translate.Export;
var translators = yield translation.getTranslators();
var translators = await translation.getTranslators();
// add styles to list
_formattedNames = {};
@ -429,5 +428,5 @@ Zotero.QuickCopy = new function() {
}
Zotero.debug("Loaded formatted names for Quick Copy in " + (new Date - t) + " ms");
});
};
}

View file

@ -167,7 +167,7 @@ class ReaderInstance {
}
this.annotationItemIDs = annotationItems.map(x => x.id);
state = state || await this._getState();
state = state || (await this._getState());
await this._waitForReader();
@ -763,7 +763,7 @@ class ReaderInstance {
else if (!path.endsWith('.lua')) {
return null;
}
if (!await IOUtils.exists(path)) {
if (!(await IOUtils.exists(path))) {
return null;
}
return Cu.cloneInto(await IOUtils.read(path), this._iframeWindow);
@ -806,7 +806,7 @@ class ReaderInstance {
let fp = new FilePicker();
fp.init(this._window, Zotero.ftl.formatValueSync('reader-import-from-epub-prompt-title'), fp.modeOpen);
fp.appendFilter('EPUB Data', '*.epub; *.lua; *.opf');
if (await fp.show() !== fp.returnOK) {
if ((await fp.show()) !== fp.returnOK) {
return null;
}
return fp.file;
@ -932,7 +932,7 @@ class ReaderInstance {
item.setAttachmentLastPageIndex(state.scrollYPercent);
}
let file = Zotero.Attachments.getStorageDirectory(item);
if (!await OS.File.exists(file.path)) {
if (!(await OS.File.exists(file.path))) {
await Zotero.Attachments.createDirectoryForItem(item);
}
file.append(this.stateFileName);

View file

@ -224,7 +224,7 @@ Zotero.RecognizeDocument = new function () {
this.report = async function (item, description) {
var attachment = Zotero.Items.get(item.getAttachments()[0]);
var filePath = attachment.getFilePath();
if (!filePath || !await OS.File.exists(filePath)) {
if (!filePath || !(await OS.File.exists(filePath))) {
throw new Error("File not found when reporting metadata");
}
@ -395,7 +395,7 @@ Zotero.RecognizeDocument = new function () {
this._recognize = async function (item) {
let filePath = await item.getFilePath();
if (!filePath || !await OS.File.exists(filePath)) throw new Zotero.Exception.Alert('recognizePDF.fileNotFound');
if (!filePath || !(await OS.File.exists(filePath))) throw new Zotero.Exception.Alert('recognizePDF.fileNotFound');
if (item.isPDFAttachment()) {
return _recognizePDF(item, filePath);

View file

@ -309,7 +309,7 @@ Zotero.Retractions = {
promises.push(zp.setVirtual(libraryID, 'retracted', current));
zp.hideRetractionBanner();
}
await Zotero.Promise.all(promises);
await Promise.all(promises);
}
if (current) {
@ -925,7 +925,7 @@ Zotero.Retractions = {
_loadCacheFile: async function () {
var cacheFile = OS.Path.join(Zotero.Profile.dir, 'retractions.json');
if (!await OS.File.exists(cacheFile)) {
if (!(await OS.File.exists(cacheFile))) {
return;
}
var data = JSON.parse(await Zotero.File.getContentsAsync(cacheFile));

View file

@ -23,7 +23,7 @@
***** END LICENSE BLOCK *****
*/
Zotero.Schema = new function(){
Zotero.Schema = new function () {
this.dbInitialized = false;
this.goToChangeLog = false;
@ -62,7 +62,7 @@ Zotero.Schema = new function(){
*/
this.getDBVersion = function (schema) {
if (_dbVersions[schema]){
return Zotero.Promise.resolve(_dbVersions[schema]);
return Promise.resolve(_dbVersions[schema]);
}
var sql = "SELECT version FROM version WHERE schema='" + schema + "'";
@ -97,14 +97,14 @@ Zotero.Schema = new function(){
//
// 'compatibility' is incremented manually by upgrade steps in order to break DB
// compatibility with older versions.
var versions = await Zotero.Promise.all([
var versions = await Promise.all([
this.getDBVersion('userdata'), this.getDBVersion('compatibility')
]);
var [userdata, compatibility] = versions;
if (!userdata) {
Zotero.debug('Database does not exist -- creating\n');
return _initializeSchema()
.then(function() {
.then(function () {
// Don't load bundled files until after UI is ready, unless this is a test run,
// in which case tests can run without a window open
(!Zotero.test ? Zotero.uiReadyPromise : Zotero.initializationPromise)
@ -408,7 +408,7 @@ Zotero.Schema = new function(){
throw new Error("version not specified");
}
var dbVersion = await Zotero.Schema.getDBVersion('globalSchema') || null;
var dbVersion = (await Zotero.Schema.getDBVersion('globalSchema')) || null;
if (dbVersion > version) {
Zotero.debug(`Database has newer global schema (${dbVersion} > ${version}) `
+ `-- skipping update and using schema from DB`);
@ -715,7 +715,7 @@ Zotero.Schema = new function(){
//
// This is mostly temporary
// TEMP - NSF
this.importSchema = Zotero.Promise.coroutine(function* (str, uri) {
this.importSchema = async function (str, uri) {
var ps = Services.prompt;
if (!uri.match(/https?:\/\/([^\.]+\.)?zotero.org\//)) {
@ -739,9 +739,9 @@ Zotero.Schema = new function(){
var itemTypeID = Zotero.ID.get('customItemTypes');
yield Zotero.DB.queryAsync("PRAGMA foreign_keys=OFF");
await Zotero.DB.queryAsync("PRAGMA foreign_keys=OFF");
try {
yield Zotero.DB.executeTransaction(async function () {
await Zotero.DB.executeTransaction(async function () {
await Zotero.DB.queryAsync("INSERT INTO customItemTypes VALUES (?, 'nsfReviewer', 'NSF Reviewer', 1, 'chrome://zotero/skin/report_user.png')", itemTypeID);
var fields = [
@ -795,7 +795,7 @@ Zotero.Schema = new function(){
});
}
finally {
yield Zotero.DB.queryAsync("PRAGMA foreign_keys=ON");
await Zotero.DB.queryAsync("PRAGMA foreign_keys=ON");
}
var s = new Zotero.Search;
@ -803,7 +803,7 @@ Zotero.Schema = new function(){
s.addCondition('itemType', 'is', 'nsfReviewer');
s.addCondition('dateDue', 'isBefore', 'today');
s.addCondition('tag', 'isNot', 'Completed');
yield s.saveTx();
await s.saveTx();
ps.alert(null, "Zotero Item Type Added", "The 'NSF Reviewer' item type and 'Overdue NSF Reviewers' saved search have been installed.");
}
@ -820,15 +820,15 @@ Zotero.Schema = new function(){
var s2 = new Zotero.Search;
s2.addCondition('itemType', 'is', 'nsfReviewer');
s2.addCondition('deleted', 'true');
if ((yield s.search()).length || (yield s2.search()).length) {
if (((await s.search())).length || ((await s2.search())).length) {
ps.alert(null, "Error", "All 'NSF Reviewer' items must be deleted before the item type can be removed from Zotero.");
return;
}
Zotero.debug("Uninstalling nsfReviewer item type");
yield Zotero.DB.queryAsync("PRAGMA foreign_keys=OFF");
await Zotero.DB.queryAsync("PRAGMA foreign_keys=OFF");
try {
yield Zotero.DB.executeTransaction(async function () {
await Zotero.DB.executeTransaction(async function () {
await Zotero.DB.queryAsync("DELETE FROM customItemTypeFields WHERE customItemTypeID=?", itemTypeID - Zotero.ItemTypes.customIDOffset);
await Zotero.DB.queryAsync("DELETE FROM customBaseFieldMappings WHERE customItemTypeID=?", itemTypeID - Zotero.ItemTypes.customIDOffset);
var fields = Zotero.ItemFields.getItemTypeFields(itemTypeID);
@ -850,12 +850,12 @@ Zotero.Schema = new function(){
});
}
finally {
yield Zotero.DB.queryAsync("PRAGMA foreign_keys=ON");
await Zotero.DB.queryAsync("PRAGMA foreign_keys=ON");
}
ps.alert(null, "Zotero Item Type Removed", "The 'NSF Reviewer' item type has been uninstalled.");
}
});
};
async function _reloadSchema(options) {
await _updateCustomTables(options);
@ -1670,7 +1670,7 @@ Zotero.Schema = new function(){
Zotero.getTranslatorsDirectory();
Zotero.getStylesDirectory();
await Zotero.Promise.all(Zotero.Translators.reinit(), Zotero.Styles.reinit());
await Promise.all(Zotero.Translators.reinit(), Zotero.Styles.reinit());
var updated = await this.updateBundledFiles();
if (updated && Zotero.Prefs.get('automaticScraperUpdates')) {
await Zotero.Schema.updateFromRepository(this.REPO_UPDATE_MANUAL);
@ -1726,9 +1726,9 @@ Zotero.Schema = new function(){
this.integrityCheckRequired = async function () {
return !!await Zotero.DB.valueQueryAsync(
return !!(await Zotero.DB.valueQueryAsync(
"SELECT value FROM settings WHERE setting='db' AND key='integrityCheck'"
);
));
};
@ -2231,7 +2231,7 @@ Zotero.Schema = new function(){
* Requires a transaction
*/
var _updateSchema = async function (schema) {
var [dbVersion, schemaVersion] = await Zotero.Promise.all(
var [dbVersion, schemaVersion] = await Promise.all(
[Zotero.Schema.getDBVersion(schema), _getSchemaSQLVersion(schema)]
);
if (dbVersion == schemaVersion) {
@ -3448,7 +3448,7 @@ Zotero.Schema = new function(){
else if (i == 120) {
// Repeat 119 if it didn't go through
if (!await Zotero.DB.columnExists('itemAnnotations', 'authorName')) {
if (!(await Zotero.DB.columnExists('itemAnnotations', 'authorName'))) {
await Zotero.DB.queryAsync("CREATE TABLE itemAnnotationsTemp (\n itemID INTEGER PRIMARY KEY,\n parentItemID INT NOT NULL,\n type INTEGER NOT NULL,\n authorName TEXT,\n text TEXT,\n comment TEXT,\n color TEXT,\n pageLabel TEXT,\n sortIndex TEXT NOT NULL,\n position TEXT NOT NULL,\n isExternal INT NOT NULL,\n FOREIGN KEY (itemID) REFERENCES items(itemID) ON DELETE CASCADE,\n FOREIGN KEY (parentItemID) REFERENCES itemAttachments(itemID)\n)");
await Zotero.DB.queryAsync("INSERT INTO itemAnnotationsTemp SELECT itemID, parentItemID, type, '', text, comment, color, pageLabel, sortIndex, position, isExternal FROM itemAnnotations");
await Zotero.DB.queryAsync("DROP TABLE itemAnnotations");

View file

@ -26,7 +26,7 @@
var { HttpServer } = ChromeUtils.importESModule("chrome://remote/content/server/httpd.sys.mjs");
Components.utils.import("resource://gre/modules/NetUtil.jsm");
Zotero.Server = new function() {
Zotero.Server = new function () {
var _onlineObserverRegistered, serv;
this.responseCodes = {
200:"OK",
@ -101,7 +101,7 @@ Zotero.Server = new function() {
* Parses a query string into a key => value object
* @param {String} queryString Query string
*/
this.decodeQueryString = function(queryString) {
this.decodeQueryString = function (queryString) {
var splitData = queryString.split("&");
var decodedData = {};
for (let variable of splitData) {
@ -552,7 +552,7 @@ Zotero.Server.RequestHandler.prototype._requestFinished = function (responseBody
}
}
Zotero.Server.RequestHandler.prototype._decodeMultipartData = function(data) {
Zotero.Server.RequestHandler.prototype._decodeMultipartData = function (data) {
const contentDispositionRe = /^Content-Disposition:\s*(.*)$/i;
const contentTypeRe = /^Content-Type:\s*(.*)$/i

View file

@ -192,7 +192,7 @@ Zotero.Server.Connector = {
* Returns:
* Array of Zotero.Translator objects
*/
Zotero.Server.Connector.GetTranslators = function() {};
Zotero.Server.Connector.GetTranslators = function () {};
Zotero.Server.Endpoints["/connector/getTranslators"] = Zotero.Server.Connector.GetTranslators;
Zotero.Server.Connector.GetTranslators.prototype = {
supportedMethods: ["POST"],
@ -204,26 +204,26 @@ Zotero.Server.Connector.GetTranslators.prototype = {
* @param {Object} data POST data or GET query string
* @param {Function} sendResponseCallback function to send HTTP response
*/
init: function(data, sendResponseCallback) {
init: function (data, sendResponseCallback) {
// Translator data
var me = this;
if(data.url) {
Zotero.Translators.getWebTranslatorsForLocation(data.url, data.url).then(function(data) {
Zotero.Translators.getWebTranslatorsForLocation(data.url, data.url).then(function (data) {
sendResponseCallback(200, "application/json",
JSON.stringify(me._serializeTranslators(data[0])));
});
} else {
Zotero.Translators.getAll().then(function(translators) {
Zotero.Translators.getAll().then(function (translators) {
var responseData = me._serializeTranslators(translators);
sendResponseCallback(200, "application/json", JSON.stringify(responseData));
}).catch(function(e) {
}).catch(function (e) {
sendResponseCallback(500);
throw e;
});
}
},
_serializeTranslators: function(translators) {
_serializeTranslators: function (translators) {
var responseData = [];
let properties = ["translatorID", "translatorType", "label", "creator", "target", "targetAll",
"minVersion", "maxVersion", "priority", "browserSupport", "inRepository", "lastUpdated"];
@ -244,7 +244,7 @@ Zotero.Server.Connector.GetTranslators.prototype = {
*
* Returns a list of available translators as an array
*/
Zotero.Server.Connector.Detect = function() {};
Zotero.Server.Connector.Detect = function () {};
Zotero.Server.Endpoints["/connector/detect"] = Zotero.Server.Connector.Detect;
Zotero.Server.Connector.Detect.prototype = {
supportedMethods: ["POST"],
@ -254,7 +254,7 @@ Zotero.Server.Connector.Detect.prototype = {
/**
* Loads HTML into a hidden browser and initiates translator detection
*/
init: async function(requestData) {
init: async function (requestData) {
try {
var translators = await this.getTranslators(requestData);
} catch (e) {
@ -262,7 +262,7 @@ Zotero.Server.Connector.Detect.prototype = {
return 500;
}
translators = translators.map(function(translator) {
translators = translators.map(function (translator) {
return translator.serialize(TRANSLATOR_PASSING_PROPERTIES);
});
return [200, "application/json", JSON.stringify(translators)];
@ -299,7 +299,7 @@ Zotero.Server.Connector.Detect.prototype = {
* Returns:
* 201 response code with item in body.
*/
Zotero.Server.Connector.SaveItems = function() {};
Zotero.Server.Connector.SaveItems = function () {};
Zotero.Server.Endpoints["/connector/saveItems"] = Zotero.Server.Connector.SaveItems;
Zotero.Server.Connector.SaveItems.prototype = {
supportedMethods: ["POST"],
@ -606,7 +606,7 @@ Zotero.Server.Connector.SaveSingleFile.prototype = {
* Returns:
* Nothing (200 OK response)
*/
Zotero.Server.Connector.SaveSnapshot = function() {};
Zotero.Server.Connector.SaveSnapshot = function () {};
Zotero.Server.Endpoints["/connector/saveSnapshot"] = Zotero.Server.Connector.SaveSnapshot;
Zotero.Server.Connector.SaveSnapshot.prototype = {
supportedMethods: ["POST"],
@ -737,7 +737,7 @@ Zotero.Server.Connector.SaveAttachmentFromResolver.prototype = {
* 200 response on successful change
* 400 on error with 'error' property in JSON
*/
Zotero.Server.Connector.UpdateSession = function() {};
Zotero.Server.Connector.UpdateSession = function () {};
Zotero.Server.Endpoints["/connector/updateSession"] = Zotero.Server.Connector.UpdateSession;
Zotero.Server.Connector.UpdateSession.prototype = {
supportedMethods: ["POST"],
@ -800,7 +800,7 @@ Zotero.Server.Connector.DelaySync.prototype = {
* - Object[Item] an array of imported items
*/
Zotero.Server.Connector.Import = function() {};
Zotero.Server.Connector.Import = function () {};
Zotero.Server.Endpoints["/connector/import"] = Zotero.Server.Connector.Import;
Zotero.Server.Connector.Import.prototype = {
supportedMethods: ["POST"],
@ -861,27 +861,27 @@ Zotero.Server.Connector.Import.prototype = {
* - {name: styleName}
*/
Zotero.Server.Connector.InstallStyle = function() {};
Zotero.Server.Connector.InstallStyle = function () {};
Zotero.Server.Endpoints["/connector/installStyle"] = Zotero.Server.Connector.InstallStyle;
Zotero.Server.Connector.InstallStyle.prototype = {
supportedMethods: ["POST"],
supportedDataTypes: '*',
permitBookmarklet: false,
init: Zotero.Promise.coroutine(function* (requestData) {
init: async function (requestData) {
let dataString = requestData.data;
if (requestData.data instanceof Ci.nsIInputStream) {
dataString = Zotero.Server.networkStreamToString(dataString, requestData.headers['content-length']);
}
try {
var { styleTitle } = yield Zotero.Styles.install(
var { styleTitle } = await Zotero.Styles.install(
dataString, requestData.searchParams.get('origin') || null, true
);
} catch (e) {
return [400, "text/plain", e.message];
}
return [201, "application/json", JSON.stringify({name: styleTitle})];
})
}
};
/**
@ -892,7 +892,7 @@ Zotero.Server.Connector.InstallStyle.prototype = {
* Returns:
* code - translator code
*/
Zotero.Server.Connector.GetTranslatorCode = function() {};
Zotero.Server.Connector.GetTranslatorCode = function () {};
Zotero.Server.Endpoints["/connector/getTranslatorCode"] = Zotero.Server.Connector.GetTranslatorCode;
Zotero.Server.Connector.GetTranslatorCode.prototype = {
supportedMethods: ["POST"],
@ -904,9 +904,9 @@ Zotero.Server.Connector.GetTranslatorCode.prototype = {
* @param {String} data POST data or GET query string
* @param {Function} sendResponseCallback function to send HTTP response
*/
init: function(postData, sendResponseCallback) {
init: function (postData, sendResponseCallback) {
var translator = Zotero.Translators.get(postData.translatorID);
Zotero.Translators.getCodeForTranslator(translator).then(function(code) {
Zotero.Translators.getCodeForTranslator(translator).then(function (code) {
sendResponseCallback(200, "application/javascript", code);
});
}
@ -924,7 +924,7 @@ Zotero.Server.Connector.GetTranslatorCode.prototype = {
* collectionID
* collectionName
*/
Zotero.Server.Connector.GetSelectedCollection = function() {};
Zotero.Server.Connector.GetSelectedCollection = function () {};
Zotero.Server.Endpoints["/connector/getSelectedCollection"] = Zotero.Server.Connector.GetSelectedCollection;
Zotero.Server.Connector.GetSelectedCollection.prototype = {
supportedMethods: ["POST"],
@ -936,7 +936,7 @@ Zotero.Server.Connector.GetSelectedCollection.prototype = {
* @param {String} data POST data or GET query string
* @param {Function} sendResponseCallback function to send HTTP response
*/
init: async function(postData, sendResponseCallback) {
init: async function (postData, sendResponseCallback) {
let allowReadOnly = (postData.hasOwnProperty("switchToReadableLibrary")) ? !postData.switchToReadableLibrary : true;
var { library, collection, editable } = Zotero.Server.Connector.getSaveTarget(allowReadOnly);
var response = {
@ -1030,7 +1030,7 @@ Zotero.Server.Connector.GetSelectedCollection.prototype = {
* {Array} hostnames
*/
Zotero.Server.Connector.GetClientHostnames = {};
Zotero.Server.Connector.GetClientHostnames = function() {};
Zotero.Server.Connector.GetClientHostnames = function () {};
Zotero.Server.Endpoints["/connector/getClientHostnames"] = Zotero.Server.Connector.GetClientHostnames;
Zotero.Server.Connector.GetClientHostnames.prototype = {
supportedMethods: ["POST"],
@ -1040,14 +1040,14 @@ Zotero.Server.Connector.GetClientHostnames.prototype = {
/**
* Returns a 200 response to say the server is alive
*/
init: Zotero.Promise.coroutine(function* (requestData) {
init: async function (requestData) {
try {
var hostnames = yield Zotero.Proxies.DNS.getHostnames();
var hostnames = await Zotero.Proxies.DNS.getHostnames();
} catch(e) {
return 500;
}
return [200, "application/json", JSON.stringify(hostnames)];
})
}
};
/**
@ -1059,7 +1059,7 @@ Zotero.Server.Connector.GetClientHostnames.prototype = {
* {Array} hostnames
*/
Zotero.Server.Connector.Proxies = {};
Zotero.Server.Connector.Proxies = function() {};
Zotero.Server.Connector.Proxies = function () {};
Zotero.Server.Endpoints["/connector/proxies"] = Zotero.Server.Connector.Proxies;
Zotero.Server.Connector.Proxies.prototype = {
supportedMethods: ["POST"],
@ -1069,10 +1069,10 @@ Zotero.Server.Connector.Proxies.prototype = {
/**
* Returns a 200 response to say the server is alive
*/
init: Zotero.Promise.coroutine(function* () {
init: async function () {
let proxies = Zotero.Proxies.proxies.map((p) => Object.assign(p.toJSON(), {hosts: p.hosts}));
return [200, "application/json", JSON.stringify(proxies)];
})
}
};
@ -1084,7 +1084,7 @@ Zotero.Server.Connector.Proxies.prototype = {
* Returns:
* Nothing (200 OK response)
*/
Zotero.Server.Connector.Ping = function() {};
Zotero.Server.Connector.Ping = function () {};
Zotero.Server.Endpoints["/connector/ping"] = Zotero.Server.Connector.Ping;
Zotero.Server.Connector.Ping.prototype = {
supportedMethods: ["GET", "POST"],

View file

@ -23,14 +23,14 @@
***** END LICENSE BLOCK *****
*/
Zotero.Standalone = new function() {
Zotero.Standalone = new function () {
/**
* Stream listener proxy for AMO requests to replace Firefox's app ID with toolkit@mozilla.org.
* This means add-ons hosted at AMO will update properly for us.
*/
var AMOStreamListener = function() {};
var AMOStreamListener = function () {};
AMOStreamListener.prototype = {
"QueryInterface": function(arg) {
"QueryInterface": function (arg) {
if (!iid.equals(Components.interfaces.nsIStreamListener)
&& !iid.equals(Components.interfaces.nsIRequestObserver)
&& !iid.equals(Components.interfaces.nsISupports)) {
@ -39,14 +39,14 @@ Zotero.Standalone = new function() {
return this;
},
"onStartRequest": function(aRequest, aContext) {
"onStartRequest": function (aRequest, aContext) {
this._stream = Cc["@mozilla.org/binaryinputstream;1"].
createInstance(Ci.nsIBinaryInputStream);
this._bytes = "";
this.oldListener.onStartRequest(aRequest, aContext);
},
"onStopRequest": function(aRequest, aContext, aStatusCode) {
"onStopRequest": function (aRequest, aContext, aStatusCode) {
var requestFailed = !Components.isSuccessCode(aStatusCode);
if(!requestFailed && (aRequest instanceof Ci.nsIHttpChannel))
requestFailed = !aRequest.requestSucceeded;
@ -63,13 +63,13 @@ Zotero.Standalone = new function() {
this.oldListener.onStopRequest(aRequest, aContext, aStatusCode);
},
"onDataAvailable": function(aRequest, aContext, aInputStream, aOffset, aCount) {
"onDataAvailable": function (aRequest, aContext, aInputStream, aOffset, aCount) {
this._stream.setInputStream(aInputStream);
this._bytes += this._stream.readBytes(aCount);
}
};
this.init = function() {
this.init = function () {
// Set not offline
Services.io.offline = false;
@ -77,7 +77,7 @@ Zotero.Standalone = new function() {
Components.classes["@mozilla.org/observer-service;1"].
getService(Components.interfaces.nsIObserverService).
addObserver({
"observe":function(ch) {
"observe":function (ch) {
try {
if(ch.QueryInterface(Components.interfaces.nsIRequest).URI.host
!== "versioncheck.addons.mozilla.org") return;

View file

@ -80,7 +80,7 @@ Zotero.Sync.Storage.Engine = function (options) {
this.maxCheckAge = 10800; // maximum age in seconds for upload modification check (3 hours)
}
Zotero.Sync.Storage.Engine.prototype.start = Zotero.Promise.coroutine(function* () {
Zotero.Sync.Storage.Engine.prototype.start = async function () {
var libraryID = this.libraryID;
if (!Zotero.Sync.Storage.Local.getEnabledForLibrary(libraryID)) {
Zotero.debug("File sync is not enabled for " + this.library.name);
@ -93,14 +93,14 @@ Zotero.Sync.Storage.Engine.prototype.start = Zotero.Promise.coroutine(function*
Zotero.debug(`${this.controller.name} file sync is not active -- verifying`);
try {
yield this.controller.checkServer();
await this.controller.checkServer();
}
catch (e) {
let wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
let lastWin = wm.getMostRecentWindow("navigator:browser");
let success = yield this.controller.handleVerificationError(e, lastWin, true);
let success = await this.controller.handleVerificationError(e, lastWin, true);
if (!success) {
Zotero.debug(this.controller.name + " verification failed", 2);
@ -122,7 +122,7 @@ Zotero.Sync.Storage.Engine.prototype.start = Zotero.Promise.coroutine(function*
}
if (this.controller.cacheCredentials) {
yield this.controller.cacheCredentials();
await this.controller.cacheCredentials();
}
var lastSyncTime = null;
@ -155,18 +155,18 @@ Zotero.Sync.Storage.Engine.prototype.start = Zotero.Promise.coroutine(function*
&& this.local.lastFullFileCheck[libraryID]
&& (this.local.lastFullFileCheck[libraryID]
+ (this.maxCheckAge * 1000)) > new Date().getTime()) {
let itemIDs = yield this.local.getFilesToCheck(libraryID, this.maxCheckAge);
yield this.local.checkForUpdatedFiles(libraryID, itemIDs);
let itemIDs = await this.local.getFilesToCheck(libraryID, this.maxCheckAge);
await this.local.checkForUpdatedFiles(libraryID, itemIDs);
}
// Otherwise check all files in library
else {
this.local.lastFullFileCheck[libraryID] = new Date().getTime();
yield this.local.checkForUpdatedFiles(libraryID);
await this.local.checkForUpdatedFiles(libraryID);
}
yield this.local.resolveConflicts(libraryID);
await this.local.resolveConflicts(libraryID);
var downloadForced = yield this.local.checkForForcedDownloads(libraryID);
var downloadForced = await this.local.checkForForcedDownloads(libraryID);
// If we don't have any forced downloads, we can skip downloads if no storage metadata has
// changed (meaning nothing else has uploaded files since the last successful file sync)
@ -180,13 +180,13 @@ Zotero.Sync.Storage.Engine.prototype.start = Zotero.Promise.coroutine(function*
// Get files to download
if (downloadAll || downloadForced) {
let itemIDs = yield this.local.getFilesToDownload(libraryID, !downloadAll);
let itemIDs = await this.local.getFilesToDownload(libraryID, !downloadAll);
if (itemIDs.length) {
Zotero.debug(itemIDs.length + " file" + (itemIDs.length == 1 ? '' : 's') + " to "
+ "download for " + this.library.name);
for (let itemID of itemIDs) {
let item = yield Zotero.Items.getAsync(itemID);
yield this.queueItem(item);
let item = await Zotero.Items.getAsync(itemID);
await this.queueItem(item);
}
}
else {
@ -196,13 +196,13 @@ Zotero.Sync.Storage.Engine.prototype.start = Zotero.Promise.coroutine(function*
// Get files to upload
if (filesEditable) {
let itemIDs = yield this.local.getFilesToUpload(libraryID);
let itemIDs = await this.local.getFilesToUpload(libraryID);
if (itemIDs.length) {
Zotero.debug(itemIDs.length + " file" + (itemIDs.length == 1 ? '' : 's') + " to "
+ "upload for " + this.library.name);
for (let itemID of itemIDs) {
let item = yield Zotero.Items.getAsync(itemID, { noCache: true });
yield this.queueItem(item);
let item = await Zotero.Items.getAsync(itemID, { noCache: true });
await this.queueItem(item);
}
}
else {
@ -222,7 +222,7 @@ Zotero.Sync.Storage.Engine.prototype.start = Zotero.Promise.coroutine(function*
var downloadSuccessful = false;
var changes = new Zotero.Sync.Storage.Result;
for (let type of ['download', 'upload']) {
let results = yield promises[type];
let results = await promises[type];
let succeeded = 0;
let failed = 0;
@ -262,13 +262,13 @@ Zotero.Sync.Storage.Engine.prototype.start = Zotero.Promise.coroutine(function*
if (downloadSuccessful) {
this.library.storageDownloadNeeded = false;
this.library.storageVersion = this.library.libraryVersion;
yield this.library.saveTx();
await this.library.saveTx();
}
// For ZFS, this purges all files on server based on flag set when switching from ZFS
// to WebDAV in prefs. For WebDAV, this purges locally deleted files on server.
try {
yield this.controller.purgeDeletedStorageFiles(libraryID);
await this.controller.purgeDeletedStorageFiles(libraryID);
}
catch (e) {
Zotero.logError(e);
@ -277,7 +277,7 @@ Zotero.Sync.Storage.Engine.prototype.start = Zotero.Promise.coroutine(function*
// If WebDAV sync, purge orphaned files
if (downloadSuccessful && this.controller.mode == 'webdav') {
try {
yield this.controller.purgeOrphanedStorageFiles(libraryID);
await this.controller.purgeOrphanedStorageFiles(libraryID);
}
catch (e) {
Zotero.logError(e);
@ -291,7 +291,7 @@ Zotero.Sync.Storage.Engine.prototype.start = Zotero.Promise.coroutine(function*
Zotero.debug("Done with file sync for " + this.library.name);
return changes;
})
}
/**
@ -310,7 +310,7 @@ Zotero.Sync.Storage.Engine.prototype.stop = function (queueToStop) {
}
}
Zotero.Sync.Storage.Engine.prototype.queueItem = Zotero.Promise.coroutine(function* (item) {
Zotero.Sync.Storage.Engine.prototype.queueItem = async function (item) {
switch (item.attachmentSyncState) {
case Zotero.Sync.Storage.Local.SYNC_STATE_TO_DOWNLOAD:
case Zotero.Sync.Storage.Local.SYNC_STATE_FORCE_DOWNLOAD:
@ -334,7 +334,7 @@ Zotero.Sync.Storage.Engine.prototype.queueItem = Zotero.Promise.coroutine(functi
}
if (type == 'upload') {
if (!(yield item.fileExists())) {
if (!((await item.fileExists()))) {
Zotero.debug("File " + item.libraryKey + " not available to upload -- skipping");
return;
}
@ -355,4 +355,4 @@ Zotero.Sync.Storage.Engine.prototype.queueItem = Zotero.Promise.coroutine(functi
});
this.numRequests++;
this.requestsRemaining++;
})
}

View file

@ -153,7 +153,7 @@ Zotero.Sync.Storage.Local = {
*
* This includes files previously modified or opened externally via Zotero within maxCheckAge
*/
getFilesToCheck: Zotero.Promise.coroutine(function* (libraryID, maxCheckAge) {
getFilesToCheck: async function (libraryID, maxCheckAge) {
var minTime = new Date().getTime() - (maxCheckAge * 1000);
// Get files modified and synced since maxCheckAge
@ -167,7 +167,7 @@ Zotero.Sync.Storage.Local = {
this.SYNC_STATE_IN_SYNC,
minTime
];
var itemIDs = yield Zotero.DB.columnQueryAsync(sql, params);
var itemIDs = await Zotero.DB.columnQueryAsync(sql, params);
// Get files opened since maxCheckAge
itemIDs = itemIDs.concat(
@ -175,7 +175,7 @@ Zotero.Sync.Storage.Local = {
);
return Zotero.Utilities.arrayUnique(itemIDs);
}),
},
/**
@ -193,7 +193,7 @@ Zotero.Sync.Storage.Local = {
* @return {Promise} Promise resolving to TRUE if any items changed state,
* FALSE otherwise
*/
checkForUpdatedFiles: Zotero.Promise.coroutine(function* (libraryID, itemIDs, itemModTimes) {
checkForUpdatedFiles: async function (libraryID, itemIDs, itemModTimes) {
var libraryName = Zotero.Libraries.getName(libraryID);
var msg = "Checking for locally changed attachment files in " + libraryName;
@ -248,7 +248,7 @@ Zotero.Sync.Storage.Local = {
sql += " AND itemID IN (" + chunk.map(() => '?').join() + ")";
params = params.concat(chunk);
}
let chunkRows = yield Zotero.DB.queryAsync(sql, params);
let chunkRows = await Zotero.DB.queryAsync(sql, params);
if (chunkRows) {
rows = rows.concat(chunkRows);
}
@ -280,7 +280,7 @@ Zotero.Sync.Storage.Local = {
rows = null;
var t = new Date();
var items = yield Zotero.Items.getAsync(itemIDs, { noCache: true });
var items = await Zotero.Items.getAsync(itemIDs, { noCache: true });
var numItems = items.length;
var updatedStates = {};
@ -290,7 +290,7 @@ Zotero.Sync.Storage.Local = {
var statesToSet = {};
for (let item of items) {
// TODO: Catch error?
let state = yield this._checkForUpdatedFile(item, attachmentData[item.id]);
let state = await this._checkForUpdatedFile(item, attachmentData[item.id]);
if (state !== false) {
if (!statesToSet[state]) {
statesToSet[state] = [];
@ -301,7 +301,7 @@ Zotero.Sync.Storage.Local = {
}
// Update sync states in bulk
if (changed) {
yield Zotero.DB.executeTransaction(async function () {
await Zotero.DB.executeTransaction(async function () {
for (let state in statesToSet) {
await this.updateSyncStates(statesToSet[state], parseInt(state));
}
@ -315,10 +315,10 @@ Zotero.Sync.Storage.Local = {
Zotero.debug(`Checked ${numItems} files in ${libraryName} in ` + (new Date() - t) + " ms");
return changed;
}),
},
_checkForUpdatedFile: Zotero.Promise.coroutine(function* (item, attachmentData) {
_checkForUpdatedFile: async function (item, attachmentData) {
var lk = item.libraryKey;
Zotero.debug("Checking attachment file for item " + lk, 4);
@ -330,7 +330,7 @@ Zotero.Sync.Storage.Local = {
var fileName = PathUtils.filename(path);
try {
let { lastModified: fmtime } = yield IOUtils.stat(path);
let { lastModified: fmtime } = await IOUtils.stat(path);
//Zotero.debug("Memory usage: " + memmgr.resident);
//Zotero.debug("File modification time for item " + lk + " is " + fmtime);
@ -361,15 +361,15 @@ Zotero.Sync.Storage.Local = {
}
// If file hash matches stored hash, only the mod time changed, so skip
let fileHash = yield Zotero.Utilities.Internal.md5Async(path);
let fileHash = await Zotero.Utilities.Internal.md5Async(path);
var hash = attachmentData ? attachmentData.hash : (yield this.getSyncedHash(item.id));
var hash = attachmentData ? attachmentData.hash : ((await this.getSyncedHash(item.id)));
if (hash && hash == fileHash) {
Zotero.debug("Mod time didn't match (" + fmtime + " != " + mtime + ") "
+ "but hash did for " + fileName + " for item " + lk
+ " -- updating file mod time");
try {
yield IOUtils.setModificationTime(path, mtime);
await IOUtils.setModificationTime(path, mtime);
}
catch (e) {
Zotero.File.checkFileAccessError(e, path, 'update');
@ -394,7 +394,7 @@ Zotero.Sync.Storage.Local = {
}
throw e;
}
}),
},
/**
*
@ -429,14 +429,14 @@ Zotero.Sync.Storage.Local = {
return false;
},
checkForForcedDownloads: Zotero.Promise.coroutine(function* (libraryID) {
checkForForcedDownloads: async function (libraryID) {
// Forced downloads happen even in on-demand mode
var sql = "SELECT COUNT(*) FROM items JOIN itemAttachments USING (itemID) "
+ "WHERE libraryID=? AND syncState=?";
return !!(yield Zotero.DB.valueQueryAsync(
return !!((await Zotero.DB.valueQueryAsync(
sql, [libraryID, this.SYNC_STATE_FORCE_DOWNLOAD]
));
}),
)));
},
/**
@ -567,7 +567,7 @@ Zotero.Sync.Storage.Local = {
* @param {Boolean} data.compressed
* @return {Promise}
*/
processDownload: Zotero.Promise.coroutine(function* (data) {
processDownload: async function (data) {
if (!data) {
throw new Error("'data' not set");
}
@ -591,15 +591,15 @@ Zotero.Sync.Storage.Local = {
// TODO: Test file hash
if (data.compressed) {
var newPath = yield this._processZipDownload(item);
var newPath = await this._processZipDownload(item);
}
else {
var newPath = yield this._processSingleFileDownload(item);
var newPath = await this._processSingleFileDownload(item);
}
// If newPath is set, the file was renamed, so set item filename to that
// and mark for updated
var path = yield item.getFilePathAsync();
var path = await item.getFilePathAsync();
if (newPath && path != newPath) {
// If library isn't editable but filename was changed, update
// database without updating the item's mod time, which would result
@ -608,10 +608,10 @@ Zotero.Sync.Storage.Local = {
if (!Zotero.Items.isEditable(item)) {
Zotero.debug("File renamed without library access -- "
+ "updating itemAttachments path", 3);
yield item.relinkAttachmentFile(newPath, true);
await item.relinkAttachmentFile(newPath, true);
}
else {
yield item.relinkAttachmentFile(newPath);
await item.relinkAttachmentFile(newPath);
}
}
catch (e) {
@ -635,11 +635,11 @@ Zotero.Sync.Storage.Local = {
try {
// If hash not provided (e.g., WebDAV), calculate it now
if (!md5) {
md5 = yield item.attachmentHash;
md5 = await item.attachmentHash;
}
// Set the file mtime to the time from the server
yield OS.File.setDates(path, null, new Date(parseInt(mtime)));
await OS.File.setDates(path, null, new Date(parseInt(mtime)));
}
catch (e) {
Zotero.File.checkFileAccessError(e, path, 'update');
@ -648,23 +648,23 @@ Zotero.Sync.Storage.Local = {
item.attachmentSyncedModificationTime = mtime;
item.attachmentSyncedHash = md5;
item.attachmentSyncState = "in_sync";
yield item.saveTx({ skipAll: true });
await item.saveTx({ skipAll: true });
return new Zotero.Sync.Storage.Result({
localChanges: true
});
}),
},
_processSingleFileDownload: Zotero.Promise.coroutine(function* (item) {
_processSingleFileDownload: async function (item) {
var tempFilePath = OS.Path.join(Zotero.getTempDirectory().path, item.key + '.tmp');
if (!(yield OS.File.exists(tempFilePath))) {
if (!((await OS.File.exists(tempFilePath)))) {
Zotero.debug(tempFilePath, 1);
throw new Error("Downloaded file not found");
}
yield Zotero.Attachments.createDirectoryForItem(item);
await Zotero.Attachments.createDirectoryForItem(item);
var filename = item.attachmentFilename;
if (!filename) {
@ -708,7 +708,7 @@ Zotero.Sync.Storage.Local = {
// Abort if Windows path limitation would cause filenames to be overly truncated
if (Zotero.isWin && filename.length < 40) {
try {
yield OS.File.remove(path);
await OS.File.remove(path);
}
catch (e) {}
// TODO: localize
@ -723,11 +723,11 @@ Zotero.Sync.Storage.Local = {
}
try {
yield OS.File.move(tempFilePath, path);
await OS.File.move(tempFilePath, path);
}
catch (e) {
try {
yield OS.File.remove(tempFilePath);
await OS.File.remove(tempFilePath);
}
catch (e) {}
@ -736,10 +736,10 @@ Zotero.Sync.Storage.Local = {
// processDownload() needs to know that we're renaming the file
return renamed ? path : null;
}),
},
_processZipDownload: Zotero.Promise.coroutine(function* (item) {
_processZipDownload: async function (item) {
var zipFile = Zotero.getTempDirectory();
zipFile.append(item.key + '.tmp');
@ -781,7 +781,7 @@ Zotero.Sync.Storage.Local = {
var parentDir = Zotero.Attachments.getStorageDirectory(item).path;
try {
yield Zotero.Attachments.createDirectoryForItem(item);
await Zotero.Attachments.createDirectoryForItem(item);
}
catch (e) {
zipReader.close();
@ -857,7 +857,7 @@ Zotero.Sync.Storage.Local = {
renamed = true;
}
if (yield OS.File.exists(destPath)) {
if (await OS.File.exists(destPath)) {
var msg = "ZIP entry '" + filePath + "' already exists";
Zotero.logError(msg);
Zotero.debug(destPath);
@ -886,7 +886,7 @@ Zotero.Sync.Storage.Local = {
// Abort if Windows path limitation would cause filenames to be overly truncated
if (Zotero.isWin && shortened < 40) {
try {
yield OS.File.remove(destPath);
await OS.File.remove(destPath);
}
catch (e) {}
zipReader.close();
@ -913,7 +913,7 @@ Zotero.Sync.Storage.Local = {
}
catch (e) {
try {
yield OS.File.remove(destPath);
await OS.File.remove(destPath);
}
catch (e) {}
@ -935,7 +935,7 @@ Zotero.Sync.Storage.Local = {
Zotero.File.checkFileAccessError(e, destPath, 'create');
}
yield Zotero.File.setNormalFilePermissions(destPath);
await Zotero.File.setNormalFilePermissions(destPath);
// If we're renaming the main file, processDownload() needs to know
if (renamed) {
@ -969,16 +969,16 @@ Zotero.Sync.Storage.Local = {
}
return returnFile;
}),
},
/**
* @return {Promise<Object[]>} - A promise for an array of conflict objects
*/
getConflicts: Zotero.Promise.coroutine(function* (libraryID) {
getConflicts: async function (libraryID) {
var sql = "SELECT itemID, version FROM items JOIN itemAttachments USING (itemID) "
+ "WHERE libraryID=? AND syncState=?";
var rows = yield Zotero.DB.queryAsync(
var rows = await Zotero.DB.queryAsync(
sql,
[
{ int: libraryID },
@ -989,7 +989,7 @@ Zotero.Sync.Storage.Local = {
var { libraryID, key } = Zotero.Items.getLibraryAndKeyFromID(row.itemID);
return [key, row.version];
});
var cacheObjects = yield Zotero.Sync.Data.Local.getCacheObjects(
var cacheObjects = await Zotero.Sync.Data.Local.getCacheObjects(
'item', libraryID, keyVersionPairs
);
if (!cacheObjects.length) return [];
@ -998,13 +998,13 @@ Zotero.Sync.Storage.Local = {
cacheObjects.forEach(obj => cacheObjectsByKey[obj.key] = obj);
var items = [];
var localItems = yield Zotero.Items.getAsync(rows.map(row => row.itemID));
var localItems = await Zotero.Items.getAsync(rows.map(row => row.itemID));
for (let localItem of localItems) {
// Use the mtime for the dateModified field, since that's all that's shown in the
// CR window at the moment
let localItemJSON = localItem.toJSON();
localItemJSON.dateModified = Zotero.Date.dateToISO(
new Date(yield localItem.attachmentModificationTime)
new Date(await localItem.attachmentModificationTime)
);
let remoteItemJSON = cacheObjectsByKey[localItem.key];
@ -1025,11 +1025,11 @@ Zotero.Sync.Storage.Local = {
})
}
return items;
}),
},
resolveConflicts: Zotero.Promise.coroutine(function* (libraryID) {
var conflicts = yield this.getConflicts(libraryID);
resolveConflicts: async function (libraryID) {
var conflicts = await this.getConflicts(libraryID);
if (!conflicts.length) return false;
Zotero.debug("Reconciling conflicts for " + Zotero.Libraries.get(libraryID).name);
@ -1055,7 +1055,7 @@ Zotero.Sync.Storage.Local = {
return false;
}
yield Zotero.DB.executeTransaction(async function () {
await Zotero.DB.executeTransaction(async function () {
for (let i = 0; i < conflicts.length; i++) {
let conflict = conflicts[i];
// TEMP
@ -1087,5 +1087,5 @@ Zotero.Sync.Storage.Local = {
}
}.bind(this));
return true;
})
}
}

View file

@ -176,7 +176,7 @@ Zotero.Sync.Storage.Request.prototype.setChannel = function (channel) {
}
Zotero.Sync.Storage.Request.prototype.start = Zotero.Promise.coroutine(function* () {
Zotero.Sync.Storage.Request.prototype.start = async function () {
Zotero.debug("Starting " + this.type + " request " + this.name);
if (this._running) {
@ -194,7 +194,7 @@ Zotero.Sync.Storage.Request.prototype.start = Zotero.Promise.coroutine(function*
//
// The main sync logic is triggered here.
try {
var results = yield Zotero.Promise.all(this._onStart.map(f => f(this)));
var results = await Promise.all(this._onStart.map(f => f(this)));
var result = new Zotero.Sync.Storage.Result;
result.updateFromResults(results);
@ -227,7 +227,7 @@ Zotero.Sync.Storage.Request.prototype.start = Zotero.Promise.coroutine(function*
Zotero.Notifier.trigger('download', 'file', item.id);
}
}
});
};
Zotero.Sync.Storage.Request.prototype.isRunning = function () {

View file

@ -24,7 +24,7 @@ Zotero.Sync.Storage.Utilities = {
* @param {Zotero.Sync.Storage.Request} request
* @return {Promise<Boolean>} - True if the zip file was created, false otherwise
*/
createUploadFile: Zotero.Promise.coroutine(function* (request) {
createUploadFile: async function (request) {
var item = this.getItemFromRequest(request);
Zotero.debug("Creating ZIP file for item " + item.libraryKey);
@ -63,7 +63,7 @@ Zotero.Sync.Storage.Utilities = {
}
}
);
}),
},
/**

View file

@ -113,7 +113,7 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
return;
}
if (password == await this.getPassword()) {
if (password == (await this.getPassword())) {
Zotero.debug("WebDAV password hasn't changed");
return;
}
@ -226,8 +226,8 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
},
cacheCredentials: Zotero.Promise.coroutine(function* () {
yield this._init();
cacheCredentials: async function () {
await this._init();
if (this._cachedCredentials) {
Zotero.debug("WebDAV credentials are already cached");
@ -237,7 +237,7 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
Zotero.debug("Caching WebDAV credentials");
try {
var req = yield Zotero.HTTP.request(
var req = await Zotero.HTTP.request(
"OPTIONS",
this.rootURI,
{
@ -259,10 +259,10 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
}
throw e;
}
}),
},
clearCachedCredentials: function() {
clearCachedCredentials: function () {
Zotero.debug("WebDAV: Clearing cached credentials");
if (this._rootURI) {
Zotero.HTTP.CookieBlocker.removeURL(this._rootURI.spec);
@ -405,16 +405,16 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
},
uploadFile: Zotero.Promise.coroutine(function* (request) {
yield this._init();
uploadFile: async function (request) {
await this._init();
var item = Zotero.Sync.Storage.Utilities.getItemFromRequest(request);
var params = {
mtime: yield item.attachmentModificationTime,
md5: yield item.attachmentHash
mtime: await item.attachmentModificationTime,
md5: await item.attachmentHash
};
var metadata = yield this._getStorageFileMetadata(item, request);
var metadata = await this._getStorageFileMetadata(item, request);
if (!request.isRunning()) {
Zotero.debug("Upload request '" + request.name
@ -427,7 +427,7 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
!= Zotero.Sync.Storage.Local.SYNC_STATE_FORCE_UPLOAD) {
if (metadata.mtime) {
// Local file time
let fmtime = yield item.attachmentModificationTime;
let fmtime = await item.attachmentModificationTime;
// Remote prop time
let mtime = metadata.mtime;
@ -437,7 +437,7 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
let hash = metadata.md5;
if (hash) {
// Local file hash
let fhash = yield item.attachmentHash;
let fhash = await item.attachmentHash;
if (fhash != hash) {
changed = true;
}
@ -450,9 +450,9 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
item.attachmentSyncedHash = hash;
}
item.attachmentSyncState = "in_sync";
yield item.saveTx({ skipAll: true });
await item.saveTx({ skipAll: true });
// skipAll doesn't mark as unsynced, so do that separately
yield item.updateSynced(false);
await item.updateSynced(false);
return new Zotero.Sync.Storage.Result({
localChanges: true,
syncRequired: true
@ -476,12 +476,12 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
Zotero.debug(`Last synced mod time for item ${item.libraryKey} doesn't `
+ "match time on storage server but hash does -- using local file mtime");
yield this._setStorageFileMetadata(item);
await this._setStorageFileMetadata(item);
item.attachmentSyncedModificationTime = fmtime;
item.attachmentSyncState = "in_sync";
yield item.saveTx({ skipAll: true });
await item.saveTx({ skipAll: true });
// skipAll doesn't mark as unsynced, so do that separately
yield item.updateSynced(false);
await item.updateSynced(false);
return new Zotero.Sync.Storage.Result({
localChanges: true,
@ -497,7 +497,7 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
// that to the WebDAV value, since that's the one in conflict.
item.attachmentSyncedModificationTime = mtime;
item.attachmentSyncState = "in_conflict";
yield item.saveTx({ skipAll: true });
await item.saveTx({ skipAll: true });
return new Zotero.Sync.Storage.Result({
fileSyncRequired: true
@ -509,7 +509,7 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
}
}
var created = yield Zotero.Sync.Storage.Utilities.createUploadFile(request);
var created = await Zotero.Sync.Storage.Utilities.createUploadFile(request);
if (!created) {
return new Zotero.Sync.Storage.Result;
}
@ -524,7 +524,7 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
if (metadata) {
var propURI = this._getItemPropertyURI(item);
try {
yield Zotero.HTTP.request(
await Zotero.HTTP.request(
"DELETE",
propURI,
{
@ -550,13 +550,13 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
file = File.createFromFileName ? File.createFromFileName(file.path) : new File(file);
// File.createFromFileName() returns a Promise in Fx54+
if (file.then) {
file = yield file;
file = await file;
}
var uri = this._getItemURI(item);
try {
var req = yield Zotero.HTTP.request(
var req = await Zotero.HTTP.request(
"PUT",
uri,
{
@ -598,16 +598,16 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
request.setChannel(false);
return this._onUploadComplete(req, request, item, params);
}),
},
/**
* @return {Promise}
* @throws {Zotero.Sync.Storage.Mode.WebDAV.VerificationError|Error}
*/
checkServer: Zotero.Promise.coroutine(function* (options = {}) {
checkServer: async function (options = {}) {
// Clear URIs
yield this._init();
await this._init();
var parentURI = this.parentURI;
var uri = this.rootURI;
@ -625,7 +625,7 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
}
// Test whether URL is WebDAV-enabled
var req = yield Zotero.HTTP.request(
var req = await Zotero.HTTP.request(
"OPTIONS",
uri,
{
@ -661,7 +661,7 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
}
// Test whether Zotero directory exists
req = yield Zotero.HTTP.request("PROPFIND", uri, {
req = await Zotero.HTTP.request("PROPFIND", uri, {
body: xmlstr,
headers: Object.assign({}, headers, contentTypeXML),
successCodes: [207, 404],
@ -674,7 +674,7 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
// Test if missing files return 404s
let missingFileURI = uri.mutate().setSpec(uri.spec + "nonexistent.prop").finalize();
try {
req = yield Zotero.HTTP.request(
req = await Zotero.HTTP.request(
"GET",
missingFileURI,
{
@ -700,7 +700,7 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
// Test if Zotero directory is writable
let testFileURI = uri.mutate().setSpec(uri.spec + "zotero-test-file.prop").finalize();
req = yield Zotero.HTTP.request("PUT", testFileURI, {
req = await Zotero.HTTP.request("PUT", testFileURI, {
body: " ",
successCodes: [200, 201, 204],
requestObserver,
@ -708,7 +708,7 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
debug: true
});
req = yield Zotero.HTTP.request(
req = await Zotero.HTTP.request(
"GET",
testFileURI,
{
@ -722,7 +722,7 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
if (req.status == 200) {
// Delete test file
yield Zotero.HTTP.request(
await Zotero.HTTP.request(
"DELETE",
testFileURI,
{
@ -754,7 +754,7 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
// Zotero directory wasn't found, so see if at least
// the parent directory exists
req = yield Zotero.HTTP.request("PROPFIND", parentURI, {
req = await Zotero.HTTP.request("PROPFIND", parentURI, {
headers: Object.assign({}, headers, contentTypeXML),
body: xmlstr,
requestObserver,
@ -778,7 +778,7 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
this.verified = true;
Zotero.debug(this.name + " file sync is successfully set up");
}),
},
/**
@ -786,7 +786,7 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
*
* @return bool True if the verification eventually succeeded, false otherwise
*/
handleVerificationError: Zotero.Promise.coroutine(function* (err, window, skipSuccessMessage) {
handleVerificationError: async function (err, window, skipSuccessMessage) {
var promptService = Services.prompt;
var errorTitle, errorMsg;
@ -866,7 +866,7 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
}
try {
yield this._createServerDirectory();
await this._createServerDirectory();
}
catch (e) {
if (e instanceof Zotero.HTTP.UnexpectedStatusException) {
@ -885,7 +885,7 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
}
try {
yield this.checkServer();
await this.checkServer();
return true;
}
catch (e) {
@ -932,7 +932,7 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
Zotero.Utilities.Internal.errorPrompt(errorTitle, e);
}
return false;
}),
},
/**
@ -940,13 +940,13 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
*
* @param {Integer} libraryID
*/
purgeDeletedStorageFiles: Zotero.Promise.coroutine(function* (libraryID) {
yield this._init();
purgeDeletedStorageFiles: async function (libraryID) {
await this._init();
var d = new Date();
Zotero.debug("Purging deleted storage files");
var files = yield Zotero.Sync.Storage.Local.getDeletedFiles(libraryID);
var files = await Zotero.Sync.Storage.Local.getDeletedFiles(libraryID);
if (!files.length) {
Zotero.debug("No files to delete remotely");
return false;
@ -955,7 +955,7 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
// Add .zip extension
var files = files.map(file => file + ".zip");
var results = yield this._deleteStorageFiles(files)
var results = await this._deleteStorageFiles(files)
// Remove deleted and nonexistent files from storage delete log
var toPurge = Zotero.Utilities.arrayUnique(
@ -964,7 +964,7 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
.map(val => val.replace(/\.(prop|zip)$/, ""))
);
if (toPurge.length > 0) {
yield Zotero.Utilities.Internal.forEachChunkAsync(
await Zotero.Utilities.Internal.forEachChunkAsync(
toPurge,
Zotero.DB.MAX_BOUND_PARAMETERS - 1,
function (chunk) {
@ -981,14 +981,14 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
Zotero.debug(results);
return results;
}),
},
/**
* Delete orphaned storage files older than a week before last sync time
*/
purgeOrphanedStorageFiles: Zotero.Promise.coroutine(function* () {
yield this._init();
purgeOrphanedStorageFiles: async function () {
await this._init();
var d = new Date();
const libraryID = Zotero.Libraries.userLibraryID;
@ -1025,7 +1025,7 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
return false;
}
var req = yield Zotero.HTTP.request(
var req = await Zotero.HTTP.request(
"PROPFIND",
uri,
{
@ -1044,7 +1044,7 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
};
var syncQueueKeys = new Set(
yield Zotero.Sync.Data.Local.getObjectsFromSyncQueue('item', libraryID)
await Zotero.Sync.Data.Local.getObjectsFromSyncQueue('item', libraryID)
);
var deleteFiles = [];
var trailingSlash = !!path.match(/\/$/);
@ -1100,7 +1100,7 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
}
let key = file.replace(/\.(zip|prop)$/, '');
let item = yield Zotero.Items.getByLibraryAndKeyAsync(libraryID, key);
let item = await Zotero.Items.getByLibraryAndKeyAsync(libraryID, key);
if (item) {
Zotero.debug("Skipping existing file " + file);
continue;
@ -1130,14 +1130,14 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
}
}
var results = yield this._deleteStorageFiles(deleteFiles);
var results = await this._deleteStorageFiles(deleteFiles);
Zotero.Prefs.set("lastWebDAVOrphanPurge", Math.round(new Date().getTime() / 1000));
Zotero.debug(`Purged orphaned storage files in ${new Date() - d} ms`);
Zotero.debug(results);
return results;
}),
},
//
@ -1150,11 +1150,11 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
* @param {Zotero.Sync.Storage.Request} request
* @return {Object} - Object with 'mtime' and 'md5'
*/
_getStorageFileMetadata: Zotero.Promise.coroutine(function* (item, request) {
_getStorageFileMetadata: async function (item, request) {
var uri = this._getItemPropertyURI(item);
try {
var req = yield Zotero.HTTP.request(
var req = await Zotero.HTTP.request(
"GET",
uri,
{
@ -1235,7 +1235,7 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
let msg = "Invalid mod date '" + Zotero.Utilities.ellipsize(mtime, 20)
+ "' for item " + item.libraryKey;
Zotero.logError(msg);
yield this._deleteStorageFiles([item.key + ".prop"]).catch(function (e) {
await this._deleteStorageFiles([item.key + ".prop"]).catch(function (e) {
Zotero.logError(e);
});
throw new Error(Zotero.Sync.Storage.Mode.WebDAV.defaultError);
@ -1245,7 +1245,7 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
mtime: parseInt(mtime),
md5
};
}),
},
/**
@ -1253,11 +1253,11 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
*
* @param {Zotero.Item} item
*/
_setStorageFileMetadata: Zotero.Promise.coroutine(function* (item) {
_setStorageFileMetadata: async function (item) {
var uri = this._getItemPropertyURI(item);
var mtime = yield item.attachmentModificationTime;
var md5 = yield item.attachmentHash;
var mtime = await item.attachmentModificationTime;
var md5 = await item.attachmentHash;
var xmlstr = '<properties version="1">'
+ '<mtime>' + mtime + '</mtime>'
@ -1265,7 +1265,7 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
+ '</properties>';
try {
yield Zotero.HTTP.request(
await Zotero.HTTP.request(
"PUT",
uri,
{
@ -1286,25 +1286,25 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
}
throw e;
}
}),
},
_onUploadComplete: Zotero.Promise.coroutine(function* (req, request, item, params) {
_onUploadComplete: async function (req, request, item, params) {
Zotero.debug("Upload of attachment " + item.key + " finished with status code " + req.status);
Zotero.debug(req.responseText);
// Update .prop file on WebDAV server
yield this._setStorageFileMetadata(item);
await this._setStorageFileMetadata(item);
item.attachmentSyncedModificationTime = params.mtime;
item.attachmentSyncedHash = params.md5;
item.attachmentSyncState = "in_sync";
yield item.saveTx({ skipAll: true });
await item.saveTx({ skipAll: true });
// skipAll doesn't mark as unsynced, so do that separately
yield item.updateSynced(false);
await item.updateSynced(false);
try {
yield OS.File.remove(
await OS.File.remove(
OS.Path.join(Zotero.getTempDirectory().path, item.key + '.zip')
);
}
@ -1317,7 +1317,7 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
remoteChanges: true,
syncRequired: true
});
}),
},
_onUploadCancel: function (httpRequest, status, data) {
@ -1397,7 +1397,7 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
* @return {Object} - Object with properties 'deleted', 'missing', and 'error', each
* each containing filenames
*/
_deleteStorageFiles: Zotero.Promise.coroutine(function* (files) {
_deleteStorageFiles: async function (files) {
var results = {
deleted: new Set(),
missing: new Set(),
@ -1424,10 +1424,10 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
var funcs = [];
for (let i = 0 ; i < files.length; i++) {
let fileName = files[i];
funcs.push(Zotero.Promise.coroutine(function* () {
funcs.push(async function () {
var deleteURI = this.rootURI.mutate().setSpec(this.rootURI.spec + fileName).finalize();
try {
var req = yield Zotero.HTTP.request(
var req = await Zotero.HTTP.request(
"DELETE",
deleteURI,
{
@ -1469,7 +1469,7 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
}
// Delete property file
var req = yield Zotero.HTTP.request(
var req = await Zotero.HTTP.request(
"DELETE",
deletePropURI,
{
@ -1489,7 +1489,7 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
results.missing.add(fileName);
break;
}
}.bind(this)));
}.bind(this));
}
Components.utils.import("resource://zotero/concurrentCaller.js");
@ -1499,14 +1499,14 @@ Zotero.Sync.Storage.Mode.WebDAV.prototype = {
logger: msg => Zotero.debug(msg),
onError: e => Zotero.logError(e)
});
yield caller.start(funcs);
await caller.start(funcs);
// Convert sets back to arrays
for (let i in results) {
results[i] = Array.from(results[i]);
}
return results;
}),
},
_throwFriendlyError: function (method, url, status) {

View file

@ -209,9 +209,9 @@ Zotero.Sync.Storage.Mode.ZFS.prototype = {
},
uploadFile: Zotero.Promise.coroutine(function* (request) {
uploadFile: async function (request) {
var item = Zotero.Sync.Storage.Utilities.getItemFromRequest(request);
var isZipUpload = yield this._isZipUpload(item);
var isZipUpload = await this._isZipUpload(item);
// If we got a quota error for this library, skip upload for all zipped attachments
// and for single-file attachments that are bigger than the remaining space. This is cleared
@ -227,7 +227,7 @@ Zotero.Sync.Storage.Mode.ZFS.prototype = {
let size;
try {
// API rounds megabytes to 1 decimal place
size = ((yield OS.File.stat(item.getFilePath())).size / 1024 / 1024).toFixed(1);
size = (((await OS.File.stat(item.getFilePath()))).size / 1024 / 1024).toFixed(1);
}
catch (e) {
Zotero.logError(e);
@ -243,19 +243,19 @@ Zotero.Sync.Storage.Mode.ZFS.prototype = {
Zotero.debug(`${remaining} MB remaining in storage -- skipping further uploads`);
request.engine.stop('upload');
}
throw yield this._getQuotaError(item);
throw await this._getQuotaError(item);
}
}
if (isZipUpload) {
let created = yield Zotero.Sync.Storage.Utilities.createUploadFile(request);
let created = await Zotero.Sync.Storage.Utilities.createUploadFile(request);
if (!created) {
return new Zotero.Sync.Storage.Result;
}
}
try {
return yield this._processUploadFile(request);
return await this._processUploadFile(request);
}
catch (e) {
// Stop trying to upload files if we hit a quota error and there's very little space
@ -269,17 +269,17 @@ Zotero.Sync.Storage.Mode.ZFS.prototype = {
}
throw e;
}
}),
},
/**
* Remove all synced files from the server
*/
purgeDeletedStorageFiles: Zotero.Promise.coroutine(function* (libraryID) {
purgeDeletedStorageFiles: async function (libraryID) {
if (libraryID != Zotero.Libraries.userLibraryID) return;
var sql = "SELECT value FROM settings WHERE setting=? AND key=?";
var values = yield Zotero.DB.columnQueryAsync(sql, ['storage', 'zfsPurge']);
var values = await Zotero.DB.columnQueryAsync(sql, ['storage', 'zfsPurge']);
if (!values.length) {
return false;
}
@ -289,11 +289,11 @@ Zotero.Sync.Storage.Mode.ZFS.prototype = {
var params = this._getRequestParams(libraryID, "removestoragefiles");
var uri = this.apiClient.buildRequestURI(params);
yield Zotero.HTTP.request("POST", uri, "");
await Zotero.HTTP.request("POST", uri, "");
var sql = "DELETE FROM settings WHERE setting=? AND key=?";
yield Zotero.DB.queryAsync(sql, ['storage', 'zfsPurge']);
}),
await Zotero.DB.queryAsync(sql, ['storage', 'zfsPurge']);
},
//
@ -315,12 +315,12 @@ Zotero.Sync.Storage.Mode.ZFS.prototype = {
* @param {Zotero.Item} item
* @return {Object|String} - Object with upload params or 'exists'
*/
_getFileUploadParameters: Zotero.Promise.coroutine(function* (item) {
_getFileUploadParameters: async function (item) {
var funcName = "Zotero.Sync.Storage.ZFS._getFileUploadParameters()";
var path = item.getFilePath();
var filename = PathUtils.filename(path);
var zip = yield this._isZipUpload(item);
var zip = await this._isZipUpload(item);
if (zip) {
var uploadPath = OS.Path.join(Zotero.getTempDirectory().path, item.key + '.zip');
}
@ -375,13 +375,13 @@ Zotero.Sync.Storage.Mode.ZFS.prototype = {
// Build POST body
var params = {
mtime: yield item.attachmentModificationTime,
md5: yield item.attachmentHash,
mtime: await item.attachmentModificationTime,
md5: await item.attachmentHash,
filename,
filesize: (yield OS.File.stat(uploadPath)).size
filesize: ((await OS.File.stat(uploadPath))).size
};
if (zip) {
params.zipMD5 = yield Zotero.Utilities.Internal.md5Async(uploadPath);
params.zipMD5 = await Zotero.Utilities.Internal.md5Async(uploadPath);
params.zipFilename = PathUtils.filename(uploadPath);
}
var body = [];
@ -393,7 +393,7 @@ Zotero.Sync.Storage.Mode.ZFS.prototype = {
var req;
while (true) {
try {
req = yield this.apiClient.makeRequest(
req = await this.apiClient.makeRequest(
"POST",
uri,
{
@ -416,7 +416,7 @@ Zotero.Sync.Storage.Mode.ZFS.prototype = {
throw e;
}
let result = yield this._handleUploadAuthorizationFailure(req, item);
let result = await this._handleUploadAuthorizationFailure(req, item);
if (result instanceof Zotero.Sync.Storage.Result) {
return result;
}
@ -469,7 +469,7 @@ Zotero.Sync.Storage.Mode.ZFS.prototype = {
}
return json;
}),
},
/**
@ -477,7 +477,7 @@ Zotero.Sync.Storage.Mode.ZFS.prototype = {
*
* These must be included in successCodes in _getFileUploadParameters()
*/
_handleUploadAuthorizationFailure: Zotero.Promise.coroutine(function* (req, item) {
_handleUploadAuthorizationFailure: async function (req, item) {
//
// These must be included in successCodes above.
// TODO: 429?
@ -496,7 +496,7 @@ Zotero.Sync.Storage.Mode.ZFS.prototype = {
else if (req.status == 404) {
Zotero.logError(`Item ${item.libraryID}/${item.key} not found in upload authorization `
+ 'request -- marking for upload');
yield Zotero.Sync.Data.Local.markObjectAsUnsynced(item);
await Zotero.Sync.Data.Local.markObjectAsUnsynced(item);
return new Zotero.Sync.Storage.Result({
syncRequired: true
});
@ -509,7 +509,7 @@ Zotero.Sync.Storage.Mode.ZFS.prototype = {
if (version > item.version) {
// Mark object for redownloading, in case the library version is up to date and
// it's just the attachment item that somehow didn't get updated
yield Zotero.Sync.Data.Local.addObjectsToSyncQueue(
await Zotero.Sync.Data.Local.addObjectsToSyncQueue(
'item', item.libraryID, [item.key], true
);
return new Zotero.Sync.Storage.Result({
@ -519,7 +519,7 @@ Zotero.Sync.Storage.Mode.ZFS.prototype = {
// Get updated item metadata
let library = Zotero.Libraries.get(item.libraryID);
let { json, error } = yield this.apiClient.downloadObjects(
let { json, error } = await this.apiClient.downloadObjects(
library.libraryType,
library.libraryTypeID,
'item',
@ -533,13 +533,13 @@ Zotero.Sync.Storage.Mode.ZFS.prototype = {
throw new Error("More than one result for item lookup");
}
yield Zotero.Sync.Data.Local.saveCacheObjects('item', item.libraryID, json);
await Zotero.Sync.Data.Local.saveCacheObjects('item', item.libraryID, json);
json = json[0];
if (json.data.version > item.version) {
// Mark object for redownloading, in case the library version is up to date and
// it's just the attachment item that somehow didn't get updated
yield Zotero.Sync.Data.Local.addObjectsToSyncQueue(
await Zotero.Sync.Data.Local.addObjectsToSyncQueue(
'item', item.libraryID, [item.key], true
);
return new Zotero.Sync.Storage.Result({
@ -547,8 +547,8 @@ Zotero.Sync.Storage.Mode.ZFS.prototype = {
});
}
let fileHash = yield item.attachmentHash;
let fileModTime = yield item.attachmentModificationTime;
let fileHash = await item.attachmentHash;
let fileModTime = await item.attachmentModificationTime;
Zotero.debug("MD5");
Zotero.debug(json.data.md5);
@ -558,13 +558,13 @@ Zotero.Sync.Storage.Mode.ZFS.prototype = {
item.attachmentSyncedModificationTime = fileModTime;
item.attachmentSyncedHash = fileHash;
item.attachmentSyncState = "in_sync";
yield item.saveTx({ skipAll: true });
await item.saveTx({ skipAll: true });
return new Zotero.Sync.Storage.Result;
}
item.attachmentSyncState = "in_conflict";
yield item.saveTx({ skipAll: true });
await item.saveTx({ skipAll: true });
return new Zotero.Sync.Storage.Result({
fileSyncRequired: true
@ -586,33 +586,33 @@ Zotero.Sync.Storage.Mode.ZFS.prototype = {
let quota = req.getResponseHeader('Zotero-Storage-Quota');
Zotero.Sync.Storage.Local.storageRemainingForLibrary.set(item.libraryID, quota - usage);
throw yield this._getQuotaError(item);
throw await this._getQuotaError(item);
}
}),
},
/**
* Given parameters from authorization, upload file to S3
*/
_uploadFile: Zotero.Promise.coroutine(function* (request, item, params) {
_uploadFile: async function (request, item, params) {
if (request.isFinished()) {
Zotero.debug("Upload request " + request.name + " is no longer running after getting "
+ "upload parameters");
return new Zotero.Sync.Storage.Result;
}
var file = yield this._getUploadFile(item);
var file = await this._getUploadFile(item);
Components.utils.importGlobalProperties(["File"]);
file = File.createFromFileName ? File.createFromFileName(file.path) : new File(file);
// File.createFromFileName() returns a Promise in Fx54+
if (file.then) {
file = yield file;
file = await file;
}
var blob = new Blob([params.prefix, file, params.suffix]);
try {
var req = yield Zotero.HTTP.request(
var req = await Zotero.HTTP.request(
"POST",
params.url,
{
@ -664,7 +664,7 @@ Zotero.Sync.Storage.Mode.ZFS.prototype = {
this._s3ConsecutiveFailures++;
Zotero.debug("Delaying " + item.libraryKey + " upload for "
+ this._s3Backoff + " seconds", 2);
yield Zotero.Promise.delay(this._s3Backoff * 1000);
await Zotero.Promise.delay(this._s3Backoff * 1000);
return this._uploadFile(request, item, params);
}
}
@ -686,13 +686,13 @@ Zotero.Sync.Storage.Mode.ZFS.prototype = {
request.setChannel(false);
return this._onUploadComplete(req, request, item, params);
}),
},
/**
* Post-upload file registration with API
*/
_onUploadComplete: Zotero.Promise.coroutine(function* (req, request, item, params) {
_onUploadComplete: async function (req, request, item, params) {
var uploadKey = params.uploadKey;
Zotero.debug("Upload of attachment " + item.key + " finished with status code " + req.status);
@ -720,7 +720,7 @@ Zotero.Sync.Storage.Mode.ZFS.prototype = {
// Register upload on server
try {
req = yield this.apiClient.makeRequest(
req = await this.apiClient.makeRequest(
"POST",
uri,
{
@ -751,13 +751,13 @@ Zotero.Sync.Storage.Mode.ZFS.prototype = {
}
params.version = version;
yield this._updateItemFileInfo(item, params);
await this._updateItemFileInfo(item, params);
return new Zotero.Sync.Storage.Result({
localChanges: true,
remoteChanges: true
});
}),
},
/**
@ -765,9 +765,9 @@ Zotero.Sync.Storage.Mode.ZFS.prototype = {
* library version returned by the upload request, and save a modified version of the item
* to the sync cache
*/
_updateItemFileInfo: Zotero.Promise.coroutine(function* (item, params) {
_updateItemFileInfo: async function (item, params) {
// Mark as in-sync
yield Zotero.DB.executeTransaction(async function () {
await Zotero.DB.executeTransaction(async function () {
// Store file mod time and hash
item.attachmentSyncedModificationTime = params.mtime;
item.attachmentSyncedHash = params.md5;
@ -792,26 +792,26 @@ Zotero.Sync.Storage.Mode.ZFS.prototype = {
});
try {
if (yield this._isZipUpload(item)) {
if (await this._isZipUpload(item)) {
var file = Zotero.getTempDirectory();
file.append(item.key + '.zip');
yield OS.File.remove(file.path);
await OS.File.remove(file.path);
}
}
catch (e) {
Components.utils.reportError(e);
}
}),
},
_onUploadCancel: Zotero.Promise.coroutine(function* (httpRequest, status, data) {
_onUploadCancel: async function (httpRequest, status, data) {
var request = data.request;
var item = data.item;
Zotero.debug("Upload of attachment " + item.key + " cancelled with status code " + status);
try {
if (yield this._isZipUpload(item)) {
if (await this._isZipUpload(item)) {
var file = Zotero.getTempDirectory();
file.append(item.key + '.zip');
file.remove(false);
@ -820,11 +820,11 @@ Zotero.Sync.Storage.Mode.ZFS.prototype = {
catch (e) {
Components.utils.reportError(e);
}
}),
},
_getUploadFile: Zotero.Promise.coroutine(function* (item) {
if (yield this._isZipUpload(item)) {
_getUploadFile: async function (item) {
if (await this._isZipUpload(item)) {
var file = Zotero.getTempDirectory();
var filename = item.key + '.zip';
file.append(filename);
@ -833,7 +833,7 @@ Zotero.Sync.Storage.Mode.ZFS.prototype = {
var file = item.getFile();
}
return file;
}),
},
/**
@ -844,14 +844,14 @@ Zotero.Sync.Storage.Mode.ZFS.prototype = {
* @return {Promise<Object>|false} - Promise for object with 'hash', 'filename', 'mtime',
* 'compressed', or false if item not found
*/
_getStorageFileInfo: Zotero.Promise.coroutine(function* (item, request) {
_getStorageFileInfo: async function (item, request) {
var funcName = "Zotero.Sync.Storage.ZFS._getStorageFileInfo()";
var params = this._getRequestParams(item.libraryID, `items/${item.key}/file`);
var uri = this.apiClient.buildRequestURI(params);
try {
let req = yield this.apiClient.makeRequest(
let req = await this.apiClient.makeRequest(
"GET",
uri,
{
@ -907,7 +907,7 @@ Zotero.Sync.Storage.Mode.ZFS.prototype = {
throw e;
}
}),
},
/**
@ -916,7 +916,7 @@ Zotero.Sync.Storage.Mode.ZFS.prototype = {
* @param {Zotero.Sync.Storage.Request} request
* @return {Promise}
*/
_processUploadFile: Zotero.Promise.coroutine(function* (request) {
_processUploadFile: async function (request) {
/*
updateSizeMultiplier(
(100 - Zotero.Sync.Storage.compressionTracker.ratio) / 100
@ -985,9 +985,9 @@ Zotero.Sync.Storage.Mode.ZFS.prototype = {
}
}*/
var result = yield this._getFileUploadParameters(item);
var result = await this._getFileUploadParameters(item);
if (result.exists) {
yield this._updateItemFileInfo(item, result);
await this._updateItemFileInfo(item, result);
return new Zotero.Sync.Storage.Result({
localChanges: true,
remoteChanges: true
@ -997,7 +997,7 @@ Zotero.Sync.Storage.Mode.ZFS.prototype = {
return result;
}
return this._uploadFile(request, item, result);
}),
},
_isZipUpload: async function (item) {

View file

@ -23,7 +23,7 @@
***** END LICENSE BLOCK *****
*/
Zotero.Styles = new function() {
Zotero.Styles = new function () {
var _initialized = false;
var _initializationDeferred = false;
var _styles, _visibleStyles;
@ -56,15 +56,15 @@ Zotero.Styles = new function() {
/**
* Initializes styles cache, loading metadata for styles into memory
*/
this.init = Zotero.Promise.coroutine(function* (options = {}) {
this.init = async function (options = {}) {
if (Zotero.Prefs.get('cite.useCiteprocRs')) {
yield Zotero.CiteprocRs.init();
await Zotero.CiteprocRs.init();
}
// Wait until bundled files have been updated, except when this is called by the schema update
// code itself
if (!options.fromSchemaUpdate) {
yield Zotero.Schema.schemaUpdatePromise;
await Zotero.Schema.schemaUpdatePromise;
}
// If an initialization has already started, a regular init() call should return the promise
@ -73,7 +73,7 @@ Zotero.Styles = new function() {
if (_initializationDeferred) {
let promise = _initializationDeferred.promise;
if (options.reinit) {
yield promise;
await promise;
}
else {
return promise;
@ -98,16 +98,16 @@ Zotero.Styles = new function() {
// main dir
var dir = Zotero.getStylesDirectory().path;
var num = yield _readStylesFromDirectory(dir, false);
var num = await _readStylesFromDirectory(dir, false);
// hidden dir
var hiddenDir = OS.Path.join(dir, 'hidden');
if (yield OS.File.exists(hiddenDir)) {
num += yield _readStylesFromDirectory(hiddenDir, true);
if (await OS.File.exists(hiddenDir)) {
num += await _readStylesFromDirectory(hiddenDir, true);
}
// Sort visible styles by title
_visibleStyles.sort(function(a, b) {
_visibleStyles.sort(function (a, b) {
return a.title.localeCompare(b.title);
})
// .. and freeze, so they can be returned directly
@ -120,7 +120,7 @@ Zotero.Styles = new function() {
var locales = {};
var primaryDialects = {};
localeFile = JSON.parse(
yield Zotero.File.getResourceAsync("chrome://zotero/content/locale/csl/locales.json")
await Zotero.File.getResourceAsync("chrome://zotero/content/locale/csl/locales.json")
);
primaryDialects = localeFile["primary-dialects"];
@ -135,7 +135,7 @@ Zotero.Styles = new function() {
// Load renamed styles
_renamedStyles = JSON.parse(
yield Zotero.File.getResourceAsync("resource://zotero/schema/renamed-styles.json")
await Zotero.File.getResourceAsync("resource://zotero/schema/renamed-styles.json")
);
_initializationDeferred.resolve();
@ -144,7 +144,7 @@ Zotero.Styles = new function() {
// Styles are fully loaded, but we still need to trigger citeproc reloads in Integration
// so that style updates are reflected in open documents
Zotero.Integration.resetSessionStyles();
});
};
this.reinit = function (options = {}) {
return this.init(Object.assign({}, options, { reinit: true }));
@ -162,13 +162,13 @@ Zotero.Styles = new function() {
* Reads all styles from a given directory and caches their metadata
* @private
*/
var _readStylesFromDirectory = Zotero.Promise.coroutine(function* (dir, hidden) {
var _readStylesFromDirectory = async function (dir, hidden) {
var numCached = 0;
var iterator = new OS.File.DirectoryIterator(dir);
try {
while (true) {
let entries = yield iterator.nextBatch(10); // TODO: adjust as necessary
let entries = await iterator.nextBatch(10); // TODO: adjust as necessary
if (!entries.length) break;
for (let i = 0; i < entries.length; i++) {
@ -180,7 +180,7 @@ Zotero.Styles = new function() {
|| entry.isDir) continue;
try {
let code = yield Zotero.File.getContentsAsync(path);
let code = await Zotero.File.getContentsAsync(path);
var style = new Zotero.Style(code, path);
}
catch (e) {
@ -208,7 +208,7 @@ Zotero.Styles = new function() {
iterator.close();
}
return numCached;
});
};
/**
* Gets a style with a given ID
@ -288,7 +288,7 @@ Zotero.Styles = new function() {
* displayed in dialogs referencing the style
* @param {Boolean} [silent=false] Skip prompts
*/
this.install = Zotero.Promise.coroutine(function* (style, origin, silent=false) {
this.install = async function (style, origin, silent=false) {
var warnDeprecated;
if (style instanceof Components.interfaces.nsIFile) {
warnDeprecated = true;
@ -303,12 +303,12 @@ Zotero.Styles = new function() {
try {
if (style.file) {
style.string = yield Zotero.File.getContentsAsync(style.file);
style.string = await Zotero.File.getContentsAsync(style.file);
}
else if (style.url) {
style.string = yield Zotero.File.getContentsFromURLAsync(style.url);
style.string = await Zotero.File.getContentsFromURLAsync(style.url);
}
var { styleTitle, styleID } = yield _install(style.string, origin, false, silent);
var { styleTitle, styleID } = await _install(style.string, origin, false, silent);
}
catch (error) {
// Unless user cancelled, show an alert with the error
@ -331,7 +331,7 @@ Zotero.Styles = new function() {
}
}
return { styleTitle, styleID };
});
};
/**
* Installs a style
@ -342,8 +342,8 @@ Zotero.Styles = new function() {
* @param {Boolean} [silent=false] Skip prompts
* @return {Promise}
*/
var _install = Zotero.Promise.coroutine(function* (style, origin, hidden, silent=false) {
if (!_initialized) yield Zotero.Styles.init();
var _install = async function (style, origin, hidden, silent=false) {
if (!_initialized) await Zotero.Styles.init();
var existingFile, destFile, source;
@ -443,8 +443,8 @@ Zotero.Styles = new function() {
}
}
yield Zotero.Styles.validate(style)
.catch(function(validationErrors) {
await Zotero.Styles.validate(style)
.catch(function (validationErrors) {
Zotero.logError("Style from " + origin + " failed to validate:\n\n" + validationErrors);
// If validation fails on the parent of a dependent style, ignore it (for now)
@ -470,8 +470,8 @@ Zotero.Styles = new function() {
// Need to fetch source
if(source.substr(0, 7) === "http://" || source.substr(0, 8) === "https://") {
try {
let xmlhttp = yield Zotero.HTTP.request("GET", source);
yield _install(xmlhttp.responseText, origin, true);
let xmlhttp = await Zotero.HTTP.request("GET", source);
await _install(xmlhttp.responseText, origin, true);
}
catch (e) {
if (typeof e === "object" && e instanceof Zotero.Exception.Alert) {
@ -496,23 +496,23 @@ Zotero.Styles = new function() {
// Remove any existing file with a different name
if(existingFile) existingFile.remove(false);
yield Zotero.File.putContentsAsync(destFile, style);
await Zotero.File.putContentsAsync(destFile, style);
yield Zotero.Styles.reinit();
await Zotero.Styles.reinit();
// Refresh preferences windows
var enumerator = Services.wm.getEnumerator("zotero:pref");
while(enumerator.hasMoreElements()) {
var win = enumerator.getNext();
if(win.Zotero_Preferences.Cite) {
yield win.Zotero_Preferences.Cite.refreshStylesList(styleID);
await win.Zotero_Preferences.Cite.refreshStylesList(styleID);
}
}
return {
styleTitle: existingTitle || title,
styleID: styleID
};
});
};
/**
* Populate menulist with locales
@ -702,7 +702,7 @@ Zotero.Style = function (style, path) {
* @param {String} [format] Output format one of [rtf, html, text]
* @param {Boolean} [automaticJournalAbbreviations] Whether to automatically abbreviate titles
*/
Zotero.Style.prototype.getCiteProc = function(locale, format, automaticJournalAbbreviations) {
Zotero.Style.prototype.getCiteProc = function (locale, format, automaticJournalAbbreviations) {
locale = locale || Zotero.locale || 'en-US';
format = format || 'text';
automaticJournalAbbreviations = !!automaticJournalAbbreviations;
@ -879,7 +879,7 @@ Zotero.Style.prototype.__defineGetter__("class",
* Retrieves the style class, either from the metadata that's already loaded or by loading the file
* @type String
*/
function() {
function () {
if(this.source) {
// use class from source style
var parentStyle = Zotero.Styles.get(this.source);
@ -897,7 +897,7 @@ Zotero.Style.prototype.__defineGetter__("hasBibliography",
* loaded or by loading the file
* @type String
*/
function() {
function () {
if(this.source) {
// use hasBibliography from source style
var parentStyle = Zotero.Styles.get(this.source);
@ -914,7 +914,7 @@ Zotero.Style.prototype.__defineGetter__("usesAbbreviation",
* Retrieves the style class, either from the metadata that's already loaded or by loading the file
* @type String
*/
function() {
function () {
if(this.source) {
var parentStyle = Zotero.Styles.get(this.source);
if(!parentStyle) return false;
@ -928,7 +928,7 @@ Zotero.Style.prototype.__defineGetter__("independentFile",
* Retrieves the file corresponding to the independent CSL
* (the parent if this style is dependent, or this style if it is not)
*/
function() {
function () {
if(this.source) {
// parent/child
var formatCSL = Zotero.Styles.get(this.source);
@ -946,7 +946,7 @@ function() {
* Retrieves the XML corresponding to this style
* @type String
*/
Zotero.Style.prototype.getXML = function() {
Zotero.Style.prototype.getXML = function () {
var indepFile = this.independentFile;
if(indepFile) return Zotero.File.getContents(indepFile);
return this.string;
@ -955,7 +955,7 @@ Zotero.Style.prototype.getXML = function() {
/**
* Deletes a style
*/
Zotero.Style.prototype.remove = Zotero.Promise.coroutine(function* () {
Zotero.Style.prototype.remove = async function () {
if (!this.path) {
throw new Error("Cannot delete a style with no associated file")
}
@ -974,11 +974,11 @@ Zotero.Style.prototype.remove = Zotero.Promise.coroutine(function* () {
if(dependentStyles) {
// copy dependent styles to hidden directory
let hiddenDir = OS.Path.join(Zotero.getStylesDirectory().path, 'hidden');
yield Zotero.File.createDirectoryIfMissingAsync(hiddenDir);
yield OS.File.move(this.path, OS.Path.join(hiddenDir, PathUtils.filename(this.path)));
await Zotero.File.createDirectoryIfMissingAsync(hiddenDir);
await OS.File.move(this.path, OS.Path.join(hiddenDir, PathUtils.filename(this.path)));
} else {
// remove defunct files
yield OS.File.remove(this.path);
await OS.File.remove(this.path);
}
// check to see if this style depended on a hidden one
@ -999,10 +999,10 @@ Zotero.Style.prototype.remove = Zotero.Promise.coroutine(function* () {
// if it was only this style with the dependency, delete the source
if(deleteSource) {
yield source.remove();
await source.remove();
}
}
}
return Zotero.Styles.reinit();
});
};

View file

@ -24,7 +24,7 @@
*/
Zotero.Sync = new function() {
Zotero.Sync = new function () {
// Keep in sync with syncObjectTypes table
this.__defineGetter__('syncObjects', function () {
return {
@ -398,7 +398,7 @@ Zotero.Sync.Server = new function () {
}
Zotero.Sync.Server.Data = new function() {
Zotero.Sync.Server.Data = new function () {
/**
* @param {String} itemTypes
* @param {String} localName

View file

@ -50,19 +50,19 @@ Zotero.Sync.APIClient.prototype = {
UPLOAD_TIMEOUT: 120000,
getKeyInfo: Zotero.Promise.coroutine(function* (options={}) {
getKeyInfo: async function (options={}) {
var uri = this.baseURL + "keys/current";
let opts = {};
Object.assign(opts, options);
opts.successCodes = [200, 403, 404];
var xmlhttp = yield this.makeRequest("GET", uri, opts);
var xmlhttp = await this.makeRequest("GET", uri, opts);
if (xmlhttp.status == 403) {
return false;
}
var json = this._parseJSON(xmlhttp.responseText);
delete json.key;
return json;
}),
},
/**
@ -70,13 +70,13 @@ Zotero.Sync.APIClient.prototype = {
*
* Note: This is the version for group metadata, not library data.
*/
getGroupVersions: Zotero.Promise.coroutine(function* (userID) {
getGroupVersions: async function (userID) {
if (!userID) throw new Error("User ID not provided");
var uri = this.baseURL + "users/" + userID + "/groups?format=versions";
var xmlhttp = yield this.makeRequest("GET", uri);
var xmlhttp = await this.makeRequest("GET", uri);
return this._parseJSON(xmlhttp.responseText);
}),
},
/**
* Get group metadata for userID
@ -84,35 +84,35 @@ Zotero.Sync.APIClient.prototype = {
* @param {Integer} userID
* @return {Object} - Group metadata response
*/
getGroups: Zotero.Promise.coroutine(function* (userID) {
getGroups: async function (userID) {
if (!userID) throw new Error("User ID not provided");
var uri = this.baseURL + "users/" + userID + "/groups";
return yield this.getPaginatedResults(
return await this.getPaginatedResults(
uri,
(previous, xmlhttp, restart) => [...previous, ...this._parseJSON(xmlhttp.responseText)],
[]
);
}),
},
/**
* @param {Integer} groupID
* @return {Object|false} - Group metadata response, or false if group not found
*/
getGroup: Zotero.Promise.coroutine(function* (groupID) {
getGroup: async function (groupID) {
if (!groupID) throw new Error("Group ID not provided");
var uri = this.baseURL + "groups/" + groupID;
var xmlhttp = yield this.makeRequest("GET", uri, { successCodes: [200, 404] });
var xmlhttp = await this.makeRequest("GET", uri, { successCodes: [200, 404] });
if (xmlhttp.status == 404) {
return false;
}
return this._parseJSON(xmlhttp.responseText);
}),
},
getSettings: Zotero.Promise.coroutine(function* (libraryType, libraryTypeID, since) {
getSettings: async function (libraryType, libraryTypeID, since) {
var params = {
libraryType: libraryType,
libraryTypeID: libraryTypeID,
@ -130,7 +130,7 @@ Zotero.Sync.APIClient.prototype = {
"If-Modified-Since-Version": since
};
}
var xmlhttp = yield this.makeRequest("GET", uri, options);
var xmlhttp = await this.makeRequest("GET", uri, options);
if (xmlhttp.status == 304) {
return false;
}
@ -138,14 +138,14 @@ Zotero.Sync.APIClient.prototype = {
libraryVersion: this._getLastModifiedVersion(xmlhttp),
settings: this._parseJSON(xmlhttp.responseText)
};
}),
},
/**
* @return {Object|false} - An object with 'libraryVersion' and a 'deleted' object, or
* false if 'since' is earlier than the beginning of the delete log
*/
getDeleted: Zotero.Promise.coroutine(function* (libraryType, libraryTypeID, since) {
getDeleted: async function (libraryType, libraryTypeID, since) {
var params = {
target: "deleted",
libraryType: libraryType,
@ -153,7 +153,7 @@ Zotero.Sync.APIClient.prototype = {
since: since || 0
};
var uri = this.buildRequestURI(params);
var xmlhttp = yield this.makeRequest("GET", uri, { successCodes: [200, 409] });
var xmlhttp = await this.makeRequest("GET", uri, { successCodes: [200, 409] });
if (xmlhttp.status == 409) {
Zotero.debug(`'since' value '${since}' is earlier than the beginning of the delete log`);
return false;
@ -162,7 +162,7 @@ Zotero.Sync.APIClient.prototype = {
libraryVersion: this._getLastModifiedVersion(xmlhttp),
deleted: this._parseJSON(xmlhttp.responseText)
};
}),
},
getKeys: async function (libraryType, libraryTypeID, queryParams) {
@ -207,7 +207,7 @@ Zotero.Sync.APIClient.prototype = {
* @return {Promise<Object>|false} - Object with 'libraryVersion' and 'results', or false if
* nothing changed since specified library version
*/
getVersions: Zotero.Promise.coroutine(function* (libraryType, libraryTypeID, objectType, queryParams) {
getVersions: async function (libraryType, libraryTypeID, objectType, queryParams) {
var objectTypePlural = Zotero.DataObjectUtilities.getObjectTypePlural(objectType);
var params = {
@ -235,7 +235,7 @@ Zotero.Sync.APIClient.prototype = {
var options = {
successCodes: [200, 304]
};
var xmlhttp = yield this.makeRequest("GET", uri, options);
var xmlhttp = await this.makeRequest("GET", uri, options);
if (xmlhttp.status == 304) {
return false;
}
@ -247,7 +247,7 @@ Zotero.Sync.APIClient.prototype = {
libraryVersion: libraryVersion,
versions: this._parseJSON(xmlhttp.responseText)
};
}),
},
/**
@ -330,7 +330,7 @@ Zotero.Sync.APIClient.prototype = {
},
uploadSettings: Zotero.Promise.coroutine(function* (libraryType, libraryTypeID, libraryVersion, settings) {
uploadSettings: async function (libraryType, libraryTypeID, libraryVersion, settings) {
var method = "POST";
var objectType = "setting";
var objectTypePlural = "settings";
@ -348,7 +348,7 @@ Zotero.Sync.APIClient.prototype = {
};
var uri = this.buildRequestURI(params);
var xmlhttp = yield this.makeRequest(method, uri, {
var xmlhttp = await this.makeRequest(method, uri, {
headers: {
"Content-Type": "application/json",
"If-Unmodified-Since-Version": libraryVersion
@ -358,10 +358,10 @@ Zotero.Sync.APIClient.prototype = {
});
this._check412(xmlhttp);
return this._getLastModifiedVersion(xmlhttp);
}),
},
uploadObjects: Zotero.Promise.coroutine(function* (libraryType, libraryTypeID, method, libraryVersion, objectType, objects) {
uploadObjects: async function (libraryType, libraryTypeID, method, libraryVersion, objectType, objects) {
if (method != 'POST' && method != 'PATCH') {
throw new Error("Invalid method '" + method + "'");
}
@ -381,7 +381,7 @@ Zotero.Sync.APIClient.prototype = {
};
var uri = this.buildRequestURI(params);
var xmlhttp = yield this.makeRequest(method, uri, {
var xmlhttp = await this.makeRequest(method, uri, {
headers: {
"Content-Type": "application/json",
"If-Unmodified-Since-Version": libraryVersion
@ -395,10 +395,10 @@ Zotero.Sync.APIClient.prototype = {
libraryVersion: this._getLastModifiedVersion(xmlhttp),
results: this._parseJSON(xmlhttp.responseText)
};
}),
},
uploadDeletions: Zotero.Promise.coroutine(function* (libraryType, libraryTypeID, libraryVersion, objectType, keys) {
uploadDeletions: async function (libraryType, libraryTypeID, libraryVersion, objectType, keys) {
var objectTypePlural = Zotero.DataObjectUtilities.getObjectTypePlural(objectType);
Zotero.debug(`Uploading ${keys.length} ${objectType} deletion`
@ -418,7 +418,7 @@ Zotero.Sync.APIClient.prototype = {
params[objectType + "Key"] = keys.join(",");
}
var uri = this.buildRequestURI(params);
var xmlhttp = yield this.makeRequest("DELETE", uri, {
var xmlhttp = await this.makeRequest("DELETE", uri, {
headers: {
"If-Unmodified-Since-Version": libraryVersion
},
@ -427,10 +427,10 @@ Zotero.Sync.APIClient.prototype = {
});
this._check412(xmlhttp);
return this._getLastModifiedVersion(xmlhttp);
}),
},
getFullTextVersions: Zotero.Promise.coroutine(function* (libraryType, libraryTypeID, since) {
getFullTextVersions: async function (libraryType, libraryTypeID, since) {
var params = {
libraryType: libraryType,
libraryTypeID: libraryTypeID,
@ -444,22 +444,22 @@ Zotero.Sync.APIClient.prototype = {
// TODO: Use pagination
var uri = this.buildRequestURI(params);
var xmlhttp = yield this.makeRequest("GET", uri);
var xmlhttp = await this.makeRequest("GET", uri);
return {
libraryVersion: this._getLastModifiedVersion(xmlhttp),
versions: this._parseJSON(xmlhttp.responseText)
};
}),
},
getFullTextForItem: Zotero.Promise.coroutine(function* (libraryType, libraryTypeID, itemKey) {
getFullTextForItem: async function (libraryType, libraryTypeID, itemKey) {
var params = {
libraryType: libraryType,
libraryTypeID: libraryTypeID,
target: `items/${itemKey}/fulltext`
};
var uri = this.buildRequestURI(params);
var xmlhttp = yield this.makeRequest("GET", uri, { successCodes: [200, 404] });
var xmlhttp = await this.makeRequest("GET", uri, { successCodes: [200, 404] });
if (xmlhttp.status == 404) {
return false;
}
@ -471,17 +471,17 @@ Zotero.Sync.APIClient.prototype = {
version: this._getLastModifiedVersion(xmlhttp),
data: this._parseJSON(xmlhttp.responseText)
};
}),
},
setFullTextForItems: Zotero.Promise.coroutine(function* (libraryType, libraryTypeID, libraryVersion, data) {
setFullTextForItems: async function (libraryType, libraryTypeID, libraryVersion, data) {
var params = {
libraryType: libraryType,
libraryTypeID: libraryTypeID,
target: "fulltext"
};
var uri = this.buildRequestURI(params);
var xmlhttp = yield this.makeRequest(
var xmlhttp = await this.makeRequest(
"POST",
uri,
{
@ -500,10 +500,10 @@ Zotero.Sync.APIClient.prototype = {
libraryVersion: this._getLastModifiedVersion(xmlhttp),
results: this._parseJSON(xmlhttp.responseText)
};
}),
},
createAPIKeyFromCredentials: Zotero.Promise.coroutine(function* (username, password) {
createAPIKeyFromCredentials: async function (username, password) {
var body = JSON.stringify({
username,
password,
@ -527,7 +527,7 @@ Zotero.Sync.APIClient.prototype = {
"Content-Type": "application/json"
};
var uri = this.baseURL + "keys";
var response = yield this.makeRequest("POST", uri, {
var response = await this.makeRequest("POST", uri, {
body, headers, successCodes: [201, 403], noAPIKey: true
});
if (response.status == 403) {
@ -540,13 +540,13 @@ Zotero.Sync.APIClient.prototype = {
}
return json;
}),
},
// Deletes current API key
deleteAPIKey: Zotero.Promise.coroutine(function* () {
yield this.makeRequest("DELETE", this.baseURL + "keys/current");
}),
deleteAPIKey: async function () {
await this.makeRequest("DELETE", this.baseURL + "keys/current");
},
buildRequestURI: function (params) {
@ -604,7 +604,7 @@ Zotero.Sync.APIClient.prototype = {
for (let index in queryParams) {
let value = queryParams[index];
if (Array.isArray(value)) {
value.forEach(function(v, i) {
value.forEach(function (v, i) {
queryParamsArray.push(encodeURIComponent(index) + '=' + encodeURIComponent(v));
});
}
@ -629,7 +629,7 @@ Zotero.Sync.APIClient.prototype = {
},
makeRequest: Zotero.Promise.coroutine(function* (method, uri, options = {}) {
makeRequest: async function (method, uri, options = {}) {
if (!this.apiKey && !options.noAPIKey) {
throw new Error('API key not set');
}
@ -664,9 +664,9 @@ Zotero.Sync.APIClient.prototype = {
var tries = 0;
while (true) {
var result = yield this.caller.start(Zotero.Promise.coroutine(function* () {
var result = await this.caller.start(async function () {
try {
var xmlhttp = yield Zotero.HTTP.request(method, uri, opts);
var xmlhttp = await Zotero.HTTP.request(method, uri, opts);
this._checkBackoff(xmlhttp);
this.rateDelayPosition = 0;
return xmlhttp;
@ -684,13 +684,13 @@ Zotero.Sync.APIClient.prototype = {
}
throw e;
}
}.bind(this)));
}.bind(this));
if (result) {
return result;
}
}
}),
},
/**
@ -705,12 +705,12 @@ Zotero.Sync.APIClient.prototype = {
* @param {mixed} initialValue
* @return {mixed} - The reduced value
*/
getPaginatedResults: Zotero.Promise.coroutine(function* (initialURL, reducer, initialValue) {
getPaginatedResults: async function (initialURL, reducer, initialValue) {
let url = initialURL;
let accumulator;
let restart = false;
while (true) {
let xmlhttp = yield this.makeRequest("GET", url);
let xmlhttp = await this.makeRequest("GET", url);
accumulator = reducer(
accumulator === undefined ? initialValue : accumulator,
xmlhttp,
@ -733,7 +733,7 @@ Zotero.Sync.APIClient.prototype = {
}
}
return accumulator;
}),
},
/**

View file

@ -91,12 +91,12 @@ Zotero.Sync.Data.Engine.prototype.UPLOAD_RESULT_OBJECT_CONFLICT = 4;
Zotero.Sync.Data.Engine.prototype.UPLOAD_RESULT_RESTART = 5;
Zotero.Sync.Data.Engine.prototype.UPLOAD_RESULT_CANCEL = 6;
Zotero.Sync.Data.Engine.prototype.start = Zotero.Promise.coroutine(function* () {
Zotero.Sync.Data.Engine.prototype.start = async function () {
Zotero.debug("Starting data sync for " + this.library.name);
// TODO: Handle new/changed user when setting key
if (this.library.libraryType == 'user' && !this.libraryTypeID) {
let info = yield this.apiClient.getKeyInfo();
let info = await this.apiClient.getKeyInfo();
Zotero.debug("Got userID " + info.userID + " for API key");
this.libraryTypeID = info.userID;
}
@ -107,10 +107,10 @@ Zotero.Sync.Data.Engine.prototype.start = Zotero.Promise.coroutine(function* ()
// Check if we've synced this library with the current architecture yet
var libraryVersion = this.library.libraryVersion;
if (this.resetMode == Zotero.Sync.Runner.RESET_MODE_TO_SERVER) {
yield this._restoreToServer();
await this._restoreToServer();
}
else if (!libraryVersion || libraryVersion == -1) {
let versionResults = yield this._upgradeCheck();
let versionResults = await this._upgradeCheck();
if (versionResults) {
libraryVersion = this.library.libraryVersion;
}
@ -127,7 +127,7 @@ Zotero.Sync.Data.Engine.prototype.start = Zotero.Promise.coroutine(function* ()
// Version results won't be available if an upgrade happened on a previous run but the
// full sync failed.
if (libraryVersion == -1) {
yield this._fullSync(versionResults);
await this._fullSync(versionResults);
}
}
@ -142,7 +142,7 @@ Zotero.Sync.Data.Engine.prototype.start = Zotero.Promise.coroutine(function* ()
let downloadResult, uploadResult;
try {
uploadResult = yield this._startUpload();
uploadResult = await this._startUpload();
}
catch (e) {
if (e instanceof Zotero.Sync.UserCancelledException) {
@ -150,7 +150,7 @@ Zotero.Sync.Data.Engine.prototype.start = Zotero.Promise.coroutine(function* ()
}
Zotero.debug("Upload failed -- performing download", 2);
Zotero.debug(e, 1);
downloadResult = yield this._startDownload();
downloadResult = await this._startDownload();
Zotero.debug("Download result is " + downloadResult, 4);
throw e;
}
@ -171,14 +171,14 @@ Zotero.Sync.Data.Engine.prototype.start = Zotero.Promise.coroutine(function* ()
}
Zotero.logError("Object in " + this.library.name + " is out of date -- resetting library");
autoReset = true;
yield this._fullSync();
await this._fullSync();
break;
case this.UPLOAD_RESULT_NOTHING_TO_UPLOAD:
if (skipDownload) {
break sync;
}
downloadResult = yield this._startDownload();
downloadResult = await this._startDownload();
Zotero.debug("Download result is " + downloadResult, 4);
if (downloadResult == this.DOWNLOAD_RESULT_CHANGES_TO_UPLOAD) {
break;
@ -195,13 +195,13 @@ Zotero.Sync.Data.Engine.prototype.start = Zotero.Promise.coroutine(function* ()
// After the first upload version conflict (which is expected after remote changes),
// start delaying to give other sync sessions time to complete
else {
let keepGoing = yield gen.next().value;
let keepGoing = await gen.next().value;
if (!keepGoing) {
throw new Error("Could not sync " + this.library.name + " -- too many retries");
}
}
downloadResult = yield this._startDownload();
downloadResult = await this._startDownload();
Zotero.debug("Download result is " + downloadResult, 4);
// No need to download again after the upload
if (downloadResult !== this.DOWNLOAD_RESULT_RESTART) {
@ -220,13 +220,13 @@ Zotero.Sync.Data.Engine.prototype.start = Zotero.Promise.coroutine(function* ()
}
this.library.updateLastSyncTime();
yield this.library.saveTx({
await this.library.saveTx({
skipNotifier: true
});
if (this.library.libraryType == 'group') {
try {
yield this._updateGroupItemUsers();
await this._updateGroupItemUsers();
}
catch (e) {
Zotero.logError(e);
@ -234,7 +234,7 @@ Zotero.Sync.Data.Engine.prototype.start = Zotero.Promise.coroutine(function* ()
}
Zotero.debug("Done syncing " + this.library.name);
});
};
/**
@ -251,7 +251,7 @@ Zotero.Sync.Data.Engine.prototype.stop = function () {
*
* @return {Promise<Integer>} - A download result code (this.DOWNLOAD_RESULT_*)
*/
Zotero.Sync.Data.Engine.prototype._startDownload = Zotero.Promise.coroutine(function* () {
Zotero.Sync.Data.Engine.prototype._startDownload = async function () {
var localChanges = false;
var libraryVersion = this.library.libraryVersion;
var newLibraryVersion;
@ -261,7 +261,7 @@ Zotero.Sync.Data.Engine.prototype._startDownload = Zotero.Promise.coroutine(func
this._statusCheck();
// Get synced settings first, since they affect how other data is displayed
let results = yield this._downloadSettings(libraryVersion);
let results = await this._downloadSettings(libraryVersion);
if (results.result == this.DOWNLOAD_RESULT_LIBRARY_UNMODIFIED) {
let stop = true;
// If it's the first sync of the session or a manual sync and there are objects in the
@ -270,10 +270,10 @@ Zotero.Sync.Data.Engine.prototype._startDownload = Zotero.Promise.coroutine(func
//
// TODO: Skip the steps without queued objects.
if (this.firstInSession || !this.background) {
stop = !(yield Zotero.Sync.Data.Local.hasObjectsInSyncQueue(this.libraryID));
stop = !((await Zotero.Sync.Data.Local.hasObjectsInSyncQueue(this.libraryID)));
}
else {
stop = !(yield Zotero.Sync.Data.Local.hasObjectsToTryInSyncQueue(this.libraryID));
stop = !((await Zotero.Sync.Data.Local.hasObjectsToTryInSyncQueue(this.libraryID)));
}
if (stop) {
Zotero.debug("Library " + this.libraryID + " hasn't been modified "
@ -294,7 +294,7 @@ Zotero.Sync.Data.Engine.prototype._startDownload = Zotero.Promise.coroutine(func
// The next run below will then see the same items in the non-top versions request,
// but they'll have been downloaded already and will be skipped.
if (objectType == 'item') {
let result = yield this._downloadUpdatedObjects(
let result = await this._downloadUpdatedObjects(
objectType,
libraryVersion,
newLibraryVersion,
@ -303,25 +303,25 @@ Zotero.Sync.Data.Engine.prototype._startDownload = Zotero.Promise.coroutine(func
}
);
if (result == this.DOWNLOAD_RESULT_RESTART) {
yield this._onLibraryVersionChange();
await this._onLibraryVersionChange();
continue loop;
}
}
let result = yield this._downloadUpdatedObjects(
let result = await this._downloadUpdatedObjects(
objectType,
libraryVersion,
newLibraryVersion
);
if (result == this.DOWNLOAD_RESULT_RESTART) {
yield this._onLibraryVersionChange();
await this._onLibraryVersionChange();
continue loop;
}
}
let deletionsResult = yield this._downloadDeletions(libraryVersion, newLibraryVersion);
let deletionsResult = await this._downloadDeletions(libraryVersion, newLibraryVersion);
if (deletionsResult.result == this.DOWNLOAD_RESULT_RESTART) {
yield this._onLibraryVersionChange();
await this._onLibraryVersionChange();
continue loop;
}
@ -346,13 +346,13 @@ Zotero.Sync.Data.Engine.prototype._startDownload = Zotero.Promise.coroutine(func
if (!this.library.storageDownloadNeeded) {
this.library.storageVersion = newLibraryVersion;
}
yield this.library.saveTx();
await this.library.saveTx();
}
return localChanges
? this.DOWNLOAD_RESULT_CHANGES_TO_UPLOAD
: this.DOWNLOAD_RESULT_NO_CHANGES_TO_UPLOAD;
});
};
/**
@ -368,8 +368,8 @@ Zotero.Sync.Data.Engine.prototype._startDownload = Zotero.Promise.coroutine(func
* version is seen, restart the sync
* @return {Object} - Object with 'result' (DOWNLOAD_RESULT_*) and 'libraryVersion'
*/
Zotero.Sync.Data.Engine.prototype._downloadSettings = Zotero.Promise.coroutine(function* (since, newLibraryVersion) {
let results = yield this.apiClient.getSettings(
Zotero.Sync.Data.Engine.prototype._downloadSettings = async function (since, newLibraryVersion) {
let results = await this.apiClient.getSettings(
this.library.libraryType,
this.libraryTypeID,
since
@ -392,7 +392,7 @@ Zotero.Sync.Data.Engine.prototype._downloadSettings = Zotero.Promise.coroutine(f
if (numObjects) {
Zotero.debug(numObjects + " settings modified since last check");
for (let setting in results.settings) {
yield Zotero.SyncedSettings.set(
await Zotero.SyncedSettings.set(
this.libraryID,
setting,
results.settings[setting].value,
@ -408,7 +408,7 @@ Zotero.Sync.Data.Engine.prototype._downloadSettings = Zotero.Promise.coroutine(f
result: this.DOWNLOAD_RESULT_CONTINUE,
libraryVersion: results.libraryVersion
};
})
}
/**
@ -421,7 +421,7 @@ Zotero.Sync.Data.Engine.prototype._downloadSettings = Zotero.Promise.coroutine(f
* @param {Object} [options]
* @return {Promise<Integer>} - A download result code (this.DOWNLOAD_RESULT_*)
*/
Zotero.Sync.Data.Engine.prototype._downloadUpdatedObjects = Zotero.Promise.coroutine(function* (objectType, since, newLibraryVersion, options = {}) {
Zotero.Sync.Data.Engine.prototype._downloadUpdatedObjects = async function (objectType, since, newLibraryVersion, options = {}) {
var objectTypePlural = Zotero.DataObjectUtilities.getObjectTypePlural(objectType);
var objectsClass = Zotero.DataObjectUtilities.getObjectsClassForObjectType(objectType);
@ -435,7 +435,7 @@ Zotero.Sync.Data.Engine.prototype._downloadUpdatedObjects = Zotero.Promise.corou
if (options.top) {
queryParams.top = true;
}
var results = yield this.apiClient.getVersions(
var results = await this.apiClient.getVersions(
this.library.libraryType,
this.libraryTypeID,
objectType,
@ -467,12 +467,12 @@ Zotero.Sync.Data.Engine.prototype._downloadUpdatedObjects = Zotero.Promise.corou
let queuedKeys = [];
if (objectType != 'item' || !options.top) {
if (this.firstInSession || !this.background) {
queuedKeys = yield Zotero.Sync.Data.Local.getObjectsFromSyncQueue(
queuedKeys = await Zotero.Sync.Data.Local.getObjectsFromSyncQueue(
objectType, this.libraryID
);
}
else {
queuedKeys = yield Zotero.Sync.Data.Local.getObjectsToTryFromSyncQueue(
queuedKeys = await Zotero.Sync.Data.Local.getObjectsToTryFromSyncQueue(
objectType, this.libraryID
);
}
@ -491,7 +491,7 @@ Zotero.Sync.Data.Engine.prototype._downloadUpdatedObjects = Zotero.Promise.corou
}
let keys = [];
let versions = yield objectsClass.getObjectVersions(
let versions = await objectsClass.getObjectVersions(
this.libraryID, Object.keys(results.versions)
);
let upToDate = [];
@ -525,7 +525,7 @@ Zotero.Sync.Data.Engine.prototype._downloadUpdatedObjects = Zotero.Promise.corou
}
return this._downloadObjects(objectType, keys);
});
};
/**
@ -587,94 +587,91 @@ Zotero.Sync.Data.Engine.prototype._downloadObjects = async function (objectType,
var num = 0;
// Process batches of object data as they're available, one at a time
await Zotero.Promise.map(
results,
async function ({ keys: batchKeys, json, error }) {
this._statusCheck();
Zotero.debug(`Processing batch of downloaded ${objectTypePlural} in ${this.library.name}`);
if (error) {
this.failed = error;
return;
}
// Save downloaded JSON for later attempts
var seenKeys = new Set();
json.forEach(obj => {
objectData[obj.key] = obj;
seenKeys.add(obj.key);
});
// If a key we requested wasn't returned, it's missing remotely
for (let key of batchKeys) {
if (!seenKeys.has(key)) {
missingKeys.push(key);
objectData[key] = false;
}
}
// Process objects
let results = await Zotero.Sync.Data.Local.processObjectsFromJSON(
objectType,
this.libraryID,
json,
this._getOptions({
onObjectProcessed: () => {
num++;
// Check for stop every 5 items
if (num % 5 == 0) {
this._statusCheck();
}
},
// Increase the notifier batch size as we go, so that new items start coming in
// one by one but then switch to larger chunks
getNotifierBatchSize: () => {
var size;
if (num < 10) {
size = 1;
}
else if (num < 50) {
size = 5;
}
else if (num < 150) {
size = 25;
}
else {
size = 50;
}
return Math.min(size, json.length);
}
})
);
num += results.length;
let processedKeys = [];
let conflictResults = [];
results.forEach(x => {
// If data was processed, remove JSON
if (x.processed) {
delete objectData[x.key];
// We'll need to add items back to restored collections
if (x.restored) {
restored.push(x.key);
}
}
// If object shouldn't be retried, mark as processed
if (x.processed || !x.retry) {
processedKeys.push(x.key);
}
if (x.conflict) {
conflictResults.push(x);
}
});
remainingKeys = Zotero.Utilities.arrayDiff(remainingKeys, processedKeys);
conflicts.push(...conflictResults);
}.bind(this),
{
concurrency: 1
await // FIXME: fx140: replace call to Zotero.Promise.map()
Zotero.Promise.map(results, async function ({ keys: batchKeys, json, error }) {
this._statusCheck();
Zotero.debug(`Processing batch of downloaded ${objectTypePlural} in ${this.library.name}`);
if (error) {
this.failed = error;
return;
}
);
// Save downloaded JSON for later attempts
var seenKeys = new Set();
json.forEach(obj => {
objectData[obj.key] = obj;
seenKeys.add(obj.key);
});
// If a key we requested wasn't returned, it's missing remotely
for (let key of batchKeys) {
if (!seenKeys.has(key)) {
missingKeys.push(key);
objectData[key] = false;
}
}
// Process objects
let results = await Zotero.Sync.Data.Local.processObjectsFromJSON(
objectType,
this.libraryID,
json,
this._getOptions({
onObjectProcessed: () => {
num++;
// Check for stop every 5 items
if (num % 5 == 0) {
this._statusCheck();
}
},
// Increase the notifier batch size as we go, so that new items start coming in
// one by one but then switch to larger chunks
getNotifierBatchSize: () => {
var size;
if (num < 10) {
size = 1;
}
else if (num < 50) {
size = 5;
}
else if (num < 150) {
size = 25;
}
else {
size = 50;
}
return Math.min(size, json.length);
}
})
);
num += results.length;
let processedKeys = [];
let conflictResults = [];
results.forEach(x => {
// If data was processed, remove JSON
if (x.processed) {
delete objectData[x.key];
// We'll need to add items back to restored collections
if (x.restored) {
restored.push(x.key);
}
}
// If object shouldn't be retried, mark as processed
if (x.processed || !x.retry) {
processedKeys.push(x.key);
}
if (x.conflict) {
conflictResults.push(x);
}
});
remainingKeys = Zotero.Utilities.arrayDiff(remainingKeys, processedKeys);
conflicts.push(...conflictResults);
}.bind(this), {
concurrency: 1
});
// If any locally deleted collections were restored, either add them back to the collection
// (if the items still exist) or remove them from the delete log and add them to the sync queue
@ -823,10 +820,10 @@ Zotero.Sync.Data.Engine.prototype._restoreRestoredCollectionItems = async functi
* version is seen, restart the sync
* @return {Object} - Object with 'result' (DOWNLOAD_RESULT_*) and 'libraryVersion'
*/
Zotero.Sync.Data.Engine.prototype._downloadDeletions = Zotero.Promise.coroutine(function* (since, newLibraryVersion) {
Zotero.Sync.Data.Engine.prototype._downloadDeletions = async function (since, newLibraryVersion) {
const batchSize = 50;
let results = yield this.apiClient.getDeleted(
let results = await this.apiClient.getDeleted(
this.library.libraryType,
this.libraryTypeID,
since
@ -867,7 +864,7 @@ Zotero.Sync.Data.Engine.prototype._downloadDeletions = Zotero.Promise.coroutine(
continue;
}
if (meta.synced) {
yield Zotero.SyncedSettings.clear(this.libraryID, key, {
await Zotero.SyncedSettings.clear(this.libraryID, key, {
skipDeleteLog: true
});
}
@ -888,7 +885,7 @@ Zotero.Sync.Data.Engine.prototype._downloadDeletions = Zotero.Promise.coroutine(
// If item is already in trash locally, just delete it
if (obj.deleted) {
Zotero.debug("Local item is in trash -- applying remote deletion");
yield obj.eraseTx({
await obj.eraseTx({
skipDeleteLog: true
});
continue;
@ -923,7 +920,7 @@ Zotero.Sync.Data.Engine.prototype._downloadDeletions = Zotero.Promise.coroutine(
Zotero.debug("Cancelling sync");
throw new Zotero.Sync.UserCancelledException();
}
yield Zotero.Utilities.Internal.forEachChunkAsync(
await Zotero.Utilities.Internal.forEachChunkAsync(
mergeData,
batchSize,
function (chunk) {
@ -947,7 +944,7 @@ Zotero.Sync.Data.Engine.prototype._downloadDeletions = Zotero.Promise.coroutine(
}
if (toDelete.length) {
yield Zotero.Utilities.Internal.forEachChunkAsync(
await Zotero.Utilities.Internal.forEachChunkAsync(
toDelete,
batchSize,
function (chunk) {
@ -968,14 +965,14 @@ Zotero.Sync.Data.Engine.prototype._downloadDeletions = Zotero.Promise.coroutine(
result: this.DOWNLOAD_RESULT_CONTINUE,
libraryVersion: results.libraryVersion
};
});
};
/**
* If something else modified the remote library while we were getting updates, wait for increasing
* amounts of time before trying again, and then start from the beginning
*/
Zotero.Sync.Data.Engine.prototype._onLibraryVersionChange = Zotero.Promise.coroutine(function* (mode) {
Zotero.Sync.Data.Engine.prototype._onLibraryVersionChange = async function (mode) {
Zotero.logError("Library version changed since last download -- restarting sync");
if (!this.downloadDelayGenerator) {
@ -984,11 +981,11 @@ Zotero.Sync.Data.Engine.prototype._onLibraryVersionChange = Zotero.Promise.corou
);
}
let keepGoing = yield this.downloadDelayGenerator.next().value;
let keepGoing = await this.downloadDelayGenerator.next().value;
if (!keepGoing) {
throw new Error("Could not update " + this.library.name + " -- library in use");
}
});
};
/**
@ -997,7 +994,7 @@ Zotero.Sync.Data.Engine.prototype._onLibraryVersionChange = Zotero.Promise.corou
* @throws {Zotero.HTTP.UnexpectedStatusException}
* @return {Promise<Integer>} - An upload result code (this.UPLOAD_RESULT_*)
*/
Zotero.Sync.Data.Engine.prototype._startUpload = Zotero.Promise.coroutine(function* () {
Zotero.Sync.Data.Engine.prototype._startUpload = async function () {
var libraryVersion = this.library.libraryVersion;
var settingsUploaded = false;
@ -1007,9 +1004,9 @@ Zotero.Sync.Data.Engine.prototype._startUpload = Zotero.Promise.coroutine(functi
// Upload synced settings
try {
let settings = yield Zotero.SyncedSettings.getUnsynced(this.libraryID);
let settings = await Zotero.SyncedSettings.getUnsynced(this.libraryID);
if (Object.keys(settings).length) {
libraryVersion = yield this._uploadSettings(settings, libraryVersion);
libraryVersion = await this._uploadSettings(settings, libraryVersion);
settingsUploaded = true;
}
else {
@ -1028,13 +1025,13 @@ Zotero.Sync.Data.Engine.prototype._startUpload = Zotero.Promise.coroutine(functi
let objectsClass = Zotero.DataObjectUtilities.getObjectsClassForObjectType(objectType);
// New/modified objects
let ids = yield Zotero.Sync.Data.Local.getUnsynced(objectType, this.libraryID);
let ids = await Zotero.Sync.Data.Local.getUnsynced(objectType, this.libraryID);
// Skip objects in sync queue, because they might have unresolved conflicts.
// The queue only has keys, so we have to convert to keys and back.
let unsyncedKeys = ids.map(id => objectsClass.getLibraryAndKeyFromID(id).key);
let origUnsynced = unsyncedKeys; // TEMP
let queueKeys = yield Zotero.Sync.Data.Local.getObjectsFromSyncQueue(objectType, this.libraryID);
let queueKeys = await Zotero.Sync.Data.Local.getObjectsFromSyncQueue(objectType, this.libraryID);
let newUnsyncedKeys = Zotero.Utilities.arrayDiff(unsyncedKeys, queueKeys);
if (newUnsyncedKeys.length < unsyncedKeys.length) {
Zotero.debug(`Skipping ${unsyncedKeys.length - newUnsyncedKeys.length} key(s) in sync queue`);
@ -1071,7 +1068,7 @@ Zotero.Sync.Data.Engine.prototype._startUpload = Zotero.Promise.coroutine(functi
}
// Deleted objects
let keys = yield Zotero.Sync.Data.Local.getDeleted(objectType, this.libraryID);
let keys = await Zotero.Sync.Data.Local.getDeleted(objectType, this.libraryID);
if (keys.length) {
Zotero.debug(`${keys.length} ${objectType} deletion`
+ (keys.length == 1 ? '' : 's')
@ -1096,7 +1093,7 @@ Zotero.Sync.Data.Engine.prototype._startUpload = Zotero.Promise.coroutine(functi
for (let objectType in objectIDs) {
this._statusCheck();
libraryVersion = yield this._uploadObjects(
libraryVersion = await this._uploadObjects(
objectType, objectIDs[objectType], libraryVersion
);
}
@ -1105,7 +1102,7 @@ Zotero.Sync.Data.Engine.prototype._startUpload = Zotero.Promise.coroutine(functi
for (let objectType in objectDeletions) {
this._statusCheck();
libraryVersion = yield this._uploadDeletions(
libraryVersion = await this._uploadDeletions(
objectType, objectDeletions[objectType], libraryVersion
);
}
@ -1115,7 +1112,7 @@ Zotero.Sync.Data.Engine.prototype._startUpload = Zotero.Promise.coroutine(functi
}
return this.UPLOAD_RESULT_SUCCESS;
});
};
Zotero.Sync.Data.Engine.prototype._uploadSettings = async function (settings, libraryVersion) {
@ -1156,7 +1153,7 @@ Zotero.Sync.Data.Engine.prototype._uploadSettings = async function (settings, li
};
Zotero.Sync.Data.Engine.prototype._uploadObjects = Zotero.Promise.coroutine(function* (objectType, ids, libraryVersion) {
Zotero.Sync.Data.Engine.prototype._uploadObjects = async function (objectType, ids, libraryVersion) {
let objectTypePlural = Zotero.DataObjectUtilities.getObjectTypePlural(objectType);
let objectsClass = Zotero.DataObjectUtilities.getObjectsClassForObjectType(objectType);
@ -1212,7 +1209,7 @@ Zotero.Sync.Data.Engine.prototype._uploadObjects = Zotero.Promise.coroutine(func
continue;
}
if (!o.json) {
o.json = yield this._getJSONForObject(
o.json = await this._getJSONForObject(
objectType,
o.id,
{
@ -1246,7 +1243,7 @@ Zotero.Sync.Data.Engine.prototype._uploadObjects = Zotero.Promise.coroutine(func
let results;
let numSuccessful = 0;
({ libraryVersion, results } = yield this.apiClient.uploadObjects(
({ libraryVersion, results } = await this.apiClient.uploadObjects(
this.library.libraryType,
this.libraryTypeID,
"POST",
@ -1321,10 +1318,10 @@ Zotero.Sync.Data.Engine.prototype._uploadObjects = Zotero.Promise.coroutine(func
delete jsonBatch[index];
}
}
yield Zotero.Sync.Data.Local.saveCacheObjects(
await Zotero.Sync.Data.Local.saveCacheObjects(
objectType, this.libraryID, toCache
);
yield Zotero.DB.executeTransaction(async function () {
await Zotero.DB.executeTransaction(async function () {
for (let i = 0; i < toSave.length; i++) {
await toSave[i].save({
skipSelect: true,
@ -1353,7 +1350,7 @@ Zotero.Sync.Data.Engine.prototype._uploadObjects = Zotero.Promise.coroutine(func
// Purge older objects in sync cache
if (toSave.length) {
yield Zotero.Sync.Data.Local.purgeCache(objectType, this.libraryID);
await Zotero.Sync.Data.Local.purgeCache(objectType, this.libraryID);
}
// Handle failed objects
@ -1374,7 +1371,7 @@ Zotero.Sync.Data.Engine.prototype._uploadObjects = Zotero.Promise.coroutine(func
Zotero.logError(`Error ${code} for ${objectType} ${key} in `
+ this.library.name + ":\n\n" + e);
let keepGoing = yield this._checkObjectUploadError(objectType, key, e, queue, batch);
let keepGoing = await this._checkObjectUploadError(objectType, key, e, queue, batch);
if (keepGoing) {
numSuccessful++;
continue;
@ -1431,16 +1428,16 @@ Zotero.Sync.Data.Engine.prototype._uploadObjects = Zotero.Promise.coroutine(func
Zotero.debug("Done uploading " + objectTypePlural + " in library " + this.libraryID);
return libraryVersion;
})
}
Zotero.Sync.Data.Engine.prototype._uploadDeletions = Zotero.Promise.coroutine(function* (objectType, keys, libraryVersion) {
Zotero.Sync.Data.Engine.prototype._uploadDeletions = async function (objectType, keys, libraryVersion) {
let objectTypePlural = Zotero.DataObjectUtilities.getObjectTypePlural(objectType);
let objectsClass = Zotero.DataObjectUtilities.getObjectsClassForObjectType(objectType);
while (keys.length) {
let batch = keys.slice(0, this.uploadDeletionBatchSize);
libraryVersion = yield this.apiClient.uploadDeletions(
libraryVersion = await this.apiClient.uploadDeletions(
this.library.libraryType,
this.libraryTypeID,
libraryVersion,
@ -1454,19 +1451,19 @@ Zotero.Sync.Data.Engine.prototype._uploadDeletions = Zotero.Promise.coroutine(fu
this.library.storageVersion = libraryVersion;
}
this.library.libraryVersion = libraryVersion;
yield this.library.saveTx({
await this.library.saveTx({
skipNotifier: true
});
// Remove successful deletions from delete log
yield Zotero.Sync.Data.Local.removeObjectsFromDeleteLog(
await Zotero.Sync.Data.Local.removeObjectsFromDeleteLog(
objectType, this.libraryID, batch
);
}
Zotero.debug(`Done uploading ${objectType} deletions in ${this.library.name}`);
return libraryVersion;
});
};
/**
@ -1579,11 +1576,11 @@ Zotero.Sync.Data.Engine.prototype._getJSONForObject = function (objectType, id,
* @return {Object[]} - Objects returned from getVersions(), keyed by objectType, for use
* by _fullSync()
*/
Zotero.Sync.Data.Engine.prototype._upgradeCheck = Zotero.Promise.coroutine(function* () {
Zotero.Sync.Data.Engine.prototype._upgradeCheck = async function () {
var libraryVersion = this.library.libraryVersion;
if (libraryVersion) return;
var lastLocalSyncTime = yield Zotero.DB.valueQueryAsync(
var lastLocalSyncTime = await Zotero.DB.valueQueryAsync(
"SELECT version FROM version WHERE schema='lastlocalsync'"
);
// Never synced with classic architecture, or already upgraded and full sync (which updates
@ -1592,7 +1589,7 @@ Zotero.Sync.Data.Engine.prototype._upgradeCheck = Zotero.Promise.coroutine(funct
Zotero.debug("Upgrading library to current sync architecture");
var lastRemoteSyncTime = yield Zotero.DB.valueQueryAsync(
var lastRemoteSyncTime = await Zotero.DB.valueQueryAsync(
"SELECT version FROM version WHERE schema='lastremotesync'"
);
// Shouldn't happen
@ -1605,8 +1602,8 @@ Zotero.Sync.Data.Engine.prototype._upgradeCheck = Zotero.Promise.coroutine(funct
lastLocalSyncTime = new Date(lastLocalSyncTime * 1000);
for (let objectType of objectTypes) {
let objectsClass = Zotero.DataObjectUtilities.getObjectsClassForObjectType(objectType);
let ids = yield objectsClass.getOlder(this.libraryID, lastLocalSyncTime);
yield objectsClass.updateSynced(ids, true);
let ids = await objectsClass.getOlder(this.libraryID, lastLocalSyncTime);
await objectsClass.updateSynced(ids, true);
}
}
@ -1624,14 +1621,14 @@ Zotero.Sync.Data.Engine.prototype._upgradeCheck = Zotero.Promise.coroutine(funct
this.setStatus("Updating " + objectTypePlural + " in " + this.library.name);
// Get versions from API for all objects
let allResults = yield this.apiClient.getVersions(
let allResults = await this.apiClient.getVersions(
this.library.libraryType,
this.libraryTypeID,
objectType
);
// Get versions from API for objects modified remotely since the last classic sync time
let sinceResults = yield this.apiClient.getVersions(
let sinceResults = await this.apiClient.getVersions(
this.library.libraryType,
this.libraryTypeID,
objectType,
@ -1654,7 +1651,7 @@ Zotero.Sync.Data.Engine.prototype._upgradeCheck = Zotero.Promise.coroutine(funct
+ allResults.libraryVersion + " != "
+ sinceResults.libraryVersion + " != "
+ lastLibraryVersion + ") -- waiting");
let keepGoing = yield gen.next().value;
let keepGoing = await gen.next().value;
if (!keepGoing) {
throw new Error("Could not update " + this.library.name + " -- library in use");
}
@ -1679,7 +1676,7 @@ Zotero.Sync.Data.Engine.prototype._upgradeCheck = Zotero.Promise.coroutine(funct
// Update versions on local objects modified remotely before last classic sync time,
// to indicate that they don't need to receive remote updates
yield Zotero.DB.executeTransaction(async function () {
await Zotero.DB.executeTransaction(async function () {
for (let objectType in currentVersions) {
let objectTypePlural = Zotero.DataObjectUtilities.getObjectTypePlural(objectType);
let objectsClass = Zotero.DataObjectUtilities.getObjectsClassForObjectType(objectType);
@ -1719,7 +1716,7 @@ Zotero.Sync.Data.Engine.prototype._upgradeCheck = Zotero.Promise.coroutine(funct
Zotero.debug("Done upgrading " + this.library.name);
return versionResults;
});
};
/**
@ -1735,7 +1732,7 @@ Zotero.Sync.Data.Engine.prototype._upgradeCheck = Zotero.Promise.coroutine(funct
* @param {Object[]} [versionResults] - Objects returned from getVersions(), keyed by objectType
* @return {Promise<Integer>} - Promise for the library version after syncing
*/
Zotero.Sync.Data.Engine.prototype._fullSync = Zotero.Promise.coroutine(function* (versionResults) {
Zotero.Sync.Data.Engine.prototype._fullSync = async function (versionResults) {
Zotero.debug("Performing a full sync of " + this.library.name);
var gen;
@ -1746,13 +1743,13 @@ Zotero.Sync.Data.Engine.prototype._fullSync = Zotero.Promise.coroutine(function*
this._statusCheck();
// Reprocess all deletions available from API
let results = yield this._downloadDeletions(0);
let results = await this._downloadDeletions(0);
lastLibraryVersion = results.libraryVersion;
// Get synced settings
results = yield this._downloadSettings(0, lastLibraryVersion);
results = await this._downloadSettings(0, lastLibraryVersion);
if (results.result == this.DOWNLOAD_RESULT_RESTART) {
yield this._onLibraryVersionChange();
await this._onLibraryVersionChange();
continue loop;
}
else {
@ -1777,19 +1774,19 @@ Zotero.Sync.Data.Engine.prototype._fullSync = Zotero.Promise.coroutine(function*
}
// If not available, get from API
else {
results = yield this.apiClient.getVersions(
results = await this.apiClient.getVersions(
this.library.libraryType,
this.libraryTypeID,
objectType
);
}
if (lastLibraryVersion != results.libraryVersion) {
yield this._onLibraryVersionChange();
await this._onLibraryVersionChange();
continue loop;
}
let toDownload = [];
let localVersions = yield objectsClass.getObjectVersions(this.libraryID);
let localVersions = await objectsClass.getObjectVersions(this.libraryID);
// Queue objects that are out of date or don't exist locally
for (let key in results.versions) {
let version = results.versions[key];
@ -1814,14 +1811,14 @@ Zotero.Sync.Data.Engine.prototype._fullSync = Zotero.Promise.coroutine(function*
if (toDownload.length) {
Zotero.debug("Downloading missing/outdated " + objectTypePlural);
yield this._downloadObjects(objectType, toDownload);
await this._downloadObjects(objectType, toDownload);
}
else {
Zotero.debug(`No missing/outdated ${objectTypePlural} to download`);
}
// Mark local objects that don't exist remotely as unsynced and version 0
let allKeys = yield objectsClass.getAllKeys(this.libraryID);
let allKeys = await objectsClass.getAllKeys(this.libraryID);
let remoteMissing = Zotero.Utilities.arrayDiff(allKeys, Object.keys(results.versions));
if (remoteMissing.length) {
Zotero.debug("Checking remotely missing " + objectTypePlural);
@ -1836,8 +1833,8 @@ Zotero.Sync.Data.Engine.prototype._fullSync = Zotero.Promise.coroutine(function*
// version will no longer match remote, and mark for upload
if (toUpload.length) {
Zotero.debug(`Marking remotely missing ${objectTypePlural} as unsynced`);
yield objectsClass.updateVersion(toUpload, 0);
yield objectsClass.updateSynced(toUpload, false);
await objectsClass.updateVersion(toUpload, 0);
await objectsClass.updateSynced(toUpload, false);
}
}
else {
@ -1848,12 +1845,12 @@ Zotero.Sync.Data.Engine.prototype._fullSync = Zotero.Promise.coroutine(function*
}
this.library.libraryVersion = lastLibraryVersion;
yield this.library.saveTx();
await this.library.saveTx();
Zotero.debug("Done with full sync for " + this.library.name);
return lastLibraryVersion;
});
};
Zotero.Sync.Data.Engine.prototype._restoreToServer = async function () {
@ -1991,7 +1988,7 @@ Zotero.Sync.Data.Engine.prototype._getOptions = function (additionalOpts = {}) {
}
Zotero.Sync.Data.Engine.prototype._handleUploadError = Zotero.Promise.coroutine(function* (e) {
Zotero.Sync.Data.Engine.prototype._handleUploadError = async function (e) {
if (e instanceof Zotero.HTTP.UnexpectedStatusException) {
switch (e.status) {
// This should only happen if library permissions were changed between the group check at
@ -2000,7 +1997,7 @@ Zotero.Sync.Data.Engine.prototype._handleUploadError = Zotero.Promise.coroutine(
case 403:
let index = Zotero.Sync.Data.Utilities.showWriteAccessLostPrompt(null, this.library);
if (index === 0) {
yield Zotero.Sync.Data.Local.resetUnsyncedLibraryData(this.libraryID);
await Zotero.Sync.Data.Local.resetUnsyncedLibraryData(this.libraryID);
return this.UPLOAD_RESULT_RESTART;
}
if (index == 1) {
@ -2027,10 +2024,10 @@ Zotero.Sync.Data.Engine.prototype._handleUploadError = Zotero.Promise.coroutine(
return this.UPLOAD_RESULT_CANCEL;
}
throw e;
});
};
Zotero.Sync.Data.Engine.prototype._checkObjectUploadError = Zotero.Promise.coroutine(function* (objectType, key, e, queue, batch) {
Zotero.Sync.Data.Engine.prototype._checkObjectUploadError = async function (objectType, key, e, queue, batch) {
var { code, data, message } = e;
// If an item's dependency is missing remotely and it isn't in the queue (which
@ -2045,7 +2042,7 @@ Zotero.Sync.Data.Engine.prototype._checkObjectUploadError = Zotero.Promise.corou
+ `references parent collection ${data.collection}, which doesn't exist`);
}
Zotero.logError(`Marking collection ${data.collection} as unsynced`);
yield Zotero.Sync.Data.Local.markObjectAsUnsynced(collection);
await Zotero.Sync.Data.Local.markObjectAsUnsynced(collection);
}
}
else if (objectType == 'item') {
@ -2056,7 +2053,7 @@ Zotero.Sync.Data.Engine.prototype._checkObjectUploadError = Zotero.Promise.corou
+ `references collection ${data.collection}, which doesn't exist`);
}
Zotero.logError(`Marking collection ${data.collection} as unsynced`);
yield Zotero.Sync.Data.Local.markObjectAsUnsynced(collection);
await Zotero.Sync.Data.Local.markObjectAsUnsynced(collection);
}
else if (data.parentItem) {
let parentItem = Zotero.Items.getByLibraryAndKey(this.libraryID, data.parentItem);
@ -2070,7 +2067,7 @@ Zotero.Sync.Data.Engine.prototype._checkObjectUploadError = Zotero.Promise.corou
if (!queue.find(o => o.id == id)
// TODO: Don't use 'delete' on batch, which results in undefineds
&& !batch.find(o => o && o.id == id)) {
yield Zotero.Sync.Data.Local.markObjectAsUnsynced(parentItem);
await Zotero.Sync.Data.Local.markObjectAsUnsynced(parentItem);
Zotero.logError(`Adding parent item ${data.parentItem} to upload queue`);
queue.push({
id,
@ -2088,7 +2085,7 @@ Zotero.Sync.Data.Engine.prototype._checkObjectUploadError = Zotero.Promise.corou
// Split old annotations before we were splitting them automatically in the PDF reader
if (message.startsWith("Annotation position is too long")) {
let item = Zotero.Items.getByLibraryAndKey(this.libraryID, key);
yield Zotero.Annotations.splitAnnotations(item);
await Zotero.Annotations.splitAnnotations(item);
}
}
else if (code == 403) {
@ -2099,7 +2096,7 @@ Zotero.Sync.Data.Engine.prototype._checkObjectUploadError = Zotero.Promise.corou
if (this.library.libraryType == 'group' && item.isFileAttachment()) {
let reset = false;
let groupID = Zotero.Groups.getGroupIDFromLibraryID(this.libraryID);
let info = yield this.apiClient.getGroup(groupID);
let info = await this.apiClient.getGroup(groupID);
if (info) {
Zotero.debug(info);
let { editable, filesEditable } = Zotero.Groups.getPermissionsFromJSON(
@ -2116,9 +2113,9 @@ Zotero.Sync.Data.Engine.prototype._checkObjectUploadError = Zotero.Promise.corou
if (index === 0) {
let group = Zotero.Groups.get(groupID);
group.filesEditable = false;
yield group.saveTx();
await group.saveTx();
yield Zotero.Sync.Data.Local.resetUnsyncedLibraryFiles(this.libraryID);
await Zotero.Sync.Data.Local.resetUnsyncedLibraryFiles(this.libraryID);
e.name = "ZoteroUploadRestartError";
}
else {
@ -2141,7 +2138,7 @@ Zotero.Sync.Data.Engine.prototype._checkObjectUploadError = Zotero.Promise.corou
}
return false;
});
};
Zotero.Sync.Data.Engine.prototype._statusCheck = function () {

View file

@ -29,7 +29,7 @@ Zotero.Sync.EventListeners.ChangeListener = new function () {
);
}
this.notify = Zotero.Promise.method(function (event, type, ids, extraData) {
this.notify = function (event, type, ids, extraData) {
var syncObjectTypeID = Zotero.Sync.Data.Utilities.getSyncObjectTypeID(type);
if (!syncObjectTypeID) {
return;
@ -94,7 +94,7 @@ Zotero.Sync.EventListeners.ChangeListener = new function () {
}
}
);
});
};
}

View file

@ -48,14 +48,14 @@ Zotero.Sync.Data.FullTextEngine = function (options) {
this.failed = false;
}
Zotero.Sync.Data.FullTextEngine.prototype.start = Zotero.Promise.coroutine(function* () {
Zotero.Sync.Data.FullTextEngine.prototype.start = async function () {
Zotero.debug("Starting full-text sync for " + this.library.name);
// Get last full-text version in settings
var libraryVersion = yield Zotero.FullText.getLibraryVersion(this.libraryID);
var libraryVersion = await Zotero.FullText.getLibraryVersion(this.libraryID);
// If main library version has changed, check to see if there's no full-text content
if (this.library.libraryVersion > libraryVersion) {
yield this._download(libraryVersion);
await this._download(libraryVersion);
}
else {
Zotero.debug("Library version hasn't changed -- skipping full-text download");
@ -63,15 +63,15 @@ Zotero.Sync.Data.FullTextEngine.prototype.start = Zotero.Promise.coroutine(funct
this._stopCheck();
yield this._upload();
})
await this._upload();
}
Zotero.Sync.Data.FullTextEngine.prototype._download = Zotero.Promise.coroutine(function* (libraryVersion) {
Zotero.Sync.Data.FullTextEngine.prototype._download = async function (libraryVersion) {
Zotero.debug("Downloading full-text content for " + this.library.name);
// Get changed with ?since
var results = yield this.apiClient.getFullTextVersions(
var results = await this.apiClient.getFullTextVersions(
this.library.libraryType,
this.library.libraryTypeID,
libraryVersion
@ -88,7 +88,7 @@ Zotero.Sync.Data.FullTextEngine.prototype._download = Zotero.Promise.coroutine(f
// Skip full text that's already up-to-date, which could happen due to a full sync or
// interrupted sync
let version = yield Zotero.Fulltext.getItemVersion(id);
let version = await Zotero.Fulltext.getItemVersion(id);
if (version == results.versions[key]) {
Zotero.debug(`Skipping up-to-date full text for ${this.library.name}`);
continue;
@ -98,30 +98,27 @@ Zotero.Sync.Data.FullTextEngine.prototype._download = Zotero.Promise.coroutine(f
this.requestPromises = [];
yield Zotero.Promise.map(
keys,
(key) => {
await // FIXME: fx140: replace call to Zotero.Promise.map()
Zotero.Promise.map(keys, (key) => {
this._stopCheck();
return this.apiClient.getFullTextForItem(
this.library.libraryType, this.library.libraryTypeID, key
)
.then((results) => {
this._stopCheck();
return this.apiClient.getFullTextForItem(
this.library.libraryType, this.library.libraryTypeID, key
if (!results) return;
return Zotero.Fulltext.setItemContent(
this.libraryID, key, results.data, results.version
)
.then((results) => {
this._stopCheck();
if (!results) return;
return Zotero.Fulltext.setItemContent(
this.libraryID, key, results.data, results.version
)
})
},
// Prepare twice the number of concurrent requests
{ concurrency: 8 }
);
})
}, // Prepare twice the number of concurrent requests
{ concurrency: 8 });
yield Zotero.FullText.setLibraryVersion(this.libraryID, results.libraryVersion);
});
await Zotero.FullText.setLibraryVersion(this.libraryID, results.libraryVersion);
};
Zotero.Sync.Data.FullTextEngine.prototype._upload = Zotero.Promise.coroutine(function* () {
Zotero.Sync.Data.FullTextEngine.prototype._upload = async function () {
if (!this.library.editable) return;
Zotero.debug("Uploading full-text content for " + this.library.name);
@ -133,7 +130,7 @@ Zotero.Sync.Data.FullTextEngine.prototype._upload = Zotero.Promise.coroutine(fun
while (true) {
this._stopCheck();
let objs = yield Zotero.FullText.getUnsyncedContent(this.libraryID, {
let objs = await Zotero.FullText.getUnsyncedContent(this.libraryID, {
maxSize: this.MAX_BATCH_SIZE,
maxItems: this.MAX_BATCH_ITEMS,
lastItemID
@ -153,13 +150,13 @@ Zotero.Sync.Data.FullTextEngine.prototype._upload = Zotero.Promise.coroutine(fun
jsonArray.push(json);
lastItemID = obj.itemID;
}
({ libraryVersion, results } = yield this.apiClient.setFullTextForItems(
({ libraryVersion, results } = await this.apiClient.setFullTextForItems(
this.library.libraryType,
this.library.libraryTypeID,
libraryVersion,
jsonArray
));
yield Zotero.DB.executeTransaction(async function () {
await Zotero.DB.executeTransaction(async function () {
for (let state of ['successful', 'unchanged']) {
for (let index in results[state]) {
let key = results[state][index].key;
@ -194,13 +191,13 @@ Zotero.Sync.Data.FullTextEngine.prototype._upload = Zotero.Promise.coroutine(fun
}
}
}
});
};
Zotero.Sync.Data.FullTextEngine.prototype.stop = Zotero.Promise.coroutine(function* () {
Zotero.Sync.Data.FullTextEngine.prototype.stop = async function () {
// TODO: Cancel requests?
this._stopping = true;
})
}
Zotero.Sync.Data.FullTextEngine.prototype._stopCheck = function () {

View file

@ -34,24 +34,24 @@ Zotero.Sync.Data.Local = {
_lastSyncTime: null,
_lastClassicSyncTime: null,
init: Zotero.Promise.coroutine(function* () {
yield this._loadLastSyncTime();
init: async function () {
await this._loadLastSyncTime();
if (!_lastSyncTime) {
yield this._loadLastClassicSyncTime();
await this._loadLastClassicSyncTime();
}
}),
},
/**
* @return {Promise}
*/
getAPIKey: Zotero.Promise.method(function () {
getAPIKey: function () {
var login = this._getAPIKeyLoginInfo();
return login
? login.password
// Fallback to old username/password
: this._getAPIKeyFromLogin();
}),
},
/**
@ -115,7 +115,7 @@ Zotero.Sync.Data.Local = {
* @param {String} [name] - New display name
* @return {Boolean} - True to continue, false to cancel
*/
checkUser: Zotero.Promise.coroutine(function* (win, userID, username, name) {
checkUser: async function (win, userID, username, name) {
var lastUserID = Zotero.Users.getCurrentUserID();
var lastUsername = Zotero.Users.getCurrentUsername();
var lastName = Zotero.Users.getCurrentName();
@ -142,7 +142,7 @@ Zotero.Sync.Data.Local = {
if (io.accept) {
var resetDataDirFile = OS.Path.join(Zotero.DataDirectory.dir, 'reset-data-directory');
yield Zotero.File.putContentsAsync(resetDataDirFile, '');
await Zotero.File.putContentsAsync(resetDataDirFile, '');
Zotero.Prefs.clear('sync.storage.downloadMode.groups');
Zotero.Prefs.clear('sync.storage.groups.enabled');
@ -164,7 +164,7 @@ Zotero.Sync.Data.Local = {
return false;
}
yield Zotero.DB.executeTransaction(async function () {
await Zotero.DB.executeTransaction(async function () {
if (lastUsername != username) {
await Zotero.Users.setCurrentUsername(username);
}
@ -183,26 +183,26 @@ Zotero.Sync.Data.Local = {
});
return true;
}),
},
/**
* @return {Promise<Boolean>} - True if library updated, false to cancel
*/
checkLibraryForAccess: Zotero.Promise.coroutine(function* (win, libraryID, editable, filesEditable) {
checkLibraryForAccess: async function (win, libraryID, editable, filesEditable) {
var library = Zotero.Libraries.get(libraryID);
// If library is going from editable to non-editable and there's unsynced local data, prompt
if (library.editable && !editable && (yield this._libraryHasUnsyncedData(libraryID))) {
if (library.editable && !editable && ((await this._libraryHasUnsyncedData(libraryID)))) {
let index = Zotero.Sync.Data.Utilities.showWriteAccessLostPrompt(win, library);
// Reset library
if (index == 0) {
// This check happens before item data is loaded for syncing, so do it now,
// since the reset requires it
if (!library.getDataLoaded('item')) {
yield library.waitForDataLoad('item');
await library.waitForDataLoad('item');
}
yield this.resetUnsyncedLibraryData(libraryID);
await this.resetUnsyncedLibraryData(libraryID);
return true;
}
@ -210,16 +210,16 @@ Zotero.Sync.Data.Local = {
return false;
}
if (library.filesEditable && !filesEditable && (yield this._libraryHasUnsyncedFiles(libraryID))) {
if (library.filesEditable && !filesEditable && ((await this._libraryHasUnsyncedFiles(libraryID)))) {
let index = Zotero.Sync.Storage.Utilities.showFileWriteAccessLostPrompt(win, library);
// Reset library files
if (index == 0) {
// This check happens before item data is loaded for syncing, so do it now,
// since the reset requires it
if (!library.getDataLoaded('item')) {
yield library.waitForDataLoad('item');
await library.waitForDataLoad('item');
}
yield this.resetUnsyncedLibraryFiles(libraryID);
await this.resetUnsyncedLibraryFiles(libraryID);
return true;
}
@ -228,60 +228,61 @@ Zotero.Sync.Data.Local = {
}
return true;
}),
},
_libraryHasUnsyncedData: Zotero.Promise.coroutine(function* (libraryID) {
let settings = yield Zotero.SyncedSettings.getUnsynced(libraryID);
_libraryHasUnsyncedData: async function (libraryID) {
let settings = await Zotero.SyncedSettings.getUnsynced(libraryID);
if (Object.keys(settings).length) {
return true;
}
for (let objectType of Zotero.DataObjectUtilities.getTypesForLibrary(libraryID)) {
let ids = yield Zotero.Sync.Data.Local.getUnsynced(objectType, libraryID);
let ids = await Zotero.Sync.Data.Local.getUnsynced(objectType, libraryID);
if (ids.length) {
return true;
}
let keys = yield Zotero.Sync.Data.Local.getDeleted(objectType, libraryID);
let keys = await Zotero.Sync.Data.Local.getDeleted(objectType, libraryID);
if (keys.length) {
return true;
}
}
return false;
}),
},
_libraryHasUnsyncedFiles: Zotero.Promise.coroutine(function* (libraryID) {
_libraryHasUnsyncedFiles: async function (libraryID) {
// TODO: Check for modified file attachment items, which also can't be uploaded
// (and which are corrected by resetUnsyncedLibraryFiles())
yield Zotero.Sync.Storage.Local.checkForUpdatedFiles(libraryID);
return !!(yield Zotero.Sync.Storage.Local.getFilesToUpload(libraryID)).length;
}),
await Zotero.Sync.Storage.Local.checkForUpdatedFiles(libraryID);
return !!((await Zotero.Sync.Storage.Local.getFilesToUpload(libraryID))).length;
},
resetUnsyncedLibraryData: Zotero.Promise.coroutine(function* (libraryID) {
let settings = yield Zotero.SyncedSettings.getUnsynced(libraryID);
resetUnsyncedLibraryData: async function (libraryID) {
let settings = await Zotero.SyncedSettings.getUnsynced(libraryID);
if (Object.keys(settings).length) {
yield Zotero.Promise.each(Object.keys(settings), function (key) {
await // FIXME: fx140: replace call to Zotero.Promise.each()
Zotero.Promise.each(Object.keys(settings), function (key) {
return Zotero.SyncedSettings.clear(libraryID, key, { skipDeleteLog: true });
});
}
for (let objectType of Zotero.DataObjectUtilities.getTypesForLibrary(libraryID)) {
// New/modified objects
let ids = yield this.getUnsynced(objectType, libraryID);
yield this._resetObjects(libraryID, objectType, ids);
let ids = await this.getUnsynced(objectType, libraryID);
await this._resetObjects(libraryID, objectType, ids);
}
// Mark library for full sync
var library = Zotero.Libraries.get(libraryID);
library.libraryVersion = -1;
yield library.saveTx();
await library.saveTx();
yield this.resetUnsyncedLibraryFiles(libraryID);
}),
await this.resetUnsyncedLibraryFiles(libraryID);
},
/**
@ -418,7 +419,7 @@ Zotero.Sync.Data.Local = {
},
_getAPIKeyFromLogin: Zotero.Promise.coroutine(function* () {
_getAPIKeyFromLogin: async function () {
let username = Zotero.Prefs.get('sync.server.username');
if (username) {
// Check for legacy password if no password set in current session
@ -428,12 +429,12 @@ Zotero.Sync.Data.Local = {
return "";
}
let json = yield Zotero.Sync.Runner.createAPIKeyFromCredentials(username, password);
let json = await Zotero.Sync.Runner.createAPIKeyFromCredentials(username, password);
this.removeLegacyLogins();
return json.key;
}
return "";
}),
},
getLegacyPassword: function (username) {
@ -516,11 +517,11 @@ Zotero.Sync.Data.Local = {
},
_loadLastSyncTime: Zotero.Promise.coroutine(function* () {
_loadLastSyncTime: async function () {
var sql = "SELECT version FROM version WHERE schema='lastsync'";
var lastsync = yield Zotero.DB.valueQueryAsync(sql);
var lastsync = await Zotero.DB.valueQueryAsync(sql);
_lastSyncTime = (lastsync ? new Date(lastsync * 1000) : false);
}),
},
/**
@ -540,7 +541,7 @@ Zotero.Sync.Data.Local = {
* @param {Integer} libraryID
* @return {Promise<Integer[]>} - A promise for an array of object ids
*/
getUnsynced: Zotero.Promise.coroutine(function* (objectType, libraryID) {
getUnsynced: async function (objectType, libraryID) {
var objectsClass = Zotero.DataObjectUtilities.getObjectsClassForObjectType(objectType);
var sql = "SELECT O." + objectsClass.idColumn + " FROM " + objectsClass.table + " O";
if (objectType == 'item') {
@ -554,7 +555,7 @@ Zotero.Sync.Data.Local = {
sql += " AND (IAn.isExternal IS NULL OR IAN.isExternal=0)";
}
var ids = yield Zotero.DB.columnQueryAsync(sql, [libraryID]);
var ids = await Zotero.DB.columnQueryAsync(sql, [libraryID]);
// Sort descendent collections last
if (objectType == 'collection') {
@ -568,7 +569,7 @@ Zotero.Sync.Data.Local = {
let c = Zotero.Collections.get(e.collectionID);
Zotero.debug(`Removing parent collection ${c.parentKey} from collection ${c.key}`);
c.parentID = null;
yield c.saveTx();
await c.saveTx();
return this.getUnsynced(...arguments);
}
else {
@ -581,7 +582,7 @@ Zotero.Sync.Data.Local = {
}
return ids;
}),
},
isSyncItem: function (item) {
@ -601,13 +602,13 @@ Zotero.Sync.Data.Local = {
* @return {Promise<Object>} - A promise for an object with object keys as keys and versions
* as properties
*/
getLatestCacheObjectVersions: Zotero.Promise.coroutine(function* (objectType, libraryID, keys=[]) {
getLatestCacheObjectVersions: async function (objectType, libraryID, keys=[]) {
var versions = {};
yield Zotero.Utilities.Internal.forEachChunkAsync(
await Zotero.Utilities.Internal.forEachChunkAsync(
keys,
Zotero.DB.MAX_BOUND_PARAMETERS - 2,
Zotero.Promise.coroutine(function* (chunk) {
async function (chunk) {
// The MAX(version) ensures we get the data from the most recent version of the object,
// thanks to SQLite 3.7.11 (http://www.sqlite.org/releaselog/3_7_11.html)
var sql = "SELECT key, MAX(version) AS version FROM syncCache "
@ -619,17 +620,17 @@ Zotero.Sync.Data.Local = {
params = params.concat(chunk);
}
sql += "GROUP BY libraryID, key";
var rows = yield Zotero.DB.queryAsync(sql, params);
var rows = await Zotero.DB.queryAsync(sql, params);
for (let i = 0; i < rows.length; i++) {
let row = rows[i];
versions[row.key] = row.version;
}
})
}
);
return versions;
}),
},
/**
@ -657,11 +658,11 @@ Zotero.Sync.Data.Local = {
/**
* @return {Promise}
*/
getCacheObject: Zotero.Promise.coroutine(function* (objectType, libraryID, key, version) {
getCacheObject: async function (objectType, libraryID, key, version) {
var sql = "SELECT data FROM syncCache WHERE libraryID=? AND key=? AND version=? "
+ "AND syncObjectTypeID IN (SELECT syncObjectTypeID FROM "
+ "syncObjectTypes WHERE name=?)";
var data = yield Zotero.DB.valueQueryAsync(sql, [libraryID, key, version, objectType]);
var data = await Zotero.DB.valueQueryAsync(sql, [libraryID, key, version, objectType]);
if (data) {
try {
return JSON.parse(data);
@ -673,13 +674,13 @@ Zotero.Sync.Data.Local = {
}
}
return false;
}),
},
getCacheObjects: Zotero.Promise.coroutine(function* (objectType, libraryID, keyVersionPairs) {
getCacheObjects: async function (objectType, libraryID, keyVersionPairs) {
if (!keyVersionPairs.length) return [];
var rows = [];
yield Zotero.Utilities.Internal.forEachChunkAsync(
await Zotero.Utilities.Internal.forEachChunkAsync(
keyVersionPairs,
240, // SQLITE_MAX_COMPOUND_SELECT defaults to 500
async function (chunk) {
@ -691,14 +692,14 @@ Zotero.Sync.Data.Local = {
+ ") AS pairs ON (pairs.key=SC.key AND pairs.version=SC.version) "
+ "WHERE libraryID=? AND "
+ "syncObjectTypeID IN (SELECT syncObjectTypeID FROM syncObjectTypes WHERE name=?)";
rows.push(...await Zotero.DB.columnQueryAsync(sql, [libraryID, objectType]));
rows.push(...(await Zotero.DB.columnQueryAsync(sql, [libraryID, objectType])));
}
)
return rows.map(row => JSON.parse(row));
}),
},
saveCacheObject: Zotero.Promise.coroutine(function* (objectType, libraryID, json) {
saveCacheObject: async function (objectType, libraryID, json) {
json = this._checkCacheJSON(json);
Zotero.debug("Saving to sync cache:");
@ -709,10 +710,10 @@ Zotero.Sync.Data.Local = {
+ "(libraryID, key, syncObjectTypeID, version, data) VALUES (?, ?, ?, ?, ?)";
var params = [libraryID, json.key, syncObjectTypeID, json.version, JSON.stringify(json)];
return Zotero.DB.queryAsync(sql, params);
}),
},
saveCacheObjects: Zotero.Promise.coroutine(function* (objectType, libraryID, jsonArray) {
saveCacheObjects: async function (objectType, libraryID, jsonArray) {
if (!Array.isArray(jsonArray)) {
throw new Error("'json' must be an array");
}
@ -735,7 +736,7 @@ Zotero.Sync.Data.Local = {
return Zotero.Utilities.Internal.forEachChunkAsync(
jsonArray,
chunkSize,
Zotero.Promise.coroutine(function* (chunk) {
async function (chunk) {
var params = [];
for (let i = 0; i < chunk.length; i++) {
let o = chunk[i];
@ -744,9 +745,9 @@ Zotero.Sync.Data.Local = {
return Zotero.DB.queryAsync(
sql + chunk.map(() => "(?, ?, ?, ?, ?)").join(", "), params
);
})
}
);
}),
},
/**
@ -765,7 +766,7 @@ Zotero.Sync.Data.Local = {
* as returned by _reconcileChanges()
* {Object[]} [conflicts] - An array of conflicting fields that can't be resolved automatically
*/
processObjectsFromJSON: Zotero.Promise.coroutine(function* (objectType, libraryID, json, options = {}) {
processObjectsFromJSON: async function (objectType, libraryID, json, options = {}) {
var objectsClass = Zotero.DataObjectUtilities.getObjectsClassForObjectType(objectType);
var objectTypePlural = Zotero.DataObjectUtilities.getObjectTypePlural(objectType);
var ObjectType = Zotero.Utilities.capitalize(objectType);
@ -809,7 +810,7 @@ Zotero.Sync.Data.Local = {
for (let i = 0; i < json.length; i++) {
// Batch notifier updates
if (notifierQueues.length == batchSize) {
yield Zotero.Notifier.commit(notifierQueues);
await Zotero.Notifier.commit(notifierQueues);
notifierQueues = [];
// Get the current batch size, which might have increased
if (options.getNotifierBatchSize) {
@ -840,7 +841,7 @@ Zotero.Sync.Data.Local = {
let parentProp = 'parent' + objectType[0].toUpperCase() + objectType.substr(1);
let parentKey = jsonData[parentProp];
if (parentKey) {
let parentObj = yield objectsClass.getByLibraryAndKeyAsync(
let parentObj = await objectsClass.getByLibraryAndKeyAsync(
libraryID, parentKey, { noCache: true }
);
if (!parentObj) {
@ -879,8 +880,8 @@ Zotero.Sync.Data.Local = {
// If the collection is in the delete log, the deletion will upload
// after downloads are done. Otherwise, we somehow missed
// downloading it and should add it to the queue to try again.
if (!(yield this.getDateDeleted('collection', libraryID, key))) {
yield this.addObjectsToSyncQueue('collection', libraryID, [key]);
if (!((await this.getDateDeleted('collection', libraryID, key)))) {
await this.addObjectsToSyncQueue('collection', libraryID, [key]);
}
break;
}
@ -894,7 +895,7 @@ Zotero.Sync.Data.Local = {
// Errors have to be thrown in order to roll back the transaction, so catch those here
// and continue
try {
yield Zotero.DB.executeTransaction(async function () {
await Zotero.DB.executeTransaction(async function () {
let obj = await objectsClass.getByLibraryAndKeyAsync(
libraryID, objectKey, { noCache: true }
);
@ -1151,12 +1152,12 @@ Zotero.Sync.Data.Local = {
}
}
yield Zotero.Promise.delay(10);
await Zotero.Promise.delay(10);
}
}
finally {
if (notifierQueues.length) {
yield Zotero.Notifier.commit(notifierQueues);
await Zotero.Notifier.commit(notifierQueues);
}
}
@ -1170,7 +1171,7 @@ Zotero.Sync.Data.Local = {
+ " in " + libraryName);
return results;
}),
},
_checkCacheJSON: function (json) {
@ -1270,7 +1271,7 @@ Zotero.Sync.Data.Local = {
/**
* Delete entries from sync cache that don't exist or are less than the current object version
*/
purgeCache: Zotero.Promise.coroutine(function* (objectType, libraryID) {
purgeCache: async function (objectType, libraryID) {
var syncObjectTypeID = Zotero.Sync.Data.Utilities.getSyncObjectTypeID(objectType);
var table = Zotero.DataObjectUtilities.getObjectsClassForObjectType(objectType).table;
var sql = "DELETE FROM syncCache WHERE ROWID IN ("
@ -1278,8 +1279,8 @@ Zotero.Sync.Data.Local = {
+ `LEFT JOIN ${table} O USING (libraryID, key, version) `
+ "WHERE syncObjectTypeID=? AND SC.libraryID=? AND "
+ "(O.libraryID IS NULL OR SC.version < O.version))";
yield Zotero.DB.queryAsync(sql, [syncObjectTypeID, libraryID]);
}),
await Zotero.DB.queryAsync(sql, [syncObjectTypeID, libraryID]);
},
clearCacheForLibrary: async function (libraryID) {
@ -1287,7 +1288,7 @@ Zotero.Sync.Data.Local = {
},
processConflicts: Zotero.Promise.coroutine(function* (objectType, libraryID, conflicts, options = {}) {
processConflicts: async function (objectType, libraryID, conflicts, options = {}) {
if (!conflicts.length) return [];
var objectsClass = Zotero.DataObjectUtilities.getObjectsClassForObjectType(objectType);
@ -1330,7 +1331,7 @@ Zotero.Sync.Data.Local = {
for (let i = 0; i < mergeData.length; i++) {
// Batch notifier updates, despite multiple transactions
if (notifierQueues.length == batchSize) {
yield Zotero.Notifier.commit(notifierQueues);
await Zotero.Notifier.commit(notifierQueues);
notifierQueues = [];
}
let notifierQueue = new Zotero.Notifier.Queue;
@ -1353,7 +1354,7 @@ Zotero.Sync.Data.Local = {
// Errors have to be thrown in order to roll back the transaction, so catch
// those here and continue
try {
yield Zotero.DB.executeTransaction(async function () {
await Zotero.DB.executeTransaction(async function () {
let obj = await objectsClass.getByLibraryAndKeyAsync(
libraryID, json.key, { noCache: true }
);
@ -1430,12 +1431,12 @@ Zotero.Sync.Data.Local = {
}
finally {
if (notifierQueues.length) {
yield Zotero.Notifier.commit(notifierQueues);
await Zotero.Notifier.commit(notifierQueues);
}
}
return results;
}),
},
showConflictResolutionWindow: function (conflicts) {
@ -1484,13 +1485,13 @@ Zotero.Sync.Data.Local = {
return _lastClassicSyncTime;
},
_loadLastClassicSyncTime: Zotero.Promise.coroutine(function* () {
_loadLastClassicSyncTime: async function () {
var sql = "SELECT version FROM version WHERE schema='lastlocalsync'";
var lastsync = yield Zotero.DB.valueQueryAsync(sql);
var lastsync = await Zotero.DB.valueQueryAsync(sql);
_lastClassicSyncTime = (lastsync ? new Date(lastsync * 1000) : false);
}),
},
_saveObjectFromJSON: Zotero.Promise.coroutine(function* (obj, json, options) {
_saveObjectFromJSON: async function (obj, json, options) {
var results = {};
try {
results.key = json.key;
@ -1508,20 +1509,20 @@ Zotero.Sync.Data.Local = {
name = name !== '' ? name : username;
// Update stored name if it changed
if (Zotero.Users.getName(userID) != name) {
yield Zotero.Users.setName(userID, name);
await Zotero.Users.setName(userID, name);
}
}
}
if (obj.isStoredFileAttachment()) {
yield this._checkAttachmentForDownload(obj, json.data.mtime, options.isNewObject);
await this._checkAttachmentForDownload(obj, json.data.mtime, options.isNewObject);
}
}
obj.version = json.data.version;
if (!options.saveAsUnsynced) {
obj.synced = true;
}
yield obj.save({
await obj.save({
skipEditCheck: true,
skipDateModifiedUpdate: true,
skipSelect: true,
@ -1533,9 +1534,9 @@ Zotero.Sync.Data.Local = {
}
});
let cacheJSON = options.cacheObject ? options.cacheObject : json.data;
yield this.saveCacheObject(obj.objectType, obj.libraryID, cacheJSON);
await this.saveCacheObject(obj.objectType, obj.libraryID, cacheJSON);
// Delete older versions of the object in the cache
yield this.deleteCacheObjectVersions(
await this.deleteCacheObjectVersions(
obj.objectType,
obj.libraryID,
json.key,
@ -1545,7 +1546,7 @@ Zotero.Sync.Data.Local = {
results.processed = true;
// Delete from sync queue
yield this._removeObjectFromSyncQueue(obj.objectType, obj.libraryID, json.key);
await this._removeObjectFromSyncQueue(obj.objectType, obj.libraryID, json.key);
// Mark updated attachments for download
if (obj.objectType == 'item' && obj.isStoredFileAttachment()) {
@ -1562,7 +1563,7 @@ Zotero.Sync.Data.Local = {
for (let c of options.newParentItemCollections) {
parentItem.addToCollection(c);
}
yield parentItem.save({
await parentItem.save({
skipEditCheck: true,
skipDateModifiedUpdate: true,
skipSelect: true,
@ -1581,7 +1582,7 @@ Zotero.Sync.Data.Local = {
results.retry = false;
}
return results;
}),
},
/**
@ -1847,57 +1848,57 @@ Zotero.Sync.Data.Local = {
},
markObjectAsSynced: Zotero.Promise.method(function (obj) {
markObjectAsSynced: function (obj) {
obj.synced = true;
return obj.saveTx({ skipAll: true });
}),
},
markObjectAsUnsynced: Zotero.Promise.method(function (obj) {
markObjectAsUnsynced: function (obj) {
obj.synced = false;
return obj.saveTx({ skipAll: true });
}),
},
/**
* @return {Promise<Date|false>}
*/
getDateDeleted: Zotero.Promise.coroutine(function* (objectType, libraryID, key) {
getDateDeleted: async function (objectType, libraryID, key) {
var syncObjectTypeID = Zotero.Sync.Data.Utilities.getSyncObjectTypeID(objectType);
var sql = "SELECT dateDeleted FROM syncDeleteLog WHERE libraryID=? AND key=? "
+ "AND syncObjectTypeID=?";
var date = yield Zotero.DB.valueQueryAsync(sql, [libraryID, key, syncObjectTypeID]);
var date = await Zotero.DB.valueQueryAsync(sql, [libraryID, key, syncObjectTypeID]);
return date ? Zotero.Date.sqlToDate(date, true) : false;
}),
},
/**
* @return {Promise<String[]>} - Promise for array of keys
*/
getDeleted: Zotero.Promise.coroutine(function* (objectType, libraryID) {
getDeleted: async function (objectType, libraryID) {
var syncObjectTypeID = Zotero.Sync.Data.Utilities.getSyncObjectTypeID(objectType);
var sql = "SELECT key FROM syncDeleteLog WHERE libraryID=? AND syncObjectTypeID=?";
return Zotero.DB.columnQueryAsync(sql, [libraryID, syncObjectTypeID]);
}),
},
/**
* @return {Promise}
*/
removeObjectsFromDeleteLog: function (objectType, libraryID, keys) {
if (!keys.length) Zotero.Promise.resolve();
if (!keys.length) Promise.resolve();
var syncObjectTypeID = Zotero.Sync.Data.Utilities.getSyncObjectTypeID(objectType);
var sql = "DELETE FROM syncDeleteLog WHERE libraryID=? AND syncObjectTypeID=? AND key IN (";
return Zotero.Utilities.Internal.forEachChunkAsync(
keys,
Zotero.DB.MAX_BOUND_PARAMETERS - 2,
Zotero.Promise.coroutine(function* (chunk) {
async function (chunk) {
var params = [libraryID, syncObjectTypeID].concat(chunk);
return Zotero.DB.queryAsync(
sql + Array(chunk.length).fill('?').join(',') + ")", params
);
})
}
);
},
@ -1913,7 +1914,7 @@ Zotero.Sync.Data.Local = {
* @param {String[]} keys
* @param {Boolean} [tryImmediately=false] - Assign lastCheck of 0 so item is retried immediately
*/
addObjectsToSyncQueue: Zotero.Promise.coroutine(function* (objectType, libraryID, keys, tryImmediately) {
addObjectsToSyncQueue: async function (objectType, libraryID, keys, tryImmediately) {
var syncObjectTypeID = Zotero.Sync.Data.Utilities.getSyncObjectTypeID(objectType);
var now = tryImmediately ? 0 : Zotero.Date.getUnixTimestamp();
@ -1923,14 +1924,14 @@ Zotero.Sync.Data.Local = {
// Check current try counts
var sql = "SELECT key, tries FROM syncQueue WHERE ";
yield Zotero.Utilities.Internal.forEachChunkAsync(
await Zotero.Utilities.Internal.forEachChunkAsync(
keys,
Math.floor(Zotero.DB.MAX_BOUND_PARAMETERS / 3),
Zotero.Promise.coroutine(function* (chunk) {
async function (chunk) {
var params = chunk.reduce(
(arr, key) => arr.concat([libraryID, key, syncObjectTypeID]), []
);
var rows = yield Zotero.DB.queryAsync(
var rows = await Zotero.DB.queryAsync(
sql + Array(chunk.length)
.fill('(libraryID=? AND key=? AND syncObjectTypeID=?)')
.join(' OR '),
@ -1939,7 +1940,7 @@ Zotero.Sync.Data.Local = {
for (let row of rows) {
keyTries[row.key] = row.tries + 1; // increment current count
}
})
}
);
// Insert or update
@ -1959,7 +1960,7 @@ Zotero.Sync.Data.Local = {
);
}
);
}),
},
hasObjectsInSyncQueue: function (libraryID) {
@ -1978,8 +1979,8 @@ Zotero.Sync.Data.Local = {
},
hasObjectsToTryInSyncQueue: Zotero.Promise.coroutine(function* (libraryID) {
var rows = yield Zotero.DB.queryAsync(
hasObjectsToTryInSyncQueue: async function (libraryID) {
var rows = await Zotero.DB.queryAsync(
"SELECT key, lastCheck, tries FROM syncQueue WHERE libraryID=?", libraryID
);
for (let row of rows) {
@ -1994,12 +1995,12 @@ Zotero.Sync.Data.Local = {
}
}
return false;
}),
},
getObjectsToTryFromSyncQueue: Zotero.Promise.coroutine(function* (objectType, libraryID) {
getObjectsToTryFromSyncQueue: async function (objectType, libraryID) {
var syncObjectTypeID = Zotero.Sync.Data.Utilities.getSyncObjectTypeID(objectType);
var rows = yield Zotero.DB.queryAsync(
var rows = await Zotero.DB.queryAsync(
"SELECT key, lastCheck, tries FROM syncQueue WHERE libraryID=? AND syncObjectTypeID=?",
[libraryID, syncObjectTypeID]
);
@ -2016,7 +2017,7 @@ Zotero.Sync.Data.Local = {
}
}
return keysToTry;
}),
},
removeObjectsFromSyncQueue: function (objectType, libraryID, keys) {
@ -2025,12 +2026,12 @@ Zotero.Sync.Data.Local = {
return Zotero.Utilities.Internal.forEachChunkAsync(
keys,
Zotero.DB.MAX_BOUND_PARAMETERS - 2,
Zotero.Promise.coroutine(function* (chunk) {
async function (chunk) {
var params = [libraryID, syncObjectTypeID].concat(chunk);
return Zotero.DB.queryAsync(
sql + Array(chunk.length).fill('?').join(',') + ")", params
);
})
}
);
},

View file

@ -119,7 +119,7 @@ Zotero.Sync.Runner_Module = function (options = {}) {
});
this._sync = Zotero.Promise.coroutine(function* (options) {
this._sync = async function (options) {
// Clear message list
_errors = [];
_tooltipMessages = [];
@ -135,9 +135,9 @@ Zotero.Sync.Runner_Module = function (options = {}) {
_stopping = false;
try {
yield Zotero.Notifier.trigger('start', 'sync', []);
await Zotero.Notifier.trigger('start', 'sync', []);
let apiKey = yield _getAPIKey();
let apiKey = await _getAPIKey();
if (!apiKey) {
throw new Zotero.Error("API key not set", Zotero.Error.ERROR_API_KEY_NOT_SET);
}
@ -154,7 +154,7 @@ Zotero.Sync.Runner_Module = function (options = {}) {
this.setSyncStatus(Zotero.getString('sync.status.waiting'));
let delay = _delaySyncUntil - new Date();
Zotero.debug(`Waiting ${delay} ms to sync`);
yield Zotero.Promise.delay(delay);
await Zotero.Promise.delay(delay);
}
// If paused, wait until we're done
@ -162,7 +162,7 @@ Zotero.Sync.Runner_Module = function (options = {}) {
if (_delayPromises.some(p => p.isPending())) {
this.setSyncStatus(Zotero.getString('sync.status.waiting'));
Zotero.debug("Syncing is paused -- waiting to sync");
yield Zotero.Promise.all(_delayPromises);
await Promise.all(_delayPromises);
// If more were added, continue
if (_delayPromises.some(p => p.isPending())) {
continue;
@ -179,18 +179,18 @@ Zotero.Sync.Runner_Module = function (options = {}) {
while (Zotero.DB.inTransaction()) {
this.setSyncStatus(Zotero.getString('sync.status.waiting'));
Zotero.debug("Transaction in progress -- waiting to sync");
yield Zotero.DB.waitForTransaction('sync');
await Zotero.DB.waitForTransaction('sync');
_stopCheck();
}
this.setSyncStatus(Zotero.getString('sync.status.preparing'));
let client = this.getAPIClient({ apiKey });
let keyInfo = yield this.checkAccess(client, options);
let keyInfo = await this.checkAccess(client, options);
_stopCheck();
let emptyLibraryContinue = yield this.checkEmptyLibrary(keyInfo);
let emptyLibraryContinue = await this.checkEmptyLibrary(keyInfo);
if (!emptyLibraryContinue) {
Zotero.debug("Syncing cancelled because user library is empty");
return false;
@ -199,7 +199,7 @@ Zotero.Sync.Runner_Module = function (options = {}) {
let wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
let lastWin = wm.getMostRecentWindow("navigator:browser");
let ok = yield Zotero.Sync.Data.Local.checkUser(
let ok = await Zotero.Sync.Data.Local.checkUser(
lastWin,
keyInfo.userID,
keyInfo.username,
@ -234,7 +234,7 @@ Zotero.Sync.Runner_Module = function (options = {}) {
resetMode: options.resetMode
};
var librariesToSync = options.libraries = yield this.checkLibraries(
var librariesToSync = options.libraries = await this.checkLibraries(
client,
options,
keyInfo,
@ -260,7 +260,7 @@ Zotero.Sync.Runner_Module = function (options = {}) {
for (let libraryID of librariesToSync) {
let library = Zotero.Libraries.get(libraryID);
if (!library.getDataLoaded('item')) {
yield library.waitForDataLoad('item');
await library.waitForDataLoad('item');
}
}
@ -276,7 +276,7 @@ Zotero.Sync.Runner_Module = function (options = {}) {
// TODO: Back off and/or nicer error
throw new Error("Too many sync attempts -- stopping");
}
let nextLibraries = yield _doDataSync(librariesToSync, engineOptions);
let nextLibraries = await _doDataSync(librariesToSync, engineOptions);
// Remove failed libraries from the successful set
Zotero.Utilities.arrayDiff(librariesToSync, nextLibraries).forEach(libraryID => {
successfulLibraries.delete(libraryID);
@ -285,7 +285,7 @@ Zotero.Sync.Runner_Module = function (options = {}) {
_stopCheck();
// Run file sync on all allowed libraries that passed the last data sync
librariesToSync = yield _doFileSync(
librariesToSync = await _doFileSync(
nextLibraries.filter(libraryID => fileLibrariesToSync.has(libraryID)),
engineOptions
);
@ -297,7 +297,7 @@ Zotero.Sync.Runner_Module = function (options = {}) {
_stopCheck();
// Run full-text sync on all allowed libraries that haven't failed a data sync
librariesToSync = yield _doFullTextSync(
librariesToSync = await _doFullTextSync(
[...successfulLibraries].filter(libraryID => fullTextLibrariesToSync.has(libraryID)),
engineOptions
);
@ -328,32 +328,32 @@ Zotero.Sync.Runner_Module = function (options = {}) {
}
}
finally {
yield this.end(options);
await this.end(options);
if (options.restartSync) {
delete options.restartSync;
Zotero.debug("Restarting sync");
yield this._sync(options);
await this._sync(options);
return;
}
// If an auto-sync was queued while a sync was ongoing, start again with its options
else if (_queuedSyncOptions.length) {
Zotero.debug("Restarting sync");
yield this._sync(JSON.parse(_queuedSyncOptions.shift()));
await this._sync(JSON.parse(_queuedSyncOptions.shift()));
return;
}
Zotero.debug("Done syncing");
Zotero.Notifier.trigger('finish', 'sync', librariesToSync || []);
}
});
};
/**
* Check key for current user info and return access info
*/
this.checkAccess = Zotero.Promise.coroutine(function* (client, options={}) {
var json = yield client.getKeyInfo(options);
this.checkAccess = async function (client, options={}) {
var json = await client.getKeyInfo(options);
Zotero.debug(json);
if (!json) {
throw new Zotero.Error("API key not set", Zotero.Error.ERROR_API_KEY_INVALID);
@ -365,17 +365,17 @@ Zotero.Sync.Runner_Module = function (options = {}) {
if (!json.access) throw new Error("'access' not found in key response");
return json;
});
};
// Prompt if library empty and there is no userID stored
this.checkEmptyLibrary = Zotero.Promise.coroutine(function* (keyInfo) {
this.checkEmptyLibrary = async function (keyInfo) {
let library = Zotero.Libraries.userLibrary;
let feeds = Zotero.Feeds.getAll();
let userID = Zotero.Users.getCurrentUserID();
if (!userID) {
let hasItems = yield library.hasItems();
let hasItems = await library.hasItems();
if (!hasItems && feeds.length <= 0 && !Zotero.resetDataDir) {
let ps = Services.prompt;
let index = ps.confirmEx(
@ -414,13 +414,13 @@ Zotero.Sync.Runner_Module = function (options = {}) {
}
}
return true;
});
};
/**
* @return {Promise<Integer[]> - IDs of libraries to sync
*/
this.checkLibraries = Zotero.Promise.coroutine(function* (client, options, keyInfo, libraries = []) {
this.checkLibraries = async function (client, options, keyInfo, libraries = []) {
var access = keyInfo.access;
var syncAllLibraries = !libraries || !libraries.length;
@ -468,7 +468,7 @@ Zotero.Sync.Runner_Module = function (options = {}) {
throw new Error("Full group access is currently required");
}
let remoteGroupVersions = yield client.getGroupVersions(keyInfo.userID);
let remoteGroupVersions = await client.getGroupVersions(keyInfo.userID);
let remoteGroupIDs = Object.keys(remoteGroupVersions).map(id => parseInt(id));
let skippedGroups = Zotero.Sync.Data.Local.getSkippedGroups();
@ -590,7 +590,7 @@ Zotero.Sync.Runner_Module = function (options = {}) {
let removedLibraryIDs = [];
for (let group of removedGroups) {
removedLibraryIDs.push(group.libraryID);
yield group.eraseTx();
await group.eraseTx();
}
libraries = Zotero.Utilities.arrayDiff(libraries, removedLibraryIDs);
@ -599,14 +599,14 @@ Zotero.Sync.Runner_Module = function (options = {}) {
keptLibraryIDs.push(group.libraryID);
group.editable = false;
group.archived = true;
yield group.saveTx();
await group.saveTx();
}
libraries = Zotero.Utilities.arrayDiff(libraries, keptLibraryIDs);
}
// Update metadata and permissions on missing or outdated groups
for (let groupID of groupsToDownload) {
let info = yield client.getGroup(groupID);
let info = await client.getGroup(groupID);
if (!info) {
throw new Error("Group " + groupID + " not found");
}
@ -617,7 +617,7 @@ Zotero.Sync.Runner_Module = function (options = {}) {
let { editable, filesEditable } = Zotero.Groups.getPermissionsFromJSON(
info.data, keyInfo.userID
);
let keepGoing = yield Zotero.Sync.Data.Local.checkLibraryForAccess(
let keepGoing = await Zotero.Sync.Data.Local.checkLibraryForAccess(
null, group.libraryID, editable, filesEditable
);
// User chose to skip library
@ -633,7 +633,7 @@ Zotero.Sync.Runner_Module = function (options = {}) {
group.version = info.version;
group.archived = false;
group.fromJSON(info.data, Zotero.Users.getCurrentUserID());
yield group.saveTx();
await group.saveTx();
// Add group to library list
libraries.push(group.libraryID);
@ -644,7 +644,7 @@ Zotero.Sync.Runner_Module = function (options = {}) {
Zotero.debug(libraries);
return [...new Set(libraries)];
});
};
/**
@ -655,7 +655,7 @@ Zotero.Sync.Runner_Module = function (options = {}) {
* @param {Boolean} skipUpdateLastSyncTime
* @return {Integer[]} - Array of libraryIDs that completed successfully
*/
var _doDataSync = Zotero.Promise.coroutine(function* (libraries, options, skipUpdateLastSyncTime) {
var _doDataSync = async function (libraries, options, skipUpdateLastSyncTime) {
var successfulLibraries = [];
for (let libraryID of libraries) {
_stopCheck();
@ -665,7 +665,7 @@ Zotero.Sync.Runner_Module = function (options = {}) {
opts.libraryID = libraryID;
_currentEngine = new Zotero.Sync.Data.Engine(opts);
yield _currentEngine.start();
await _currentEngine.start();
_currentEngine = null;
successfulLibraries.push(libraryID);
}
@ -693,16 +693,16 @@ Zotero.Sync.Runner_Module = function (options = {}) {
// Update last-sync time if any libraries synced
// TEMP: Do we want to show updated time if some libraries haven't synced?
if (!libraries.length || successfulLibraries.length) {
yield Zotero.Sync.Data.Local.updateLastSyncTime();
await Zotero.Sync.Data.Local.updateLastSyncTime();
}
return successfulLibraries;
}.bind(this));
}.bind(this);
/**
* @return {Integer[]} - Array of libraries that need data syncing again
*/
var _doFileSync = Zotero.Promise.coroutine(function* (libraries, options) {
var _doFileSync = async function (libraries, options) {
Zotero.debug("Starting file syncing");
var resyncLibraries = []
for (let libraryID of libraries) {
@ -737,7 +737,7 @@ Zotero.Sync.Runner_Module = function (options = {}) {
}
tries--;
_currentEngine = new Zotero.Sync.Storage.Engine(opts);
let results = yield _currentEngine.start();
let results = await _currentEngine.start();
_currentEngine = null;
if (results.syncRequired) {
resyncLibraries.push(libraryID);
@ -774,13 +774,13 @@ Zotero.Sync.Runner_Module = function (options = {}) {
Zotero.debug("Libraries to resync: " + resyncLibraries.join(", "));
}
return resyncLibraries;
}.bind(this));
}.bind(this);
/**
* @return {Integer[]} - Array of libraries that need data syncing again
*/
var _doFullTextSync = Zotero.Promise.coroutine(function* (libraries, options) {
var _doFullTextSync = async function (libraries, options) {
if (!Zotero.Prefs.get("sync.fulltext.enabled")) return [];
Zotero.debug("Starting full-text syncing");
@ -794,7 +794,7 @@ Zotero.Sync.Runner_Module = function (options = {}) {
opts.libraryID = libraryID;
_currentEngine = new Zotero.Sync.Data.FullTextEngine(opts);
yield _currentEngine.start();
await _currentEngine.start();
_currentEngine = null;
}
catch (e) {
@ -821,7 +821,7 @@ Zotero.Sync.Runner_Module = function (options = {}) {
Zotero.debug("Libraries to resync: " + resyncLibraries.join(", "));
}
return resyncLibraries;
}.bind(this));
}.bind(this);
/**
@ -845,13 +845,13 @@ Zotero.Sync.Runner_Module = function (options = {}) {
/**
* Download a single file on demand (not within a sync process)
*/
this.downloadFile = Zotero.Promise.coroutine(function* (item, requestCallbacks) {
this.downloadFile = async function (item, requestCallbacks) {
if (Zotero.HTTP.browserIsOffline()) {
Zotero.debug("Browser is offline", 2);
return false;
}
var apiKey = yield _getAPIKey();
var apiKey = await _getAPIKey();
if (!apiKey) {
Zotero.debug("API key not set -- skipping download");
return false;
@ -876,7 +876,7 @@ Zotero.Sync.Runner_Module = function (options = {}) {
throw new Error("Not a stored file attachment");
}
if (yield item.getFilePathAsync()) {
if (await item.getFilePathAsync()) {
Zotero.debug("File already exists -- replacing");
}
@ -898,7 +898,7 @@ Zotero.Sync.Runner_Module = function (options = {}) {
: [onStart]
});
return request.start();
});
};
this.stop = function () {
@ -1119,17 +1119,17 @@ Zotero.Sync.Runner_Module = function (options = {}) {
}
this.checkErrors = Zotero.Promise.coroutine(function* (errors, options = {}) {
this.checkErrors = async function (errors, options = {}) {
for (let e of errors) {
let handled = yield this.checkError(e, options);
let handled = await this.checkError(e, options);
if (handled) {
break;
}
}
});
};
this.checkError = Zotero.Promise.coroutine(function* (e, options = {}) {
this.checkError = async function (e, options = {}) {
if (e.name && e.name == 'Zotero Error') {
switch (e.error) {
case Zotero.Error.ERROR_API_KEY_NOT_SET:
@ -1206,13 +1206,13 @@ Zotero.Sync.Runner_Module = function (options = {}) {
if (data && data.tag !== undefined) {
// Show long tag fixer and handle result
e.dialogButtonText = Zotero.getString('general.fix');
e.dialogButtonCallback = Zotero.Promise.coroutine(function* () {
e.dialogButtonCallback = async function () {
var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
var lastWin = wm.getMostRecentWindow("navigator:browser");
// Open long tag fixer for library we're syncing
let oldTagIDs = yield Zotero.Tags.getLongTagsInLibrary(object.libraryID);
let oldTagIDs = await Zotero.Tags.getLongTagsInLibrary(object.libraryID);
for (let oldTagID of oldTagIDs) {
let oldTag = Zotero.Tags.getName(oldTagID);
@ -1228,11 +1228,11 @@ Zotero.Sync.Runner_Module = function (options = {}) {
if (!dataOut.result) {
return;
}
const itemIDs = yield Zotero.Tags.getTagItems(object.libraryID, oldTagID);
const itemIDs = await Zotero.Tags.getTagItems(object.libraryID, oldTagID);
switch (dataOut.result.op) {
case 'split':
yield Zotero.DB.executeTransaction(async function () {
await Zotero.DB.executeTransaction(async function () {
for (let itemID of itemIDs) {
let item = await Zotero.Items.getAsync(itemID);
let tagType = item.getTagType(oldTag);
@ -1247,7 +1247,7 @@ Zotero.Sync.Runner_Module = function (options = {}) {
break;
case 'edit':
yield Zotero.DB.executeTransaction(async function () {
await Zotero.DB.executeTransaction(async function () {
for (let itemID of itemIDs) {
let item = await Zotero.Items.getAsync(itemID);
item.replaceTag(oldTag, dataOut.result.tag);
@ -1257,13 +1257,13 @@ Zotero.Sync.Runner_Module = function (options = {}) {
break;
case 'delete':
yield Zotero.Tags.removeFromLibrary(object.libraryID, oldTagID);
await Zotero.Tags.removeFromLibrary(object.libraryID, oldTagID);
break;
}
}
options.restartSync = true;
});
};
e.dialogButtonImmediate = true;
}
else {
@ -1342,7 +1342,7 @@ Zotero.Sync.Runner_Module = function (options = {}) {
e.errorType = 'ignore';
}
}
});
};
/**
@ -1543,7 +1543,7 @@ Zotero.Sync.Runner_Module = function (options = {}) {
var buttonCallback = e.dialogButtonCallback;
}
// eslint-disable-next-line no-inner-declarations
function addEventHandlers(button, cb) {
button.addEventListener("click", () => {
cb();
@ -1650,9 +1650,9 @@ Zotero.Sync.Runner_Module = function (options = {}) {
}
this.createAPIKeyFromCredentials = Zotero.Promise.coroutine(function* (username, password) {
this.createAPIKeyFromCredentials = async function (username, password) {
var client = this.getAPIClient();
var json = yield client.createAPIKeyFromCredentials(username, password);
var json = await client.createAPIKeyFromCredentials(username, password);
if (!json) {
return false;
}
@ -1662,19 +1662,19 @@ Zotero.Sync.Runner_Module = function (options = {}) {
if (!json.username) throw new Error("username not found in key response");
if (!json.access) throw new Error("'access' not found in key response");
yield Zotero.Sync.Data.Local.setAPIKey(json.key);
await Zotero.Sync.Data.Local.setAPIKey(json.key);
return json;
})
}
this.deleteAPIKey = Zotero.Promise.coroutine(function* (){
this.deleteAPIKey = async function () {
this.resetStorageController('zfs');
var apiKey = yield Zotero.Sync.Data.Local.getAPIKey();
var apiKey = await Zotero.Sync.Data.Local.getAPIKey();
var client = this.getAPIClient({apiKey});
yield Zotero.Sync.Data.Local.setAPIKey();
yield client.deleteAPIKey();
})
await Zotero.Sync.Data.Local.setAPIKey();
await client.deleteAPIKey();
}
function _addTooltipMessage(msg) {
@ -1734,10 +1734,10 @@ Zotero.Sync.Runner_Module = function (options = {}) {
}
var _getAPIKey = Zotero.Promise.method(function () {
var _getAPIKey = function () {
// Set as .apiKey on Runner in tests or set in login manager
return _apiKey || Zotero.Sync.Data.Local.getAPIKey()
})
}
function _stopCheck() {

View file

@ -30,15 +30,15 @@ if (!Zotero.Sync.Data) {
Zotero.Sync.Data.Utilities = {
_syncObjectTypeIDs: {},
init: Zotero.Promise.coroutine(function* () {
init: async function () {
// If not found, cache all
var sql = "SELECT name, syncObjectTypeID AS id FROM syncObjectTypes";
var rows = yield Zotero.DB.queryAsync(sql);
var rows = await Zotero.DB.queryAsync(sql);
for (let i = 0; i < rows.length; i++) {
row = rows[i];
this._syncObjectTypeIDs[row.name] = row.id;
}
}),
},
getSyncObjectTypeID: function (objectType) {
if (!this._syncObjectTypeIDs[objectType]) {

View file

@ -42,7 +42,7 @@ Zotero.SyncedSettings = (function () {
*/
onSyncDownload: {
listeners: {},
addListener: function(libraryID, setting, fn, bindTarget=null) {
addListener: function (libraryID, setting, fn, bindTarget=null) {
if (!this.listeners[libraryID]) {
this.listeners[libraryID] = {};
}
@ -58,16 +58,16 @@ Zotero.SyncedSettings = (function () {
* @param {Object} newValue
* @param {Boolean} conflict - true if both client and remote values had changed before sync
*/
trigger: Zotero.Promise.coroutine(function* (libraryID, setting, oldValue, newValue, conflict) {
trigger: async function (libraryID, setting, oldValue, newValue, conflict) {
var libListeners = this.listeners[libraryID] || {};
var settingListeners = libListeners[setting] || [];
Array.prototype.splice.call(arguments, 0, 2);
if (settingListeners) {
for (let listener of settingListeners) {
yield Zotero.Promise.resolve(listener[0].apply(listener[1], arguments));
await Promise.resolve(listener[0].apply(listener[1], arguments));
}
}
})
}
},
loadAll: async function (libraryID) {
@ -185,24 +185,24 @@ Zotero.SyncedSettings = (function () {
};
},
getUnsynced: Zotero.Promise.coroutine(function* (libraryID) {
getUnsynced: async function (libraryID) {
var sql = "SELECT setting, value FROM syncedSettings WHERE synced=0 AND libraryID=?";
var rows = yield Zotero.DB.queryAsync(sql, libraryID);
var rows = await Zotero.DB.queryAsync(sql, libraryID);
var obj = {};
rows.forEach(row => obj[row.setting] = JSON.parse(row.value));
return obj;
}),
},
markAsSynced: Zotero.Promise.coroutine(function* (libraryID, settings, version) {
markAsSynced: async function (libraryID, settings, version) {
var sql = "UPDATE syncedSettings SET synced=1, version=? WHERE libraryID=? AND setting IN "
+ "(" + settings.map(x => '?').join(', ') + ")";
yield Zotero.DB.queryAsync(sql, [version, libraryID].concat(settings));
await Zotero.DB.queryAsync(sql, [version, libraryID].concat(settings));
for (let key of settings) {
let setting = _cache[libraryID][key];
setting.synced = true;
setting.version = version;
}
}),
},
/**
* Used for restore-to-server
@ -217,7 +217,7 @@ Zotero.SyncedSettings = (function () {
}
},
set: Zotero.Promise.coroutine(function* (libraryID, setting, value, version = 0, synced) {
set: async function (libraryID, setting, value, version = 0, synced) {
if (typeof value == undefined) {
throw new Error("Value not provided");
}
@ -268,12 +268,12 @@ Zotero.SyncedSettings = (function () {
if (version > 0) {
args.unshift(version)
}
yield Zotero.DB.queryAsync(sql, args);
await Zotero.DB.queryAsync(sql, args);
}
else {
var sql = "INSERT INTO syncedSettings "
+ "(setting, libraryID, value, version, synced) VALUES (?, ?, ?, ?, ?)";
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
sql, [setting, libraryID, JSON.stringify(value), version, synced]
);
}
@ -288,13 +288,13 @@ Zotero.SyncedSettings = (function () {
var conflict = metadata && !metadata.synced && metadata.version < version;
if (version > 0) {
yield this.onSyncDownload.trigger(libraryID, setting, currentValue, value, conflict);
await this.onSyncDownload.trigger(libraryID, setting, currentValue, value, conflict);
}
yield Zotero.Notifier.trigger(event, 'setting', [id], extraData);
await Zotero.Notifier.trigger(event, 'setting', [id], extraData);
return true;
}),
},
clear: Zotero.Promise.coroutine(function* (libraryID, setting, options) {
clear: async function (libraryID, setting, options) {
options = options || {};
var currentValue = this.get(libraryID, setting);
@ -313,13 +313,13 @@ Zotero.SyncedSettings = (function () {
}
var sql = "DELETE FROM syncedSettings WHERE setting=? AND libraryID=?";
yield Zotero.DB.queryAsync(sql, [setting, libraryID]);
await Zotero.DB.queryAsync(sql, [setting, libraryID]);
delete _cache[libraryID][setting];
yield Zotero.Notifier.trigger('delete', 'setting', [id], extraData);
await Zotero.Notifier.trigger('delete', 'setting', [id], extraData);
return true;
})
}
};
return module;

View file

@ -36,7 +36,7 @@ const BOMs = {
Components.utils.import("resource://gre/modules/NetUtil.jsm");
Zotero.Translate.DOMWrapper = new function() {
Zotero.Translate.DOMWrapper = new function () {
var Cu = Components.utils;
/*
@ -132,7 +132,7 @@ Zotero.Translate.DOMWrapper = new function() {
let dummy;
if (typeof obj === "function")
dummy = function() {};
dummy = function () {};
else
dummy = Object.create(null);
@ -167,11 +167,11 @@ Zotero.Translate.DOMWrapper = new function() {
// enumerable.
var _permit = { value: 'rw', writable: false, configurable: false, enumerable: true };
return {
getOwnPropertyDescriptor: function(name) { return _permit; },
ownKeys: function() { throw Error("Can't enumerate ExposedPropsWaiver"); },
enumerate: function() { throw Error("Can't enumerate ExposedPropsWaiver"); },
defineProperty: function(name) { throw Error("Can't define props on ExposedPropsWaiver"); },
deleteProperty: function(name) { throw Error("Can't delete props from ExposedPropsWaiver"); }
getOwnPropertyDescriptor: function (name) { return _permit; },
ownKeys: function () { throw Error("Can't enumerate ExposedPropsWaiver"); },
enumerate: function () { throw Error("Can't enumerate ExposedPropsWaiver"); },
defineProperty: function (name) { throw Error("Can't define props on ExposedPropsWaiver"); },
deleteProperty: function (name) { throw Error("Can't delete props from ExposedPropsWaiver"); }
};
};
ExposedPropsWaiver = new Proxy({}, ExposedPropsWaiverHandler());
@ -328,7 +328,7 @@ Zotero.Translate.DOMWrapper = new function() {
* @param {XPCCrossOriginWrapper} obj
* @return {Object} An obj that is no longer Xrayed
*/
this.wrap = function(obj, overrides) {
this.wrap = function (obj, overrides) {
if(isWrapper(obj)) return obj;
return wrapPrivileged(obj, overrides);
};
@ -336,7 +336,7 @@ Zotero.Translate.DOMWrapper = new function() {
/**
* Unwraps an object
*/
this.unwrap = function(obj) {
this.unwrap = function (obj) {
if(isWrapper(obj)) {
return unwrapPrivileged(obj);
} else {
@ -347,7 +347,7 @@ Zotero.Translate.DOMWrapper = new function() {
/**
* Wraps an object in the same sandbox as another object
*/
this.wrapIn = function(obj, insamebox) {
this.wrapIn = function (obj, insamebox) {
if(insamebox.__wrappingManager) return insamebox.__wrappingManager.wrap(obj);
return this.wrap(obj);
}
@ -365,7 +365,7 @@ Zotero.Translate.DOMWrapper = new function() {
* @param {Translate} translate
* @param {String|window} sandboxLocation
*/
Zotero.Translate.SandboxManager = function(sandboxLocation) {
Zotero.Translate.SandboxManager = function (sandboxLocation) {
this.sandbox = {
Zotero: {},
// As of Fx60, XPathResult is no longer available as nsIDOMXPathResult in XPCOM, so just
@ -382,10 +382,10 @@ Zotero.Translate.SandboxManager = function(sandboxLocation) {
ANY_UNORDERED_NODE_TYPE: 8,
FIRST_ORDERED_NODE_TYPE: 9
},
DOMParser: function() {
DOMParser: function () {
return new DOMParser();
},
XMLSerializer: function() {
XMLSerializer: function () {
return new XMLSerializer();
}
};
@ -398,7 +398,7 @@ Zotero.Translate.SandboxManager.prototype = {
* @param {String[]} functions Functions to import into the sandbox (rather than leaving
* as inner functions)
*/
eval: function(code, functions) {
eval: function (code, functions) {
// delete functions to import
for (var i in functions) {
delete this.sandbox[functions[i]];
@ -418,7 +418,7 @@ Zotero.Translate.SandboxManager.prototype = {
}
// Eval in a closure
(function() {
(function () {
eval(code);
}).call(this);
},
@ -430,16 +430,16 @@ Zotero.Translate.SandboxManager.prototype = {
* @param {Boolean} passTranslateAsFirstArgument Whether the translate instance should be passed
* as the first argument to the function.
*/
importObject: function(object, passAsFirstArgument, attachTo) {
importObject: function (object, passAsFirstArgument, attachTo) {
if(!attachTo) attachTo = this.sandbox.Zotero;
for(var key in (object.__exposedProps__ ? object.__exposedProps__ : object)) {
if(Function.prototype[key]) continue;
if(typeof object[key] === "function" || typeof object[key] === "object") {
// magic closures
attachTo[key] = new function() {
attachTo[key] = new function () {
var fn = object[key];
return function() {
return function () {
var args = (passAsFirstArgument ? [passAsFirstArgument] : []);
for(var i=0; i<arguments.length; i++) {
args.push(arguments[i]);
@ -467,7 +467,7 @@ Zotero.Translate.IO.maintainedInstances = [];
/******* (Native) Read support *******/
Zotero.Translate.IO.Read = function(file, sandboxManager) {
Zotero.Translate.IO.Read = function (file, sandboxManager) {
Zotero.Translate.IO.maintainedInstances.push(this);
this.file = file;
@ -635,14 +635,14 @@ Zotero.Translate.IO.Read.prototype = {
"setCharacterSet":"r"
},
"_openRawStream":function() {
"_openRawStream":function () {
if(this._rawStream) this._rawStream.close();
this._rawStream = Components.classes["@mozilla.org/network/file-input-stream;1"]
.createInstance(Components.interfaces.nsIFileInputStream);
this._rawStream.init(this.file, 0x01, 0o664, 0);
},
"_rewind":function() {
"_rewind":function () {
this._linesExhausted = false;
this._rawStream.QueryInterface(Components.interfaces.nsISeekableStream)
.seek(Components.interfaces.nsISeekableStream.NS_SEEK_SET, this._bomLength);
@ -650,7 +650,7 @@ Zotero.Translate.IO.Read.prototype = {
this.bytesRead = this._bomLength;
},
"_seekToStart":function(charset) {
"_seekToStart":function (charset) {
this._openRawStream();
this._rewind();
@ -661,7 +661,7 @@ Zotero.Translate.IO.Read.prototype = {
Components.interfaces.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
},
"_readToString":function() {
"_readToString":function () {
var str = {};
var stringBits = [];
this.inputStream.QueryInterface(Components.interfaces.nsIUnicharInputStream);
@ -673,7 +673,7 @@ Zotero.Translate.IO.Read.prototype = {
return stringBits.join("");
},
"_initRDF":function() {
"_initRDF":function () {
Zotero.debug("Translate: Initializing RDF data store");
this._dataStore = new Zotero.RDF.AJAW.IndexedFormula();
var parser = new Zotero.RDF.AJAW.RDFParser(this._dataStore);
@ -689,7 +689,7 @@ Zotero.Translate.IO.Read.prototype = {
}
},
"setCharacterSet":function(charset) {
"setCharacterSet":function (charset) {
if(typeof charset !== "string") {
throw new Error("Translate: setCharacterSet: charset must be a string");
}
@ -702,7 +702,7 @@ Zotero.Translate.IO.Read.prototype = {
}
},
"read":function(bytes) {
"read":function (bytes) {
var str = {};
if(bytes) {
@ -722,7 +722,7 @@ Zotero.Translate.IO.Read.prototype = {
return str.value;
},
"getXML":function() {
"getXML":function () {
if(this.bytesRead !== 0) this._seekToStart(this._charset);
try {
var xml = Zotero.Translate.IO.parseDOMXML(this._rawStream, this._charset, this.file.fileSize);
@ -747,7 +747,7 @@ Zotero.Translate.IO.Read.prototype = {
}
},
"close":function() {
"close":function () {
var myIndex = Zotero.Translate.IO.maintainedInstances.indexOf(this);
if(myIndex !== -1) Zotero.Translate.IO.maintainedInstances.splice(myIndex, 1);
@ -758,13 +758,13 @@ Zotero.Translate.IO.Read.prototype = {
}
}
Zotero.Translate.IO.Read.prototype.__defineGetter__("contentLength",
function() {
function () {
return this.file.fileSize;
});
/******* Write support *******/
Zotero.Translate.IO.Write = function(file) {
Zotero.Translate.IO.Write = function (file) {
Zotero.Translate.IO.maintainedInstances.push(this);
this._rawStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
.createInstance(Components.interfaces.nsIFileOutputStream);
@ -779,13 +779,13 @@ Zotero.Translate.IO.Write.prototype = {
"setCharacterSet":"r"
},
"_initRDF":function() {
"_initRDF":function () {
Zotero.debug("Translate: Initializing RDF data store");
this._dataStore = new Zotero.RDF.AJAW.IndexedFormula();
this.RDF = new Zotero.Translate.IO._RDFSandbox(this._dataStore);
},
"setCharacterSet":function(charset) {
"setCharacterSet":function (charset) {
if(typeof charset !== "string") {
throw new Error("Translate: setCharacterSet: charset must be a string");
}
@ -807,7 +807,7 @@ Zotero.Translate.IO.Write.prototype = {
this._processor = processor;
},
"write":function(data) {
"write":function (data) {
if(!this._charset) this.setCharacterSet("UTF-8");
if (this._processor) {
@ -847,7 +847,7 @@ Zotero.Translate.IO.Write.prototype = {
}
},
"close":function() {
"close":function () {
if(Zotero.Translate.IO.rdfDataModes.indexOf(this._mode) !== -1) {
this.write(this.RDF.serialize());
}

View file

@ -38,7 +38,7 @@
* <li>baseURI - URI to which attachment paths should be relative</li>
* <li>saveOptions - Options to pass to DataObject::save() (e.g., skipSelect)</li>
*/
Zotero.Translate.ItemSaver = function(options) {
Zotero.Translate.ItemSaver = function (options) {
// initialize constants
this._IDMap = {};
@ -452,7 +452,7 @@ Zotero.Translate.ItemSaver.prototype = {
},
"saveCollections": Zotero.Promise.coroutine(function* (collections) {
"saveCollections": async function (collections) {
var collectionsToProcess = collections.slice();
// Use first collection passed to translate process as the root
var rootCollectionID = (this._collections && this._collections.length)
@ -460,7 +460,7 @@ Zotero.Translate.ItemSaver.prototype = {
var parentIDs = collections.map(c => null);
var topLevelCollections = [];
yield Zotero.DB.executeTransaction(async function () {
await Zotero.DB.executeTransaction(async function () {
while(collectionsToProcess.length) {
var collection = collectionsToProcess.shift();
var parentID = parentIDs.shift();
@ -503,7 +503,7 @@ Zotero.Translate.ItemSaver.prototype = {
}.bind(this));
return topLevelCollections;
}),
},
/**
* Create a copy of item JSON without irrelevant fields to avoid warnings in Item#fromJSON
@ -577,7 +577,7 @@ Zotero.Translate.ItemSaver.prototype = {
* @return {Zotero.Promise<Zotero.Item|false} - False is returned if attachment
* was not saved due to error or user settings.
*/
_saveAttachment: Zotero.Promise.coroutine(function* (attachment, parentItemID, attachmentCallback) {
_saveAttachment: async function (attachment, parentItemID, attachmentCallback) {
try {
let newAttachment;
@ -588,13 +588,13 @@ Zotero.Translate.ItemSaver.prototype = {
|| attachment.linkMode == Zotero.Attachments.LINK_MODE_LINKED_URL;
if (isLink || this.attachmentMode === Zotero.Translate.ItemSaver.ATTACHMENT_MODE_IGNORE) {
newAttachment = yield this._saveAttachmentLink.apply(this, arguments);
newAttachment = await this._saveAttachmentLink.apply(this, arguments);
}
else if (isSinglefileSnapshot || this.attachmentMode == Zotero.Translate.ItemSaver.ATTACHMENT_MODE_DOWNLOAD) {
newAttachment = yield this._saveAttachmentDownload.apply(this, arguments);
newAttachment = await this._saveAttachmentDownload.apply(this, arguments);
}
else if (this.attachmentMode == Zotero.Translate.ItemSaver.ATTACHMENT_MODE_FILE) {
newAttachment = yield this._saveAttachmentFile.apply(this, arguments);
newAttachment = await this._saveAttachmentFile.apply(this, arguments);
}
else {
Zotero.debug(`Translate: Ignoring attachment ${attachment.title} due to ATTACHMENT_MODE_IGNORE`);
@ -612,7 +612,7 @@ Zotero.Translate.ItemSaver.prototype = {
if (attachment.accessDate) newAttachment.setField("accessDate", attachment.accessDate);
if (attachment.tags) newAttachment.setTags(this._cleanTags(attachment.tags));
if (attachment.note) newAttachment.setNote(attachment.note);
yield newAttachment.saveTx(this._saveOptions);
await newAttachment.saveTx(this._saveOptions);
this._handleRelated(attachment, newAttachment);
Zotero.debug("Translate: Created attachment; id is " + newAttachment.id, 4);
@ -624,9 +624,9 @@ Zotero.Translate.ItemSaver.prototype = {
attachmentCallback(attachment, false, e);
return false;
}
}),
},
_saveAttachmentFile: Zotero.Promise.coroutine(function* (attachment, parentItemID, attachmentCallback) {
_saveAttachmentFile: async function (attachment, parentItemID, attachmentCallback) {
Zotero.debug("Translate: Adding attachment", 4);
attachmentCallback(attachment, 0);
@ -693,7 +693,7 @@ Zotero.Translate.ItemSaver.prototype = {
// At this point, must be a valid HTTP/HTTPS url
attachment.linkMode = "linked_url";
newItem = yield Zotero.Attachments.linkFromURL({
newItem = await Zotero.Attachments.linkFromURL({
url: attachment.url,
parentItemID,
contentType: attachment.mimeType || undefined,
@ -706,7 +706,7 @@ Zotero.Translate.ItemSaver.prototype = {
// Don't link if it's a path to the current storage directory
&& !Zotero.File.directoryContains(Zotero.DataDirectory.getSubdirectory('storage'), file.path)) {
attachment.linkMode = "linked_file";
newItem = yield Zotero.Attachments.linkFromFile({
newItem = await Zotero.Attachments.linkFromFile({
file,
parentItemID,
collections: !parentItemID ? this._collections : undefined,
@ -722,7 +722,7 @@ Zotero.Translate.ItemSaver.prototype = {
else {
if (attachment.url) {
attachment.linkMode = "imported_url";
newItem = yield Zotero.Attachments.importSnapshotFromFile({
newItem = await Zotero.Attachments.importSnapshotFromFile({
file: file,
url: attachment.url,
title: attachment.title,
@ -736,7 +736,7 @@ Zotero.Translate.ItemSaver.prototype = {
}
else {
attachment.linkMode = "imported_file";
newItem = yield Zotero.Attachments.importFromFile({
newItem = await Zotero.Attachments.importFromFile({
file: file,
parentItemID,
libraryID: this._libraryID,
@ -748,9 +748,9 @@ Zotero.Translate.ItemSaver.prototype = {
}
return newItem;
}),
},
"_parsePathURI":function(path) {
"_parsePathURI":function (path) {
try {
var uri = Services.io.newURI(path, "", this._baseURI);
} catch(e) {
@ -779,7 +779,7 @@ Zotero.Translate.ItemSaver.prototype = {
return file;
},
"_parseAbsolutePath":function(path) {
"_parseAbsolutePath":function (path) {
var file;
try {
file = Zotero.File.pathToFile(path);
@ -797,7 +797,7 @@ Zotero.Translate.ItemSaver.prototype = {
return file;
},
"_parseRelativePath":function(path) {
"_parseRelativePath":function (path) {
if (!this._baseURI) {
Zotero.debug("Translate: Cannot parse as relative path. No base URI available.");
return false;
@ -817,7 +817,7 @@ Zotero.Translate.ItemSaver.prototype = {
return file;
},
"_parsePath":function(path) {
"_parsePath":function (path) {
Zotero.debug("Translate: Attempting to parse path " + path);
var file;
@ -875,7 +875,7 @@ Zotero.Translate.ItemSaver.prototype = {
return false;
},
_saveAttachmentLink: async function(attachment, parentItemID, attachmentCallback) {
_saveAttachmentLink: async function (attachment, parentItemID, attachmentCallback) {
attachment.linkMode = "linked_url";
let url, mimeType;
if(attachment.document) {
@ -919,7 +919,7 @@ Zotero.Translate.ItemSaver.prototype = {
});
},
_saveAttachmentDownload: Zotero.Promise.coroutine(function* (attachment, parentItemID, attachmentCallback) {
_saveAttachmentDownload: async function (attachment, parentItemID, attachmentCallback) {
Zotero.debug("Translate: Adding attachment", 4);
let doc = undefined;
@ -974,7 +974,7 @@ Zotero.Translate.ItemSaver.prototype = {
let mimeType = attachment.mimeType ? attachment.mimeType : null;
let fileBaseName;
if (parentItemID) {
let parentItem = yield Zotero.Items.getAsync(parentItemID);
let parentItem = await Zotero.Items.getAsync(parentItemID);
fileBaseName = Zotero.Attachments.getFileBaseNameFromItem(parentItem, { attachmentTitle: title });
}
@ -991,9 +991,9 @@ Zotero.Translate.ItemSaver.prototype = {
collections: !parentItemID ? this._collections : undefined,
saveOptions: this._saveOptions,
});
}),
},
"_saveNote":Zotero.Promise.coroutine(function* (note, parentItemID) {
"_saveNote":async function (note, parentItemID) {
var myNote = new Zotero.Item('note');
myNote.libraryID = this._libraryID;
if (parentItemID) {
@ -1009,12 +1009,12 @@ Zotero.Translate.ItemSaver.prototype = {
if (!parentItemID && this._collections) {
myNote.setCollections(this._collections);
}
yield myNote.save(this._saveOptions);
await myNote.save(this._saveOptions);
if (typeof note == "object") {
this._handleRelated(note, myNote);
}
return myNote;
}),
},
_cleanCreators: function (creators) {
creators.forEach(creator => {
@ -1029,7 +1029,7 @@ Zotero.Translate.ItemSaver.prototype = {
* Remove automatic tags if automatic tags pref is on, and set type
* to automatic if forced
*/
"_cleanTags":function(tags) {
"_cleanTags":function (tags) {
// If all tags are automatic and automatic tags pref is on, return immediately
let tagPref = Zotero.Prefs.get("automaticTags");
if(this._forceTagType == 1 && !tagPref) return [];
@ -1050,7 +1050,7 @@ Zotero.Translate.ItemSaver.prototype = {
return newTags;
},
"_handleRelated":function(item, newItem) {
"_handleRelated":function (item, newItem) {
// add to ID map
if(item.itemID || item.id) {
this._IDMap[item.itemID || item.id] = newItem.id;
@ -1069,7 +1069,7 @@ Zotero.Translate.ItemSaver.prototype = {
}
}
Zotero.Translate.ItemGetter = function() {
Zotero.Translate.ItemGetter = function () {
this._itemsLeft = [];
this._collectionsLeft = null;
this._exportFileDirectory = null;
@ -1111,7 +1111,7 @@ Zotero.Translate.ItemGetter.prototype = {
* NOTE: This function should use the Zotero.Promise.method wrapper which adds a
* isResolved property to the returned promise for noWait translation.
*/
setAll: Zotero.Promise.method(async function (libraryID, getChildCollections) {
setAll: async function (libraryID, getChildCollections) {
this._itemsLeft = (await Zotero.Items.getAll(libraryID, true))
.filter((item) => {
// Don't export annotations
@ -1128,7 +1128,7 @@ Zotero.Translate.ItemGetter.prototype = {
this._itemsLeft.sort((a, b) => a.id - b.id);
this.numItems = this._itemsLeft.length;
}),
},
exportFiles: function (dir, extension, { includeAnnotations }) {
// generate directory
@ -1254,7 +1254,7 @@ Zotero.Translate.ItemGetter.prototype = {
//
// TODO: Change the below to use OS.File.DirectoryIterator?
if (linkMode != Zotero.Attachments.LINK_MODE_LINKED_FILE
&& await Zotero.Attachments.hasMultipleFiles(attachment)) {
&& (await Zotero.Attachments.hasMultipleFiles(attachment))) {
var copySrcs = [];
var files = attachment.getFile().parent.directoryEntries;
while (files.hasMoreElements()) {
@ -1347,7 +1347,7 @@ Zotero.Translate.ItemGetter.prototype = {
return false;
},
"nextCollection":function() {
"nextCollection":function () {
if(!this._collectionsLeft || this._collectionsLeft.length == 0) return false;
var returnItem = this._collectionsLeft.shift();
@ -1357,4 +1357,4 @@ Zotero.Translate.ItemGetter.prototype = {
return obj;
}
}
Zotero.Translate.ItemGetter.prototype.__defineGetter__("numItemsRemaining", function() { return this._itemsLeft.length });
Zotero.Translate.ItemGetter.prototype.__defineGetter__("numItemsRemaining", function () { return this._itemsLeft.length });

View file

@ -29,7 +29,7 @@
* Singleton to handle loading and caching of translators
* @namespace
*/
Zotero.Translators = new function() {
Zotero.Translators = new function () {
var _cache, _translators;
var _initialized = false;
var _initializationDeferred = false;
@ -48,11 +48,11 @@ Zotero.Translators = new function() {
* @param {Object} [options.metadataCache] - Translator metadata keyed by filename, if already
* available (e.g., in updateBundledFiles()), to avoid unnecessary file reads
*/
this.init = Zotero.Promise.coroutine(function* (options = {}) {
this.init = async function (options = {}) {
// Wait until bundled files have been updated, except when this is called by the schema update
// code itself
if (!options.fromSchemaUpdate) {
yield Zotero.Schema.schemaUpdatePromise;
await Zotero.Schema.schemaUpdatePromise;
}
// If an initialization has already started, a regular init() call should return the promise
@ -61,7 +61,7 @@ Zotero.Translators = new function() {
if (_initializationDeferred) {
let promise = _initializationDeferred.promise;
if (options.reinit) {
yield promise;
await promise;
}
else {
return promise;
@ -77,7 +77,7 @@ Zotero.Translators = new function() {
_translators = {};
var sql = "SELECT rowid, fileName, metadataJSON, lastModifiedTime FROM translatorCache";
var dbCacheResults = yield Zotero.DB.queryAsync(sql);
var dbCacheResults = await Zotero.DB.queryAsync(sql);
var dbCache = {};
for (let i = 0; i < dbCacheResults.length; i++) {
let entry = dbCacheResults[i];
@ -90,7 +90,7 @@ Zotero.Translators = new function() {
var iterator = new OS.File.DirectoryIterator(translatorsDir);
try {
while (true) {
let entries = yield iterator.nextBatch(5); // TODO: adjust as necessary
let entries = await iterator.nextBatch(5); // TODO: adjust as necessary
if (!entries.length) break;
for (let i = 0; i < entries.length; i++) {
let entry = entries[i];
@ -104,7 +104,7 @@ Zotero.Translators = new function() {
lastModifiedTime = entry.winLastWriteDate.getTime();
}
else {
lastModifiedTime = (yield OS.File.stat(path)).lastModificationDate.getTime();
lastModifiedTime = ((await OS.File.stat(path))).lastModificationDate.getTime();
}
// Check passed cache for metadata
@ -134,7 +134,7 @@ Zotero.Translators = new function() {
Zotero.debug(memCacheJSON || dbCacheEntry.metadataJSON, 1);
// If JSON is invalid, clear from cache
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
"DELETE FROM translatorCache WHERE fileName=?",
fileName
);
@ -144,7 +144,7 @@ Zotero.Translators = new function() {
// Otherwise, load from file
else {
try {
var translator = yield this.loadFromFile(path);
var translator = await this.loadFromFile(path);
}
catch (e) {
Zotero.logError(e);
@ -153,9 +153,9 @@ Zotero.Translators = new function() {
// so that the translator is reinstalled the next time it's updated.
//
// TODO: Reinstall the correct translator immediately
yield OS.File.remove(path);
await OS.File.remove(path);
let sql = "DELETE FROM translatorCache WHERE fileName=?";
yield Zotero.DB.queryAsync(sql, fileName);
await Zotero.DB.queryAsync(sql, fileName);
continue;
}
}
@ -174,16 +174,16 @@ Zotero.Translators = new function() {
translator.logError("Deleting older translator "
+ existingTranslator.fileName + " with same ID as "
+ translator.fileName);
yield OS.File.remove(existingTranslator.path);
yield removeFromCaches(existingTranslator);
await OS.File.remove(existingTranslator.path);
await removeFromCaches(existingTranslator);
}
// If cached translator is newer, keep it and discard this one
else if (existingTranslator.lastUpdated > translator.lastUpdated) {
translator.logError("Deleting older translator "
+ translator.fileName + " with same ID as "
+ existingTranslator.fileName);
yield OS.File.remove(translator.path);
yield removeFromDBCache(translator.fileName);
await OS.File.remove(translator.path);
await removeFromDBCache(translator.fileName);
continue;
}
// If cached translator has the same timestamp and matches the label, keep
@ -192,8 +192,8 @@ Zotero.Translators = new function() {
translator.logError("Translator " + existingTranslator.fileName
+ " with same ID is already loaded and matches label -- deleting "
+ translator.fileName);
yield OS.File.remove(translator.path);
yield removeFromDBCache(translator.fileName);
await OS.File.remove(translator.path);
await removeFromDBCache(translator.fileName);
continue;
}
// Otherwise delete the cached one and install this one
@ -201,8 +201,8 @@ Zotero.Translators = new function() {
translator.logError("Deleting translator " + translator.fileName
+ " with same ID as " + existingTranslator.fileName + " but with "
+ "mismatched filename");
yield OS.File.remove(existingTranslator.path);
yield removeFromCaches(existingTranslator);
await OS.File.remove(existingTranslator.path);
await removeFromCaches(existingTranslator);
}
}
@ -219,7 +219,7 @@ Zotero.Translators = new function() {
}
if (!dbCacheEntry) {
yield this.cacheInDB(
await this.cacheInDB(
fileName,
translator.serialize(Zotero.Translator.TRANSLATOR_REQUIRED_PROPERTIES.
concat(Zotero.Translator.TRANSLATOR_OPTIONAL_PROPERTIES)),
@ -238,7 +238,7 @@ Zotero.Translators = new function() {
// Remove translators from DB cache if no file
for (let fileName in dbCache) {
if (!filesInCache[fileName]) {
yield Zotero.DB.queryAsync(
await Zotero.DB.queryAsync(
"DELETE FROM translatorCache WHERE rowid=?",
dbCache[fileName].rowid
);
@ -264,7 +264,7 @@ Zotero.Translators = new function() {
_initialized = true;
Zotero.debug("Cached " + numCached + " translators in " + ((new Date) - start) + " ms");
});
};
this.reinit = async function (options = {}) {
@ -363,16 +363,16 @@ Zotero.Translators = new function() {
return _translators[id] ? _translators[id] : false;
}
this.getCodeForTranslator = Zotero.Promise.method(function (translator) {
this.getCodeForTranslator = function (translator) {
if (translator.code) return translator.code;
return Zotero.File.getContentsAsync(translator.path).then(function(code) {
return Zotero.File.getContentsAsync(translator.path).then(function (code) {
if (translator.cacheCode) {
// See Translator.init() for cache rules
translator.code = code;
}
return code;
});
});
};
/**
* Gets all translators for a specific type of translation
@ -397,11 +397,11 @@ Zotero.Translators = new function() {
* @param {String} uri The URI for which to look for translators
* @param {String} rootUri The root URI of the page, different from `uri` if running in an iframe
*/
this.getWebTranslatorsForLocation = function(URI, rootURI) {
this.getWebTranslatorsForLocation = function (URI, rootURI) {
var isFrame = URI !== rootURI;
var type = isFrame ? "webWithTargetAll" : "web";
return this.getAllForType(type).then(function(allTranslators) {
return this.getAllForType(type).then(function (allTranslators) {
var potentialTranslators = [];
var proxies = [];
@ -445,7 +445,7 @@ Zotero.Translators = new function() {
*
* @param {String} URI to get searchURIs and converterFunctions for
*/
this.getSearchURIs = function(URI) {
this.getSearchURIs = function (URI) {
var properURI = Zotero.Proxies.proxyToProper(URI);
if (properURI !== URI) {
// if we know this proxy, just use the proper URI for detection
@ -469,10 +469,10 @@ Zotero.Translators = new function() {
for (var i=1; i<hostnames.length-2; i++) {
if (TLDS[hostnames[i].toLowerCase()]) {
var properHost = hostnames.slice(0, i+1).join(".");
searchURIs[m[1]+properHost+URI.substr(m[0].length)] = new function() {
searchURIs[m[1]+properHost+URI.substr(m[0].length)] = new function () {
var re = new RegExp('^https?://(?:[^/]+\\.)?'+Zotero.Utilities.quotemeta(properHost)+'(?=/)', "gi");
var proxyHost = hostnames.slice(i+1).join(".").replace(/\$/g, "$$$$");
return function(uri) { return uri.replace(re, "$&."+proxyHost) };
return function (uri) { return uri.replace(re, "$&."+proxyHost) };
};
}
}
@ -488,8 +488,8 @@ Zotero.Translators = new function() {
* @return {Promise<Zotero.Translator[]|true>} - An array of translators if no callback is specified;
* otherwise true
*/
this.getImportTranslatorsForLocation = function(location, callback) {
return this.getAllForType("import").then(function(allTranslators) {
this.getImportTranslatorsForLocation = function (location, callback) {
return this.getAllForType("import").then(function (allTranslators) {
var tier1Translators = [];
var tier2Translators = [];
@ -514,7 +514,7 @@ Zotero.Translators = new function() {
* @param {String} label
* @return {String}
*/
this.getFileNameFromLabel = function(label, alternative) {
this.getFileNameFromLabel = function (label, alternative) {
var fileName = Zotero.Utilities.removeDiacritics(
Zotero.File.getValidFileName(label)) + ".js";
// Use translatorID if name still isn't ASCII (e.g., Cyrillic)
@ -623,14 +623,14 @@ Zotero.Translators = new function() {
* @param {String} code
* @return {Promise<String>}
*/
this.save = Zotero.Promise.coroutine(function* (metadata, code) {
this.save = async function (metadata, code) {
var str = this.stringify(metadata, code);
var destFile = this.getSavePath(metadata);
var existingTranslator = this.get(metadata.translatorID);
var sameFile = existingTranslator && destFile == existingTranslator.path;
var exists = yield OS.File.exists(destFile);
var exists = await OS.File.exists(destFile);
if (!sameFile && exists) {
var msg = `Overwriting translator with same filename '${PathUtils.filename(destFile)}'`;
Zotero.debug(msg, 1);
@ -641,9 +641,9 @@ Zotero.Translators = new function() {
Zotero.debug("Saving translator '" + metadata.label + "'");
Zotero.debug(metadata);
return Zotero.File.putContentsAsync(destFile, str).then(() => destFile);
});
};
this.cacheInDB = function(fileName, metadataJSON, lastModifiedTime) {
this.cacheInDB = function (fileName, metadataJSON, lastModifiedTime) {
return Zotero.DB.queryAsync(
"REPLACE INTO translatorCache VALUES (?, ?, ?)",
[fileName, JSON.stringify(metadataJSON), lastModifiedTime]

View file

@ -23,7 +23,7 @@
***** END LICENSE BLOCK *****
*/
Zotero.UIProperties = new class {
Zotero.UIProperties = new (class {
_roots = new Set();
registerRoot(root) {
@ -84,4 +84,4 @@ Zotero.UIProperties = new class {
root.style.setProperty('--zotero-ui-density', density);
root.setAttribute('zoteroUIDensity', density);
}
};
});

View file

@ -157,11 +157,11 @@ Zotero.URI = new function () {
}
this.getFeedItemURI = function(feedItem) {
this.getFeedItemURI = function (feedItem) {
return this.getItemURI(feedItem);
}
this.getFeedItemPath = function(feedItem) {
this.getFeedItemPath = function (feedItem) {
return this.getItemPath(feedItem);
}
@ -180,11 +180,11 @@ Zotero.URI = new function () {
return this._getObjectPath(collection);
}
this.getFeedURI = function(feed) {
this.getFeedURI = function (feed) {
return this.getLibraryURI(feed);
}
this.getFeedPath = function(feed) {
this.getFeedPath = function (feed) {
return this.getLibraryPath(feed);
}
@ -220,7 +220,7 @@ Zotero.URI = new function () {
return uri;
};
this._getObjectPath = function(obj) {
this._getObjectPath = function (obj) {
let path = this.getLibraryPath(obj.libraryID);
if (obj instanceof Zotero.Library) {
return path;
@ -245,7 +245,7 @@ Zotero.URI = new function () {
* @param {Zotero.Item | Zotero.Collection | Zotero.Group | Zotero.Search} obj
* @return {String}
*/
this.getObjectURI = function(obj) {
this.getObjectURI = function (obj) {
return this.defaultPrefix + this._getObjectPath(obj);
};
@ -264,11 +264,11 @@ Zotero.URI = new function () {
* @param {String} itemURI
* @return {Promise<Zotero.Item|false>}
*/
this.getURIItem = Zotero.Promise.method(function (itemURI) {
this.getURIItem = function (itemURI) {
var obj = this._getURIObject(itemURI, 'item');
if (!obj) return false;
return Zotero.Items.getByLibraryAndKeyAsync(obj.libraryID, obj.key);
});
};
/**
@ -308,11 +308,11 @@ Zotero.URI = new function () {
* @param {Zotero.Collection|FALSE}
* @return {Promise<Zotero.Collection|false>}
*/
this.getURICollection = Zotero.Promise.method(function (collectionURI) {
this.getURICollection = function (collectionURI) {
var obj = this._getURIObject(collectionURI, 'collection');
if (!obj) return false;
return Zotero.Collections.getByLibraryAndKeyAsync(obj.libraryID, obj.key);
});
};
/**
@ -455,7 +455,7 @@ Zotero.URI = new function () {
* @return {Promise<Integer|FALSE>} - A promise for either a libraryID or FALSE if a matching
* library couldn't be found
*/
this._getURIObjectLibraryID = Zotero.Promise.coroutine(function* (objectURI) {
this._getURIObjectLibraryID = async function (objectURI) {
let uri = objectURI.replace(/\/+$/, ''); // Drop trailing "/"
let uriParts = uri.match(uriPartsRe);
@ -464,7 +464,7 @@ Zotero.URI = new function () {
let type = uriParts[4];
// Personal library
if (!type || type == 'publications') {
libraryID = yield Zotero.DB.valueQueryAsync(
libraryID = await Zotero.DB.valueQueryAsync(
"SELECT libraryID FROM libraries WHERE type='user'"
);
}
@ -475,7 +475,7 @@ Zotero.URI = new function () {
}
// Group libraries
else {
libraryID = yield Zotero.DB.valueQueryAsync(
libraryID = await Zotero.DB.valueQueryAsync(
"SELECT libraryID FROM groups WHERE groupID=?", uriParts[3]
);
}
@ -486,7 +486,7 @@ Zotero.URI = new function () {
}
return libraryID;
});
};
@ -500,7 +500,7 @@ Zotero.URI = new function () {
* @return {Promise<Object|FALSE>} - A promise for an object with 'objectType', 'libraryID', 'key'
* or FALSE if library didn't exist
*/
this._getURIObjectLibraryKeyFromDB = Zotero.Promise.coroutine(function* (objectURI, type) {
this._getURIObjectLibraryKeyFromDB = async function (objectURI, type) {
let uri = objectURI.replace(/\/+$/, ''); // Drop trailing /
let uriParts = uri.match(uriPartsRe);
@ -508,7 +508,7 @@ Zotero.URI = new function () {
throw new Error("Could not parse object URI " + uri);
}
let libraryID = yield this._getURIObjectLibraryID(uri);
let libraryID = await this._getURIObjectLibraryID(uri);
if (!libraryID) {
return false;
}
@ -525,5 +525,5 @@ Zotero.URI = new function () {
if (type && type != retObj.objectType) return false;
return retObj;
});
};
}

View file

@ -69,25 +69,25 @@ Zotero.Users = new function () {
};
this.getCurrentUserID = function() { return _userID };
this.setCurrentUserID = Zotero.Promise.coroutine(function* (val) {
this.getCurrentUserID = function () { return _userID };
this.setCurrentUserID = async function (val) {
val = parseInt(val);
if (!(val > 0)) throw new Error("userID must be a positive integer");
var sql = "REPLACE INTO settings VALUES ('account', 'userID', ?)";
yield Zotero.DB.queryAsync(sql, val);
await Zotero.DB.queryAsync(sql, val);
_userID = val;
});
};
this.getCurrentUsername = () => _username;
this.setCurrentUsername = Zotero.Promise.coroutine(function* (val) {
this.setCurrentUsername = async function (val) {
if (!val || typeof val != 'string') throw new Error('username must be a non-empty string');
var sql = "REPLACE INTO settings VALUES ('account', 'username', ?)";
yield Zotero.DB.queryAsync(sql, val);
await Zotero.DB.queryAsync(sql, val);
_username = val;
});
};
this.getCurrentName = function () {

View file

@ -579,7 +579,7 @@ Zotero.Utilities.Internal = {
* @param {String[]} args Arguments given
* @return {Promise} Promise resolved to true if command succeeds, or an error otherwise
*/
exec: Zotero.Promise.method(function (cmd, args) {
exec: function (cmd, args) {
if (typeof cmd == 'string') {
Components.utils.import("resource://gre/modules/FileUtils.jsm");
cmd = new FileUtils.File(cmd);
@ -609,7 +609,7 @@ Zotero.Utilities.Internal = {
} });
return deferred.promise;
}),
},
/**
* Run a short-lived process and return its stdout
@ -619,12 +619,12 @@ Zotero.Utilities.Internal = {
* @return {Promise<String>}
*/
subprocess: async function (command, args = []) {
// eslint-disable-next-line no-undef
command = PathUtils.isAbsolute(command) ? command : await Subprocess.pathSearch(command);
Zotero.debug("Running " + command + " " + args.map(arg => "'" + arg + "'").join(" "));
// eslint-disable-next-line no-undef
let proc = await Subprocess.call({
command,
arguments: args,
@ -737,12 +737,12 @@ Zotero.Utilities.Internal = {
// Be safe
if (!delay) {
Zotero.logError(`Incorrect delay ${delay} -- stopping`);
yield Zotero.Promise.resolve(false);
yield Promise.resolve(false);
}
if (maxTime && (totalTime + delay) > maxTime) {
Zotero.debug(`Total delay time exceeds ${maxTime} -- stopping`);
yield Zotero.Promise.resolve(false);
yield Promise.resolve(false);
}
totalTime += delay;
@ -1825,9 +1825,9 @@ Zotero.Utilities.Internal = {
spawn: function (generator, thisObject) {
if (thisObject) {
return Zotero.Promise.coroutine(generator.bind(thisObject))();
return generator.bind(thisObject)();
}
return Zotero.Promise.coroutine(generator)();
return generator();
},
/**
@ -2038,7 +2038,7 @@ Zotero.Utilities.Internal = {
// at the time of runListeners() call to prevent triggering listeners that are added right
// runListeners() invocation
for (let [listener, once] of Array.from(this._events[event].listeners.entries())) {
await Zotero.Promise.resolve(listener.call(this));
await Promise.resolve(listener.call(this));
if (once) {
this._events[event].listeners.delete(listener);
}
@ -2612,7 +2612,7 @@ Zotero.Utilities.Internal.executeAppleScript = new function () {
Zotero.Utilities.Internal.activate = new function () {
// For Carbon and X11
var _carbon, ProcessSerialNumber, SetFrontProcessWithOptions;
// eslint-disable-next-line no-unused-vars
var _x11, _x11Display, _x11RootWindow, XClientMessageEvent, XFetchName, XFree, XQueryTree,
XOpenDisplay, XCloseDisplay, XFlush, XDefaultRootWindow, XInternAtom, XSendEvent,
XMapRaised, XGetWindowProperty, X11Atom, X11Bool, X11Display, X11Window, X11Status;
@ -2642,9 +2642,9 @@ Zotero.Utilities.Internal.activate = new function () {
var event = new XClientMessageEvent();
event.type = 33; /* ClientMessage*/
event.serial = 0;
// eslint-disable-next-line camelcase
event.send_event = 1;
// eslint-disable-next-line camelcase
event.message_type = XInternAtom(_x11Display, "_NET_ACTIVE_WINDOW", 0);
event.display = _x11Display;
event.window = x11Window;
@ -2826,11 +2826,11 @@ Zotero.Utilities.Internal.activate = new function () {
[
{ type: ctypes.int },
{ serial: ctypes.unsigned_long },
// eslint-disable-next-line camelcase
{ send_event: X11Bool },
{ display: X11Display.ptr },
{ window: X11Window },
// eslint-disable-next-line camelcase
{ message_type: X11Atom },
{ format: ctypes.int },
{ l0: ctypes.long },

View file

@ -39,7 +39,7 @@ const { CommandLineOptions } = ChromeUtils.importESModule("chrome://zotero/conte
/*
* Core functions
*/
(function() {
(function () {
// Privileged (public) methods
this.getStorageDirectory = getStorageDirectory;
this.debug = debug;
@ -90,7 +90,7 @@ const { CommandLineOptions } = ChromeUtils.importESModule("chrome://zotero/conte
return windows;
};
this.getActiveZoteroPane = function() {
this.getActiveZoteroPane = function () {
var win = Services.wm.getMostRecentWindow("navigator:browser");
return win ? win.ZoteroPane : null;
};
@ -302,7 +302,7 @@ const { CommandLineOptions } = ChromeUtils.importESModule("chrome://zotero/conte
]
)
: Zotero.getString('dataDir.notFound', Zotero.clientName);
_startupErrorHandler = async function() {
_startupErrorHandler = async function () {
var ps = Services.prompt;
var buttonFlags = ps.BUTTON_POS_0 * ps.BUTTON_TITLE_IS_STRING
+ ps.BUTTON_POS_1 * ps.BUTTON_TITLE_IS_STRING
@ -388,7 +388,7 @@ const { CommandLineOptions } = ChromeUtils.importESModule("chrome://zotero/conte
}, "quit-application-granted", false);
// Register shutdown handler to call Zotero.shutdown()
var _shutdownObserver = {observe:function() { Zotero.shutdown().done() }};
var _shutdownObserver = {observe:function () { Zotero.shutdown().done() }};
Services.obs.addObserver(_shutdownObserver, "quit-application", false);
// Get startup errors
@ -402,7 +402,7 @@ const { CommandLineOptions } = ChromeUtils.importESModule("chrome://zotero/conte
Services.console.registerListener(ConsoleListener);
// Add shutdown listener to remove quit-application observer and console listener
this.addShutdownListener(function() {
this.addShutdownListener(function () {
Services.obs.removeObserver(_shutdownObserver, "quit-application", false);
Services.console.unregisterListener(ConsoleListener);
});
@ -421,7 +421,7 @@ const { CommandLineOptions } = ChromeUtils.importESModule("chrome://zotero/conte
/**
* Triggers events when initialization finishes
*/
this.initComplete = async function() {
this.initComplete = async function () {
if(Zotero.initialized) return;
Zotero.debug("Running initialization callbacks");
@ -457,8 +457,8 @@ const { CommandLineOptions } = ChromeUtils.importESModule("chrome://zotero/conte
*
* @return {Promise:Boolean}
*/
var _initFull = Zotero.Promise.coroutine(function* () {
if (!(yield _initDB())) return false;
var _initFull = async function () {
if (!((await _initDB()))) return false;
Zotero.VersionHeader.init();
@ -467,11 +467,11 @@ const { CommandLineOptions } = ChromeUtils.importESModule("chrome://zotero/conte
var restoreFile = OS.Path.join(dataDir, 'restore-from-server');
var resetDataDirFile = OS.Path.join(dataDir, 'reset-data-directory');
var result = yield Zotero.Promise.all([OS.File.exists(restoreFile), OS.File.exists(resetDataDirFile)]);
var result = await Promise.all([OS.File.exists(restoreFile), OS.File.exists(resetDataDirFile)]);
if (result.some(r => r)) {
[Zotero.restoreFromServer, Zotero.resetDataDir] = result;
try {
yield Zotero.DB.closeDatabase();
await Zotero.DB.closeDatabase();
// TODO: better error handling
@ -484,11 +484,11 @@ const { CommandLineOptions } = ChromeUtils.importESModule("chrome://zotero/conte
if (Zotero.restoreFromServer) {
let dbfile = Zotero.DataDirectory.getDatabase();
Zotero.debug("Deleting " + dbfile);
yield OS.File.remove(dbfile, { ignoreAbsent: true });
await OS.File.remove(dbfile, { ignoreAbsent: true });
let storageDir = OS.Path.join(dataDir, 'storage');
Zotero.debug("Deleting " + storageDir.path);
OS.File.removeDir(storageDir, { ignoreAbsent: true }),
yield OS.File.remove(restoreFile);
await OS.File.remove(restoreFile);
Zotero.restoreFromServer = true;
}
else if (Zotero.resetDataDir) {
@ -505,7 +505,7 @@ const { CommandLineOptions } = ChromeUtils.importESModule("chrome://zotero/conte
let lastError;
// Delete all files in directory rather than removing directory, in case it's
// a symlink
yield Zotero.File.iterateDirectory(dataDir, async function (entry) {
await Zotero.File.iterateDirectory(dataDir, async function (entry) {
// Don't delete some files
if (entry.name == 'pipes') {
return;
@ -531,7 +531,7 @@ const { CommandLineOptions } = ChromeUtils.importESModule("chrome://zotero/conte
}
Zotero.debug("Done with reset");
if (!(yield _initDB())) return false;
if (!((await _initDB()))) return false;
}
catch (e) {
// Restore from backup?
@ -549,7 +549,7 @@ const { CommandLineOptions } = ChromeUtils.importESModule("chrome://zotero/conte
try {
// Require >=2.1b3 database to ensure proper locking
let dbSystemVersion = yield Zotero.Schema.getDBVersion('system');
let dbSystemVersion = await Zotero.Schema.getDBVersion('system');
if (dbSystemVersion > 0 && dbSystemVersion < 31) {
let ps = Services.prompt;
var buttonFlags = (ps.BUTTON_POS_0) * (ps.BUTTON_TITLE_IS_STRING)
@ -581,7 +581,7 @@ const { CommandLineOptions } = ChromeUtils.importESModule("chrome://zotero/conte
}
// Select new data directory
else if (index == 1) {
let dir = yield Zotero.DataDirectory.choose(true);
let dir = await Zotero.DataDirectory.choose(true);
if (!dir) {
quit = true;
}
@ -598,7 +598,7 @@ const { CommandLineOptions } = ChromeUtils.importESModule("chrome://zotero/conte
}
try {
var updated = yield Zotero.Schema.updateSchema({
var updated = await Zotero.Schema.updateSchema({
onBeforeUpdate: (options = {}) => {
if (options.minor) return;
try {
@ -626,7 +626,7 @@ const { CommandLineOptions } = ChromeUtils.importESModule("chrome://zotero/conte
+ Zotero.getString('startupError.zoteroVersionIsOlder.upgrade',
ZOTERO_CONFIG.DOMAIN_NAME);
Zotero.startupError = msg;
_startupErrorHandler = function() {
_startupErrorHandler = function () {
var ps = Services.prompt;
var buttonFlags = (ps.BUTTON_POS_0) * (ps.BUTTON_TITLE_IS_STRING)
+ (ps.BUTTON_POS_1) * (ps.BUTTON_TITLE_CANCEL)
@ -679,18 +679,18 @@ const { CommandLineOptions } = ChromeUtils.importESModule("chrome://zotero/conte
);
ZoteroAutoComplete.init();
yield Zotero.Users.init();
yield Zotero.Libraries.init();
await Zotero.Users.init();
await Zotero.Libraries.init();
yield Zotero.ID.init();
yield Zotero.ItemTypes.init();
yield Zotero.ItemFields.init();
yield Zotero.CreatorTypes.init();
yield Zotero.FileTypes.init();
yield Zotero.CharacterSets.init();
yield Zotero.RelationPredicates.init();
await Zotero.ID.init();
await Zotero.ItemTypes.init();
await Zotero.ItemFields.init();
await Zotero.CreatorTypes.init();
await Zotero.FileTypes.init();
await Zotero.CharacterSets.init();
await Zotero.RelationPredicates.init();
yield Zotero.Session.init();
await Zotero.Session.init();
Zotero.locked = false;
@ -699,12 +699,12 @@ const { CommandLineOptions } = ChromeUtils.importESModule("chrome://zotero/conte
Zotero.Server.init();
}
yield Zotero.Fulltext.init();
await Zotero.Fulltext.init();
Zotero.Notifier.registerObserver(Zotero.Tags, 'setting', 'tags');
yield Zotero.Sync.Data.Local.init();
yield Zotero.Sync.Data.Utilities.init();
await Zotero.Sync.Data.Local.init();
await Zotero.Sync.Data.Utilities.init();
Zotero.Sync.Storage.Local.init();
Zotero.Sync.Runner = new Zotero.Sync.Runner_Module;
Zotero.Sync.EventListeners.init();
@ -713,43 +713,41 @@ const { CommandLineOptions } = ChromeUtils.importESModule("chrome://zotero/conte
Zotero.MIMETypeHandler.init();
Zotero.CookieSandbox.init();
yield Zotero.Proxies.init();
await Zotero.Proxies.init();
// Initialize keyboard shortcuts
Zotero.Keys.init();
Zotero.Date.init();
Zotero.LocateManager.init();
yield Zotero.Collections.init();
yield Zotero.Items.init();
yield Zotero.Searches.init();
yield Zotero.Tags.init();
yield Zotero.Creators.init();
yield Zotero.Groups.init();
yield Zotero.Relations.init();
yield Zotero.Retractions.init();
yield Zotero.Dictionaries.init();
await Zotero.Collections.init();
await Zotero.Items.init();
await Zotero.Searches.init();
await Zotero.Tags.init();
await Zotero.Creators.init();
await Zotero.Groups.init();
await Zotero.Relations.init();
await Zotero.Retractions.init();
await Zotero.Dictionaries.init();
Zotero.Reader.init();
// Load all library data except for items, which are loaded when libraries are first
// clicked on or if otherwise necessary
yield Zotero.Promise.each(
Zotero.Libraries.getAll(),
library => Zotero.Promise.coroutine(function* () {
yield Zotero.SyncedSettings.loadAll(library.libraryID);
if (library.libraryType != 'feed') {
yield Zotero.Collections.loadAll(library.libraryID);
yield Zotero.Searches.loadAll(library.libraryID);
}
})()
);
await // FIXME: fx140: replace call to Zotero.Promise.each()
Zotero.Promise.each(Zotero.Libraries.getAll(), library => (async function () {
await Zotero.SyncedSettings.loadAll(library.libraryID);
if (library.libraryType != 'feed') {
await Zotero.Collections.loadAll(library.libraryID);
await Zotero.Searches.loadAll(library.libraryID);
}
})());
// Migrate fields from Extra that can be moved to item fields after a schema update
yield Zotero.Schema.migrateExtraFields();
await Zotero.Schema.migrateExtraFields();
Zotero.Items.startEmptyTrashTimer();
yield Zotero.QuickCopy.init();
await Zotero.QuickCopy.init();
Zotero.addShutdownListener(() => Zotero.QuickCopy.uninit());
Zotero.Feeds.init();
@ -768,18 +766,18 @@ const { CommandLineOptions } = ChromeUtils.importESModule("chrome://zotero/conte
}
return false;
}
});
};
/**
* Initializes the DB connection
*/
var _initDB = Zotero.Promise.coroutine(function* (haveReleasedLock) {
var _initDB = async function (haveReleasedLock) {
// Initialize main database connection
Zotero.DB = new Zotero.DBConnection('zotero');
try {
// Test read access
yield Zotero.DB.test();
await Zotero.DB.test();
let dbfile = Zotero.DataDirectory.getDatabase();
@ -824,7 +822,7 @@ const { CommandLineOptions } = ChromeUtils.importESModule("chrome://zotero/conte
}
return true;
});
};
function _checkDataDirAccessError(e) {
@ -859,7 +857,7 @@ const { CommandLineOptions } = ChromeUtils.importESModule("chrome://zotero/conte
}
this.shutdown = Zotero.Promise.coroutine(function* () {
this.shutdown = async function () {
Zotero.debug("Shutting down Zotero");
try {
@ -876,16 +874,16 @@ const { CommandLineOptions } = ChromeUtils.importESModule("chrome://zotero/conte
Zotero.logError(e);
}
}
yield Promise.all(shutdownPromises);
await Promise.all(shutdownPromises);
if (Zotero.DB) {
// close DB
yield Zotero.DB.closeDatabase(true)
await Zotero.DB.closeDatabase(true)
}
} catch(e) {
Zotero.logError(e);
}
});
};
this.getProfileDirectory = function () {
@ -1517,7 +1515,7 @@ const { CommandLineOptions } = ChromeUtils.importESModule("chrome://zotero/conte
var { AddonManager } = ChromeUtils.import("resource://gre/modules/AddonManager.jsm");
var installed = await AddonManager.getAllAddons();
installed.sort(function(a, b) {
installed.sort(function (a, b) {
return ((a.appDisabled || a.userDisabled) ? 1 : 0) -
((b.appDisabled || b.userDisabled) ? 1 : 0);
});
@ -1565,7 +1563,7 @@ const { CommandLineOptions } = ChromeUtils.importESModule("chrome://zotero/conte
return Zotero.Utilities.Internal.getAncestorByTagName(elem, tagName);
}
this.randomString = function(len, chars) {
this.randomString = function (len, chars) {
return Zotero.Utilities.randomString(len, chars);
}
@ -1581,7 +1579,7 @@ const { CommandLineOptions } = ChromeUtils.importESModule("chrome://zotero/conte
return file;
}
this.lazy = function(fn) {
this.lazy = function (fn) {
return Zotero.Utilities.Internal.lazy(fn);
}
@ -1715,7 +1713,7 @@ const { CommandLineOptions } = ChromeUtils.importESModule("chrome://zotero/conte
/**
* Adds a listener to be called when Zotero shuts down (even if Firefox is not shut down)
*/
this.addShutdownListener = function(listener) {
this.addShutdownListener = function (listener) {
_shutdownListeners.push(listener);
}
@ -1750,28 +1748,28 @@ const { CommandLineOptions } = ChromeUtils.importESModule("chrome://zotero/conte
/*
* Clear entries that no longer exist from various tables
*/
this.purgeDataObjects = Zotero.Promise.coroutine(function* () {
this.purgeDataObjects = async function () {
var d = new Date();
yield Zotero.DB.executeTransaction(async function () {
await Zotero.DB.executeTransaction(async function () {
return Zotero.Creators.purge();
});
yield Zotero.DB.executeTransaction(async function () {
await Zotero.DB.executeTransaction(async function () {
return Zotero.Tags.purge();
});
yield Zotero.Fulltext.purgeUnusedWords();
yield Zotero.Items.purge();
await Zotero.Fulltext.purgeUnusedWords();
await Zotero.Items.purge();
// DEBUG: this might not need to be permanent
//yield Zotero.DB.executeTransaction(async function () {
// return Zotero.Relations.purge();
//});
Zotero.debug("Purged data tables in " + (new Date() - d) + " ms");
});
};
this.reloadDataObjects = function () {
return Zotero.Promise.all([
return Promise.all([
Zotero.Collections.reloadAll(),
Zotero.Creators.reloadAll(),
Zotero.Items.reloadAll()
@ -1782,7 +1780,7 @@ const { CommandLineOptions } = ChromeUtils.importESModule("chrome://zotero/conte
/**
* Brings Zotero Standalone to the foreground
*/
this.activateStandalone = function() {
this.activateStandalone = function () {
var uri = Services.io.newURI('zotero://select', null, null);
var handler = Components.classes['@mozilla.org/uriloader/external-protocol-service;1']
.getService(Components.interfaces.nsIExternalProtocolService)
@ -1904,7 +1902,7 @@ const { CommandLineOptions } = ChromeUtils.importESModule("chrome://zotero/conte
var ConsoleListener = {
"QueryInterface":ChromeUtils.generateQI([Components.interfaces.nsIConsoleMessage,
Components.interfaces.nsISupports]),
"observe":function(msg) {
"observe":function (msg) {
if(!_shouldKeepError(msg)) return;
if(_recentErrors.length === ERROR_BUFFER_SIZE) _recentErrors.shift();
_recentErrors.push(msg);
@ -1919,7 +1917,7 @@ const { CommandLineOptions } = ChromeUtils.importESModule("chrome://zotero/conte
*
* Actions are configured in ZoteroPane.handleKeyPress()
*/
Zotero.Keys = new function() {
Zotero.Keys = new function () {
this.init = init;
this.windowInit = windowInit;
this.getCommand = getCommand;
@ -2160,7 +2158,7 @@ Zotero.DragDrop = {
/*
* Implements nsIWebProgressListener
*/
Zotero.WebProgressFinishListener = function(onFinish) {
Zotero.WebProgressFinishListener = function (onFinish) {
var _request;
var _finished = false;
@ -2168,7 +2166,7 @@ Zotero.WebProgressFinishListener = function(onFinish) {
return _request;
};
this.onStateChange = function(wp, req, stateFlags, status) {
this.onStateChange = function (wp, req, stateFlags, status) {
//Zotero.debug('onStateChange: ' + stateFlags);
if (stateFlags & Components.interfaces.nsIWebProgressListener.STATE_STOP
&& stateFlags & Components.interfaces.nsIWebProgressListener.STATE_IS_NETWORK
@ -2203,27 +2201,27 @@ Zotero.WebProgressFinishListener = function(onFinish) {
}
}
this.onProgressChange = function(wp, req, curSelfProgress, maxSelfProgress, curTotalProgress, maxTotalProgress) {
this.onProgressChange = function (wp, req, curSelfProgress, maxSelfProgress, curTotalProgress, maxTotalProgress) {
//Zotero.debug('onProgressChange');
//Zotero.debug('Current: ' + curTotalProgress);
//Zotero.debug('Max: ' + maxTotalProgress);
}
this.onLocationChange = function(wp, req, location) {}
this.onSecurityChange = function(wp, req, stateFlags, status) {}
this.onStatusChange = function(wp, req, status, msg) {}
this.onLocationChange = function (wp, req, location) {}
this.onSecurityChange = function (wp, req, stateFlags, status) {}
this.onStatusChange = function (wp, req, status, msg) {}
}
/*
* Saves or loads JSON objects.
*/
Zotero.JSON = new function() {
this.serialize = function(arg) {
Zotero.JSON = new function () {
this.serialize = function (arg) {
Zotero.debug("WARNING: Zotero.JSON.serialize() is deprecated; use JSON.stringify()");
return JSON.stringify(arg);
}
this.unserialize = function(arg) {
this.unserialize = function (arg) {
Zotero.debug("WARNING: Zotero.JSON.unserialize() is deprecated; use JSON.parse()");
return JSON.parse(arg);
}