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 settingsRepository repository.SettingsRepository
18 }
19)
20
21func getPagination(ctx *fasthttp.RequestCtx) *repository.Pagination {
22 var (
23 size int
24 page int
25 sizeStr = string(ctx.FormValue("size"))
26 pageStr = string(ctx.FormValue("page"))
27 )
28
29 if sizeStr == "" {
30 size = 100
31 } else if s, err := strconv.Atoi(sizeStr); err != nil {
32 size = 100
33 } else {
34 size = s
35 }
36
37 if pageStr == "" {
38 page = 0
39 } else if p, err := strconv.Atoi(pageStr); err != nil {
40 page = 0
41 } else {
42 page = p
43 }
44
45 return &repository.Pagination{
46 Page: page,
47 Size: size,
48 }
49}
50
51func NewMediaView(
52 mediaRepository repository.MediaRepository,
53 userRepository repository.UserRepository,
54 settingsRepository repository.SettingsRepository,
55) *MediaView {
56 return &MediaView{
57 mediaRepository: mediaRepository,
58 userRepository: userRepository,
59 settingsRepository: settingsRepository,
60 }
61}
62
63func (self *MediaView) Index(ctx *fasthttp.RequestCtx) error {
64 p := getPagination(ctx)
65 token := ext.GetTokenFromCtx(ctx)
66
67 userPath, err := self.userRepository.GetPathFromUserID(ctx, token.UserID)
68 if err != nil {
69 return err
70 }
71
72 p.Path = userPath
73 medias, err := self.mediaRepository.List(ctx, p)
74 if err != nil {
75 return err
76 }
77
78 settings, err := self.settingsRepository.Load(ctx)
79 if err != nil {
80 return err
81 }
82
83 page := &templates.MediaPage{
84 Medias: medias,
85 Next: &repository.Pagination{
86 Size: p.Size,
87 Page: p.Page + 1,
88 },
89 Settings: settings,
90 }
91
92 templates.WritePageTemplate(ctx, page)
93
94 return nil
95}
96
97func (self *MediaView) GetImage(ctx *fasthttp.RequestCtx) error {
98 pathHash := string(ctx.FormValue("path_hash"))
99
100 media, err := self.mediaRepository.Get(ctx, pathHash)
101 if err != nil {
102 return err
103 }
104
105 ctx.Response.Header.SetContentType(media.MIMEType)
106 fasthttp.ServeFileUncompressed(ctx, media.Path)
107 return nil
108}
109
110func (self *MediaView) GetThumbnail(ctx *fasthttp.RequestCtx) error {
111 pathHash := string(ctx.FormValue("path_hash"))
112
113 path, err := self.mediaRepository.GetThumbnailPath(ctx, pathHash)
114 if err != nil {
115 ctx.Redirect("/media/image?path_hash="+pathHash, 307)
116 // nolint: nilerr
117 return nil
118 }
119
120 ctx.Request.Header.SetContentType("image/jpeg")
121 fasthttp.ServeFileUncompressed(ctx, path)
122 return nil
123}
124
125func (self *MediaView) SetMyselfIn(r *ext.Router) {
126 r.GET("/media", self.Index)
127 r.POST("/media", self.Index)
128
129 r.GET("/media/image", self.GetImage)
130 r.GET("/media/thumbnail", self.GetThumbnail)
131}