Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart
15.0 KB
Raw Blame
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
import 'api_service.dart';

/// File extension (with leading dot) for an ABS ebookFile, or '' if unknown.
/// Prefers the explicit `ebookFormat` field over the filename extension so a
/// mis-named file can't be treated as the wrong format downstream (foliate-js
/// tells CBZ and EPUB apart purely by the served filename).
String ebookExtFromFile(Map<String, dynamic> ebookFile) {
  final fmt = (ebookFile['ebookFormat'] as String?)?.toLowerCase();
  if (fmt != null && fmt.isNotEmpty) return '.$fmt';
  final name = (ebookFile['metadata'] as Map<String, dynamic>?)?['filename'] as String?
      ?? ebookFile['name'] as String?
      ?? '';
  return name.contains('.') ? name.substring(name.lastIndexOf('.')).toLowerCase() : '';
}

/// Formats the in-app readers can open. EPUB uses the full reader, PDF the
/// dedicated viewer, foliate-js covers MOBI/AZW3, and comics get the comic
/// reader. A CBZ opens on the phone; CBR (RAR) and CB7 (7-Zip) need a server
/// that hands out the pages (BookOrbit), so on their own they stay
/// download-only.
const foliateEbookFormats = {'mobi', 'azw3'};
const comicEbookFormats = {'cbz', 'cbr', 'cb7'};
const readableEbookFormats = {'epub', 'pdf', 'cbz', ...foliateEbookFormats};
const allEbookFormats = {...readableEbookFormats, 'cbr', 'cb7'};

/// The ebook to save to the device: the plain EPUB when a read along copy,
/// which carries the whole audiobook inside it, is the one opened for reading.
Map<String, dynamic>? exportEbookFile(Map<String, dynamic>? item) {
  final media = item?['media'] as Map<String, dynamic>?;
  final plain = (media?['readAlongEpub'] as Map?)?['plainEbookFile'];
  return plain is Map<String, dynamic> ? plain : resolveEbookFile(item);
}

/// The ebook to use for a library item: the server's primary (media.ebookFile)
/// when set, otherwise the best supplementary ebook from libraryFiles - epub
/// first (mirroring the server's own primary pick), then the first readable
/// format, then any ebook file (a CBR can still be saved to device).
/// Audiobooks-only libraries mark every ebook supplementary and never set a
/// primary, so without this fallback those books always showed "no ebook".
Map<String, dynamic>? resolveEbookFile(Map<String, dynamic>? item) {
  if (item == null) return null;
  final media = item['media'] as Map<String, dynamic>?;
  final primary = media?['ebookFile'] as Map<String, dynamic>?;
  if (primary != null) return primary;
  Map<String, dynamic>? firstReadable;
  Map<String, dynamic>? firstEbook;
  for (final f in (item['libraryFiles'] as List<dynamic>? ?? const [])) {
    if (f is! Map<String, dynamic>) continue;
    final ext = ebookExtFromFile(f);
    final fmt = ext.startsWith('.') ? ext.substring(1) : ext;
    if (!allEbookFormats.contains(fmt)) continue;
    if (fmt == 'epub') return f;
    if (readableEbookFormats.contains(fmt)) firstReadable ??= f;
    firstEbook ??= f;
  }
  return firstReadable ?? firstEbook;
}

/// Whether a library item comes with an ebook, from the full item or from
/// the minified list form, which only carries the format.
bool hasEbookFile(Map<String, dynamic>? item) {
  if (item == null) return false;
  if (resolveEbookFile(item) != null) return true;
  final media = item['media'] as Map<String, dynamic>?;
  final fmt = media?['ebookFormat'];
  return fmt is String && fmt.isNotEmpty;
}

Directory? _ebookCacheDirHandle;

Future<Directory> _ebookCacheDir() async {
  final base = await getApplicationSupportDirectory();
  final dir = Directory('${base.path}/ebook_cache');
  if (!dir.existsSync()) dir.createSync(recursive: true);
  _ebookCacheDirHandle = dir;
  return dir;
}

