Improve Sheet model
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
@@ -8,10 +9,12 @@ import (
|
||||
"path/filepath"
|
||||
"sheetless-server/database"
|
||||
"sheetless-server/models"
|
||||
"sheetless-server/utils"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const uploadDir = "./uploads"
|
||||
@@ -79,14 +82,29 @@ func UploadSheet(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
fileHash, err := utils.FileHashFromUpload(out)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed calculating hash"})
|
||||
return
|
||||
}
|
||||
|
||||
uuid, err := GenerateNonexistentSheetUuid()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed generating sheet uuid"})
|
||||
return
|
||||
}
|
||||
|
||||
// Create database record
|
||||
sheet := models.MusicSheet{
|
||||
sheet := models.Sheet{
|
||||
Uuid: *uuid,
|
||||
Title: title,
|
||||
Composer: composer,
|
||||
Description: description,
|
||||
FilePath: filePath,
|
||||
FileSize: fileInfo.Size(),
|
||||
UserID: userID.(uint),
|
||||
FileHash: fileHash,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
if err := database.DB.Create(&sheet).Error; err != nil {
|
||||
@@ -103,7 +121,7 @@ func UploadSheet(c *gin.Context) {
|
||||
}
|
||||
|
||||
func ListSheets(c *gin.Context) {
|
||||
var sheets []models.MusicSheet
|
||||
var sheets []models.Sheet
|
||||
|
||||
query := database.DB.Preload("User")
|
||||
|
||||
@@ -131,7 +149,7 @@ func DownloadSheet(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
var sheet models.MusicSheet
|
||||
var sheet models.Sheet
|
||||
if err := database.DB.First(&sheet, uint(id)).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Sheet not found"})
|
||||
return
|
||||
@@ -147,4 +165,26 @@ func DownloadSheet(c *gin.Context) {
|
||||
c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filepath.Base(sheet.FilePath)))
|
||||
c.Header("Content-Type", "application/pdf")
|
||||
c.File(sheet.FilePath)
|
||||
}
|
||||
}
|
||||
|
||||
func GenerateNonexistentSheetUuid() (*uuid.UUID, error) {
|
||||
for i := 0; i < 10; i++ {
|
||||
uuid := uuid.New()
|
||||
|
||||
var exists bool
|
||||
err := database.DB.Model(&models.Sheet{}).
|
||||
Select("count(*) > 0").
|
||||
Where("uuid = ?", uuid).
|
||||
Find(&exists).
|
||||
Error
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !exists {
|
||||
return &uuid, nil
|
||||
}
|
||||
}
|
||||
return nil, errors.New("Somehow unable to generate new uuid for sheet.")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user