2023-09-11 16:25:39 +00:00
|
|
|
/*
|
|
|
|
Copyright © 2023 Seednode <seednode@seedno.de>
|
|
|
|
*/
|
|
|
|
|
|
|
|
package formats
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
2023-09-11 21:05:38 +00:00
|
|
|
"net/http"
|
2023-09-11 16:25:39 +00:00
|
|
|
"os"
|
2023-09-12 18:06:45 +00:00
|
|
|
"path/filepath"
|
2023-09-11 16:25:39 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type SupportedFormat struct {
|
2023-09-12 00:43:18 +00:00
|
|
|
Css string
|
|
|
|
Title func(queryParams, fileUri, filePath, fileName, mime string) string
|
|
|
|
Body func(queryParams, fileUri, filePath, fileName, mime string) string
|
2023-09-11 16:25:39 +00:00
|
|
|
Extensions []string
|
2023-09-11 21:05:38 +00:00
|
|
|
MimeTypes []string
|
2023-09-12 00:43:18 +00:00
|
|
|
Validate func(filePath string) bool
|
2023-09-11 16:25:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type SupportedFormats struct {
|
2023-09-12 18:06:45 +00:00
|
|
|
Extensions map[string]*SupportedFormat
|
|
|
|
MimeTypes map[string]*SupportedFormat
|
2023-09-11 16:25:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *SupportedFormats) Add(t *SupportedFormat) {
|
2023-09-12 18:06:45 +00:00
|
|
|
for _, v := range t.Extensions {
|
|
|
|
_, exists := s.Extensions[v]
|
|
|
|
if !exists {
|
|
|
|
s.Extensions[v] = t
|
|
|
|
}
|
2023-09-11 16:25:39 +00:00
|
|
|
}
|
|
|
|
|
2023-09-12 18:06:45 +00:00
|
|
|
for _, v := range t.MimeTypes {
|
|
|
|
_, exists := s.Extensions[v]
|
|
|
|
if !exists {
|
|
|
|
s.MimeTypes[v] = t
|
2023-09-11 16:25:39 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-09-12 18:06:45 +00:00
|
|
|
func FileType(path string, registeredFormats *SupportedFormats) (bool, *SupportedFormat, string, error) {
|
2023-09-11 16:25:39 +00:00
|
|
|
file, err := os.Open(path)
|
|
|
|
switch {
|
|
|
|
case errors.Is(err, os.ErrNotExist):
|
|
|
|
return false, nil, "", nil
|
|
|
|
case err != nil:
|
|
|
|
return false, nil, "", err
|
|
|
|
}
|
|
|
|
defer file.Close()
|
|
|
|
|
2023-09-11 21:05:38 +00:00
|
|
|
head := make([]byte, 512)
|
2023-09-11 16:25:39 +00:00
|
|
|
file.Read(head)
|
|
|
|
|
2023-09-11 21:05:38 +00:00
|
|
|
mimeType := http.DetectContentType(head)
|
2023-09-11 16:25:39 +00:00
|
|
|
|
2023-09-12 18:06:45 +00:00
|
|
|
// try identifying files by mime types first
|
|
|
|
fileType, exists := registeredFormats.MimeTypes[mimeType]
|
|
|
|
if exists {
|
|
|
|
return fileType.Validate(path), fileType, mimeType, nil
|
|
|
|
}
|
2023-09-11 16:25:39 +00:00
|
|
|
|
2023-09-12 18:06:45 +00:00
|
|
|
// if mime type detection fails, use the file extension
|
|
|
|
fileType, exists = registeredFormats.Extensions[filepath.Ext(path)]
|
|
|
|
if exists {
|
|
|
|
return fileType.Validate(path), fileType, mimeType, nil
|
2023-09-11 16:25:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return false, nil, "", nil
|
|
|
|
}
|