aboutsummaryrefslogtreecommitdiff
path: root/pkg/view/album.go
blob: b19e381bb5008ca4468fc6bd5f7b492ab07d8148 (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
102
package view

import (
	"net/http"

	"git.sr.ht/~gabrielgio/img/pkg/database/repository"
	"git.sr.ht/~gabrielgio/img/pkg/ext"
	"git.sr.ht/~gabrielgio/img/templates"
)

type (
	AlbumView struct {
		mediaRepository    repository.MediaRepository
		userRepository     repository.UserRepository
		settingsRepository repository.SettingsRepository
	}
)

func NewAlbumView(
	mediaRepository repository.MediaRepository,
	userRepository repository.UserRepository,
	settingsRepository repository.SettingsRepository,
) *AlbumView {
	return &AlbumView{
		mediaRepository:    mediaRepository,
		userRepository:     userRepository,
		settingsRepository: settingsRepository,
	}
}

func (self *AlbumView) Index(w http.ResponseWriter, r *http.Request) error {
	p := getPagination(r)
	token := ext.GetTokenFromCtx(r)

	// TODO: optmize call, GetPathFromUserID may no be necessary
	userPath, err := self.userRepository.GetPathFromUserID(r.Context(), token.UserID)
	if err != nil {
		return err
	}

	var albums []*repository.Album
	var album *repository.Album

	if p.AlbumID == nil {
		// use user path as default value
		p.Path = userPath

		album, err = self.mediaRepository.GetAlbumByAbsolutePath(r.Context(), p.Path)
		if err != nil {
			return err
		}

		albums, err = self.mediaRepository.ListAlbums(r.Context(), album.ID)
		if err != nil {
			return err
		}
	} else {
		album, err = self.mediaRepository.GetAlbum(r.Context(), *p.AlbumID)
		if err != nil {
			return err
		}

		// TODO: User can enter a album out of its bounderies
		p.Path = album.Path

		albums, err = self.mediaRepository.ListAlbums(r.Context(), *p.AlbumID)
		if err != nil {
			return err
		}
	}

	medias, err := self.mediaRepository.List(r.Context(), p)
	if err != nil {
		return err
	}

	settings, err := self.settingsRepository.Load(r.Context())
	if err != nil {
		return err
	}

	page := &templates.AlbumPage{
		Medias: medias,
		Albums: albums,
		Name:   album.Name,
		Next: &repository.Pagination{
			Size:    p.Size,
			Page:    p.Page + 1,
			AlbumID: &album.ID,
		},
		Settings: settings,
	}

	templates.WritePageTemplate(w, page)

	return nil
}

func (self *AlbumView) SetMyselfIn(r *ext.Router) {
	r.GET("/album/", self.Index)
	r.POST("/album/", self.Index)
}