Manage display of book covers

This commit is contained in:
2025-10-28 18:35:36 +01:00
parent 8b8eee8210
commit b4df375e4c
20 changed files with 257 additions and 353 deletions

View File

@@ -14,9 +14,11 @@ import (
)
type bookUserGet struct {
BookId uint `json:"id"`
Title string `json:"title" binding:"required,max=300"`
Author string `json:"author" binding:"max=100"`
Rating int `json:"rating" binding:"min=0,max=10"`
Read bool `json:"read"`
}
func TestGetBooksHandler_Demo(t *testing.T) {
@@ -35,6 +37,27 @@ func TestGetBooksHandler_Demo2(t *testing.T) {
assert.Equal(t, 2, len(books))
}
func TestGetBooksHandler_CheckOneBook(t *testing.T) {
router := testutils.TestSetup()
token := testutils.ConnectDemo2User(router)
books := testGetbooksHandler(t, router, token, 200)
var book bookUserGet
for _, b := range books {
if b.Title == "De sang-froid" {
book = b
}
}
assert.Equal(t,
bookUserGet{
BookId: 18,
Title: "De sang-froid",
Author: "Truman Capote",
Rating: 6,
Read: true,
}, book)
}
func testGetbooksHandler(t *testing.T, router *gin.Engine, userToken string, expectedCode int) []bookUserGet {
req, _ := http.NewRequest("GET", "/mybooks", nil)
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", userToken))

View File

@@ -21,6 +21,7 @@ func Initdb(databasePath string, demoDataPath string) *gorm.DB {
db.AutoMigrate(&model.Book{})
db.AutoMigrate(&model.User{})
db.AutoMigrate(&model.UserBook{})
db.AutoMigrate(&model.StaticFile{})
var book model.Book
queryResult := db.Limit(1).Find(&book)
if queryResult.RowsAffected == 0 && demoDataPath != "" {

View File

@@ -0,0 +1,42 @@
package fileutils
import (
"mime/multipart"
"path/filepath"
"strconv"
"git.artlef.fr/PersonalLibraryManager/internal/appcontext"
"git.artlef.fr/PersonalLibraryManager/internal/model"
)
func SaveStaticFile(ac *appcontext.AppContext, file *multipart.FileHeader) (model.StaticFile, error) {
filename := file.Filename
filepath := computePathFromName(ac, filename)
err := ac.C.SaveUploadedFile(file, ac.Config.ImageFolderPath+"/"+filepath)
if err != nil {
return model.StaticFile{}, err
}
staticFile := model.StaticFile{
Name: filename,
Path: filepath,
}
ac.Db.Save(&staticFile)
return staticFile, nil
}
func computePathFromName(ac *appcontext.AppContext, filename string) string {
var existingFiles []model.StaticFile
ac.Db.Where("name = ?", filename).Find(&existingFiles)
l := len(existingFiles)
if l == 0 {
return filename
} else {
extension := filepath.Ext(filename)
basename := filename[:len(filename)-len(extension)]
return basename + "-" + strconv.Itoa(l) + extension
}
}
func GetWsLinkPrefix() string {
return "/bookcover/"
}

View File

@@ -8,4 +8,6 @@ type Book struct {
Author string `json:"author"`
AddedBy User
AddedByID uint
Cover StaticFile
CoverID uint
}

9
internal/model/file.go Normal file
View File

@@ -0,0 +1,9 @@
package model
import "gorm.io/gorm"
type StaticFile struct {
gorm.Model
Name string `gorm:"not null"`
Path string `gorm:"not null;index;uniqueIndex"`
}

View File

@@ -18,6 +18,10 @@ type HttpError struct {
}
func ValidateId(db *gorm.DB, id uint, value any) error {
//id = 0 means empty id, so no check
if id == 0 {
return nil
}
record := map[string]any{}
result := db.Model(value).First(&record, id)
if result.Error == nil {

69
internal/query/query.go Normal file
View File

@@ -0,0 +1,69 @@
package query
import (
"strings"
"git.artlef.fr/PersonalLibraryManager/internal/fileutils"
"git.artlef.fr/PersonalLibraryManager/internal/model"
"gorm.io/gorm"
)
type BookGet struct {
Title string `json:"title" binding:"required,max=300"`
Author string `json:"author" binding:"max=100"`
Rating int `json:"rating"`
Read bool `json:"read"`
CoverPath string `json:"coverPath"`
}
func FetchBookGet(db *gorm.DB, userId uint, bookId uint64) (BookGet, error) {
var book BookGet
query := db.Model(&model.Book{})
query = query.Select("books.title, books.author, user_books.rating, user_books.read, " + selectStaticFilesPath())
query = query.Joins("left join user_books on (user_books.book_id = books.id and user_books.user_id = ?)", userId)
query = query.Joins("left join static_files on (static_files.id = books.cover_id)")
query = query.Where("books.id = ?", bookId)
res := query.First(&book)
return book, res.Error
}
type BookSearchGet struct {
Title string `json:"title" binding:"required,max=300"`
Author string `json:"author" binding:"max=100"`
ID uint `json:"id"`
CoverPath string `json:"coverPath"`
}
func FetchBookSearchGet(db *gorm.DB, searchterm string) ([]BookSearchGet, error) {
var books []BookSearchGet
query := db.Model(&model.Book{})
query = query.Select("books.title, books.author, books.id," + selectStaticFilesPath())
query = query.Joins("left join static_files on (static_files.id = books.cover_id)")
query = query.Where("LOWER(title) LIKE ?", "%"+strings.ToLower(searchterm)+"%")
res := query.Find(&books)
return books, res.Error
}
type BookUserGet struct {
ID uint `json:"id"`
Title string `json:"title" binding:"required,max=300"`
Author string `json:"author" binding:"max=100"`
Rating int `json:"rating" binding:"min=0,max=10"`
Read bool `json:"read" binding:"boolean"`
CoverPath string `json:"coverPath"`
}
func FetchBookUserGet(db *gorm.DB, userId uint) ([]BookUserGet, error) {
var books []BookUserGet
query := db.Model(&model.UserBook{})
query = query.Select("books.id, books.title, books.author, user_books.rating, user_books.read," + selectStaticFilesPath())
query = query.Joins("left join books on (books.id = user_books.book_id)")
query = query.Joins("left join static_files on (static_files.id = books.cover_id)")
query = query.Where("user_id = ?", userId)
res := query.Find(&books)
return books, res.Error
}
func selectStaticFilesPath() string {
return "(CASE COALESCE(static_files.path, '') WHEN '' THEN '' ELSE concat('" + fileutils.GetWsLinkPrefix() + "', static_files.path) END) as CoverPath"
}

View File

@@ -7,16 +7,10 @@ import (
"git.artlef.fr/PersonalLibraryManager/internal/appcontext"
"git.artlef.fr/PersonalLibraryManager/internal/model"
"git.artlef.fr/PersonalLibraryManager/internal/myvalidator"
"git.artlef.fr/PersonalLibraryManager/internal/query"
"github.com/gin-gonic/gin"
)
type bookGet struct {
Title string `json:"title" binding:"required,max=300"`
Author string `json:"author" binding:"max=100"`
Rating int `json:"rating"`
Read bool `json:"read"`
}
func GetBookHandler(ac appcontext.AppContext) {
bookId, err := strconv.ParseUint(ac.C.Param("id"), 10, 64)
if err != nil {
@@ -33,13 +27,8 @@ func GetBookHandler(ac appcontext.AppContext) {
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
return
}
var book bookGet
query := ac.Db.Model(&model.Book{})
query = query.Select("books.title, books.author, user_books.rating, user_books.read")
query = query.Joins("left join user_books on (user_books.book_id = books.id and user_books.user_id = ?)", user.ID)
query = query.Where("books.id = ?", bookId)
res := query.First(&book)
if res.Error != nil {
book, queryErr := query.FetchBookGet(ac.Db, user.ID, bookId)
if queryErr != nil {
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
return
}

View File

@@ -7,8 +7,9 @@ import (
)
type bookPostCreate struct {
Title string `json:"title" binding:"required,max=300"`
Author string `json:"author" binding:"max=100"`
Title string `json:"title" binding:"required,max=300"`
Author string `json:"author" binding:"max=100"`
CoverID uint `json:"coverId"`
}
func PostBookHandler(ac appcontext.AppContext) {
@@ -18,6 +19,11 @@ func PostBookHandler(ac appcontext.AppContext) {
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
return
}
err = myvalidator.ValidateId(ac.Db, book.CoverID, &model.StaticFile{})
if err != nil {
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
return
}
user, fetchUserErr := ac.GetAuthenticatedUser()
if fetchUserErr != nil {
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
@@ -33,9 +39,13 @@ func PostBookHandler(ac appcontext.AppContext) {
}
func bookWsToDb(b bookPostCreate, user *model.User) model.Book {
return model.Book{
book := model.Book{
Title: b.Title,
Author: b.Author,
AddedBy: *user,
}
if b.CoverID > 0 {
book.CoverID = b.CoverID
}
return book
}

View File

@@ -2,33 +2,18 @@ package routes
import (
"net/http"
"strings"
"git.artlef.fr/PersonalLibraryManager/internal/appcontext"
"git.artlef.fr/PersonalLibraryManager/internal/model"
"git.artlef.fr/PersonalLibraryManager/internal/myvalidator"
"git.artlef.fr/PersonalLibraryManager/internal/query"
)
type bookSearchGet struct {
Title string `json:"title" binding:"required,max=300"`
Author string `json:"author" binding:"max=100"`
ID uint `json:"id"`
}
func GetSearchBooksHandler(ac appcontext.AppContext) {
searchterm := ac.C.Param("searchterm")
var booksDb []model.Book
ac.Db.Where("LOWER(title) LIKE ?", "%"+strings.ToLower(searchterm)+"%").Find(&booksDb)
books := make([]bookSearchGet, 0)
for _, b := range booksDb {
books = append(books, bookDbToWs(&b))
books, err := query.FetchBookSearchGet(ac.Db, searchterm)
if err != nil {
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
return
}
ac.C.JSON(http.StatusOK, books)
}
func bookDbToWs(b *model.Book) bookSearchGet {
return bookSearchGet{
Title: b.Title,
Author: b.Author,
ID: b.ID,
}
}

View File

@@ -4,39 +4,16 @@ import (
"net/http"
"git.artlef.fr/PersonalLibraryManager/internal/appcontext"
"git.artlef.fr/PersonalLibraryManager/internal/model"
"git.artlef.fr/PersonalLibraryManager/internal/myvalidator"
"git.artlef.fr/PersonalLibraryManager/internal/query"
)
type bookUserGet struct {
BookID uint `json:"id"`
Title string `json:"title" binding:"required,max=300"`
Author string `json:"author" binding:"max=100"`
Rating int `json:"rating" binding:"min=0,max=10"`
Read bool `json:"read" binding:"boolean"`
}
func GetMyBooksHanderl(ac appcontext.AppContext) {
var userbooks []model.UserBook
user, err := ac.GetAuthenticatedUser()
if err != nil {
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
return
}
ac.Db.Preload("Book").Where("user_id = ?", user.ID).Find(&userbooks)
booksDto := make([]bookUserGet, 0)
for _, userbook := range userbooks {
booksDto = append(booksDto, userBookDbToWs(&userbook))
}
ac.C.JSON(http.StatusOK, booksDto)
}
func userBookDbToWs(b *model.UserBook) bookUserGet {
return bookUserGet{
BookID: b.BookID,
Title: b.Book.Title,
Author: b.Book.Author,
Rating: b.Rating,
Read: b.Read,
}
userbooks, err := query.FetchBookUserGet(ac.Db, user.ID)
ac.C.JSON(http.StatusOK, userbooks)
}

View File

@@ -4,21 +4,33 @@ import (
"net/http"
"git.artlef.fr/PersonalLibraryManager/internal/appcontext"
"git.artlef.fr/PersonalLibraryManager/internal/fileutils"
"git.artlef.fr/PersonalLibraryManager/internal/model"
"git.artlef.fr/PersonalLibraryManager/internal/myvalidator"
"github.com/gin-gonic/gin"
)
type fileInfoPost struct {
FileID uint `json:"fileId"`
FilePath string `json:"filepath"`
}
func PostUploadBookCoverHandler(ac appcontext.AppContext) {
file, err := ac.C.FormFile("file")
if err != nil {
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
return
}
filepath := file.Filename
err = ac.C.SaveUploadedFile(file, ac.Config.ImageFolderPath+"/"+filepath)
if err != nil {
myvalidator.ReturnErrorsAsJsonResponse(&ac, err)
staticFile, saveErr := fileutils.SaveStaticFile(&ac, file)
if saveErr != nil {
myvalidator.ReturnErrorsAsJsonResponse(&ac, saveErr)
return
}
ac.C.JSON(http.StatusOK, gin.H{"filepath": "/bookcover/" + filepath})
ac.C.JSON(http.StatusOK, staticFileDbToWs(&staticFile))
}
func staticFileDbToWs(f *model.StaticFile) fileInfoPost {
return fileInfoPost{
FileID: f.ID,
FilePath: fileutils.GetWsLinkPrefix() + f.Path,
}
}