-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmessage.ts
More file actions
59 lines (54 loc) · 2.08 KB
/
message.ts
File metadata and controls
59 lines (54 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { Event, Message, getBrowserInstance, getFromStorage, isQueueMessage, parseTypeObject, replyMessage } from '../../helpers/sharedExt';
import { Queue } from '../queue';
type Msg = { type: string, name?: string, [key: string]: any; };
/**
* handle postMessage event
* @returns `true` if event handeled, else parsed message
*/
export const handle = (e: MessageEvent) => {
if (!e.origin.match(/^https?:\/\/(?:.+\.)?nebula\.(?:app|tv)$/))
return true;
const msg = parseTypeObject<Msg>(e.data, true);
if (msg === null)
return true; // ignore invalid messages
if (msg.type.startsWith('enhancer-message-') || msg.type.startsWith('enhancer-event-'))
return true; // ignore replies and events
console.dev.debug('Handling message', msg);
if (isQueueMessage(msg.type))
return Queue.get().handleMessage(e, msg), true;
let promise: Promise<any>;
switch (msg.type) {
case Message.GET_STORAGE:
promise = getFromStorage(msg.get);
break;
case Message.GET_MESSAGE:
promise = Promise.resolve(getBrowserInstance().i18n.getMessage(msg.message));
break;
case Message.GET_QSTATUS:
promise = Promise.resolve({
canNext: Queue.get().canGoNext(),
canPrev: Queue.get().canGoPrev(),
position: Queue.get().position,
length: Queue.get().length,
});
break;
case Message.REGISTER_LISTENER:
registerListener(e, msg);
return true;
default:
return msg;
}
// use raw promises here because we don't care about the return value, let the rest of the handler continue
promise.then(val => replyMessage(e, msg.name, val, null)).catch(err => replyMessage(e, msg.name, null, err));
return true;
};
const registerListener = (e: MessageEvent, msg: Msg) => {
switch (msg.event) {
case Event.QUEUE_CHANGE:
Queue.get().onChange(() => replyMessage(e, msg.name, { canNext: Queue.get().canGoNext(), canPrev: Queue.get().canGoPrev() }));
break;
case Event.STORAGE_CHANGE:
getBrowserInstance().storage.onChanged.addListener((...args) => replyMessage(e, msg.name, args));
break;
}
};