Files
zurg/pkg/davextra/util.go
Ben Sarmiento acee02377e Proper caching
2023-10-18 12:36:34 +02:00

53 lines
1.3 KiB
Go

package davextra
import (
"fmt"
"net/url"
"path/filepath"
"regexp"
"strings"
)
// GetLinkFragment returns the longest alphanumeric string from a link
func GetLinkFragment(link string) string {
re := regexp.MustCompile(`\w+`)
matches := re.FindAllString(link, -1) // Returns all matches
var longestMatch string
for _, match := range matches {
if len(match) > len(longestMatch) {
longestMatch = match
}
}
return longestMatch[:4]
}
// InsertLinkFragment inserts the link ID into a filename
// returns the new filename
func InsertLinkFragment(filename, dupeID string) string {
ext := filepath.Ext(filename)
name := strings.TrimSuffix(filename, ext)
return fmt.Sprintf("%s DMM%s%s", name, dupeID, ext)
}
// ExtractLinkFragment extracts the link ID from a filename
// returns the original filename and the link ID
func ExtractLinkFragment(filename string) (string, string) {
filenameV2, err := url.PathUnescape(filename)
if err != nil {
filenameV2 = filename
}
ext := filepath.Ext(filenameV2)
name := strings.TrimSuffix(filenameV2, ext)
r := regexp.MustCompile(`\sDMM(\w+)`)
matches := r.FindStringSubmatch(name)
if len(matches) < 2 {
// No ID found
return filenameV2, ""
}
// Remove ID from filename
originalName := strings.Replace(name, matches[0], "", 1)
return originalName + ext, matches[1]
}