/// Warms the synchronous directory handle so [cachedEbookBytesSync] can see
/// cached ebooks from sync code (e.g. download size accounting).
Future<void> hydrateEbookCacheDir() => _ebookCacheDir();

/// Size in bytes of the cached ebook for [itemId], or 0 when there is none or
/// the directory handle hasn't been warmed yet.
int cachedEbookBytesSync(String itemId) {
  final dir = _ebookCacheDirHandle;
  if (dir == null || !dir.existsSync()) return 0;
  try {
    for (final f in dir.listSync()) {
      if (f is File && f.uri.pathSegments.last.startsWith('$itemId.')) {
        return f.lengthSync();
      }
    }
  } catch (_) {}
  return 0;
}

/// Synthesizes an ebookFile map from a cached file on disk, so a downloaded
/// book can open its ebook offline even when no ebook metadata survived (old
/// downloads persisted before the trimmed libraryItem was kept). The format
/// comes from the cached file's extension, which [ebookCacheFileFor] derived
/// from the real ebookFile at download time, so the reader routing (EPUB vs
/// PDF vs foliate) stays correct. When several formats are cached for one item
/// the EPUB wins, mirroring [resolveEbookFile]'s pick (and transcript
/// correction can only read EPUBs). Returns null when nothing is cached.
Future<Map<String, dynamic>?> cachedEbookFileFor(String itemId) async {
  try {
    final dir = await _ebookCacheDir();
    Map<String, dynamic>? first;
    for (final f in dir.listSync()) {
      if (f is! File) continue;
      final name = f.uri.pathSegments.last;
      if (!name.startsWith('$itemId.')) continue;
      if (await f.length() <= 0) continue;
      final ext = name.substring(name.lastIndexOf('.') + 1).toLowerCase();
      if (!allEbookFormats.contains(ext)) continue;
      final entry = {
        'ebookFormat': ext,
        'metadata': {'filename': name},
      };
      if (ext == 'epub') return entry;
      first ??= entry;
    }
    return first;
  } catch (_) {}
  return null;
}

/// Item ids that have an ebook file in the cache.
Future<List<String>> cachedEbookItemIds() async {
  final ids = <String>{};
  try {
    final dir = await _ebookCacheDir();
    for (final f in dir.listSync()) {
      if (f is! File) continue;
      final name = f.uri.pathSegments.last;
      final dot = name.lastIndexOf('.');
      if (dot <= 0) continue;
      final ext = name.substring(dot + 1).toLowerCase();
      if (!allEbookFormats.contains(ext)) continue;
      ids.add(name.substring(0, dot));
    }
  } catch (_) {}
  return ids.toList();
}

/// Cover kept beside a cached ebook for the offline lists. Named so neither
/// cachedEbookFileFor nor cachedEbookBytesSync can take it for the book.
Future<File> ebookCoverCacheFile(String itemId) async {
  final dir = await _ebookCacheDir();
  return File('${dir.path}/cover_$itemId.jpg');
}

Future<void> deleteCachedEbookCover(String itemId) async {
  try {
    final f = await ebookCoverCacheFile(itemId);
    if (f.existsSync()) await f.delete();
  } catch (_) {}
}

/// Persistent cache path for an item's ebook, keyed by itemId so it's stable
/// across sessions. Lives in app support (not temp, not iCloud-backed docs) so
/// once an ebook is here it stays available offline.
Future<File> ebookCacheFileFor(String itemId, Map<String, dynamic> ebookFile) async {
  final dir = await _ebookCacheDir();
  return File('${dir.path}/$itemId${ebookExtFromFile(ebookFile)}');
}

/// The location index epub.js builds by walking the whole book, kept beside
/// the cached epub so the walk happens once per file instead of on every
/// open. Tagged with the epub's byte size so a re-downloaded file rebuilds
/// it. Named `<item>.<ext>.locations.json`, so deleteCachedEbook sweeps it
/// with the book and cachedEbookFileFor never mistakes it for one.
File _locationsFileFor(File epub) => File('${epub.path}.locations.json');

