93 lines
2.4 KiB
Dart
93 lines
2.4 KiB
Dart
import "dart:convert";
|
|
import "dart:typed_data";
|
|
|
|
import "package:flutter/foundation.dart";
|
|
import "package:quotegen_client/models/gallery_item.dart";
|
|
import "package:quotegen_client/providers/form_provider.dart";
|
|
import "package:quotegen_client/services/gallery_db.dart";
|
|
|
|
|
|
class GalleryProvider extends ChangeNotifier {
|
|
|
|
List<GalleryItem> items = [];
|
|
bool isLoading = false;
|
|
|
|
|
|
GalleryProvider() {
|
|
load();
|
|
}
|
|
|
|
Future<void> load() async {
|
|
isLoading = true;
|
|
notifyListeners();
|
|
|
|
items = await GalleryDB.getAllItems();
|
|
|
|
isLoading = false;
|
|
notifyListeners();
|
|
}
|
|
|
|
// returns false if a duplicate already exists
|
|
Future<bool> saveCurrentForm(FormProvider form) async {
|
|
final avatarB64 = form.avatarImage != null ? base64Encode(form.avatarImage!) : null;
|
|
final postB64 = form.postImage != null ? base64Encode(form.postImage!) : null;
|
|
final ts = form.combineDateTime();
|
|
|
|
final isDuplicate = items.any((i) =>
|
|
i.displayName == form.displayName &&
|
|
i.handle == form.handle &&
|
|
i.content == form.content &&
|
|
i.verified == form.verified &&
|
|
i.timestamp == ts &&
|
|
i.avatarImageB64 == avatarB64 &&
|
|
i.postImageB64 == postB64 &&
|
|
i.replies == form.replies &&
|
|
i.retweets == form.retweets &&
|
|
i.likes == form.likes &&
|
|
i.views == form.views
|
|
);
|
|
|
|
if (isDuplicate) return false;
|
|
|
|
final id = DateTime.now().millisecondsSinceEpoch.toString();
|
|
|
|
final item = GalleryItem(
|
|
id: id,
|
|
displayName: form.displayName,
|
|
handle: form.handle,
|
|
content: form.content,
|
|
verified: form.verified,
|
|
timestamp: ts,
|
|
avatarImageB64: avatarB64,
|
|
postImageB64: postB64,
|
|
replies: form.replies,
|
|
retweets: form.retweets,
|
|
likes: form.likes,
|
|
views: form.views,
|
|
createdAt: DateTime.now().millisecondsSinceEpoch,
|
|
);
|
|
|
|
await GalleryDB.saveItem(item);
|
|
items.insert(0, item);
|
|
notifyListeners();
|
|
return true;
|
|
}
|
|
|
|
Future<void> deleteItem(String id) async {
|
|
await GalleryDB.deleteItem(id);
|
|
items.removeWhere((i) => i.id == id);
|
|
notifyListeners();
|
|
}
|
|
|
|
// decode image bytes for a gallery item - returns null if no image
|
|
Uint8List? decodeAvatar(GalleryItem item) {
|
|
if (item.avatarImageB64 == null) return null;
|
|
return base64Decode(item.avatarImageB64!);
|
|
}
|
|
|
|
Uint8List? decodePostImage(GalleryItem item) {
|
|
if (item.postImageB64 == null) return null;
|
|
return base64Decode(item.postImageB64!);
|
|
}
|
|
}
|