aboutsummaryrefslogtreecommitdiff
path: root/background/page_info_server.js
diff options
context:
space:
mode:
Diffstat (limited to 'background/page_info_server.js')
-rw-r--r--background/page_info_server.js77
1 files changed, 77 insertions, 0 deletions
diff --git a/background/page_info_server.js b/background/page_info_server.js
new file mode 100644
index 0000000..49919fd
--- /dev/null
+++ b/background/page_info_server.js
@@ -0,0 +1,77 @@
+/**
+ * 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 remove_storage_listener(cb)
+{
+ storage.remove_change_listener(cb);
+}
+
+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(() => remove_storage_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
+ */