commit 7f52e00341cb401ac68781981f3df848e30f46d8
parent 395d596105a55823bf584c08839833f100d5507e
Author: Aurimas Vinckevicius <aurimas.dev@gmail.com>
Date: Sun, 8 Feb 2015 17:21:11 -0600
Cleanup ISBNs when importing from web/search translators
Validate, convert to ISBN-13, and list in a space-separated format
Diffstat:
2 files changed, 54 insertions(+), 0 deletions(-)
diff --git a/chrome/content/zotero/xpcom/translation/translate.js b/chrome/content/zotero/xpcom/translation/translate.js
@@ -616,6 +616,32 @@ Zotero.Translate.Sandbox = {
if(setShortTitle) item.shortTitle = title;
}
+ /* Clean up ISBNs
+ * Allow multiple ISBNs, but...
+ * (1) validate all ISBNs
+ * (2) convert all ISBNs to ISBN-13
+ * (3) remove any duplicates
+ * (4) separate them with space
+ */
+ if (item.ISBN) {
+ // Match ISBNs with groups separated by various dashes or even spaces
+ var isbnRe = /\b(?:97[89][\s\x2D\xAD\u2010-\u2015\u2043\u2212]*)?(?:\d[\s\x2D\xAD\u2010-\u2015\u2043\u2212]*){9}[\dx](?![\x2D\xAD\u2010-\u2015\u2043\u2212])\b/gi,
+ validISBNs = [],
+ isbn;
+ while (isbn = isbnRe.exec(item.ISBN)) {
+ var validISBN = Zotero.Utilities.cleanISBN(isbn[0]);
+ if (!validISBN) {
+ // Back up and move up one character
+ isbnRe.lastIndex = isbn.index + 1;
+ continue;
+ }
+
+ var isbn13 = Zotero.Utilities.toISBN13(validISBN);
+ if (validISBNs.indexOf(isbn13) == -1) validISBNs.push(isbn13);
+ }
+ item.ISBN = validISBNs.join(' ');
+ }
+
// refuse to save very long tags
if(item.tags) {
for(var i=0; i<item.tags.length; i++) {
diff --git a/chrome/content/zotero/xpcom/utilities.js b/chrome/content/zotero/xpcom/utilities.js
@@ -310,6 +310,34 @@ Zotero.Utilities = {
return false;
},
+
+ /*
+ * Convert ISBN 10 to ISBN 13
+ * @param {String} isbn ISBN 10 or ISBN 13
+ * cleanISBN
+ * @return {String} ISBN-13
+ */
+ "toISBN13": function(isbn) {
+ if (!/^(?:97[89])?\d{9}[\dxX]$/.test(isbn)
+ && !(isbn = Zotero.Utilities.cleanISBN(isbn))
+ ) {
+ throw new Error('Invalid ISBN: ' + isbn);
+ }
+
+ if (isbn.length == 13) return isbn; // Recalculate check digit?
+
+ isbn = '978' + isbn.substr(0,9);
+
+ var sum = 0;
+ for (var i = 0; i < 12; i++) {
+ sum += isbn[i] * (i%2 ? 3 : 1);
+ }
+
+ var checkDigit = 10 - (sum % 10);
+ if (checkDigit == 10) checkDigit = 0;
+
+ return isbn + checkDigit;
+ },
/**
* Clean and validate ISSN.