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 if err != nil {
86 return err
87 }
88 return nil
89}
90
91func (self *MediaView) GetImage(ctx *fasthttp.RequestCtx) error {
92 pathHash := string(ctx.FormValue("path_hash"))
93
94 media, err := self.mediaRepository.Get(ctx, pathHash)
95 if err != nil {
96 return err
97 }
98
99 ctx.Response.Header.SetContentType(media.MIMEType)
100 fasthttp.ServeFileUncompressed(ctx, media.Path)
101 return nil
102}
103
104func (self *MediaView) GetThumbnail(ctx *fasthttp.RequestCtx) error {
105 pathHash := string(ctx.FormValue("path_hash"))
106
107 path, err := self.mediaRepository.GetThumbnailPath(ctx, pathHash)
108 if err != nil {
109 ctx.Redirect("/media/image?path_hash="+pathHash, 307)
110 // nolint: nilerr
111 return nil
112 }
113
114 ctx.Request.Header.SetContentType("image/jpeg")
115 fasthttp.ServeFileUncompressed(ctx, path)
116 return nil
117}
118
119func (self *MediaView) SetMyselfIn(r *ext.Router) {
120 r.GET("/media", self.Index)
121 r.POST("/media", self.Index)
122
123 r.GET("/media/image", self.GetImage)
124 r.GET("/media/thumbnail", self.GetThumbnail)
125}