Project

General

Profile

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

haketilo / html / install.js @ 9bee4afa

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
#FROM common/jsonschema.js IMPORT haketilo_validator, haketilo_schemas, \
53
                                  haketilo_schema_name_regex
54

    
55
#FROM html/repo_query_cacher_client.js IMPORT indirect_fetch
56

    
57
const coll = new Intl.Collator();
58

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

    
67
    const name_comparison = coll.compare(def1.long_name, def2.long_name);
68
    return name_comparison === 0 ?
69
	coll.compare(def1.identifier, def2.identifier) : name_comparison;
70
}
71

    
72
function ItemEntry(install_view, item) {
73
    Object.assign(this, clone_template("install_list_entry"));
74
    this.item_def = item.def;
75

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

    
84
    let preview_cb = () => install_view.preview_item(item.def);
85
    preview_cb = install_view.dialog_ctx.when_hidden(preview_cb);
86
    this.details_but.addEventListener("click", preview_cb);
87
}
88

    
89
const container_ids = [
90
    "install_preview",
91
    "dialog_container",
92
    "mapping_preview_container",
93
    "resource_preview_container"
94
];
95

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

    
109
    work.err = function (error, user_message) {
110
	if (!this.is_ok)
111
	    return;
112

    
113
	if (error)
114
	    console.error("Haketilo:", error);
115
	work.is_ok = false;
116
	work.reject_cb(user_message);
117
    }
118

    
119
    return [work,
120
	    new Promise((...cbs) => [work.resolve_cb, work.reject_cb] = cbs)];
