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

236 lines
7 KiB
Dart
Raw Normal View History

2024-05-08 05:03:49 -04:00
// provider to provide the api instance
import 'dart:convert';
2025-03-25 22:01:16 +05:30
import 'package:hooks_riverpod/hooks_riverpod.dart';
2024-09-06 15:10:00 -04:00
import 'package:http/http.dart';
2024-06-28 06:01:56 -04:00
import 'package:logging/logging.dart';
2024-05-08 05:03:49 -04:00
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:shelfsdk/audiobookshelf_api.dart';
2024-08-23 04:21:46 -04:00
import 'package:vaani/db/cache_manager.dart';
import 'package:vaani/models/error_response.dart';
2024-08-23 04:21:46 -04:00
import 'package:vaani/settings/api_settings_provider.dart';
import 'package:vaani/settings/models/authenticated_user.dart';
import 'package:vaani/shared/extensions/obfuscation.dart';
2024-05-08 05:03:49 -04:00
part 'api_provider.g.dart';
2024-09-06 15:10:00 -04:00
// TODO: workaround for https://github.com/rrousselGit/riverpod/issues/3718
typedef ResponseErrorHandler = void Function(
Response response, [
Object? error,
]);
2024-06-28 06:01:56 -04:00
final _logger = Logger('api_provider');
2024-05-08 05:03:49 -04:00
Uri makeBaseUrl(String address) {
if (!address.startsWith('http') && !address.startsWith('https')) {
address = 'https://$address';
}
if (!Uri.parse(address).isAbsolute) {
throw ArgumentError.value(address, 'address', 'Invalid address');
}
return Uri.parse(address);
}
/// get the api instance for the given base url
@riverpod
2025-03-25 22:01:16 +05:30
AudiobookshelfApi audiobookshelfApi(Ref ref, Uri? baseUrl) {
2024-05-08 05:03:49 -04:00
// try to get the base url from app settings
final apiSettings = ref.watch(apiSettingsProvider);
baseUrl ??= apiSettings.activeServer?.serverUrl;
return AudiobookshelfApi(
2024-08-23 03:44:44 -04:00
baseUrl: makeBaseUrl(baseUrl.toString()),
2024-05-08 05:03:49 -04:00
);
}
/// get the api instance for the authenticated user
///
/// if the user is not authenticated throw an error
2024-05-14 06:13:16 -04:00
@Riverpod(keepAlive: true)
2025-03-25 22:01:16 +05:30
AudiobookshelfApi authenticatedApi(Ref ref) {
2024-05-08 05:03:49 -04:00
final apiSettings = ref.watch(apiSettingsProvider);
final user = apiSettings.activeUser;
if (user == null) {
_logger.severe('No active user can not provide authenticated api');
2024-05-08 05:03:49 -04:00
throw StateError('No active user');
}
return AudiobookshelfApi(
2024-08-23 03:44:44 -04:00
baseUrl: makeBaseUrl(user.server.serverUrl.toString()),
2024-05-08 05:03:49 -04:00
token: user.authToken,
);
}
/// ping the server to check if it is reachable
@riverpod
2025-03-25 22:01:16 +05:30
FutureOr<bool> isServerAlive(Ref ref, String address) async {
2024-05-08 05:03:49 -04:00
if (address.isEmpty) {
return false;
}
2024-09-06 15:10:00 -04:00
try {
return await AudiobookshelfApi(baseUrl: makeBaseUrl(address))
.server
.ping() ??
false;
} catch (e) {
2024-05-08 05:03:49 -04:00
return false;
}
2024-09-06 15:10:00 -04:00
}
/// fetch status of server
@riverpod
FutureOr<ServerStatusResponse?> serverStatus(
2025-03-25 22:01:16 +05:30
Ref ref,
2024-09-06 15:10:00 -04:00
Uri baseUrl, [
ResponseErrorHandler? responseErrorHandler,
]) async {
_logger.fine('fetching server status: ${baseUrl.obfuscate()}');
2024-09-06 15:10:00 -04:00
final api = ref.watch(audiobookshelfApiProvider(baseUrl));
final res =
await api.server.status(responseErrorHandler: responseErrorHandler);
_logger.fine('server status: $res');
return res;
2024-05-08 05:03:49 -04:00
}
/// fetch the personalized view
@riverpod
class PersonalizedView extends _$PersonalizedView {
@override
Stream<List<Shelf>> build() async* {
final api = ref.watch(authenticatedApiProvider);
final apiSettings = ref.watch(apiSettingsProvider);
final user = apiSettings.activeUser;
if (user == null) {
_logger.warning('no active user');
yield [];
return;
}
2024-05-08 05:03:49 -04:00
if (apiSettings.activeLibraryId == null) {
2024-05-09 23:23:50 -04:00
// set it to default user library by logging in and getting the library id
final login = await ref.read(loginProvider().future);
if (login == null) {
_logger.shout('failed to login, not building personalized view');
yield [];
return;
}
2024-05-08 05:03:49 -04:00
ref.read(apiSettingsProvider.notifier).updateState(
apiSettings.copyWith(activeLibraryId: login.userDefaultLibraryId),
2024-05-08 05:03:49 -04:00
);
yield [];
return;
2024-05-09 23:23:50 -04:00
}
2024-05-08 05:03:49 -04:00
// try to find in cache
// final cacheKey = 'personalizedView:${apiSettings.activeLibraryId}';
final key = 'personalizedView:${apiSettings.activeLibraryId! + user.id}';
2024-05-09 23:23:50 -04:00
final cachedRes = await apiResponseCacheManager.getFileFromMemory(
key,
) ??
await apiResponseCacheManager.getFileFromCache(key);
2024-05-08 05:03:49 -04:00
if (cachedRes != null) {
2024-09-06 15:10:00 -04:00
_logger.fine('reading from cache: $cachedRes for key: $key');
try {
final resJson = jsonDecode(await cachedRes.file.readAsString()) as List;
final res = [
for (final item in resJson)
Shelf.fromJson(item as Map<String, dynamic>),
];
_logger.fine('successfully read from cache key: $key');
yield res;
} catch (e) {
_logger.warning('error reading from cache: $e\n$cachedRes');
}
2024-05-08 05:03:49 -04:00
}
// ! exaggerated delay
2024-05-09 23:23:50 -04:00
// await Future.delayed(const Duration(seconds: 2));
final res = await api.libraries
2024-05-08 05:03:49 -04:00
.getPersonalized(libraryId: apiSettings.activeLibraryId!);
// debugPrint('personalizedView: ${res!.map((e) => e).toSet()}');
// save to cache
2024-09-06 15:10:00 -04:00
if (res != null) {
final newFile = await apiResponseCacheManager.putFile(
key,
utf8.encode(jsonEncode(res)),
fileExtension: 'json',
key: key,
);
_logger.fine('writing to cache: $newFile');
yield res;
} else {
_logger.warning('failed to fetch personalized view');
yield [];
}
2024-05-08 05:03:49 -04:00
}
// method to force refresh the view and ignore the cache
Future<void> forceRefresh() async {
// clear the cache
// TODO: find a better way to clear the cache for only personalized view key
2024-05-08 05:03:49 -04:00
return apiResponseCacheManager.emptyCache();
}
}
/// fetch continue listening audiobooks
@riverpod
FutureOr<GetUserSessionsResponse> fetchContinueListening(
2025-03-25 22:01:16 +05:30
Ref ref,
2024-05-08 05:03:49 -04:00
) async {
final api = ref.watch(authenticatedApiProvider);
final res = await api.me.getSessions();
// debugPrint(
// 'fetchContinueListening: ${res.sessions.map((e) => e.libraryItemId).toSet()}',
// );
return res!;
}
2024-06-17 01:33:56 -04:00
@riverpod
FutureOr<User> me(
2025-03-25 22:01:16 +05:30
Ref ref,
2024-06-17 01:33:56 -04:00
) async {
final api = ref.watch(authenticatedApiProvider);
final errorResponseHandler = ErrorResponseHandler();
final res = await api.me.getUser(
responseErrorHandler: errorResponseHandler.storeError,
);
if (res == null) {
_logger.severe(
'me failed, got response: ${errorResponseHandler.response.obfuscate()}',
);
throw StateError('me failed');
}
return res;
}
@riverpod
FutureOr<LoginResponse?> login(
2025-03-25 22:01:16 +05:30
Ref ref, {
AuthenticatedUser? user,
}) async {
if (user == null) {
// try to get the user from settings
final apiSettings = ref.watch(apiSettingsProvider);
user = apiSettings.activeUser;
if (user == null) {
_logger.severe('no active user to login');
return null;
}
_logger.fine('no user provided, using active user: ${user.obfuscate()}');
}
final api = ref.watch(audiobookshelfApiProvider(user.server.serverUrl));
api.token = user.authToken;
var errorResponseHandler = ErrorResponseHandler();
_logger.fine('logging in with authenticated api');
final res = await api.misc.authorize(
responseErrorHandler: errorResponseHandler.storeError,
);
if (res == null) {
_logger.severe(
'login failed, got response: ${errorResponseHandler.response.obfuscate()}',
);
return null;
}
_logger.fine('login response: ${res.obfuscate()}');
return res;
2024-06-17 01:33:56 -04:00
}