Auto-rename file and set automatic title after Create Parent Item (#4474)

This commit is contained in:
Abe Jellinek 2024-08-02 02:44:41 -04:00 committed by GitHub
parent e40cf686bc
commit 11a5853657
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 63 additions and 5 deletions

View file

@ -5342,12 +5342,24 @@ var ZoteroPane = new function()
}
}
await Zotero.DB.executeTransaction(async () => {
for (let item of items) {
item.setAutoAttachmentTitle();
await item.save();
for (let item of items) {
if (Zotero.Attachments.shouldAutoRenameFile(item.attachmentLinkMode == Zotero.Attachments.LINK_MODE_LINKED_FILE)) {
let path = item.getFilePath();
if (!path) {
Zotero.debug('No path for attachment ' + item.key);
continue;
}
let ext = Zotero.File.getExtension(path);
let fileBaseName = Zotero.Attachments.getFileBaseNameFromItem(item.parentItem, { attachmentTitle: item.getField('title') });
let newName = fileBaseName + (ext ? '.' + ext : '');
let result = await item.renameAttachmentFile(newName, false, true);
if (result !== true) {
throw new Error('Error renaming ' + path);
}
item.setAutoAttachmentTitle({ ignoreAutoRenamePrefs: true });
await item.saveTx();
}
});
}
};

View file

@ -1671,4 +1671,50 @@ describe("ZoteroPane", function() {
assert.equal(epubAttachment.getField('title'), Zotero.getString('file-type-ebook'));
});
});
describe("#createParentItemsFromSelected()", function () {
async function createParent() {
let parent;
let dialogPromise = waitForDialog(async (win) => {
parent = await createDataObject('item', { title: 'Book Title' });
win.io.dataOut = { parent };
win.close();
}, false, 'chrome://zotero/content/createParentDialog.xhtml');
let createParentPromise = zp.createParentItemsFromSelected();
await dialogPromise;
await createParentPromise;
return parent;
}
it("should rename the attachment and set an automatic title", async function () {
let attachment = await importPDFAttachment({
title: 'Attachment title',
});
assert.equal(attachment.attachmentFilename, 'test.pdf');
let parent = await createParent();
assert.equal(attachment.parentItem, parent);
assert.equal(attachment.attachmentFilename, 'Book Title.pdf');
assert.equal(attachment.getField('title'), Zotero.getString('file-type-pdf'));
});
it("should not rename a linked attachment or set an automatic title when linked file renaming disabled", async function () {
Zotero.Prefs.set('autoRenameFiles.linked', false);
let file = getTestDataDirectory();
file.append('test.pdf');
let attachment = await Zotero.Attachments.linkFromFile({
file,
title: 'Attachment title'
});
assert.equal(attachment.attachmentFilename, 'test.pdf');
let parent = await createParent();
assert.equal(attachment.parentItem, parent);
assert.equal(attachment.attachmentFilename, 'test.pdf');
assert.equal(attachment.getField('title'), 'Attachment title');
Zotero.Prefs.clear('autoRenameFiles.linked');
});
});
})