package view import ( "strconv" "github.com/valyala/fasthttp" "git.sr.ht/~gabrielgio/img/pkg/database/repository" "git.sr.ht/~gabrielgio/img/pkg/ext" "git.sr.ht/~gabrielgio/img/templates" ) type ( MediaView struct { mediaRepository repository.MediaRepository userRepository repository.UserRepository } ) func getPagination(ctx *fasthttp.RequestCtx) *repository.Pagination { var ( size int page int sizeStr = string(ctx.FormValue("size")) pageStr = string(ctx.FormValue("page")) ) if sizeStr == "" { size = 100 } else if s, err := strconv.Atoi(sizeStr); err != nil { size = 100 } else { size = s } if pageStr == "" { page = 0 } else if p, err := strconv.Atoi(pageStr); err != nil { page = 0 } else { page = p } return &repository.Pagination{ Page: page, Size: size, } } func NewMediaView( mediaRepository repository.MediaRepository, userRepository repository.UserRepository, ) *MediaView { return &MediaView{ mediaRepository: mediaRepository, userRepository: userRepository, } } func (self *MediaView) Index(ctx *fasthttp.RequestCtx) error { p := getPagination(ctx) token := ext.GetTokenFromCtx(ctx) userPath, err := self.userRepository.GetPathFromUserID(ctx, token.UserID) if err != nil { return err } p.Path = userPath medias, err := self.mediaRepository.List(ctx, p) if err != nil { return err } page := &templates.MediaPage{ Medias: medias, Next: &repository.Pagination{ Size: p.Size, Page: p.Page + 1, }, } templates.WritePageTemplate(ctx, page) if err != nil { return err } return nil } func (self *MediaView) GetImage(ctx *fasthttp.RequestCtx) error { pathHash := string(ctx.FormValue("path_hash")) media, err := self.mediaRepository.Get(ctx, pathHash) if err != nil { return err } ctx.Response.Header.SetContentType(media.MIMEType) fasthttp.ServeFileUncompressed(ctx, media.Path) return nil } func (self *MediaView) GetThumbnail(ctx *fasthttp.RequestCtx) error { pathHash := string(ctx.FormValue("path_hash")) path, err := self.mediaRepository.GetThumbnailPath(ctx, pathHash) if err != nil { ctx.Redirect("/media/image?path_hash="+pathHash, 307) // nolint: nilerr return nil } ctx.Request.Header.SetContentType("image/jpeg") fasthttp.ServeFileUncompressed(ctx, path) return nil } func (self *MediaView) SetMyselfIn(r *ext.Router) { r.GET("/media", self.Index) r.POST("/media", self.Index) r.GET("/media/image", self.GetImage) r.GET("/media/thumbnail", self.GetThumbnail) }