summaryrefslogtreecommitdiff
blob: 5f857edb95b96c28c688b8ca8d6c2e9c83ad0790 (plain)
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
( function ( mw, $ ) {
	/* global moment:false */
	/**
	 * Controller for Echo notifications
	 *
	 * @param {mw.echo.api.EchoApi} echoApi Echo API
	 * @param {mw.echo.dm.ModelManager} manager Model manager
	 */
	mw.echo.Controller = function MwEchoController( echoApi, manager ) {
		this.api = echoApi;
		this.manager = manager;
	};

	/* Initialization */

	OO.initClass( mw.echo.Controller );

	/**
	 * Update a filter value.
	 * The method accepts a filter name and as many arguments
	 * as needed.
	 *
	 * @param {string} filter Filter name
	 */
	mw.echo.Controller.prototype.setFilter = function ( filter ) {
		var filtersModel = this.manager.getFiltersModel(),
			values = Array.prototype.slice.call( arguments );

		values.shift();

		if ( filter === 'readState' ) {
			filtersModel.setReadState( values[ 0 ] );
		} else if ( filter === 'sourcePage' ) {
			filtersModel.setCurrentSourcePage( values[ 0 ], values[ 1 ] );
			this.manager.getLocalCounter().setSource( filtersModel.getSourcePagesModel().getCurrentSource() );
		}

		// Reset pagination
		this.manager.getPaginationModel().reset();
	};

	/**
	 * Fetch the next page by date
	 *
	 * @return {jQuery.Promise} A promise that resolves with an object where the keys are
	 *  days and the items are item IDs.
	 */
	mw.echo.Controller.prototype.fetchNextPageByDate = function () {
		this.manager.getPaginationModel().forwards();
		return this.fetchLocalNotificationsByDate();
	};

	/**
	 * Fetch the previous page by date
	 *
	 * @return {jQuery.Promise} A promise that resolves with an object where the keys are
	 *  days and the items are item IDs.
	 */
	mw.echo.Controller.prototype.fetchPrevPageByDate = function () {
		this.manager.getPaginationModel().backwards();
		return this.fetchLocalNotificationsByDate();
	};

	/**
	 * Fetch the first page by date
	 *
	 * @return {jQuery.Promise} A promise that resolves with an object where the keys are
	 *  days and the items are item IDs.
	 */
	mw.echo.Controller.prototype.fetchFirstPageByDate = function () {
		this.manager.getPaginationModel().setCurrPageIndex( 0 );
		return this.fetchLocalNotificationsByDate();
	};

	/**
	 * Fetch unread pages in all wikis and create foreign API sources
	 * as needed.
	 *
	 * @return {jQuery.Promise} A promise that resolves when the page filter
	 *  model is updated with the unread notification count per page per wiki
	 */
	mw.echo.Controller.prototype.fetchUnreadPagesByWiki = function () {
		var controller = this,
			filterModel = this.manager.getFiltersModel(),
			sourcePageModel = filterModel.getSourcePagesModel();

		return this.api.fetchUnreadNotificationPages()
			.then( function ( data ) {
				var source,
					result = {},
					foreignSources = {};

				for ( source in data ) {
					if ( source !== mw.config.get( 'wgDBname' ) ) {
						// Collect sources for API
						foreignSources[ source ] = data[ source ].source;
					}
					result[ source === mw.config.get( 'wgDBname' ) ? 'local' : source ] = data[ source ];
				}

				// Register the foreign sources in the API
				controller.api.registerForeignSources( foreignSources, false );

				// Register pages
				sourcePageModel.setAllSources( result );
			} );
	};

	/**
	 * Fetch notifications from the local API and sort them by date.
	 * This method ignores cross-wiki notifications and bundles.
	 *
	 * @param {number} [page] Page number. If not given, it defaults to the current
	 *  page.
	 * @return {jQuery.Promise} A promise that resolves with an object where the keys are
	 *  days and the items are item IDs.
	 */
	mw.echo.Controller.prototype.fetchLocalNotificationsByDate = function ( page ) {
		var controller = this,
			pagination = this.manager.getPaginationModel(),
			filters = this.manager.getFiltersModel(),
			currentSource = filters.getSourcePagesModel().getCurrentSource(),
			continueValue = pagination.getPageContinue( page || pagination.getCurrPageIndex() );

		pagination.setItemsPerPage( this.api.getLimit() );

		return this.api.fetchFilteredNotifications(
			this.manager.getTypeString(),
			currentSource,
			{
				'continue': continueValue,
				readState: filters.getReadState(),
				titles: filters.getSourcePagesModel().getGroupedPagesForCurrentTitle()
			}
		)
			.then( function ( data ) {
				var i, notifData, newNotifData, localizedDate, date, itemModel, symbolicName,
					maxSeenTime,
					dateItemIds = {},
					dateItems = {},
					models = {};

				data = data || { list: [] };

				// Go over the data
				for ( i = 0; i < data.list.length; i++ ) {
					notifData = data.list[ i ];

					// Set source's seenTime
					// TODO: This query brings up mixed alert and message notifications.
					// Regularly, each of those will have a different seenTime that is
					// calculated for each badge, but for this page, both are fetched.
					// For the moment, we are picking the max seenTime from
					// either alert or notice and updating both, since the page gives
					// us a mixed view which will update both seenTime to be the same
					// anyways.
					maxSeenTime = data.seenTime.alert < data.seenTime.notice ?
						data.seenTime.notice : data.seenTime.alert;
					controller.manager.getSeenTimeModel().setSeenTime(
						maxSeenTime
					);

					// Collect common data
					newNotifData = controller.createNotificationData( notifData );
					if ( notifData.type !== 'foreign' ) {
						localizedDate = moment.utc( newNotifData.timestamp ).local().format( 'YYYYMMDD' );

						newNotifData.modelName = 'local_' + localizedDate;
						newNotifData.source = currentSource;

						// Single notifications
						itemModel = new mw.echo.dm.NotificationItem(
							notifData.id,
							newNotifData
						);

						dateItems[ localizedDate ] = dateItems[ localizedDate ] || [];
						dateItems[ localizedDate ].push( itemModel );

						dateItemIds[ localizedDate ] = dateItemIds[ localizedDate ] || [];
						dateItemIds[ localizedDate ].push( notifData.id );
					}
				}

				// Fill in the models
				for ( date in dateItems ) {
					symbolicName = 'local_' + date;

					// Set up model
					models[ symbolicName ] = new mw.echo.dm.NotificationsList( {
						type: controller.manager.getTypes(),
						name: symbolicName,
						source: currentSource,
						title: date,
						timestamp: date,
						sortingCallback: function ( a, b ) {
							// Reverse sorting. In the special page we want the
							// items sorted only by timestamp, regardless of
							// read/unread state
							if ( b.getTimestamp() < a.getTimestamp() ) {
								return -1;
							} else if ( b.getTimestamp() > a.getTimestamp() ) {
								return 1;
							}

							// Fallback on IDs
							return b.getId() - a.getId();
						}
					} );
					models[ symbolicName ].setItems( dateItems[ date ] );
				}

				// Register local sources
				controller.api.registerLocalSources( Object.keys( models ) );

				// Update the manager
				controller.manager.setNotificationModels( models );

				// Update the pagination
				pagination.setNextPageContinue( data.continue );

				// Update the local counter
				controller.manager.getLocalCounter().update();

				return dateItemIds;
			} )
			.then(
				null,
				function ( errCode, errObj ) {
					return {
						errCode: errCode,
						errInfo: OO.getProp( errObj, 'error', 'info' )
					};
				}
			);
	};
	/**
	 * Fetch notifications from the local API and update the notifications list.
	 *
	 * @param {boolean} [isForced] Force a renewed fetching promise. If set to false, the
	 *  model will request the stored/cached fetching promise from the API. A 'true' value
	 *  will force the API to re-request that information from the server and update the
	 *  notifications.
	 * @return {jQuery.Promise} A promise that resolves with an array of notification IDs
	 */
	mw.echo.Controller.prototype.fetchLocalNotifications = function ( isForced ) {
		var controller = this,
			// Create a new local list model
			localListModel = new mw.echo.dm.NotificationsList( {
				type: this.manager.getTypes()
			} ),
			localItems = [],
			idArray = [];

		this.manager.counter.update();

		// Fetch the notifications from the database
		// Initially, we're going to have to split the operation
		// between local notifications and x-wiki notifications
		// until the backend gives us the x-wiki notifications as
		// part of the original response.
		return this.api.fetchNotifications( this.manager.getTypeString(), 'local', !!isForced, { unreadFirst: true, bundle: true } /* filters */ )
			.then(
				// Success
				function ( data ) {
					var i, notifData, newNotifData,
						foreignListModel, source, itemModel,
						allModels = { local: localListModel },
						createBundledNotification = function ( modelName, rawBundledNotifData ) {
							var bundleNotifData = controller.createNotificationData( rawBundledNotifData );
							bundleNotifData.bundled = true;
							bundleNotifData.modelName = modelName;
							return new mw.echo.dm.NotificationItem(
								rawBundledNotifData.id,
								bundleNotifData
							);
						};

					data = data || { list: [] };

					// Go over the data
					for ( i = 0; i < data.list.length; i++ ) {
						notifData = data.list[ i ];

						// Set source's seenTime
						controller.manager.getSeenTimeModel().setSeenTime(
							controller.getTypes().length > 1 ?
								(
									data.seenTime.alert < data.seenTime.notice ?
										data.seenTime.notice : data.seenTime.alert
								) :
								data.seenTime[ controller.getTypeString() ]
						);

						// Collect common data
						newNotifData = controller.createNotificationData( notifData );
						if ( notifData.type === 'foreign' ) {
							// x-wiki notification multi-group
							// We need to request a new list model
							newNotifData.name = 'xwiki';
							allModels.xwiki = foreignListModel = new mw.echo.dm.CrossWikiNotificationItem( notifData.id, newNotifData );
							foreignListModel.setForeign( true );

							// Register foreign sources
							controller.api.registerForeignSources( notifData.sources, true );
							// Add the lists according to the sources
							for ( source in notifData.sources ) {
								foreignListModel.getList().addGroup(
									source,
									notifData.sources[ source ]
								);
							}

						} else if ( Array.isArray( newNotifData.bundledNotifications ) ) {
							// local bundle
							newNotifData.modelName = 'bundle_' + notifData.id;
							itemModel = new mw.echo.dm.BundleNotificationItem(
								notifData.id,
								newNotifData.bundledNotifications.map( createBundledNotification.bind( null, newNotifData.modelName ) ),
								newNotifData
							);
							allModels[ newNotifData.modelName ] = itemModel;
						} else {
							// Local single notifications
							itemModel = new mw.echo.dm.NotificationItem(
								notifData.id,
								newNotifData
							);

							idArray.push( notifData.id );
							localItems.push( itemModel );

							if ( newNotifData.bundledNotifications ) {
								// This means that bundledNotifications is truthy
								// but is not an array. We should log this in the console
								mw.log.warn(
									'newNotifData.bundledNotifications is expected to be an array,' +
									'but instead received "' + $.type( newNotifData.bundledNotifications ) + '"'
								);
							}
						}

					}

					// Refresh local items
					localListModel.addItems( localItems );

					// Update the controller
					controller.manager.setNotificationModels( allModels );

					return idArray;
				},
				// Failure
				function ( errCode, errObj ) {
					if ( !controller.manager.getNotificationModel( 'local' ) ) {
						// Update the controller
						controller.manager.setNotificationModels( { local: localListModel } );
					}
					return {
						errCode: errCode,
						errInfo: OO.getProp( errObj, 'error', 'info' )
					};
				}
			);
	};

	/**
	 * Create notification data config object for notification items from the
	 * given API data.
	 *
	 * @param {Object} apiData API data
	 * @return {Object} Notification config data object
	 */
	mw.echo.Controller.prototype.createNotificationData = function ( apiData ) {
		var utcTimestamp, utcIsoMoment,
			content = apiData[ '*' ] || {};

		if ( apiData.timestamp.utciso8601 ) {
			utcTimestamp = apiData.timestamp.utciso8601;
		} else {
			// Temporary until c05133283af0486e08c9a97a468bc075e238f2d2 rolls out to the
			// whole WMF cluster
			utcIsoMoment = moment.utc( apiData.timestamp.utcunix * 1000 );
			utcTimestamp = utcIsoMoment.format( 'YYYY-MM-DD[T]HH:mm:ss[Z]' );
		}

		return {
			type: apiData.section,
			foreign: false,
			source: 'local',
			count: apiData.count,
			read: !!apiData.read,
			seen: (
				!!apiData.read ||
				utcTimestamp <= this.manager.getSeenTime()
			),
			timestamp: utcTimestamp,
			category: apiData.category,
			content: {
				header: content.header,
				compactHeader: content.compactHeader,
				body: content.body
			},
			iconURL: content.iconUrl,
			iconType: content.icon,
			primaryUrl: OO.getProp( content.links, 'primary', 'url' ),
			secondaryUrls: OO.getProp( content.links, 'secondary' ) || [],
			bundledIds: apiData.bundledIds,
			bundledNotifications: apiData.bundledNotifications
		};
	};

	/**
	 * Mark all items within a given list model as read.
	 *
	 * NOTE: This method is strictly for list models, and will not work for
	 * group list models. To mark items as read in the xwiki model, whether
	 * it is pre-populated or not, please see #markEntireCrossWikiItemAsRead
	 *
	 * @param {string} [modelName] Symbolic name for the model
	 * @param {boolean} [isRead=true]
	 * @return {jQuery.Promise} Promise that is resolved when all items
	 *  were marked as read.
	 */
	mw.echo.Controller.prototype.markEntireListModelRead = function ( modelName, isRead ) {
		var i, items, item,
			itemIds = [],
			model = this.manager.getNotificationModel( modelName || 'local' );

		if ( !model ) {
			// Model doesn't exist
			return $.Deferred().reject();
		}

		// Default to true
		isRead = isRead === undefined ? true : isRead;

		items = model.getItems();
		for ( i = 0; i < items.length; i++ ) {
			item = items[ i ];
			if ( item.isRead() !== isRead ) {
				itemIds.push( item.getId() );
			}
		}

		return this.markItemsRead( itemIds, model.getName(), isRead );
	};

	/**
	 * Mark all notifications of a certain source as read, even those that
	 * are not currently displayed.
	 *
	 * @param {string} [source] Notification source. If not given, the currently
	 *  selected source is used.
	 * @return {jQuery.Promise} A promise that is resolved after
	 *  all notifications for the given source were marked as read
	 */
	mw.echo.Controller.prototype.markAllRead = function ( source ) {
		var model,
			controller = this,
			itemIds = [],
			readState = this.manager.getFiltersModel().getReadState(),
			localCounter = this.manager.getLocalCounter();

		source = source || this.manager.getFiltersModel().getSourcePagesModel().getCurrentSource();

		this.manager.getNotificationsBySource( source ).forEach( function ( notification ) {
			if ( !notification.isRead() ) {
				itemIds = itemIds.concat( notification.getAllIds() );
				notification.toggleRead( true );

				if ( readState === 'unread' ) {
					// Remove the items if we are in 'unread' filter state
					model = controller.manager.getNotificationModel( notification.getModelName() );
					model.discardItems( notification );
				}
			}
		} );

		// Update pagination count
		this.manager.updateCurrentPageItemCount();

		localCounter.estimateChange( -itemIds.length );
		return this.api.markAllRead(
			source,
			this.getTypes()
		).then(
			this.refreshUnreadCount.bind( this )
		).then(
			localCounter.update.bind( localCounter, true )
		);
	};

	/**
	 * Mark all local notifications as read
	 *
	 * @return {jQuery.Promise} Promise that is resolved when all
	 *  local notifications have been marked as read.
	 */
	mw.echo.Controller.prototype.markLocalNotificationsRead = function () {
		var modelName, model,
			itemIds = [],
			readState = this.manager.getFiltersModel().getReadState(),
			modelItems = {};

		this.manager.getLocalNotifications().forEach( function ( notification ) {
			if ( !notification.isRead() ) {
				itemIds = itemIds.concat( notification.getAllIds() );
				notification.toggleRead( true );

				modelName = notification.getModelName();
				modelItems[ modelName ] = modelItems[ modelName ] || [];
				modelItems[ modelName ].push( notification );
			}
		} );

		// Remove the items if we are in 'unread' filter state
		if ( readState === 'unread' ) {
			for ( modelName in modelItems ) {
				model = this.manager.getNotificationModel( modelName );
				model.discardItems( modelItems[ modelName ] );
			}
		}

		// Update pagination count
		this.manager.updateCurrentPageItemCount();

		this.manager.getUnreadCounter().estimateChange( -itemIds.length );
		this.manager.getLocalCounter().estimateChange( -itemIds.length );
		return this.api.markItemsRead( itemIds, 'local', true ).then( this.refreshUnreadCount.bind( this ) );
	};

	/**
	 * Fetch notifications from the cross-wiki sources.
	 *
	 * @return {jQuery.Promise} Promise that is resolved when all items
	 *  from the cross-wiki sources are populated into the cross-wiki
	 *  model.
	 */
	mw.echo.Controller.prototype.fetchCrossWikiNotifications = function () {
		var controller = this,
			xwikiModel = this.manager.getNotificationModel( 'xwiki' );

		if ( !xwikiModel ) {
			// There is no xwiki notifications model, so we can't
			// fetch into it
			return $.Deferred().reject().promise();
		}

		return this.api.fetchNotificationGroups( xwikiModel.getSourceNames(), this.manager.getTypeString(), true )
			.then(
				function ( groupList ) {
					var i, notifData, listModel, group, groupItems,
						items = [];

					for ( group in groupList ) {
						listModel = xwikiModel.getItemBySource( group );
						groupItems = groupList[ group ];

						items = [];
						for ( i = 0; i < groupItems.length; i++ ) {
							notifData = controller.createNotificationData( groupItems[ i ] );
							items.push(
								new mw.echo.dm.NotificationItem( groupItems[ i ].id, $.extend( notifData, {
									modelName: 'xwiki',
									source: group,
									bundled: true,
									foreign: true
								} ) )
							);
						}
						// Add items
						listModel.setItems( items );
					}
				},
				function ( errCode, errObj ) {
					return {
						errCode: errCode,
						errInfo: errCode === 'http' ?
							mw.msg( 'echo-api-failure-cross-wiki' ) :
							OO.getProp( errObj, 'error', 'info' )
					};
				}
			);
	};

	/**
	 * Mark local items as read in the API.
	 *
	 * @param {string[]|string} itemIds An array of item IDs, or a single item ID, to mark as read
	 * @param {string} modelName The name of the model that these items belong to
	 * @param {boolean} [isRead=true] The read state of the item; true for marking the
	 *  item as read, false for marking the item as unread
	 * @return {jQuery.Promise} A promise that is resolved when the operation
	 *  is complete, with the number of unread notifications still remaining
	 *  for the set type of this controller, in the given source.
	 */
	mw.echo.Controller.prototype.markItemsRead = function ( itemIds, modelName, isRead ) {
		var items,
			model = this.manager.getNotificationModel( modelName ),
			readState = this.manager.getFiltersModel().getReadState(),
			allIds = [];

		itemIds = Array.isArray( itemIds ) ? itemIds : [ itemIds ];

		// Default to true
		isRead = isRead === undefined ? true : isRead;

		items = model.findByIds( itemIds );

		// If we are only looking at specific read state,
		// then we need to make sure the items are removed
		// from the visible list, because they no longer
		// correspond with the chosen state filter
		if ( readState === 'read' && !isRead ) {
			model.discardItems( items );
		} else if ( readState === 'unread' && isRead ) {
			model.discardItems( items );
			// TODO: We should also find a way to update the pagination
			// here properly. Do we pull more items from the next page
			// when items are cleared? Do we set some threshhold for
			// removed items where if it is reached, we update the list
			// to reflect the new pagination? etc.
		}

		items.forEach( function ( notification ) {
			allIds = allIds.concat( notification.getAllIds() );
			if ( readState === 'all' ) {
				notification.toggleRead( isRead );
			}
		} );

		// Update pagination count
		this.manager.updateCurrentPageItemCount();

		this.manager.getUnreadCounter().estimateChange( isRead ? -allIds.length : allIds.length );
		if ( modelName !== 'xwiki' ) {
			// For the local counter, we should only estimate the change if the items
			// are not cross-wiki
			this.manager.getLocalCounter().estimateChange( isRead ? -allIds.length : allIds.length );
		}

		return this.api.markItemsRead( allIds, model.getSource(), isRead ).then( this.refreshUnreadCount.bind( this ) );
	};

	/**
	 * Mark cross-wiki items as read in the API.
	 *
	 * @param {string[]|string} itemIds An array of item IDs, or a single item ID, to mark as read
	 * @param {string} source The name for the source list that these items belong to
	 * @return {jQuery.Promise} A promise that is resolved when the operation
	 *  is complete, with the number of unread notifications still remaining
	 *  for the set type of this controller, in the given source.
	 */
	mw.echo.Controller.prototype.markCrossWikiItemsRead = function ( itemIds, source ) {
		var sourceModel,
			notifs,
			allIds = [],
			xwikiModel = this.manager.getNotificationModel( 'xwiki' );

		if ( !xwikiModel ) {
			return $.Deferred().reject().promise();
		}
		itemIds = Array.isArray( itemIds ) ? itemIds : [ itemIds ];

		sourceModel = xwikiModel.getList().getGroupByName( source );
		notifs = sourceModel.findByIds( itemIds );
		sourceModel.discardItems( notifs );
		// Update pagination count
		this.manager.updateCurrentPageItemCount();

		notifs.forEach( function ( notif ) {
			allIds = allIds.concat( notif.getAllIds() );
		} );
		this.manager.getUnreadCounter().estimateChange( -allIds.length );
		return this.api.markItemsRead( allIds, source, true )
			.then( this.refreshUnreadCount.bind( this ) );
	};

	/**
	 * Mark all cross-wiki notifications from all sources as read
	 *
	 * @return {jQuery.Promise} Promise that is resolved when all notifications
	 *  are marked as read
	 */
	mw.echo.Controller.prototype.markEntireCrossWikiItemAsRead = function () {
		var controller = this,
			xwikiModel = this.manager.getNotificationModel( 'xwiki' );

		if ( !xwikiModel ) {
			return $.Deferred().reject().promise();
		}

		this.manager.getUnreadCounter().estimateChange( -xwikiModel.getCount() );

		return this.api.fetchNotificationGroups( xwikiModel.getSourceNames(), this.manager.getTypeString() )
			.then( function ( groupList ) {
				var i, listModel, group, groupItems,
					promises = [],
					idArray = [];

				for ( group in groupList ) {
					listModel = xwikiModel.getItemBySource( group );
					groupItems = groupList[ group ];

					idArray = [];
					for ( i = 0; i < groupItems.length; i++ ) {
						idArray = idArray.concat( groupItems[ i ].id ).concat( groupItems[ i ].bundledIds || [] );
					}

					// Mark items as read in the API
					promises.push(
						controller.api.markItemsRead( idArray, listModel.getName(), true )
					);
				}

				// Synchronously remove this model from the widget
				controller.removeCrossWikiItem();

				return mw.echo.api.NetworkHandler.static.waitForAllPromises( promises ).then(
					controller.refreshUnreadCount.bind( controller )
				);
			} );
	};

	/**
	 * Remove the entire cross-wiki model.
	 */
	mw.echo.Controller.prototype.removeCrossWikiItem = function () {
		this.manager.removeNotificationModel( 'xwiki' );
	};

	/**
	 * Refresh the unread notifications counter
	 *
	 * @return {jQuery.Promise} A promise that is resolved when the counter
	 *  is updated with the actual unread count from the server.
	 */
	mw.echo.Controller.prototype.refreshUnreadCount = function () {
		return this.manager.getUnreadCounter().update();
	};

	/**
	 * Update global seenTime for all sources
	 *
	 * @return {jQuery.Promise} A promise that is resolved when the
	 *  seenTime was updated for all the controller's types and sources.
	 */
	mw.echo.Controller.prototype.updateSeenTime = function () {
		var controller = this;

		return this.api.updateSeenTime(
			this.getTypes(),
			// For consistency, use current source, though seenTime
			// will be updated globally
			this.manager.getFiltersModel().getSourcePagesModel().getCurrentSource()
		)
			.then( function ( time ) {
				controller.manager.getSeenTimeModel().setSeenTime( time );
			} );
	};

	/**
	 * Perform a dynamic action
	 *
	 * @param {Object} data Action data for the network
	 * @param {string} [source] Requested source to query. Defaults to currently
	 *  selected source.
	 * @return {jQuery.Promise} jQuery promise that resolves when the action is done
	 */
	mw.echo.Controller.prototype.performDynamicAction = function ( data, source ) {
		source = source || this.manager.getFiltersModel().getSourcePagesModel().getCurrentSource();
		return this.api.queryAPI( data, source );
	};

	/**
	 * Get the types associated with the controller and model
	 *
	 * @return {string[]} Notification types
	 */
	mw.echo.Controller.prototype.getTypes = function () {
		return this.manager.getTypes();
	};

	/**
	 * Return a string representation of the notification type.
	 * It could be 'alert', 'message' or, if both are set, 'all'
	 *
	 * @return {string} String representation of notifications type
	 */
	mw.echo.Controller.prototype.getTypeString = function () {
		return this.manager.getTypeString();
	};
}( mediaWiki, jQuery ) );