Project

General

Profile

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

haketilo / html / install.js @ 72553a2d

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
#FROM common/misc.js      IMPORT sha256_async AS compute_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 = install_view.dialog_ctx.when_hidden(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 _make_url_reg(item_type) {
117
    return new RegExp(
118
	`^https://hydrilla\\.koszko\\.org/schemas/api_${item_type}_description-1\\.([1-9][0-9]*\\.)*schema\\.json$`
119
    );
120
}
121

    
122
const _regexes = {};
123

    
124
function item_schema_url_regex(item_type) {
125
    _regexes[item_type] = _regexes[item_type] || _make_url_reg(item_type);
126
    return _regexes[item_type];
127
}
128

    
129
function InstallView(tab_id, on_view_show, on_view_hide) {
130
    Showable.call(this, on_view_show, on_view_hide);
131

    
132
    Object.assign(this, clone_template("install_view"));
133

    
134
    const show_container = name => {
135
	for (const cid of container_ids) {
136
	    if (cid !== name)
137
		this[cid].classList.add("hide");
138
	}
139
	this[name].classList.remove("hide");
140
    }
141

    
142
    this.dialog_ctx = dialog.make(() => show_container("dialog_container"),
143
				  () => show_container("install_preview"));
144
    this.dialog_container.prepend(this.dialog_ctx.main_div);
145

    
146
    /* Make a link to view a file from the repository. */
147
    const make_file_link = (preview_ctx, file_ref) => {
148
	const a = document.createElement("a");
149
	a.href = `${this.repo_url}file/sha256/${file_ref.sha256}`;
150
	a.innerText = file_ref.file;
151

    
152
	return a;
153
    }
154

    
155
    this.previews_ctx = {};
156

    
157
    this.preview_item = item_def => {
158
	if (!this.shown)
159
	    return;
160

    
161
	const fun = ip[`${item_def.type}_preview`];
162
	const preview_ctx = fun(item_def, this.previews_ctx[item_def.type],
163
				make_file_link);
164
	this.previews_ctx[item_def.type] = preview_ctx;
165

    
166
	const container_name = `${item_def.type}_preview_container`;
167
	show_container(container_name);
168
	this[container_name].prepend(preview_ctx.main_div);
169
    }
170

    
171
    let back_cb = () => show_container("install_preview");
172
    back_cb = this.dialog_ctx.when_hidden(back_cb);
173
    for (const type of ["resource", "mapping"])
174
	this[`${type}_back_but`].addEventListener("click", back_cb);
175

    
176
    const process_item = async (work, item_type, id, ver) => {
177
	if (!work.is_ok || work.processed_by_type[item_type].has(id))
178
	    return;
179

    
180
	work.processed_by_type[item_type].add(id);
181
	work.waiting++;
182

    
183
	const url = ver ?
184
	      `${this.repo_url}${item_type}/${id}/${ver.join(".")}.json` :
185
	      `${this.repo_url}${item_type}/${id}.json`;
186
	const response =
187
	      await browser.tabs.sendMessage(tab_id, ["repo_query", url]);
188
	if (!work.is_ok)
189
	    return;
190

    
191
	if ("error" in response) {
192
	    return work.err(response.error,
193
			    "Failure to communicate with repository :(");
194
	}
195

    
196
	if (!response.ok) {
197
	    return work.err(null,
198
			    `Repository sent HTTP code ${response.status} :(`);
199
	}
200

    
201
	if ("error_json" in response) {
202
	    return work.err(response.error_json,
203
			    "Repository's response is not valid JSON :(");
204
	}
205

    
206
	const captype = item_type[0].toUpperCase() + item_type.substring(1);
207
	const reg = item_schema_url_regex(item_type);
208

    
209
	if (!response.json["$schema"]) {
210
	    const msg = `${captype} ${item_id_string(id, ver)} was served using a nonconforming response format.`;
211
	    return work.err(null, msg);
212
	} else if (!reg.test(response.json["$schema"])) {
213
	    const msg = `${captype} ${item_id_string(id, ver)} was served using unsupported Hydrilla API version. You might need to update Haketilo.`;
214
	    return work.err(null, msg);
215
	}
216

    
217
	/* TODO: JSON schema validation should be added here. */
218

    
219
	const scripts = item_type === "resource" && response.json.scripts;
220
	const files = response.json.source_copyright.concat(scripts || []);
221

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

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

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

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

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

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

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

    
268
	this.repo_url = repo_url;
269

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

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

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

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

    
286
	    await dialog_prom;
287

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

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

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

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

    
302
	work.waiting++;
303

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

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

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

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

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

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

    
348
	    work.result.push([sha256, text]);
349
	}
350

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

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

    
359
	const processed_files = new Set();
360

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

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

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

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

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

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

    
388
	if (files !== undefined) {
389
	    const data = {file: {sha256: files}};
390

    
391
	    for (const type of ["resource", "mapping"]) {
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[type] = 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
(11-11/27)