ultisuite-backend/internal/api/photos/service.go

100 lines
2.7 KiB
Go

package photos
import (
"context"
"io"
"strings"
"github.com/ultisuite/ulti-backend/internal/api/paginate"
"github.com/ultisuite/ulti-backend/internal/api/query"
photospkg "github.com/ultisuite/ulti-backend/internal/photos"
)
type Service struct {
client *photospkg.Client
}
func NewService(client *photospkg.Client) *Service {
return &Service{client: client}
}
type AssetsList struct {
Assets []photospkg.Asset `json:"assets"`
Page int `json:"page"`
Pagination query.PaginationMeta `json:"pagination,omitempty"`
}
func (s *Service) ListAssets(ctx context.Context, apiKey string, params query.ListParams) (AssetsList, error) {
assets, err := s.client.GetAssets(ctx, apiKey, params.Page, params.PageSize)
if err != nil {
return AssetsList{}, err
}
filtered := filterAssets(assets, params.Q)
total := int64(len(filtered))
page, _ := paginate.Slice(filtered, 0, len(filtered))
return AssetsList{
Assets: page,
Page: params.Page,
Pagination: params.Meta(&total),
}, nil
}
type AlbumsList struct {
Albums []photospkg.Album `json:"albums"`
Pagination query.PaginationMeta `json:"pagination,omitempty"`
}
func (s *Service) ListAlbums(ctx context.Context, apiKey string, params query.ListParams) (AlbumsList, error) {
albums, err := s.client.GetAlbums(ctx, apiKey)
if err != nil {
return AlbumsList{}, err
}
filtered := filterAlbums(albums, params.Q)
page, total := paginate.Slice(filtered, params.Offset(), params.Limit())
return AlbumsList{
Albums: page,
Pagination: params.Meta(&total),
}, nil
}
func (s *Service) UploadAsset(ctx context.Context, apiKey string, body io.Reader, contentType string) (string, error) {
return s.client.UploadAsset(ctx, apiKey, body, contentType)
}
func (s *Service) GetAssetThumbnail(ctx context.Context, apiKey, assetID string) (io.ReadCloser, string, error) {
return s.client.GetAssetThumbnail(ctx, apiKey, assetID)
}
func (s *Service) DeleteAsset(ctx context.Context, apiKey, assetID string) error {
return s.client.DeleteAsset(ctx, apiKey, assetID)
}
func filterAssets(assets []photospkg.Asset, q string) []photospkg.Asset {
q = strings.ToLower(strings.TrimSpace(q))
if q == "" {
return assets
}
out := make([]photospkg.Asset, 0, len(assets))
for _, a := range assets {
if strings.Contains(strings.ToLower(a.OriginalName), q) ||
strings.Contains(strings.ToLower(a.MimeType), q) {
out = append(out, a)
}
}
return out
}
func filterAlbums(albums []photospkg.Album, q string) []photospkg.Album {
q = strings.ToLower(strings.TrimSpace(q))
if q == "" {
return albums
}
out := make([]photospkg.Album, 0, len(albums))
for _, a := range albums {
if strings.Contains(strings.ToLower(a.Name), q) {
out = append(out, a)
}
}
return out
}