File size: 2,512 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
const EventEmitter = require( 'events' ).EventEmitter;
const WebSocket = require( 'ws' );
const keychain = require( '../../../lib/keychain' );
const log = require( '../../../lib/logger' )( 'desktop:notifications:api' );
const { fetchNote, markReadStatus } = require( './notes' );

/*
 * Module constants
 */
const pingMs = 30000; // Pinghub ping measured at ~27s during testing

class WPNotificationsAPI extends EventEmitter {
	constructor() {
		super();
	}

	heartbeat() {
		clearTimeout( this.pingTimeout );

		this.pingTimeout = setTimeout( () => {
			log.info( 'Websocket heartbeat timed out, attempting to reconnect...' );
			this.ws.terminate();
			this.connect();
			// heartbeat timeout: server ping interval + conservative assumption of latency.
		}, pingMs + 1000 );
	}

	async connect( cookie ) {
		// If a cookie value was not explicitly passed in, let's try to fetch it from the keychain
		if ( ! cookie ) {
			cookie = await keychain.read( 'wp_api_sec' );
		}

		if ( ! cookie ) {
			log.info( 'Failed to initialize websocket: missing wp_api_sec cookie' );
			this.ws = null;
			return;
		}

		this.ws = new WebSocket(
			'https://public-api.wordpress.com/pinghub/wpcom/me/newest-note-data',
			[],
			{
				headers: {
					Origin: `https://public-api.wordpress.com`,
					Cookie: `wp_api_sec=${ cookie }`,
				},
			}
		);

		this.ws.on( 'open', () => {
			log.info( 'Websocket connected' );
			this.heartbeat();
		} );

		this.ws.on( 'ping', () => {
			log.debug( 'Websocket ping' );
			this.heartbeat();
		} );

		this.ws.on( 'close', () => {
			log.info( 'Websocket disconnected' );
			clearTimeout( this.pingTimeout );
		} );

		this.ws.on( 'error', ( error ) => {
			log.info( 'Websocket error: ', error );
		} );

		this.ws.on( 'message', async ( message ) => {
			const json = JSON.parse( message );
			log.debug( 'Received message: ', json );

			const { note_id: noteId } = json;
			if ( ! noteId ) {
				return;
			}

			try {
				const note = await fetchNote( noteId );
				log.debug( 'Parsed note: ', note );
				this.emit( 'note', note );
			} catch ( e ) {
				log.error( `Failed to fetch note with id: ${ noteId }: `, e );
			}
		} );
	}

	async markNoteAsRead( noteId, callback ) {
		try {
			await markReadStatus( noteId, true );
			if ( callback ) {
				callback();
			}
		} catch ( e ) {
			log.error( 'Failed to mark note as read:', e );
		}
	}

	disconnect() {
		if ( this.ws ) {
			this.ws.terminate();
			this.ws = null;
		}
	}
}

module.exports = new WPNotificationsAPI();