lens @ master

  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	user := ext.GetUserFromCtx(r)
 34
 35	// TODO: optmize call, GetPathFromUserID may no be necessary
 36	userPath, err := self.userRepository.GetPathFromUserID(r.Context(), user.ID)
 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	medias, err := self.mediaRepository.List(r.Context(), p)
 73	if err != nil {
 74		return err
 75	}
 76
 77	settings, err := self.settingsRepository.Load(r.Context())
 78	if err != nil {
 79		return err
 80	}
 81
 82	page := &templates.AlbumPage{
 83		Medias: medias,
 84		Albums: albums,
 85		Name:   album.Name,
 86		Next: &repository.Pagination{
 87			Size:    p.Size,
 88			Page:    p.Page + 1,
 89			AlbumID: &album.ID,
 90		},
 91		Settings: settings,
 92	}
 93
 94	templates.WritePageTemplate(w, page, user.IsAdmin)
 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}