1
|
/**
|
2
|
* Myext storage through connection (server side)
|
3
|
*
|
4
|
* Copyright (C) 2021 Wojtek Kosior
|
5
|
* Redistribution terms are gathered in the `copyright' file.
|
6
|
*/
|
7
|
|
8
|
"use strict";
|
9
|
|
10
|
(() => {
|
11
|
const listen_for_connection = window.listen_for_connection;
|
12
|
const get_storage = window.get_storage;
|
13
|
const TYPE_PREFIX = window.TYPE_PREFIX;
|
14
|
const CONNECTION_TYPE = window.CONNECTION_TYPE;
|
15
|
|
16
|
var storage;
|
17
|
|
18
|
async function handle_remote_call(port, message)
|
19
|
{
|
20
|
let [call_id, func, args] = message;
|
21
|
|
22
|
try {
|
23
|
let result = await Promise.resolve(storage[func](...args));
|
24
|
port.postMessage({call_id, result});
|
25
|
} catch (error) {
|
26
|
error = error + '';
|
27
|
port.postMessage({call_id, error});
|
28
|
}
|
29
|
}
|
30
|
|
31
|
function remove_storage_listener(cb) {
|
32
|
storage.remove_change_listener(cb);
|
33
|
}
|
34
|
|
35
|
function new_connection(port)
|
36
|
{
|
37
|
console.log("new remote storage connection!");
|
38
|
|
39
|
port.postMessage({
|
40
|
[TYPE_PREFIX.SCRIPT] : storage.get_all(TYPE_PREFIX.SCRIPT),
|
41
|
[TYPE_PREFIX.BAG] : storage.get_all(TYPE_PREFIX.BAG),
|
42
|
[TYPE_PREFIX.PAGE] : storage.get_all(TYPE_PREFIX.PAGE)
|
43
|
});
|
44
|
|
45
|
let handle_change = change => port.postMessage(change);
|
46
|
|
47
|
storage.add_change_listener(handle_change);
|
48
|
|
49
|
port.onMessage.addListener(m => handle_remote_call(port, m));
|
50
|
port.onDisconnect.addListener(() =>
|
51
|
remove_storage_listener(handle_change));
|
52
|
}
|
53
|
|
54
|
async function start()
|
55
|
{
|
56
|
storage = await get_storage();
|
57
|
|
58
|
listen_for_connection(CONNECTION_TYPE.REMOTE_STORAGE, new_connection);
|
59
|
}
|
60
|
|
61
|
window.start_storage_server = start;
|
62
|
})();
|