Changed the structure of the whole application, should be no changes to functionality.

This commit is contained in:
2021-12-05 11:18:48 +01:00
parent 0a73134381
commit e1de6f0f76
28 changed files with 935 additions and 1105 deletions

76
pkg/server/index.go Normal file
View File

@@ -0,0 +1,76 @@
package server
import (
"music-server/pkg/db"
"music-server/pkg/models"
)
func GetVersionHistory() models.VersionData {
db.Testf()
data := models.VersionData{Version: "2.2.0",
Changelog: "Changed the structure of the whole application, should be no changes to functionality.",
History: []models.VersionData{
{
Version: "2.1.4",
Changelog: "Game list should now be sorted, a new endpoint with the game list in random order have been added.",
},
{
Version: "2.1.3",
Changelog: "Added a check to see if song exists before returning it, if not a new song will be picked up.",
},
{
Version: "2.1.2",
Changelog: "Added test server to swagger file.",
},
{
Version: "2.1.1",
Changelog: "Fixed bug where wrong song was showed as currently played.",
},
{
Version: "2.1.0",
Changelog: "Added /addQue to add the last received song to the songQue. " +
"Changed /rand and /rand/low to not add song to the que. " +
"Changed /next to not call /rand when the end of the que is reached, instead the last song in the que will be resent.",
},
{
Version: "2.0.3",
Changelog: "Another small change that should fix the caching problem.",
},
{
Version: "2.0.2",
Changelog: "Hopefully fixed the caching problem with random.",
},
{
Version: "2.0.1",
Changelog: "Fixed CORS",
},
{
Version: "2.0.0",
Changelog: "Rebuilt the application in Go.",
},
{
Version: "1.2.0",
Changelog: "Made the /sync endpoint async. " +
"Fixed bug where the game list wasn't reloaded when using /reset. " +
"Fixed bug where the songNo showed in the list didn't match what should be sent.",
},
{
Version: "1.1.0",
Changelog: "Added sync endpoint, don't really trust it to 100%, would say beta. " +
"Fixed bug with /next after /previous. Added /reset endpoint. " +
"Added some info more to /info and /list.",
},
{
Version: "1.0.0",
Changelog: "Added swagger documentation. Created version 1.0.",
},
{
Version: "0.5.5",
Changelog: "Added increase played endpoint.",
},
},
}
return data
}

233
pkg/server/music.go Normal file
View File

@@ -0,0 +1,233 @@
package server
import (
"io/ioutil"
"log"
"math/rand"
"music-server/pkg/db"
"music-server/pkg/models"
"os"
"strconv"
"time"
)
var currentSong = -1
var games []models.GameData
var songQue []models.SongData
var lastFetched models.SongData
func GetSoundCheckSong() string {
Reset()
files, err := ioutil.ReadDir("songs")
if err != nil {
log.Fatal(err)
}
fileInfo := files[rand.Intn(len(files))]
return "songs/" + fileInfo.Name()
}
func Reset() {
songQue = nil
currentSong = -1
games = db.FindAllGames()
}
func AddLatestToQue() {
if lastFetched.Path != "" {
currentSong = len(songQue)
songQue = append(songQue, lastFetched)
lastFetched = models.SongData{}
}
}
func GetRandomSong() string {
if games == nil || len(games) == 0 {
games = db.FindAllGames()
}
song := getSongFromList(games)
lastFetched = song
return song.Path
}
func GetRandomSongLowChance() string {
gameList := db.FindAllGames()
var listOfGames []models.GameData
var averagePlayed = getAveragePlayed(gameList)
for _, data := range gameList {
var timesToAdd = averagePlayed - data.TimesPlayed
if timesToAdd <= 0 {
listOfGames = append(listOfGames, data)
} else {
for i := 0; i < timesToAdd; i++ {
listOfGames = append(listOfGames, data)
}
}
}
song := getSongFromList(listOfGames)
lastFetched = song
return song.Path
}
func GetSongInfo() models.SongInfo {
if songQue == nil {
return models.SongInfo{}
}
var currentSongData = songQue[currentSong]
currentGameData := getCurrentGame(currentSongData)
return models.SongInfo{
Game: currentGameData.GameName,
GamePlayed: currentGameData.TimesPlayed,
Song: currentSongData.SongName,
SongPlayed: currentSongData.TimesPlayed,
CurrentlyPlaying: true,
SongNo: currentSong,
}
}
func GetPlayedSongs() []models.SongInfo {
var songList []models.SongInfo
for i, song := range songQue {
gameData := getCurrentGame(song)
songList = append(songList, models.SongInfo{
Game: gameData.GameName,
GamePlayed: gameData.TimesPlayed,
Song: song.SongName,
SongPlayed: song.TimesPlayed,
CurrentlyPlaying: i == currentSong,
SongNo: i,
})
}
return songList
}
func GetSong(song string) string {
currentSong, _ = strconv.Atoi(song)
if currentSong >= len(songQue) {
currentSong = len(songQue) - 1
} else if currentSong < 0 {
currentSong = 0
}
var songData = songQue[currentSong]
return songData.Path
}
func GetAllGames() []string {
if games == nil || len(games) == 0 {
games = db.FindAllGames()
}
var jsonArray []string
for _, game := range games {
jsonArray = append(jsonArray, game.GameName)
}
return jsonArray
}
func GetAllGamesRandom() []string {
if games == nil || len(games) == 0 {
games = db.FindAllGames()
}
var jsonArray []string
for _, game := range games {
jsonArray = append(jsonArray, game.GameName)
}
rand.Seed(time.Now().UnixNano())
rand.Shuffle(len(jsonArray), func(i, j int) { jsonArray[i], jsonArray[j] = jsonArray[j], jsonArray[i] })
return jsonArray
}
func SetPlayed(songNumber int) {
if songQue == nil || len(songQue) == 0 || songNumber >= len(songQue) {
return
}
var songData = songQue[songNumber]
db.AddGamePlayed(songData.GameId)
db.AddSongPlayed(songData.GameId, songData.SongName)
}
func GetNextSong() string {
if songQue == nil {
return ""
}
if currentSong == len(songQue)-1 || currentSong == -1 {
var songData = songQue[currentSong]
return songData.Path
} else {
currentSong = currentSong + 1
var songData = songQue[currentSong]
return songData.Path
}
}
func GetPreviousSong() string {
if songQue == nil {
return ""
}
if currentSong == -1 || currentSong == 0 {
var songData = songQue[0]
return songData.Path
} else {
currentSong = currentSong - 1
var songData = songQue[currentSong]
return songData.Path
}
}
func getSongFromList(games []models.GameData) models.SongData {
songFound := false
var song models.SongData
for !songFound {
game := getRandomGame(games)
songs := db.FindSongsFromGame(game.Id)
song = songs[rand.Intn(len(songs))]
//Check if file exists and open
openFile, err := os.Open(song.Path)
if err != nil {
//File not found
log.Fatal("Song not found, maybe delete song and/or game" + song.SongName + " songPath: " + song.Path)
} else {
songFound = true
}
err = openFile.Close()
if err != nil {
log.Fatal(err)
}
}
return song
}
func getCurrentGame(currentSongData models.SongData) models.GameData {
for _, game := range games {
if game.Id == currentSongData.GameId {
return game
}
}
return models.GameData{}
}
func getAveragePlayed(gameList []models.GameData) int {
var sum int
for _, data := range gameList {
sum += data.TimesPlayed
}
return sum / len(gameList)
}
func getRandomGame(listOfGames []models.GameData) models.GameData {
return listOfGames[rand.Intn(len(listOfGames))]
}

