prepareSubtitles method

  1. @override
Future<List<SubtitleItem>> prepareSubtitles(
  1. {required AppModel appModel,
  2. required WidgetRef ref,
  3. required MediaItem item}
)
override

Get the player controller to be used when a media item is loaded up,

Implementation

@override
Future<List<SubtitleItem>> prepareSubtitles({
  required AppModel appModel,
  required WidgetRef ref,
  required MediaItem item,
}) async {
  String videoId = VideoId(item.mediaIdentifier).value;
  List<String> subtitlesList = [...getSubtitleItems(videoId)!];
  List<String> metadataList = [...getSubtitleMetadata(videoId)!];

  String? targetLanguageItem;
  String? appLanguageItem;
  String? targetLanguageMeta;
  String? appLanguageMeta;
  int targetLanguageIndex = -1;
  int appLanguageIndex = -1;

  targetLanguageIndex = metadataList.indexWhere(
      (e) => e.contains('[${appModel.targetLanguage.languageCode}]'));
  appLanguageIndex = metadataList
      .indexWhere((e) => e.contains('[${appModel.appLocale.languageCode}]'));

  if (targetLanguageIndex != -1) {
    targetLanguageMeta = metadataList.removeAt(targetLanguageIndex);
    targetLanguageItem = subtitlesList.removeAt(targetLanguageIndex);
  }

  targetLanguageIndex = metadataList.indexWhere(
      (e) => e.contains('[${appModel.targetLanguage.languageCode}]'));
  appLanguageIndex = metadataList
      .indexWhere((e) => e.contains('[${appModel.appLocale.languageCode}]'));

  if (appLanguageIndex != -1 && targetLanguageIndex != appLanguageIndex) {
    appLanguageMeta = metadataList.removeAt(appLanguageIndex);
    appLanguageItem = subtitlesList.removeAt(appLanguageIndex);
  }

  subtitlesList = [
    if (targetLanguageItem != null) targetLanguageItem,
    if (appLanguageItem != null) appLanguageItem,
    ...subtitlesList,
  ];

  metadataList = [
    if (targetLanguageMeta != null) targetLanguageMeta,
    if (appLanguageMeta != null) appLanguageMeta,
    ...metadataList,
  ];

  return subtitlesList.mapIndexed((index, subtitles) {
    String metadata = metadataList[index];

    _subtitleControllerCache.putIfAbsent(
      subtitles,
      () => SubtitleController(
        provider: SubtitleProvider.fromString(
          data: subtitles,
          type: SubtitleType.vtt,
        ),
      ),
    );
    SubtitleController controller = _subtitleControllerCache[subtitles]!;

    return SubtitleItem(
      controller: controller,
      metadata: metadata,
      type: SubtitleItemType.webSubtitle,
    );
  }).toList();
}