<commit_before>var self = require('sdk/self');
const {
	Cc, Ci, Cu
} = require("chrome");

var Zotero = Cc["@zotero.org/Zotero;1"].getService(Ci.nsISupports).wrappedJSObject;

var buttons = require('sdk/ui/button/action');
var tabs = require("sdk/tabs");
var tab_utils = require("sdk/tabs/utils");
var utils = require('sdk/window/utils');
var {
	viewFor
} = require("sdk/view/core");
var {
	setTimeout
} = require("sdk/timers");
var preferences = require("sdk/simple-prefs").prefs;


/*
 * Add import button to Firefox toolbar.
 */
var importButton = buttons.ActionButton({
	id: "import-button",
	label: "Import references into JabRef",
	icon: {
		"16": "./JabRef-icon-16.png",
		"48": "./JabRef-icon-48.png"
	},
	onClick: handleImportClick,
});

/*
 * Get the underlying document of the tab.
 */
function getDocumentForTab(tab) {
	var lowLevelTab = viewFor(tab);
	// Get the ContentDocument of the tab
	var browser = tab_utils.getBrowserForTab(lowLevelTab);
	return browser.contentDocument;
}

/*
 * Import items found on the present website.
 */
function handleImportClick(state) {
	// Get active tab
	var activeTab = tabs.activeTab;
	var doc = getDocumentForTab(activeTab);

	// Create and show panel
	var panel = require("sdk/panel").Panel({
		width: 330,
		height: 150,
		contentURL: "./progressPanel.html"
	});
	panel.port.on('winsize', function(data) {
		panel.resize(330, data.height);
	});
	panel.show({
		position: importButton
	});

	// Detect and import bibliographic items
	startImport(doc, panel);
}

/*
 * Detects contained bibliographic items and sends them to JabRef.
 */
function startImport(doc, panel) {
	// Look for translators which are able to handle the current website
	var translate = new Zotero.Translate.Web();
	translate.setDocument(doc);
	translate.setHandler("translators", function(obj, item) {
		detectAndExportReferenceItems(obj, item, panel)
	});

	translate.getTranslators(false); // false = return only the first translator
}

/*
 * Called when a translator is found (search initiated by Zotero.Translate.getTranslators()).
 * Uses the translator to search for bibliographic items and export them.
 */
function detectAndExportReferenceItems(translate, translators, panel) {
	var items = [];
	translate.setTranslator(translators[0]);

	translate.clearHandlers("itemDone");
	translate.clearHandlers("done");
	translate.clearHandlers("attachmentProgress");

	translate.setHandler("itemDone", function(obj, dbItem, item) {
		// Prepare attachment data
		var attachments = [];
		for (var i = item.attachments.length - 1; i >= 0; i--) {
			attachments.push({
				attachmentId: JSON.stringify(item.attachments[i]).hashCode(),
				title: item.attachments[i].title,
				imageSrc: Zotero.Utilities.determineAttachmentIcon(item.attachments[i]),
			});
		};
		var finishedItem = {
			title: item.title,
			attachments: attachments,
			imageSrc: Zotero.ItemTypes.getImageSrc(item.itemType)
		};
		// Pass parsed item to progress window
		panel.port.emit("show", finishedItem);

		// Remember that this item was finished 
		items.push(dbItem);
	});

	translate.setHandler("done", function() {
		// Translation is done, so export the discovered items
		exportItems(items);

		// Hide panel in 1 sec
		setTimeout(function() {
			panel.hide();
		}, 1000);
	});

	translate.setHandler("attachmentProgress", function(obj, attachment, progress, error) {
		// Notify progress window about the attachment download
		panel.port.emit("updateProgress", {
			attachmentId: JSON.stringify(attachment).hashCode(),
			progress: progress
		});
	});

	// Run translator
	translate.translate();
	//translate.translate(false); // this would not save the items to the zotero database
}

/*
 * Exports the given items to JabRef.
 */
