coolink-ts
Version:
Coocaa Coolink APP JavaScript library base on Thresh-lib.
74 lines (59 loc) • 2.32 kB
text/typescript
import coolink from '../coolink/api'
import {addLinkingMsgCallback, deleteLinkingMsgCallback} from './messageProcess'
import cooInfo, { isTv as isTvFunc } from '../shared/cooInfo';
export default class LinkedController
{
private commKey: string;
public state : any;
public linkCommandCallback : Function = null;
public onState: Function = null;
public static Create(key: string): LinkedController {
let thiz = new LinkedController(key);
addLinkingMsgCallback(key, thiz.onMessage.bind(thiz));
return thiz;
}
private constructor(key: string) {
this.commKey = key;
this.linkCommandCallback = null;
}
public disableLinking() : void {
deleteLinkingMsgCallback(this.commKey);
}
public isTv() {
return isTvFunc();
}
public sendLinkCommand(obj: any) {
let newObj = {...obj, mapToLinkingWidget: this.commKey };
let random1: string = (parseInt((Math.random() * 10000000).toString())).toString();
let random2: string = (parseInt((Math.random() * 10000000).toString())).toString();
let random3: string = (parseInt((Math.random() * 10000000).toString())).toString();
let random4: string = (parseInt((Math.random() * 10000000).toString())).toString();
coolink.protocol.sendMessage({
"id": random1 + random2 + random3 + random4,
"content": JSON.stringify(newObj),
"appTargetID": cooInfo.infos.miniAppCode,
"appSourceID": cooInfo.infos.miniAppCode,
"type": "TEXT",
"extra": {},
"reply": false,
"broadcast": this.isTv() ? true : false
} as any);
}
public setLinkCommandCallback(cb: Function) {
this.linkCommandCallback = cb;
}
private onMessage(msg: any, rawMsg: any) {
if (msg && msg?.cmd && msg.cmd == 'set_remote_state') {
if (this.onState && msg?.value) {
this.onState(msg.value);
}
} else {
if (this.linkCommandCallback) {
this.linkCommandCallback(msg, rawMsg);
}
}
}
public setOnStateCallback(cb: Function) {
this.onState = cb;
}
}