forked from AOSSIE-Org/Resonate
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexplore_story_controller.dart
More file actions
540 lines (472 loc) · 17.9 KB
/
explore_story_controller.dart
File metadata and controls
540 lines (472 loc) · 17.9 KB
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
import 'dart:async';
import 'dart:developer';
import 'dart:io' as io;
import 'package:appwrite/appwrite.dart';
import 'package:appwrite/models.dart';
import 'package:audio_metadata_reader/audio_metadata_reader.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:resonate/controllers/auth_state_controller.dart';
import 'package:resonate/models/chapter.dart';
import 'package:resonate/models/story.dart';
import 'package:resonate/services/appwrite_service.dart';
import 'package:resonate/utils/constants.dart';
import 'package:resonate/utils/enums/story_category.dart';
class ExploreStoryController extends GetxController {
final Databases databases = AppwriteService.getDatabases();
final Storage storage = AppwriteService.getStorage();
final authStateController = Get.put(AuthStateController());
RxList<Story> recommendedStories = <Story>[].obs;
RxList<Story> userCreatedStories = <Story>[].obs;
RxList<Story> userLikedStories = <Story>[].obs;
RxList<Story> searchResponseStories = <Story>[].obs;
RxList<Story> openedCategotyStories = <Story>[].obs;
Rx<bool> isLoadingRecommendedStories = false.obs;
Rx<bool> isLoadingCategoryPage = false.obs;
Rx<bool> isLoadingStoryPage = false.obs;
Rx<bool> isSearching = false.obs;
Rx<bool> searchBarIsEmpty = true.obs;
@override
void onInit() async {
super.onInit();
await fetchStoryRecommendation();
await fetchUserCreatedStories();
await fetchUserLikedStories();
}
Future<void> fetchMoreDetailsForSelectedStory(Story story) async {
isLoadingStoryPage.value = true;
List<Chapter> storyChapters = [];
try {
storyChapters = await fetchChaptersForStory(story.storyId);
} on AppwriteException catch (e) {
log("failed to fetch story chapters for selected search result query: ${e.message}");
}
bool hasUserLiked = false;
try {
hasUserLiked = await checkIfStoryLikedByUser(story.storyId);
} on AppwriteException catch (e) {
log("failed to check if user liked story for selected search result query ${e.message}");
}
Document doc = await databases.getDocument(
databaseId: storyDatabaseId,
collectionId: storyCollectionId,
documentId: story.storyId,
queries: [
Query.select(["likes"])
]);
int likes = doc.data['likes'];
story.chapters = storyChapters;
story.isLikedByCurrentUser.value = hasUserLiked;
story.likesCount.value = likes;
isLoadingStoryPage.value = false;
}
Future<void> updateLikesCountAndUserLikeStatus(Story story) async {
Document doc = await databases.getDocument(
databaseId: storyDatabaseId,
collectionId: storyCollectionId,
documentId: story.storyId,
queries: [
Query.select(["likes"])
]);
int likes = doc.data['likes'];
bool hasUserLiked = await checkIfStoryLikedByUser(story.storyId);
story.likesCount.value = likes;
story.isLikedByCurrentUser.value = hasUserLiked;
}
Future<void> searchStories(String query) async {
List<Document> storyDocuments = await databases.listDocuments(
databaseId: storyDatabaseId,
collectionId: storyCollectionId,
queries: [
Query.or([
Query.search('title', query),
Query.search('creatorName', query),
Query.search('description', query)
]),
Query.limit(16)
]).then((value) => value.documents);
searchResponseStories.value =
await convertAppwriteDocListToStoryList(storyDocuments);
}
Future<void> updateStoriesPlayDurationLength(
List<Chapter> chapters, String storyId) async {
int totalStoryDuration = chapters.fold(0, (sum, chapter) {
return sum + chapter.playDuration;
});
try {
await databases.updateDocument(
databaseId: storyDatabaseId,
collectionId: storyCollectionId,
documentId: storyId,
data: {"playDuration": totalStoryDuration});
} on AppwriteException catch (e) {
log("Failed to update story duration: ${e.message}");
}
}
Future<void> pushChaptersToStory(
List<Chapter> chapters, String storyId) async {
for (Chapter chapter in chapters) {
String colorString = chapter.tintColor.toHex(leadingHashSign: false);
String coverImgUrl = chapter.coverImageUrl;
if (!coverImgUrl.contains("http")) {
coverImgUrl = await uploadFileToAppwriteGetUrl(
storyBucketId, chapter.chapterId, coverImgUrl, "story cover");
}
String audioFileId = 'audioFor${chapter.chapterId}';
String audioFileUrl = await uploadFileToAppwriteGetUrl(
storyBucketId, audioFileId, chapter.audioFileUrl, "audio file");
await databases.createDocument(
databaseId: storyDatabaseId,
collectionId: chapterCollectionId,
documentId: chapter.chapterId,
data: {
'title': chapter.title,
'description': chapter.description,
'coverImgUrl': coverImgUrl,
'lyrics': chapter.lyrics,
'playDuration': chapter.playDuration,
'tintColor': colorString,
'storyId': storyId,
'audioFileUrl': audioFileUrl
});
}
}
Future<void> fetchStoryByCategory(StoryCategory category) async {
isLoadingCategoryPage.value = true;
List<Document> storyDocuments = [];
try {
storyDocuments = await databases.listDocuments(
databaseId: storyDatabaseId,
collectionId: storyCollectionId,
queries: [
Query.limit(15),
Query.equal('category', category.name)
]).then((value) => value.documents);
} on AppwriteException catch (e) {
log('Failed to fetch stories for categories: ${e.message}');
}
openedCategotyStories.value =
await convertAppwriteDocListToStoryList(storyDocuments);
isLoadingCategoryPage.value = false;
}
Future<String> uploadFileToAppwriteGetUrl(String bucketId, String fileId,
String filePath, String fileIdentificationForError) async {
try {
await storage.createFile(
bucketId: storyBucketId,
fileId: fileId,
file: InputFile.fromPath(path: filePath),
);
} on AppwriteException catch (e) {
log("failed to upload $fileIdentificationForError to appwrite: ${e.message}");
}
return "$appwriteEndpoint/storage/buckets/$bucketId/files/$fileId/view?project=$appwriteProjectId";
}
Future<Chapter> createChapter(String title, String description,
String coverImgPath, String audioFilePath, String lyricsFilePath) async {
final track = io.File(audioFilePath);
final metadata = readMetadata(track);
int playDuration = metadata.duration?.inMilliseconds ?? 0;
String chapterId = ID.unique();
Color primaryColor;
if (!coverImgPath.contains('http')) {
ColorScheme imageColorScheme = await ColorScheme.fromImageProvider(
provider: FileImage(io.File(coverImgPath)));
primaryColor = imageColorScheme.primary;
} else {
primaryColor = const Color(0xffcbc6c6);
}
String lyrics = '';
if (lyricsFilePath != '') {
lyrics = await io.File(lyricsFilePath).readAsString();
}
// coverImageUrl and audioFileUrl recieve paths while the chapter creation process
// as cannot push files to storage to get URL unless user is final on creating a story
return Chapter(chapterId, title, coverImgPath, description, lyrics,
audioFilePath, playDuration, primaryColor);
}
Future<void> createStory(
String title,
String desciption,
StoryCategory category,
String coverImgRef,
int storyPlayDuration,
List<Chapter> chapters) async {
String storyId = ID.unique();
String coverImgUrl = coverImgRef;
Color primaryColor;
if (!coverImgUrl.contains("http")) {
ColorScheme imageColorScheme = await ColorScheme.fromImageProvider(
provider: FileImage(io.File(coverImgUrl)));
primaryColor = imageColorScheme.primary;
coverImgUrl = await uploadFileToAppwriteGetUrl(
storyBucketId, storyId, coverImgRef, "story cover");
} else {
primaryColor = const Color(0xffcbc6c6);
}
try {
await pushChaptersToStory(chapters, storyId);
} on AppwriteException catch (e) {
log("failed to push chapters to appwrite: ${e.message}");
}
String colorString = primaryColor.toHex(leadingHashSign: false);
try {
await databases.createDocument(
databaseId: storyDatabaseId,
collectionId: storyCollectionId,
documentId: storyId,
data: {
'title': title,
'description': desciption,
'category': category.name,
'coverImgUrl': coverImgUrl,
'creatorId': authStateController.uid,
'creatorName': authStateController.displayName,
'creatorImgUrl': authStateController.profileImageUrl,
'likes': 0,
'playDuration': storyPlayDuration,
'tintColor': colorString
});
} on AppwriteException catch (e) {
log("failed to upload story to appwrite: ${e.message}");
}
await fetchUserCreatedStories();
await fetchStoryRecommendation();
}
Future<void> fetchUserLikedStories() async {
List<Document> userLikedDocuments = await databases.listDocuments(
databaseId: storyDatabaseId,
collectionId: likeCollectionId,
queries: [
Query.equal('uId', authStateController.uid)
]).then((value) => value.documents);
List<Document> userLikedStoriesDocuments =
await Future.wait(userLikedDocuments.map((value) async {
return await databases.getDocument(
databaseId: storyDatabaseId,
collectionId: storyCollectionId,
documentId: value.data['storyId']);
}).toList());
userLikedStories.value =
await convertAppwriteDocListToStoryList(userLikedStoriesDocuments);
}
Future<void> deleteStory(Story story) async {
try {
await storage.deleteFile(bucketId: storyBucketId, fileId: story.storyId);
} on AppwriteException catch (e) {
log('failed to delete story cover image ${e.message}');
}
try {
await deleteAllStoryChapters(story.chapters);
} on AppwriteException catch (e) {
log('failed to delete all story chapters ${e.message}');
}
try {
await deleteAllStoryLikes(story.storyId);
} on AppwriteException catch (e) {
log('failed to delete all story likes: ${e.message}');
}
try {
await databases.deleteDocument(
databaseId: storyDatabaseId,
collectionId: storyCollectionId,
documentId: story.storyId);
} on AppwriteException catch (e) {
log("failed to delete a document: ${e.message}");
}
fetchUserCreatedStories();
}
Future<void> deleteAllStoryLikes(String storyId) async {
List<Document> storyLikeDocuments = await databases.listDocuments(
databaseId: storyDatabaseId,
collectionId: likeCollectionId,
queries: [
Query.equal('storyId', storyId)
]).then((value) => value.documents);
for (Document like in storyLikeDocuments) {
await databases.deleteDocument(
databaseId: storyDatabaseId,
collectionId: likeCollectionId,
documentId: like.$id);
}
}
Future<void> deleteChapter(Chapter chapter) async {
try {
await storage.deleteFile(
bucketId: storyBucketId, fileId: chapter.chapterId);
} on AppwriteException catch (e) {
log("failed to delete chapter cover img ${e.message}");
}
try {
await storage.deleteFile(
bucketId: storyBucketId, fileId: 'audioFor${chapter.chapterId}');
} on AppwriteException catch (e) {
log("failed to delete chapter audio file ${e.message}");
}
try {
await databases.deleteDocument(
databaseId: storyDatabaseId,
collectionId: chapterCollectionId,
documentId: chapter.chapterId);
} on AppwriteException catch (e) {
log("failed to delete chapter document ${e.message}");
}
}
Future<void> deleteAllStoryChapters(List<Chapter> chapters) async {
for (Chapter chapter in chapters) {
await deleteChapter(chapter);
}
}
Future<void> fetchUserCreatedStories() async {
List<Document> storyDocuments = [];
try {
storyDocuments = await databases.listDocuments(
databaseId: storyDatabaseId,
collectionId: storyCollectionId,
queries: [
Query.equal('creatorId', authStateController.uid)
]).then((value) => value.documents);
} on AppwriteException catch (e) {
log('Failed to fetch user created stories: ${e.message}');
}
userCreatedStories.value =
await convertAppwriteDocListToStoryList(storyDocuments);
}
Future<void> likeStoryFromUserAccount(Story story) async {
try {
await databases.createDocument(
databaseId: storyDatabaseId,
collectionId: likeCollectionId,
documentId: ID.unique(),
data: {'uId': authStateController.uid, 'storyId': story.storyId});
} on AppwriteException catch (e) {
log('Failed to like a story: ${e.message}');
}
try {
await databases.updateDocument(
databaseId: storyDatabaseId,
collectionId: storyCollectionId,
documentId: story.storyId,
data: {"likes": story.likesCount.value + 1});
} on AppwriteException catch (e) {
log("Failed to add one story like: ${e.message}");
}
fetchUserLikedStories();
}
Future<void> unlikeStoryFromUserAccount(Story story) async {
List<Document> userLikeDocuments = [];
try {
userLikeDocuments = await databases.listDocuments(
databaseId: storyDatabaseId,
collectionId: likeCollectionId,
queries: [
Query.and([
Query.equal('uId', authStateController.uid),
Query.equal('storyId', story.storyId)
]),
]).then((value) => value.documents);
} on AppwriteException catch (e) {
log('Failed to fetch Like Document: ${e.message}');
}
try {
await databases.deleteDocument(
databaseId: storyDatabaseId,
collectionId: likeCollectionId,
documentId: userLikeDocuments.first.$id,
);
} on AppwriteException catch (e) {
log('Failed to Unlike i.e delete Like Document: ${e.message}');
}
try {
await databases.updateDocument(
databaseId: storyDatabaseId,
collectionId: storyCollectionId,
documentId: story.storyId,
data: {"likes": story.likesCount.value - 1});
} on AppwriteException catch (e) {
log("Failed to reduce one story like: ${e.message}");
}
fetchUserLikedStories();
}
Future<List<Chapter>> fetchChaptersForStory(String storyId) async {
List<Document> chapterDocuments = await databases.listDocuments(
databaseId: storyDatabaseId,
collectionId: chapterCollectionId,
queries: [
Query.equal('storyId', storyId)
]).then((value) => value.documents);
List<Chapter> currentStoryChapters = chapterDocuments.map((value) {
Color tintColor = Color(int.parse("0xff${value.data['tintColor']}"));
return Chapter(
value.$id,
value.data['title'],
value.data['coverImgUrl'],
value.data['description'],
value.data['lyrics'],
value.data['audioFileUrl'],
value.data['playDuration'],
tintColor);
}).toList();
return currentStoryChapters;
}
Future<bool> checkIfStoryLikedByUser(String storyId) async {
List<Document> userLikeDocuments = await databases.listDocuments(
databaseId: storyDatabaseId,
collectionId: likeCollectionId,
queries: [
Query.and([
Query.equal('uId', authStateController.uid),
Query.equal('storyId', storyId)
]),
]).then((value) => value.documents);
return userLikeDocuments.isNotEmpty;
}
Future<void> fetchStoryRecommendation() async {
isLoadingRecommendedStories.value = true;
List<Document> storyDocuments = [];
try {
storyDocuments = await databases.listDocuments(
databaseId: storyDatabaseId,
collectionId: storyCollectionId,
queries: [Query.limit(10)]).then((value) => value.documents);
} on AppwriteException catch (e) {
log('Failed to fetch stories: ${e.message}');
}
recommendedStories.value =
await convertAppwriteDocListToStoryList(storyDocuments);
isLoadingRecommendedStories.value = false;
}
Future<List<Story>> convertAppwriteDocListToStoryList(
List<Document> storyDocuments) async {
return await Future.wait(storyDocuments.map((value) async {
StoryCategory category =
StoryCategory.values.byName(value.data['category']);
Color tintColor = Color(int.parse("0xff${value.data['tintColor']}"));
return Story(
title: value.data['title'],
storyId: value.$id,
description: value.data['description'],
userIsCreator: value.data['creatorId'] == authStateController.uid,
category: category,
coverImageUrl: value.data['coverImgUrl'],
creatorId: value.data['creatorId'],
creatorName: value.data['creatorName'],
creatorImgUrl: value.data['creatorImgUrl'],
creationDate: DateTime.parse(value.$createdAt),
likesCount: value.data['likes'],
isLikedByCurrentUser: false,
playDuration: value.data['playDuration'],
tintColor: tintColor,
chapters: [],
);
}).toList());
}
}
extension HexColor on Color {
/// Prefixes a hash sign if [leadingHashSign] is set to `true` (default is `true`).
String toHex({bool leadingHashSign = true}) => '${leadingHashSign ? '#' : ''}'
'${(a * 255).toInt().toRadixString(16).padLeft(2, '0')}'
'${r.toInt().toRadixString(16).padLeft(2, '0')}'
'${g.toInt().toRadixString(16).padLeft(2, '0')}'
'${b.toInt().toRadixString(16).padLeft(2, '0')}';
}