92 lines
2.1 KiB
Go
92 lines
2.1 KiB
Go
package database
|
|
|
|
import (
|
|
"fmt"
|
|
"log/slog"
|
|
"time"
|
|
|
|
"git.jmbit.de/jmb/scanfile/server/internal/store"
|
|
)
|
|
|
|
type File struct {
|
|
Id int64
|
|
Blake2 string `xorm:"unique"`//Used for checking if the file already exists
|
|
Uuid string `xorm:"unique"`//used for file blob storage etc.
|
|
Name string //Name of the file
|
|
Description string //Any text to add to it for context
|
|
MimeType string
|
|
Size int64
|
|
CreatedAt time.Time `xorm:"created"`
|
|
UpdatedAt time.Time `xorm:"updated"`
|
|
}
|
|
|
|
// Insert File to DB
|
|
func (f File) Insert() error {
|
|
_, err := engine.InsertOne(f)
|
|
return err
|
|
}
|
|
|
|
// Deletes a File
|
|
// TODO: Make atomic
|
|
func (f File) Delete() error {
|
|
err := store.DeleteFile(f.Uuid)
|
|
if err != nil {
|
|
slog.Error("Could not delete File from disk", "file-uuid", f.Uuid, "file-name", f.Name)
|
|
return err
|
|
}
|
|
slog.Info("Deleted File from disk", "uuid", f.Uuid)
|
|
_, err = engine.Delete(f)
|
|
if err != nil {
|
|
slog.Error("Could not delete File from DB", "file-uuid", f.Uuid, "file-name", f.Name)
|
|
return err
|
|
}
|
|
slog.Info("Deleted File from DB", "file-uuid", f.Uuid)
|
|
|
|
return nil
|
|
}
|
|
|
|
|
|
func FileByID(id int64) (File, error) {
|
|
file := File{Id: id}
|
|
success, err := engine.Get(&file)
|
|
if err != nil || success == false {
|
|
return file, err
|
|
}
|
|
return file, nil
|
|
}
|
|
|
|
func FileByUUID(uuid string) (File, error) {
|
|
file := File{Uuid: uuid}
|
|
success, err := engine.Get(&file)
|
|
if err != nil || success == false {
|
|
return file, err
|
|
}
|
|
return file, nil
|
|
}
|
|
|
|
func FileByBlake2(hash string) (File, error) {
|
|
file := File{Blake2: hash}
|
|
success, err := engine.Get(&file)
|
|
slog.Info("Getting file for blake2 hash", "success", success, "hash", hash)
|
|
if err != nil {
|
|
return file, err
|
|
}
|
|
if success == false {
|
|
return file, fmt.Errorf("Record not found")
|
|
}
|
|
return file, nil
|
|
}
|
|
|
|
func FileAlreadyExists(blake2 string) (bool, error) {
|
|
file := new(File)
|
|
count, err := engine.Where("blake2 LIKE ?", blake2).Count(file)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
if count > 0 {
|
|
return true, nil
|
|
} else {
|
|
return false, nil
|
|
}
|
|
}
|
|
|