Future<String?> loadCachedLocations(File epub) async {
  try {
    final f = _locationsFileFor(epub);
    if (!f.existsSync()) return null;
    final decoded = jsonDecode(await f.readAsString());
    if (decoded is! Map) return null;
    if (decoded['size'] != await epub.length()) return null;
    final locations = decoded['locations'];
    return locations is String && locations.isNotEmpty ? locations : null;
  } catch (_) {
    return null;
  }
}

Future<void> saveCachedLocations(File epub, String locations) async {
  try {
    await _locationsFileFor(epub).writeAsString(
      jsonEncode({'size': await epub.length(), 'locations': locations}),
    );
  } catch (_) {}
}

/// Drops the location index kept beside [epub], for a copy that changed.
Future<void> dropCachedLocations(File epub) async {
  try {
    final f = _locationsFileFor(epub);
    if (f.existsSync()) await f.delete();
  } catch (_) {}
}

/// What identifies the server's copy of an ebook, so a cached copy can tell
/// when the server has rewritten it (BookOrbit writing metadata back, a file
/// replaced on disk). Null when the item says nothing about it.
String? ebookFileVersion(Map<String, dynamic> ebookFile) {
  final v = ebookFile['version'];
  if (v is String && v.isNotEmpty) return v;
  final meta = ebookFile['metadata'] as Map?;
  final mtime = meta?['mtimeMs'];
  if (mtime is num && mtime > 0) return '${mtime.toInt()}:${meta?['size'] ?? ''}';
  return null;
}

File _versionFileFor(File cached) => File('${cached.path}.version');

/// Whether [cached] is still the server's current copy. One cached before
/// versions were kept takes the current version as its own.
Future<bool> cachedEbookIsCurrent(File cached, Map<String, dynamic> ebookFile) async {
  final version = ebookFileVersion(ebookFile);
  if (version == null) return true;
  try {
    final f = _versionFileFor(cached);
    if (!f.existsSync()) {
      await f.writeAsString(version);
      return true;
    }
    return await f.readAsString() == version;
  } catch (_) {
    return true;
  }
}

/// Notes which server copy [cached] is, once it has been fetched.
Future<void> rememberEbookVersion(File cached, Map<String, dynamic> ebookFile) async {
  final version = ebookFileVersion(ebookFile);
  if (version == null) return;
  try {
    await _versionFileFor(cached).writeAsString(version);
  } catch (_) {}
}

/// True if the item's ebook is already cached on disk (readable offline).
Future<bool> isEbookCached(String itemId, Map<String, dynamic> ebookFile) async {
  final f = await ebookCacheFileFor(itemId, ebookFile);
  return f.existsSync() && await f.length() > 0;
}

/// Returns the cached ebook, downloading it if not already present. The download
/// is atomic (written to a .part file then renamed) so an interrupted transfer
/// never leaves a half-written file that looks complete. Once fetched the ebook
/// stays available offline.
Future<File> fetchEbookToCache(
  ApiService api,
  String itemId,
  Map<String, dynamic> ebookFile,
  String title,
) async {
  final cachedFile = await ebookCacheFileFor(itemId, ebookFile);
  if (cachedFile.existsSync() && await cachedFile.length() > 0) {
    if (await cachedEbookIsCurrent(cachedFile, ebookFile)) {
      debugPrint('[EbookCache] cache hit item=$itemId bytes=${await cachedFile.length()}');
      return cachedFile;
    }
    debugPrint('[EbookCache] item=$itemId changed on the server - fetching the new copy');
    try {
      final fresh = await _downloadEbook(api, itemId, ebookFile, cachedFile);
      await dropCachedLocations(fresh);
      return fresh;
    } catch (e) {
      debugPrint('[EbookCache] item=$itemId new copy failed, keeping the old one: $e');
      return cachedFile;
    }
  }
  return _downloadEbook(api, itemId, ebookFile, cachedFile);
}