function exportItems(items) {
	if (items.length <= 0)
		return;

	// translate() deletes items array; this is why we save a cloned array here
	var copyItems = items.slice(0);

	// Create a new temporary file
	var file = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties).get("TmpD", Ci.nsIFile);
	file.append("zotero_export.bib");
	file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0666);

	// Prepare export
	var exportTranslator = new Zotero.Translate.Export();
	//exportTranslator.setTranslator('9cb70025-a888-4a29-a210-93ec52da40d4'); // BibTeX
	exportTranslator.setTranslator('b6e39b57-8942-4d11-8259-342c46ce395f'); // BibLaTeX
	exportTranslator.setItems(items);
	exportTranslator.setLocation(file);

	exportTranslator.clearHandlers("done");
	exportTranslator.setHandler("done", function(obj, returnValue) {
		importIntoJabRef(file);
	});

	// Perform export
	exportTranslator.translate();

	// Delete saved items from zotero database, so we don't leave any traces
	deleteItemsFromZoteroDatabase(copyItems);
}

/*
 * Sends the given bib file to JabRef.
 */
function importIntoJabRef(file) {
	// Get JabRef executable
	var jabRef = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);
	jabRef.initWithPath(preferences.jabRefPath);
	// Start JabRef
	var process = Cc["@mozilla.org/process/util;1"].createInstance(Ci.nsIProcess);
	process.init(jabRef);
	var args = ["--importToOpen", file.path];
	process.run(false, args, args.length);
}

/*
 * Delete items from Zotero db.
 */
function deleteItemsFromZoteroDatabase(items) {
	for (i = 0; i < items.length; i++) {
		Zotero.Items.erase(items[i].id);
	}
}

/*
 * Listen for tab content loads in order to enable/disable the import button.
 */
tabs.on('ready', function(tab) {
	var doc = getDocumentForTab(tab);

	// Search for translators
	var translate = new Zotero.Translate.Web();
	translate.setDocument(doc);<commit_msg>Fix #18: downloaded files are present<commit_after>var self = require('sdk/self');
const {
	Cc, Ci, Cu
} = require("chrome");

var Zotero = Cc["@zotero.org/Zotero;1"].getService(Ci.nsISupports).wrappedJSObject;

var buttons = require('sdk/ui/button/action');
var tabs = require("sdk/tabs");
var tab_utils = require("sdk/tabs/utils");
var utils = require('sdk/window/utils');
var {
	viewFor
} = require("sdk/view/core");
var {
	setTimeout
} = require("sdk/timers");
var preferences = require("sdk/simple-prefs").prefs;


/*
 * Add import button to Firefox toolbar.
 */
var importButton = buttons.ActionButton({
	id: "import-button",
	label: "Import references into JabRef",
	icon: {
		"16": "./JabRef-icon-16.png",
		"48": "./JabRef-icon-48.png"
	},
	onClick: handleImportClick,
});

/*
 * Get the underlying document of the tab.
 */
function getDocumentForTab(tab) {
	var lowLevelTab = viewFor(tab);
	// Get the ContentDocument of the tab
	var browser = tab_utils.getBrowserForTab(lowLevelTab);
	return browser.contentDocument;
}

/*
 * Import items found on the present website.
 */
function handleImportClick(state) {
	// Get active tab
	var activeTab = tabs.activeTab;
	var doc = getDocumentForTab(activeTab);

	// Create and show panel
	var panel = require("sdk/panel").Panel({
		width: 330,
		height: 150,
		contentURL: "./progressPanel.html"
	});
	panel.port.on('winsize', function(data) {
		panel.resize(330, data.height);
	});
	panel.show({
		position: importButton
	});

	// Detect and import bibliographic items
	startImport(doc, panel);
}

/*
 * Detects contained bibliographic items and sends them to JabRef.
 */
function startImport(doc, panel) {
	// Look for translators which are able to handle the current website
	var translate = new Zotero.Translate.Web();
	translate.setDocument(doc);
	translate.setHandler("translators", function(obj, item) {
		detectAndExportReferenceItems(obj, item, panel)
	});

	translate.getTranslators(false); // false = return only the first translator
}

/*
 * Called when a translator is found (search initiated by Zotero.Translate.getTranslators()).
 * Uses the translator to search for bibliographic items and export them.
 */
function detectAndExportReferenceItems(translate, translators, panel) {
	var items = [];
	translate.setTranslator(translators[0]);

	translate.clearHandlers("itemDone");
	translate.clearHandlers("done");
	translate.clearHandlers("attachmentProgress");

	translate.setHandler("itemDone", function(obj, dbItem, item) {
		// Prepare attachment data
		var attachments = [];
		for (var i = item.attachments.length - 1; i >= 0; i--) {
			attachments.push({
				attachmentId: JSON.stringify(item.attachments[i]).hashCode(),
				title: item.attachments[i].title,
				imageSrc: Zotero.Utilities.determineAttachmentIcon(item.attachments[i]),
			});
		};
		var finishedItem = {
			title: item.title,
			attachments: attachments,
			imageSrc: Zotero.ItemTypes.getImageSrc(item.itemType)
		};
		// Pass parsed item to progress window
		panel.port.emit("show", finishedItem);

		// Remember that this item was finished 
		items.push(dbItem);
	});

	translate.setHandler("done", function() {
		// Translation is done, so export the discovered items
		exportItems(items);

		// Hide panel in 1 sec
		setTimeout(function() {
			panel.hide();
		}, 1000);
	});

	translate.setHandler("attachmentProgress", function(obj, attachment, progress, error) {
		// Notify progress window about the attachment download
		panel.port.emit("updateProgress", {
			attachmentId: JSON.stringify(attachment).hashCode(),
			progress: progress
		});
	});

	// Run translator
	translate.translate();
	//translate.translate(false); // this would not save the items to the zotero database
}

/*
 * Exports the given items to JabRef.
 */
function exportItems(items) {
	if (items.length <= 0)
		return;

	// translate() deletes items array; this is why we save a cloned array here
	var copyItems = items.slice(0);

	// Create a new temporary file
	var file = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties).get("TmpD", Ci.nsIFile);
	file.append("zotero_export.bib");
	file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0666);

	// Prepare export
	var exportTranslator = new Zotero.Translate.Export();
	//exportTranslator.setTranslator('9cb70025-a888-4a29-a210-93ec52da40d4'); // BibTeX
	exportTranslator.setTranslator('b6e39b57-8942-4d11-8259-342c46ce395f'); // BibLaTeX
	exportTranslator.setItems(items);
	exportTranslator.setLocation(file);

	exportTranslator.clearHandlers("done");
	exportTranslator.setHandler("done", function(obj, returnValue) {
		importIntoJabRef(file);
	});

	// Perform export
	exportTranslator.translate();

	// Delete saved items from zotero database, so we don't leave any traces
	deleteItemsFromZoteroDatabase(copyItems);
}

