66 lines
2.1 KiB
Go
66 lines
2.1 KiB
Go
package main
|
|
|
|
import (
|
|
"errors"
|
|
"strings"
|
|
"time"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type MediaAsset struct {
|
|
ID uint `gorm:"primaryKey" json:"id"`
|
|
AssetKey string `gorm:"uniqueIndex;size:512" json:"assetKey"`
|
|
Source string `gorm:"index;size:32" json:"source"`
|
|
RID string `gorm:"index;size:256" json:"rid"`
|
|
Quality string `gorm:"index;size:32" json:"quality"`
|
|
LocalPath string `json:"localPath,omitempty"`
|
|
Format string `json:"format,omitempty"`
|
|
ActualQuality string `json:"actualQuality,omitempty"`
|
|
Size int64 `json:"size"`
|
|
Status string `gorm:"index;size:20" json:"status"`
|
|
OwnerTaskID uint `gorm:"index" json:"ownerTaskId,omitempty"`
|
|
LeaseUntil time.Time `gorm:"index" json:"-"`
|
|
Generation uint64 `json:"generation"`
|
|
CreatedAt time.Time `json:"createdAt"`
|
|
UpdatedAt time.Time `json:"updatedAt"`
|
|
}
|
|
|
|
func assetKey(source, rid, quality string) string {
|
|
return strings.Join([]string{source, rid, quality}, "\x00")
|
|
}
|
|
|
|
func (a *App) ensureAsset(t *Task) (*MediaAsset, error) {
|
|
if t.AssetID != 0 {
|
|
var asset MediaAsset
|
|
if err := a.db.First(&asset, t.AssetID).Error; err == nil {
|
|
return &asset, nil
|
|
}
|
|
}
|
|
key := assetKey(t.Source, t.RID, t.Quality)
|
|
var asset MediaAsset
|
|
err := a.db.Where("asset_key = ?", key).First(&asset).Error
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
asset = MediaAsset{AssetKey: key, Source: t.Source, RID: t.RID, Quality: t.Quality, Status: "new"}
|
|
if err := a.db.Create(&asset).Error; err != nil {
|
|
if a.db.Where("asset_key = ?", key).First(&asset).Error != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
} else if err != nil {
|
|
return nil, err
|
|
}
|
|
t.AssetID = asset.ID
|
|
if err := a.db.Model(t).Update("asset_id", asset.ID).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
return &asset, nil
|
|
}
|
|
|
|
// acquireAsset is the compatibility entry point.
|
|
func (a *App) acquireAsset(t *Task) (*MediaAsset, bool, error) { return a.claimAsset(t) }
|
|
|
|
func (a *App) markAssetDone(t *Task) { _ = a.finishAsset(t) }
|
|
|
|
func (a *App) releaseAsset(t *Task) { a.invalidateAsset(t) }
|