Future<File> _downloadEbook(
  ApiService api,
  String itemId,
  Map<String, dynamic> ebookFile,
  File cachedFile,
) async {
  final ino = ebookFile['ino'] as String?;
  if (ino == null) throw Exception('No ebook file found');

  final cleanBase = api.baseUrl.endsWith('/')
      ? api.baseUrl.substring(0, api.baseUrl.length - 1)
      : api.baseUrl;
  // Auth travels both ways: the Authorization header (re-attached across the
  // manual redirect hops below) plus `?token=` in the URL, because some
  // reverse proxies strip the header - the same reason audio file downloads
  // use the token form (see ApiService.buildFileUrl).
  final url = api.isBookOrbit
      ? api.buildReaderEbookUrl(itemId, ino)
      : '$cleanBase/api/items/$itemId/file/$ino?token=${api.token}';

  debugPrint('[EbookCache] downloading item=$itemId path=/api/items/$itemId/file/$ino');
  final startedAt = DateTime.now();
  final partFile = File('${cachedFile.path}.part');
  final request = http.Request('GET', Uri.parse(url));
  request.followRedirects = false;
  api.mediaHeaders.forEach((k, v) => request.headers[k] = v);
  final client = http.Client();
  try {
    var response = await client.send(request);
    var redirects = 0;
    while ([301, 302, 303, 307, 308].contains(response.statusCode) && redirects < 5) {
      final location = response.headers['location'];
      if (location == null) break;
      final redirectUrl = Uri.parse(url).resolve(location);
      final rReq = http.Request('GET', redirectUrl);
      api.mediaHeaders.forEach((k, v) => rReq.headers[k] = v);
      rReq.followRedirects = false;
      response = await client.send(rReq);
      redirects++;
    }
    if (response.statusCode != 200) {
      throw Exception('Failed to download ebook (${response.statusCode})');
    }
    final ct = response.headers['content-type'] ?? '';
    if (ct.contains('text/html')) throw Exception('Server returned an error page');
    final total = response.contentLength ?? -1;
    debugPrint('[EbookCache] receiving item=$itemId bytes=${total < 0 ? 'unknown' : total}');
    final sink = partFile.openWrite();
    var received = 0;
    var logged = 0;
    try {
      // A stalled transfer used to sit forever with the reader spinning.
      await sink.addStream(response.stream.timeout(const Duration(seconds: 60)).map((chunk) {
        received += chunk.length;
        if (received - logged >= 50 * 1024 * 1024) {
          logged = received;
          debugPrint('[EbookCache] item=$itemId received $received of ${total < 0 ? '?' : total} bytes');
        }
        return chunk;
      }));
    } on TimeoutException {
      debugPrint('[EbookCache] item=$itemId stalled after $received bytes');
      throw Exception('The ebook download stopped responding');
    } finally {
      await sink.close();
    }
    if (cachedFile.existsSync()) await cachedFile.delete();
    await partFile.rename(cachedFile.path);
    await rememberEbookVersion(cachedFile, ebookFile);
    final secs = DateTime.now().difference(startedAt).inMilliseconds / 1000.0;
    debugPrint('[EbookCache] downloaded item=$itemId bytes=${await cachedFile.length()} in ${secs}s');
  } finally {
    client.close();
    if (partFile.existsSync()) {
      try { await partFile.delete(); } catch (_) {}
    }
  }
  return cachedFile;
}

/// Removes any cached ebook for [itemId] (used when a download is removed).
Future<void> deleteCachedEbook(String itemId) async {
  try {
    final dir = await _ebookCacheDir();
    if (!dir.existsSync()) return;
    for (final f in dir.listSync()) {
      if (f is! File) continue;
      final name = f.uri.pathSegments.last;
      if (name == itemId ||
          name.startsWith('$itemId.') ||
          name == 'cover_$itemId.jpg') {
        try { await f.delete(); } catch (_) {}
      }
    }
  } catch (_) {}
}