connection.ts (2355B)
1 import { WeeChatProtocol } from './parser'; 2 import { transformToReduxAction } from './action_transformer'; 3 4 const protocol = new WeeChatProtocol(); 5 6 export default class WeechatConnection { 7 dispatch: any; 8 hostname: string; 9 password: string; 10 ssl: boolean; 11 compressed: boolean; 12 websocket: WebSocket; 13 onSuccess: (conn: WeechatConnection) => void; 14 onError: (reconnect: boolean) => void; 15 connected: boolean; 16 reconnect: boolean; 17 18 constructor(dispatch) { 19 this.dispatch = dispatch; 20 this.websocket = null; 21 this.reconnect = this.connected = false; 22 } 23 24 connect( 25 host: string, 26 password = '', 27 ssl: boolean, 28 onSuccess: (conn: WeechatConnection) => void, 29 onError: (reconnect: boolean) => void 30 ): void { 31 this.hostname = host; 32 this.password = password; 33 this.ssl = ssl; 34 this.onSuccess = onSuccess; 35 this.onError = onError; 36 37 this.openSocket(); 38 } 39 40 openSocket(): void { 41 this.websocket = new WebSocket( 42 `${this.ssl ? 'wss' : 'ws'}://${this.hostname}/weechat` 43 ); 44 45 this.websocket.onopen = () => this.onopen(); 46 this.websocket.onmessage = (event) => this.onmessage(event); 47 this.websocket.onerror = (event) => this.handleError(event); 48 this.websocket.onclose = () => this.close(); 49 } 50 51 onopen(): void { 52 this.send( 53 `init password=${this.password},compression=${ 54 this.compressed ? 'zlib' : 'off' 55 }\n` 56 ); 57 this.send('(version) info version'); 58 this.connected = true; 59 this.onSuccess(this); 60 } 61 62 handleError(event: Event): void { 63 console.log(event); 64 this.reconnect = this.connected; 65 this.onError(this.reconnect); 66 } 67 68 close(): void { 69 this.connected = false; 70 this.send('quit'); 71 this.websocket.close(); 72 this.dispatch({ 73 type: 'DISCONNECT' 74 }); 75 76 if (this.reconnect) { 77 this.reconnect = false; 78 this.openSocket(); 79 } 80 } 81 82 onmessage(event: WebSocketMessageEvent): void { 83 const parsed = protocol.parse(event.data) as WeechatResponse<any>; 84 85 console.log('Parsed data:', parsed); 86 try { 87 const action = transformToReduxAction(parsed); 88 if (action) { 89 this.dispatch(action); 90 } 91 } catch (e) { 92 console.log(e, parsed); 93 } 94 } 95 96 send(data: string): void { 97 console.log('Sending data:', data); 98 this.websocket.send(data + '\n'); 99 } 100 }