feat: enhance logging in audiobook player and provider for better debugging

This commit is contained in:
Dr-Blank 2024-10-03 04:31:50 -04:00
parent 2545988434
commit f6cfff5413
No known key found for this signature in database
GPG key ID: 7452CC63F210A266
5 changed files with 39 additions and 40 deletions

View file

@ -17,33 +17,32 @@ final _logger = Logger('AudiobookPlayer');
/// returns the sum of the duration of all the previous tracks before the [index] /// returns the sum of the duration of all the previous tracks before the [index]
Duration sumOfTracks(BookExpanded book, int? index) { Duration sumOfTracks(BookExpanded book, int? index) {
_logger.fine('Calculating sum of tracks for index: $index');
// return 0 if index is less than 0 // return 0 if index is less than 0
if (index == null || index < 0) { if (index == null || index < 0) {
_logger.warning('Index is null or less than 0, returning 0');
return Duration.zero; return Duration.zero;
} }
return book.tracks.sublist(0, index).fold<Duration>(Duration.zero, final total = book.tracks.sublist(0, index).fold<Duration>(
(previousValue, element) { Duration.zero,
return previousValue + element.duration; (previousValue, element) => previousValue + element.duration,
}); );
_logger.fine('Sum of tracks for index: $index is $total');
return total;
} }
/// returns the [AudioTrack] to play based on the [position] in the [book] /// returns the [AudioTrack] to play based on the [position] in the [book]
AudioTrack getTrackToPlay(BookExpanded book, Duration position) { AudioTrack getTrackToPlay(BookExpanded book, Duration position) {
// var totalDuration = Duration.zero; _logger.fine('Getting track to play for position: $position');
// for (var track in book.tracks) { final track = book.tracks.firstWhere(
// totalDuration += track.duration;
// if (totalDuration >= position) {
// return track;
// }
// }
// return book.tracks.last;
return book.tracks.firstWhere(
(element) { (element) {
return element.startOffset <= position && return element.startOffset <= position &&
(element.startOffset + element.duration) >= position; (element.startOffset + element.duration) >= position;
}, },
orElse: () => book.tracks.last, orElse: () => book.tracks.last,
); );
_logger.fine('Track to play for position: $position is $track');
return track;
} }
/// will manage the audio player instance /// will manage the audio player instance
@ -51,6 +50,7 @@ class AudiobookPlayer extends AudioPlayer {
// constructor which takes in the BookExpanded object // constructor which takes in the BookExpanded object
AudiobookPlayer(this.token, this.baseUrl) : super() { AudiobookPlayer(this.token, this.baseUrl) : super() {
// set the source of the player to the first track in the book // set the source of the player to the first track in the book
_logger.config('Setting up audiobook player');
} }
/// the [BookExpanded] being played /// the [BookExpanded] being played
@ -85,20 +85,23 @@ class AudiobookPlayer extends AudioPlayer {
List<Uri>? downloadedUris, List<Uri>? downloadedUris,
Uri? artworkUri, Uri? artworkUri,
}) async { }) async {
_logger.finer(
'Initial position: $initialPosition, Downloaded URIs: $downloadedUris',
);
final appSettings = loadOrCreateAppSettings(); final appSettings = loadOrCreateAppSettings();
// if the book is null, stop the player
if (book == null) { if (book == null) {
_book = null; _book = null;
_logger.info('Book is null, stopping player'); _logger.info('Book is null, stopping player');
return stop(); return stop();
} }
// see if the book is the same as the current book
if (_book == book) { if (_book == book) {
_logger.info('Book is the same, doing nothing'); _logger.info('Book is the same, doing nothing');
return; return;
} }
// first stop the player and clear the source _logger.info('Setting source for book: $book');
_logger.fine('Stopping player');
await stop(); await stop();
_book = book; _book = book;
@ -115,6 +118,7 @@ class AudiobookPlayer extends AudioPlayer {
? initialPosition - trackToPlay.startOffset ? initialPosition - trackToPlay.startOffset
: null; : null;
_logger.finer('Setting audioSource');
await setAudioSource( await setAudioSource(
preload: preload, preload: preload,
initialIndex: initialIndex, initialIndex: initialIndex,
@ -146,7 +150,7 @@ class AudiobookPlayer extends AudioPlayer {
}).toList(), }).toList(),
), ),
).catchError((error) { ).catchError((error) {
_logger.shout('Error: $error'); _logger.shout('Error in setting audio source: $error');
}); });
} }
@ -154,7 +158,7 @@ class AudiobookPlayer extends AudioPlayer {
Future<void> togglePlayPause() { Future<void> togglePlayPause() {
// check if book is set // check if book is set
if (_book == null) { if (_book == null) {
throw StateError('No book is set'); _logger.warning('No book is set, not toggling play/pause');
} }
// TODO refactor this to cover all the states // TODO refactor this to cover all the states
@ -170,9 +174,11 @@ class AudiobookPlayer extends AudioPlayer {
@override @override
Future<void> seek(Duration? positionInBook, {int? index}) async { Future<void> seek(Duration? positionInBook, {int? index}) async {
if (_book == null) { if (_book == null) {
_logger.warning('No book is set, not seeking');
return; return;
} }
if (positionInBook == null) { if (positionInBook == null) {
_logger.warning('Position given is null, not seeking');
return; return;
} }
final tracks = _book!.tracks; final tracks = _book!.tracks;

View file

@ -1,21 +1,11 @@
import 'package:logging/logging.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:vaani/api/api_provider.dart'; import 'package:vaani/api/api_provider.dart';
import 'package:vaani/features/player/core/audiobook_player.dart' import 'package:vaani/features/player/core/audiobook_player.dart' as core;
as core;
part 'audiobook_player.g.dart'; part 'audiobook_player.g.dart';
// @Riverpod(keepAlive: true) final _logger = Logger('AudiobookPlayerProvider');
// core.AudiobookPlayer audiobookPlayer(
// AudiobookPlayerRef ref,
// ) {
// final api = ref.watch(authenticatedApiProvider);
// final player = core.AudiobookPlayer(api.token!, api.baseUrl);
// ref.onDispose(player.dispose);
// return player;
// }
const playerId = 'audiobook_player'; const playerId = 'audiobook_player';
@ -32,6 +22,7 @@ class SimpleAudiobookPlayer extends _$SimpleAudiobookPlayer {
); );
ref.onDispose(player.dispose); ref.onDispose(player.dispose);
_logger.finer('created simple player');
return player; return player;
} }
@ -47,18 +38,16 @@ class AudiobookPlayer extends _$AudiobookPlayer {
// bind notify listeners to the player // bind notify listeners to the player
player.playerStateStream.listen((_) { player.playerStateStream.listen((_) {
notifyListeners(); ref.notifyListeners();
}); });
_logger.finer('created player');
return player; return player;
} }
void notifyListeners() {
ref.notifyListeners();
}
Future<void> setSpeed(double speed) async { Future<void> setSpeed(double speed) async {
await state.setSpeed(speed); await state.setSpeed(speed);
notifyListeners(); ref.notifyListeners();
} }
} }

