getBooksHistory method

Future<List<MediaItem>> getBooksHistory(
  1. {required AppModel appModel,
  2. required Language language,
  3. bool recursive = false}
)

Fetch JSON for all books in IndexedDB.

Implementation

Future<List<MediaItem>> getBooksHistory({
  required AppModel appModel,
  required Language language,
  bool recursive = false,
}) async {
  int port = getPortForLanguage(appModel.targetLanguage);

  List<MediaItem>? items;

  HeadlessInAppWebView webView = HeadlessInAppWebView(
    initialUrlRequest: URLRequest(
      url: Uri.parse('http://localhost:$port/'),
    ),
    onLoadStop: (controller, url) async {
      controller.evaluateJavascript(source: getHistoryJs);
    },
    onConsoleMessage: (controller, message) async {
      try {
        Map<String, dynamic> messageJson = jsonDecode(message.message);

        if (messageJson['messageType'] != null) {
          switch (messageJson['messageType']) {
            case 'history':
              try {
                items = getItemsFromJson(messageJson, port);
              } catch (error, stack) {
                items = [];
                debugPrint('$error');
                debugPrint('$stack');
              }
              break;
            case 'empty':
              if (!appModel.targetLanguage.preferVerticalReading) {
                await controller.evaluateJavascript(
                    source:
                        'javascript:window.localStorage.setItem("writingMode", "horizontal-tb")');
                await controller.evaluateJavascript(
                    source:
                        'javascript:window.localStorage.setItem("fontSize", 16)');
              } else {
                await controller.evaluateJavascript(
                    source:
                        'javascript:window.localStorage.setItem("fontSize", 24)');
              }

              items = [];
              break;
            case 'error':
              items = [];
              break;
          }
        }
      } on FormatException catch (_) {}
    },
  );

  try {
    await webView.run();
    while (items == null) {
      await Future.delayed(const Duration(milliseconds: 500));
    }
  } finally {
    await webView.dispose();
  }

  return items!;
}