From 0df199852fd6c6202cfc119981ce4b42e3962783 Mon Sep 17 00:00:00 2001
From: comp500 <comp500@users.noreply.github.com>
Date: Fri, 23 Jun 2023 19:45:44 +0100
Subject: [PATCH] Attempt to redownload cached files when errors are found

---
 core/download.go | 23 ++++++++++++++++++-----
 1 file changed, 18 insertions(+), 5 deletions(-)

diff --git a/core/download.go b/core/download.go
index faff528..066d956 100644
--- a/core/download.go
+++ b/core/download.go
@@ -72,19 +72,21 @@ func (d *downloadSessionInternal) StartDownloads() chan CompletedDownload {
 			downloads <- found
 		}
 		for _, task := range d.downloadTasks {
+			warnings := make([]error, 0)
+
 			// Get handle for mod
 			cacheHandle := d.cacheIndex.GetHandleFromHash(task.hashFormat, task.hash)
 			if cacheHandle != nil {
 				download, err := reuseExistingFile(cacheHandle, d.hashesToObtain, task.mod)
 				if err != nil {
-					downloads <- CompletedDownload{
-						Error: err,
-						Mod:   task.mod,
-					}
+					// Remove handle and try again
+					cacheHandle.Remove()
+					cacheHandle = nil
+					warnings = append(warnings, fmt.Errorf("redownloading cached file: %w", err))
 				} else {
 					downloads <- download
+					continue
 				}
-				continue
 			}
 
 			download, err := downloadNewFile(&task, d.cacheFolder, d.hashesToObtain, &d.cacheIndex)
@@ -94,6 +96,7 @@ func (d *downloadSessionInternal) StartDownloads() chan CompletedDownload {
 					Mod:   task.mod,
 				}
 			} else {
+				download.Warnings = warnings
 				downloads <- download
 			}
 		}
@@ -538,6 +541,16 @@ func (h *CacheIndexHandle) UpdateIndex() (warnings []error) {
 	return
 }
 
+func (h *CacheIndexHandle) Remove() {
+	for hashFormat := range h.Hashes {
+		hashList := h.index.Hashes[hashFormat]
+		if h.hashIdx < len(hashList) {
+			h.index.Hashes[hashFormat] = slices.Delete(hashList, h.hashIdx, h.hashIdx+1)
+		}
+	}
+	return
+}
+
 func CreateDownloadSession(mods []*Mod, hashesToObtain []string) (DownloadSession, error) {
 	// Load cache index
 	cacheIndex := CacheIndex{Version: 1, Hashes: make(map[string][]string)}