downloadLibraries method

Future<void> downloadLibraries(
  1. VersionInfo versionInfo
)

Downloads all libraries required for the specified Minecraft version.

Iterates through the version's library list and downloads each one, reporting progress via callbacks.

versionInfo Information about the Minecraft version whose libraries should be downloaded.

Throws an exception if the library information is missing.

Implementation

Future<void> downloadLibraries(VersionInfo versionInfo) async {
  if (versionInfo.libraries == null) {
    throw Exception('Failed to get libraries info');
  }

  final librariesDir = getLibrariesDir();
  await ensureDirectory(librariesDir);

  final libraries = versionInfo.libraries!;
  final operationName = 'Downloading libraries';
  final totalLibraries = libraries.length;

  if (onOperationProgress != null) {
    onOperationProgress!(operationName, 0, totalLibraries, 0);
  }

  int completedLibraries = 0;
  int lastReportedPercentage = 0;

  for (final library in libraries) {
    final downloads = library.downloads;
    if (downloads == null) {
      completedLibraries++;
      continue;
    }

    final artifact = downloads.artifact;
    if (artifact == null) {
      completedLibraries++;
      continue;
    }

    final path = artifact.path;
    final url = artifact.url;
    final size = artifact.size;

    if (path == null || url == null) {
      completedLibraries++;
      continue;
    }

    final libraryPath = normalizePath(p.join(librariesDir, path));
    final libraryName = path.split('/').last;

    try {
      await downloadFile(
        url,
        libraryPath,
        expectedSize: size,
        resourceName: libraryName,
      );
      debugPrint('Downloaded library: $path');

      completedLibraries++;

      if (onOperationProgress != null) {
        final percentage = (completedLibraries / totalLibraries) * 100;
        final reportPercentage =
            (percentage ~/ progressReportRate) * progressReportRate;

        if (reportPercentage > lastReportedPercentage) {
          lastReportedPercentage = reportPercentage;
          onOperationProgress!(
            operationName,
            completedLibraries,
            totalLibraries,
            max(0.0, min(percentage, 100.0)),
          );
        }
      }
    } catch (e) {
      debugPrint('Failed to download library: $url - $e');
      completedLibraries++;
    }
  }

  if (onOperationProgress != null) {
    onOperationProgress!(
      operationName,
      totalLibraries,
      totalLibraries,
      100.0,
    );
  }

  _librariesCompleter.complete();
}