135
pkg/server/sync.go Normal file
View File

@@ -0,0 +1,135 @@
package server
import (
"fmt"
"io/ioutil"
"log"
"music-server/pkg/db"
"music-server/pkg/models"
"os"
"sort"
"strconv"
"strings"
)
func SyncGames() {
host := os.Getenv("DB_HOST")
var dir string
if host != "" {
dir = "/sorted/"
} else {
dir = "/Users/sebastian/Resilio Sync/Sorterat_test/"
}
fmt.Printf("dir: %s\n", dir)
foldersToSkip := []string{".sync"}
fmt.Println(foldersToSkip)
db.SetGameDeletionDate()
files, err := ioutil.ReadDir(dir)
if err != nil {
log.Fatal(err)
}
for _, file := range files {
if file.IsDir() && !contains(foldersToSkip, file.Name()) {
fmt.Println(file.Name())
path := dir + file.Name() + "/"
fmt.Println(path)
innerFiles, err := ioutil.ReadDir(path)
if err != nil {
log.Fatal(err)
}
id := -1
for _, song := range innerFiles {
id = getIdFromFile(song)
if id != -1 {
break
}
}
if id == -1 {
addNewGame(file.Name(), path)
} else {
checkIfChanged(id, file.Name(), path)
checkSongs(path, id)
}
}
}
}
func ResetDB() {
db.ClearSongs(-1)
db.ClearGames()
}
func getIdFromFile(file os.FileInfo) int {
name := file.Name()
if !file.IsDir() && strings.HasSuffix(name, ".id") {
name = strings.Replace(name, ".id", "", 1)
name = strings.Replace(name, ".", "", 1)
i, _ := strconv.Atoi(name)
return i
}
return -1
}
func checkIfChanged(id int, name string, path string) {
fmt.Printf("Id from file: %v\n", id)
nameFromDb := db.GetGameName(id)
fmt.Printf("Name from file: %v\n", name)
fmt.Printf("Name from DB: %v\n", nameFromDb)
if nameFromDb == "" {
fmt.Println("Not in db")
db.InsertGameWithExistingId(id, name, path)
fmt.Println("Added to db")
} else if name != nameFromDb {
fmt.Println("Diff name")
db.UpdateGameName(id, name, path)
}
db.RemoveDeletionDate(id)
}
func addNewGame(name string, path string) {
newId := db.GetIdByGameName(name)
if newId == -1 {
newId = db.InsertGame(name, path)
}
fmt.Printf("newId = %v", newId)
fileName := path + "/." + strconv.Itoa(newId) + ".id"
fmt.Printf("fileName = %v", fileName)
err := ioutil.WriteFile(fileName, nil, 0644)
if err != nil {
panic(err)
}
checkSongs(path, newId)
}
func checkSongs(gameDir string, gameId int) {
songs := make([]models.SongData, 0)
findSongsFromGame := db.FindSongsFromGame(gameId)
files, err := ioutil.ReadDir(gameDir)
if err != nil {
log.Fatal(err)
}
for _, entry := range files {
path := gameDir + entry.Name()
songName := entry.Name()
if !entry.IsDir() && !strings.HasSuffix(songName, ".id") {
songs = append(songs, models.SongData{GameId: gameId, SongName: songName, Path: path})
}
}
if len(songs) != len(findSongsFromGame) {
db.ClearSongs(gameId)
for _, song := range songs {
db.AddSong(song)
}
}
}
func contains(s []string, searchTerm string) bool {
i := sort.SearchStrings(s, searchTerm)
return i < len(s) && s[i] == searchTerm
}