Skip to content

Instantly share code, notes, and snippets.

@zhongxiang117
Forked from retorquere/File Hierarchy.js
Created January 26, 2022 09:43
Show Gist options
  • Save zhongxiang117/04715af86f4aaa93cdcd4c64fb797a37 to your computer and use it in GitHub Desktop.
Save zhongxiang117/04715af86f4aaa93cdcd4c64fb797a37 to your computer and use it in GitHub Desktop.
{
"translatorID": "86ffd88b-6f4e-4bec-a5be-839c1034beb2",
"label": "File Hierarchy",
"description": "Export files according to collection organisation",
"creator": "Emiliano Heyns",
"target": "txt",
"minVersion": "4.0.27",
"maxVersion": "",
"configOptions": {
"getCollections": true
},
"displayOptions": {
"exportFileData": true
},
"translatorType": 2,
"browserSupport": "gcsv",
"priority": 100,
"inRepository": false,
"lastUpdated": "2018-09-27 11:34:45"
}
class Collections {
constructor() {
this.collections = {};
let coll;
while (coll = Zotero.nextCollection()) {
const key = (coll.primary ? coll.primary : coll).key;
this.collections[key] = {
parent: coll.fields.parentKey,
name: coll.name,
};
}
for (const key in this.collections) {
const coll = this.collections[key];
if (coll.parent && !this.collections[coll.parent]) {
coll.parent = false;
}
coll.path = this.path(coll);
}
Zotero.debug('collections: ' + JSON.stringify(this.collections));
}
path(coll) {
return (this.collections[coll.parent] ? this.path(this.collections[coll.parent]) + '/' : '') + coll.name.replace(/[#%&{}\\<>\*\?\/\$!'":@]/g, '_');
}
save(att, collections) {
collections = (collections || []).map(key => this.collections[key]).filter(coll => coll);
Zotero.debug(`Saving attachment filename=${att.filename}, contentType=${att.contentType} localPath = ${att.localPath}, defaultPath=${att.defaultPath} ${Object.keys(att)}`);
if (att.contentType === 'text/html')
att.filename = `${att.filename.replace(/\.html?$/, '')}/${att.filename}`; // assume text/html is snapshot
if (collections.length) {
for (const coll of collections) {
att.saveFile(`${coll.path}/${att.filename}`, true);
Zotero.write(`${coll.path}/${att.filename}\n`);
}
}
else {
att.saveFile(att.filename, true);
Zotero.write(`${att.filename}\n`);
}
}
}
function doExport() {
if (!Zotero.getOption('exportFileData'))
throw new Error('File Hierarchy needs "Export File Data" to be on');
const collections = new Collections;
let item, attachments;
while ((item = Zotero.nextItem())) {
if (item.itemType === 'attachment') {
attachments = [item];
}
else {
attachments = item.attachments || [];
}
if (attachments.length === 0)
continue;
Zotero.debug(`saving ${attachments.length} attachments to ${JSON.stringify(item.collections)}`);
for (const att of attachments) {
collections.save(att, item.collections);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment