Project

General

Profile

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

haketilo / html / install.js @ 92fc67cf

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 compute_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/sha256/${file_ref.sha256}`;
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 scripts = item_type === "resource" && response.json.scripts;
215
	const files = response.json.source_copyright.concat(scripts || []);
216

    
217
	if (item_type === "mapping") {
218
	    for (const res_ref of Object.values(response.json.payloads || {}))
219
		process_item(work, "resource", res_ref.identifier);
220
	} else {
221
	    for (const res_ref of (response.json.dependencies || []))
222
		process_item(work, "resource", res_ref.identifier);
223
	}
224

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

    
243
	if (--work.waiting === 0)
244
	    work.resolve_cb(work.result);
245
    }
246

    
247
    async function compute_deps(item_type, item_id, item_ver) {
248
	const [work, work_prom] = await init_work();
249
	work.processed_by_type = {"mapping" : new Set(), "resource": new Set()};
250

    
251
	process_item(work, item_type, item_id, item_ver);
252

    
253
	const items = await work_prom;
254
	items.sort((i1, i2) => compare_items(i1.def, i2.def));
255
	return items;
256
    }
257

    
258
    const show_super = this.show;
259
    this.show = async (repo_url, item_type, item_id, item_ver) => {
260
	if (!show_super())
261
	    return;
262

    
263
	this.repo_url = repo_url;
264

    
265
	dialog.loader(this.dialog_ctx, "Fetching data from repository...");
266

    
267
	try {
268
	    var items = await compute_deps(item_type, item_id, item_ver);
269
	} catch(e) {
270
	    var dialog_prom = dialog.error(this.dialog_ctx, e);
271
	}
272

    
273
	if (!dialog_prom && items.length === 0) {
274
	    const msg = "Nothing to do - packages already installed.";
275
	    var dialog_prom = dialog.info(this.dialog_ctx, msg);
276
	}
277

    
278
	if (dialog_prom) {
279
	    dialog.close(this.dialog_ctx);
280

    
281
	    await dialog_prom;
282

    
283
	    this.hide();
284
	    return;
285
	}
286

    
287
	this.item_entries = items.map(i => new ItemEntry(this, i));
288
	this.to_install_list.append(...this.item_entries.map(ie => ie.main_li));
289

    
290
	dialog.close(this.dialog_ctx);
291
    }
292

    
293
    const process_file = async (work, sha256) => {
294
	if (!work.is_ok)
295
	    return;
296

    
297
	work.waiting++;
298

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

    
309
	if (!file_uses) {
310
	    const url = `${this.repo_url}file/sha256/${sha256}`;
311

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

    
321
	    if (!response.ok) {
322
		const msg = `Repository sent HTTP code ${response.status} :(`;
323
		return work.err(null, msg);
324
	    }
325

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

    
335
	    const digest = await compute_sha256(text);
336
	    if (!work.is_ok)
337
		return;
338
	    if (digest !== sha256) {
339
		const msg = `${url} served a file with different SHA256 cryptographic sum :(`;
340
		return work.err(null, msg);
341
	    }
342

    
343
	    work.result.push([sha256, text]);
344
	}
345

    
346
	if (--work.waiting === 0)
347
	    work.resolve_cb(work.result);
348
    }
349

    
350
    const get_missing_files = async item_defs => {
351
	const [work, work_prom] = await init_work();
352
	work.file_uses_transaction = work.db.transaction("file_uses");
353

    
354
	const processed_files = new Set();
355

    
356
	for (const item_def of item_defs) {
357
	    for (const file of get_files(item_def)) {
358
		if (!processed_files.has(file.sha256)) {
359
		    processed_files.add(file.sha256);
360
		    process_file(work, file.sha256);
361
		}
362
	    }
363
	}
364

    
365
	return processed_files.size > 0 ? work_prom : [];
366
    }
367

    
368
    const perform_install = async () => {
369
	if (!this.show || !this.item_entries)
370
	    return;
371

    
372
	dialog.loader(this.dialog_ctx, "Installing...");
373

    
374
	const item_defs = this.item_entries.map(ie => ie.item_def);
375

    
376
	try {
377
	    var files = (await get_missing_files(item_defs))
378
		.reduce((ac, [h, txt]) => Object.assign(ac, {[h]: txt}), {});
379
	} catch(e) {
380
	    var dialog_prom = dialog.error(this.dialog_ctx, e);
381
	}
382

    
383
	if (files !== undefined) {
384
	    const data = {file: {sha256: files}};
385

    
386
	    for (const type of ["resource", "mapping"]) {
387
		const set = {};
388

    
389
		for (const def of item_defs.filter(def => def.type === type))
390
		    set[def.identifier] = {[version_string(def.version)]: def};
391

    
392
		data[type] = set;
393
	    }
394

    
395
	    try {
396
		await haketilodb.save_items(data);
397
	    } catch(e) {
398
		console.error(e);
399
		const msg = "Error writing to Haketilo's internal database :(";
400
		var dialog_prom = dialog.error(this.dialog_ctx, msg);
401
	    }
402
	}
403

    
404
	if (!dialog_prom) {
405
	    const msg = "Successfully installed!";
406
	    var dialog_prom = dialog.info(this.dialog_ctx, msg);
407
	}
408

    
409
	dialog.close(this.dialog_ctx);
410

    
411
	await dialog_prom;
412

    
413
	this.hide();
414
    }
415

    
416
    const hide_super = this.hide;
417
    this.hide = () => {
418
	if (!hide_super())
419
	    return;
420

    
421
	delete this.item_entries;
422
	[...this.to_install_list.children].forEach(n => n.remove());
423
    }
424

    
425
    const hide_cb = this.dialog_ctx.when_hidden(this.hide);
426
    this.cancel_but.addEventListener("click", hide_cb);
427

    
428
    const install_cb = this.dialog_ctx.when_hidden(perform_install);
429
    this.install_but.addEventListener("click", install_cb);
430
}
431
#EXPORT InstallView
(11-11/26)