1
+ import { WebSocketConnection } from "../../database/realtime/WebSocketConnection" ;
2
+ import { Client as WebSocketImpl } from "faye-websocket" ;
3
+ import { PersistentStorage } from '../../database/core/storage/storage' ;
4
+ import { CONSTANTS as ENV_CONSTANTS } from "../../utils/constants" ;
5
+ import { CONSTANTS } from "../../database/realtime/Constants" ;
6
+ import firebase from "../../app" ;
7
+
8
+ /**
9
+ * @param onMessage Callback when messages arrive
10
+ * @param onDisconnect Callback with connection lost.
11
+ */
12
+ WebSocketConnection . prototype . open = function ( onMessage : ( msg : Object ) => any , onDisconnect : ( ) => any ) {
13
+ this . onDisconnect = onDisconnect ;
14
+ this . onMessage = onMessage ;
15
+
16
+ this . log_ ( 'Websocket connecting to ' + this . connURL ) ;
17
+
18
+ this . everConnected_ = false ;
19
+ // Assume failure until proven otherwise.
20
+ PersistentStorage . set ( 'previous_websocket_failure' , true ) ;
21
+
22
+ try {
23
+ const device = ENV_CONSTANTS . NODE_ADMIN ? 'AdminNode' : 'Node' ;
24
+ // UA Format: Firebase/<wire_protocol>/<sdk_version>/<platform>/<device>
25
+ const options = {
26
+ 'headers' : {
27
+ 'User-Agent' : `Firebase/${ CONSTANTS . PROTOCOL_VERSION } /${ firebase . SDK_VERSION } /${ process . platform } /${ device } `
28
+ } } ;
29
+
30
+ // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.
31
+ const env = process [ 'env' ] ;
32
+ const proxy = ( this . connURL . indexOf ( "wss://" ) == 0 )
33
+ ? ( env [ 'HTTPS_PROXY' ] || env [ 'https_proxy' ] )
34
+ : ( env [ 'HTTP_PROXY' ] || env [ 'http_proxy' ] ) ;
35
+
36
+ if ( proxy ) {
37
+ options [ 'proxy' ] = { origin : proxy } ;
38
+ }
39
+
40
+ this . mySock = new WebSocketImpl ( this . connURL , [ ] , options ) ;
41
+ } catch ( e ) {
42
+ this . log_ ( 'Error instantiating WebSocket.' ) ;
43
+ const error = e . message || e . data ;
44
+ if ( error ) {
45
+ this . log_ ( error ) ;
46
+ }
47
+ this . onClosed_ ( ) ;
48
+ return ;
49
+ }
50
+
51
+ this . mySock . onopen = ( ) => {
52
+ this . log_ ( 'Websocket connected.' ) ;
53
+ this . everConnected_ = true ;
54
+ } ;
55
+
56
+ this . mySock . onclose = ( ) => {
57
+ this . log_ ( 'Websocket connection was disconnected.' ) ;
58
+ this . mySock = null ;
59
+ this . onClosed_ ( ) ;
60
+ } ;
61
+
62
+ this . mySock . onmessage = ( m ) => {
63
+ this . handleIncomingFrame ( m ) ;
64
+ } ;
65
+
66
+ this . mySock . onerror = ( e ) => {
67
+ this . log_ ( 'WebSocket error. Closing connection.' ) ;
68
+ const error = e . message || e . data ;
69
+ if ( error ) {
70
+ this . log_ ( error ) ;
71
+ }
72
+ this . onClosed_ ( ) ;
73
+ } ;
74
+ }
0 commit comments