From dcfc5e51fa11ed100c66205a36c73a25b08fdb40 Mon Sep 17 00:00:00 2001 From: Mossroy Date: Sun, 21 Oct 2018 10:51:42 +0200 Subject: [PATCH] Add API for reading ZIM Metadata. Fixes #395 It is especially useful to read the language of the ZIM file --- tests/tests.js | 20 ++++++++++++++++++++ www/js/lib/zimArchive.js | 26 ++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/tests/tests.js b/tests/tests.js index acef94df..4c0e5f50 100644 --- a/tests/tests.js +++ b/tests/tests.js @@ -134,6 +134,26 @@ define(['jquery', 'zimArchive', 'zimDirEntry', 'util', 'uiUtil', 'utf8'], QUnit.test("ZIM archive is ready", function(assert) { assert.ok(localZimArchive.isReady() === true, "ZIM archive should be set as ready"); }); + + QUnit.module("ZIM metadata"); + QUnit.test("read ZIM language", function(assert) { + var done = assert.async(); + assert.expect(1); + var callbackFunction = function(language) { + assert.equal(language , 'eng', 'The language read inside the Metadata should be "eng" for "English"'); + done(); + }; + localZimArchive.getMetadata("Language", callbackFunction); + }); + QUnit.test("try to read a missing metadata", function(assert) { + var done = assert.async(); + assert.expect(1); + var callbackFunction = function(string) { + assert.equal(string, undefined, 'The metadata zzz should not be found inside the ZIM'); + done(); + }; + localZimArchive.getMetadata("zzz", callbackFunction); + }); QUnit.module("zim_direntry_search_and_read"); QUnit.test("check DirEntry.fromStringId 'A Fool for You'", function(assert) { diff --git a/www/js/lib/zimArchive.js b/www/js/lib/zimArchive.js index a7aea511..aff31544 100644 --- a/www/js/lib/zimArchive.js +++ b/www/js/lib/zimArchive.js @@ -37,6 +37,10 @@ define(['zimfile', 'zimDirEntry', 'util', 'utf8'], * @param {ZIMArchive} zimArchive Ready-to-use ZIMArchive */ + /** + * @callback callbackMetadata + * @param {String} data metadata string + */ /** * Creates a ZIM archive object to access the ZIM file at the given path in the given storage. @@ -280,6 +284,28 @@ define(['zimfile', 'zimDirEntry', 'util', 'utf8'], var index = Math.floor(Math.random() * this._file.articleCount); this._file.dirEntryByUrlIndex(index).then(callback); }; + + /** + * Read a Metadata string inside the ZIM file. + * @param {String} key + * @param {callbackMetadata} callback + */ + ZIMArchive.prototype.getMetadata = function (key, callback) { + var that = this; + this.getDirEntryByTitle("M/" + key).then(function (dirEntry) { + if (dirEntry === null || dirEntry === undefined) { + console.warn("Title M/" + key + " not found in the archive"); + callback(); + } else { + that.readUtf8File(dirEntry, function (dirEntryRead, data) { + callback(data); + }); + } + }).fail(function (e) { + console.warn("Metadata with key " + key + " not found in the archive", e); + callback(); + }); + }; /** * Functions and classes exposed by this module