import { Realtime } from 'ably' import EventEmitter from 'eventemitter3' type ConnectionState = 'initialized' | 'connecting' | 'connected' | 'disconnected' | 'suspended' | 'closing' | 'closed' | 'failed' const AblyConnectionState: {[key: string]: ConnectionState} = { initialized: "initialized", // Not yet started to connect connecting: "connecting", // Connecting connected: "connected", // Connected disconnected: "disconnected", // Temporary disconnect. Will retry suspended: "suspended", // No connection for 2 min. Will still retry every 30 sec closing: "closing", // Starting to close, initiated by us closed: "closed", // Manually closed by us failed: "failed", // Permanent failure. No reconnects } type Events = 'connection-failed' | 'login' | 'logout' | 'change' const environment: Record = window && window['__env__'] && typeof window['__env__'] == 'object' ? window['__env__'] : {} export class AuthChangeNotifier extends EventEmitter{ private _ably: Realtime private _enabled = true constructor(){ super() const authUrl = `https://${environment['ably.api'] ?? 'ably.api.24sevenoffice.com'}/auth` this._ably = new Realtime({ authUrl, authHeaders: {authorization: 'IGNORED'}, autoConnect: false }) this._ably.connection.on(AblyConnectionState.initialized, () => {}) this._ably.connection.on(AblyConnectionState.connecting, () => {}) this._ably.connection.on(AblyConnectionState.connected, () => {}) this._ably.connection.on(AblyConnectionState.disconnected, () => {}) this._ably.connection.on(AblyConnectionState.suspended, () => {}) this._ably.connection.on(AblyConnectionState.closing, () => {}) this._ably.connection.on(AblyConnectionState.closed, () => {}) this._ably.connection.on(AblyConnectionState.failed, () => this.emit('connection-failed')) } enable() { this._enabled = true } disable() { this._enabled = false } listen(license: string){ this._ably.close() this._ably.connect() const identityId = license.split(';')[0] const channel = this._ably.channels.get(`identity:${identityId}`) channel.subscribe('authentication', event => { const type = event.data.type const license = event.data.license if(!this._enabled) return switch (type) { case 'login': case 'logout': this.emit(type) break case 'change': this.emit(type, license) break; } }) } }