summaryrefslogtreecommitdiff
path: root/background/page_info_server.js
blob: 6f02750cdbc35731e5584ed16e5bd193ae8706db (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
/**
 * part of Hachette
 * Serving of storage data corresponding to requested urls (server side).
 *
 * Copyright (C) 2021 Wojtek Kosior
 * Redistribution terms are gathered in the `copyright' file.
 */

/*
 * IMPORTS_START
 * IMPORT listen_for_connection
 * IMPORT get_storage
 * IMPORT get_query_all
 * IMPORT TYPE_PREFIX
 * IMPORT CONNECTION_TYPE
 * IMPORT url_matches
 * IMPORTS_END
 */

var storage;
var query_all;

function handle_change(connection_data, change)
{
    if (change.prefix !== TYPE_PREFIX.PAGE)
	return;

    connection_data.port.postMessage(["change", change]);
}

async function handle_subscription(connection_data, message)
{
    const [action, url] = message;
    if (action === "unsubscribe") {
	connection_data.subscribed.delete(url);
	return;
    }

    connection_data.subscribed.add(url);
    connection_data.port.postMessage(["new_url", query_all(url)]);
}

function new_connection(port)
{
    console.log("new page info connection!");

    const connection_data = {
	subscribed : new Set(),
	port
    };

    let _handle_change = change => handle_change(connection_data, change);

    storage.add_change_listener(_handle_change);

    port.onMessage.addListener(m => handle_subscription(connection_data, m));
    port.onDisconnect.addListener(
	() => storage.remove_change_listener(_handle_change)
    );
}

async function start_page_info_server()
{
    storage = await get_storage();
    query_all = await get_query_all();

    listen_for_connection(CONNECTION_TYPE.PAGE_INFO, new_connection);
}

/*
 * EXPORTS_START
 * EXPORT start_page_info_server
 * EXPORTS_END
 */