]> git.r.bdr.sh - rbdr/mobius/blob - hotline/file_path.go
Fix upload folder name pattern matching
[rbdr/mobius] / hotline / file_path.go
1 package hotline
2
3 import (
4 "bytes"
5 "encoding/binary"
6 "errors"
7 "path"
8 "strings"
9 )
10
11 const pathSeparator = "/" // File path separator TODO: make configurable to support Windows
12
13 // FilePathItem represents the file or directory portion of a delimited file path (e.g. foo and bar in "/foo/bar")
14 // 00 00
15 // 09
16 // 73 75 62 66 6f 6c 64 65 72 // "subfolder"
17 type FilePathItem struct {
18 Len byte
19 Name []byte
20 }
21
22 func NewFilePathItem(b []byte) FilePathItem {
23 return FilePathItem{
24 Len: b[2],
25 Name: b[3:],
26 }
27 }
28
29 type FilePath struct {
30 ItemCount [2]byte
31 Items []FilePathItem
32 }
33
34 const minFilePathLen = 2
35
36 func (fp *FilePath) UnmarshalBinary(b []byte) error {
37 if b == nil {
38 return nil
39 }
40 if len(b) < minFilePathLen {
41 return errors.New("insufficient bytes")
42 }
43 err := binary.Read(bytes.NewReader(b[0:2]), binary.BigEndian, &fp.ItemCount)
44 if err != nil {
45 return err
46 }
47
48 pathData := b[2:]
49 for i := uint16(0); i < fp.Len(); i++ {
50 segLen := pathData[2]
51 fp.Items = append(fp.Items, NewFilePathItem(pathData[:segLen+3]))
52 pathData = pathData[3+segLen:]
53 }
54
55 return nil
56 }
57
58 func (fp *FilePath) IsDropbox() bool {
59 if fp.Len() == 0 {
60 return false
61 }
62
63 return strings.Contains(strings.ToLower(string(fp.Items[fp.Len()-1].Name)), "drop box")
64 }
65
66 func (fp *FilePath) IsUploadDir() bool {
67 if fp.Len() == 0 {
68 return false
69 }
70
71 return strings.Contains(strings.ToLower(string(fp.Items[fp.Len()-1].Name)), "upload")
72 }
73
74 func (fp *FilePath) Len() uint16 {
75 return binary.BigEndian.Uint16(fp.ItemCount[:])
76 }
77
78 func (fp *FilePath) String() string {
79 out := []string{"/"}
80 for _, i := range fp.Items {
81 out = append(out, string(i.Name))
82 }
83
84 return path.Join(out...)
85 }
86
87 func ReadFilePath(filePathFieldData []byte) string {
88 var fp FilePath
89 err := fp.UnmarshalBinary(filePathFieldData)
90 if err != nil {
91 // TODO
92 }
93 return fp.String()
94 }
95
96 func readPath(fileRoot string, filePath, fileName []byte) (fullPath string, err error) {
97 var fp FilePath
98 if filePath != nil {
99 if err = fp.UnmarshalBinary(filePath); err != nil {
100 return "", err
101 }
102 }
103
104 fullPath = path.Join(
105 "/",
106 fileRoot,
107 fp.String(),
108 path.Join("/", string(fileName)),
109 )
110
111 return fullPath, nil
112 }