2019-08-17 22:50:48 +00:00
|
|
|
/*
|
2020-01-01 17:00:00 +00:00
|
|
|
* Copyright (C) 2019-2020 Alex Yatskov <alex@foosoft.net>
|
2019-08-17 22:50:48 +00:00
|
|
|
* Author: Alex Yatskov <alex@foosoft.net>
|
|
|
|
*
|
|
|
|
* This program is free software: you can redistribute it and/or modify
|
|
|
|
* it under the terms of the GNU General Public License as published by
|
|
|
|
* the Free Software Foundation, either version 3 of the License, or
|
|
|
|
* (at your option) any later version.
|
|
|
|
*
|
|
|
|
* This program is distributed in the hope that it will be useful,
|
|
|
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
* GNU General Public License for more details.
|
|
|
|
*
|
|
|
|
* You should have received a copy of the GNU General Public License
|
|
|
|
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
|
|
class FrontendApiReceiver {
|
2019-12-12 02:59:38 +00:00
|
|
|
constructor(source='', handlers=new Map()) {
|
|
|
|
this._source = source;
|
|
|
|
this._handlers = handlers;
|
2019-08-17 22:50:48 +00:00
|
|
|
|
|
|
|
chrome.runtime.onConnect.addListener(this.onConnect.bind(this));
|
|
|
|
}
|
|
|
|
|
|
|
|
onConnect(port) {
|
|
|
|
if (port.name !== 'frontend-api-receiver') { return; }
|
|
|
|
|
|
|
|
port.onMessage.addListener(this.onMessage.bind(this, port));
|
|
|
|
}
|
|
|
|
|
2019-08-19 00:51:19 +00:00
|
|
|
onMessage(port, {id, action, params, target, senderId}) {
|
2019-12-12 02:59:38 +00:00
|
|
|
if (target !== this._source) { return; }
|
|
|
|
|
|
|
|
const handler = this._handlers.get(action);
|
|
|
|
if (typeof handler !== 'function') { return; }
|
2019-08-17 22:50:48 +00:00
|
|
|
|
2019-08-19 00:51:19 +00:00
|
|
|
this.sendAck(port, id, senderId);
|
2019-08-17 22:50:48 +00:00
|
|
|
|
|
|
|
handler(params).then(
|
2019-11-27 03:01:54 +00:00
|
|
|
(result) => {
|
2019-08-19 00:51:19 +00:00
|
|
|
this.sendResult(port, id, senderId, {result});
|
2019-08-17 22:50:48 +00:00
|
|
|
},
|
2019-11-27 03:01:54 +00:00
|
|
|
(error) => {
|
2019-10-08 01:04:58 +00:00
|
|
|
this.sendResult(port, id, senderId, {error: errorToJson(error)});
|
2019-08-17 22:50:48 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2019-08-19 00:51:19 +00:00
|
|
|
sendAck(port, id, senderId) {
|
|
|
|
port.postMessage({type: 'ack', id, senderId});
|
2019-08-17 22:50:48 +00:00
|
|
|
}
|
|
|
|
|
2019-08-19 00:51:19 +00:00
|
|
|
sendResult(port, id, senderId, data) {
|
|
|
|
port.postMessage({type: 'result', id, senderId, data});
|
2019-08-17 22:50:48 +00:00
|
|
|
}
|
|
|
|
}
|