lens @ master

 1package view
 2
 3import (
 4	"mime"
 5	"net/http"
 6	"path/filepath"
 7
 8	"git.sr.ht/~gabrielgio/img/pkg/database/repository"
 9	"git.sr.ht/~gabrielgio/img/pkg/ext"
10	"git.sr.ht/~gabrielgio/img/pkg/service"
11	"git.sr.ht/~gabrielgio/img/templates"
12)
13
14type (
15	FileSystemView struct {
16		fsService service.FileSystemController
17		settings  repository.SettingsRepository
18	}
19	FilePage struct {
20		Page      *service.Page
21		ShowMode  bool
22		ShowOwner bool
23	}
24)
25
26func NewFileSystemView(
27	controller service.FileSystemController,
28	settingsRepository repository.SettingsRepository,
29) *FileSystemView {
30	return &FileSystemView{
31		fsService: controller,
32		settings:  settingsRepository,
33	}
34}
35
36func (self *FileSystemView) Index(w http.ResponseWriter, r *http.Request) error {
37	var (
38		pathValue = r.FormValue("path")
39		user      = ext.GetUserFromCtx(r)
40	)
41
42	fullpath, err := self.fsService.GetFullpath(r.Context(), user.ID, pathValue)
43	if err != nil {
44		return err
45	}
46
47	isFile, err := self.fsService.IsFile(r.Context(), fullpath)
48	if err != nil {
49		return err
50	}
51
52	if isFile {
53		mimetype := mime.TypeByExtension(filepath.Ext(fullpath))
54		w.Header().Set("Content-Type", mimetype)
55		http.ServeFile(w, r, fullpath)
56		return nil
57	}
58
59	page, err := self.fsService.GetPage(r.Context(), pathValue, fullpath)
60	if err != nil {
61		return err
62	}
63
64	settings, err := self.settings.Load(r.Context())
65	if err != nil {
66		return err
67	}
68
69	templates.WritePageTemplate(w, &templates.FilePage{
70		Page:      page,
71		ShowMode:  settings.ShowMode,
72		ShowOwner: settings.ShowOwner,
73	}, user.IsAdmin)
74
75	return nil
76}
77
78func (self *FileSystemView) SetMyselfIn(r *ext.Router) {
79	r.GET("/", self.Index)
80	r.POST("/", self.Index)
81	r.GET("/fs", self.Index)
82	r.POST("/fs", self.Index)
83}