aboutsummaryrefslogtreecommitdiff
path: root/pkg/view/media.go
blob: 22f950d8050cba87ad40c33a420cb80e29625dc0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package view

import (
	"strconv"

	"github.com/valyala/fasthttp"

	"git.sr.ht/~gabrielgio/img"
	"git.sr.ht/~gabrielgio/img/pkg/components/media"
	"git.sr.ht/~gabrielgio/img/pkg/ext"
)

type (
	MediaView struct {
		mediaRepository media.Repository
	}

	Page struct {
		Medias []*media.Media
		Next   *media.Pagination
	}
)

func getPagination(ctx *fasthttp.RequestCtx) *media.Pagination {
	var (
		size    int
		page    int
		sizeStr = string(ctx.FormValue("size"))
		pageStr = string(ctx.FormValue("page"))
	)

	if sizeStr == "" {
		size = 100
	} else if s, err := strconv.Atoi(sizeStr); err != nil {
		size = 100
	} else {
		size = s
	}

	if pageStr == "" {
		page = 0
	} else if p, err := strconv.Atoi(pageStr); err != nil {
		page = 0
	} else {
		page = p
	}

	return &media.Pagination{
		Page: page,
		Size: size,
	}
}

func NewMediaView(mediaRepository media.Repository) *MediaView {
	return &MediaView{
		mediaRepository: mediaRepository,
	}
}

func (self *MediaView) Index(ctx *fasthttp.RequestCtx) error {
	p := getPagination(ctx)
	medias, err := self.mediaRepository.List(ctx, p)
	if err != nil {
		return err
	}

	err = img.Render(ctx, "media.html", &img.HTMLView[*Page]{
		Title: "Media",
		Data: &Page{
			Medias: medias,
			Next: &media.Pagination{
				Size: p.Size,
				Page: p.Page + 1,
			},
		},
	})
	if err != nil {
		return err
	}
	return nil
}

func (self *MediaView) GetImage(ctx *fasthttp.RequestCtx) error {
	pathHash := string(ctx.FormValue("path_hash"))

	media, err := self.mediaRepository.Get(ctx, pathHash)
	if err != nil {
		return err
	}

	ctx.Response.Header.SetContentType(media.MIMEType)
	ctx.SendFile(media.Path)
	return nil
}

func (self *MediaView) SetMyselfIn(r *ext.Router) {
	r.GET("/media", self.Index)
	r.POST("/media", self.Index)

	r.GET("/media/image", self.GetImage)
}