diff options
Diffstat (limited to 'html/install.js')
-rw-r--r-- | html/install.js | 453 |
1 files changed, 453 insertions, 0 deletions
diff --git a/html/install.js b/html/install.js new file mode 100644 index 0000000..dbc490d --- /dev/null +++ b/html/install.js @@ -0,0 +1,453 @@ +/** + * This file is part of Haketilo. + * + * Function: Install mappings/resources in Haketilo. + * + * Copyright (C) 2022 Wojtek Kosior + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * As additional permission under GNU GPL version 3 section 7, you + * may distribute forms of that code without the copy of the GNU + * GPL normally required by section 4, provided you include this + * license notice and, in case of non-source distribution, a URL + * through which recipients can access the Corresponding Source. + * If you modify file(s) with this exception, you may extend this + * exception to your version of the file(s), but you are not + * obligated to do so. If you do not wish to do so, delete this + * exception statement from your version. + * + * As a special exception to the GPL, any HTML file which merely + * makes function calls to this code, and for that purpose + * includes it by reference shall be deemed a separate work for + * copyright law purposes. If you modify this code, you may extend + * this exception to your version of the code, but you are not + * obligated to do so. If you do not wish to do so, delete this + * exception statement from your version. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + * + * I, Wojtek Kosior, thereby promise not to sue for violation of this file's + * license. Although I request that you do not make use of this code in a + * proprietary program, I am not going to enforce this in court. + */ + +#IMPORT common/indexeddb.js AS haketilodb +#IMPORT html/dialog.js +#IMPORT html/item_preview.js AS ip + +#FROM common/browser.js IMPORT browser +#FROM html/DOM_helpers.js IMPORT clone_template +#FROM common/entities.js IMPORT item_id_string, version_string, get_files +#FROM common/misc.js IMPORT sha256_async AS sha256 + +const coll = new Intl.Collator(); + +/* + * Comparator used to sort items in the order we want them to appear in + * install dialog: first mappings alphabetically, then resources alphabetically. + */ +function compare_items(def1, def2) { + if (def1.type !== def2.type) + return def1.type === "mapping" ? -1 : 1; + + const name_comparison = coll.compare(def1.long_name, def2.long_name); + return name_comparison === 0 ? + coll.compare(def1.identifier, def2.identifier) : name_comparison; +} + +function ItemEntry(install_view, item) { + Object.assign(this, clone_template("install_list_entry")); + this.item_def = item.def; + + this.item_name.innerText = item.def.long_name; + this.item_id.innerText = item_id_string(item.def); + if (item.db_def) { + this.old_ver.innerText = + version_string(item.db_def.version, item.db_def.revision); + this.update_info.classList.remove("hide"); + } + + let preview_cb = () => install_view.preview_item(item.def); + preview_cb = dialog.when_hidden(install_view.dialog_ctx, preview_cb); + this.details_but.addEventListener("click", preview_cb); +} + +const container_ids = [ + "install_preview", + "dialog_container", + "mapping_preview_container", + "resource_preview_container" +]; + +/* + * Work object is used to communicate between asynchronously executing + * functions when computing dependencies tree of an item and when fetching + * files for installation. + */ +async function init_work() { + const work = { + waiting: 0, + is_ok: true, + db: (await haketilodb.get()), + result: [] + }; + + work.err = function (error, user_message) { + if (error) + console.error(error); + work.is_ok = false; + work.reject_cb(user_message); + } + + return [work, + new Promise((...cbs) => [work.resolve_cb, work.reject_cb] = cbs)]; +} + +function InstallView(tab_id, on_view_show, on_view_hide) { + Object.assign(this, clone_template("install_view")); + this.shown = false; + + const show_container = name => { + for (const cid of container_ids) { + if (cid !== name) + this[cid].classList.add("hide"); + } + this[name].classList.remove("hide"); + } + + this.dialog_ctx = dialog.make(() => show_container("dialog_container"), + () => show_container("install_preview")); + this.dialog_container.prepend(this.dialog_ctx.main_div); + + /* Make a link to view a file from the repository. */ + const make_file_link = (preview_ctx, file_ref) => { + const a = document.createElement("a"); + a.href = `${this.repo_url}file/${file_ref.hash_key}`; + a.innerText = file_ref.file; + + return a; + } + + this.previews_ctx = {}; + + this.preview_item = item_def => { + if (!this.shown) + return; + + const fun = ip[`${item_def.type}_preview`]; + const preview_ctx = fun(item_def, this.previews_ctx[item_def.type], + make_file_link); + this.previews_ctx[item_def.type] = preview_ctx; + + const container_name = `${item_def.type}_preview_container`; + show_container(container_name); + this[container_name].prepend(preview_ctx.main_div); + } + + const back_cb = dialog.when_hidden(this.dialog_ctx, + () => show_container("install_preview")); + for (const type of ["resource", "mapping"]) + this[`${type}_back_but`].addEventListener("click", back_cb); + + const process_item = async (work, item_type, id, ver) => { + if (!work.is_ok || work.processed_by_type[item_type].has(id)) + return; + + work.processed_by_type[item_type].add(id); + work.waiting++; + + const url = ver ? + `${this.repo_url}${item_type}/${id}/${ver.join(".")}.json` : + `${this.repo_url}${item_type}/${id}.json`; + const response = + await browser.tabs.sendMessage(tab_id, ["repo_query", url]); + if (!work.is_ok) + return; + + if ("error" in response) { + return work.err(response.error, + "Failure to communicate with repository :("); + } + + if (!response.ok) { + return work.err(null, + `Repository sent HTTP code ${response.status} :(`); + } + + if ("error_json" in response) { + return work.err(response.error_json, + "Repository's response is not valid JSON :("); + } + + if (response.json.api_schema_version > [1]) { + let api_ver = ""; + try { + api_ver = + ` (${version_string(response.json.api_schema_version)})`; + } catch(e) { + console.warn(e); + } + + const captype = item_type[0].toUpperCase() + item_type.substring(1); + const msg = `${captype} ${item_id_string(id, ver)} was served using unsupported Hydrilla API version${api_ver}. You might need to update Haketilo.`; + return work.err(null, msg); + } + + /* TODO: JSON schema validation should be added here. */ + + delete response.json.api_schema_version; + delete response.json.api_schema_revision; + + const files = response.json.source_copyright + .concat(item_type === "resource" ? response.json.scripts : []); + for (const file of files) { + file.hash_key = `sha256-${file.sha256}`; + delete file.sha256; + } + + if (item_type === "mapping") { + for (const res_ref of Object.values(response.json.payloads)) + process_item(work, "resource", res_ref.identifier); + } else { + for (const res_id of (response.json.dependencies || [])) + process_item(work, "resource", res_id); + } + + /* + * At this point we already have JSON definition of the item and we + * triggered processing of its dependencies. We now have to verify if + * the same or newer version of the item is already present in the + * database and if so - omit this item. + */ + const transaction = work.db.transaction(item_type); + try { + var db_def = await haketilodb.idb_get(transaction, item_type, id); + if (!work.is_ok) + return; + } catch(e) { + const msg = "Error accessing Haketilo's internal database :("; + return work.err(e, msg); + } + if (!db_def || db_def.version < response.json.version) + work.result.push({def: response.json, db_def}); + + if (--work.waiting === 0) + work.resolve_cb(work.result); + } + + async function compute_deps(item_type, item_id, item_ver) { + const [work, work_prom] = await init_work(); + work.processed_by_type = {"mapping" : new Set(), "resource": new Set()}; + + process_item(work, item_type, item_id, item_ver); + + const items = await work_prom; + items.sort((i1, i2) => compare_items(i1.def, i2.def)); + return items; + } + + this.show = async (repo_url, item_type, item_id, item_ver) => { + if (this.shown) + return; + + this.shown = true; + + this.repo_url = repo_url; + + dialog.loader(this.dialog_ctx, "Fetching data from repository..."); + + try { + on_view_show(); + } catch(e) { + console.error(e); + } + + try { + var items = await compute_deps(item_type, item_id, item_ver); + } catch(e) { + var dialog_prom = dialog.error(this.dialog_ctx, e); + } + + if (!dialog_prom && items.length === 0) { + const msg = "Nothing to do - packages already installed."; + var dialog_prom = dialog.info(this.dialog_ctx, msg); + } + + if (dialog_prom) { + dialog.close(this.dialog_ctx); + + await dialog_prom; + + hide(); + return; + } + + this.item_entries = items.map(i => new ItemEntry(this, i)); + this.to_install_list.append(...this.item_entries.map(ie => ie.main_li)); + + dialog.close(this.dialog_ctx); + } + + const process_file = async (work, hash_key) => { + if (!work.is_ok) + return; + + work.waiting++; + + try { + var file_uses = await haketilodb.idb_get(work.file_uses_transaction, + "file_uses", hash_key); + if (!work.is_ok) + return; + } catch(e) { + const msg = "Error accessing Haketilo's internal database :("; + return work.err(e, msg); + } + + if (!file_uses) { + const url = `${this.repo_url}file/${hash_key}`; + + try { + var response = await fetch(url); + if (!work.is_ok) + return; + } catch(e) { + const msg = "Failure to communicate with repository :("; + return work.err(e, msg); + } + + if (!response.ok) { + const msg = `Repository sent HTTP code ${response.status} :(`; + return work.err(null, msg); + } + + try { + var text = await response.text(); + if (!work.is_ok) + return; + } catch(e) { + const msg = "Repository's response is not valid text :("; + return work.err(e, msg); + } + + const digest = await sha256(text); + if (!work.is_ok) + return; + if (`sha256-${digest}` !== hash_key) { + const msg = `${url} served a file with different SHA256 cryptographic sum :(`; + return work.err(null, msg); + } + + work.result.push([hash_key, text]); + } + + if (--work.waiting === 0) + work.resolve_cb(work.result); + } + + const get_missing_files = async item_defs => { + const [work, work_prom] = await init_work(); + work.file_uses_transaction = work.db.transaction("file_uses"); + + const processed_files = new Set(); + + for (const item_def of item_defs) { + for (const file of get_files(item_def)) { + if (!processed_files.has(file.hash_key)) { + processed_files.add(file.hash_key); + process_file(work, file.hash_key); + } + } + } + + return processed_files.size > 0 ? work_prom : []; + } + + const perform_install = async () => { + if (!this.show || !this.item_entries) + return; + + dialog.loader(this.dialog_ctx, "Installing..."); + + const item_defs = this.item_entries.map(ie => ie.item_def); + + try { + var files = (await get_missing_files(item_defs)) + .reduce((ac, [hk, txt]) => Object.assign(ac, {[hk]: txt}), {}); + } catch(e) { + var dialog_prom = dialog.error(this.dialog_ctx, e); + } + + if (files !== undefined) { + const data = {files}; + const names = [["mappings", "mapping"], ["resources", "resource"]]; + + for (const [set_name, type] of names) { + const set = {}; + + for (const def of item_defs.filter(def => def.type === type)) + set[def.identifier] = {[version_string(def.version)]: def}; + + data[set_name] = set; + } + + try { + await haketilodb.save_items(data); + } catch(e) { + console.error(e); + const msg = "Error writing to Haketilo's internal database :("; + var dialog_prom = dialog.error(this.dialog_ctx, msg); + } + } + + if (!dialog_prom) { + const msg = "Successfully installed!"; + var dialog_prom = dialog.info(this.dialog_ctx, msg); + } + + dialog.close(this.dialog_ctx); + + await dialog_prom; + + hide(); + } + + const hide = () => { + if (!this.shown) + return; + + this.shown = false; + delete this.item_entries; + [...this.to_install_list.children].forEach(n => n.remove()); + + try { + on_view_hide(); + } catch(e) { + console.error(e); + } + } + + this.when_hidden = cb => { + const wrapped_cb = (...args) => { + if (!this.shown) + return cb(...args); + } + return wrapped_cb; + } + + const hide_cb = dialog.when_hidden(this.dialog_ctx, hide); + this.cancel_but.addEventListener("click", hide_cb); + + const install_cb = dialog.when_hidden(this.dialog_ctx, perform_install); + this.install_but.addEventListener("click", install_cb); +} |