14 // FilePathItem represents the file or directory portion of a delimited file path (e.g. foo and bar in "/foo/bar")
18 // 73 75 62 66 6f 6c 64 65 72 "subfolder"
19 type FilePathItem struct {
24 const fileItemMinLen = 3
26 // fileItemScanner implements bufio.SplitFunc for parsing incoming byte slices into complete tokens
27 func fileItemScanner(data []byte, _ bool) (advance int, token []byte, err error) {
28 if len(data) < fileItemMinLen {
32 advance = fileItemMinLen + int(data[2])
33 return advance, data[0:advance], nil
36 // Write implements the io.Writer interface for FilePathItem
37 func (fpi *FilePathItem) Write(b []byte) (n int, err error) {
39 return n, errors.New("buflen too small")
42 fpi.Name = b[fileItemMinLen : fpi.Len+fileItemMinLen]
44 return int(fpi.Len) + fileItemMinLen, nil
47 type FilePath struct {
52 // Write implements io.Writer interface for FilePath
53 func (fp *FilePath) Write(b []byte) (n int, err error) {
54 reader := bytes.NewReader(b)
55 err = binary.Read(reader, binary.BigEndian, &fp.ItemCount)
56 if err != nil && !errors.Is(err, io.EOF) {
59 if errors.Is(err, io.EOF) {
63 scanner := bufio.NewScanner(reader)
64 scanner.Split(fileItemScanner)
66 for i := 0; i < int(binary.BigEndian.Uint16(fp.ItemCount[:])); i++ {
70 // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the
71 // scanner re-uses the buffer for subsequent scans.
72 buf := make([]byte, len(scanner.Bytes()))
73 copy(buf, scanner.Bytes())
75 if _, err := fpi.Write(buf); err != nil {
78 fp.Items = append(fp.Items, fpi)
84 // IsDropbox checks if a FilePath matches the special drop box folder type
85 func (fp *FilePath) IsDropbox() bool {
90 return strings.Contains(strings.ToLower(string(fp.Items[fp.Len()-1].Name)), "drop box")
93 func (fp *FilePath) IsUploadDir() bool {
98 return strings.Contains(strings.ToLower(string(fp.Items[fp.Len()-1].Name)), "upload")
101 func (fp *FilePath) IsUserDir() bool {
106 return strings.HasPrefix(string(fp.Items[0].Name), "~")
110 func (fp *FilePath) Len() uint16 {
111 return binary.BigEndian.Uint16(fp.ItemCount[:])
114 func ReadPath(fileRoot string, filePath, fileName []byte) (fullPath string, err error) {
117 if _, err = fp.Write(filePath); err != nil {
123 for _, pathItem := range fp.Items {
124 subPath = filepath.Join("/", subPath, string(pathItem.Name))
127 fullPath = filepath.Join(
130 filepath.Join("/", string(fileName)),
132 fullPath, err = txtDecoder.String(fullPath)
134 return "", fmt.Errorf("invalid filepath encoding: %w", err)