website/pkg/models/photo.go

97 lines
2.2 KiB
Go
Raw Normal View History

package models
import (
"errors"
"math"
"time"
)
// Photo table.
type Photo struct {
ID uint64 `gorm:"primaryKey"`
UserID uint64 `gorm:"index"`
Filename string
CroppedFilename string // if cropped, e.g. for profile photo
Filesize int64
Caption string
Flagged bool // photo has been reported by the community
Visibility PhotoVisibility
Gallery bool // photo appears in the public gallery (if public)
Explicit bool // is an explicit photo
CreatedAt time.Time
UpdatedAt time.Time
}
// PhotoVisibility settings.
type PhotoVisibility string
const (
PhotoPublic PhotoVisibility = "public" // on profile page and/or public gallery
PhotoFriends = "friends" // only friends can see it
PhotoPrivate = "private" // private
)
// CreatePhoto with most of the settings you want (not ID or timestamps) in the database.
func CreatePhoto(tmpl Photo) (*Photo, error) {
if tmpl.UserID == 0 {
return nil, errors.New("UserID required")
}
p := &Photo{
UserID: tmpl.UserID,
Filename: tmpl.Filename,
CroppedFilename: tmpl.CroppedFilename,
Caption: tmpl.Caption,
Visibility: tmpl.Visibility,
Gallery: tmpl.Gallery,
Explicit: tmpl.Explicit,
}
result := DB.Create(p)
return p, result.Error
}
// GetPhoto by ID.
func GetPhoto(id uint64) (*Photo, error) {
p := &Photo{}
result := DB.First(&p, id)
return p, result.Error
}
/*
PaginateUserPhotos gets a page of photos belonging to a user ID.
*/
func PaginateUserPhotos(userID uint64, visibility []PhotoVisibility, pager *Pagination) ([]*Photo, error) {
var p = []*Photo{}
query := DB.Where(
"user_id = ? AND visibility IN ?",
userID,
visibility,
).Order(
pager.Sort,
)
// Get the total count.
query.Model(&Photo{}).Count(&pager.Total)
pager.Pages = int(math.Ceil(float64(pager.Total) / float64(pager.PerPage)))
result := query.Offset(
pager.GetOffset(),
).Limit(pager.PerPage).Find(&p)
return p, result.Error
}
// Save photo.
func (p *Photo) Save() error {
result := DB.Save(p)
return result.Error
}
// Delete photo.
func (p *Photo) Delete() error {
result := DB.Delete(p)
return result.Error
}