getItemsFromJson method

List<MediaItem> getItemsFromJson(
  1. Map<String, dynamic> json,
  2. int port
)

Fetch the list of history items given JSON from IndexedDB.

Implementation

List<MediaItem> getItemsFromJson(Map<String, dynamic> json, int port) {
  List<Map<String, dynamic>> bookmarks =
      List<Map<String, dynamic>>.from(jsonDecode(json['bookmark']));
  List<Map<String, dynamic>> datas =
      List<Map<String, dynamic>>.from(jsonDecode(json['data']));
  Map<int, Map<String, dynamic>> bookmarksById =
      Map<int, Map<String, dynamic>>.fromEntries(
          bookmarks.map((e) => MapEntry(e['dataId'] as int, e)));

  List<MapEntry<int, MediaItem>> itemsById = datas.mapIndexed((index, data) {
    int position = 0;
    int duration = 1;

    Map<String, dynamic>? bookmark = bookmarksById[data['id']];

    if (bookmark != null) {
      position = bookmark['exploredCharCount'] as int;
      double progress = double.parse(bookmark['progress'].toString());
      if (progress == 0) {
        duration = 1;
      } else {
        duration = position ~/ progress;
      }
    }

    String id = data['id'].toString();
    String title = data['title'] as String? ?? ' ';
    String? base64Image;
    try {
      Uri.parse(data['coverImage']);
      base64Image = data['coverImage'];
    } catch (e) {
      base64Image = null;
    }

    return MapEntry(
      index,
      MediaItem(
        mediaIdentifier: 'http://localhost:$port/b.html?id=$id&?title=$title',
        title: title,
        base64Image: base64Image,
        mediaTypeIdentifier: ReaderTtuSource.instance.mediaType.uniqueKey,
        mediaSourceIdentifier: ReaderTtuSource.instance.uniqueKey,
        position: position,
        duration: duration,
        canDelete: false,
        canEdit: true,
      ),
    );
  }).toList();

  List<int> lastOpens = datas.mapIndexed((index, data) {
    return data['lastBookOpen'] as int? ?? 0;
  }).toList();

  itemsById.sort((a, b) => lastOpens[b.key].compareTo(lastOpens[a.key]));
  List<MediaItem> itemsByLastOpened = itemsById.map((e) => e.value).toList();

  return itemsByLastOpened;
}