lens @ d2a9e162352646e7f1550823c3d88496590f8760

  1package view
  2
  3import (
  4	"net/http"
  5
  6	"git.sr.ht/~gabrielgio/img/pkg/database/repository"
  7	"git.sr.ht/~gabrielgio/img/pkg/ext"
  8	"git.sr.ht/~gabrielgio/img/templates"
  9)
 10
 11type (
 12	AlbumView struct {
 13		mediaRepository    repository.MediaRepository
 14		userRepository     repository.UserRepository
 15		settingsRepository repository.SettingsRepository
 16	}
 17)
 18
 19func NewAlbumView(
 20	mediaRepository repository.MediaRepository,
 21	userRepository repository.UserRepository,
 22	settingsRepository repository.SettingsRepository,
 23) *AlbumView {
 24	return &AlbumView{
 25		mediaRepository:    mediaRepository,
 26		userRepository:     userRepository,
 27		settingsRepository: settingsRepository,
 28	}
 29}
 30
 31func (self *AlbumView) Index(w http.ResponseWriter, r *http.Request) error {
 32	p := getPagination(r)
 33	token := ext.GetTokenFromCtx(w, r)
 34
 35	// TODO: optmize call, GetPathFromUserID may no be necessary
 36	userPath, err := self.userRepository.GetPathFromUserID(r.Context(), token.UserID)
 37	if err != nil {
 38		return err
 39	}
 40
 41	var albums []*repository.Album
 42	var album *repository.Album
 43
 44	if p.AlbumID == nil {
 45		// use user path as default value
 46		p.Path = userPath
 47
 48		album, err = self.mediaRepository.GetAlbumByAbsolutePath(r.Context(), p.Path)
 49		if err != nil {
 50			return err
 51		}
 52
 53		albums, err = self.mediaRepository.ListAlbums(r.Context(), album.ID)
 54		if err != nil {
 55			return err
 56		}
 57	} else {
 58		album, err = self.mediaRepository.GetAlbum(r.Context(), *p.AlbumID)
 59		if err != nil {
 60			return err
 61		}
 62
 63		// TODO: User can enter a album out of its bounderies
 64		p.Path = album.Path
 65
 66		albums, err = self.mediaRepository.ListAlbums(r.Context(), *p.AlbumID)
 67		if err != nil {
 68			return err
 69		}
 70
 71	}
 72
 73	medias, err := self.mediaRepository.List(r.Context(), p)
 74	if err != nil {
 75		return err
 76	}
 77
 78	settings, err := self.settingsRepository.Load(r.Context())
 79	if err != nil {
 80		return err
 81	}
 82
 83	page := &templates.AlbumPage{
 84		Medias: medias,
 85		Albums: albums,
 86		Name:   album.Name,
 87		Next: &repository.Pagination{
 88			Size: p.Size,
 89			Page: p.Page + 1,
 90		},
 91		Settings: settings,
 92	}
 93
 94	templates.WritePageTemplate(w, page)
 95
 96	return nil
 97}
 98
 99func (self *AlbumView) SetMyselfIn(r *ext.Router) {
100	r.GET("/album/", self.Index)
101	r.POST("/album/", self.Index)
102}