1package view
2
3import (
4 "strconv"
5
6 "github.com/valyala/fasthttp"
7
8 "git.sr.ht/~gabrielgio/img/pkg/database/repository"
9 "git.sr.ht/~gabrielgio/img/pkg/ext"
10 "git.sr.ht/~gabrielgio/img/templates"
11)
12
13type (
14 MediaView struct {
15 mediaRepository repository.MediaRepository
16 userRepository repository.UserRepository
17 }
18)
19
20func getPagination(ctx *fasthttp.RequestCtx) *repository.Pagination {
21 var (
22 size int
23 page int
24 sizeStr = string(ctx.FormValue("size"))
25 pageStr = string(ctx.FormValue("page"))
26 )
27
28 if sizeStr == "" {
29 size = 100
30 } else if s, err := strconv.Atoi(sizeStr); err != nil {
31 size = 100
32 } else {
33 size = s
34 }
35
36 if pageStr == "" {
37 page = 0
38 } else if p, err := strconv.Atoi(pageStr); err != nil {
39 page = 0
40 } else {
41 page = p
42 }
43
44 return &repository.Pagination{
45 Page: page,
46 Size: size,
47 }
48}
49
50func NewMediaView(
51 mediaRepository repository.MediaRepository,
52 userRepository repository.UserRepository,
53) *MediaView {
54 return &MediaView{
55 mediaRepository: mediaRepository,
56 userRepository: userRepository,
57 }
58}
59
60func (self *MediaView) Index(ctx *fasthttp.RequestCtx) error {
61 p := getPagination(ctx)
62 token := ext.GetTokenFromCtx(ctx)
63
64 userPath, err := self.userRepository.GetPathFromUserID(ctx, token.UserID)
65 if err != nil {
66 return err
67 }
68
69 p.Path = userPath
70 medias, err := self.mediaRepository.List(ctx, p)
71 if err != nil {
72 return err
73 }
74
75 page := &templates.MediaPage{
76 Medias: medias,
77 Next: &repository.Pagination{
78 Size: p.Size,
79 Page: p.Page + 1,
80 },
81 }
82
83 templates.WritePageTemplate(ctx, page)
84
85 return nil
86}
87
88func (self *MediaView) GetImage(ctx *fasthttp.RequestCtx) error {
89 pathHash := string(ctx.FormValue("path_hash"))
90
91 media, err := self.mediaRepository.Get(ctx, pathHash)
92 if err != nil {
93 return err
94 }
95
96 ctx.Response.Header.SetContentType(media.MIMEType)
97 fasthttp.ServeFileUncompressed(ctx, media.Path)
98 return nil
99}
100
101func (self *MediaView) GetThumbnail(ctx *fasthttp.RequestCtx) error {
102 pathHash := string(ctx.FormValue("path_hash"))
103
104 path, err := self.mediaRepository.GetThumbnailPath(ctx, pathHash)
105 if err != nil {
106 ctx.Redirect("/media/image?path_hash="+pathHash, 307)
107 // nolint: nilerr
108 return nil
109 }
110
111 ctx.Request.Header.SetContentType("image/jpeg")
112 fasthttp.ServeFileUncompressed(ctx, path)
113 return nil
114}
115
116func (self *MediaView) SetMyselfIn(r *ext.Router) {
117 r.GET("/media", self.Index)
118 r.POST("/media", self.Index)
119
120 r.GET("/media/image", self.GetImage)
121 r.GET("/media/thumbnail", self.GetThumbnail)
122}