package moe.nekojimi.friendcloud; import moe.nekojimi.friendcloud.objects.NetworkFile; import moe.nekojimi.friendcloud.tasks.FileDownloadTask; import java.util.*; import java.util.concurrent.CompletableFuture; public class DownloadManager { private static DownloadManager instance = null; public static DownloadManager getInstance() { if(instance == null) instance = new DownloadManager(); return instance; } private DownloadManager() { } public Map> activeDownloads = new HashMap<>(); public CompletableFuture downloadPieces(NetworkFile file, SortedSet pieces) { cullCompletedDownloads(); Set> tasksToWaitFor = new HashSet<>(); SortedSet inactivePieces = new TreeSet<>(pieces); for (Map.Entry> e : activeDownloads.entrySet()) { if (!Collections.disjoint(inactivePieces, e.getKey().getMissingPieceIndices())) { inactivePieces.removeAll(e.getKey().getMissingPieceIndices()); tasksToWaitFor.add(e.getValue()); } } if (!inactivePieces.isEmpty()) { FileDownloadTask downloadTask = new FileDownloadTask(file, Main.getInstance().getConnectionManager(), pieces); CompletableFuture completableFuture = CompletableFuture.runAsync(downloadTask,Main.getInstance().getExecutor()); activeDownloads.put(downloadTask,completableFuture); return completableFuture; } return CompletableFuture.allOf(tasksToWaitFor.toArray(new CompletableFuture[0])); } private void cullCompletedDownloads() { Set toRemove = new HashSet<>(); for (Map.Entry> e : activeDownloads.entrySet()) { if (e.getValue().isDone()) toRemove.add(e.getKey()); } for (FileDownloadTask t: toRemove) activeDownloads.remove(t); } public Map> getActiveDownloads() { return Collections.unmodifiableMap(activeDownloads); } }