121
}
122

    
123
function InstallView(tab_id, on_view_show, on_view_hide) {
124
    Showable.call(this, on_view_show, on_view_hide);
125

    
126
    Object.assign(this, clone_template("install_view"));
127

    
128
    const show_container = name => {
129
	for (const cid of container_ids) {
130
	    if (cid !== name)
131
		this[cid].classList.add("hide");
132
	}
133
	this[name].classList.remove("hide");
134
    }
135

    
136
    this.dialog_ctx = dialog.make(() => show_container("dialog_container"),
137
				  () => show_container("install_preview"));
138
    this.dialog_container.prepend(this.dialog_ctx.main_div);
139

    
140
    /* Make a link to view a file from the repository. */
141
    const make_file_link = (preview_ctx, file_ref) => {
142
	const a = document.createElement("a");
143
	a.href = `${this.repo_url}file/sha256/${file_ref.sha256}`;
144
	a.innerText = file_ref.file;
145

    
146
	return a;
147
    }
148

    
149
    this.previews_ctx = {};
150

    
151
    this.preview_item = item_def => {
152
	if (!this.shown)
153
	    return;
154

    
155
	const fun = ip[`${item_def.type}_preview`];
156
	const preview_ctx = fun(item_def, this.previews_ctx[item_def.type],
157
				make_file_link);
158
	this.previews_ctx[item_def.type] = preview_ctx;
159

    
160
	const container_name = `${item_def.type}_preview_container`;
161
	show_container(container_name);
162
	this[container_name].prepend(preview_ctx.main_div);
163
    }
164

    
165
    let back_cb = () => show_container("install_preview");
166
    back_cb = this.dialog_ctx.when_hidden(back_cb);
167
    for (const type of ["resource", "mapping"])
168
	this[`${type}_back_but`].addEventListener("click", back_cb);
169

    
170
    const process_item = async (work, item_type, id, ver) => {
171
	if (!work.is_ok || work.processed_by_type[item_type].has(id))
172
	    return;
173

    
174
	work.processed_by_type[item_type].add(id);
175
	work.waiting++;
176

    
177
	const url = ver ?
178
	      `${this.repo_url}${item_type}/${id}/${ver.join(".")}` :
179
	      `${this.repo_url}${item_type}/${id}.json`;
180

    
181

    
182
	try {
183
	    var response = await indirect_fetch(tab_id, url);
184
	} catch(e) {
185
	    return work.err(e, "Failure to communicate with repository :(");
186
	}
187

    
188
	if (!work.is_ok)
189
	    return;
190

    
191
	if (!response.ok) {
192
	    return work.err(null,
193
			    `Repository sent HTTP code ${response.status} :(`);
194
	}
195

    
196
	try {
197
	    var json = await response.json();
198
	} catch(e) {
199
	    return work.err(e, "Repository's response is not valid JSON :(");
200
	}
201

    
202
	if (!work.is_ok)
203
	    return;
204

    
205
	const captype = item_type[0].toUpperCase() + item_type.substring(1);
206

    
207
	const nonconforming_format_error_msg =
208
	      `${captype} ${item_id_string(id, ver)} was served using a nonconforming response format.`;
209

    
210
	try {
211
	    const match = haketilo_schema_name_regex.exec(json.$schema);
212
	    var major_schema_version = match.groups.major;
213

    
214
	    if (!["1", "2"].includes(major_schema_version)) {
215
		const msg = `${captype} ${item_id_string(id, ver)} was served using unsupported Hydrilla API version. You might need to update Haketilo.`;
216
		return work.err(null, msg);
217
	    }
218
	} catch(e) {
219
	    return work.err(e, nonconforming_format_error_msg);
220
	}
221

    
222
	const schema_name = `api_${item_type}_description-${major_schema_version}.schema.json`;
223

    
224
	const schema = haketilo_schemas[schema_name];
225
	const result = haketilo_validator.validate(json, schema);
226
	if (result.errors.length > 0)
227
	    return work.err(result.errors, nonconforming_format_error_msg);
228

    
229
	const scripts = item_type === "resource" && json.scripts;
230
	const files = json.source_copyright.concat(scripts || []);
231

    
232
	if (item_type === "mapping") {
233
	    for (const res_ref of Object.values(json.payloads || {}))
234
		process_item(work, "resource", res_ref.identifier);
235
	} else {
236
	    for (const res_ref of (json.dependencies || []))
237
		process_item(work, "resource", res_ref.identifier);
238
	}
239

    
240
	if (major_schema_version >= 2) {
241
	    for (const map_ref of (json.required_mappings || []))
242
		process_item(work, "mapping", map_ref.identifier);
243
	}
244

    
245
	/*
246
	 * At this point we already have JSON definition of the item and we
247
	 * triggered processing of its dependencies. We now have to verify if
248
	 * the same or newer version of the item is already present in the
249
	 * database and if so - omit this item.
250
	 */
251
	const transaction = work.db.transaction(item_type);
252
	try {
253
	    var db_def = await haketilodb.idb_get(transaction, item_type, id);
254
	    if (!work.is_ok)
255
		return;
256
	} catch(e) {
257
	    const msg = "Error accessing Haketilo's internal database :(";
258
	    return work.err(e, msg);
259
	}
260
	if (!db_def || db_def.version < json.version)
261
	    work.result.push({def: json, db_def});
262

    
263
	if (--work.waiting === 0)
264
	    work.resolve_cb(work.result);
265
    }
266

    
267
    async function compute_deps(item_type, item_id, item_ver) {
268
	const [work, work_prom] = await init_work();
269
	work.processed_by_type = {"mapping" : new Set(), "resource": new Set()};
270

    
271
	process_item(work, item_type, item_id, item_ver);
272

    
273
	const items = await work_prom;
274
	items.sort((i1, i2) => compare_items(i1.def, i2.def));
275
	return items;
276
    }
277

    
278
    const show_super = this.show;
279
    this.show = async (repo_url, item_type, item_id, item_ver) => {
280
	if (!show_super())
281
	    return;
282

    
283
	this.repo_url = repo_url;
284

    
285
	dialog.loader(this.dialog_ctx, "Fetching data from repository...");
286

    
287
	try {
288
	    var items = await compute_deps(item_type, item_id, item_ver);
289
	} catch(e) {
290
	    var dialog_prom = dialog.error(this.dialog_ctx, e);
291
	}
292

    
293
	if (!dialog_prom && items.length === 0) {
294
	    const msg = "Nothing to do - packages already installed.";
295
	    var dialog_prom = dialog.info(this.dialog_ctx, msg);
296
	}
297

    
298
	if (dialog_prom) {
299
	    dialog.close(this.dialog_ctx);
300

    
301
	    await dialog_prom;
302

    
303
	    this.hide();
304
	    return;
305
	}
306

    
307
	this.item_entries = items.map(i => new ItemEntry(this, i));
308
	this.to_install_list.append(...this.item_entries.map(ie => ie.main_li));
309

    
310
	dialog.close(this.dialog_ctx);
311
    }
312

    
313
    const process_file = async (work, sha256) => {
314
	if (!work.is_ok)
315
	    return;
316

    
317
	work.waiting++;
318

    
319
	try {
320
	    var file_uses = await haketilodb.idb_get(work.file_uses_transaction,
321
						     "file_uses", sha256);
322
	    if (!work.is_ok)
323
		return;
324
	} catch(e) {
325
	    const msg = "Error accessing Haketilo's internal database :(";
326
	    return work.err(e, msg);
327
	}
328

    
329
	if (!file_uses) {
330
	    const url = `${this.repo_url}file/sha256/${sha256}`;
331

    
332
	    try {
333
		var response = await fetch(url);
334
		if (!work.is_ok)
335
		    return;
336
	    } catch(e) {
337
		const msg = "Failure to communicate with repository :(";
338
		return work.err(e, msg);
339
	    }
340

    
341
	    if (!response.ok) {
342
		const msg = `Repository sent HTTP code ${response.status} :(`;
343
		return work.err(null, msg);
344
	    }
345

    
346
	    const text = await response.text();
347
	    if (!work.is_ok)
348
		return;
349

    
350
	    const digest = await compute_sha256(text);
351
	    if (!work.is_ok)
352
		return;
353
	    if (digest !== sha256) {
354
		const msg = `${url} served a file with different SHA256 cryptographic sum :(`;
355
		return work.err(null, msg);
356
	    }
357

    
358
	    work.result.push([sha256, text]);
359
	}
360

    
361
	if (--work.waiting === 0)
362
	    work.resolve_cb(work.result);
363
    }
364

    
365
    const get_missing_files = async item_defs => {
366
	const [work, work_prom] = await init_work();
367
	work.file_uses_transaction = work.db.transaction("file_uses");
368

    
369
	const processed_files = new Set();
370

    
371
	for (const item_def of item_defs) {
372
	    for (const file of get_files(item_def)) {
373
		if (!processed_files.has(file.sha256)) {
374
		    processed_files.add(file.sha256);
375
		    process_file(work, file.sha256);
376
		}
377
	    }
378
	}
379

    
380
	return processed_files.size > 0 ? work_prom : [];
381
    }
382

    
383
    const perform_install = async () => {
384
	if (!this.show || !this.item_entries)
385
	    return;
386

    
387
	dialog.loader(this.dialog_ctx, "Installing...");
388

    
389
	const item_defs = this.item_entries.map(ie => ie.item_def);
390

    
391
	try {
392
	    var files = (await get_missing_files(item_defs))
393
		.reduce((ac, [h, txt]) => Object.assign(ac, {[h]: txt}), {});
394
	} catch(e) {
395
	    var dialog_prom = dialog.error(this.dialog_ctx, e);
396
	}
397

    
398
	if (files !== undefined) {
399
	    const data = {file: {sha256: files}};
400

    
401
	    for (const type of ["resource", "mapping"]) {
402
		const set = {};
403

    
404
		for (const def of item_defs.filter(def => def.type === type))
405
		    set[def.identifier] = {[version_string(def.version)]: def};
406

    
407
		data[type] = set;
408
	    }
409

    
410
	    try {
411
		await haketilodb.save_items(data);
412
	    } catch(e) {
413
		console.error("Haketilo:", e);
414
		const msg = "Error writing to Haketilo's internal database :(";
415
		var dialog_prom = dialog.error(this.dialog_ctx, msg);
416
	    }
417
	}
418

    
419
	if (!dialog_prom) {
420
	    const msg = "Successfully installed!";
421
	    var dialog_prom = dialog.info(this.dialog_ctx, msg);
422
	}
423

    
424
	dialog.close(this.dialog_ctx);
425

    
426
	await dialog_prom;
427

    
428
	this.hide();
429
    }
430

    
431
    const hide_super = this.hide;
432
    this.hide = () => {
433
	if (!hide_super())
434
	    return;
435

    
436
	delete this.item_entries;
437
	[...this.to_install_list.children].forEach(n => n.remove());
438
    }
439

    
440
    const hide_cb = this.dialog_ctx.when_hidden(this.hide);
441
    this.cancel_but.addEventListener("click", hide_cb);
442

    
443
    const install_cb = this.dialog_ctx.when_hidden(perform_install);
444
    this.install_but.addEventListener("click", install_cb);
445
}
446
#EXPORT InstallView
(11-11/28)