/*
 * Sends the given bib file to JabRef.
 */
function importIntoJabRef(file) {
	// Get JabRef executable
	var jabRef = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);
	jabRef.initWithPath(preferences.jabRefPath);
	// Start JabRef
	var process = Cc["@mozilla.org/process/util;1"].createInstance(Ci.nsIProcess);
	process.init(jabRef);
	var args = ["--importToOpen", file.path];
	process.run(false, args, args.length);
}

/*
 * Delete items from Zotero db.
 */
function deleteItemsFromZoteroDatabase(items) {
	for (i = 0; i < items.length; i++) {
		// Zotero also will delete the attachments if we delete the item
		// so we trick Zotero and mark the attachments as linked so they are not deleted 
		var attachments = items[i].getAttachments();
		for (var i in attachments) {
			var attachment = Zotero.Items.get(attachments[i]);
			attachment.attachmentLinkMode = Zotero.Attachments.LINK_MODE_LINKED_URL;
			attachment.save();
		}

		Zotero.Items.erase(items[i].id);
	}
}

/*
 * Listen for tab content loads in order to enable/disable the import button.
 */
tabs.on('ready', function(tab) {
	var doc = getDocumentForTab(tab);

	// Search for translators
	var translate = new Zotero.Translate.Web();
	translate.setDocument(doc);
{'fraction_non_alphanumeric': 0.13669803250641574, 'fraction_numerical': 0.01420017108639863, 'mean_word_length': 4.52243741143127, 'pattern_counts': {'":': 4, '<': 7, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6897010', 'n_tokens_mistral': 4063, 'n_tokens_neox': 3749, 'n_words': 910}