import { WatcherProxy, WebsocketPayload } from "../interfaces/watcher-proxy.i"; import { Observable, Observer, of, Subject } from "rxjs"; // import { createWebsocket } from "./rxjs-websocket"; import { switchMap, shareReplay, tap, take } from "rxjs/operators"; import WebSocketManagement from 'wsmanagement'; /** * @description * Connect to the augmented node using websocket * This class manage websocket reconnection and also manage the clientID used to identify the channel on the backend */ export class StandardWatcherProxy implements WatcherProxy { private WSM = (Observable.create(async (observer: Observer) => { const id = await this.clientID(); const WSM = new WebSocketManagement(this.url, this.apiKey, id); WSM.connectAugmentedNodeWS((data) => this.WSMMessages.next(data)) const int = setInterval(() => { if ((WSM as any).wsan.readyState === 1) { clearInterval(int) observer.next(WSM); } }, 1000) })).pipe(shareReplay()) as Observable private WSMMessages = new Subject(); constructor( private url: string = "ws://206.189.191.247:7999/BTCnet/ws-validator", private apiKey: string, private clientID: () => Promise = () => Promise.resolve('07069ecd-8969-40fb-82fd-5cd735aa9095')) { } unwatch(transactionId: string, address: string, network: string, nbConf: number): Observable { this.WSM.pipe( tap((wsm: WebSocketManagement) => { wsm.sendActionToAugmentedNode({ transactionID: transactionId, destinationAddress: '', sourceAddress: address, onlyReqConf: false, }, { network: nbConf } as any, network as any, '' as any, 'unsubscribe', true, false, ) }), take(1), ).subscribe(); return of(); } watch(transactionId: string, address: string, network: string, nbConf: number): Observable { return this.WSM.pipe(switchMap((wsm: WebSocketManagement) => { wsm.sendActionToAugmentedNode({ transactionID: transactionId, destinationAddress: '', sourceAddress: address, onlyReqConf: false, }, { [network]: nbConf } as any, network as any, '' as any, 'subscribe', true, false, ) return this.WSMMessages as any as Observable })) } }