Project

General

Profile

Download (12.7 KB) Statistics
| Branch: | Tag: | Revision:

haketilo / html / install.js @ 4c6a2323

1
/**
2
 * This file is part of Haketilo.
3
 *
4
 * Function: Install mappings/resources in Haketilo.
5
 *
6
 * Copyright (C) 2022 Wojtek Kosior
7
 *
8
 * This program is free software: you can redistribute it and/or modify
9
 * it under the terms of the GNU General Public License as published by
10
 * the Free Software Foundation, either version 3 of the License, or
11
 * (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * As additional permission under GNU GPL version 3 section 7, you
19
 * may distribute forms of that code without the copy of the GNU
20
 * GPL normally required by section 4, provided you include this
21
 * license notice and, in case of non-source distribution, a URL
22
 * through which recipients can access the Corresponding Source.
23
 * If you modify file(s) with this exception, you may extend this
24
 * exception to your version of the file(s), but you are not
25
 * obligated to do so. If you do not wish to do so, delete this
26
 * exception statement from your version.
27
 *
28
 * As a special exception to the GPL, any HTML file which merely
29
 * makes function calls to this code, and for that purpose
30
 * includes it by reference shall be deemed a separate work for
31
 * copyright law purposes. If you modify this code, you may extend
32
 * this exception to your version of the code, but you are not
33
 * obligated to do so. If you do not wish to do so, delete this
34
 * exception statement from your version.
35
 *
36
 * You should have received a copy of the GNU General Public License
37
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
38
 *
39
 * I, Wojtek Kosior, thereby promise not to sue for violation of this file's
40
 * license. Although I request that you do not make use of this code in a
41
 * proprietary program, I am not going to enforce this in court.
42
 */
43

    
44
#IMPORT common/indexeddb.js AS haketilodb
45
#IMPORT html/dialog.js
46
#IMPORT html/item_preview.js AS ip
47

    
48
#FROM common/browser.js   IMPORT browser
49
#FROM html/DOM_helpers.js IMPORT clone_template, Showable
50
#FROM common/entities.js  IMPORT item_id_string, version_string, get_files, \
51
                                 is_valid_version
52
#FROM common/misc.js      IMPORT sha256_async AS sha256
53

    
54
const coll = new Intl.Collator();
55

    
56
/*
57
 * Comparator used to sort items in the order we want them to appear in
58
 * install dialog: first mappings alphabetically, then resources alphabetically.
59
 */
60
function compare_items(def1, def2) {
61
    if (def1.type !== def2.type)
62
	return def1.type === "mapping" ? -1 : 1;
63

    
64
    const name_comparison = coll.compare(def1.long_name, def2.long_name);
65
    return name_comparison === 0 ?
66
	coll.compare(def1.identifier, def2.identifier) : name_comparison;
67
}
68

    
69
function ItemEntry(install_view, item) {
70
    Object.assign(this, clone_template("install_list_entry"));
71
    this.item_def = item.def;
72

    
73
    this.item_name.innerText = item.def.long_name;
74
    this.item_id.innerText = item_id_string(item.def);
75
    if (item.db_def) {
76
	this.old_ver.innerText =
77
	    version_string(item.db_def.version, item.db_def.revision);
78
	this.update_info.classList.remove("hide");
79
    }
80

    
81
    let preview_cb = () => install_view.preview_item(item.def);
82
    preview_cb = install_view.dialog_ctx.when_hidden(preview_cb);
83
    this.details_but.addEventListener("click", preview_cb);
84
}
85

    
86
const container_ids = [
87
    "install_preview",
88
    "dialog_container",
89
    "mapping_preview_container",
90
    "resource_preview_container"
91
];
92

    
93
/*
94
 * Work object is used to communicate between asynchronously executing
95
 * functions when computing dependencies tree of an item and when fetching
96
 * files for installation.
97
 */
