From 787794ac9700e96fe586dfeec2908ce38bab4e30 Mon Sep 17 00:00:00 2001 From: The Magician Date: Tue, 21 May 2024 12:33:14 +0100 Subject: [PATCH] Move set import code to main.go --- sevenkeys/main.go | 51 ++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 46 insertions(+), 5 deletions(-) diff --git a/sevenkeys/main.go b/sevenkeys/main.go index 6dcc087..8233716 100644 --- a/sevenkeys/main.go +++ b/sevenkeys/main.go @@ -1,10 +1,15 @@ package main import ( + "database/sql" + "io" "log" + "net/http" "os" "sevenkeys/database" + "sevenkeys/database/operations" "sevenkeys/scryfall/methods" + "sevenkeys/scryfall/types" ) const CACHE_DIR string = "cache" @@ -34,23 +39,59 @@ func createCacheDirectories() error { return nil } +func importSets(db *sql.DB, sets []types.Set) error { + for _, set := range sets { + // We're only interested in paper cards, so skip importing + // any sets that were only released in a video game + if set.Digital { + continue + } + + log.Println("Importing " + set.Code) + err = operations.InsertOrUpdateSet(db, set) + if err != nil { + return err + } + + log.Println("Downloading logo for " + set.Code) + response, err := http.Get(set.IconSvgUri) + defer response.Body.Close() + if err != nil { + return err + } + + iconFilename := SET_ICON_CACHE_DIR + set.Code + SET_ICON_FILE_EXTENSION + iconFile, err := os.Create(iconFilename) + if err != nil { + return err + } + + io.Copy(iconFile, response.Body) + log.Println("Finished importing " + set.Code) + } +} + func main() { log.Println("Connecting to database...") db := database.GetDatabaseFromConfig("config.json") log.Println("Connected.") - log.Println("Downloading set data from Scryfall...") - sets, err := methods.GetSets() - check(err) - log.Println("Downloaded set data.") - log.Println("Creating cache directories...") err = createCacheDirectories() check(err) log.Println("Created cache directories.") + log.Println("Downloading set data from Scryfall...") + sets, err := methods.GetSets() + check(err) + log.Println("Downloaded set data.") + // Loop through sets, import set data into database and download icons // TODO: Only download icon if we don't already have the file + log.Println("Importing set data...") + err = importSets() + check(err) + log.Println("Imported sets.") // Check whether card data has been updated since last download // If yes, redownload and recache the bulk data