hugo-medialog/internal/books/controller.go

88 lines
1.9 KiB
Go

package books
import (
"fmt"
"hugo-medialog/utils"
"os"
"path/filepath"
"gopkg.in/yaml.v2"
)
func LoadBooks() ([]Book, error) {
booksFile := os.Getenv("OBSIDIAN_BOOKS_FILE")
fileData, err := os.ReadFile(booksFile)
if err != nil {
return nil, err
}
var books []Book
err = yaml.Unmarshal(fileData, &books)
if err != nil {
return nil, err
}
return books, nil
}
func ProcessBooks(books []Book) error {
fmt.Printf(" B O O K S\n")
utils.Sep()
for _, book := range books {
fmt.Printf("Title: %s, Author: %s, ID: %s\n", book.Title, book.Author, book.ID)
// If we dont have ID, search movie by Title and get the ID
if book.ID == "" {
err := SearchBookByTitle(book.Title, &book)
if err != nil {
fmt.Printf("Error searching book by title %s: %s\n", book.Title, err)
continue
}
}
book.Slug = utils.Sluggify(book.Title)
// Now we need to get the image
imageURL := getBookCoverByTitle(book.Title)
if imageURL != "" {
err := DownloadImage(imageURL, book.Slug)
if err != nil {
fmt.Printf("Error downloading %s: %s\n", imageURL, err)
}
}
book.Image = fmt.Sprintf("%s.jpg", book.Slug)
err := generateBookMarkdown(book)
if err != nil {
return err
}
utils.Sep()
}
return nil
}
func generateBookMarkdown(book Book) error {
templatePath := filepath.Join(os.Getenv("TEMPLATES_DIR"), "book.md.tpl")
outputDir := os.Getenv("MARKDOWN_OUTPUT_BOOKS_DIR")
if err := utils.CreateDirIfNotExists(outputDir); err != nil {
return err
}
outputPath := filepath.Join(outputDir, fmt.Sprintf("%s.md", book.Slug))
data := map[string]interface{}{
"Title": book.Title,
"Author": book.Author,
"Link": book.Link,
"Subtitle": book.Year,
"Year": book.Year,
"Rate": book.Rate,
"Pages": book.Pages,
"Progress": book.Progress,
"Image": book.Image,
"Date": book.Date,
"Tags": "reading",
}
return utils.GenerateMarkdown(templatePath, outputPath, data)
}