This repository has been archived by the owner on May 31, 2021. It is now read-only.
/
posts_list_bloc.dart
502 lines (452 loc) · 17.2 KB
/
posts_list_bloc.dart
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 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:meta/meta.dart';
import 'package:mooncake/dependency_injection/dependency_injection.dart';
import 'package:mooncake/entities/entities.dart';
import 'package:mooncake/ui/ui.dart';
import 'package:mooncake/usecases/usecases.dart';
import '../export.dart';
/// Implementation of [Bloc] that allows to properly deal with
/// events and states related to the list of posts.
class PostsListBloc extends Bloc<PostsListEvent, PostsListState> {
static const _HOME_LIMIT = 25;
// Synchronization
final int _syncPeriod;
final SyncPostsUseCase _syncPostsUseCase;
Timer _syncTimer;
// Use cases
final GetNotificationsUseCase _getNotifications;
final GetHomePostsUseCase _getHomePostsUseCase;
final GetHomeEventsUseCase _getHomeEventsUseCase;
final UpdatePostsStatusUseCase _updatePostsStatusUseCase;
final ManagePostReactionsUseCase _managePostReactionsUseCase;
final VotePollUseCase _votePollUseCase;
final HidePostUseCase _hidePostUseCase;
final DeletePostsUseCase _deletePostsUseCase;
final BlockUserUseCase _blockUserUseCase;
final UpdatePostUseCase _updatePostUseCase;
final DeletePostUseCase _deletePostUseCase;
final GetActiveAccountUseCase _getActiveAccountUseCase;
// Subscriptions
StreamSubscription _eventsSubscription;
StreamSubscription _postsSubscription;
StreamSubscription _txSubscription;
StreamSubscription _logoutSubscription;
PostsListBloc({
@required int syncPeriod,
@required AccountBloc accountBloc,
@required FirebaseAnalytics analytics,
@required GetHomePostsUseCase getHomePostsUseCase,
@required GetHomeEventsUseCase getHomeEventsUseCase,
@required SyncPostsUseCase syncPostsUseCase,
@required GetNotificationsUseCase getNotificationsUseCase,
@required UpdatePostsStatusUseCase updatePostsStatusUseCase,
@required ManagePostReactionsUseCase managePostReactionsUseCase,
@required HidePostUseCase hidePostUseCase,
@required VotePollUseCase votePollUseCase,
@required DeletePostsUseCase deletePostsUseCase,
@required BlockUserUseCase blockUserUseCase,
@required UpdatePostUseCase updatePostUseCase,
@required DeletePostUseCase deletePostUseCase,
@required GetActiveAccountUseCase getActiveAccountUseCase,
}) : _syncPeriod = syncPeriod,
assert(getNotificationsUseCase != null),
_getNotifications = getNotificationsUseCase,
assert(getHomePostsUseCase != null),
_getHomePostsUseCase = getHomePostsUseCase,
assert(getHomeEventsUseCase != null),
_getHomeEventsUseCase = getHomeEventsUseCase,
assert(syncPostsUseCase != null),
_syncPostsUseCase = syncPostsUseCase,
assert(updatePostsStatusUseCase != null),
_updatePostsStatusUseCase = updatePostsStatusUseCase,
assert(managePostReactionsUseCase != null),
_managePostReactionsUseCase = managePostReactionsUseCase,
assert(hidePostUseCase != null),
_hidePostUseCase = hidePostUseCase,
assert(votePollUseCase != null),
_votePollUseCase = votePollUseCase,
assert(deletePostsUseCase != null),
_deletePostsUseCase = deletePostsUseCase,
assert(blockUserUseCase != null),
_blockUserUseCase = blockUserUseCase,
assert(updatePostUseCase != null),
_updatePostUseCase = updatePostUseCase,
assert(deletePostUseCase != null),
_deletePostUseCase = deletePostUseCase,
assert(getActiveAccountUseCase != null),
_getActiveAccountUseCase = getActiveAccountUseCase,
super(PostsLoading()) {
// Handle the last account state
final accountState = accountBloc.state;
_handleAccountStateChange(accountState);
// Subscribe to account state changes in order to perform setup
// operations upon login and cleanup ones upon logging out
_logoutSubscription = accountBloc.listen((state) async {
await _handleAccountStateChange(state);
});
}
Future<void> _handleAccountStateChange(AccountState state) async {
if (state is LoggedOut) {
print('User logged out, stopping sync and deleting posts');
_stopListeningToUpdates();
await _deletePostsUseCase.delete();
} else if (state is LoggedIn) {
print('User logged in, starting posts sync');
_startListeningToUpdates();
}
}
factory PostsListBloc.create(BuildContext context, {int syncPeriod = 30}) {
return PostsListBloc(
syncPeriod: syncPeriod,
accountBloc: BlocProvider.of(context),
getHomePostsUseCase: Injector.get(),
getHomeEventsUseCase: Injector.get(),
syncPostsUseCase: Injector.get(),
analytics: Injector.get(),
getNotificationsUseCase: Injector.get(),
updatePostsStatusUseCase: Injector.get(),
managePostReactionsUseCase: Injector.get(),
hidePostUseCase: Injector.get(),
votePollUseCase: Injector.get(),
deletePostsUseCase: Injector.get(),
blockUserUseCase: Injector.get(),
updatePostUseCase: Injector.get(),
deletePostUseCase: Injector.get(),
getActiveAccountUseCase: Injector.get(),
);
}
@override
Stream<Transition<PostsListEvent, PostsListState>> transformEvents(
Stream<PostsListEvent> events,
TransitionFunction<PostsListEvent, PostsListState> next,
) {
return super.transformEvents(events.distinct(), next);
}
@override
Stream<PostsListState> mapEventToState(PostsListEvent event) async* {
final currentState = state;
if (event is PostsUpdated) {
yield* _mapPostsUpdatedEventToState(event);
} else if (event is AddOrRemoveLike) {
yield* _convertAddOrRemoveLikeEvent(event);
} else if (event is AddOrRemovePostReaction) {
yield* _mapAddPostReactionEventToState(event);
} else if (event is VotePoll) {
yield* _mapVotePollEventToState(event);
} else if (event is HidePost) {
yield* _mapHidePostEventToState(event);
} else if (event is BlockUser) {
yield* _mapBlockUserEventToState(event);
} else if (event is SyncPosts) {
yield* _mapSyncPostsListEventToState();
} else if (event is SyncPostsCompleted) {
yield _mapSyncPostsCompletedEventToState();
} else if (event is ShouldRefreshPosts) {
yield* _mapShouldRefreshPostsEventToState();
} else if (event is RefreshPosts) {
yield* _refreshPostsEventToState();
} else if (event is FetchPosts && !_hasReachedMax(currentState)) {
yield* _mapFetchEventToState();
} else if (event is TxSuccessful) {
_handleTxSuccessfulEvent(event);
} else if (event is TxFailed) {
_handleTxFailedEvent(event);
} else if (event is DeletePosts) {
_handleDeletePosts();
} else if (event is RetryPostUpload) {
yield* _mapRetryPostUploadEventToState(event);
} else if (event is DeletePost) {
yield* _mapDeletePostToState(event);
}
}
/// Starts all the needed periodic operations (eg. sync) and
/// the listening of all the useful events.
void _startListeningToUpdates() {
// Start the syncing timer
_initializeSyncTimer();
// Subscribe to the posts changes
if (_postsSubscription == null) {
_listenHomePosts(_HOME_LIMIT);
}
// Subscribe to tell the user he should refresh
_eventsSubscription ??= _getHomeEventsUseCase.stream.listen((event) {
add(ShouldRefreshPosts());
});
// Subscribe to the transactions notifications
_txSubscription ??= _getNotifications.stream().listen((notification) {
if (notification is TxSuccessfulNotification) {
add(TxSuccessful(txHash: notification.txHash));
} else if (notification is TxFailedNotification) {
add(TxFailed(txHash: notification.txHash, error: notification.error));
}
});
}
/// Stop all periodic activities as well as all subscriptions.
void _stopListeningToUpdates() {
_syncTimer?.cancel();
_syncTimer = null;
_postsSubscription?.cancel();
_postsSubscription = null;
_eventsSubscription?.cancel();
_eventsSubscription = null;
_txSubscription?.cancel();
_txSubscription = null;
}
/// Refreshes the subscription that listens to changes inside the number
/// of home posts.
void _listenHomePosts(int limit) {
_postsSubscription?.cancel();
_postsSubscription = _getHomePostsUseCase.stream(limit).listen((posts) {
if (posts.isEmpty) return;
add(PostsUpdated(posts));
});
}
/// Tells whether all the posts have been fetched from the remote source
/// or there are still some pages left.
bool _hasReachedMax(PostsListState state) {
return state is PostsLoaded && state.hasReachedMax;
}
/// Initializes the timer allowing us to sync the user activity once every
/// [syncPeriod] seconds if it hasn't been done before.
void _initializeSyncTimer() {
if (_syncTimer?.isActive != true) {
_syncTimer?.cancel();
_syncTimer = Timer.periodic(Duration(seconds: _syncPeriod), (t) {
add(SyncPosts());
});
}
}
/// Merges the [current] posts list with the [newList].
/// INVARIANT: `current.length > newList.length`
List<Post> _mergePosts(List<Post> current, List<Post> newList) {
final posts = current.map((post) {
final newPost = newList.firstWhere(
(p) => p.id == post.id,
orElse: () => null,
);
return newPost ?? post;
}).toList();
return posts;
}
/// Handles the event emitted when a new list of posts has been emitted.
Stream<PostsListState> _mapPostsUpdatedEventToState(
PostsUpdated event,
) async* {
final currentState = state;
if (currentState is PostsLoading) {
yield PostsLoaded.first(posts: event.posts);
} else if (currentState is PostsLoaded) {
// Avoid overloading operations
if (currentState.posts == event.posts) {
return;
}
yield currentState.copyWith(
posts: event.posts.length < currentState.posts.length
? await _mergePosts(currentState.posts, event.posts)
: event.posts,
refreshing: false,
shouldRefresh: false,
);
}
}
/// Converts an [AddOrRemoveLikeEvent] into an
/// [AddOrRemovePostReaction] event so that it can be handled properly.
Stream<PostsListState> _convertAddOrRemoveLikeEvent(
AddOrRemoveLike event,
) {
final reactEvent = AddOrRemovePostReaction(
event.post,
Constants.LIKE_REACTION,
);
return _mapAddPostReactionEventToState(reactEvent);
}
/// Handles the event emitted when the user likes a post
Stream<PostsListState> _mapAddPostReactionEventToState(
AddOrRemovePostReaction event,
) async* {
final currentState = state;
if (currentState is PostsLoaded) {
final newPost = await _managePostReactionsUseCase.addOrRemove(
post: event.post,
reaction: event.reaction,
);
final posts = currentState.posts
.map((post) => post.id == newPost.id ? newPost : post)
.toList();
yield currentState.copyWith(posts: posts);
}
}
/// Handles the event emitted when the user votes on a specific post poll.
Stream<PostsListState> _mapVotePollEventToState(VotePoll event) async* {
final currentState = state;
if (currentState is PostsLoaded) {
final newPost = await _votePollUseCase.vote(event.post, event.option);
final newPosts = currentState.posts
.map((post) => post.id == newPost.id ? newPost : post)
.toList();
yield currentState.copyWith(posts: newPosts);
}
}
/// Handles the event emitted when a post should be hidden from the user view.
Stream<PostsListState> _mapHidePostEventToState(
HidePost event,
) async* {
final currentState = state;
if (currentState is PostsLoaded) {
final newPost = await _hidePostUseCase.hide(event.post);
final newPosts = currentState.posts
.map((post) => post.id == newPost.id ? newPost : post)
.toList();
yield currentState.copyWith(posts: newPosts);
}
}
/// Handles the event emitted when the user wants to block another user.
Stream<PostsListState> _mapBlockUserEventToState(BlockUser event) async* {
final currentState = state;
if (currentState is PostsLoaded) {
await _blockUserUseCase.block(event.user);
final newPosts = currentState.posts
.where((post) => post.owner.address != event.user.address)
.toList();
yield currentState.copyWith(posts: newPosts);
}
}
Stream<PostsListState> _mapFetchEventToState() async* {
final currentState = state;
if (currentState is PostsLoading) {
final posts = await _getHomePostsUseCase.get(
start: 0,
limit: _HOME_LIMIT,
);
yield PostsLoaded.first(posts: posts);
} else if (currentState is PostsLoaded) {
final posts = await _getHomePostsUseCase.get(
start: currentState.posts.length,
limit: _HOME_LIMIT,
);
yield posts.isEmpty
? currentState.copyWith(hasReachedMax: true)
: currentState.copyWith(
posts: currentState.posts + posts,
hasReachedMax: false,
);
// Listen to new changes on all the posts
if (posts.isNotEmpty) {
_listenHomePosts(currentState.posts.length + posts.length);
}
}
}
/// Handles the event that is emitted when the list of posts should be
/// refreshed.
Stream<PostsListState> _mapShouldRefreshPostsEventToState() async* {
final currentState = state;
if (currentState is PostsLoaded) {
yield currentState.copyWith(shouldRefresh: true);
}
}
/// Handles the event emitted when the list of the home posts
/// should be updated.
Stream<PostsListState> _refreshPostsEventToState() async* {
final currentState = state;
var limit = _HOME_LIMIT;
if (currentState is PostsLoaded) {
limit = currentState.posts.length;
yield currentState.copyWith(refreshing: true, shouldRefresh: false);
}
final posts = await _getHomePostsUseCase.get(start: 0, limit: limit);
if (currentState is PostsLoaded) {
yield currentState.copyWith(
refreshing: false,
posts: posts,
shouldRefresh: false,
);
} else if (currentState is PostsLoading) {
yield PostsLoaded.first(posts: posts);
}
}
/// Handles the event emitted when the posts must be synced uploading
/// all the changes stored locally to the chain
Stream<PostsListState> _mapSyncPostsListEventToState() async* {
final currentState = state;
if (currentState is PostsLoaded) {
// Fet the current user
final user = await _getActiveAccountUseCase.single();
// Show the snackbar
yield currentState.copyWith(syncingPosts: true);
// Wait for the sync
yield await _syncPostsUseCase.sync(user.address).catchError((error) {
print('Sync error: $error');
return _mapSyncPostsCompletedEventToState();
}).then((syncedPosts) {
return _mapSyncPostsCompletedEventToState();
});
}
}
/// Handles the event that tells the bloc the synchronization has completed
PostsListState _mapSyncPostsCompletedEventToState() {
// Once the sync has been completed, hide the bar and load the new posts
final currentState = state;
if (currentState is PostsLoaded) {
return currentState.copyWith(syncingPosts: false);
}
return currentState;
}
/// Handles the event that tells the Bloc that a transaction has
/// been successful.
void _handleTxSuccessfulEvent(TxSuccessful event) async {
final status = PostStatus.txSuccessful(txHash: event.txHash);
await _updatePostsStatusUseCase.update(event.txHash, status);
}
/// Handles the event that tells the Bloc that a transaction has not
/// been successful.
void _handleTxFailedEvent(TxFailed event) async {
final status = PostStatus.errored(event.error);
await _updatePostsStatusUseCase.update(event.txHash, status);
}
void _handleDeletePosts() async {
await _deletePostsUseCase.delete();
add(RefreshPosts());
}
/// Handles the event that is emitted when the user tries to repost
/// a failed post attempt
Stream<PostsListState> _mapRetryPostUploadEventToState(
RetryPostUpload event,
) async* {
final user = await _getActiveAccountUseCase.single();
final updatePost = event.post.copyWith(
status: PostStatus.storedLocally(user.address),
);
final currentState = state;
if (currentState is PostsLoaded) {
await _updatePostUseCase.update(updatePost);
yield currentState.copyWith(
posts: _mergePosts(currentState.posts, [updatePost]),
);
}
}
/// Handles the event that is emitted when the user wants to delete a failed post
Stream<PostsListState> _mapDeletePostToState(DeletePost event) async* {
final currentState = state;
if (currentState is PostsLoaded) {
await _deletePostUseCase.delete(event.post);
yield currentState.copyWith(
posts: currentState.posts
.where((post) => post.id != event.post.id)
.toList());
}
}
@override
Future<void> close() {
_eventsSubscription?.cancel();
_postsSubscription?.cancel();
_txSubscription?.cancel();
_syncTimer?.cancel();
_logoutSubscription?.cancel();
return super.close();
}
}