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