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/components/media"
10 "git.sr.ht/~gabrielgio/img/pkg/ext"
11)
12
13type (
14 MediaView struct {
15 mediaRepository media.Repository
16 }
17
18 Page struct {
19 Medias []*media.Media
20 Next *media.Pagination
21 }
22)
23
24func getPagination(ctx *fasthttp.RequestCtx) *media.Pagination {
25 var (
26 size int
27 page int
28 sizeStr = string(ctx.FormValue("size"))
29 pageStr = string(ctx.FormValue("page"))
30 )
31
32 if sizeStr == "" {
33 size = 100
34 } else if s, err := strconv.Atoi(sizeStr); err != nil {
35 size = 100
36 } else {
37 size = s
38 }
39
40 if pageStr == "" {
41 page = 0
42 } else if p, err := strconv.Atoi(pageStr); err != nil {
43 page = 0
44 } else {
45 page = p
46 }
47
48 return &media.Pagination{
49 Page: page,
50 Size: size,
51 }
52}
53
54func NewMediaView(mediaRepository media.Repository) *MediaView {
55 return &MediaView{
56 mediaRepository: mediaRepository,
57 }
58}
59
60func (self *MediaView) Index(ctx *fasthttp.RequestCtx) error {
61 p := getPagination(ctx)
62 medias, err := self.mediaRepository.List(ctx, p)
63 if err != nil {
64 return err
65 }
66
67 err = img.Render(ctx, "media.html", &img.HTMLView[*Page]{
68 Title: "Media",
69 Data: &Page{
70 Medias: medias,
71 Next: &media.Pagination{
72 Size: p.Size,
73 Page: p.Page + 1,
74 },
75 },
76 })
77 if err != nil {
78 return err
79 }
80 return nil
81}
82
83func (self *MediaView) GetImage(ctx *fasthttp.RequestCtx) error {
84 pathHash := string(ctx.FormValue("path_hash"))
85
86 media, err := self.mediaRepository.Get(ctx, pathHash)
87 if err != nil {
88 return err
89 }
90
91 ctx.Response.Header.SetContentType(media.MIMEType)
92 fasthttp.ServeFileUncompressed(ctx, media.Path)
93 return nil
94}
95
96func (self *MediaView) SetMyselfIn(r *ext.Router) {
97 r.GET("/media", self.Index)
98 r.POST("/media", self.Index)
99
100 r.GET("/media/image", self.GetImage)
101}