hugo-medialog/internal/games/controller.go

105 lines
2.4 KiB
Go

package games
import (
"fmt"
"hugo-medialog/utils"
"os"
"path/filepath"
"gopkg.in/yaml.v2"
)
func LoadGames() ([]Game, error) {
gamesFile := os.Getenv("OBSIDIAN_GAMES_FILE")
fileData, err := os.ReadFile(gamesFile)
if err != nil {
return nil, err
}
var games []Game
err = yaml.Unmarshal(fileData, &games)
if err != nil {
return nil, err
}
return games, nil
}
func ProcessGames(games []Game) error {
fmt.Printf(" G A M E S\n")
utils.Sep()
for _, game := range games {
fmt.Printf("Title: %s\n", game.Title)
// If we dont have ID, search movie by Title and get the ID
if game.ID == 0 {
err := SearchGameByTitle(game.Title, &game)
if err != nil {
fmt.Printf("Error searching game by title %s: %s\n", game.Title, err)
continue
}
}
game.Slug = utils.Sluggify(game.Title)
// Download Images
if game.Image != "" {
suffix := ""
err := DownloadImage(game.Image, game.Slug, suffix)
if err != nil {
fmt.Printf("Error downloading %s: %s\n", game.Image, err)
}
game.Image = fmt.Sprintf("%s.jpg", game.Slug)
}
if game.Poster != "" {
suffix := "-poster"
err := DownloadImage(game.Poster, game.Slug, suffix)
if err != nil {
fmt.Printf("Error downloading %s: %s\n", game.Image, err)
}
game.Poster = fmt.Sprintf("%s%s.jpg", game.Slug, suffix)
}
if game.Background != "" {
suffix := "-background"
err := DownloadImage(game.Background, game.Slug, suffix)
if err != nil {
fmt.Printf("Error downloading %s: %s\n", game.Background, err)
}
game.Background = fmt.Sprintf("%s%s.jpg", game.Slug, suffix)
}
err := generateGameMarkdown(game)
if err != nil {
return err
}
utils.Sep()
}
return nil
}
func generateGameMarkdown(game Game) error {
templatePath := filepath.Join(os.Getenv("TEMPLATES_DIR"), "game.md.tpl")
outputDir := os.Getenv("MARKDOWN_OUTPUT_GAMES_DIR")
if err := utils.CreateDirIfNotExists(outputDir); err != nil {
return err
}
outputPath := filepath.Join(outputDir, fmt.Sprintf("%s.md", game.Slug))
data := map[string]interface{}{
"Title": game.Title,
"Platform": game.Platform,
"Link": game.Link,
"Subtitle": game.Year,
"Year": game.Year,
"Rate": game.Rate,
"Progress": game.Progress,
"Image": game.Image,
"Poster": game.Poster,
"Background": game.Background,
"Date": game.Date,
"Tags": "playing",
}
return utils.GenerateMarkdown(templatePath, outputPath, data)
}