98
async function init_work() {
99
    const work = {
100
	waiting: 0,
101
	is_ok: true,
102
	db: (await haketilodb.get()),
103
	result: []
104
    };
105

    
106
    work.err = function (error, user_message) {
107
	if (error)
108
    	    console.error(error);
109
	work.is_ok = false;
110
	work.reject_cb(user_message);
111
    }
112

    
113
    return [work,
114
	    new Promise((...cbs) => [work.resolve_cb, work.reject_cb] = cbs)];
115
}
116

    
117
function InstallView(tab_id, on_view_show, on_view_hide) {
118
    Showable.call(this, on_view_show, on_view_hide);
119

    
120
    Object.assign(this, clone_template("install_view"));
121

    
122
    const show_container = name => {
123
	for (const cid of container_ids) {
124
	    if (cid !== name)
125
		this[cid].classList.add("hide");
126
	}
127
	this[name].classList.remove("hide");
128
    }
129

    
130
    this.dialog_ctx = dialog.make(() => show_container("dialog_container"),
131
				  () => show_container("install_preview"));
132
    this.dialog_container.prepend(this.dialog_ctx.main_div);
133

    
134
    /* Make a link to view a file from the repository. */
135
    const make_file_link = (preview_ctx, file_ref) => {
136
	const a = document.createElement("a");
137
	a.href = `${this.repo_url}file/${file_ref.hash_key}`;
138
	a.innerText = file_ref.file;
139

    
140
	return a;
141
    }
142

    
143
    this.previews_ctx = {};
144

    
145
    this.preview_item = item_def => {
146
	if (!this.shown)
147
	    return;
148

    
149
	const fun = ip[`${item_def.type}_preview`];
150
	const preview_ctx = fun(item_def, this.previews_ctx[item_def.type],
151
				make_file_link);
152
	this.previews_ctx[item_def.type] = preview_ctx;
153

    
154
	const container_name = `${item_def.type}_preview_container`;
155
	show_container(container_name);
156
	this[container_name].prepend(preview_ctx.main_div);
157
    }
158

    
159
    let back_cb = () => show_container("install_preview");
160
    back_cb = this.dialog_ctx.when_hidden(back_cb);
161
    for (const type of ["resource", "mapping"])
162
	this[`${type}_back_but`].addEventListener("click", back_cb);
163

    
164
    const process_item = async (work, item_type, id, ver) => {
165
	if (!work.is_ok || work.processed_by_type[item_type].has(id))
166
	    return;
167

    
168
	work.processed_by_type[item_type].add(id);
169
	work.waiting++;
170

    
171
	const url = ver ?
172
	      `${this.repo_url}${item_type}/${id}/${ver.join(".")}.json` :
173
	      `${this.repo_url}${item_type}/${id}.json`;
174
	const response =
175
	      await browser.tabs.sendMessage(tab_id, ["repo_query", url]);
176
	if (!work.is_ok)
177
	    return;
178

    
179
	if ("error" in response) {
180
	    return work.err(response.error,
181
			    "Failure to communicate with repository :(");
182
	}
183

    
184
	if (!response.ok) {
185
	    return work.err(null,
186
			    `Repository sent HTTP code ${response.status} :(`);
187
	}
188

    
189
	if ("error_json" in response) {
190
	    return work.err(response.error_json,
191
			    "Repository's response is not valid JSON :(");
192
	}
193

    
194
	if (!is_valid_version(response.json.api_schema_version)) {
195
	    var bad_api_ver = "";
196
	} else if (response.json.api_schema_version > [1]) {
197
	    var bad_api_ver =
198
		` (${version_string(response.json.api_schema_version)})`;
199
	} else {
200
	    var bad_api_ver = false;
201
	}
202

    
203
	if (bad_api_ver !== false) {
204
	    const captype = item_type[0].toUpperCase() + item_type.substring(1);
205
	    const msg = `${captype} ${item_id_string(id, ver)} was served using unsupported Hydrilla API version${bad_api_ver}. You might need to update Haketilo.`;
206
	    return work.err(null, msg);
207
	}
208

    
209
	/* TODO: JSON schema validation should be added here. */
210

    
211
	delete response.json.api_schema_version;
212
	delete response.json.api_schema_revision;
213

    
214
	const files = response.json.source_copyright
215
	      .concat(item_type === "resource" ? response.json.scripts : []);
216
	for (const file of files) {
217
	    file.hash_key = `sha256-${file.sha256}`;
218
	    delete file.sha256;
219
	}
220

    
221
	if (item_type === "mapping") {
222
	    for (const res_ref of Object.values(response.json.payloads))
223
		process_item(work, "resource", res_ref.identifier);
224
	} else {
225
	    for (const res_id of (response.json.dependencies || []))
226
		process_item(work, "resource", res_id);
227
	}
228

    
229
	/*
230
	 * At this point we already have JSON definition of the item and we
231
	 * triggered processing of its dependencies. We now have to verify if
232
	 * the same or newer version of the item is already present in the
233
	 * database and if so - omit this item.
234
	 */
235
	const transaction = work.db.transaction(item_type);
236
	try {
237
	    var db_def = await haketilodb.idb_get(transaction, item_type, id);
238
	    if (!work.is_ok)
239
		return;
240
	} catch(e) {
241
	    const msg = "Error accessing Haketilo's internal database :(";
242
	    return work.err(e, msg);
243
	}
244
	if (!db_def || db_def.version < response.json.version)
245
	    work.result.push({def: response.json, db_def});
246

    
247
	if (--work.waiting === 0)
248
	    work.resolve_cb(work.result);
249
    }
250

    
251
    async function compute_deps(item_type, item_id, item_ver) {
252
	const [work, work_prom] = await init_work();
253
	work.processed_by_type = {"mapping" : new Set(), "resource": new Set()};
254

    
255
	process_item(work, item_type, item_id, item_ver);
256

    
257
	const items = await work_prom;
258
	items.sort((i1, i2) => compare_items(i1.def, i2.def));
259
	return items;
260
    }
261

    
262
    const show_super = this.show;
263
    this.show = async (repo_url, item_type, item_id, item_ver) => {
264
	if (!show_super())
265
	    return;
266

    
267
	this.repo_url = repo_url;
268

    
269
	dialog.loader(this.dialog_ctx, "Fetching data from repository...");
270

    
271
	try {
272
	    var items = await compute_deps(item_type, item_id, item_ver);
273
	} catch(e) {
274
	    var dialog_prom = dialog.error(this.dialog_ctx, e);
275
	}
276

    
277
	if (!dialog_prom && items.length === 0) {
278
	    const msg = "Nothing to do - packages already installed.";
279
	    var dialog_prom = dialog.info(this.dialog_ctx, msg);
280
	}
281

    
282
	if (dialog_prom) {
283
	    dialog.close(this.dialog_ctx);
284

    
285
	    await dialog_prom;
286

    
287
	    this.hide();
288
	    return;
289
	}
290

    
291
	this.item_entries = items.map(i => new ItemEntry(this, i));
292
	this.to_install_list.append(...this.item_entries.map(ie => ie.main_li));
293

    
294
	dialog.close(this.dialog_ctx);
295
    }
296

    
297
    const process_file = async (work, hash_key) => {
298
	if (!work.is_ok)
299
	    return;
300

    
301
	work.waiting++;
302

    
303
	try {
304
	    var file_uses = await haketilodb.idb_get(work.file_uses_transaction,
305
						     "file_uses", hash_key);
306
	    if (!work.is_ok)
307
		return;
308
	} catch(e) {
309
	    const msg = "Error accessing Haketilo's internal database :(";
310
	    return work.err(e, msg);
311
	}
312

    
313
	if (!file_uses) {
314
	    const url = `${this.repo_url}file/${hash_key}`;
315

    
316
	    try {
317
		var response = await fetch(url);
318
		if (!work.is_ok)
319
		    return;
320
	    } catch(e) {
321
		const msg = "Failure to communicate with repository :(";
322
		return work.err(e, msg);
323
	    }
324

    
325
	    if (!response.ok) {
326
		const msg = `Repository sent HTTP code ${response.status} :(`;
327
		return work.err(null, msg);
328
	    }
329

    
330
	    try {
331
		var text = await response.text();
332
		if (!work.is_ok)
333
		    return;
334
	    } catch(e) {
335
		const msg = "Repository's response is not valid text :(";
336
		return work.err(e, msg);
337
	    }
338

    
339
	    const digest = await sha256(text);
340
	    if (!work.is_ok)
341
		return;
342
	    if (`sha256-${digest}` !== hash_key) {
343
		const msg = `${url} served a file with different SHA256 cryptographic sum :(`;
344
		return work.err(null, msg);
345
	    }
346

    
347
	    work.result.push([hash_key, text]);
348
	}
349

    
350
	if (--work.waiting === 0)
351
	    work.resolve_cb(work.result);
352
    }
353

    
354
    const get_missing_files = async item_defs => {
355
	const [work, work_prom] = await init_work();
356
	work.file_uses_transaction = work.db.transaction("file_uses");
357

    
358
	const processed_files = new Set();
359

    
360
	for (const item_def of item_defs) {
361
	    for (const file of get_files(item_def)) {
362
		if (!processed_files.has(file.hash_key)) {
363
		    processed_files.add(file.hash_key);
364
		    process_file(work, file.hash_key);
365
		}
366
	    }
367
	}
368

    
369
	return processed_files.size > 0 ? work_prom : [];
370
    }
371

    
372
    const perform_install = async () => {
373
	if (!this.show || !this.item_entries)
374
	    return;
375

    
376
	dialog.loader(this.dialog_ctx, "Installing...");
377

    
378
	const item_defs = this.item_entries.map(ie => ie.item_def);
379

    
380
	try {
381
	    var files = (await get_missing_files(item_defs))
382
		.reduce((ac, [hk, txt]) => Object.assign(ac, {[hk]: txt}), {});
383
	} catch(e) {
384
	    var dialog_prom = dialog.error(this.dialog_ctx, e);
385
	}
386

    
387
	if (files !== undefined) {
388
	    const data = {files};
389
	    const names = [["mappings", "mapping"], ["resources", "resource"]];
390

    
391
	    for (const [set_name, type] of names) {
392
		const set = {};
393

    
394
		for (const def of item_defs.filter(def => def.type === type))
395
		    set[def.identifier] = {[version_string(def.version)]: def};
396

    
397
		data[set_name] = set;
398
	    }
399

    
400
	    try {
401
		await haketilodb.save_items(data);
402
	    } catch(e) {
403
		console.error(e);
404
		const msg = "Error writing to Haketilo's internal database :(";
405
		var dialog_prom = dialog.error(this.dialog_ctx, msg);
406
	    }
407
	}
408

    
409
	if (!dialog_prom) {
410
	    const msg = "Successfully installed!";
411
	    var dialog_prom = dialog.info(this.dialog_ctx, msg);
412
	}
413

    
414
	dialog.close(this.dialog_ctx);
415

    
416
	await dialog_prom;
417

    
418
	this.hide();
419
    }
420

    
421
    const hide_super = this.hide;
422
    this.hide = () => {
423
	if (!hide_super())
424
	    return;
425

    
426
	delete this.item_entries;
427
	[...this.to_install_list.children].forEach(n => n.remove());
428
    }
429

    
430
    const hide_cb = this.dialog_ctx.when_hidden(this.hide);
431
    this.cancel_but.addEventListener("click", hide_cb);
432

    
433
    const install_cb = this.dialog_ctx.when_hidden(perform_install);
434
    this.install_but.addEventListener("click", install_cb);
435
}
436
#EXPORT InstallView
(9-9/24)