-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathindex.js
502 lines (428 loc) · 13.9 KB
/
index.js
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
import repliesCache from '../comment-replies-cache';
import { store } from '../state';
import actions from '../state/actions';
import getAllNotes from '../state/selectors/get-all-notes';
import { fetchNote, listNotes, sendLastSeenTime, subscribeToNoteStream } from './wpcom';
const debug = require( 'debug' )( 'notifications:rest-client' );
const settings = {
max_refresh_ms: 180000,
refresh_ms: 30000,
initial_limit: 10,
increment_limit: 10,
max_limit: 100,
};
export function Client() {
this.noteList = [];
this.gettingNotes = false;
this.timeout = false;
this.isVisible = false;
this.isShowing = false;
this.lastSeenTime = 0;
this.noteRequestLimit = settings.initial_limit;
this.retries = 0;
this.subscribeTry = 0;
this.subscribeTries = 3;
this.subscribing = false;
this.subscribed = false;
this.firstRender = true;
this.locale = null;
this.inbox = [];
window.addEventListener( 'storage', handleStorageEvent.bind( this ) );
this.main( this );
}
function main() {
// subscribe if possible
if ( ! this.subscribed && ! this.subscribing ) {
if ( this.subscribeTry < this.subscribeTries ) {
debug( 'main: trying to subscribe' );
this.subscribing = true;
subscribeToNoteStream( pinghubCallback.bind( this ) );
} else if ( this.subscribeTry === this.subscribeTries ) {
const sub_retry_ms = 120000;
debug( 'main: polling until next subscribe attempt', 'sub_retry_ms =', sub_retry_ms );
setTimeout( () => {
this.subscribeTry = 0;
}, sub_retry_ms );
}
this.subscribeTry++;
}
// subscribers call main() when the subscription delivers a message
const notes = getAllNotes( store.getState() );
if ( notes.length && this.subscribed && ! this.inbox.length ) {
return debug( 'main: subscribed, no new messages; sleeping' );
}
// schedule the next call to main()
this.reschedule();
// nobody's looking. take a nap until they return.
if ( ! this.isVisible ) {
return debug( 'main: not visible. sleeping.' );
}
if ( this.inbox.length === 1 && this.inbox[ 0 ].action && this.inbox[ 0 ].action === 'push' ) {
const note_id = this.inbox[ 0 ].note_id;
debug( 'main: have one push message with note_id, calling getNote(%d)', note_id, this.inbox );
this.inbox = [];
this.getNote( note_id );
} else if ( this.inbox.length ) {
debug( 'main: have messages, calling getNotes', this.inbox );
this.inbox = [];
this.getNotes();
} else if ( ! notes.length ) {
debug( 'main: no notes in local cache, calling getNotes' );
this.getNotes();
} else {
debug( 'main: polling, have notes in local cache, calling getNotesList' );
this.getNotesList();
}
}
function reschedule( refresh_ms ) {
if ( ! refresh_ms ) {
refresh_ms = settings.refresh_ms;
}
if ( this.timeout ) {
clearTimeout( this.timeout );
this.timeout = false;
}
if ( this.subscribed ) {
debug( 'reschedule', 'subscribed; not polling' );
} else {
debug( 'reschedule', 'refresh_ms =', refresh_ms );
this.timeout = setTimeout( main.bind( this ), refresh_ms );
}
}
function pinghubCallback( err, event ) {
const responseType = event?.response?.type;
this.subscribing = false;
// WebSocket error: costs one try
if ( err || ! responseType || responseType === 'error' ) {
debug( 'pinghubCallback: error', 'err =', err );
this.subscribed = false;
} else if ( responseType === 'open' ) {
// WebSocket connected: stop polling
debug( 'pinghubCallback: connected', event.response );
this.subscribeTry = 0;
this.subscribed = true;
} else if ( responseType === 'close' ) {
// WebSocket disconnected: have another try
debug( 'pinghubCallback: disconnected', event.response );
this.subscribeTry = 0;
this.subscribed = false;
} else if ( responseType === 'message' ) {
// WebSocket message: add to inbox, call main() to trigger API call
let message = true;
try {
message = JSON.parse( event?.response?.data );
} catch ( e ) {}
this.inbox.push( message );
debug( 'pinghubCallback: received message', event.response, 'this.inbox =', this.inbox );
this.main();
} else {
// Missed case?
debug( 'pinghubCallback: unknown event.response.type', event.response );
throw new Error(
'notifications:rest-client:pinghubCallback unknown event.response.type: ' + responseType
);
}
this.reschedule();
}
function getNote( note_id ) {
// initialize the list if it's empty
if ( this.noteList.length === 0 ) {
this.getNotes();
}
const parameters = {
fields: 'id,type,unread,body,subject,timestamp,meta,note_hash',
};
fetchNote( note_id, parameters, ( error, data ) => {
if ( error ) {
return;
}
store.dispatch( actions.notes.addNotes( data.notes ) );
ready.call( this );
} );
}
function getNotes() {
if ( this.gettingNotes ) {
return;
}
this.gettingNotes = true;
const parameters = {
fields: 'id,type,unread,body,subject,timestamp,meta,note_hash',
number: this.noteRequestLimit,
locale: this.locale,
};
const notes = getAllNotes( store.getState() );
if ( ! notes.length || this.noteRequestLimit > notes.length ) {
store.dispatch( actions.ui.loadNotes() );
}
listNotes( parameters, ( error, data ) => {
this.gettingNotes = false;
if ( error ) {
/*
* Something failed, so try again and
* reset the local noteList copy. We
* might have optimistically modified
* it when we last compared it to the
* server, but there's been a failure
* here so resetting it will force a
* full refresh.
*/
this.retries = this.retries + 1;
const backoff_ms = Math.min(
settings.refresh_ms * ( this.retries + 1 ),
settings.max_refresh_ms
);
debug( 'getNotes error, using backoff_ms=%d', backoff_ms );
this.noteList = [];
this.reschedule( backoff_ms );
return;
}
store.dispatch( actions.ui.loadedNotes() );
const oldNotes = getAllNotes( store.getState() ).map( ( { id } ) => id );
const newNotes = data.notes.map( ( n ) => n.id );
const notesToRemove = oldNotes.filter( ( old ) => ! newNotes.includes( old ) );
notesToRemove.length && store.dispatch( actions.notes.removeNotes( notesToRemove ) );
store.dispatch( actions.notes.addNotes( data.notes ) );
// Store id/hash pairs for now until properly reduxified
// this is used as a network optimization to quickly determine
// changes without downloading all the data
this.noteList = data.notes.map( ( { id, note_hash } ) => ( { id, note_hash } ) );
this.updateLastSeenTime( Number( data.last_seen_time ) );
if ( parameters.number === settings.max_limit ) {
/*
* Since we store note data in a local cache,
* we want to purge the data if the notes
* no longer exist, but we only want to do it
* if we have loaded all the notes, otherwise
* we might expunge legitimate entries that
* simply haven't been loaded yet.
*/
cleanupLocalCache.call( this );
}
this.retries = 0;
ready.call( this );
} );
}
function getNotesList() {
const notes = getAllNotes( store.getState() );
// make sure we have some notes before we run this
if ( ! notes.length ) {
return;
}
if ( this.gettingNotes ) {
return;
}
this.gettingNotes = true;
const parameters = {
fields: 'id,note_hash',
number: this.noteRequestLimit,
};
listNotes( parameters, ( error, data ) => {
debug( 'getNotesList callback:', error, data );
this.gettingNotes = false;
if ( error ) {
this.retries = this.retries + 1;
const backoff_ms = Math.min(
settings.refresh_ms * ( this.retries + 1 ),
settings.max_refresh_ms
);
debug( 'getNotesList error, using backoff_ms=%d', backoff_ms );
return this.reschedule( backoff_ms );
}
this.retries = 0;
/* Compare list of notes from server to local copy */
const [ localIds, localHashes ] = [
this.noteList.map( ( note ) => note.id ),
this.noteList.map( ( note ) => note.note_hash ),
];
const [ serverIds, serverHashes ] = [
data.notes.map( ( note ) => note.id ),
data.notes.map( ( note ) => note.note_hash ),
];
const serverHasChanges =
serverIds.some( ( sId ) => ! localIds.includes( sId ) ) ||
serverHashes.some( ( sHash ) => ! localHashes.includes( sHash ) );
/* Actually remove the notes from the local copy */
const notesToRemove = localIds.filter( ( local ) => ! serverIds.includes( local ) );
if ( notesToRemove.length ) {
store.dispatch( actions.notes.removeNotes( notesToRemove ) );
}
/* Update our local copy of the note list */
this.noteList = data.notes;
this.updateLastSeenTime( Number( data.last_seen_time ) );
// Clean out stored reply texts that are older than a day
repliesCache.cleanup();
/* Grab updates/changes from server if they exist */
return serverHasChanges ? this.getNotes() : ready.call( this );
} );
}
/**
* Reports new notification data if available
*
* New notification data is available _if_ we
* have a note with a timestamp newer than we
* did the last time we called this function.
*/
function ready() {
const notes = getAllNotes( store.getState() );
let newNotes = notes.filter(
( note ) => Date.parse( note.timestamp ) / 1000 > this.lastSeenTime
);
let newNoteCount = newNotes.length;
if ( ! this.firstRender && this.lastSeenTime === 0 ) {
newNoteCount = 0;
newNotes = [];
}
const latestType = notes.slice( -1 )[ 0 ]?.type ?? null;
store.dispatch( { type: 'APP_RENDER_NOTES', newNoteCount, latestType } );
this.firstRender = false;
}
/** @type {RegExp} matches keys which may no longer need to exist */
const obsoleteKeyPattern = /^(note_read_status|reply)_(\d+)/;
const safelyRemoveKey = ( key ) => {
try {
localStorage.removeItem( key );
} catch ( e ) {}
};
function cleanupLocalCache() {
const notes = getAllNotes( store.getState() );
const currentNoteIds = notes.map( ( n ) => n.id );
Object.keys( localStorage )
.map( ( key ) => obsoleteKeyPattern.exec( key ) )
.filter( ( match ) => match && ! currentNoteIds.includes( match[ 1 ] ) )
.forEach( safelyRemoveKey );
}
/**
* Update lastSeenTime in object instance, localStorage, and remote database.
* Advance this.lastSeenTime to proposedTime or the latest visible note time.
* If the timestamp comes from a note, update the remote database.
* @param {number} proposedTime A proposed update to our lastSeenTime timestamp
* @param {boolean} fromStorage Whether this call is from handleStorageEvent
* @returns {boolean} whether or not we will update our lastSeenTime value
*/
function updateLastSeenTime( proposedTime, fromStorage ) {
let fromNote = false;
let mostRecentNoteTime = 0;
// Make sure we aren't getting milliseconds
// The check time is Aug 8, 2005 in ms
if ( proposedTime > 1123473600000 ) {
proposedTime = proposedTime / 1000;
}
debug( 'updateLastSeenTime 0', {
proposedTime: proposedTime,
fromStorage: fromStorage,
lastSeenTime: this.lastSeenTime,
} );
// Event was triggered by another tab's localStorage.setItem; ignore localStorage and remote.
if ( fromStorage ) {
if ( proposedTime <= this.lastSeenTime ) {
return false;
}
this.lastSeenTime = proposedTime;
return true;
}
const notes = getAllNotes( store.getState() );
if ( notes.length ) {
mostRecentNoteTime = Date.parse( notes[ 0 ].timestamp ) / 1000;
}
debug( 'updateLastSeenTime 1', {
proposedTime: proposedTime,
showing: this.isShowing,
visible: this.isVisible,
lastSeenTime: this.lastSeenTime,
mostRecentNoteTime: mostRecentNoteTime,
} );
// Advance proposedTime to the latest visible note time.
if ( this.isShowing && this.isVisible && mostRecentNoteTime > proposedTime ) {
proposedTime = mostRecentNoteTime;
fromNote = true;
}
debug( 'updateLastSeenTime 2', {
proposedTime: proposedTime,
fromNote: fromNote,
oldNews: proposedTime <= this.lastSeenTime,
} );
// Ignore old news.
if ( proposedTime <= this.lastSeenTime ) {
return false;
}
this.lastSeenTime = proposedTime;
try {
localStorage.setItem( 'notesLastMarkedSeen', this.lastSeenTime );
} catch ( e ) {}
// Update the database only if an unseen note has become visible.
if ( fromNote ) {
debug( 'updateLastSeenTime 3', this.lastSeenTime );
sendLastSeenTime( this.lastSeenTime );
}
return true;
}
function refreshNotes() {
if ( this.subscribed ) {
return;
}
debug( 'Refreshing notes...' );
getNotesList.call( this );
}
function handleStorageEvent( event ) {
// Both event and its key property should exist.
if ( ! event?.key ) {
return;
}
if ( event.key === 'notesLastMarkedSeen' ) {
try {
const lastSeenTime = Number( event.newValue );
if ( updateLastSeenTime.call( this, lastSeenTime, true ) ) {
store.dispatch( {
type: 'APP_RENDER_NOTES',
newNoteCount: 0,
} );
}
} catch ( e ) {}
return;
}
if ( 'note_read_status_' === event.key.substring( 0, 17 ) ) {
const noteId = parseInt( event.key.slice( 17 ), 10 );
return store.dispatch( actions.notes.readNote( noteId ) );
}
}
function loadMore() {
const notes = getAllNotes( store.getState() );
if ( ! notes.length || this.noteRequestLimit > notes.length ) {
// we're already attempting to load more notes
return;
}
if ( this.noteRequestLimit >= settings.max_limit ) {
return;
}
this.noteRequestLimit = this.noteRequestLimit + settings.increment_limit;
if ( this.noteRequestLimit > settings.max_limit ) {
this.noteRequestLimit = settings.max_limit;
}
this.getNotes();
}
function setVisibility( { isShowing, isVisible } ) {
if ( this.isShowing === isShowing && this.isVisible === isVisible ) {
return;
}
this.isShowing = isShowing;
this.isVisible = isVisible;
debug( 'Visibility set', {
isShowing: this.isShowing,
isVisible: this.isVisible,
} );
// Fetch notification when visible for the first time or visible and showing
if ( isVisible && ( ! this.lastSeenTime || isShowing ) ) {
this.updateLastSeenTime( 0 );
this.main();
}
}
Client.prototype.main = main;
Client.prototype.reschedule = reschedule;
Client.prototype.getNote = getNote;
Client.prototype.getNotes = getNotes;
Client.prototype.getNotesList = getNotesList;
Client.prototype.updateLastSeenTime = updateLastSeenTime;
Client.prototype.loadMore = loadMore;
Client.prototype.refreshNotes = refreshNotes;
Client.prototype.setVisibility = setVisibility;
export default Client;