summaryrefslogtreecommitdiff
path: root/html/display-panel.js
blob: 2539dedf323aa09040e0992d11a729c404d32f61 (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
/**
 * Hachette display panel logic
 *
 * Copyright (C) 2021 Wojtek Kosior
 * Redistribution terms are gathered in the `copyright' file.
 */

/*
 * IMPORTS_START
 * IMPORT browser
 * IMPORT is_chrome
 * IMPORT is_mozilla
 *** Using remote storage here seems inefficient, we only resort to that
 *** temporarily, before all storage access gets reworked.
 * IMPORT get_remote_storage
 * IMPORT get_import_frame
 * IMPORT query_all
 * IMPORT CONNECTION_TYPE
 * IMPORT is_privileged_url
 * IMPORT TYPE_PREFIX
 * IMPORT nice_name
 * IMPORT open_in_settings
 * IMPORT for_each_possible_pattern
 * IMPORT by_id
 * IMPORT clone_template
 * IMPORTS_END
 */

let storage;
let tab_url;

const tab_query = {currentWindow: true, active: true};

async function get_current_tab()
{
    /* Fix for fact that Chrome does not use promises here */
    const promise = is_chrome ?
	  new Promise((resolve, reject) =>
		      browser.tabs.query(tab_query, tab => resolve(tab))) :
	  browser.tabs.query(tab_query);

    try {
	return (await promise)[0];
    } catch(e) {
	console.log(e);
    }
}

const page_url_heading = by_id("page_url_heading");
const show_privileged_notice_chbx = by_id("show_privileged_notice_chbx");
const show_page_state_chbx = by_id("show_page_state_chbx");

async function show_page_activity_info()
{
    const tab = await get_current_tab();

    if (tab === undefined) {
	page_url_heading.textContent = "unknown page";
	return;
    }

    tab_url = /^([^?#]*)/.exec(tab.url)[1];
    page_url_heading.textContent = tab_url;
    if (is_privileged_url(tab_url)) {
	show_privileged_notice_chbx.checked = true;
	return;
    }

    populate_possible_patterns_list(tab_url);
    show_page_state_chbx.checked = true;

    try_to_connect(tab.id);
}

const possible_patterns_ul = by_id("possible_patterns");
const pattern_li_template = by_id("pattern_li_template");
pattern_li_template.removeAttribute("id");
const known_patterns = new Map();

function add_pattern_to_list(pattern)
{
    const li = pattern_li_template.cloneNode(true);
    li.id = `pattern_li_${known_patterns.size}`;
    known_patterns.set(pattern, li.id);

    const span = li.firstElementChild;
    span.textContent = pattern;

    const button = span.nextElementSibling;
    const settings_opener = () => open_in_settings(TYPE_PREFIX.PAGE, pattern);
    button.addEventListener("click", settings_opener);

    possible_patterns_ul.appendChild(li)

    return li.id;
}

function ensure_pattern_exists(pattern)
{
    let id = known_patterns.get(pattern);
    /*
     * As long as pattern computation works well, we should never get into this
     * conditional block. This is just a safety measure. To be removed as part
     * of a bigger rework when we start taking iframes into account.
     */
    if (id === undefined) {
	console.log(`unknown pattern: ${pattern}`);
	id = add_pattern_to_list(pattern);
    }

    return id;
}

function set_pattern_li_button_text(li_id, text)
{
    by_id(li_id).firstElementChild.nextElementSibling.textContent = text;
}

function handle_page_change(change)
{
    const li_id = ensure_pattern_exists(change.item);
    if (change.old_val === undefined)
	set_pattern_li_button_text(li_id, "Edit in settings");
    if (change.new_val === undefined)
	set_pattern_li_button_text(li_id, "Add setting");
}

function populate_possible_patterns_list(url)
{
    for_each_possible_pattern(url, add_pattern_to_list);

    for (const [pattern, settings] of query_all(storage, url)) {
	set_pattern_li_button_text(ensure_pattern_exists(pattern),
				   "Edit in settings");
    }

    storage.add_change_listener(handle_page_change, [TYPE_PREFIX.PAGE]);
}

const connected_chbx = by_id("connected_chbx");
const query_pattern_but = by_id("query_pattern");

var content_script_port;

function try_to_connect(tab_id)
{
    /* This won't connect to iframes. We'll add support for them later */
    const connect_info = {name: CONNECTION_TYPE.ACTIVITY_INFO, frameId: 0};
    content_script_port = browser.tabs.connect(tab_id, connect_info);

    const disconnect_cb = () => handle_disconnect(tab_id, start_querying_repos);
    content_script_port.onDisconnect.addListener(disconnect_cb);
    content_script_port.onMessage.addListener(handle_activity_report);

    query_pattern_but.addEventListener("click", start_querying_repos);

    if (is_mozilla)
	setTimeout(() => monitor_connecting(tab_id), 1000);
}

const query_started_chbx = by_id("query_started_chbx");

function start_querying_repos(port)
{
    const repo_urls = storage.get_all_names(TYPE_PREFIX.REPO);
    if (content_script_port)
	content_script_port.postMessage([TYPE_PREFIX.URL, tab_url, repo_urls]);
    query_started_chbx.checked = true;
}

const loading_chbx = by_id("loading_chbx");

function handle_disconnect(tab_id, button_cb)
{
    query_pattern_but.removeEventListener("click", button_cb);
    content_script_port = null;

    if (is_chrome && !browser.runtime.lastError)
	return;

    /* return if error was not during connection initialization */
    if (connected_chbx.checked)
	return;

    loading_chbx.checked = !loading_chbx.checked;
    setTimeout(() => try_to_connect(tab_id), 1000);
}

function monitor_connecting(tab_id)
{
    if (connected_chbx.checked)
	return;

    if (content_script_port)
	content_script_port.disconnect();
    else
	return;

    loading_chbx.checked = !loading_chbx.checked;
    try_to_connect(tab_id);
}

const pattern_span = by_id("pattern");
const view_pattern_but = by_id("view_pattern");
const blocked_span = by_id("blocked");
const payload_span = by_id("payload");
const view_payload_but = by_id("view_payload");
const container_for_injected = by_id("container_for_injected");

const queried_items = new Map();

function handle_activity_report(message)
{
    connected_chbx.checked = true;

    const [type, data] = message;

    if (type === "settings") {
	let [pattern, settings] = data;

	settings = settings || {};
	blocked_span.textContent = settings.allow ? "no" : "yes";

	if (pattern) {
	    pattern_span.textContent = pattern;
	    const settings_opener =
		  () => open_in_settings(TYPE_PREFIX.PAGE, pattern);
	    view_pattern_but.classList.remove("hide");
	    view_pattern_but.addEventListener("click", settings_opener);
	} else {
	    pattern_span.textContent = "none";
	}

	const components = settings.components;
	if (components) {
	    payload_span.textContent = nice_name(...components);
	    const settings_opener = () => open_in_settings(...components);
	    view_payload_but.classList.remove("hide");
	    view_payload_but.addEventListener("click", settings_opener);
	} else {
	    payload_span.textContent = "none";
	}
    }
    if (type === "script") {
	const h4 = document.createElement("h4");
	const pre = document.createElement("pre");
	h4.textContent = "script";
	pre.textContent = data;

	container_for_injected.appendChild(h4);
	container_for_injected.appendChild(pre);
    }
    if (type === "repo_query_action") {
	query_started_chbx.checked = true;

	const key = data.prefix + data.item;
	const results = queried_items.get(key) || {};
	Object.assign(results, data.results);
	queried_items.set(key, results);

	const action = data.prefix === TYPE_PREFIX.URL ?
	      show_query_result : record_fetched_install_dep;

	for (const [repo_url, result] of Object.entries(data.results))
	    action(data.prefix, data.item, repo_url, result);
    }
}

const container_for_repo_responses = by_id("container_for_repo_responses");

const results_lists = new Map();

function create_results_list(url)
{
    const list_div = document.createElement("div");
    const list_head = document.createElement("h4");
    const list = document.createElement("ul");

    list_head.textContent = url;
    list_div.appendChild(list_head);
    list_div.appendChild(list);
    container_for_repo_responses.appendChild(list_div);

    const list_object = {list, by_repo: new Map()};

    results_lists.set(url, list_object);

    return list_object;
}

function create_result_item(list_object, repo_url, result)
{
    const result_li = document.createElement("li");
    const repo_url_span = document.createElement("span");
    const result_item = {result_li, appended: null};

    repo_url_span.textContent = repo_url;
    result_li.appendChild(repo_url_span);

    list_object.list.appendChild(result_li);
    list_object.by_repo.set(repo_url, result_item);

    return result_item;
}

function set_appended(result_item, element)
{
    if (result_item.appended)
	result_item.appended.remove();
    result_item.appended = element;
    result_item.result_li.appendChild(element);
}

function show_message(result_item, text)
{
    const div = document.createElement("div");
    div.textContent = text;
    set_appended(result_item, div);
}

function showcb(text)
{
    return item => show_message(item, text);
}

function unroll_chbx_first_checked(entry_object)
{
    if (!entry_object.chbx.checked)
	return;

    entry_object.chbx.removeEventListener("change", entry_object.unroll_cb);
    delete entry_object.unroll_cb;

    entry_object.unroll.textContent = "preview not implemented...";
}

const show_install_chbx = by_id("show_install_view_chbx");

let import_frame;
let install_target = null;

function install_abort(error_state)
{
    import_frame.show_error(`Error: ${error_state}`);
    install_target = null;
}

/*
 * Translate objects from the format in which they are sent by Hydrilla to the
 * format in which they are stored in settings.
 */

function translate_script(script_object, repo_url)
{
    return {
	[TYPE_PREFIX.SCRIPT + script_object.name]: {
	    hash: script_object.sha256,
	    url: `${repo_url}/content/${script_object.location}`
	}
    };
}

function translate_bag(bag_object)
{
    return {
	[TYPE_PREFIX.BAG + bag_object.name]: bag_object.components
    };
}

const format_translators = {
    [TYPE_PREFIX.BAG]: translate_bag,
    [TYPE_PREFIX.SCRIPT]: translate_script
};

function install_check_ready()
{
    if (install_target.to_fetch.size > 0)
	return;

    const page_key = [TYPE_PREFIX.PAGE + install_target.pattern];
    const to_install = [{[page_key]: {components: install_target.payload}}];

    for (const key of install_target.fetched) {
	const old_object =
	      queried_items.get(key)[install_target.repo_url].response;
	const new_object =
	      format_translators[key[0]](old_object, install_target.repo_url);
	to_install.push(new_object);
    }

    import_frame.show_selection(to_install);
}

const possible_errors = ["connection_error", "parse_error"];

function fetch_install_deps(components)
{
    const needed = [...components];
    const processed = new Set();

    while (needed.length > 0) {
	const [prefix, item] = needed.pop();
	const key = prefix + item;
	processed.add(key);
	const results = queried_items.get(key);
	let relevant_result = null;

	if (results)
	    relevant_result = results[install_target.repo_url];

	if (!relevant_result) {
	    content_script_port.postMessage([prefix, item,
					     [install_target.repo_url]]);
	    install_target.to_fetch.add(key);
	    continue;
	}

	if (possible_errors.includes(relevant_result.state)) {
	    install_abort(relevant_result.state);
	    return false;
	}

	install_target.fetched.add(key);

	if (prefix !== TYPE_PREFIX.BAG)
	    continue;

	for (const dependency of relevant_result.response.components) {
	    if (processed.has(dependency.join('')))
		continue;
	    needed.push(dependency);
	}
    }
}

function record_fetched_install_dep(prefix, item, repo_url, result)
{
    const key = prefix + item;

    if (!install_target || repo_url !== install_target.repo_url ||
	!install_target.to_fetch.has(key))
	return;

    if (possible_errors.includes(result.state)) {
	install_abort(result.state);
	return;
    }

    if (result.state !== "completed")
	return;

    install_target.to_fetch.delete(key);
    install_target.fetched.add(key);

    if (prefix === TYPE_PREFIX.BAG &&
	fetch_install_deps(result.response.components) === false)
	return;

    install_check_ready();
}

function install_clicked(entry_object)
{
    show_install_chbx.checked = true;
    import_frame.show_loading();

    install_target = {
	repo_url: entry_object.repo_url,
	pattern: entry_object.match_object.pattern,
	payload: entry_object.match_object.payload,
	fetched: new Set(),
	to_fetch: new Set()
    };

    fetch_install_deps([install_target.payload]);

    install_check_ready();
}

var max_query_result_id = 0;

function show_query_successful_result(result_item, repo_url, result)
{
    const ul = document.createElement("ul");

    set_appended(result_item, ul);

    for (const match of result) {
	const entry_object = clone_template("query_match_li_template");

	entry_object.pattern.textContent = match.pattern;

	ul.appendChild(entry_object.li);

	if (!match.payload) {
	    entry_object.payload.textContent = "(none)";
	    for (const key of ["chbx", "br", "triangle", "unroll"])
		entry_object[key].remove();
	    continue;
	}

	entry_object.component.textContent = nice_name(...match.payload);

	const install_cb = () => install_clicked(entry_object);
	entry_object.btn.addEventListener("click", install_cb);

	const chbx_id = `query_result_${max_query_result_id++}`;
	entry_object.chbx.id = chbx_id;
	entry_object.lbl.setAttribute("for", chbx_id);

	entry_object.unroll_cb = () => unroll_chbx_first_checked(entry_object);
	entry_object.chbx.addEventListener("change", entry_object.unroll_cb);

	entry_object.component_object = match.payload;
	entry_object.match_object = match;
	entry_object.repo_url = repo_url;
    }
}

function show_query_result(url_prefix, url, repo_url, result)
{
    const results_list_object = results_lists.get(url) ||
	  create_results_list(url);
    const result_item = results_list_object.by_repo.get(repo_url) ||
	  create_result_item(results_list_object, repo_url, result);

    const completed_cb =
	  item => show_query_successful_result(item, repo_url, result.response);
    const possible_actions = {
	completed: completed_cb,
	started: showcb("loading..."),
	connection_error: showcb("Error when querying repository."),
	parse_error: showcb("Bad data format received.")
    };
    possible_actions[result.state](result_item, repo_url);
}

by_id("settings_but")
    .addEventListener("click", (e) => browser.runtime.openOptionsPage());

async function main()
{
    storage = await get_remote_storage();
    import_frame = await get_import_frame();
    import_frame.onclose = () => show_install_chbx.checked = false;
    show_page_activity_info();
}

main();