From 5616b515128739f965b5c86bdb758caa34ac0d50 Mon Sep 17 00:00:00 2001 From: Sebastian Date: Wed, 31 Jul 2024 21:57:02 +0200 Subject: [PATCH] Added check if game not found --- pkg/db/game.go | 12 +++++++----- pkg/server/music.go | 10 ++++++++-- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/pkg/db/game.go b/pkg/db/game.go index 07ab7e5..581e358 100644 --- a/pkg/db/game.go +++ b/pkg/db/game.go @@ -2,11 +2,13 @@ package db import ( "context" + "errors" "fmt" - "github.com/jackc/pgtype" "music-server/pkg/models" "os" "time" + + "github.com/jackc/pgtype" ) func GetGameName(gameId int) string { @@ -20,17 +22,17 @@ func GetGameName(gameId int) string { return gameName } -func GetGameById(gameId int) models.GameData { +func GetGameById(gameId int) (models.GameData, error) { var id, timesPlayed int var numberOfSongs pgtype.Int4 var gameName, path string var added, deleted, lastChanged, lastPlayed pgtype.Timestamp err := pool.QueryRow(context.Background(), "SELECT id, game_name, added, deleted, last_changed, path, times_played, last_played, number_of_songs "+ - "FROM game WHERE id = $1", gameId).Scan(&id, &gameName, &added, &deleted, &lastChanged, &path, ×Played, &lastPlayed, &numberOfSongs) + "FROM game WHERE id = $1 AND deleted IS NULL", gameId).Scan(&id, &gameName, &added, &deleted, &lastChanged, &path, ×Played, &lastPlayed, &numberOfSongs) if err != nil { _, _ = fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err) - return models.GameData{} + return models.GameData{}, errors.New("Game not found") } return models.GameData{ Id: id, @@ -42,7 +44,7 @@ func GetGameById(gameId int) models.GameData { TimesPlayed: timesPlayed, LastPlayed: lastPlayed.Time, NumberOfSongs: numberOfSongs.Int, - } + }, nil } func SetGameDeletionDate() { diff --git a/pkg/server/music.go b/pkg/server/music.go index b541faa..f043992 100644 --- a/pkg/server/music.go +++ b/pkg/server/music.go @@ -72,7 +72,7 @@ func GetRandomSongLowChance() string { } } } - song := getSongFromList(games) + song := getSongFromList(listOfGames) lastFetched = song return song.Path @@ -93,7 +93,13 @@ func GetRandomSongClassic() string { var song models.SongData for !songFound { song = listOfAllSongs[rand.Intn(len(listOfAllSongs))] - gameData := db.GetGameById(song.GameId) + gameData, err := db.GetGameById(song.GameId) + + if err != nil { + db.RemoveBrokenSong(song) + log.Println("Song not found, song '" + song.SongName + "' deleted from game '" + gameData.GameName + "' FileName: " + song.FileName) + continue + } //Check if file exists and open openFile, err := os.Open(song.Path)