Project

General

Profile

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

haketilo / html / install.js @ 7218849a

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
50
#FROM common/entities.js  IMPORT item_id_string, version_string, get_files
51
#FROM common/misc.js      IMPORT sha256_async AS sha256
52

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

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

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

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

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

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

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

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

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

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

    
116
function InstallView(tab_id, on_view_show, on_view_hide) {
117
    Object.assign(this, clone_template("install_view"));
118
    this.shown = false;
119

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

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

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

    
138
	return a;
139
    }
140

    
141
    this.previews_ctx = {};
142

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

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

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

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

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

    
166
	work.processed_by_type[item_type].add(id);
167
	work.waiting++;
168

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

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

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

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

    
192
	if (response.json.api_schema_version > [1]) {
193
	    let api_ver = "";
194
	    try {
195
		api_ver =
196
		    ` (${version_string(response.json.api_schema_version)})`;
197
	    } catch(e) {
198
		console.warn(e);
199
	    }
200

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

    
206
	/* TODO: JSON schema validation should be added here. */
207

    
208
	delete response.json.api_schema_version;
209
	delete response.json.api_schema_revision;
210

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

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

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

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

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

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

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

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

    
263
	this.shown = true;
264

    
265
	this.repo_url = repo_url;
266

    
267
	dialog.loader(this.dialog_ctx, "Fetching data from repository...");
268

    
269
	try {
270
	    on_view_show();
271
	} catch(e) {
272
	    console.error(e);
273
	}
274

    
275
	try {
276
	    var items = await compute_deps(item_type, item_id, item_ver);
277
	} catch(e) {
278
	    var dialog_prom = dialog.error(this.dialog_ctx, e);
279
	}
280

    
281
	if (!dialog_prom && items.length === 0) {
282
	    const msg = "Nothing to do - packages already installed.";
283
	    var dialog_prom = dialog.info(this.dialog_ctx, msg);
284
	}
285

    
286
	if (dialog_prom) {
287
	    dialog.close(this.dialog_ctx);
288

    
289
	    await dialog_prom;
290

    
291
	    hide();
292
	    return;
293
	}
294

    
295
	this.item_entries = items.map(i => new ItemEntry(this, i));
296
	this.to_install_list.append(...this.item_entries.map(ie => ie.main_li));
297

    
298
	dialog.close(this.dialog_ctx);
299
    }
300

    
301
    const process_file = async (work, hash_key) => {
302
	if (!work.is_ok)
303
	    return;
304

    
305
	work.waiting++;
306

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

    
317
	if (!file_uses) {
318
	    const url = `${this.repo_url}file/${hash_key}`;
319

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

    
329
	    if (!response.ok) {
330
		const msg = `Repository sent HTTP code ${response.status} :(`;
331
		return work.err(null, msg);
332
	    }
333

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

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

    
351
	    work.result.push([hash_key, text]);
352
	}
353

    
354
	if (--work.waiting === 0)
355
	    work.resolve_cb(work.result);
356
    }
357

    
358
    const get_missing_files = async item_defs => {
359
	const [work, work_prom] = await init_work();
360
	work.file_uses_transaction = work.db.transaction("file_uses");
361

    
362
	const processed_files = new Set();
363

    
364
	for (const item_def of item_defs) {
365
	    for (const file of get_files(item_def)) {
366
		if (!processed_files.has(file.hash_key)) {
367
		    processed_files.add(file.hash_key);
368
		    process_file(work, file.hash_key);
369
		}
370
	    }
371
	}
372

    
373
	return processed_files.size > 0 ? work_prom : [];
374
    }
375

    
376
    const perform_install = async () => {
377
	if (!this.show || !this.item_entries)
378
	    return;
379

    
380
	dialog.loader(this.dialog_ctx, "Installing...");
381

    
382
	const item_defs = this.item_entries.map(ie => ie.item_def);
383

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

    
391
	if (files !== undefined) {
392
	    const data = {files};
393
	    const names = [["mappings", "mapping"], ["resources", "resource"]];
394

    
395
	    for (const [set_name, type] of names) {
396
		const set = {};
397

    
398
		for (const def of item_defs.filter(def => def.type === type))
399
		    set[def.identifier] = {[version_string(def.version)]: def};
400

    
401
		data[set_name] = set;
402
	    }
403

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

    
413
	if (!dialog_prom) {
414
	    const msg = "Successfully installed!";
415
	    var dialog_prom = dialog.info(this.dialog_ctx, msg);
416
	}
417

    
418
	dialog.close(this.dialog_ctx);
419

    
420
	await dialog_prom;
421

    
422
	hide();
423
    }
424

    
425
    const hide = () => {
426
	if (!this.shown)
427
	    return;
428

    
429
	this.shown = false;
430
	delete this.item_entries;
431
	[...this.to_install_list.children].forEach(n => n.remove());
432

    
433
	try {
434
	    on_view_hide();
435
	} catch(e) {
436
	    console.error(e);
437
	}
438
    }
439

    
440
    this.when_hidden = cb => {
441
	const wrapped_cb = (...args) => {
442
	    if (!this.shown)
443
		return cb(...args);
444
	}
445
	return wrapped_cb;
446
    }
447

    
448
    const hide_cb = dialog.when_hidden(this.dialog_ctx, hide);
449
    this.cancel_but.addEventListener("click", hide_cb);
450

    
451
    const install_cb = dialog.when_hidden(this.dialog_ctx, perform_install);
452
    this.install_but.addEventListener("click", install_cb);
453
}
(14-14/29)