Files
battle-caster-v1/src/model/Remote/Channels/ChromcastSummon.ts
2024-11-24 18:03:06 +00:00

63 lines
1.9 KiB
TypeScript

import { loadScript } from "../../../helpers/loadScript";
import { JsonChannelSummon, Message, MessageEmitter } from "./type";
// @ts-ignore
import type {CastReceiverContext, CastReceiverOptions} from '@types/chromecast-caf-receiver/cast.framework';
const CHANNEL = 'urn:x-cast:eu.fisoft.battlecaster.custom';
export class ChromecastChannelSummon extends MessageEmitter implements JsonChannelSummon {
constructor() {
super();
}
log(...data: any[]) {
// @ts-ignore
this.emit({ type: 'log', data: data });
}
async initialize() {
this.log('loading cast_receiver_framework.js');
await loadScript('//www.gstatic.com/cast/sdk/libs/caf_receiver/v3/cast_receiver_framework.js')
this.initializeCastApi();
}
initializeCastApi() {
this.log('initializeCastApi');
// @ts-ignore
const context: CastReceiverContext = cast.framework.CastReceiverContext.getInstance();
// @ts-ignore
const options: CastReceiverOptions = new cast.framework.CastReceiverOptions();
context.addCustomMessageListener(CHANNEL, async (event: any) => {
try {
this.log('Message received', event.senderId, event.data);
const msg = event.data;
if (msg.type === 'hello') {
this.log('Chromecast summoned', event.senderId);
this.send({type: 'summoned', name: msg.name ?? 'Chromecast'});
}
this.emit(msg);
} catch (err) {
this.log('error', err);
}
});
options.customNamespaces = {
// @ts-ignore
[CHANNEL]: cast.framework.system.MessageType.JSON,
}
options.disableIdleTimeout = true;
options.maxInactivity = 3600; // Development only
context.start(options);
}
send(data: Message): void {
try {
// @ts-ignore
const context: CastReceiverContext = cast.framework.CastReceiverContext.getInstance()
context.sendCustomMessage(CHANNEL, undefined, data);
} catch (err) {
this.log('send error', err);
}
}
}