Project

General

Profile

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

haketilo / background / page_info_server.js @ 5957fbee

1
/**
2
 * part of Hachette
3
 * Serving of storage data corresponding to requested urls (server side).
4
 *
5
 * Copyright (C) 2021 Wojtek Kosior
6
 * Redistribution terms are gathered in the `copyright' file.
7
 */
8

    
9
/*
10
 * IMPORTS_START
11
 * IMPORT listen_for_connection
12
 * IMPORT get_storage
13
 * IMPORT query_all
14
 * IMPORT TYPE_PREFIX
15
 * IMPORT CONNECTION_TYPE
16
 * IMPORT url_matches
17
 * IMPORTS_END
18
 */
19

    
20
var storage;
21

    
22
function handle_change(connection_data, change)
23
{
24
    if (change.prefix !== TYPE_PREFIX.PAGE)
25
	return;
26

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

    
30
async function handle_subscription(connection_data, message)
31
{
32
    const [action, url] = message;
33
    if (action === "unsubscribe") {
34
	connection_data.subscribed.delete(url);
35
	return;
36
    }
37

    
38
    connection_data.subscribed.add(url);
39
    connection_data.port.postMessage(["new_url", query_all(storage, url)]);
40
}
41

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

    
46
    const connection_data = {
47
	subscribed : new Set(),
48
	port
49
    };
50

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

    
53
    storage.add_change_listener(_handle_change);
54

    
55
    port.onMessage.addListener(m => handle_subscription(connection_data, m));
56
    port.onDisconnect.addListener(
57
	() => storage.remove_change_listener(_handle_change)
58
    );
59
}
60

    
61
async function start_page_info_server()
62
{
63
    storage = await get_storage();
64

    
65
    listen_for_connection(CONNECTION_TYPE.PAGE_INFO, new_connection);
66
}
67

    
68
/*
69
 * EXPORTS_START
70
 * EXPORT start_page_info_server
71
 * EXPORTS_END
72
 */
(3-3/6)