60 lines
1.3 KiB
Go
60 lines
1.3 KiB
Go
package database
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"log/slog"
|
|
"orbits-server/internal/shared/security"
|
|
"orbits-server/internal/shared/utility"
|
|
"path/filepath"
|
|
"time"
|
|
)
|
|
|
|
// it has been made more general for DRY purposes
|
|
// this function should only be called after manually checking the filetype
|
|
func BuildFileRecord(r io.Reader, metaName string, contentDirectory string) (File, error) {
|
|
ext := filepath.Ext(metaName)
|
|
category := utility.CategorizeMediaType(ext)
|
|
if category == utility.Unspecified {
|
|
return File{}, fmt.Errorf("unsupported filetype")
|
|
}
|
|
|
|
checksum, err := security.HashFileReader(r)
|
|
if err != nil {
|
|
slog.Error("failed to calculate hash of file at given path", "error", err)
|
|
return File{}, err
|
|
}
|
|
|
|
safeName := security.GenerateSafeName() + ext
|
|
destPath := filepath.Join(contentDirectory, safeName)
|
|
|
|
f := File{
|
|
MediaType: category,
|
|
MetaName: metaName,
|
|
FileID: safeName,
|
|
FilePath: destPath,
|
|
Checksum: checksum,
|
|
}
|
|
|
|
return f, nil
|
|
}
|
|
|
|
func BuildKeyRecord(keyHash string, metaName string, expiresAt time.Time) (AccessKey, error) {
|
|
now := time.Now()
|
|
if expiresAt.Before(now) {
|
|
return AccessKey{}, fmt.Errorf("key is already expired")
|
|
}
|
|
|
|
safeName := "orbits_" + security.GenerateSafeName()
|
|
|
|
k := AccessKey{
|
|
MetaName: metaName,
|
|
KeyID: safeName,
|
|
KeyHash: keyHash,
|
|
Revoked: false,
|
|
ExpiresAt: expiresAt,
|
|
}
|
|
|
|
return k, nil
|
|
}
|