2019-08-17 22:50:48 +00:00
|
|
|
/*
|
|
|
|
* Copyright (C) 2019 Alex Yatskov <alex@foosoft.net>
|
|
|
|
* 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 {
|
|
|
|
constructor(source='', handlers={}) {
|
|
|
|
this.source = source;
|
|
|
|
this.handlers = handlers;
|
|
|
|
|
|
|
|
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-08-17 22:50:48 +00:00
|
|
|
if (
|
|
|
|
target !== this.source ||
|
2019-11-25 19:19:18 +00:00
|
|
|
!hasOwn(this.handlers, action)
|
2019-08-17 22:50:48 +00:00
|
|
|
) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2019-08-19 00:51:19 +00:00
|
|
|
this.sendAck(port, id, senderId);
|
2019-08-17 22:50:48 +00:00
|
|
|
|
|
|
|
const handler = this.handlers[action];
|
|
|
|
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
|
|
|
}
|
|
|
|
}
|