View file

@ -7,7 +7,7 @@ part of 'audiobook_player.dart';
// ************************************************************************** // **************************************************************************
String _$simpleAudiobookPlayerHash() => String _$simpleAudiobookPlayerHash() =>
r'9e11ed2791d35e308f8cbe61a79a45cf51466ebb'; r'5e94bbff4314adceb5affa704fc4d079d4016afa';
/// Simple because it doesn't rebuild when the player state changes /// Simple because it doesn't rebuild when the player state changes
/// it only rebuilds when the token changes /// it only rebuilds when the token changes
@ -26,7 +26,7 @@ final simpleAudiobookPlayerProvider =
); );
typedef _$SimpleAudiobookPlayer = Notifier<core.AudiobookPlayer>; typedef _$SimpleAudiobookPlayer = Notifier<core.AudiobookPlayer>;
String _$audiobookPlayerHash() => r'44394b1dbbf85eb19ef1f693717e8cbc15b768e5'; String _$audiobookPlayerHash() => r'0f180308067486896fec6a65a6afb0e6686ac4a0';
/// See also [AudiobookPlayer]. /// See also [AudiobookPlayer].
@ProviderFor(AudiobookPlayer) @ProviderFor(AudiobookPlayer)

View file

@ -1,3 +1,4 @@
import 'package:logging/logging.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:shelfsdk/audiobookshelf_api.dart'; import 'package:shelfsdk/audiobookshelf_api.dart';
import 'package:vaani/features/player/providers/audiobook_player.dart'; import 'package:vaani/features/player/providers/audiobook_player.dart';
@ -5,12 +6,15 @@ import 'package:vaani/shared/extensions/model_conversions.dart';
part 'currently_playing_provider.g.dart'; part 'currently_playing_provider.g.dart';
final _logger = Logger('CurrentlyPlayingProvider');
@riverpod @riverpod
BookExpanded? currentlyPlayingBook(CurrentlyPlayingBookRef ref) { BookExpanded? currentlyPlayingBook(CurrentlyPlayingBookRef ref) {
try { try {
final player = ref.watch(audiobookPlayerProvider); final player = ref.watch(audiobookPlayerProvider);
return player.book; return player.book;
} catch (e) { } catch (e) {
_logger.warning('Error getting currently playing book: $e');
return null; return null;
} }
} }

View file

@ -7,7 +7,7 @@ part of 'currently_playing_provider.dart';
// ************************************************************************** // **************************************************************************
String _$currentlyPlayingBookHash() => String _$currentlyPlayingBookHash() =>
r'52334c7b4d68fd498a2a00208d8d7f1ba0085237'; r'7440b0d54cb364f66e704783652e8f1490ae90e0';
/// See also [currentlyPlayingBook]. /// See also [currentlyPlayingBook].
@ProviderFor(currentlyPlayingBook) @ProviderFor(currentlyPlayingBook)