aboutsummaryrefslogtreecommitdiff
path: root/pkg/service/filesystem.go
blob: 3516ce2642ba63e2d8ef7f774469657d64123c70 (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
package service

import (
	"io/fs"
	"net/url"
	"path"
	"strings"

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

type (
	FileSystemController struct {
		repository repository.FileSystemRepository
	}

	DirectoryParam struct {
		Name           string
		UrlEncodedPath string
	}

	FileParam struct {
		UrlEncodedPath string
		Info           fs.FileInfo
	}

	Page struct {
		History []*DirectoryParam
		Files   []*FileParam
	}
)

func NewFileSystemController(repository repository.FileSystemRepository) *FileSystemController {
	return &FileSystemController{
		repository: repository,
	}
}

func getHistory(filepath string) []*DirectoryParam {
	var (
		paths  = strings.Split(filepath, "/")
		result = make([]*DirectoryParam, 0, len(paths))
		acc    = ""
	)

	// add root folder
	result = append(result, &DirectoryParam{
		Name:           "...",
		UrlEncodedPath: "",
	})

	if len(paths) == 1 && paths[0] == "" {
		return result
	}

	for _, p := range paths {
		acc = path.Join(acc, p)
		result = append(result, &DirectoryParam{
			Name:           p,
			UrlEncodedPath: url.QueryEscape(acc),
		})
	}
	return result
}

func (self *FileSystemController) GetPage(filepath string) (*Page, error) {
	decodedPath, err := url.QueryUnescape(filepath)
	if err != nil {
		return nil, err
	}

	files, err := self.repository.List(decodedPath)
	if err != nil {
		return nil, err
	}

	params := make([]*FileParam, 0, len(files))
	for _, info := range files {
		fullPath := path.Join(decodedPath, info.Name())
		scapedFullPath := url.QueryEscape(fullPath)
		params = append(params, &FileParam{
			Info:           info,
			UrlEncodedPath: scapedFullPath,
		})
	}

	return &Page{
		Files:   params,
		History: getHistory(decodedPath),
	}, nil
}