Dr-Blank.Vaani/lib/api/library_item_provider.dart

72 lines
2.3 KiB
Dart
Raw Normal View History

2024-05-09 23:23:50 -04:00
import 'dart:convert';
2024-06-28 06:01:56 -04:00
import 'package:logging/logging.dart';
2024-05-09 23:23:50 -04:00
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:shelfsdk/audiobookshelf_api.dart' as shelfsdk;
2024-08-23 04:21:46 -04:00
import 'package:vaani/api/api_provider.dart';
import 'package:vaani/db/cache/cache_key.dart';
import 'package:vaani/db/cache_manager.dart';
import 'package:vaani/shared/extensions/model_conversions.dart';
2024-05-09 23:23:50 -04:00
part 'library_item_provider.g.dart';
2024-06-28 06:01:56 -04:00
final _logger = Logger('LibraryItemProvider');
2024-05-09 23:23:50 -04:00
/// provides the library item for the given id
@Riverpod(keepAlive: true)
2024-05-09 23:23:50 -04:00
class LibraryItem extends _$LibraryItem {
@override
2024-06-16 22:24:32 -04:00
Stream<shelfsdk.LibraryItemExpanded> build(String id) async* {
2024-05-09 23:23:50 -04:00
final api = ref.watch(authenticatedApiProvider);
2024-06-28 06:01:56 -04:00
_logger.fine('LibraryItemProvider fetching library item: $id');
2024-05-09 23:23:50 -04:00
// ! this is a mock delay
// await Future.delayed(const Duration(seconds: 150));
2024-05-09 23:23:50 -04:00
// look for the item in the cache
final key = CacheKey.libraryItem(id);
final cachedFile = await apiResponseCacheManager.getFileFromMemory(key) ??
await apiResponseCacheManager.getFileFromCache(key);
if (cachedFile != null) {
2024-06-28 06:01:56 -04:00
_logger.fine(
2024-08-23 04:21:46 -04:00
'LibraryItemProvider reading from cache for $id from ${cachedFile.file}',
);
2024-05-09 23:23:50 -04:00
// read file as json
2024-06-16 22:24:32 -04:00
final cachedItem = shelfsdk.LibraryItemExpanded.fromJson(
2024-05-09 23:23:50 -04:00
jsonDecode(await cachedFile.file.readAsString()),
);
yield cachedItem;
2024-06-16 22:24:32 -04:00
} else {
2024-06-28 06:01:56 -04:00
_logger.fine('LibraryItemProvider cache miss for $id');
2024-05-09 23:23:50 -04:00
}
2024-06-16 22:24:32 -04:00
// ! this is a mock delay
// await Future.delayed(const Duration(seconds: 3));
2024-05-14 06:13:16 -04:00
final item = await api.items.get(
libraryItemId: id,
2024-06-16 22:24:32 -04:00
parameters: const shelfsdk.GetItemReqParams(
expanded: true,
include: [
shelfsdk.GetItemIncludeOption.progress,
shelfsdk.GetItemIncludeOption.rssFeed,
shelfsdk.GetItemIncludeOption.authors,
shelfsdk.GetItemIncludeOption.downloads,
],
),
2024-05-14 06:13:16 -04:00
);
2024-05-09 23:23:50 -04:00
if (item != null) {
// save to cache
final newFile = await apiResponseCacheManager.putFile(
key,
2024-06-16 22:24:32 -04:00
utf8.encode(jsonEncode(item.asExpanded.toJson())),
2024-05-09 23:23:50 -04:00
fileExtension: 'json',
key: key,
);
2024-06-28 06:01:56 -04:00
_logger.fine('writing to cache: $newFile');
2024-06-16 22:24:32 -04:00
yield item.asExpanded;
2024-05-09 23:23:50 -04:00
}
}
}