Working download photo method

Signed-off-by: Kris Nóva <kris@nivenly.com>
This commit is contained in:
Kris Nóva 2021-02-09 18:25:46 -08:00
parent c1a45bf8e3
commit b7fd487a2e
18 changed files with 918 additions and 170 deletions

View file

@ -124,7 +124,7 @@ func GetAccountFolders(router *gin.RouterGroup) {
if cacheData, ok := cache.Get(cacheKey); ok {
cached := cacheData.(fs.FileInfos)
log.Debugf("cache hit for %s [%s]", cacheKey, time.Since(start))
log.Debugf("api: cache hit for %s [%s]", cacheKey, time.Since(start))
c.JSON(http.StatusOK, cached)
return

View file

@ -38,22 +38,32 @@ func BatchPhotosArchive(router *gin.RouterGroup) {
return
}
log.Infof("archive: adding %s", f.String())
log.Infof("photos: archiving %s", f.String())
// Soft delete by setting deleted_at to current date.
err := entity.Db().Where("photo_uid IN (?)", f.Photos).Delete(&entity.Photo{}).Error
if service.Config().BackupYaml() {
photos, err := query.PhotoSelection(f)
if err != nil {
if err != nil {
AbortEntityNotFound(c)
return
}
for _, p := range photos {
if err := p.Archive(); err != nil {
log.Errorf("archive: %s", err)
} else {
SavePhotoAsYaml(p)
}
}
} else if err := entity.Db().Where("photo_uid IN (?)", f.Photos).Delete(&entity.Photo{}).Error; err != nil {
log.Errorf("archive: %s", err)
AbortSaveFailed(c)
return
} else if err := entity.Db().Model(&entity.PhotoAlbum{}).Where("photo_uid IN (?)", f.Photos).UpdateColumn("hidden", true).Error; err != nil {
log.Errorf("archive: %s", err)
}
// Remove archived photos from albums.
logError("archive", entity.Db().Model(&entity.PhotoAlbum{}).Where("photo_uid IN (?)", f.Photos).UpdateColumn("hidden", true).Error)
if err := entity.UpdatePhotoCounts(); err != nil {
log.Errorf("photos: %s", err)
}
logError("photos", entity.UpdatePhotoCounts())
UpdateClientConfig()
@ -63,6 +73,62 @@ func BatchPhotosArchive(router *gin.RouterGroup) {
})
}
// POST /api/v1/batch/photos/restore
func BatchPhotosRestore(router *gin.RouterGroup) {
router.POST("/batch/photos/restore", func(c *gin.Context) {
s := Auth(SessionID(c), acl.ResourcePhotos, acl.ActionDelete)
if s.Invalid() {
AbortUnauthorized(c)
return
}
var f form.Selection
if err := c.BindJSON(&f); err != nil {
AbortBadRequest(c)
return
}
if len(f.Photos) == 0 {
Abort(c, http.StatusBadRequest, i18n.ErrNoItemsSelected)
return
}
log.Infof("photos: restoring %s", f.String())
if service.Config().BackupYaml() {
photos, err := query.PhotoSelection(f)
if err != nil {
AbortEntityNotFound(c)
return
}
for _, p := range photos {
if err := p.Restore(); err != nil {
log.Errorf("restore: %s", err)
} else {
SavePhotoAsYaml(p)
}
}
} else if err := entity.Db().Unscoped().Model(&entity.Photo{}).Where("photo_uid IN (?)", f.Photos).
UpdateColumn("deleted_at", gorm.Expr("NULL")).Error; err != nil {
log.Errorf("restore: %s", err)
AbortSaveFailed(c)
return
}
logError("photos", entity.UpdatePhotoCounts())
UpdateClientConfig()
event.EntitiesRestored("photos", f.Photos)
c.JSON(http.StatusOK, i18n.NewResponse(http.StatusOK, i18n.MsgSelectionRestored))
})
}
// POST /api/v1/batch/photos/approve
func BatchPhotosApprove(router *gin.RouterGroup) {
router.POST("batch/photos/approve", func(c *gin.Context) {
@ -98,7 +164,7 @@ func BatchPhotosApprove(router *gin.RouterGroup) {
for _, p := range photos {
if err := p.Approve(); err != nil {
log.Errorf("photo: %s (approve)", err.Error())
log.Errorf("approve: %s", err)
} else {
approved = append(approved, p)
SavePhotoAsYaml(p)
@ -113,50 +179,6 @@ func BatchPhotosApprove(router *gin.RouterGroup) {
})
}
// POST /api/v1/batch/photos/restore
func BatchPhotosRestore(router *gin.RouterGroup) {
router.POST("/batch/photos/restore", func(c *gin.Context) {
s := Auth(SessionID(c), acl.ResourcePhotos, acl.ActionDelete)
if s.Invalid() {
AbortUnauthorized(c)
return
}
var f form.Selection
if err := c.BindJSON(&f); err != nil {
AbortBadRequest(c)
return
}
if len(f.Photos) == 0 {
Abort(c, http.StatusBadRequest, i18n.ErrNoItemsSelected)
return
}
log.Infof("archive: restoring %s", f.String())
err := entity.Db().Unscoped().Model(&entity.Photo{}).Where("photo_uid IN (?)", f.Photos).
UpdateColumn("deleted_at", gorm.Expr("NULL")).Error
if err != nil {
AbortSaveFailed(c)
return
}
if err := entity.UpdatePhotoCounts(); err != nil {
log.Errorf("photos: %s", err)
}
UpdateClientConfig()
event.EntitiesRestored("photos", f.Photos)
c.JSON(http.StatusOK, i18n.NewResponse(http.StatusOK, i18n.MsgSelectionRestored))
})
}
// POST /api/v1/batch/albums/delete
func BatchAlbumsDelete(router *gin.RouterGroup) {
router.POST("/batch/albums/delete", func(c *gin.Context) {
@ -214,22 +236,23 @@ func BatchPhotosPrivate(router *gin.RouterGroup) {
return
}
log.Infof("photos: mark %s as private", f.String())
log.Infof("photos: updating private flag for %s", f.String())
err := entity.Db().Model(entity.Photo{}).Where("photo_uid IN (?)", f.Photos).UpdateColumn("photo_private",
gorm.Expr("CASE WHEN photo_private > 0 THEN 0 ELSE 1 END")).Error
if err != nil {
if err := entity.Db().Model(entity.Photo{}).Where("photo_uid IN (?)", f.Photos).UpdateColumn("photo_private",
gorm.Expr("CASE WHEN photo_private > 0 THEN 0 ELSE 1 END")).Error; err != nil {
log.Errorf("private: %s", err)
AbortSaveFailed(c)
return
}
if err := entity.UpdatePhotoCounts(); err != nil {
log.Errorf("photos: %s", err)
}
logError("photos", entity.UpdatePhotoCounts())
if entities, err := query.PhotoSelection(f); err == nil {
event.EntitiesUpdated("photos", entities)
if photos, err := query.PhotoSelection(f); err == nil {
for _, p := range photos {
SavePhotoAsYaml(p)
}
event.EntitiesUpdated("photos", photos)
}
UpdateClientConfig()
@ -313,7 +336,7 @@ func BatchPhotosDelete(router *gin.RouterGroup) {
return
}
log.Infof("archive: permanently deleting %s", f.String())
log.Infof("photos: deleting %s", f.String())
photos, err := query.PhotoSelection(f)
@ -327,7 +350,7 @@ func BatchPhotosDelete(router *gin.RouterGroup) {
// Delete photos.
for _, p := range photos {
if err := photoprism.Delete(p); err != nil {
log.Errorf("photo: %s (delete)", err.Error())
log.Errorf("delete: %s", err)
} else {
deleted = append(deleted, p)
}
@ -335,9 +358,7 @@ func BatchPhotosDelete(router *gin.RouterGroup) {
// Update counts and views if needed.
if len(deleted) > 0 {
if err := entity.UpdatePhotoCounts(); err != nil {
log.Errorf("photos: %s", err)
}
logError("photos", entity.UpdatePhotoCounts())
UpdateClientConfig()

View file

@ -50,7 +50,7 @@ func AlbumCover(router *gin.RouterGroup) {
cacheKey := CacheKey(albumCover, uid, typeName)
if cacheData, ok := cache.Get(cacheKey); ok {
log.Debugf("cache hit for %s [%s]", cacheKey, time.Since(start))
log.Debugf("api: cache hit for %s [%s]", cacheKey, time.Since(start))
cached := cacheData.(ThumbCache)
@ -108,8 +108,8 @@ func AlbumCover(router *gin.RouterGroup) {
}
if err != nil {
log.Errorf("album: %s", err)
c.Data(http.StatusOK, "image/svg+xml", photoIconSvg)
log.Errorf("%s: %s", albumCover, err)
c.Data(http.StatusOK, "image/svg+xml", albumIconSvg)
return
} else if thumbnail == "" {
log.Errorf("%s: %s has empty thumb name - bug?", albumCover, filepath.Base(fileName))
@ -160,7 +160,7 @@ func LabelCover(router *gin.RouterGroup) {
cacheKey := CacheKey(labelCover, uid, typeName)
if cacheData, ok := cache.Get(cacheKey); ok {
log.Debugf("cache hit for %s [%s]", cacheKey, time.Since(start))
log.Debugf("api: cache hit for %s [%s]", cacheKey, time.Since(start))
cached := cacheData.(ThumbCache)

View file

@ -56,7 +56,7 @@ func GetFolders(router *gin.RouterGroup, urlPath, rootName, rootPath string) {
if cacheData, ok := cache.Get(cacheKey); ok {
cached := cacheData.(FoldersResponse)
log.Debugf("cache hit for %s [%s]", cacheKey, time.Since(start))
log.Debugf("api: cache hit for %s [%s]", cacheKey, time.Since(start))
c.JSON(http.StatusOK, cached)
return

View file

@ -0,0 +1,140 @@
package api
import (
"net/http"
"path/filepath"
"time"
"github.com/gin-gonic/gin"
"github.com/photoprism/photoprism/internal/photoprism"
"github.com/photoprism/photoprism/internal/query"
"github.com/photoprism/photoprism/internal/service"
"github.com/photoprism/photoprism/internal/thumb"
"github.com/photoprism/photoprism/pkg/fs"
"github.com/photoprism/photoprism/pkg/txt"
)
const (
folderCover = "folder-cover"
)
// GET /api/v1/folders/t/:hash/:token/:type
//
// Parameters:
// uid: string folder uid
// token: string url security token, see config
// type: string thumb type, see thumb.Types
func GetFolderCover(router *gin.RouterGroup) {
router.GET("/folders/t/:uid/:token/:type", func(c *gin.Context) {
if InvalidPreviewToken(c) {
c.Data(http.StatusForbidden, "image/svg+xml", folderIconSvg)
return
}
start := time.Now()
conf := service.Config()
uid := c.Param("uid")
typeName := c.Param("type")
download := c.Query("download") != ""
thumbType, ok := thumb.Types[typeName]
if !ok {
log.Errorf("folder: invalid thumb type %s", txt.Quote(typeName))
c.Data(http.StatusOK, "image/svg+xml", folderIconSvg)
return
}
if thumbType.ExceedsSize() && !conf.ThumbUncached() {
typeName, thumbType = thumb.Find(conf.ThumbSize())
if typeName == "" {
log.Errorf("folder: invalid thumb size %d", conf.ThumbSize())
c.Data(http.StatusOK, "image/svg+xml", folderIconSvg)
return
}
}
cache := service.CoverCache()
cacheKey := CacheKey(folderCover, uid, typeName)
if cacheData, ok := cache.Get(cacheKey); ok {
log.Debugf("api: cache hit for %s [%s]", cacheKey, time.Since(start))
cached := cacheData.(ThumbCache)
if !fs.FileExists(cached.FileName) {
log.Errorf("%s: %s not found", folderCover, uid)
c.Data(http.StatusOK, "image/svg+xml", folderIconSvg)
return
}
AddCoverCacheHeader(c)
if download {
c.FileAttachment(cached.FileName, cached.ShareName)
} else {
c.File(cached.FileName)
}
return
}
f, err := query.FolderCoverByUID(uid)
if err != nil {
log.Debugf("%s: no photos yet, using generic image for %s", folderCover, uid)
c.Data(http.StatusOK, "image/svg+xml", folderIconSvg)
return
}
fileName := photoprism.FileName(f.FileRoot, f.FileName)
if !fs.FileExists(fileName) {
log.Errorf("%s: could not find original for %s", folderCover, fileName)
c.Data(http.StatusOK, "image/svg+xml", folderIconSvg)
// Set missing flag so that the file doesn't show up in search results anymore.
log.Warnf("%s: %s is missing", folderCover, txt.Quote(f.FileName))
logError(folderCover, f.Update("FileMissing", true))
return
}
// Use original file if thumb size exceeds limit, see https://github.com/photoprism/photoprism/issues/157
if thumbType.ExceedsSizeUncached() && !download {
log.Debugf("%s: using original, size exceeds limit (width %d, height %d)", folderCover, thumbType.Width, thumbType.Height)
AddCoverCacheHeader(c)
c.File(fileName)
return
}
var thumbnail string
if conf.ThumbUncached() || thumbType.OnDemand() {
thumbnail, err = thumb.FromFile(fileName, f.FileHash, conf.ThumbPath(), thumbType.Width, thumbType.Height, thumbType.Options...)
} else {
thumbnail, err = thumb.FromCache(fileName, f.FileHash, conf.ThumbPath(), thumbType.Width, thumbType.Height, thumbType.Options...)
}
if err != nil {
log.Errorf("%s: %s", folderCover, err)
c.Data(http.StatusOK, "image/svg+xml", folderIconSvg)
return
} else if thumbnail == "" {
log.Errorf("%s: %s has empty thumb name - bug?", folderCover, filepath.Base(fileName))
c.Data(http.StatusOK, "image/svg+xml", folderIconSvg)
return
}
cache.SetDefault(cacheKey, ThumbCache{thumbnail, f.ShareBase(0)})
log.Debugf("cached %s [%s]", cacheKey, time.Since(start))
AddCoverCacheHeader(c)
if download {
c.FileAttachment(thumbnail, f.DownloadName(DownloadName(c), 0))
} else {
c.File(thumbnail)
}
})
}

332
internal/api/photo.go Normal file
View file

@ -0,0 +1,332 @@
package api
import (
"net/http"
"path/filepath"
"github.com/gin-gonic/gin"
"github.com/photoprism/photoprism/internal/acl"
"github.com/photoprism/photoprism/internal/entity"
"github.com/photoprism/photoprism/internal/event"
"github.com/photoprism/photoprism/internal/form"
"github.com/photoprism/photoprism/internal/i18n"
"github.com/photoprism/photoprism/internal/photoprism"
"github.com/photoprism/photoprism/internal/query"
"github.com/photoprism/photoprism/internal/service"
"github.com/photoprism/photoprism/pkg/fs"
"github.com/photoprism/photoprism/pkg/txt"
)
// SavePhotoAsYaml saves photo data as YAML file.
func SavePhotoAsYaml(p entity.Photo) {
c := service.Config()
// Write YAML sidecar file (optional).
if !c.BackupYaml() {
return
}
fileName := p.YamlFileName(c.OriginalsPath(), c.SidecarPath())
if err := p.SaveAsYaml(fileName); err != nil {
log.Errorf("photo: %s (update yaml)", err)
} else {
log.Debugf("photo: updated yaml file %s", txt.Quote(filepath.Base(fileName)))
}
}
// GET /api/v1/photos/:uid
//
// Parameters:
// uid: string PhotoUID as returned by the API
func GetPhoto(router *gin.RouterGroup) {
router.GET("/photos/:uid", func(c *gin.Context) {
s := Auth(SessionID(c), acl.ResourcePhotos, acl.ActionRead)
if s.Invalid() {
AbortUnauthorized(c)
return
}
p, err := query.PhotoPreloadByUID(c.Param("uid"))
if err != nil {
AbortEntityNotFound(c)
return
}
c.IndentedJSON(http.StatusOK, p)
})
}
// PUT /api/v1/photos/:uid
func UpdatePhoto(router *gin.RouterGroup) {
router.PUT("/photos/:uid", func(c *gin.Context) {
s := Auth(SessionID(c), acl.ResourcePhotos, acl.ActionUpdate)
if s.Invalid() {
AbortUnauthorized(c)
return
}
uid := c.Param("uid")
m, err := query.PhotoByUID(uid)
if err != nil {
AbortEntityNotFound(c)
return
}
// TODO: Proof-of-concept for form handling - might need refactoring
// 1) Init form with model values
f, err := form.NewPhoto(m)
if err != nil {
Abort(c, http.StatusInternalServerError, i18n.ErrSaveFailed)
return
}
// 2) Update form with values from request
if err := c.BindJSON(&f); err != nil {
Abort(c, http.StatusBadRequest, i18n.ErrBadRequest)
return
} else if f.PhotoPrivate {
FlushCoverCache()
}
// 3) Save model with values from form
if err := entity.SavePhotoForm(m, f); err != nil {
Abort(c, http.StatusInternalServerError, i18n.ErrSaveFailed)
return
}
PublishPhotoEvent(EntityUpdated, uid, c)
event.SuccessMsg(i18n.MsgChangesSaved)
p, err := query.PhotoPreloadByUID(uid)
if err != nil {
AbortEntityNotFound(c)
return
}
SavePhotoAsYaml(p)
UpdateClientConfig()
c.JSON(http.StatusOK, p)
})
}
// GET /api/v1/photos/:uid/dl
//
// Parameters:
// uid: string PhotoUID as returned by the API
func GetPhotoDownload(router *gin.RouterGroup) {
router.GET("/photos/:uid/dl", func(c *gin.Context) {
if InvalidDownloadToken(c) {
c.Data(http.StatusForbidden, "image/svg+xml", brokenIconSvg)
return
}
f, err := query.FileByPhotoUID(c.Param("uid"))
if err != nil {
c.Data(http.StatusNotFound, "image/svg+xml", photoIconSvg)
return
}
fileName := photoprism.FileName(f.FileRoot, f.FileName)
if !fs.FileExists(fileName) {
log.Errorf("photo: file %s is missing", txt.Quote(f.FileName))
c.Data(http.StatusNotFound, "image/svg+xml", photoIconSvg)
// Set missing flag so that the file doesn't show up in search results anymore.
logError("photo", f.Update("FileMissing", true))
return
}
c.FileAttachment(fileName, f.DownloadName(DownloadName(c), 0))
})
}
// GET /api/v1/photos/:uid/yaml
//
// Parameters:
// uid: string PhotoUID as returned by the API
func GetPhotoYaml(router *gin.RouterGroup) {
router.GET("/photos/:uid/yaml", func(c *gin.Context) {
s := Auth(SessionID(c), acl.ResourcePhotos, acl.ActionExport)
if s.Invalid() {
AbortUnauthorized(c)
return
}
p, err := query.PhotoPreloadByUID(c.Param("uid"))
if err != nil {
c.AbortWithStatus(http.StatusNotFound)
return
}
data, err := p.Yaml()
if err != nil {
c.AbortWithStatus(http.StatusInternalServerError)
return
}
if c.Query("download") != "" {
AddDownloadHeader(c, c.Param("uid")+fs.YamlExt)
}
c.Data(http.StatusOK, "text/x-yaml; charset=utf-8", data)
})
}
// POST /api/v1/photos/:uid/approve
//
// Parameters:
// uid: string PhotoUID as returned by the API
func ApprovePhoto(router *gin.RouterGroup) {
router.POST("/photos/:uid/approve", func(c *gin.Context) {
s := Auth(SessionID(c), acl.ResourcePhotos, acl.ActionUpdate)
if s.Invalid() {
AbortUnauthorized(c)
return
}
id := c.Param("uid")
m, err := query.PhotoByUID(id)
if err != nil {
AbortEntityNotFound(c)
return
}
if err := m.Approve(); err != nil {
log.Errorf("photo: %s", err.Error())
AbortSaveFailed(c)
return
}
SavePhotoAsYaml(m)
PublishPhotoEvent(EntityUpdated, id, c)
c.JSON(http.StatusOK, gin.H{"photo": m})
})
}
// POST /api/v1/photos/:uid/like
//
// Parameters:
// uid: string PhotoUID as returned by the API
func LikePhoto(router *gin.RouterGroup) {
router.POST("/photos/:uid/like", func(c *gin.Context) {
s := Auth(SessionID(c), acl.ResourcePhotos, acl.ActionLike)
if s.Invalid() {
AbortUnauthorized(c)
return
}
id := c.Param("uid")
m, err := query.PhotoByUID(id)
if err != nil {
AbortEntityNotFound(c)
return
}
if err := m.SetFavorite(true); err != nil {
log.Errorf("photo: %s", err.Error())
AbortSaveFailed(c)
return
}
SavePhotoAsYaml(m)
PublishPhotoEvent(EntityUpdated, id, c)
c.JSON(http.StatusOK, gin.H{"photo": m})
})
}
// DELETE /api/v1/photos/:uid/like
//
// Parameters:
// uid: string PhotoUID as returned by the API
func DislikePhoto(router *gin.RouterGroup) {
router.DELETE("/photos/:uid/like", func(c *gin.Context) {
s := Auth(SessionID(c), acl.ResourcePhotos, acl.ActionLike)
if s.Invalid() {
AbortUnauthorized(c)
return
}
id := c.Param("uid")
m, err := query.PhotoByUID(id)
if err != nil {
AbortEntityNotFound(c)
return
}
if err := m.SetFavorite(false); err != nil {
log.Errorf("photo: %s", err.Error())
AbortSaveFailed(c)
return
}
SavePhotoAsYaml(m)
PublishPhotoEvent(EntityUpdated, id, c)
c.JSON(http.StatusOK, gin.H{"photo": m})
})
}
// POST /api/v1/photos/:uid/files/:file_uid/primary
//
// Parameters:
// uid: string PhotoUID as returned by the API
// file_uid: string File UID as returned by the API
func PhotoPrimary(router *gin.RouterGroup) {
router.POST("/photos/:uid/files/:file_uid/primary", func(c *gin.Context) {
s := Auth(SessionID(c), acl.ResourcePhotos, acl.ActionUpdate)
if s.Invalid() {
AbortUnauthorized(c)
return
}
uid := c.Param("uid")
fileUID := c.Param("file_uid")
err := query.SetPhotoPrimary(uid, fileUID)
if err != nil {
AbortEntityNotFound(c)
return
}
PublishPhotoEvent(EntityUpdated, uid, c)
event.SuccessMsg(i18n.MsgChangesSaved)
p, err := query.PhotoPreloadByUID(uid)
if err != nil {
AbortEntityNotFound(c)
return
}
c.JSON(http.StatusOK, p)
})
}

View file

@ -55,7 +55,7 @@ func GetThumb(router *gin.RouterGroup) {
cacheKey := CacheKey("thumbs", fileHash, typeName)
if cacheData, ok := cache.Get(cacheKey); ok {
log.Debugf("cache hit for %s [%s]", cacheKey, time.Since(start))
log.Debugf("api: cache hit for %s [%s]", cacheKey, time.Since(start))
cached := cacheData.(ThumbCache)

View file

@ -69,7 +69,7 @@ func PhotoUnstack(router *gin.RouterGroup) {
stackPrimary, err := stackPhoto.PrimaryFile()
if err != nil {
log.Errorf("photo: can't find primary file for existing photo (unstack %s)", txt.Quote(baseName))
log.Errorf("photo: can't find primary file for %s (unstack)", txt.Quote(baseName))
AbortUnexpected(c)
return
}
@ -81,11 +81,11 @@ func PhotoUnstack(router *gin.RouterGroup) {
AbortEntityNotFound(c)
return
} else if related.Len() == 0 {
log.Errorf("photo: no files found (unstack %s)", txt.Quote(baseName))
log.Errorf("photo: no files found for %s (unstack)", txt.Quote(baseName))
AbortEntityNotFound(c)
return
} else if related.Main == nil {
log.Errorf("photo: no main file found (unstack %s)", txt.Quote(baseName))
log.Errorf("photo: no main file found for %s (unstack)", txt.Quote(baseName))
AbortEntityNotFound(c)
return
}