Compare commits

...
22 Commits
Author SHA1 Message Date
Graham Steffaniak 18114347f8 updated with more fixes (#1232) 2025-09-16 19:52:30 -05:00
Graham Steffaniak 99fd8e69db updated with onlyoffice issue fixes (#1231) 2025-09-16 16:20:30 -05:00
Graham Steffaniak 3f67f79a9e updated with user edit form fix (#1230) 2025-09-16 15:06:14 -05:00
Graham Steffaniak 5d1b565ac6 updated with preview fixes (#1229) 2025-09-16 14:23:21 -05:00
Graham Steffaniak 73d66e8b15 fix album art indexing (#1222) 2025-09-16 11:36:49 -05:00
Graham Steffaniak 0a262553b4 Merge branch 'dev/v0.8.6' of github.com:gtsteffaniak/filebrowser into dev/v0.8.6 2025-09-14 10:31:49 -05:00
e398f1f5af Beta/v0.8.5 (#1218)
Co-authored-by: Max <mail@kjmax.com>
Co-authored-by: Kurami <kurami32_kbm@proton.me>
Co-authored-by: Alexander Noyle <alexnoyle@icloud.com>
2025-09-14 10:30:47 -05:00
Graham Steffaniak 60615a7c4d added translations (#1217) 2025-09-13 17:49:58 -05:00
Graham Steffaniak 7a329ba160 Merge branch 'main' into dev/v0.8.5 2025-09-13 17:44:38 -05:00
Graham Steffaniak 1cbe826346 Folder preview thumbnails (#1216) 2025-09-13 17:37:36 -05:00
はらたく aed5c7bed7 feat(i18n): improve Japanese translations (#1215) 2025-09-13 16:44:44 -05:00
Graham Steffaniak 8125211675 removed debug logs for media metadata 2025-09-12 19:44:26 -05:00
Graham Steffaniak e36bca2eb2 v0.8.5 changes 2025-09-12 19:21:18 -05:00
Graham Steffaniak f8dbb2da67 Last minute changes 0.8.5 (#1214) 2025-09-12 19:19:39 -05:00
Graham Steffaniak deab8dce4b Add next previous (#1213) 2025-09-12 13:37:18 -05:00
Graham Steffaniak b8a8ae3c5d updated with metadata changes (#1210) 2025-09-11 09:40:49 -05:00
Graham SteffaniakandNotAlexNoyle b2c2a373dd updated bugfixes (#1206)
Co-authored-by: Alexander Noyle <alexnoyle@icloud.com>
2025-09-10 19:26:23 -05:00
ce177a4f59 fix issues features (#1201)
Co-authored-by: Max <mail@kjmax.com>
Co-authored-by: Kurami <kurami32_kbm@proton.me>
2025-09-10 14:12:28 -05:00
NotAlexNoyle 30503683c6 Fix typo in Configuration Setup (#1205) 2025-09-10 13:23:05 -05:00
Graham Steffaniak 2d2a3d7707 updated debugging and scoped path (#1198) 2025-09-09 12:21:16 -05:00
Graham Steffaniak 7baf2653e0 feat: remember view settings per folder (#1196) 2025-09-08 18:31:00 -05:00
256f4ca0b8 Beta/v0.8.4 (#1187)
Co-authored-by: Max <mail@kjmax.com>
Co-authored-by: Kurami <kurami32_kbm@proton.me>
2025-09-05 18:56:18 -05:00
175 changed files with 13685 additions and 4849 deletions

No files matched your search

+91 -1
View File
@@ -2,6 +2,96 @@
All notable changes to this project will be documented in this file. For commit guidelines, please refer to [Standard Version](https://github.com/conventional-changelog/standard-version).
## v0.8.6-beta
**Notes**:
- Please remove `indexAbumArt` config option from your config: it has been deprecated... I found a way to detect album art without impacting indexing performance -- so its default behavior.
- Download button should be invisible before password input #1162
- opus files / opus files detected wrongly #1164
- changed autoplay behavior on plyr to not start playing if blocked instead of playing muted.
- QR-Code disappearing / sliding out from shared link #1155
- audio player matches dark/light mode better
**BugFixes**:
- Copy/Move index update changes to be more thorough and update album artwork #1220 #1219
- fix preview related issues #1225 #1223
- Scrollbar missing on user-edit-prompt in v0.8.5-beta #1221
- copy share download link inconsistency #1207
- fixed some onlyoffice related issues #1192 #1068
- Creating a file, then a folder with the same name makes the folder unusable #1167
- fix plyr issue switching from video to audio via next/previous button.
## v0.8.5-beta
**New Features**:
- backend media metadata processing
- significantly improved performance
- album artwork shows in listing view as preview thumbnail Album art thumbnail: display embedded covers of mp3/flac files #925
- folders can show album art if enabled with indexing `server.sources.config.indexAlbumArt:true`
- removed need for frontend dependancies.
- optional thumbnail support for folders -- uses first child item with thumbnail as cover. Useful in combination with album metadata support to show album covers for folders with music.
- Remember folder view type (and sorting) for each folder #966
- heic is supported in viewer (via ffmpeg conversion) when on non-safari browser. This can be enabled via `integrations.ffmpeg.convert.impagePreview.heic: true` #1191
- OnlyOffice: Add option to open documents in viewer mode (`integrations.office.viewOnly`) #1193
- Exclude folders and file names 'starting with' or wildcard option #1054
- added better info for failed uploads #1050
- upload prompt "clear completed" can be changed to "clear all" in uploads & downloads settings to clear error and conflict states as well. #1128
- share 'default view mode' option #1212
- Universal Next/Previous buttons
- available for all listing items (including office/markdown etc)
- remembers sort order from parent directory
- new "Quick Jump" prompt if you drag the next/previous icons. This shows other files available to "jump" directly to quickly.
**Notes**:
- Added more tests to ensure new features work in future.
- caching for preview images is md5 based. Moved, renamed, or duplicate images don't get re-generated. Same album artwork shares cache.
- Hide @eaDir folder by default #1212
- defaults to hide "@eadir" folders (common for synology) #1212
- After move/copy, ability to move to the destination folder #999
**BugFixes**:
- Access Management: issue with access settings #1195
- fix shutdown panic related to sse connection
- Custom theming not working in 0.8.4 beta #1204
- Config Viewer not working #1189
- "Path not found" when trying to share a file or folder inside a sub-directory #1139
- files containing "+" in share issue #1089
## v0.8.4-beta
**New Features**:
- New media player styles and features
- Custom Media Player: enhanced media player using plyr thanks @Kurami32 (see #1160)
- Custom Media Player: also adds support for metadata
- added embeded video subtitle support (for both native and custom player). @maxbin123 #1072 #1157
- Users can disable the customer player and opt of native in profile settings.
- Option to disable backend update check via `server.disableUpdateCheck` #1134
- added `frontend.favicon` and `frontend.description` for html overrides
- onlyoffice is now supported in shares. Both viewing and editing can be configured per-share.
- Added only office debug view and wiki to assist with debugging issues #1068 #911 #1074
- Dark mode enforcement possible for shared links #1029
- added `System & Admin` section to settings
- includes a new config viewer to see current running config (hides secrets) #838
- added `server.minSearchLength` to allow adjusting the length requirement for search #1174
**Notes**:
- access management: specific folders/files with access are shown instead permission denied for parent folder
- navigation no longer appends last location hash which should fix some unwanted navation behavior #1070
- altered the context menu style and behavior.
- documentation update: comma or Space separated extensions #1138
- Files and folders can be created with "/" or "\" on the name #1126
- Share management should not be allowed without authentication #1163
- Question about customizing session timeout #1184
**BugFixes**:
- access management: delay showing rule changes in the list fixed. #1131
- Color names are not localized #1159
- rename issues #1170 #1171
- some shortcuts not working #1056
- Can't copy/paste text on mobile #1168
- Can't change between images inside of the share image viewer. #1144
- fixed and updated translations with variables always showing english.
## v0.8.3-beta
**BugFixes**:
@@ -18,7 +108,7 @@ All notable changes to this project will be documented in this file. For commit
**Notes**:
- 8.0 ffmpeg version bundled with docker
- go 1.25 upgrade with green tea GC enabled
- totp secrets accept non-secure strings, only throwing warning
- totp secrets accept non-secure strings, only throwing warning
- adjusted download limit so it also counts viewing text "content" of files (like in editor). You can also "disable file viewing" to stop the editor from showing. lower quality file image previews are not counted as downloads.
- updated invalid share message to be more clear https://github.com/gtsteffaniak/filebrowser/issues/1120
+3 -3
View File
@@ -9,14 +9,14 @@ Thank you for your interest in contributing to FileBrowser Quantum! This guide w
- **Docker** (optional, for containerized development)
- **Git**
### Required Tools
### Optional Tools
- **ffmpeg**: Required for video thumbnail generation
- **ffmpeg**: For media features (subtitles, thumbnails, heic)
- Ubuntu/Debian: `sudo apt-get install ffmpeg`
- macOS: `brew install ffmpeg`
- Windows: Download from [ffmpeg.org](https://ffmpeg.org/download.html)
- **mupdf-tools**: Required for PDF preview generation
- **mupdf-tools**: For PDF preview generation
- Ubuntu/Debian: `sudo apt-get install mupdf-tools`
- macOS: `brew install mupdf-tools`
- Windows: Download from [mupdf.com](https://mupdf.com/downloads/)
+3
View File
@@ -16,6 +16,9 @@ RUN upx filebrowser
FROM node:lts-slim AS nbuild
WORKDIR /app
COPY ./frontend/package.json ./
RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates \
&& git config --global url."https://github.com/".insteadOf "git@github.com:" \
&& git config --global url."https://github.com/".insteadOf "ssh://git@github.com/"
RUN npm i --maxsockets 1
COPY ./frontend/ ./
RUN npm run build-docker
+1
View File
@@ -10,6 +10,7 @@ COPY [ "./frontend/tests/", "./tests" ]
WORKDIR /app/backend/
COPY [ "./backend/filebrowser*", "./"]
COPY [ "./backend/reduce-rounded-corners.css", "./no-rounded.css" ]
RUN mkdir -p ./http/dist
COPY [ "./backend/http/embed/", "./http/dist/"]
+3
View File
@@ -14,6 +14,9 @@ RUN upx filebrowser
FROM node:lts-slim AS nbuild
WORKDIR /app
COPY ./frontend/package.json ./
RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates \
&& git config --global url."https://github.com/".insteadOf "git@github.com:" \
&& git config --global url."https://github.com/".insteadOf "ssh://git@github.com/"
RUN npm i --maxsockets 1
COPY ./frontend/ ./
RUN npm run build-docker
+5
View File
@@ -15,6 +15,11 @@ server:
frontend:
name: "Graham's Filebrowser"
disableDefaultLinks: true
styling:
customThemes:
no-rounded:
description: "No rounded corners" # The description of the theme to display in the UI.
css: "no-rounded.css" # The css file path and filename to use for the theme.
externalLinks:
- text: "A playwright test"
url: "https://playwright.dev/"
+2
View File
@@ -19,6 +19,8 @@ frontend:
auth:
methods:
password:
enabled: false
proxy:
enabled: true
header: "X-Username"
@@ -11,7 +11,7 @@ import { defineConfig, devices } from "@playwright/test";
*/
export default defineConfig({
globalSetup: "./tests/playwright/proxy-setup.ts",
timeout: 3000,
timeout: 5000,
testDir: "./tests/playwright/proxy",
/* Run tests in files in parallel */
fullyParallel: false,
+2 -2
View File
@@ -2,7 +2,7 @@ package diskcache
import (
"context"
"crypto/sha1" //nolint:gosec
"crypto/sha1"
"encoding/hex"
"errors"
"fmt"
@@ -106,7 +106,7 @@ func (f *FileCache) getScopedLocks(key string) (lock sync.Locker) {
}
func (f *FileCache) getFileName(key string) string {
hasher := sha1.New() //nolint:gosec
hasher := sha1.New()
_, _ = hasher.Write([]byte(key))
hash := hex.EncodeToString(hasher.Sum(nil))
return filepath.Join(f.dir, fmt.Sprintf("%s/%s/%s", hash[:1], hash[1:3], hash))
+174
View File
@@ -177,3 +177,177 @@ func TestSortItems(t *testing.T) {
})
}
}
func TestDeleteFilesCacheClearing(t *testing.T) {
// Create a temporary directory for testing
tempDir, err := os.MkdirTemp("", "filebrowser_test")
if err != nil {
t.Fatalf("Failed to create temp dir: %v", err)
}
defer os.RemoveAll(tempDir)
// Create a test file
testFile := filepath.Join(tempDir, "Test Object")
err = os.WriteFile(testFile, []byte("test content"), 0644)
if err != nil {
t.Fatalf("Failed to create test file: %v", err)
}
// Initialize a mock index
idx := indexing.Index{
Source: settings.Source{
Path: tempDir,
},
}
// Get the real path and cache it
_, isDir, err := idx.GetRealPath("/Test Object")
if err != nil {
t.Fatalf("Failed to get real path: %v", err)
}
// Verify the file is detected as a file (not directory)
if isDir {
t.Errorf("Expected file to be detected as file, but got directory")
}
// Initialize the index in the indexing system
indexing.Initialize(settings.Source{
Name: "test",
Path: tempDir,
}, true) // true for mock mode
// Delete the file
err = DeleteFiles("test", testFile, tempDir)
if err != nil {
t.Fatalf("Failed to delete file: %v", err)
}
// Create a directory with the same name
testDir := filepath.Join(tempDir, "Test Object")
err = os.Mkdir(testDir, 0755)
if err != nil {
t.Fatalf("Failed to create test directory: %v", err)
}
// Get the real path again - it should now detect it as a directory
// The cache should have been cleared, so it should re-detect the type
realPath2, isDir2, err := idx.GetRealPath("/Test Object")
if err != nil {
t.Fatalf("Failed to get real path after recreation: %v", err)
}
// Verify the directory is detected as a directory
if !isDir2 {
t.Errorf("Expected directory to be detected as directory, but got file. Real path: %s", realPath2)
}
// Clean up
os.RemoveAll(tempDir)
}
func TestOverrideDirectoryToFile(t *testing.T) {
// Create a temporary directory for testing
tempDir, err := os.MkdirTemp("", "filebrowser_test")
if err != nil {
t.Fatalf("Failed to create temp dir: %v", err)
}
defer os.RemoveAll(tempDir)
// Initialize the index in the indexing system
indexing.Initialize(settings.Source{
Name: "test",
Path: tempDir,
}, true) // true for mock mode
// Create a directory first
testDir := filepath.Join(tempDir, "Test Object")
err = os.Mkdir(testDir, 0755)
if err != nil {
t.Fatalf("Failed to create test directory: %v", err)
}
// Now try to create a file with the same name (should work with override)
fileOpts := iteminfo.FileOptions{
Path: "/Test Object",
Source: "test",
}
// Create a test reader with some content
testContent := "This is test file content"
reader := strings.NewReader(testContent)
err = WriteFile(fileOpts, reader)
if err != nil {
t.Fatalf("Failed to create file over directory: %v", err)
}
// Verify the file was created and the directory was removed
stat, err := os.Stat(testDir)
if err != nil {
t.Fatalf("File should exist but got error: %v", err)
}
if stat.IsDir() {
t.Errorf("Expected file but got directory")
}
// Verify the content
content, err := os.ReadFile(testDir)
if err != nil {
t.Fatalf("Failed to read file content: %v", err)
}
if string(content) != testContent {
t.Errorf("Expected content %q but got %q", testContent, string(content))
}
// Clean up
os.RemoveAll(tempDir)
}
func TestOverrideFileToDirectory(t *testing.T) {
// Create a temporary directory for testing
tempDir, err := os.MkdirTemp("", "filebrowser_test")
if err != nil {
t.Fatalf("Failed to create temp dir: %v", err)
}
defer os.RemoveAll(tempDir)
// Initialize the index in the indexing system
indexing.Initialize(settings.Source{
Name: "test",
Path: tempDir,
}, true) // true for mock mode
// Create a file first
testFile := filepath.Join(tempDir, "Test Object")
err = os.WriteFile(testFile, []byte("test content"), 0644)
if err != nil {
t.Fatalf("Failed to create test file: %v", err)
}
// Now try to create a directory with the same name (should work with override)
fileOpts := iteminfo.FileOptions{
Path: "/Test Object/",
Source: "test",
}
err = WriteDirectory(fileOpts)
if err != nil {
t.Fatalf("Failed to create directory over file: %v", err)
}
// Verify the directory was created and the file was removed
stat, err := os.Stat(testFile)
if err != nil {
t.Fatalf("Directory should exist but got error: %v", err)
}
if !stat.IsDir() {
t.Errorf("Expected directory but got file")
}
// Clean up
os.RemoveAll(tempDir)
}
+261 -84
View File
@@ -1,13 +1,8 @@
package files
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"encoding/base64"
"fmt"
"hash"
"io"
"unicode"
"unicode/utf8"
@@ -18,6 +13,7 @@ import (
"strings"
"time"
"github.com/dhowden/tag"
"github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils"
"github.com/gtsteffaniak/filebrowser/backend/common/errors"
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
@@ -28,65 +24,131 @@ import (
"github.com/gtsteffaniak/go-logger/logger"
)
func FileInfoFaster(opts iteminfo.FileOptions) (iteminfo.ExtendedFileInfo, error) {
response := iteminfo.ExtendedFileInfo{}
func FileInfoFaster(opts iteminfo.FileOptions) (*iteminfo.ExtendedFileInfo, error) {
response := &iteminfo.ExtendedFileInfo{}
index := indexing.GetIndex(opts.Source)
if index == nil {
return response, fmt.Errorf("could not get index: %v ", opts.Source)
}
if opts.Access != nil && !opts.Access.Permitted(index.Path, opts.Path, opts.Username) {
return response, errors.ErrPermissionDenied
}
realPath, isDir, err := index.GetRealPath(opts.Path)
if err != nil {
return response, err
return response, fmt.Errorf("could not get real path for requested path: %v", opts.Path)
}
opts.IsDir = isDir
var info *iteminfo.FileInfo
var exists bool
err = index.RefreshFileInfo(opts)
if err != nil {
if err == errors.ErrNotIndexed && index.Config.DisableIndexing {
info, err = index.GetFsDirInfo(opts.Path)
if err != nil {
return response, err
var useFsDirInfo bool
if isDir {
err = index.RefreshFileInfo(opts)
if err != nil {
if err == errors.ErrNotIndexed && index.Config.DisableIndexing {
useFsDirInfo = true
} else if err == errors.ErrNotIndexed {
return response, fmt.Errorf("could not refresh file info: %v", err)
}
} else if err == errors.ErrNotIndexed {
return response, fmt.Errorf("could not refresh file info: %v", err)
}
}
if useFsDirInfo {
info, err = index.GetFsDirInfo(opts.Path)
if err != nil {
return response, err
}
} else {
info, exists = index.GetReducedMetadata(opts.Path, opts.IsDir)
if !exists {
return response, fmt.Errorf("could not get metadata for path: %v", opts.Path)
err = index.RefreshFileInfo(opts)
if err != nil {
return response, fmt.Errorf("could not refresh file info: %v", err)
}
info, exists = index.GetReducedMetadata(opts.Path, opts.IsDir)
if !exists {
return response, fmt.Errorf("could not get metadata for path: %v", opts.Path)
}
}
}
response.FileInfo = *info
response.RealPath = realPath
response.Source = opts.Source
if opts.Access != nil && !opts.Access.Permitted(index.Path, opts.Path, opts.Username) {
// check if any subpath is permitted
// keep track of permitted paths and only show them at the end
subFolders := info.Folders
subFiles := info.Files
response.Folders = make([]iteminfo.ItemInfo, 0)
response.Files = make([]iteminfo.ItemInfo, 0)
hasPermittedPaths := false
for _, subFolder := range subFolders {
indexPath := info.Path + subFolder.Name
if opts.Access.Permitted(index.Path, indexPath, opts.Username) {
hasPermittedPaths = true
response.Folders = append(response.Folders, subFolder)
}
}
for _, subFile := range subFiles {
indexPath := info.Path + subFile.Name
if opts.Access.Permitted(index.Path, indexPath, opts.Username) {
hasPermittedPaths = true
response.Files = append(response.Files, subFile)
}
}
if !hasPermittedPaths {
return response, errors.ErrPermissionDenied
}
}
if opts.Content {
if info.Size < 20*1024*1024 { // 20 megabytes in bytes
content, err := getContent(realPath)
if err != nil {
logger.Debugf("could not get content for file: "+info.Path, info.Name, err)
return response, err
}
response.Content = content
} else {
logger.Debug("skipping large text file contents (20MB limit): "+info.Path, info.Name)
}
processContent(response, index)
}
response.FileInfo = *info
response.RealPath = realPath
response.Source = index.Name
if settings.Config.Integrations.OnlyOffice.Secret != "" && info.Type != "directory" && iteminfo.IsOnlyOffice(info.Name) {
response.OnlyOfficeId = generateOfficeId(realPath)
}
if strings.HasPrefix(info.Type, "video") {
parentInfo, exists := index.GetReducedMetadata(filepath.Dir(info.Path), true)
if exists {
response.DetectSubtitles(parentInfo)
}
}
return response, nil
}
func processContent(info *iteminfo.ExtendedFileInfo, idx *indexing.Index) {
isVideo := strings.HasPrefix(info.Type, "video")
isAudio := strings.HasPrefix(info.Type, "audio")
isFolder := info.Type == "directory"
if isFolder {
return
}
if isVideo {
parentInfo, exists := idx.GetReducedMetadata(filepath.Dir(info.Path), true)
if exists {
info.DetectSubtitles(parentInfo)
err := info.LoadSubtitleContent()
if err != nil {
logger.Debug("failed to load subtitle content: " + err.Error())
}
}
return
}
if isAudio {
err := extractAudioMetadata(info)
if err != nil {
logger.Debugf("failed to extract audio metadata for file: "+info.RealPath, info.Name, err)
} else {
info.HasPreview = info.AudioMeta.AlbumArt != ""
}
return
}
// Process text content for non-video, non-audio files
if info.Size < 20*1024*1024 { // 20 megabytes in bytes
content, err := getContent(info.RealPath)
if err != nil {
logger.Debugf("could not get content for file: "+info.RealPath, info.Name, err)
return
}
info.Content = content
} else {
logger.Debug("skipping large text file contents (20MB limit): "+info.Path, info.Name)
}
}
func generateOfficeId(realPath string) string {
key, ok := utils.OnlyOfficeCache.Get(realPath).(string)
if !ok {
@@ -98,34 +160,54 @@ func generateOfficeId(realPath string) string {
return key
}
// Checksum checksums a given File for a given User, using a specific
// algorithm. The checksums data is saved on File object.
func GetChecksum(fullPath, algo string) (map[string]string, error) {
subs := map[string]string{}
reader, err := os.Open(fullPath)
// extractAudioMetadata extracts metadata from an audio file using dhowden/tag
func extractAudioMetadata(item *iteminfo.ExtendedFileInfo) error {
file, err := os.Open(item.RealPath)
if err != nil {
return subs, err
return err
}
defer reader.Close()
defer file.Close()
hashFuncs := map[string]hash.Hash{
"md5": md5.New(),
"sha1": sha1.New(),
"sha256": sha256.New(),
"sha512": sha512.New(),
}
h, ok := hashFuncs[algo]
if !ok {
return subs, errors.ErrInvalidOption
}
_, err = io.Copy(h, reader)
// Check file size first to prevent reading extremely large files
fileInfo, err := file.Stat()
if err != nil {
return subs, err
return err
}
subs[algo] = hex.EncodeToString(h.Sum(nil))
return subs, nil
// Skip files larger than 50MB to prevent memory issues
maxSize := int64(50)
if fileInfo.Size() > maxSize*1024*1024 {
return fmt.Errorf("file exceeds metadata check limit: %d MB", maxSize)
}
m, err := tag.ReadFrom(file)
if err != nil {
return err
}
item.AudioMeta = &iteminfo.AudioMetadata{
Title: m.Title(),
Artist: m.Artist(),
Album: m.Album(),
Year: m.Year(),
Genre: m.Genre(),
}
// Extract track number
track, _ := m.Track()
item.AudioMeta.Track = track
// Extract album art and encode as base64 with strict size limits
if picture := m.Picture(); picture != nil && picture.Data != nil {
// More aggressive size limit to prevent memory issues (max 2MB)
if len(picture.Data) <= 2*1024*1024 {
item.AudioMeta.AlbumArt = base64.StdEncoding.EncodeToString(picture.Data)
} else {
logger.Debugf("Skipping album art for %s: too large (%d bytes)", item.RealPath, len(picture.Data))
}
}
return nil
}
func DeleteFiles(source, absPath string, absDirPath string) error {
@@ -140,6 +222,17 @@ func DeleteFiles(source, absPath string, absDirPath string) error {
if index.Config.DisableIndexing {
return nil
}
// Clear RealPathCache entries for the deleted path to prevent cache issues
// when a folder with the same name is created later
indexPath := index.MakeIndexPath(absPath)
realPath, _, err := index.GetRealPath(indexPath)
if err == nil {
// Clear both the path and the isdir cache entries
indexing.RealPathCache.Delete(realPath)
indexing.RealPathCache.Delete(realPath + ":isdir")
}
refreshConfig := iteminfo.FileOptions{Path: index.MakeIndexPath(absDirPath), IsDir: true}
err = index.RefreshFileInfo(refreshConfig)
if err != nil {
@@ -148,7 +241,7 @@ func DeleteFiles(source, absPath string, absDirPath string) error {
return nil
}
func RefreshIndex(source string, path string, isDir bool) error {
func RefreshIndex(source string, path string, isDir bool, recursive bool) error {
idx := indexing.GetIndex(source)
if idx == nil {
return fmt.Errorf("could not get index: %v ", source)
@@ -157,7 +250,7 @@ func RefreshIndex(source string, path string, isDir bool) error {
return nil
}
path = idx.MakeIndexPath(path)
return idx.RefreshFileInfo(iteminfo.FileOptions{Path: path, IsDir: isDir})
return idx.RefreshFileInfo(iteminfo.FileOptions{Path: path, IsDir: isDir, Recursive: recursive})
}
// validateMoveDestination checks if a move/rename operation is valid
@@ -199,21 +292,47 @@ func MoveResource(isSrcDir, isDestDir bool, sourceIndex, destIndex, realsrc, rea
if err != nil {
return err
}
go RefreshIndex(sourceIndex, realsrc, isSrcDir) //nolint:errcheck
go RefreshIndex(destIndex, realdst, isDestDir) //nolint:errcheck
// update shares
idx := indexing.GetIndex(sourceIndex)
if idx == nil {
return fmt.Errorf("could not get index: %v ", sourceIndex)
// For move operations:
// 1. Delete the source from the index (recursively if it's a directory)
// 2. Recursively index the destination to capture the entire moved tree
// Get indexes for deletion and refresh operations
srcIdx := indexing.GetIndex(sourceIndex)
if srcIdx == nil {
return fmt.Errorf("could not get source index: %v", sourceIndex)
}
idx2 := indexing.GetIndex(destIndex)
if idx2 == nil {
return fmt.Errorf("could not get index: %v ", destIndex)
dstIdx := indexing.GetIndex(destIndex)
if dstIdx == nil {
return fmt.Errorf("could not get destination index: %v", destIndex)
}
// Delete from source index (recursively for directories)
go srcIdx.DeleteMetadata(realsrc, isSrcDir, isSrcDir) //nolint:errcheck
// Clear RealPathCache entries for the moved path to prevent cache issues
// when a file/folder with the same name is created later
srcIndexPath := srcIdx.MakeIndexPath(realsrc)
srcRealPath, _, err := srcIdx.GetRealPath(srcIndexPath)
if err == nil {
// Clear both the path and the isdir cache entries
indexing.RealPathCache.Delete(srcRealPath)
indexing.RealPathCache.Delete(srcRealPath + ":isdir")
}
// For move operations, refresh the parent directory to capture the moved file
refreshPath := realdst
refreshIsDir := isDestDir
if !isSrcDir {
// If moving a file (regardless of destination), refresh the parent directory
refreshPath = filepath.Dir(realdst)
refreshIsDir = true
}
go RefreshIndex(destIndex, refreshPath, refreshIsDir, true) //nolint:errcheck
// Use backend source paths to match how shares are stored
go s.UpdateShares(idx.Path, idx.MakeIndexPath(realsrc), idx2.Path, idx2.MakeIndexPath(realdst)) //nolint:errcheck
go s.UpdateShares(srcIdx.Path, srcIdx.MakeIndexPath(realsrc), dstIdx.Path, dstIdx.MakeIndexPath(realdst)) //nolint:errcheck
return nil
}
@@ -227,9 +346,31 @@ func CopyResource(isSrcDir, isDestDir bool, sourceIndex, destIndex, realsrc, rea
if err != nil {
return err
}
go RefreshIndex(sourceIndex, realsrc, isSrcDir) //nolint:errcheck
go RefreshIndex(destIndex, realdst, isDestDir) //nolint:errcheck
// update shares
// For copy operations:
// 1. Shallow refresh of source (just to update access times if needed)
// 2. Recursively index the destination to capture the entire copied tree
// Refresh source (parent directory if it's a file)
srcRefreshPath := realsrc
srcRefreshIsDir := isSrcDir
if !isSrcDir {
srcRefreshPath = filepath.Dir(realsrc)
srcRefreshIsDir = true
}
go RefreshIndex(sourceIndex, srcRefreshPath, srcRefreshIsDir, false) //nolint:errcheck
// Refresh destination (parent directory if it's a file)
dstRefreshPath := realdst
dstRefreshIsDir := isDestDir
if !isSrcDir {
// If copying a file (regardless of destination), refresh the parent directory
dstRefreshPath = filepath.Dir(realdst)
dstRefreshIsDir = true
}
go RefreshIndex(destIndex, dstRefreshPath, dstRefreshIsDir, true) //nolint:errcheck
return nil
}
@@ -239,12 +380,31 @@ func WriteDirectory(opts iteminfo.FileOptions) error {
return fmt.Errorf("could not get index: %v ", opts.Source)
}
realPath, _, _ := idx.GetRealPath(opts.Path)
var stat os.FileInfo
var err error
// Check if the destination exists and is a file
if stat, err = os.Stat(realPath); err == nil && !stat.IsDir() {
// If it's a file and we're trying to create a directory, remove the file first
err = os.Remove(realPath)
if err != nil {
return fmt.Errorf("could not remove existing file to create directory: %v", err)
}
// Clear the cache for the removed file
indexPath := idx.MakeIndexPath(opts.Path)
realPath, _, err = idx.GetRealPath(indexPath)
if err == nil {
indexing.RealPathCache.Delete(realPath)
indexing.RealPathCache.Delete(realPath + ":isdir")
}
}
// Ensure the parent directories exist
err := os.MkdirAll(realPath, fileutils.PermDir)
err = os.MkdirAll(realPath, fileutils.PermDir)
if err != nil {
return err
}
return RefreshIndex(idx.Name, opts.Path, true)
return RefreshIndex(idx.Name, opts.Path, true, true)
}
func WriteFile(opts iteminfo.FileOptions, in io.Reader) error {
@@ -252,14 +412,31 @@ func WriteFile(opts iteminfo.FileOptions, in io.Reader) error {
if idx == nil {
return fmt.Errorf("could not get index: %v ", opts.Source)
}
dst, _, _ := idx.GetRealPath(opts.Path)
realPath, _, _ := idx.GetRealPath(opts.Path)
// Ensure the parent directories exist
err := os.MkdirAll(filepath.Dir(dst), fileutils.PermDir)
err := os.MkdirAll(filepath.Dir(realPath), fileutils.PermDir)
if err != nil {
return err
}
var stat os.FileInfo
// Check if the destination exists and is a directory
if stat, err = os.Stat(realPath); err == nil && stat.IsDir() {
// If it's a directory and we're trying to create a file, remove the directory first
err = os.RemoveAll(realPath)
if err != nil {
return fmt.Errorf("could not remove existing directory to create file: %v", err)
}
// Clear the cache for the removed directory
indexPath := idx.MakeIndexPath(opts.Path)
realPath, _, err = idx.GetRealPath(indexPath)
if err == nil {
indexing.RealPathCache.Delete(realPath)
indexing.RealPathCache.Delete(realPath + ":isdir")
}
}
// Open the file for writing (create if it doesn't exist, truncate if it does)
file, err := os.OpenFile(dst, os.O_RDWR|os.O_CREATE|os.O_TRUNC, fileutils.PermFile)
file, err := os.OpenFile(realPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, fileutils.PermFile)
if err != nil {
return err
}
@@ -270,7 +447,7 @@ func WriteFile(opts iteminfo.FileOptions, in io.Reader) error {
if err != nil {
return err
}
return RefreshIndex(opts.Source, opts.Path, false)
return RefreshIndex(opts.Source, opts.Path, false, false)
}
// getContent reads and returns the file content if it's considered an editable text file.
+3 -2
View File
@@ -590,10 +590,11 @@ var types = map[string]string{
".xpi": "application/x-xpinstall",
".wasm": "application/wasm",
".m4a": "audio/mp4",
".flac": "audio/x-flac",
".flac": "audio/flac",
".amr": "audio/amr",
".aac": "audio/aac",
".opus": "video/ogg",
".opus": "audio/ogg", // https://wiki.xiph.org/MIME_Types_and_File_Extensions
".ogx": "application/ogg",
".m4v": "video/mp4",
".mkv": "video/x-matroska",
".caf": "audio/x-caf",
+8 -2
View File
@@ -332,7 +332,7 @@ func createConfig(configpath string) {
}
// cleanup database if it exists
if _, err := os.Stat(config.Server.Database); err == nil {
response := askYesNoQuestion(reader, "Database specified already exists. Move databse file to backup to start fresh?", "no")
response := askYesNoQuestion(reader, "Database specified already exists. Move database file to backup to start fresh?", "no")
if !response {
return
}
@@ -349,11 +349,17 @@ func createConfig(configpath string) {
}
func generateYaml() {
if os.Getenv("FILEBROWSER_GENERATE_CONFIG") != "" {
generateConfig := os.Getenv("FILEBROWSER_GENERATE_CONFIG") == "true"
devMode := os.Getenv("FILEBROWSER_DEVMODE") == "true"
if generateConfig || devMode {
logger.Info("Generating config.yaml")
settings.GenerateYaml()
}
if generateConfig {
os.Exit(0)
}
}
func SplitByMultiple(str string) []string {
+17 -5
View File
@@ -54,12 +54,14 @@ func StartFilebrowser() {
if !keepGoing {
return
}
info, _ := utils.CheckForUpdates()
if info.LatestVersion != "" {
logger.Infof("A new version is available: %s (current: %s)", info.LatestVersion, info.CurrentVersion)
logger.Infof("Release notes: %s", info.ReleaseNotes)
if !settings.Config.Server.DisableUpdateCheck {
info, _ := utils.CheckForUpdates()
if info.LatestVersion != "" {
logger.Infof("A new version is available: %s (current: %s)", info.LatestVersion, info.CurrentVersion)
logger.Infof("Release notes: %s", info.ReleaseNotes)
}
go utils.StartCheckForUpdates()
}
go utils.StartCheckForUpdates()
// Create context and channels for graceful shutdown
ctx, cancel := context.WithCancel(context.Background())
@@ -75,12 +77,22 @@ func StartFilebrowser() {
if !dbExists {
database = fmt.Sprintf("Creating new database : %v", settings.Config.Server.Database)
}
// Dev mode enables development features like template hot-reloading
devMode := os.Getenv("FILEBROWSER_DEVMODE") == "true"
_, err := os.Stat("http/dist")
// In dev mode, always use filesystem assets. Otherwise, check if http/dist exists
if !devMode {
settings.Config.Server.EmbeddedFs = os.IsNotExist(err)
}
sourceList := []string{}
for path, source := range settings.Config.Server.SourceMap {
sourceList = append(sourceList, fmt.Sprintf("%v: %v", source.Name, path))
}
logger.Infof("Initializing FileBrowser Quantum (%v)", version.Version)
logger.Infof("Using Config file : %v", configPath)
logger.Infof("Using Embedded FS : %v", settings.Config.Server.EmbeddedFs)
logger.Infof("Auth Methods : %v", settings.Config.Auth.AuthMethods)
logger.Info(database)
logger.Infof("Sources : %v", sourceList)
+7 -7
View File
@@ -12,12 +12,12 @@ import (
)
type Auth struct {
TokenExpirationHours int `json:"tokenExpirationHours"` // the number of hours until the token expires. Default is 2 hours.
TokenExpirationHours int `json:"tokenExpirationHours"` // time in hours each web UI session token is valid for. Default is 2 hours.
Methods LoginMethods `json:"methods"`
Key string `json:"key"` // the key used to sign the JWT tokens. If not set, a random key will be generated.
AdminUsername string `json:"adminUsername"` // the username of the admin user. If not set, the default is "admin".
AdminPassword string `json:"adminPassword"` // the password of the admin user. If not set, the default is "admin".
TotpSecret string `json:"totpSecret"` // secret used to encrypt TOTP secrets
Key string `json:"key"` // secret: the key used to sign the JWT tokens. If not set, a random key will be generated.
AdminUsername string `json:"adminUsername"` // secret: the username of the admin user. If not set, the default is "admin".
AdminPassword string `json:"adminPassword"` // secret: the password of the admin user. If not set, the default is "admin".
TotpSecret string `json:"totpSecret"` // secret: secret used to encrypt TOTP secrets
AuthMethods []string `json:"-"`
}
@@ -52,8 +52,8 @@ type Recaptcha struct {
// OpenID OAuth2.0
type OidcConfig struct {
Enabled bool `json:"enabled"` // whether to enable OIDC authentication
ClientID string `json:"clientId"` // client id of the OIDC application
ClientSecret string `json:"clientSecret"` // client secret of the OIDC application
ClientID string `json:"clientId"` // secret: client id of the OIDC application
ClientSecret string `json:"clientSecret"` // secret: client secret of the OIDC application
IssuerUrl string `json:"issuerUrl"` // authorization URL of the OIDC provider
Scopes string `json:"scopes"` // scopes to request from the OIDC provider
UserIdentifier string `json:"userIdentifier"` // the field value to use as the username. Default is "preferred_username", can also be "email" or "username", or "phone"
+69 -4
View File
@@ -48,6 +48,9 @@ func Initialize(configFile string) {
}
func setupFrontend(generate bool) {
if Config.Server.MinSearchLength == 0 {
Config.Server.MinSearchLength = 3
}
if !Config.Frontend.DisableDefaultLinks {
Config.Frontend.ExternalLinks = append(Config.Frontend.ExternalLinks, ExternalLink{
Text: fmt.Sprintf("(%v)", version.Version),
@@ -56,14 +59,19 @@ func setupFrontend(generate bool) {
})
Config.Frontend.ExternalLinks = append(Config.Frontend.ExternalLinks, ExternalLink{
Text: "Help",
Url: "https://github.com/gtsteffaniak/filebrowser/wiki",
Url: "help prompt",
})
}
if Config.Frontend.Description == "" {
Config.Frontend.Description = "FileBrowser Quantum is a file manager for the web which can be used to manage files on your server"
}
Config.Frontend.Styling.LightBackground = FallbackColor(Config.Frontend.Styling.LightBackground, "#f5f5f5")
Config.Frontend.Styling.DarkBackground = FallbackColor(Config.Frontend.Styling.DarkBackground, "#141D24")
Config.Frontend.Styling.CustomCSS = readCustomCSS(Config.Frontend.Styling.CustomCSS)
Config.Frontend.Styling.CustomCSSRaw = readCustomCSS(Config.Frontend.Styling.CustomCSS)
Config.Frontend.Styling.CustomThemeOptions = map[string]CustomTheme{}
Config.Frontend.Styling.CustomThemes = map[string]CustomTheme{}
if Config.Frontend.Styling.CustomThemes == nil {
Config.Frontend.Styling.CustomThemes = map[string]CustomTheme{}
}
for name, theme := range Config.Frontend.Styling.CustomThemes {
addCustomTheme(name, theme.Description, theme.CSS)
}
@@ -85,6 +93,9 @@ func setupFrontend(generate bool) {
if !ok {
addCustomTheme("default", "The default theme", "")
}
// Load custom favicon if configured
loadCustomFavicon()
}
func getRealPath(path string) string {
@@ -353,7 +364,7 @@ func setDefaults(generate bool) Settings {
if database == "" {
database = "database.db"
}
return Settings{
s := Settings{
Server: Server{
Port: 80,
NumImageProcessors: numCpus,
@@ -401,6 +412,12 @@ func setDefaults(generate bool) Settings {
},
},
}
// Initialize ImagePreview map with all supported types set to false by default
s.Integrations.Media.Convert.ImagePreview = make(map[ImagePreviewType]bool)
for _, t := range AllImagePreviewTypes {
s.Integrations.Media.Convert.ImagePreview[t] = false
}
return s
}
func ConvertToBackendScopes(scopes []users.SourceScope) ([]users.SourceScope, error) {
@@ -511,6 +528,54 @@ func GetSources(u *users.User) []string {
return sources
}
func loadCustomFavicon() {
// Check if a custom favicon path is configured
if Config.Frontend.Favicon == "" {
logger.Debug("No custom favicon configured, using default")
return
}
// Get absolute path for the favicon
faviconPath, err := filepath.Abs(Config.Frontend.Favicon)
if err != nil {
logger.Warningf("Could not resolve favicon path '%v': %v", Config.Frontend.Favicon, err)
Config.Frontend.Favicon = "" // Unset invalid path
return
}
// Check if the favicon file exists and get info
stat, err := os.Stat(faviconPath)
if err != nil {
logger.Warningf("Could not access custom favicon file '%v': %v", faviconPath, err)
Config.Frontend.Favicon = "" // Unset invalid path
return
}
// Check file size (limit to 1MB for security)
const maxFaviconSize = 1024 * 1024 // 1MB
if stat.Size() > maxFaviconSize {
logger.Warningf("Favicon file '%v' is too large (%d bytes), maximum allowed is %d bytes", faviconPath, stat.Size(), maxFaviconSize)
Config.Frontend.Favicon = "" // Unset invalid path
return
}
// Validate file format based on extension
ext := strings.ToLower(filepath.Ext(faviconPath))
switch ext {
case ".ico", ".png", ".svg":
// Valid favicon formats
default:
logger.Warningf("Unsupported favicon format '%v', supported formats: .ico, .png, .svg", ext)
Config.Frontend.Favicon = "" // Unset invalid path
return
}
// Update to absolute path and mark as valid
Config.Frontend.Favicon = faviconPath
logger.Infof("Successfully validated custom favicon at '%v' (%d bytes, %s)", faviconPath, stat.Size(), ext)
}
func modifyExcludeInclude(config *Source) {
normalize := func(s []string, checkExists bool) {
for i, v := range s {
+696 -43
View File
@@ -14,19 +14,44 @@ import (
"gopkg.in/yaml.v3"
)
// commentsMap[typeName][fieldName] = combined doc+inline comment text
type commentsMap map[string]map[string]string
// CommentsMap[typeName][fieldName] = combined doc+inline comment text
type CommentsMap map[string]map[string]string
// collectComments parses all Go source in the directory of srcPath and returns commentsMap.
func collectComments(srcPath string) (commentsMap, error) {
// SecretFieldsMap[typeName][fieldName] = true if field should be redacted
type SecretFieldsMap map[string]map[string]bool
// DeprecatedFieldsMap[typeName][fieldName] = true if field is deprecated
type DeprecatedFieldsMap map[string]map[string]bool
// getStringStyle determines whether a string should be quoted in YAML
func getStringStyle(value string) yaml.Style {
// Always quote all strings for consistency
return yaml.DoubleQuotedStyle
}
// CollectComments parses all Go source in the directory of srcPath and returns CommentsMap.
func CollectComments(srcPath string) (CommentsMap, error) {
comments, _, _, err := CollectCommentsAndSecrets(srcPath)
return comments, err
}
// CollectCommentsAndSecrets parses all Go source and returns comments, secrets, and deprecated field mappings
func CollectCommentsAndSecrets(srcPath string) (CommentsMap, SecretFieldsMap, DeprecatedFieldsMap, error) {
// parse entire package so we capture comments on all types
dir := filepath.Dir(srcPath)
dir := srcPath
if filepath.IsAbs(srcPath) {
// If it's an absolute path to a file, get the directory
dir = filepath.Dir(srcPath)
}
fset := token.NewFileSet()
pkgs, err := parser.ParseDir(fset, dir, nil, parser.ParseComments)
if err != nil {
return nil, err
return nil, nil, nil, err
}
out := make(commentsMap)
comments := make(CommentsMap)
secrets := make(SecretFieldsMap)
deprecated := make(DeprecatedFieldsMap)
for _, pkg := range pkgs {
for _, file := range pkg.Files {
for _, decl := range file.Decls {
@@ -43,48 +68,342 @@ func collectComments(srcPath string) (commentsMap, error) {
if !ok {
continue
}
m := make(map[string]string)
out[ts.Name.Name] = m
typeName := ts.Name.Name
commentMap := make(map[string]string)
secretMap := make(map[string]bool)
deprecatedMap := make(map[string]bool)
comments[typeName] = commentMap
secrets[typeName] = secretMap
deprecated[typeName] = deprecatedMap
for _, field := range st.Fields.List {
if len(field.Names) == 0 {
continue
}
name := field.Names[0].Name
var parts []string
var fullComment string
if field.Doc != nil {
parts = append(parts, strings.TrimSpace(field.Doc.Text()))
docText := strings.TrimSpace(field.Doc.Text())
parts = append(parts, docText)
fullComment += docText + " "
}
if field.Comment != nil {
parts = append(parts, strings.TrimSpace(field.Comment.Text()))
commentText := strings.TrimSpace(field.Comment.Text())
parts = append(parts, commentText)
fullComment += commentText
}
if len(parts) > 0 {
m[name] = strings.Join(parts, " : ")
commentMap[name] = strings.Join(parts, " : ")
}
// Check if field should be treated as secret
if strings.Contains(strings.ToLower(fullComment), "secret:") {
secretMap[name] = true
}
// Check if field should be treated as deprecated
if strings.Contains(strings.ToLower(fullComment), "deprecated:") {
deprecatedMap[name] = true
}
}
}
}
}
}
return out, nil
return comments, secrets, deprecated, nil
}
// buildNode constructs a yaml.Node for any Go value, injecting comments on struct fields.
func buildNode(v reflect.Value, comm commentsMap) (*yaml.Node, error) {
// PathToTypeField represents a mapping from YAML path to Go type and field info
type PathToTypeField struct {
TypeName string
FieldName string
}
// buildStructPathMap builds a dynamic mapping from YAML paths to Go struct types/fields using reflection
func buildStructPathMap(config *Settings) map[string]PathToTypeField {
pathMap := make(map[string]PathToTypeField)
// Start with the root Settings struct
buildPathMapRecursive(reflect.TypeOf(config).Elem(), reflect.ValueOf(config).Elem(), "", "Settings", pathMap)
return pathMap
}
// buildPathMapRecursive recursively builds the path mapping using reflection
func buildPathMapRecursive(structType reflect.Type, structValue reflect.Value, currentPath string, typeName string, pathMap map[string]PathToTypeField) {
for i := 0; i < structType.NumField(); i++ {
field := structType.Field(i)
// Skip unexported fields
if field.PkgPath != "" {
continue
}
// Skip fields marked to ignore
if yamlTag := field.Tag.Get("yaml"); yamlTag == "-" {
continue
}
if jsonTag := field.Tag.Get("json"); jsonTag == "-" {
continue
}
// Determine the YAML field name from struct tags
yamlFieldName := getYamlFieldName(field)
// Build the full path
var fullPath string
if currentPath == "" {
fullPath = yamlFieldName
} else {
fullPath = currentPath + "." + yamlFieldName
}
// Add this field to the path map
pathMap[fullPath] = PathToTypeField{
TypeName: typeName,
FieldName: field.Name,
}
// If this field is a struct, recurse into it
fieldValue := structValue.Field(i)
fieldType := field.Type
// Handle pointers
if fieldType.Kind() == reflect.Ptr {
if fieldValue.IsNil() {
// Skip nil pointers
continue
}
fieldValue = fieldValue.Elem()
fieldType = fieldType.Elem()
}
// Recurse into structs (but not slices of structs for now - those are handled differently)
if fieldType.Kind() == reflect.Struct {
// Skip certain types that shouldn't be recursed into
if isSkippableStructType(fieldType) {
continue
}
buildPathMapRecursive(fieldType, fieldValue, fullPath, fieldType.Name(), pathMap)
} else if fieldType.Kind() == reflect.Slice && fieldType.Elem().Kind() == reflect.Struct {
// For slices of structs, we map to the element type
elemType := fieldType.Elem()
if !isSkippableStructType(elemType) {
// Create a zero value of the element type to recurse into
zeroValue := reflect.Zero(elemType)
buildPathMapRecursive(elemType, zeroValue, fullPath, elemType.Name(), pathMap)
}
}
}
}
// getYamlFieldName determines the YAML field name from struct tags
func getYamlFieldName(field reflect.StructField) string {
// Check yaml tag first
if yamlTag := field.Tag.Get("yaml"); yamlTag != "" && yamlTag != "-" {
return strings.Split(yamlTag, ",")[0]
}
// Check json tag second
if jsonTag := field.Tag.Get("json"); jsonTag != "" && jsonTag != "-" {
return strings.Split(jsonTag, ",")[0]
}
// Default to field name
return field.Name
}
// isSkippableStructType checks if a struct type should be skipped during recursion
func isSkippableStructType(t reflect.Type) bool {
// Skip types from other packages that we don't want to recurse into
pkgPath := t.PkgPath()
// Skip external packages
if pkgPath != "" && !strings.Contains(pkgPath, "filebrowser/backend") {
return true
}
return false
}
// CollectCommentsFromEmbeddedYaml parses comments from embedded YAML content and returns CommentsMap, SecretFieldsMap, and DeprecatedFieldsMap
func CollectCommentsFromEmbeddedYaml(yamlContent string) (CommentsMap, SecretFieldsMap, DeprecatedFieldsMap, error) {
comments := make(CommentsMap)
secrets := make(SecretFieldsMap)
deprecated := make(DeprecatedFieldsMap)
// Build the dynamic path mapping from the actual Config struct
pathMap := buildStructPathMap(&Config)
lines := strings.Split(yamlContent, "\n")
// Track the current path in the YAML structure
var currentPath []string
for _, line := range lines {
// Skip empty lines and lines that are just comments
trimmed := strings.TrimSpace(line)
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
continue
}
// Find the key and comment in the line
if !strings.Contains(line, ":") {
continue
}
// Split on the first colon to get key part
colonIndex := strings.Index(line, ":")
keyPart := line[:colonIndex]
restPart := line[colonIndex+1:]
// Calculate indentation
indent := 0
for i, char := range keyPart {
if char == ' ' {
indent++
} else {
keyPart = keyPart[i:]
break
}
}
depth := indent / 2
// Get the key name
key := strings.TrimSpace(keyPart)
if key == "" {
continue
}
// Adjust the current path based on depth
if depth < len(currentPath) {
currentPath = currentPath[:depth]
}
// Add current key to path
if depth < len(currentPath) {
currentPath[depth] = key
currentPath = currentPath[:depth+1]
} else {
currentPath = append(currentPath, key)
}
// Look for comment in the rest of the line
var comment string
if strings.Contains(restPart, "#") {
// Find the comment part (not inside quotes)
inQuotes := false
for i, char := range restPart {
if char == '"' && (i == 0 || restPart[i-1] != '\\') {
inQuotes = !inQuotes
} else if char == '#' && !inQuotes {
comment = strings.TrimSpace(restPart[i+1:])
break
}
}
}
// Store comment if it exists
if comment != "" {
// Build the full path string
fullPath := strings.Join(currentPath, ".")
// Look up the type and field name from our dynamic mapping
if pathInfo, exists := pathMap[fullPath]; exists {
typeName := pathInfo.TypeName
fieldName := pathInfo.FieldName
// Initialize maps if they don't exist
if comments[typeName] == nil {
comments[typeName] = make(map[string]string)
}
if secrets[typeName] == nil {
secrets[typeName] = make(map[string]bool)
}
if deprecated[typeName] == nil {
deprecated[typeName] = make(map[string]bool)
}
comments[typeName][fieldName] = comment
// Check for secret and deprecated markers
commentLower := strings.ToLower(comment)
if strings.Contains(commentLower, "secret:") {
secrets[typeName][fieldName] = true
}
if strings.Contains(commentLower, "deprecated:") {
deprecated[typeName][fieldName] = true
}
}
}
}
return comments, secrets, deprecated, nil
}
// parseDefaultsFromEmbeddedYaml creates a default config by parsing the embedded YAML template
func parseDefaultsFromEmbeddedYaml(embeddedYaml string) (*Settings, error) {
// Start with baseline defaults from setDefaults to ensure all fields are initialized
defaultConfig := setDefaults(true)
defaultConfig.Server.Sources = []Source{{Path: "."}}
// Parse the embedded YAML to overlay the documented defaults
if err := yaml.Unmarshal([]byte(embeddedYaml), &defaultConfig); err != nil {
return nil, fmt.Errorf("failed to unmarshal embedded YAML into config: %v", err)
}
return &defaultConfig, nil
}
// readEmbeddedYaml attempts to read the embedded config.generated.yaml file
func readEmbeddedYaml() (string, error) {
// Try to read from the relative path that should work when the binary includes embedded files
embeddedContent, err := os.ReadFile("http/dist/config.generated.yaml")
if err != nil {
// Try alternative path
embeddedContent, err = os.ReadFile("backend/http/dist/config.generated.yaml")
if err != nil {
// Try current directory path
embeddedContent, err = os.ReadFile("dist/config.generated.yaml")
if err != nil {
return "", fmt.Errorf("could not read embedded YAML from any path: %v", err)
}
}
}
return string(embeddedContent), nil
}
// BuildNode constructs a yaml.Node for any Go value, injecting comments on struct fields.
func BuildNode(v reflect.Value, comm CommentsMap) (*yaml.Node, error) {
return buildNodeWithDefaults(v, comm, reflect.Value{}, SecretFieldsMap{}, DeprecatedFieldsMap{})
}
// buildNodeWithDefaults constructs a yaml.Node for any Go value, skipping fields that match defaults, redacting secrets, and filtering deprecated fields
func buildNodeWithDefaults(v reflect.Value, comm CommentsMap, defaults reflect.Value, secrets SecretFieldsMap, deprecated DeprecatedFieldsMap) (*yaml.Node, error) {
// Dereference pointers
if v.Kind() == reflect.Ptr {
if v.IsNil() {
return &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!null", Value: "null"}, nil
}
return buildNode(v.Elem(), comm)
var defaultsElem reflect.Value
if defaults.IsValid() && !defaults.IsNil() {
defaultsElem = defaults.Elem()
}
return buildNodeWithDefaults(v.Elem(), comm, defaultsElem, secrets, deprecated)
}
switch v.Kind() {
case reflect.String:
value := v.String()
return &yaml.Node{
Kind: yaml.ScalarNode,
Tag: "!!str",
Value: v.String(),
Style: yaml.DoubleQuotedStyle,
Value: value,
Style: getStringStyle(value),
}, nil
case reflect.Struct:
rt := v.Type()
@@ -104,6 +423,26 @@ func buildNode(v reflect.Value, comm commentsMap) (*yaml.Node, error) {
continue
}
// Skip deprecated fields if filtering is enabled
if len(deprecated) > 0 && deprecated[typeName][sf.Name] {
continue
}
currentField := v.Field(i)
// If we have defaults, compare and skip if values match
if defaults.IsValid() && i < defaults.NumField() {
defaultField := defaults.Field(i)
currentValue := currentField.Interface()
defaultValue := defaultField.Interface()
isEqual := reflect.DeepEqual(currentValue, defaultValue)
if isEqual {
continue // Skip this field as it matches the default
}
}
// determine key: yaml tag > json tag > field name
yamlTag := sf.Tag.Get("yaml")
jsonTag := sf.Tag.Get("json")
@@ -118,22 +457,43 @@ func buildNode(v reflect.Value, comm commentsMap) (*yaml.Node, error) {
keyNode := &yaml.Node{Kind: yaml.ScalarNode, Value: keyName}
// attach validate and comments inline
// attach validate and comments inline (only when comments are enabled)
var parts []string
if cm := comm[typeName][sf.Name]; cm != "" {
parts = append(parts, cm)
}
if vt := sf.Tag.Get("validate"); vt != "" {
parts = append(parts, fmt.Sprintf(" validate:%s", vt))
// Only add validation tags if comments map is not empty (meaning comments are enabled)
if len(comm) > 0 {
if vt := sf.Tag.Get("validate"); vt != "" {
parts = append(parts, fmt.Sprintf(" validate:%s", vt))
}
}
if len(parts) > 0 {
keyNode.LineComment = strings.Join(parts, " ")
}
valNode, err := buildNode(v.Field(i), comm)
if err != nil {
return nil, err
// Check if this field should be redacted as a secret
var valNode *yaml.Node
var err error
if secrets[typeName][sf.Name] {
valNode = &yaml.Node{
Kind: yaml.ScalarNode,
Tag: "!!str",
Value: "**hidden**",
Style: yaml.DoubleQuotedStyle, // Keep secrets quoted for clarity
}
} else {
// Pass through the corresponding default field for recursive comparison
var defaultField reflect.Value
if defaults.IsValid() && i < defaults.NumField() {
defaultField = defaults.Field(i)
}
valNode, err = buildNodeWithDefaults(currentField, comm, defaultField, secrets, deprecated)
if err != nil {
return nil, err
}
}
mapNode.Content = append(mapNode.Content, keyNode, valNode)
}
@@ -148,15 +508,26 @@ func buildNode(v reflect.Value, comm commentsMap) (*yaml.Node, error) {
// placeholder for empty slice of structs
if v.Len() == 0 && v.Type().Elem().Kind() == reflect.Struct {
zero := reflect.Zero(v.Type().Elem())
n, err := buildNode(zero, comm)
var defaultElem reflect.Value
if defaults.IsValid() && defaults.Len() > 0 {
defaultElem = defaults.Index(0)
}
n, err := buildNodeWithDefaults(zero, comm, defaultElem, secrets, deprecated)
if err != nil {
return nil, err
}
seq.Content = append(seq.Content, n)
// Only add placeholder if it's not empty
if n.Kind == yaml.MappingNode && len(n.Content) > 0 {
seq.Content = append(seq.Content, n)
}
return seq, nil
}
for i := 0; i < v.Len(); i++ {
n, err := buildNode(v.Index(i), comm)
var defaultElem reflect.Value
if defaults.IsValid() && i < defaults.Len() {
defaultElem = defaults.Index(i)
}
n, err := buildNodeWithDefaults(v.Index(i), comm, defaultElem, secrets, deprecated)
if err != nil {
return nil, err
}
@@ -164,6 +535,42 @@ func buildNode(v reflect.Value, comm commentsMap) (*yaml.Node, error) {
}
return seq, nil
case reflect.Map:
if v.Len() == 0 {
// Return an empty string node for empty maps, which renders as a blank value.
return &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: ""}, nil
}
mapNode := &yaml.Node{Kind: yaml.MappingNode}
// Special handling for ImagePreview maps - show all supported types
if isImagePreviewMap(v) {
return buildImagePreviewMap(v, comm, secrets, deprecated)
}
for _, key := range v.MapKeys() {
// Handle key
keyStr := fmt.Sprintf("%v", key.Interface())
keyNode := &yaml.Node{
Kind: yaml.ScalarNode,
Value: keyStr,
}
// Handle value recursively
mapVal := v.MapIndex(key)
var defaultVal reflect.Value
if defaults.IsValid() {
defaultVal = defaults.MapIndex(key)
}
valNode, err := buildNodeWithDefaults(mapVal, comm, defaultVal, secrets, deprecated)
if err != nil {
return nil, err
}
mapNode.Content = append(mapNode.Content, keyNode, valNode)
}
return mapNode, nil
default:
n := &yaml.Node{}
if err := n.Encode(v.Interface()); err != nil {
@@ -186,21 +593,148 @@ func GenerateYaml() {
setupSources(true)
setupUrls()
setupFrontend(true)
input := "common/settings/settings.go" // "path to Go source file or directory containing structs"
output := "generated.yaml" // "output YAML file"
output := "generated.yaml" // "output YAML file"
comm, err := collectComments(input)
// Generate YAML with comments enabled, full config, and deprecated fields filtered
// Force the source path to be correct for static generation
yamlContent, err := GenerateConfigYamlWithSource(&Config, true, true, true, "common/settings")
if err != nil {
fmt.Fprintf(os.Stderr, "error parsing comments: %v\n", err)
fmt.Fprintf(os.Stderr, "error generating YAML: %v\n", err)
os.Exit(1)
}
node, err := buildNode(reflect.ValueOf(Config), comm)
if err != nil {
fmt.Fprintf(os.Stderr, "error building YAML node: %v\n", err)
if err := os.WriteFile(output, []byte(yamlContent), 0644); err != nil {
fmt.Fprintf(os.Stderr, "error writing YAML: %v\n", err)
os.Exit(1)
}
fmt.Printf("Generated YAML with comments (deprecated fields filtered): %s\n", output)
}
// GenerateConfigYaml generates YAML from a given config with options for comments and filtering
func GenerateConfigYaml(config *Settings, showComments bool, showFull bool, filterDeprecated bool) (string, error) {
// Try different source paths to handle both runtime and test scenarios
sourcePaths := []string{
"common/settings", // When running from backend directory
".", // When running tests from settings directory
"../settings", // Alternative test path
}
for _, sourcePath := range sourcePaths {
yamlOutput, err := GenerateConfigYamlWithSource(config, showComments, showFull, filterDeprecated, sourcePath)
if err == nil {
return yamlOutput, nil
}
// If it's not a file not found error, return immediately
if !strings.Contains(err.Error(), "no such file or directory") && !strings.Contains(err.Error(), "cannot find") {
return "", err
}
}
// If all paths failed, try with empty maps to at least generate basic YAML
return GenerateConfigYamlWithEmptyMaps(config, showFull)
}
// GenerateConfigYamlWithEmbedded generates YAML from a given config using embedded YAML content as comment source
func GenerateConfigYamlWithEmbedded(config *Settings, showComments bool, showFull bool, filterDeprecated bool, embeddedYaml string) (string, error) {
var comm CommentsMap
var secrets SecretFieldsMap
var deprecated DeprecatedFieldsMap
var err error
if showComments && embeddedYaml != "" {
// Parse comments from the embedded YAML content
comm, secrets, deprecated, err = CollectCommentsFromEmbeddedYaml(embeddedYaml)
if err != nil {
return "", fmt.Errorf("error parsing embedded YAML comments: %w", err)
}
} else {
// Create empty maps
comm = make(CommentsMap)
secrets = make(SecretFieldsMap)
deprecated = make(DeprecatedFieldsMap)
}
// If not filtering deprecated fields, clear the deprecated map
if !filterDeprecated {
deprecated = make(DeprecatedFieldsMap)
}
var node *yaml.Node
if showFull {
// Show the full current config
node, err = buildNodeWithDefaults(reflect.ValueOf(config), comm, reflect.Value{}, secrets, deprecated)
} else {
// Show only non-default values by comparing with defaults from embedded YAML
defaultConfig, parseErr := parseDefaultsFromEmbeddedYaml(embeddedYaml)
if parseErr != nil {
return "", fmt.Errorf("failed to parse defaults from embedded YAML: %v", parseErr)
}
node, err = buildNodeWithDefaults(reflect.ValueOf(config), comm, reflect.ValueOf(defaultConfig), secrets, deprecated)
}
if err != nil {
return "", err
}
// Create document
doc := &yaml.Node{Kind: yaml.DocumentNode}
doc.Content = []*yaml.Node{node}
// Encode to YAML
var rawBuf bytes.Buffer
enc := yaml.NewEncoder(&rawBuf)
enc.SetIndent(2)
if err := enc.Encode(doc); err != nil {
return "", err
}
// Apply comment alignment if comments are enabled
yamlOutput := rawBuf.String()
if showComments {
yamlOutput = AlignComments(yamlOutput)
}
return yamlOutput, nil
}
// GenerateConfigYamlWithEmptyMaps generates YAML without comment parsing when source files are unavailable
func GenerateConfigYamlWithEmptyMaps(config *Settings, showFull bool) (string, error) {
// Create empty maps
comm := make(CommentsMap)
secrets := make(SecretFieldsMap)
deprecated := make(DeprecatedFieldsMap)
var node *yaml.Node
var err error
if showFull {
// Show the full current config
node, err = buildNodeWithDefaults(reflect.ValueOf(config), comm, reflect.Value{}, secrets, deprecated)
} else {
// Show only non-default values by comparing with defaults during node building
// Try to use embedded YAML defaults for consistency, fallback to setDefaults
var defaultConfig *Settings
embeddedYaml, readErr := readEmbeddedYaml()
if readErr == nil {
defaultConfig, err = parseDefaultsFromEmbeddedYaml(embeddedYaml)
}
if err != nil || readErr != nil {
// Fallback to setDefaults
defaultConfigValue := setDefaults(true)
defaultConfigValue.Server.Sources = []Source{{Path: "."}}
defaultConfig = &defaultConfigValue
}
node, err = buildNodeWithDefaults(reflect.ValueOf(config), comm, reflect.ValueOf(defaultConfig), secrets, deprecated)
}
if err != nil {
return "", err
}
// Convert to YAML
doc := &yaml.Node{Kind: yaml.DocumentNode}
doc.Content = []*yaml.Node{node}
@@ -208,17 +742,86 @@ func GenerateYaml() {
enc := yaml.NewEncoder(&rawBuf)
enc.SetIndent(2)
if err := enc.Encode(doc); err != nil {
fmt.Fprintf(os.Stderr, "error encoding YAML: %v\n", err)
os.Exit(1)
return "", err
}
aligned := alignComments(rawBuf.String())
return AlignComments(rawBuf.String()), nil
}
if err := os.WriteFile(output, []byte(aligned), 0644); err != nil {
fmt.Fprintf(os.Stderr, "error writing YAML: %v\n", err)
os.Exit(1)
// GenerateConfigYamlWithSource generates YAML from a given config with options for comments and filtering, using a custom source path
func GenerateConfigYamlWithSource(config *Settings, showComments bool, showFull bool, filterDeprecated bool, sourcePath string) (string, error) {
var comm CommentsMap
var secrets SecretFieldsMap
var deprecated DeprecatedFieldsMap
var err error
if showComments {
// Collect comments, secrets, and deprecated fields from the settings source files
comm, secrets, deprecated, err = CollectCommentsAndSecrets(sourcePath)
if err != nil {
return "", err
}
} else {
// Still need to collect secrets and deprecated fields even if not showing comments
_, secrets, deprecated, err = CollectCommentsAndSecrets(sourcePath)
if err != nil {
return "", err
}
// Create empty comments map
comm = make(CommentsMap)
}
fmt.Printf("Generated YAML with comments: %s\n", output)
// If not filtering deprecated fields, clear the deprecated map
if !filterDeprecated {
deprecated = make(DeprecatedFieldsMap)
}
var node *yaml.Node
if showFull {
// Show the full current config
node, err = buildNodeWithDefaults(reflect.ValueOf(config), comm, reflect.Value{}, secrets, deprecated)
} else {
// Show only non-default values by comparing with defaults during node building
// Try to use embedded YAML defaults for consistency, fallback to setDefaults
var defaultConfig *Settings
embeddedYaml, readErr := readEmbeddedYaml()
if readErr == nil {
defaultConfig, err = parseDefaultsFromEmbeddedYaml(embeddedYaml)
}
if err != nil || readErr != nil {
// Fallback to setDefaults
defaultConfigValue := setDefaults(true)
defaultConfigValue.Server.Sources = []Source{{Path: "."}}
defaultConfig = &defaultConfigValue
}
node, err = buildNodeWithDefaults(reflect.ValueOf(config), comm, reflect.ValueOf(defaultConfig), secrets, deprecated)
}
if err != nil {
return "", err
}
// Create document
doc := &yaml.Node{Kind: yaml.DocumentNode}
doc.Content = []*yaml.Node{node}
// Encode to YAML
var rawBuf bytes.Buffer
enc := yaml.NewEncoder(&rawBuf)
enc.SetIndent(2)
if err := enc.Encode(doc); err != nil {
return "", err
}
// Apply comment alignment if comments are enabled
yamlOutput := rawBuf.String()
if showComments {
yamlOutput = AlignComments(yamlOutput)
}
return yamlOutput, nil
}
// formatLine applies padding to a single line so its comment starts at a target column.
@@ -257,8 +860,8 @@ func formatLine(line string) string {
return line
}
// alignComments formats each line of the YAML string independently.
func alignComments(input string) string {
// AlignComments formats each line of the YAML string independently.
func AlignComments(input string) string {
lines := strings.Split(input, "\n")
outputLines := make([]string, len(lines))
@@ -268,3 +871,53 @@ func alignComments(input string) string {
return strings.Join(outputLines, "\n")
}
// isImagePreviewMap checks if the given map is an ImagePreview map
func isImagePreviewMap(v reflect.Value) bool {
if v.Kind() != reflect.Map {
return false
}
// Check if the map key type is ImagePreviewType
keyType := v.Type().Key()
return keyType.Name() == "ImagePreviewType"
}
// buildImagePreviewMap builds a YAML node for ImagePreview maps, showing all supported types
func buildImagePreviewMap(v reflect.Value, comm CommentsMap, secrets SecretFieldsMap, deprecated DeprecatedFieldsMap) (*yaml.Node, error) {
mapNode := &yaml.Node{Kind: yaml.MappingNode}
// Get all supported image preview types from the global slice
for _, imageType := range AllImagePreviewTypes {
typeName := string(imageType)
// Create key node
keyNode := &yaml.Node{
Kind: yaml.ScalarNode,
Value: typeName,
}
// Get the value from the map, defaulting to false if not present
var value bool
if v.Len() > 0 {
// Look for the key in the map
for _, mapKey := range v.MapKeys() {
if mapKey.String() == typeName {
value = v.MapIndex(mapKey).Bool()
break
}
}
}
// Create value node
valNode := &yaml.Node{
Kind: yaml.ScalarNode,
Tag: "!!bool",
Value: fmt.Sprintf("%t", value),
}
mapNode.Content = append(mapNode.Content, keyNode, valNode)
}
return mapNode, nil
}
@@ -0,0 +1,230 @@
package settings
import (
"regexp"
"strings"
"testing"
)
func TestGenerateConfigYaml_Basic(t *testing.T) {
reNumber := regexp.MustCompile(`^-?\d+(\.\d+)?$`)
// Test using the actual source directory structure
config := &Settings{
UserDefaults: UserDefaults{
Locale: "es", // Non-default value
DarkMode: true, // Default value
DisableOfficePreviewExt: ".docx .xlsx", // This field is deprecated
},
Auth: Auth{
Key: "secret123", // This is a secret field
AdminUsername: "testadmin", // This is a secret field
AdminPassword: "testpassword", // This is a secret field
},
}
// Test different combinations
testCases := []struct {
name string
showComments bool
showFull bool
filterDeprecated bool
expectSecrets bool
expectDeprecated bool
}{
{
name: "API_mode_all_fields",
showComments: false,
showFull: true,
filterDeprecated: false,
expectSecrets: true, // Secrets should be hidden
expectDeprecated: true, // Deprecated should be shown
},
{
name: "Static_config_filter_deprecated",
showComments: true,
showFull: true,
filterDeprecated: true,
expectSecrets: true, // Secrets should be hidden
expectDeprecated: false, // Deprecated should be filtered
},
{
name: "Filtered_non_defaults",
showComments: false,
showFull: false,
filterDeprecated: false,
expectSecrets: true, // Secrets should be hidden
expectDeprecated: false, // Might not appear if matches default
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
// Use the current directory structure for real testing
yamlOutput, err := GenerateConfigYaml(config, tc.showComments, tc.showFull, tc.filterDeprecated)
if err != nil {
t.Fatalf("GenerateConfigYaml failed: %v", err)
}
// Basic validation - should produce some output
if len(yamlOutput) == 0 {
t.Fatal("Generated empty YAML")
}
// Test string quoting - string values should be quoted, numbers and booleans should not
lines := strings.Split(yamlOutput, "\n")
for _, line := range lines {
if strings.Contains(line, ":") && !strings.HasSuffix(strings.TrimSpace(line), ":") {
// This is a key-value line, skip comment portion
parts := strings.SplitN(line, ":", 2)
if len(parts) == 2 {
value := strings.TrimSpace(parts[1])
// Remove comments
if commentIdx := strings.Index(value, "#"); commentIdx >= 0 {
value = strings.TrimSpace(value[:commentIdx])
}
// Skip empty values, arrays, and objects
if value == "" || strings.HasPrefix(value, "[") || strings.HasPrefix(value, "{") {
continue
}
// Check if it's a number (should NOT be quoted)
if reNumber.MatchString(value) {
if strings.HasPrefix(value, "\"") {
t.Errorf("Numeric value should not be quoted in line: %s (value: '%s')", line, value)
}
continue
}
// Check if it's a boolean (should NOT be quoted)
if value == "true" || value == "false" {
if strings.HasPrefix(value, "\"") {
t.Errorf("Boolean value should not be quoted in line: %s (value: '%s')", line, value)
}
continue
}
// Everything else should be a quoted string
if !strings.HasPrefix(value, "\"") || !strings.HasSuffix(value, "\"") {
// Add debug info to see what's wrong
t.Logf("DEBUG: Checking value '%s' from line '%s'", value, strings.TrimSpace(line))
t.Errorf("String value should be quoted in line: %s (value: %s)", strings.TrimSpace(line), value)
}
}
}
}
// Test secret hiding
if tc.expectSecrets {
if !strings.Contains(yamlOutput, "**hidden**") {
t.Error("Expected secrets to be hidden with **hidden**")
}
if strings.Contains(yamlOutput, "secret123") || strings.Contains(yamlOutput, "testadmin") || strings.Contains(yamlOutput, "testpassword") {
t.Error("Secret values should not appear in output")
}
}
// Test deprecated field filtering
hasDeprecated := strings.Contains(yamlOutput, "disableOfficePreviewExt")
if tc.expectDeprecated && !hasDeprecated {
t.Error("Expected deprecated field to be present")
}
if !tc.expectDeprecated && hasDeprecated && tc.filterDeprecated {
t.Error("Expected deprecated field to be filtered out when filterDeprecated=true")
}
// Test comments
hasComments := strings.Contains(yamlOutput, "#")
if tc.showComments && !hasComments {
t.Error("Expected comments to be present when showComments=true")
}
t.Logf("Test case: %s\nGenerated YAML:\n%s\n", tc.name, yamlOutput)
})
}
}
func TestCollectCommentsAndSecrets_Basic(t *testing.T) {
// Test the comment and secret collection directly
comments, secrets, deprecated, err := CollectCommentsAndSecrets(".")
if err != nil {
t.Fatalf("CollectCommentsAndSecrets failed: %v", err)
}
// Should find some secrets in the actual source files
foundSecrets := false
for typeName, typeSecrets := range secrets {
for fieldName := range typeSecrets {
t.Logf("Found secret: %s.%s", typeName, fieldName)
foundSecrets = true
}
}
if !foundSecrets {
t.Error("Expected to find some secret fields in the actual source code")
}
// Should find some deprecated fields
foundDeprecated := false
for typeName, typeDeprecated := range deprecated {
for fieldName := range typeDeprecated {
t.Logf("Found deprecated: %s.%s", typeName, fieldName)
foundDeprecated = true
}
}
if !foundDeprecated {
t.Error("Expected to find some deprecated fields in the actual source code")
}
t.Logf("Comments: %d types", len(comments))
t.Logf("Secrets: %d types", len(secrets))
t.Logf("Deprecated: %d types", len(deprecated))
}
func TestGenerateYaml_StaticGeneration(t *testing.T) {
// Test the static generation function that's used by FILEBROWSER_GENERATE_CONFIG=true
// Create a temporary config for testing
config := &Settings{
UserDefaults: UserDefaults{
Locale: "en",
DisableOfficePreviewExt: ".docx .xlsx", // This should be filtered out
},
Auth: Auth{
Key: "test-secret", // This should be redacted
},
}
// Test static generation with comments and deprecated filtering
yamlOutput, err := GenerateConfigYamlWithSource(config, true, true, true, ".")
if err != nil {
t.Fatalf("Static generation failed: %v", err)
}
// Verify comments are included
if !strings.Contains(yamlOutput, "#") {
t.Error("Static generation should include comments")
}
// Verify deprecated field is filtered out
if strings.Contains(yamlOutput, "disableOfficePreviewExt") {
t.Error("Static generation should filter out deprecated field disableOfficePreviewExt")
}
// Verify secrets are redacted
if !strings.Contains(yamlOutput, "**hidden**") {
t.Error("Static generation should redact secrets")
}
if strings.Contains(yamlOutput, "test-secret") {
t.Error("Static generation should not contain actual secret values")
}
// Verify it has proper structure
if !strings.Contains(yamlOutput, "userDefaults:") {
t.Error("Static generation should contain userDefaults section")
}
if !strings.Contains(yamlOutput, "auth:") {
t.Error("Static generation should contain auth section")
}
t.Logf("Static generation successful with comments and proper filtering")
}
+470
View File
@@ -0,0 +1,470 @@
package settings
import (
"os"
"regexp"
"strings"
"testing"
)
// Test structs for comprehensive testing
type TestConfig struct {
PublicField string `json:"publicField"` // A regular public field
SecretField string `json:"secretField"` // secret: this should be hidden
DeprecatedField string `json:"deprecatedField"` // deprecated: this field is old
EmptyField string `json:"emptyField"` // An empty string field
DefaultField string `json:"defaultField"` // A field that matches default
NonDefaultField string `json:"nonDefaultField"` // A field that differs from default
NestedStruct TestNested `json:"nestedStruct"`
}
type TestNested struct {
NestedPublic string `json:"nestedPublic"` // A nested public field
NestedSecret string `json:"nestedSecret"` // secret: nested secret field
NestedDeprecated string `json:"nestedDeprecated"` // deprecated: nested deprecated field
}
// Helper to create test source files for comment parsing
func createTestSourceFile(t *testing.T, content string) (string, func()) {
tmpFile, err := os.CreateTemp("", "test_*.go")
if err != nil {
t.Fatal(err)
}
if _, err := tmpFile.WriteString(content); err != nil {
t.Fatal(err)
}
tmpFile.Close()
cleanup := func() {
os.Remove(tmpFile.Name())
}
return tmpFile.Name(), cleanup
}
func TestGenerateConfigYaml_StringQuoting(t *testing.T) {
reNumber := regexp.MustCompile(`^-?\d+(\.\d+)?$`)
// Create a simple test source file for this test
sourceContent := `package settings
type Settings struct {
UserDefaults UserDefaults ` + "`json:\"userDefaults\"`" + `
Auth Auth ` + "`json:\"auth\"`" + `
}
type UserDefaults struct {
Locale string ` + "`json:\"locale\"`" + `
}
type Auth struct {
AdminUsername string ` + "`json:\"adminUsername\"`" + `
}
`
tmpFile, cleanup := createTestSourceFile(t, sourceContent)
defer cleanup()
sourcePath := tmpFile[:strings.LastIndex(tmpFile, "/")]
// Create real Settings with string values to test quoting
settings := &Settings{
UserDefaults: UserDefaults{
Locale: "en-US",
},
Auth: Auth{
AdminUsername: "admin",
},
}
// Test with no filtering - should quote all strings
yamlOutput, err := GenerateConfigYamlWithSource(settings, false, true, false, sourcePath)
if err != nil {
t.Fatalf("GenerateConfigYaml failed: %v", err)
}
// All string values should be quoted
lines := strings.Split(yamlOutput, "\n")
for _, line := range lines {
if strings.Contains(line, ":") && !strings.HasSuffix(strings.TrimSpace(line), ":") {
// This is a key-value line
parts := strings.SplitN(line, ":", 2)
if len(parts) == 2 {
value := strings.TrimSpace(parts[1])
// Remove comments
if commentIdx := strings.Index(value, "#"); commentIdx >= 0 {
value = strings.TrimSpace(value[:commentIdx])
}
// Skip empty values, arrays, objects, booleans
if value == "" || value == "false" || value == "true" || strings.HasPrefix(value, "[") || strings.HasPrefix(value, "{") {
continue
}
// Check if it's a number (should NOT be quoted)
if reNumber.MatchString(value) {
if strings.HasPrefix(value, "\"") {
t.Errorf("Numeric value should not be quoted: %s (value: '%s')", line, value)
}
continue
}
// Everything else should be a quoted string
if !strings.HasPrefix(value, "\"") || !strings.HasSuffix(value, "\"") {
t.Errorf("String value should be quoted: %s (value: '%s')", line, value)
}
}
}
}
}
func TestGenerateConfigYaml_SecretHiding(t *testing.T) {
// Create temporary source file with our test structs
sourceContent := `package settings
type TestConfig struct {
PublicField string ` + "`json:\"publicField\"`" + ` // A regular public field
SecretField string ` + "`json:\"secretField\"`" + ` // secret: this should be hidden
}
type TestNested struct {
NestedPublic string ` + "`json:\"nestedPublic\"`" + ` // A nested public field
NestedSecret string ` + "`json:\"nestedSecret\"`" + ` // secret: nested secret field
}
`
tmpFile, cleanup := createTestSourceFile(t, sourceContent)
defer cleanup()
// Test secret detection
_, secrets, _, err := CollectCommentsAndSecrets(tmpFile)
if err != nil {
t.Fatalf("CollectCommentsAndSecrets failed: %v", err)
}
// Verify secret fields are detected
if !secrets["TestConfig"]["SecretField"] {
t.Error("SecretField should be marked as secret")
}
if !secrets["TestNested"]["NestedSecret"] {
t.Error("NestedSecret should be marked as secret")
}
if secrets["TestConfig"]["PublicField"] {
t.Error("PublicField should not be marked as secret")
}
// Test that secrets are properly collected
if len(secrets["TestConfig"]) != 1 {
t.Errorf("Expected 1 secret field in TestConfig, got %d", len(secrets["TestConfig"]))
}
}
func TestGenerateConfigYaml_DeprecatedFiltering(t *testing.T) {
// Create temporary source file with deprecated fields
sourceContent := `package settings
type TestConfig struct {
PublicField string ` + "`json:\"publicField\"`" + ` // A regular public field
DeprecatedField string ` + "`json:\"deprecatedField\"`" + ` // deprecated: this field is old
}
`
tmpFile, cleanup := createTestSourceFile(t, sourceContent)
defer cleanup()
// Test deprecated detection
_, _, deprecated, err := CollectCommentsAndSecrets(tmpFile)
if err != nil {
t.Fatalf("CollectCommentsAndSecrets failed: %v", err)
}
// Verify deprecated fields are detected
if !deprecated["TestConfig"]["DeprecatedField"] {
t.Error("DeprecatedField should be marked as deprecated")
}
if deprecated["TestConfig"]["PublicField"] {
t.Error("PublicField should not be marked as deprecated")
}
}
func TestGenerateConfigYaml_FullVsFiltered(t *testing.T) {
// Create minimal test source
sourceContent := `package settings
type Settings struct {
UserDefaults UserDefaults ` + "`json:\"userDefaults\"`" + `
}
type UserDefaults struct {
DarkMode bool ` + "`json:\"darkMode\"`" + `
Locale string ` + "`json:\"locale\"`" + `
}
`
tmpFile, cleanup := createTestSourceFile(t, sourceContent)
defer cleanup()
sourcePath := tmpFile[:strings.LastIndex(tmpFile, "/")]
// Create a config with both default and non-default values
config := &Settings{
UserDefaults: UserDefaults{
DarkMode: true, // This matches default
Locale: "es", // This differs from default ("en")
},
}
// Test full=true - should show all fields
fullYaml, err := GenerateConfigYamlWithSource(config, false, true, false, sourcePath)
if err != nil {
t.Fatalf("GenerateConfigYaml with full=true failed: %v", err)
}
// Test full=false - should only show non-default fields
filteredYaml, err := GenerateConfigYamlWithSource(config, false, false, false, sourcePath)
if err != nil {
t.Fatalf("GenerateConfigYaml with full=false failed: %v", err)
}
// Full output should be longer than filtered
if len(fullYaml) <= len(filteredYaml) {
t.Error("Full YAML should be longer than filtered YAML")
}
// Filtered output should contain the non-default field
if !strings.Contains(filteredYaml, "locale") {
t.Error("Filtered YAML should contain non-default locale field")
}
// Full output should contain default fields
if !strings.Contains(fullYaml, "darkMode") {
t.Error("Full YAML should contain darkMode field")
}
}
func TestGenerateConfigYaml_CommentsOnOff(t *testing.T) {
// Use the actual settings source directory since comments work there
config := &Settings{
UserDefaults: UserDefaults{
Locale: "en",
},
}
// Test with comments=true using the real source
withComments, err := GenerateConfigYaml(config, true, true, false)
if err != nil {
t.Fatalf("GenerateConfigYaml with comments=true failed: %v", err)
}
// Test with comments=false using the real source
withoutComments, err := GenerateConfigYaml(config, false, true, false)
if err != nil {
t.Fatalf("GenerateConfigYaml with comments=false failed: %v", err)
}
// Output with comments should be longer
if len(withComments) <= len(withoutComments) {
t.Errorf("YAML with comments (%d chars) should be longer than without comments (%d chars)", len(withComments), len(withoutComments))
}
// With comments should contain '#' characters
if !strings.Contains(withComments, "#") {
t.Error("YAML with comments should contain '#' characters")
}
// Without comments should not contain '#' characters
if strings.Contains(withoutComments, "#") {
t.Error("YAML without comments should not contain '#' characters")
}
}
func TestGenerateConfigYaml_IntegrationTest(t *testing.T) {
reNumber := regexp.MustCompile(`^-?\d+(\.\d+)?$`)
// Comprehensive test with all features
config := &Settings{
UserDefaults: UserDefaults{
Locale: "es", // Non-default
DarkMode: true, // Default
DisableOfficePreviewExt: ".docx .xlsx", // This is deprecated
},
Auth: Auth{
Key: "secret123", // This is secret
AdminUsername: "admin", // This is secret
AdminPassword: "password", // This is secret
},
}
tests := []struct {
name string
showComments bool
showFull bool
filterDeprecated bool
expectSecret bool
expectDeprecated bool
expectFull bool
expectComments bool
}{
{
name: "API mode: show all including deprecated",
showComments: false,
showFull: true,
filterDeprecated: false,
expectSecret: true, // secrets should be hidden
expectDeprecated: true, // deprecated should be shown
expectFull: true, // all fields shown
expectComments: false, // no comments
},
{
name: "Static config mode: filter deprecated",
showComments: true,
showFull: true,
filterDeprecated: true,
expectSecret: true, // secrets should be hidden
expectDeprecated: false, // deprecated should be filtered
expectFull: true, // all non-deprecated fields shown
expectComments: true, // comments included
},
{
name: "Filtered output: only changes",
showComments: false,
showFull: false,
filterDeprecated: false,
expectSecret: true, // secrets should be hidden
expectDeprecated: false, // might not appear if matches default
expectFull: false, // only non-default fields
expectComments: false, // no comments
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
yamlOutput, err := GenerateConfigYaml(config, tt.showComments, tt.showFull, tt.filterDeprecated)
if err != nil {
t.Fatalf("GenerateConfigYaml failed: %v", err)
}
// Check secret hiding
if tt.expectSecret {
if !strings.Contains(yamlOutput, "**hidden**") {
t.Error("Expected secrets to be hidden with **hidden**")
}
if strings.Contains(yamlOutput, "secret123") {
t.Error("Secret values should not appear in output")
}
}
// Check deprecated field filtering
hasDeprecated := strings.Contains(yamlOutput, "disableOfficePreviewExt")
if tt.expectDeprecated && !hasDeprecated {
t.Error("Expected deprecated field to be present")
}
if !tt.expectDeprecated && hasDeprecated && tt.filterDeprecated {
t.Error("Expected deprecated field to be filtered out")
}
// Check comments
hasComments := strings.Contains(yamlOutput, "#")
if tt.expectComments && !hasComments {
t.Error("Expected comments to be present")
}
if !tt.expectComments && hasComments {
t.Error("Expected no comments")
}
// Check string quoting - all string values should be quoted
lines := strings.Split(yamlOutput, "\n")
for _, line := range lines {
if strings.Contains(line, ":") && !strings.HasSuffix(strings.TrimSpace(line), ":") {
// This is a key-value line
parts := strings.SplitN(line, ":", 2)
if len(parts) == 2 {
value := strings.TrimSpace(parts[1])
// Skip comments and empty values
if commentIdx := strings.Index(value, "#"); commentIdx >= 0 {
// If comment starts at the beginning, there's no value, just a comment
if commentIdx == 0 {
continue
}
value = strings.TrimSpace(value[:commentIdx])
}
// Check if it's a number (should NOT be quoted)
if reNumber.MatchString(value) {
if strings.HasPrefix(value, "\"") {
t.Errorf("Numeric value should not be quoted in line: %s (value: '%s')", line, value)
}
continue
}
// Check if it's a boolean (should NOT be quoted)
if value == "true" || value == "false" {
if strings.HasPrefix(value, "\"") {
t.Errorf("Boolean value should not be quoted in line: %s (value: '%s')", line, value)
}
continue
}
// Skip arrays, objects, and empty values
if value == "" || strings.HasPrefix(value, "[") || strings.HasPrefix(value, "{") || strings.Contains(value, ":") {
continue
}
// Everything else should be a quoted string
if !strings.HasPrefix(value, "\"") || !strings.HasSuffix(value, "\"") {
t.Errorf("String value should be quoted in line: %s (value: '%s')", line, value)
}
}
}
}
t.Logf("Generated YAML for %s:\n%s", tt.name, yamlOutput)
})
}
}
func TestGenerateConfigYaml_EdgeCases(t *testing.T) {
tests := []struct {
name string
config *Settings
desc string
}{
{
name: "empty_config",
config: &Settings{},
desc: "Empty config should generate valid YAML",
},
{
name: "only_defaults",
config: &Settings{
UserDefaults: UserDefaults{
DarkMode: true, // default value
Locale: "en", // default value
},
},
desc: "Config with only default values",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Test all combinations
for _, showComments := range []bool{false, true} {
for _, showFull := range []bool{false, true} {
for _, filterDeprecated := range []bool{false, true} {
yamlOutput, err := GenerateConfigYaml(tt.config, showComments, showFull, filterDeprecated)
if err != nil {
t.Fatalf("GenerateConfigYaml failed for %s (comments=%v, full=%v, filterDeprecated=%v): %v",
tt.desc, showComments, showFull, filterDeprecated, err)
}
// Basic validation - should produce valid YAML structure
if yamlOutput == "" {
t.Errorf("Generated empty YAML for %s", tt.desc)
}
// Should not contain obvious error messages (but allow "error" in log levels etc)
if strings.Contains(yamlOutput, "Error:") || strings.Contains(yamlOutput, "ERROR:") {
t.Errorf("YAML contains error for %s", tt.desc)
}
}
}
}
})
}
}
+1 -1
View File
@@ -14,7 +14,7 @@ type AuthMethod string
// GenerateKey generates a key of 512 bits.
func GenerateKey() ([]byte, error) {
b := make([]byte, 64) //nolint:gomnd
b := make([]byte, 64)
_, err := rand.Read(b)
// Note that err == nil only if we read len(b) bytes.
if err != nil {
+83 -48
View File
@@ -21,16 +21,18 @@ type Settings struct {
}
type Server struct {
NumImageProcessors int `json:"numImageProcessors"` // number of concurrent image processing jobs used to create previews, default is number of cpu cores available.
Socket string `json:"socket"` // socket to listen on
TLSKey string `json:"tlsKey"` // path to TLS key
TLSCert string `json:"tlsCert"` // path to TLS cert
DisablePreviews bool `json:"disablePreviews"` // disable all previews thumbnails, simple icons will be used
DisableResize bool `json:"disablePreviewResize"` // disable resizing of previews for faster loading over slow connections
DisableTypeDetectionByHeader bool `json:"disableTypeDetectionByHeader"` // disable type detection by header, useful if filesystem is slow.
Port int `json:"port"` // port to listen on
BaseURL string `json:"baseURL"` // base URL for the server, the subpath that the server is running on.
Logging []LogConfig `json:"logging"`
MinSearchLength int `json:"minSearchLength" yaml:"minSearchLength"` // minimum length of search query to begin searching (default: 3)
DisableUpdateCheck bool `json:"disableUpdateCheck"` // disables backend update check service
NumImageProcessors int `json:"numImageProcessors"` // number of concurrent image processing jobs used to create previews, default is number of cpu cores available.
Socket string `json:"socket"` // socket to listen on
TLSKey string `json:"tlsKey"` // path to TLS key
TLSCert string `json:"tlsCert"` // path to TLS cert
DisablePreviews bool `json:"disablePreviews"` // disable all previews thumbnails, simple icons will be used
DisableResize bool `json:"disablePreviewResize"` // disable resizing of previews for faster loading over slow connections
DisableTypeDetectionByHeader bool `json:"disableTypeDetectionByHeader"` // disable type detection by header, useful if filesystem is slow.
Port int `json:"port"` // port to listen on
BaseURL string `json:"baseURL"` // base URL for the server, the subpath that the server is running on.
Logging []LogConfig `json:"logging" yaml:"logging"`
DebugMedia bool `json:"debugMedia"` // output ffmpeg stdout for media integration -- careful can produces lots of output!
Database string `json:"database"` // path to the database file
Sources []Source `json:"sources" validate:"required,dive"`
@@ -42,6 +44,7 @@ type Server struct {
SourceMap map[string]Source `json:"-" validate:"omitempty"` // uses realpath as key
NameToSource map[string]Source `json:"-" validate:"omitempty"` // uses name as key
MuPdfAvailable bool `json:"-"` // used internally if compiled with mupdf support
EmbeddedFs bool `json:"-"` // used internally if compiled with embedded fs support
}
type Integrations struct {
@@ -52,43 +55,67 @@ type Integrations struct {
// onlyoffice secret is stored in the local.json file
// docker exec <containerID> /var/www/onlyoffice/documentserver/npm/json -f /etc/onlyoffice/documentserver/local.json 'services.CoAuthoring.secret.session.string'
type OnlyOffice struct {
Url string `json:"url" validate:"required"` // The URL to the OnlyOffice Document Server, needs to be accessible to the user.
InternalUrl string `json:"internalUrl"` // An optional internal address that the filebrowser server can use to communicate with the OnlyOffice Document Server, could be useful to bypass proxy.
Secret string `json:"secret" validate:"required"`
Url string `json:"url" validate:"required"` // The URL to the OnlyOffice Document Server, needs to be accessible to the user.
InternalUrl string `json:"internalUrl"` // An optional internal address that the filebrowser server can use to communicate with the OnlyOffice Document Server, could be useful to bypass proxy.
Secret string `json:"secret" validate:"required"` // secret: authentication key for OnlyOffice integration
ViewOnly bool `json:"viewOnly"` // view only mode for OnlyOffice
}
type Media struct {
FfmpegPath string `json:"ffmpegPath"` // path to ffmpeg directory with ffmpeg and ffprobe (eg. /usr/local/bin)
FfmpegPath string `json:"ffmpegPath"` // path to ffmpeg directory with ffmpeg and ffprobe (eg. /usr/local/bin)
Convert FfmpegConvert `json:"convert"` // config for ffmpeg conversion settings
}
type FfmpegConvert struct {
ImagePreview map[ImagePreviewType]bool `json:"imagePreview"` // supported image preview formats. default is heic
}
type ImagePreviewType string
const (
HEICImagePreview ImagePreviewType = "heic"
//RAWImagePreview ImagePreviewType = "raw"
)
func (i ImagePreviewType) String() string {
return string(i)
}
// AllImagePreviewTypes contains all supported image preview types.
var AllImagePreviewTypes = []ImagePreviewType{
HEICImagePreview,
//RAWImagePreview,
}
type LogConfig struct {
Levels string `json:"levels"` // separated list of log levels to enable. (eg. "info|warning|error|debug")
ApiLevels string `json:"apiLevels"` // separated list of log levels to enable for the API. (eg. "info|warning|error")
Output string `json:"output"` // output location. (eg. "stdout" or "path/to/file.log")
NoColors bool `json:"noColors"` // disable colors in the output
Json bool `json:"json"` // output in json format, currently not supported
Utc bool `json:"utc"` // use UTC time in the output instead of local time
Levels string `json:"levels" yaml:"levels"` // separated list of log levels to enable. (eg. "info|warning|error|debug")
ApiLevels string `json:"apiLevels" yaml:"apiLevels"` // separated list of log levels to enable for the API. (eg. "info|warning|error")
Output string `json:"output" yaml:"output"` // output location. (eg. "stdout" or "path/to/file.log")
NoColors bool `json:"noColors" yaml:"noColors"` // disable colors in the output
Json bool `json:"json" yaml:"json"` // output in json format, currently not supported
Utc bool `json:"utc" yaml:"utc"` // use UTC time in the output instead of local time
}
type Source struct {
Path string `json:"path" validate:"required"` // file system path. (Can be relative)
Name string `json:"name"` // display name
Config SourceConfig `json:"config"`
Config SourceConfig `json:"config,omitempty"`
}
type SourceConfig struct {
DenyByDefault bool `json:"denyByDefault"` // deny access unless an "allow" access rule was specifically created.
Private bool `json:"private"` // designate as source as private -- currently just means no sharing permitted.
Disabled bool `json:"disabled"` // disable the source, this is useful so you don't need to remove it from the config file
IndexingInterval uint32 `json:"indexingIntervalMinutes"` // optional manual overide interval in minutes to re-index the source
DisableIndexing bool `json:"disableIndexing"` // disable the indexing of this source
MaxWatchers int `json:"maxWatchers"` // number of concurrent watchers to use for this source, currently not supported
NeverWatchPaths []string `json:"neverWatchPaths"` // paths that get initially once. Useful for folders that rarely change contents (without source path prefix)
Exclude ExcludeIndexFilter `json:"exclude"` // exclude files and folders from indexing, if include is not set
Include IncludeIndexFilter `json:"include"` // include files and folders from indexing, if exclude is not set
DefaultUserScope string `json:"defaultUserScope"` // default "/" should match folders under path
DefaultEnabled bool `json:"defaultEnabled"` // should be added as a default source for new users?
CreateUserDir bool `json:"createUserDir"` // create a user directory for each user
DenyByDefault bool `json:"denyByDefault,omitempty"` // deny access unless an "allow" access rule was specifically created.
Private bool `json:"private"` // designate as source as private -- currently just means no sharing permitted.
Disabled bool `json:"disabled,omitempty"` // disable the source, this is useful so you don't need to remove it from the config file
IndexingInterval uint32 `json:"indexingIntervalMinutes,omitempty"` // optional manual overide interval in minutes to re-index the source
DisableIndexing bool `json:"disableIndexing,omitempty"` // disable the indexing of this source
MaxWatchers int `json:"maxWatchers"` // number of concurrent watchers to use for this source, currently not supported
NeverWatchPaths []string `json:"neverWatchPaths"` // paths that get initially once. Useful for folders that rarely change contents (without source path prefix)
Exclude ExcludeIndexFilter `json:"exclude"` // exclude files and folders from indexing, if include is not set
Include IncludeIndexFilter `json:"include"` // include files and folders from indexing, if exclude is not set
DefaultUserScope string `json:"defaultUserScope"` // default "/" should match folders under path
DefaultEnabled bool `json:"defaultEnabled"` // should be added as a default source for new users?
CreateUserDir bool `json:"createUserDir"` // create a user directory for each user
IndexAlbumArt bool `json:"indexAlbumArt"` // deprecated: always enabled since 0.8.6
}
type IncludeIndexFilter struct {
@@ -97,14 +124,16 @@ type IncludeIndexFilter struct {
}
type ExcludeIndexFilter struct {
Hidden bool `json:"hidden"` // exclude hidden files and folders.
ZeroSizeFolders bool `json:"ignoreZeroSizeFolders"` // ignore folders with 0 size
FilePaths []string `json:"filePaths"` // list of filepaths Eg. "folder1" or "file1.txt" or "folder1/file1.txt" (without source path prefix)
FolderPaths []string `json:"folderPaths"` // (filepath) list of folder names to include/exclude. Eg. "folder1" or "folder1/subfolder" (do not include source path, just the subpaths from the source path)
FileNames []string `json:"fileNames"` // (global) list of file names to include/exclude. Eg. "a.jpg"
FolderNames []string `json:"folderNames"` // (global) list of folder names to include/exclude. Eg. "@eadir" or ".thumbnails"
FileEndsWith []string `json:"fileEndsWith"` // (global) exclude files that end with these suffixes. Eg. ".jpg" or ".txt"
FolderEndsWith []string `json:"folderEndsWith"` // (global) exclude folders that end with these suffixes. Eg. ".thumbnails" or ".git"
Hidden bool `json:"hidden"` // exclude hidden files and folders.
ZeroSizeFolders bool `json:"ignoreZeroSizeFolders"` // ignore folders with 0 size
FilePaths []string `json:"filePaths"` // list of filepaths Eg. "folder1" or "file1.txt" or "folder1/file1.txt" (without source path prefix)
FolderPaths []string `json:"folderPaths"` // (filepath) list of folder names to include/exclude. Eg. "folder1" or "folder1/subfolder" (do not include source path, just the subpaths from the source path)
FileNames []string `json:"fileNames"` // (global) list of file names to include/exclude. Eg. "a.jpg"
FolderNames []string `json:"folderNames"` // (global) list of folder names to include/exclude. Eg. "@eadir" or ".thumbnails"
FileEndsWith []string `json:"fileEndsWith"` // (global) exclude files that end with these suffixes. Eg. ".jpg" or ".txt"
FolderEndsWith []string `json:"folderEndsWith"` // (global) exclude folders that end with these suffixes. Eg. ".thumbnails" or ".git"
FileStartsWith []string `json:"fileStartsWith"` // (global) exclude files that start with these prefixes. Eg. "archive-" or "backup-"
FolderStartsWith []string `json:"folderStartsWith"` // (global) exclude folders that start with these prefixes. Eg. "archive-" or "backup-"
}
type Frontend struct {
@@ -114,19 +143,24 @@ type Frontend struct {
ExternalLinks []ExternalLink `json:"externalLinks"`
DisableNavButtons bool `json:"disableNavButtons"` // disable the nav buttons in the sidebar
Styling StylingConfig `json:"styling"`
Favicon string `json:"favicon"` // path to a favicon to use for the frontend
Description string `json:"description"` // description that shows up in html head meta description
}
type StylingConfig struct {
CustomCSS string `json:"customCSS"` // if a valid path to a css file is provided, it will be applied for all users. (eg. "reduce-rounded-corners.css")
LightBackground string `json:"lightBackground"` // specify a valid CSS color property value to use as the background color in light mode
DarkBackground string `json:"darkBackground"` // Specify a valid CSS color property value to use as the background color in dark mode
CustomThemes map[string]CustomTheme `json:"customThemes"` // A list of custom css files that each user can select to override the default styling. if "default" is key name then it will be the default option.
CustomThemeOptions map[string]CustomTheme `json:"-"` // not exposed
CustomCSS string `json:"customCSS"` // if a valid path to a css file is provided, it will be applied for all users. (eg. "reduce-rounded-corners.css")
CustomCSSRaw string `json:"-"` // The css raw content to use for the custom css.
LightBackground string `json:"lightBackground"` // specify a valid CSS color property value to use as the background color in light mode
DarkBackground string `json:"darkBackground"` // Specify a valid CSS color property value to use as the background color in dark mode
CustomThemes map[string]CustomTheme `json:"customThemes"` // A list of custom css files that each user can select to override the default styling. if "default" is key name then it will be the default option.
// In-memory (not exposed to config)
CustomThemeOptions map[string]CustomTheme `json:"-"` // not exposed
}
type CustomTheme struct {
Description string `json:"description"` // The description of the theme to display in the UI.
CSS string `json:"css,omitempty"` // The css file path and filename to use for the theme.
CssRaw string `json:"-"` // The css raw content to use for the theme.
}
type ExternalLink struct {
@@ -152,8 +186,8 @@ type UserDefaults struct {
GallerySize int `json:"gallerySize"` // 0-9 - the size of the gallery thumbnails
ThemeColor string `json:"themeColor"` // theme color to use: eg. #ff0000, or var(--red), var(--purple), etc
QuickDownload bool `json:"quickDownload"` // show icon to download in one click
DisablePreviewExt string `json:"disablePreviewExt"` // comma separated list of file extensions to disable preview for
DisableViewingExt string `json:"disableViewingExt"` // comma separated list of file extensions to disable viewing for
DisablePreviewExt string `json:"disablePreviewExt"` // space separated list of file extensions to disable preview for
DisableViewingExt string `json:"disableViewingExt"` // space separated list of file extensions to disable viewing for
LockPassword bool `json:"lockPassword"` // disable the user from changing their password
DisableSettings bool `json:"disableSettings,omitempty"` // disable the user from viewing the settings page
Preview users.Preview `json:"preview"`
@@ -167,4 +201,5 @@ type UserDefaults struct {
DisableOnlyOfficeExt string `json:"disableOnlyOfficeExt"` // list of file extensions to disable onlyoffice editor for
CustomTheme string `json:"customTheme"` // Name of theme to use chosen from custom themes config.
ShowSelectMultiple bool `json:"showSelectMultiple"` // show select multiple files on desktop
DebugOffice bool `json:"debugOffice"` // debug onlyoffice editor
}
+8 -4
View File
@@ -74,17 +74,21 @@ func FallbackColor(val, defaultColor string) string {
}
func addCustomTheme(name, description, cssFilePath string) {
// Store only file path in config (for YAML export)
Config.Frontend.Styling.CustomThemes[name] = CustomTheme{
Description: description,
CSS: cssFilePath, // Store file path, not content
}
// Load CSS content for runtime use (frontend consumption)
cssContent := ""
if cssFilePath != "" {
cssContent = readCustomCSS(cssFilePath)
}
Config.Frontend.Styling.CustomThemes[name] = CustomTheme{
Description: description,
CSS: cssContent,
}
Config.Frontend.Styling.CustomThemeOptions[name] = CustomTheme{
Description: description,
CSS: cssFilePath,
CssRaw: cssContent, // Store loaded content
}
}
+1
View File
@@ -12,4 +12,5 @@ var (
SearchResultsCache = cache.NewCache(15*time.Second, 1*time.Hour)
OnlyOfficeCache = cache.NewCache(48*time.Hour, 1*time.Hour)
JwtCache = cache.NewCache(1*time.Hour, 72*time.Hour)
MediaCache = cache.NewCache(24 * time.Hour) // subtitles get cached for 24 hours
)
+43
View File
@@ -0,0 +1,43 @@
package utils
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"hash"
"io"
"os"
"github.com/gtsteffaniak/filebrowser/backend/common/errors"
)
// GetChecksum calculates the checksum of a file using the specified algorithm.
// Returns the checksum as a hex-encoded string.
func GetChecksum(fullPath, algo string) (string, error) {
reader, err := os.Open(fullPath)
if err != nil {
return "", err
}
defer reader.Close()
hashFuncs := map[string]hash.Hash{
"md5": md5.New(),
"sha1": sha1.New(),
"sha256": sha256.New(),
"sha512": sha512.New(),
}
h, ok := hashFuncs[algo]
if !ok {
return "", errors.ErrInvalidOption
}
_, err = io.Copy(h, reader)
if err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}
+7
View File
@@ -121,3 +121,10 @@ func NonNilSlice[T any](in []T) []T {
}
return in
}
func Ternary[T any](cond bool, vtrue, vfalse T) T {
if cond {
return vtrue
}
return vfalse
}
+76 -13
View File
@@ -176,6 +176,7 @@ func (s *Storage) DenyUser(sourcePath, indexPath, username string) error {
}
rule.Deny.Users[username] = struct{}{}
s.incrementSourceVersion(sourcePath)
accessCache.Set(accessChangedKey+sourcePath, false)
return s.SaveToDB()
}
@@ -195,6 +196,7 @@ func (s *Storage) AllowUser(sourcePath, indexPath, username string) error {
}
rule.Allow.Users[username] = struct{}{}
s.incrementSourceVersion(sourcePath)
accessCache.Set(accessChangedKey+sourcePath, false)
return s.SaveToDB()
}
@@ -212,6 +214,7 @@ func (s *Storage) DenyGroup(sourcePath, indexPath, groupname string) error {
}
rule.Deny.Groups[groupname] = struct{}{}
s.incrementSourceVersion(sourcePath)
accessCache.Set(accessChangedKey+sourcePath, false)
return s.SaveToDB()
}
@@ -229,6 +232,7 @@ func (s *Storage) AllowGroup(sourcePath, indexPath, groupname string) error {
}
rule.Allow.Groups[groupname] = struct{}{}
s.incrementSourceVersion(sourcePath)
accessCache.Set(accessChangedKey+sourcePath, false)
return s.SaveToDB()
}
@@ -242,6 +246,7 @@ func (s *Storage) DenyAll(sourcePath, indexPath string) error {
}
rule.DenyAll = true
s.incrementSourceVersion(sourcePath)
accessCache.Set(accessChangedKey+sourcePath, false)
return s.SaveToDB()
}
@@ -268,32 +273,91 @@ func (s *Storage) Permitted(sourcePath, indexPath, username string) bool {
}
func (s *Storage) computePermitted(sourcePath, indexPath, username string) bool {
var rulesFound []*AccessRule
// Walk up the path hierarchy and collect all relevant rules
currentPath := indexPath
for {
permitted, found := s.permittedAtExactPath(sourcePath, indexPath, username)
rule, found := s.getRuleAtExactPath(sourcePath, currentPath)
if found {
return permitted
rulesFound = append(rulesFound, rule)
}
indexPath = utils.GetParentDirectoryPath(indexPath)
if indexPath == "" {
if currentPath == "/" || currentPath == "." || currentPath == "" {
break
}
currentPath = utils.GetParentDirectoryPath(currentPath)
}
// Now evaluate the rules, starting from the most specific (indexPath) to the least specific (root)
for _, rule := range rulesFound {
permitted, hasSpecificRule := s.evaluateRuleForUser(rule, username)
if hasSpecificRule {
return permitted
}
}
// No rules found anywhere in the path hierarchy
// Check if the source has DenyByDefault configured (acts like a root-level denyAll rule)
// No specific user or group rule found in the hierarchy.
// Check for any DenyAll rule in the path.
for _, rule := range rulesFound {
if rule.DenyAll {
return false
}
}
// No specific rules found anywhere in the path hierarchy.
// Fallback to the source's DenyByDefault setting.
sourceInfo, ok := settings.Config.Server.SourceMap[sourcePath]
if !ok {
logger.Errorf("source %s not found in config during access check", sourcePath)
return false
}
if sourceInfo.Config.DenyByDefault {
return false
}
return true
return !sourceInfo.Config.DenyByDefault
}
// getRuleAtExactPath is a helper to get a rule without the recursive logic.
func (s *Storage) getRuleAtExactPath(sourcePath, indexPath string) (*AccessRule, bool) {
s.mux.RLock()
defer s.mux.RUnlock()
rulesBySource, ok := s.AllRules[sourcePath]
if !ok {
return nil, false
}
rule, ok := rulesBySource[indexPath]
return rule, ok
}
// evaluateRuleForUser evaluates a single rule for a user and returns if a specific rule was found.
func (s *Storage) evaluateRuleForUser(rule *AccessRule, username string) (permitted bool, hasSpecificRule bool) {
// Check user deny first
if _, found := rule.Deny.Users[username]; found {
return false, true
}
// Check group deny
for group := range rule.Deny.Groups {
if s.isUserInGroup(username, group) {
return false, true
}
}
// Check user allow
if _, found := rule.Allow.Users[username]; found {
return true, true
}
// Check group allow
for group := range rule.Allow.Groups {
if s.isUserInGroup(username, group) {
return true, true
}
}
// No specific rule for this user in this rule set.
return false, false
}
/*
// permittedAtExactPath checks if a rule exists at the given path and evaluates it if so.
func (s *Storage) permittedAtExactPath(sourcePath, indexPath, username string) (bool, bool) {
s.mux.RLock()
@@ -366,6 +430,7 @@ func (s *Storage) permittedRule(rule *AccessRule, username string, sourcePath st
return true
}
*/
// isUserInGroup checks if a username is in a group.
func (s *Storage) isUserInGroup(username, group string) bool {
@@ -416,8 +481,6 @@ func (s *Storage) GetFrontendRules(sourcePath, indexPath string) (FrontendAccess
frontendRules.Deny.Groups = utils.NonNilSlice(slices.Collect(maps.Keys(rule.Deny.Groups)))
frontendRules.Allow.Users = utils.NonNilSlice(slices.Collect(maps.Keys(rule.Allow.Users)))
frontendRules.Allow.Groups = utils.NonNilSlice(slices.Collect(maps.Keys(rule.Allow.Groups)))
logger.Debugf("Returning frontend rules for source: %s and index: %s", sourcePath, indexPath)
return frontendRules, ok
}
+74
View File
@@ -405,3 +405,77 @@ func TestPermitted_DenyByDefaultWithDenyAll(t *testing.T) {
t.Error("bob should not be permitted (DenyByDefault is true and no allow rule)")
}
}
func TestPermitted_DenyByDefault_AdminRootAccess(t *testing.T) {
// 1. Setup
access.ClearCache()
s, userStore := createTestStorage(t)
createTestUser(t, userStore, "admin")
createTestUser(t, userStore, "graham")
createTestUser(t, userStore, "bob")
err := s.LoadFromDB()
if err != nil && err != storm.ErrNotFound {
t.Errorf("unexpected error loading from DB: %v", err)
}
// 2. Configure source with DenyByDefault: true
originalSourceMap := settings.Config.Server.SourceMap
defer func() {
settings.Config.Server.SourceMap = originalSourceMap
access.ClearCache()
}()
settings.Config.Server.SourceMap = map[string]settings.Source{
"mnt/secure": {
Path: "mnt/secure",
Name: "secure",
Config: settings.SourceConfig{
DenyByDefault: true,
},
},
}
// 3. Set up access rules
if err := s.AllowUser("mnt/secure", "/", "admin"); err != nil {
t.Fatalf("AllowUser for admin failed: %v", err)
}
if err := s.AllowUser("mnt/secure", "/test", "graham"); err != nil {
t.Fatalf("AllowUser for graham failed: %v", err)
}
// 4. Assertions
// Admin checks
if !s.Permitted("mnt/secure", "/", "admin") {
t.Error("admin should be permitted for /")
}
if !s.Permitted("mnt/secure", "/test", "admin") {
t.Error("admin should be permitted for /test")
}
if !s.Permitted("mnt/secure", "/test/sub", "admin") {
t.Error("admin should be permitted for /test/sub (this is the bug)")
}
// Graham checks
if !s.Permitted("mnt/secure", "/test", "graham") {
t.Error("graham should be permitted for /test")
}
if !s.Permitted("mnt/secure", "/test/sub", "graham") {
t.Error("graham should be permitted for /test/sub")
}
if s.Permitted("mnt/secure", "/", "graham") {
t.Error("graham should NOT be permitted for /")
}
if s.Permitted("mnt/secure", "/anotherfolder", "graham") {
t.Error("graham should NOT be permitted for /anotherfolder")
}
// Bob checks (should have no access)
if s.Permitted("mnt/secure", "/", "bob") {
t.Error("bob should NOT be permitted for /")
}
if s.Permitted("mnt/secure", "/test", "bob") {
t.Error("bob should NOT be permitted for /test")
}
if s.Permitted("mnt/secure", "/test/sub", "bob") {
t.Error("bob should NOT be permitted for /test/sub")
}
}
+96
View File
@@ -0,0 +1,96 @@
package share
import (
"os"
"path/filepath"
)
// IsSingleFileShare determines if this share is for a single file (not a directory).
// It checks both the file extension and filesystem to determine if the path points to a file.
func (l *Link) IsSingleFileShare() bool {
if l.Path == "" {
return false
}
// First, check if the path has a file extension (common indicator of a file)
ext := filepath.Ext(l.Path)
if ext != "" {
// If it has an extension, it's likely a file, but let's verify with filesystem
return l.isFileOnFilesystem()
}
// If no extension, check if it's a directory by looking at the filesystem
return !l.isDirectoryOnFilesystem()
}
// isFileOnFilesystem checks if the path exists and is a file on the filesystem
func (l *Link) isFileOnFilesystem() bool {
// Construct the full path using Source and Path
fullPath := l.Path
if l.Source != "" {
// If Source is provided, it might be a relative path from the source
fullPath = filepath.Join(l.Source, l.Path)
}
info, err := os.Stat(fullPath)
if err != nil {
// If we can't stat the file, fall back to extension check
return filepath.Ext(l.Path) != ""
}
return !info.IsDir()
}
// isDirectoryOnFilesystem checks if the path exists and is a directory on the filesystem
func (l *Link) isDirectoryOnFilesystem() bool {
// Construct the full path using Source and Path
fullPath := l.Path
if l.Source != "" {
// If Source is provided, it might be a relative path from the source
fullPath = filepath.Join(l.Source, l.Path)
}
info, err := os.Stat(fullPath)
if err != nil {
// If we can't stat the file, assume it's a file if it has an extension
return filepath.Ext(l.Path) == ""
}
return info.IsDir()
}
// IsExpired checks if the share has expired based on the Expire timestamp
func (l *Link) IsExpired() bool {
if l.Expire == 0 {
return false // No expiration set
}
// This would need time.Now().Unix() but we avoid importing time here
// The actual expiration check is handled in the storage layer
return false // Placeholder - actual implementation would check current time
}
// HasPassword checks if the share is password protected
func (l *Link) HasPassword() bool {
return l.PasswordHash != ""
}
// IsPermanent checks if the share is permanent (no expiration)
func (l *Link) IsPermanent() bool {
return l.Expire == 0
}
// GetFileExtension returns the file extension of the shared file
func (l *Link) GetFileExtension() string {
if l.Path == "" {
return ""
}
return filepath.Ext(l.Path)
}
// GetFileName returns just the filename (without path) of the shared item
func (l *Link) GetFileName() string {
if l.Path == "" {
return ""
}
return filepath.Base(l.Path)
}
+25 -22
View File
@@ -4,28 +4,31 @@ import "sync"
type CommonShare struct {
//AllowEdit bool `json:"allowEdit,omitempty"`
AllowUpload bool `json:"allowUpload,omitempty"`
DisableFileViewer bool `json:"disableFileViewer,omitempty"`
DownloadsLimit int `json:"downloadsLimit,omitempty"`
ShareTheme string `json:"shareTheme,omitempty"`
DisableAnonymous bool `json:"disableAnonymous,omitempty"`
MaxBandwidth int `json:"maxBandwidth,omitempty"`
DisableThumbnails bool `json:"disableThumbnails,omitempty"`
KeepAfterExpiration bool `json:"keepAfterExpiration,omitempty"`
AllowedUsernames []string `json:"allowedUsernames,omitempty"`
ThemeColor string `json:"themeColor,omitempty"`
Banner string `json:"banner,omitempty"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Favicon string `json:"favicon,omitempty"`
QuickDownload bool `json:"quickDownload,omitempty"`
HideNavButtons bool `json:"hideNavButtons,omitempty"`
DisableSidebar bool `json:"disableSidebar"`
ViewMode string `json:"viewMode,omitempty"`
Source string `json:"source,omitempty"` // backend source is path to maintain between name changes
Path string `json:"path,omitempty"`
DownloadURL string `json:"downloadURL,omitempty"`
DisableShareCard bool `json:"disableShareCard,omitempty"`
AllowUpload bool `json:"allowUpload,omitempty"`
DisableFileViewer bool `json:"disableFileViewer,omitempty"`
DownloadsLimit int `json:"downloadsLimit,omitempty"`
ShareTheme string `json:"shareTheme,omitempty"`
DisableAnonymous bool `json:"disableAnonymous,omitempty"`
MaxBandwidth int `json:"maxBandwidth,omitempty"`
DisableThumbnails bool `json:"disableThumbnails,omitempty"`
KeepAfterExpiration bool `json:"keepAfterExpiration,omitempty"`
AllowedUsernames []string `json:"allowedUsernames,omitempty"`
ThemeColor string `json:"themeColor,omitempty"`
Banner string `json:"banner,omitempty"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Favicon string `json:"favicon,omitempty"`
QuickDownload bool `json:"quickDownload,omitempty"`
HideNavButtons bool `json:"hideNavButtons,omitempty"`
DisableSidebar bool `json:"disableSidebar"`
Source string `json:"source,omitempty"` // backend source is path to maintain between name changes
Path string `json:"path,omitempty"`
DownloadURL string `json:"downloadURL,omitempty"`
DisableShareCard bool `json:"disableShareCard,omitempty"`
EnforceDarkLightMode string `json:"enforceDarkLightMode,omitempty"` // "dark" or "light"
ViewMode string `json:"viewMode,omitempty"` // default view mode for anonymous users: "list", "compact", "normal", "gallery"
EnableOnlyOffice bool `json:"enableOnlyOffice,omitempty"`
EnableOnlyOfficeEditing bool `json:"enableOnlyOfficeEditing,omitempty"`
}
type CreateBody struct {
CommonShare
+2 -1
View File
@@ -7,6 +7,7 @@ import (
"strings"
storm "github.com/asdine/storm/v3"
"github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils"
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
"github.com/gtsteffaniak/filebrowser/backend/database/storage/bolt"
@@ -57,7 +58,7 @@ func dbExists(path string) (bool, error) {
d := filepath.Dir(path)
_, err = os.Stat(d)
if os.IsNotExist(err) {
if err := os.MkdirAll(d, 0700); err != nil { //nolint:govet,gomnd
if err = os.MkdirAll(d, fileutils.PermDir); err != nil {
return false, err
}
return false, nil
+14 -14
View File
@@ -42,13 +42,15 @@ type Sorting struct {
type Preview struct {
DisableHideSidebar bool `json:"disableHideSidebar"` // disable the hide sidebar preview for previews and editors
HighQuality bool `json:"highQuality"` // generate high quality preview images
Image bool `json:"image"` // show real image as icon instead of generic photo icon
Video bool `json:"video"` // show preview image for video files
MotionVideoPreview bool `json:"motionVideoPreview"` // show multiple frames for videos in preview when hovering
Office bool `json:"office"` // show preview image for office files
PopUp bool `json:"popup"` // show larger popup preview when hovering
HighQuality bool `json:"highQuality"` // generate high quality thumbnail preview images
Image bool `json:"image"` // show thumbnail preview image for image files
Video bool `json:"video"` // show thumbnail preview image for video files
MotionVideoPreview bool `json:"motionVideoPreview"` // show multiple frames for videos in thumbnail preview when hovering
Office bool `json:"office"` // show thumbnail preview image for office files
PopUp bool `json:"popup"` // show larger popup preview when hovering over thumbnail
AutoplayMedia bool `json:"autoplayMedia"` // autoplay media files in preview
DefaultMediaPlayer bool `json:"defaultMediaPlayer"` // disable html5 media player and use the default media player
Folder bool `json:"folder"` // show thumbnail preview image for folder files
}
// User describes a user.
@@ -99,19 +101,17 @@ type NonAdminEditable struct {
FileLoading FileLoading `json:"fileLoading"` // upload and download settings
DisableOfficePreviewExt string `json:"disableOfficePreviewExt"` // deprecated
DisableOnlyOfficeExt string `json:"disableOnlyOfficeExt"` // deprecated
DisablePreviewExt string `json:"disablePreviewExt"` // comma separated list of file extensions to disable preview for
DisableViewingExt string `json:"disableViewingExt"` // comma separated list of file extensions to disable viewing for
DisablePreviewExt string `json:"disablePreviewExt"` // space separated list of file extensions to disable preview for
DisableViewingExt string `json:"disableViewingExt"` // space separated list of file extensions to disable viewing for
CustomTheme string `json:"customTheme"` // Name of theme to use chosen from custom themes config.
ShowSelectMultiple bool `json:"showSelectMultiple"` // show select multiple files on desktop
DebugOffice bool `json:"debugOffice"` // debug onlyoffice editor
}
type FileLoading struct {
MaxConcurrent int `json:"maxConcurrentUpload"`
ChunkSize int `json:"uploadChunkSizeMb"`
}
var AnonymousUser = User{
Username: "anonymous", // temp user not registered
MaxConcurrent int `json:"maxConcurrentUpload"`
ChunkSize int `json:"uploadChunkSizeMb"`
ClearAll bool `json:"clearAll"`
}
func CleanUsername(s string) string {
+28 -5
View File
@@ -75,7 +75,12 @@ func Register(username string, sources []string) chan EventMessage {
func Unregister(username string, ch chan EventMessage) {
userClientsMu.Lock()
conns := userClients[username]
defer userClientsMu.Unlock()
conns, ok := userClients[username]
if !ok {
// User already cleaned up by Shutdown, nothing to do.
return
}
for i, c := range conns {
if c == ch {
userClients[username] = append(conns[:i], conns[i+1:]...)
@@ -85,18 +90,15 @@ func Unregister(username string, ch chan EventMessage) {
if len(userClients[username]) == 0 {
delete(userClients, username)
}
userClientsMu.Unlock()
sourceClientsMu.Lock()
defer sourceClientsMu.Unlock()
for source, clients := range sourceClients {
delete(clients, ch)
if len(clients) == 0 {
delete(sourceClients, source)
}
}
sourceClientsMu.Unlock()
close(ch)
}
func SendToUsers(eventType, message string, users []string) {
@@ -138,3 +140,24 @@ func handleSourceUpdates() {
}
}
}
func Shutdown() {
userClientsMu.Lock()
defer userClientsMu.Unlock()
sourceClientsMu.Lock()
defer sourceClientsMu.Unlock()
for username, clientChannels := range userClients {
for _, ch := range clientChannels {
// Clean up source clients
for source, clients := range sourceClients {
delete(clients, ch)
if len(clients) == 0 {
delete(sourceClients, source)
}
}
close(ch)
}
delete(userClients, username)
}
}
+372
View File
@@ -0,0 +1,372 @@
package ffmpeg
import (
"bytes"
"fmt"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils"
)
// ImageService handles image operations with ffmpeg
type ImageService struct {
ffmpegPath string
ffprobePath string
debug bool
cacheDir string
}
// NewImageService creates a new image service instance
func NewImageService(ffmpegPath, ffprobePath string, debug bool, cacheDir string) *ImageService {
return &ImageService{
ffmpegPath: ffmpegPath,
ffprobePath: ffprobePath,
debug: debug,
cacheDir: cacheDir,
}
}
// GetImageOrientation extracts the EXIF orientation from an image file using exiftool
func (s *ImageService) GetImageOrientation(imagePath string) (string, error) {
// Use exiftool to get orientation information
cmd := exec.Command("exiftool", "-Orientation", "-s3", imagePath)
var out bytes.Buffer
var errOut bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &errOut
if err := cmd.Run(); err != nil {
return "Horizontal (normal)", nil // Default to normal orientation
}
orientation := strings.TrimSpace(out.String())
if orientation == "" {
orientation = "Horizontal (normal)" // Default if no orientation found
}
return orientation, nil
}
// GetOrientationFilter converts EXIF orientation to FFmpeg filter
func (s *ImageService) GetOrientationFilter(orientation string) string {
switch orientation {
// Text-based EXIF orientation values (from exiftool)
case "Rotate 90 CW", "Right-top":
return ",transpose=1" // 90° clockwise
case "Rotate 180", "Bottom-right":
return ",transpose=1,transpose=1" // 180° (two 90° rotations)
case "Rotate 270 CW", "Left-bottom":
return ",transpose=2" // 90° counter-clockwise
case "Mirror horizontal", "Top-right":
return ",hflip" // Horizontal flip
case "Mirror vertical", "Bottom-left":
return ",vflip" // Vertical flip (upside down)
case "Mirror horizontal and rotate 270 CW", "Right-bottom":
return ",transpose=0" // 90° counter-clockwise + horizontal flip
case "Mirror horizontal and rotate 90 CW", "Left-top":
return ",transpose=3" // 90° clockwise + horizontal flip
case "Horizontal (normal)", "Top-left":
return "" // No rotation needed
// Numeric EXIF orientation values (standard EXIF specification)
case "1":
return "" // Top-left (normal)
case "2":
return ",hflip" // Top-right (flip horizontal)
case "3":
return ",transpose=1,transpose=1" // Bottom-right (rotate 180)
case "4":
return ",vflip" // Bottom-left (flip vertical)
case "5":
return ",transpose=3" // Left-top (transpose: 90° CW + horizontal flip)
case "6":
return ",transpose=1" // Right-top (rotate 90 CW)
case "7":
return ",transpose=0" // Right-bottom (transverse: 90° CCW + horizontal flip)
case "8":
return ",transpose=2" // Left-bottom (rotate 270 CW / 90° CCW)
default:
return "" // Default to no rotation for unknown orientations
}
}
// GetImageDimensions extracts the dimensions of an image file using ffprobe
func (s *ImageService) GetImageDimensions(imagePath string) (width, height int, err error) {
// Get HEIC dimensions (fallback to individual stream dimensions for nowe re
probeCmd := exec.Command(
s.ffprobePath,
"-v", "error",
"-select_streams", "v:0",
"-show_entries", "stream=width,height",
"-of", "csv=p=0:s=x",
imagePath,
)
var probeOut bytes.Buffer
var probeErr bytes.Buffer
probeCmd.Stdout = &probeOut
probeCmd.Stderr = &probeErr
if err = probeCmd.Run(); err != nil {
return 0, 0, fmt.Errorf("ffprobe command failed on image file '%s': %w", imagePath, err)
}
dimensions := strings.TrimSpace(probeOut.String())
// Handle cases where ffprobe returns multiple lines or extra characters
// Take the first line and clean it up
lines := strings.Split(dimensions, "\n")
cleanDimensions := strings.TrimSpace(lines[0])
// Remove any trailing 'x' characters that might appear
cleanDimensions = strings.TrimSuffix(cleanDimensions, "x")
parts := strings.Split(cleanDimensions, "x")
if len(parts) != 2 {
return 0, 0, fmt.Errorf("invalid dimensions format: %s", cleanDimensions)
}
width, err = strconv.Atoi(parts[0])
if err != nil {
return 0, 0, fmt.Errorf("invalid width: %w", err)
}
height, err = strconv.Atoi(parts[1])
if err != nil {
return 0, 0, fmt.Errorf("invalid height: %w", err)
}
return width, height, nil
}
// ConvertHEICToJPEGDirect converts a HEIC file to JPEG using direct FFmpeg conversion (fast method)
func (s *ImageService) ConvertHEICToJPEGDirect(heicPath string, targetWidth, targetHeight int, quality string) ([]byte, error) {
// Get EXIF orientation and create appropriate filter
orientation, err := s.GetImageOrientation(heicPath)
if err != nil {
orientation = "Horizontal (normal)"
}
orientationFilter := s.GetOrientationFilter(orientation)
// Create temporary output file
outputDir := s.cacheDir
err = os.MkdirAll(outputDir, fileutils.PermDir)
if err != nil {
return nil, fmt.Errorf("failed to create cache directory: %w", err)
}
outputFile := filepath.Join(outputDir, fmt.Sprintf("heic_direct_%d.jpg", os.Getpid()))
defer os.Remove(outputFile)
// Build FFmpeg command for direct conversion
args := []string{"-i", heicPath}
// Build video filter chain with scaling and orientation
var filterChain string
if targetWidth > 0 && targetHeight > 0 {
filterChain = fmt.Sprintf("scale=%d:%d:force_original_aspect_ratio=decrease%s", targetWidth, targetHeight, orientationFilter)
} else {
// For original size, only apply orientation if needed
if orientationFilter != "" {
filterChain = orientationFilter[1:] // Remove leading comma
}
}
// Add video filter if we have one
if filterChain != "" {
args = append(args, "-vf", filterChain)
}
// Add quality and output settings
args = append(args, "-q:v", quality, "-pix_fmt", "yuvj420p", "-y", outputFile)
cmd := exec.Command(s.ffmpegPath, args...)
var cmdOut bytes.Buffer
var cmdErr bytes.Buffer
cmd.Stdout = &cmdOut
cmd.Stderr = &cmdErr
if err = cmd.Run(); err != nil {
return nil, fmt.Errorf("direct HEIC conversion failed: %w", err)
}
// Read the converted file
jpegBytes, err := os.ReadFile(outputFile)
if err != nil {
return nil, fmt.Errorf("failed to read converted JPEG: %w", err)
}
return jpegBytes, nil
}
// ConvertHEICToJPEG converts a HEIC file to JPEG with specified dimensions and quality using proper tile extraction
func (s *ImageService) ConvertHEICToJPEG(heicPath string, targetWidth, targetHeight int, quality string) ([]byte, error) {
// Create temporary directory for tile processing
outputDir := s.cacheDir
tempDir := filepath.Join(outputDir, fmt.Sprintf("heic_tiles_%d", os.Getpid()))
err := os.MkdirAll(tempDir, fileutils.PermDir)
if err != nil {
return nil, fmt.Errorf("failed to create temp directory: %w", err)
}
defer os.RemoveAll(tempDir)
// Step 1: Get grid info using trace output
// Use ffprobe with trace level to get grid information (with time limit for speed)
gridCmd := exec.Command(s.ffmpegPath, "-loglevel", "trace", "-i", heicPath, "-f", "null", "-", "-t", "0.1")
var gridOut bytes.Buffer
var gridErr bytes.Buffer
gridCmd.Stdout = &gridOut
gridCmd.Stderr = &gridErr
_ = gridCmd.Run() // Don't check error, we're just extracting info
traceOutput := gridErr.String()
// Parse grid dimensions from trace output
var gridCols, gridRows = 8, 6 // Default fallback
var val int
// Look for grid_row and grid_col in trace output
lines := strings.Split(traceOutput, "\n")
for _, line := range lines {
if strings.Contains(line, "grid_row") {
// Try to extract grid_row value
if parts := strings.Split(line, "grid_row"); len(parts) > 1 {
if matches := strings.Fields(parts[1]); len(matches) > 0 {
if val, err = strconv.Atoi(strings.Trim(matches[0], " :=")); err == nil {
gridRows = val + 1 // HEIC grid_row is 0-based
}
}
}
}
if strings.Contains(line, "grid_col") {
// Try to extract grid_col value
if parts := strings.Split(line, "grid_col"); len(parts) > 1 {
if matches := strings.Fields(parts[1]); len(matches) > 0 {
if val, err = strconv.Atoi(strings.Trim(matches[0], " :=")); err == nil {
gridCols = val + 1 // HEIC grid_col is 0-based
}
}
}
}
}
// Get EXIF orientation and create appropriate filter
orientation, err := s.GetImageOrientation(heicPath)
if err != nil {
orientation = "Horizontal (normal)"
}
orientationFilter := s.GetOrientationFilter(orientation)
// Step 2: Extract tile streams (skip stream 0 which is compatibility image)
// Extract using JPEG for faster I/O (PNG was unnecessarily slow and large)
// Skip the first output (stream 0) since it's the compatibility image
tilesPattern := filepath.Join(tempDir, "output_%d.jpg")
extractCmd := exec.Command(
s.ffmpegPath,
"-i", heicPath,
"-map", "0", // Map all streams
"-q:v", "3", // Medium quality for intermediate tiles
"-y",
tilesPattern,
)
var extractOut bytes.Buffer
var extractErr bytes.Buffer
extractCmd.Stdout = &extractOut
extractCmd.Stderr = &extractErr
if err = extractCmd.Run(); err != nil {
return nil, fmt.Errorf("tile extraction failed: %w", err)
}
// Step 3: Filter tiles (skip output_0.png which is compatibility image)
files, err := filepath.Glob(filepath.Join(tempDir, "output_*.jpg"))
if err != nil || len(files) == 0 {
return nil, fmt.Errorf("no tiles extracted, found %d files", len(files))
}
// Create filtered tiles, skipping output_0.jpg (compatibility image)
// and rename them to sequential tile_001.jpg, tile_002.jpg, etc.
tileIndex := 1
expectedTiles := gridCols * gridRows
for i := 1; i <= len(files); i++ { // Start from 1 to skip output_0.jpg
sourceFile := filepath.Join(tempDir, fmt.Sprintf("output_%d.jpg", i))
var info os.FileInfo
if info, err = os.Stat(sourceFile); err == nil && info.Size() > 500 {
// This is a valid tile, rename it to sequential format
targetFile := filepath.Join(tempDir, fmt.Sprintf("tile_%03d.jpg", tileIndex))
if err = os.Rename(sourceFile, targetFile); err != nil {
continue
}
tileIndex++
// Stop if we have enough tiles
if tileIndex > expectedTiles {
break
}
}
}
actualTiles := tileIndex - 1
// Step 4: Merge tiles back into final image with proper quality and rotation
outputFile := filepath.Join(tempDir, "final_output.jpg")
// Build the video filter chain
inputPattern := filepath.Join(tempDir, "tile_%03d.jpg")
// Create filter chain: tile assembly + proper scaling
var filterChain string
// For original size (targetWidth=0, targetHeight=0), don't scale
if targetWidth == 0 && targetHeight == 0 {
// This is original size - no scaling, maximum quality
// Use padding=0:margin=0 to eliminate black borders between tiles
filterChain = fmt.Sprintf("tile=%dx%d:nb_frames=%d:padding=0:margin=0%s",
gridCols, gridRows, actualTiles, orientationFilter)
} else {
// This is a resize request - apply scaling with proper aspect handling
filterChain = fmt.Sprintf("tile=%dx%d:nb_frames=%d:padding=0:margin=0%s,scale=%d:%d:force_original_aspect_ratio=decrease:eval=frame",
gridCols, gridRows, actualTiles, orientationFilter, targetWidth, targetHeight)
}
mergeCmd := exec.Command(
s.ffmpegPath,
"-i", inputPattern,
"-vf", filterChain,
"-frames:v", "1",
"-q:v", quality, // Use the quality setting passed in
"-pix_fmt", "yuvj420p", // Use full-range YUV for better JPEG compatibility
"-y",
outputFile,
)
var mergeOut bytes.Buffer
var mergeErr bytes.Buffer
mergeCmd.Stdout = &mergeOut
mergeCmd.Stderr = &mergeErr
if err = mergeCmd.Run(); err != nil {
return nil, fmt.Errorf("tile merge failed: %w", err)
}
// Step 5: Read final output
jpegBytes, err := os.ReadFile(outputFile)
if err != nil {
return nil, fmt.Errorf("failed to read merged JPEG: %w", err)
}
return jpegBytes, nil
}
+290
View File
@@ -0,0 +1,290 @@
package ffmpeg
import (
"os"
"path/filepath"
"testing"
)
func TestGetOrientationFilter(t *testing.T) {
service := &ImageService{}
tests := []struct {
name string
orientation string
expected string
}{
{
name: "Normal orientation",
orientation: "Horizontal (normal)",
expected: "",
},
{
name: "Normal orientation alternative",
orientation: "Top-left",
expected: "",
},
{
name: "Rotate 90 CW",
orientation: "Rotate 90 CW",
expected: ",transpose=1",
},
{
name: "Rotate 90 CW alternative",
orientation: "Right-top",
expected: ",transpose=1",
},
{
name: "Rotate 180",
orientation: "Rotate 180",
expected: ",transpose=1,transpose=1",
},
{
name: "Rotate 180 alternative",
orientation: "Bottom-right",
expected: ",transpose=1,transpose=1",
},
{
name: "Rotate 270 CW",
orientation: "Rotate 270 CW",
expected: ",transpose=2",
},
{
name: "Rotate 270 CW alternative",
orientation: "Left-bottom",
expected: ",transpose=2",
},
{
name: "Mirror horizontal",
orientation: "Mirror horizontal",
expected: ",hflip",
},
{
name: "Mirror horizontal alternative",
orientation: "Top-right",
expected: ",hflip",
},
{
name: "Mirror vertical",
orientation: "Mirror vertical",
expected: ",vflip",
},
{
name: "Mirror vertical alternative",
orientation: "Bottom-left",
expected: ",vflip",
},
{
name: "Mirror horizontal and rotate 270 CW",
orientation: "Mirror horizontal and rotate 270 CW",
expected: ",transpose=0",
},
{
name: "Mirror horizontal and rotate 270 CW alternative",
orientation: "Right-bottom",
expected: ",transpose=0",
},
{
name: "Mirror horizontal and rotate 90 CW",
orientation: "Mirror horizontal and rotate 90 CW",
expected: ",transpose=3",
},
{
name: "Mirror horizontal and rotate 90 CW alternative",
orientation: "Left-top",
expected: ",transpose=3",
},
{
name: "Unknown orientation",
orientation: "Unknown Orientation",
expected: "",
},
{
name: "Empty orientation",
orientation: "",
expected: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := service.GetOrientationFilter(tt.orientation)
if result != tt.expected {
t.Errorf("GetOrientationFilter(%q) = %q, want %q", tt.orientation, result, tt.expected)
}
})
}
}
func TestGetImageOrientation(t *testing.T) {
// Create a temporary directory for testing
tempDir, err := os.MkdirTemp("", "ffmpeg_test")
if err != nil {
t.Fatalf("Failed to create temp directory: %v", err)
}
defer os.RemoveAll(tempDir)
service := NewImageService("ffmpeg", "ffprobe", false, tempDir)
t.Run("Non-existent file", func(t *testing.T) {
nonExistentFile := filepath.Join(tempDir, "non_existent.heic")
orientation, err := service.GetImageOrientation(nonExistentFile)
// Should return default orientation when exiftool fails
if err != nil {
t.Errorf("Expected no error for non-existent file, got: %v", err)
}
if orientation != "Horizontal (normal)" {
t.Errorf("Expected default orientation 'Horizontal (normal)', got: %q", orientation)
}
})
t.Run("Empty file path", func(t *testing.T) {
orientation, err := service.GetImageOrientation("")
// Should return default orientation when exiftool fails
if err != nil {
t.Errorf("Expected no error for empty file path, got: %v", err)
}
if orientation != "Horizontal (normal)" {
t.Errorf("Expected default orientation 'Horizontal (normal)', got: %q", orientation)
}
})
}
func TestNewImageService(t *testing.T) {
ffmpegPath := "/usr/bin/ffmpeg"
ffprobePath := "/usr/bin/ffprobe"
debug := true
cacheDir := "/tmp/test_cache"
service := NewImageService(ffmpegPath, ffprobePath, debug, cacheDir)
if service.ffmpegPath != ffmpegPath {
t.Errorf("Expected ffmpegPath %q, got %q", ffmpegPath, service.ffmpegPath)
}
if service.ffprobePath != ffprobePath {
t.Errorf("Expected ffprobePath %q, got %q", ffprobePath, service.ffprobePath)
}
if service.debug != debug {
t.Errorf("Expected debug %v, got %v", debug, service.debug)
}
if service.cacheDir != cacheDir {
t.Errorf("Expected cacheDir %q, got %q", cacheDir, service.cacheDir)
}
}
// Integration test for orientation handling in direct conversion
func TestConvertHEICToJPEGDirect_OrientationHandling(t *testing.T) {
// Skip this test if ffmpeg is not available
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
// Create a temporary directory for testing
tempDir, err := os.MkdirTemp("", "ffmpeg_integration_test")
if err != nil {
t.Fatalf("Failed to create temp directory: %v", err)
}
defer os.RemoveAll(tempDir)
service := NewImageService("ffmpeg", "ffprobe", true, tempDir)
t.Run("Direct conversion with orientation detection", func(t *testing.T) {
// This test requires actual HEIC files to work properly
// For CI/CD environments, we can mock this or skip if files don't exist
heicTestFiles := []string{
"/Users/steffag/Downloads/heic/IMG_6660.heic",
"/Users/steffag/Downloads/heic/IMG_2919.HEIC",
"/Users/steffag/Downloads/heic/shelf-christmas-decoration.heic",
}
for _, testFile := range heicTestFiles {
// Check if test file exists
if _, err := os.Stat(testFile); os.IsNotExist(err) {
t.Logf("Skipping test for %s (file not found)", filepath.Base(testFile))
continue
}
t.Logf("Testing orientation handling for %s", filepath.Base(testFile))
// Test orientation detection
orientation, err := service.GetImageOrientation(testFile)
if err != nil {
t.Errorf("Failed to get orientation for %s: %v", filepath.Base(testFile), err)
continue
}
t.Logf("Detected orientation: %s", orientation)
// Test filter generation
filter := service.GetOrientationFilter(orientation)
t.Logf("Generated filter: %s", filter)
// Test actual conversion (small size for speed)
jpegBytes, err := service.ConvertHEICToJPEGDirect(testFile, 100, 100, "5")
if err != nil {
t.Errorf("Failed to convert %s: %v", filepath.Base(testFile), err)
continue
}
if len(jpegBytes) < 400 {
t.Errorf("Converted image too small (%d bytes), likely conversion failed", len(jpegBytes))
}
t.Logf("Successfully converted %s to %d bytes", filepath.Base(testFile), len(jpegBytes))
}
})
}
// Benchmark the orientation filter generation
func BenchmarkGetOrientationFilter(b *testing.B) {
service := &ImageService{}
orientations := []string{
"Horizontal (normal)",
"Rotate 90 CW",
"Rotate 180",
"Mirror vertical",
"Unknown Orientation",
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
orientation := orientations[i%len(orientations)]
_ = service.GetOrientationFilter(orientation)
}
}
// Test table for all EXIF orientation values
func TestGetOrientationFilter_AllEXIFValues(t *testing.T) {
service := &ImageService{}
// Test all possible EXIF orientation values according to EXIF spec
exifTests := []struct {
exifValue string
description string
expectsTransformation bool
}{
{"1", "Top-left (normal)", false},
{"2", "Top-right (flip horizontal)", true},
{"3", "Bottom-right (rotate 180)", true},
{"4", "Bottom-left (flip vertical)", true},
{"5", "Left-top (transpose)", true},
{"6", "Right-top (rotate 90 CW)", true},
{"7", "Right-bottom (transverse)", true},
{"8", "Left-bottom (rotate 270 CW)", true},
}
for _, tt := range exifTests {
t.Run(tt.description, func(t *testing.T) {
filter := service.GetOrientationFilter(tt.exifValue)
if tt.expectsTransformation && filter == "" {
t.Errorf("Expected transformation for EXIF value %s (%s), but got empty filter", tt.exifValue, tt.description)
}
if !tt.expectsTransformation && filter != "" {
t.Errorf("Expected no transformation for EXIF value %s (%s), but got filter: %s", tt.exifValue, tt.description, filter)
}
})
}
}
+289
View File
@@ -0,0 +1,289 @@
package ffmpeg
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
"github.com/gtsteffaniak/go-logger/logger"
)
// SubtitleTrack represents a subtitle track (embedded or external file)
type SubtitleTrack struct {
Name string `json:"name"` // filename for external, or descriptive name for embedded
Language string `json:"language,omitempty"` // language code
Title string `json:"title,omitempty"` // title/description
Index *int `json:"index,omitempty"` // stream index for embedded subtitles (nil for external)
Codec string `json:"codec,omitempty"` // codec name for embedded subtitles
Content string `json:"content,omitempty"` // subtitle content
IsFile bool `json:"isFile"` // true for external files, false for embedded streams
}
// FFProbeOutput represents the JSON output from ffprobe
type FFProbeOutput struct {
Streams []struct {
Index int `json:"index"`
CodecType string `json:"codec_type"`
CodecName string `json:"codec_name"`
Tags map[string]string `json:"tags,omitempty"`
Disposition map[string]int `json:"disposition,omitempty"`
} `json:"streams"`
}
// DetectAllSubtitles finds both embedded and external subtitle tracks
func DetectAllSubtitles(videoPath string, parentDir string, modtime time.Time) []SubtitleTrack {
key := "all_subtitles:" + videoPath + ":" + modtime.Format(time.RFC3339)
// Check cache first
if cached, ok := utils.MediaCache.Get(key).([]SubtitleTrack); ok {
return cached
}
var allSubtitles []SubtitleTrack
// First, get embedded subtitles
embeddedSubs := detectEmbeddedSubtitles(videoPath)
allSubtitles = append(allSubtitles, embeddedSubs...)
// Then, get external subtitle files
externalSubs := detectExternalSubtitles(videoPath, parentDir)
allSubtitles = append(allSubtitles, externalSubs...)
// Cache the complete list
utils.MediaCache.Set(key, allSubtitles)
return allSubtitles
}
// detectEmbeddedSubtitles uses ffprobe to find embedded subtitle tracks
func detectEmbeddedSubtitles(realPath string) []SubtitleTrack {
cmd := exec.Command("ffprobe",
"-v", "quiet",
"-print_format", "json",
"-show_streams",
"-select_streams", "s",
realPath)
output, err := cmd.Output()
if err != nil {
logger.Debug("ffprobe failed for file: " + realPath + ", error: " + err.Error())
return nil
}
var probeOutput FFProbeOutput
if err := json.Unmarshal(output, &probeOutput); err != nil {
logger.Debug("failed to parse ffprobe output for file: " + realPath)
return nil
}
var subtitles []SubtitleTrack
for _, stream := range probeOutput.Streams {
if stream.CodecType == "subtitle" {
track := SubtitleTrack{
Index: &stream.Index,
Codec: stream.CodecName,
IsFile: false, // This is an embedded subtitle
}
// Extract language and title from tags
if stream.Tags != nil {
if lang, ok := stream.Tags["language"]; ok {
track.Language = lang
}
if title, ok := stream.Tags["title"]; ok {
track.Title = title
}
}
// Generate a descriptive name
if track.Title != "" {
track.Name = track.Title
} else if track.Language != "" {
track.Name = "Embedded (" + track.Language + ")"
} else {
track.Name = "Embedded Subtitle " + strconv.Itoa(stream.Index)
}
subtitles = append(subtitles, track)
}
}
return subtitles
}
// detectExternalSubtitles finds external subtitle files in the same directory
func detectExternalSubtitles(videoPath string, parentDir string) []SubtitleTrack {
var subtitles []SubtitleTrack
// Get the base name of the video (without extension)
videoBaseName := strings.TrimSuffix(filepath.Base(videoPath), filepath.Ext(videoPath))
// Common subtitle extensions
subtitleExts := []string{".srt", ".vtt", ".lrc", ".sbv", ".ass", ".ssa", ".sub", ".smi"}
// Look for subtitle files with matching base name
for _, ext := range subtitleExts {
subtitlePath := filepath.Join(parentDir, videoBaseName+ext)
if _, err := os.Stat(subtitlePath); err == nil {
// File exists
track := SubtitleTrack{
Name: filepath.Base(subtitlePath),
IsFile: true, // This is an external file
}
// Try to infer language from filename patterns like "video.en.srt"
parts := strings.Split(videoBaseName, ".")
if len(parts) > 1 {
// Check if the last part before extension looks like a language code
lastPart := parts[len(parts)-1]
if len(lastPart) == 2 || len(lastPart) == 3 {
track.Language = lastPart
}
}
subtitles = append(subtitles, track)
}
}
return subtitles
}
// ExtractSubtitleContent extracts subtitle content without service management
func ExtractSubtitleContent(videoPath string, streamIndex int) (string, error) {
cmd := exec.Command("ffmpeg",
"-i", videoPath,
"-map", fmt.Sprintf("0:%d", streamIndex),
"-c:s", "webvtt",
"-f", "webvtt",
"-") // output to stdout
output, err := cmd.Output()
if err != nil {
return "", fmt.Errorf("subtitle extraction failed: %v", err)
}
return string(output), nil
}
// LoadAndConvertSubtitleFile loads a subtitle file and converts it to WebVTT format
func LoadAndConvertSubtitleFile(subtitlePath string) (string, error) {
ext := strings.ToLower(filepath.Ext(subtitlePath))
if ext == ".vtt" {
// Already WebVTT, just read it
content, err := os.ReadFile(subtitlePath)
if err != nil {
return "", err
}
return string(content), nil
}
if ext == ".srt" {
// Convert SRT to WebVTT using ffmpeg
cmd := exec.Command("ffmpeg",
"-i", subtitlePath,
"-c:s", "webvtt",
"-f", "webvtt",
"-") // output to stdout
output, err := cmd.Output()
if err != nil {
return "", fmt.Errorf("failed to convert SRT to WebVTT: %v", err)
}
return string(output), nil
}
// For other formats, try to read as plain text and hope for the best
// This is a fallback - ideally you'd want format-specific converters
content, err := os.ReadFile(subtitlePath)
if err != nil {
return "", err
}
// Basic conversion wrapper for non-VTT formats
vttHeader := "WEBVTT\n\n"
return vttHeader + string(content), nil
}
// ExtractSingleSubtitle extracts content for a specific subtitle track by array index
func ExtractSingleSubtitle(videoPath string, parentDir string, trackIndex int, modtime time.Time) (SubtitleTrack, error) {
// Get all subtitle tracks
allTracks := DetectAllSubtitles(videoPath, parentDir, modtime)
if trackIndex >= len(allTracks) {
return SubtitleTrack{}, fmt.Errorf("subtitle track %d not found (only %d tracks available)", trackIndex, len(allTracks))
}
track := allTracks[trackIndex]
// Load content based on type
if track.IsFile {
// Load external subtitle file
subtitlePath := filepath.Join(parentDir, track.Name)
content, err := LoadAndConvertSubtitleFile(subtitlePath)
if err != nil {
return SubtitleTrack{}, fmt.Errorf("failed to load external subtitle: %v", err)
}
track.Content = content
} else {
// Extract embedded subtitle content
if track.Index == nil {
return SubtitleTrack{}, fmt.Errorf("embedded subtitle track has no stream index")
}
content, err := ExtractSubtitleContent(videoPath, *track.Index)
if err != nil {
return SubtitleTrack{}, fmt.Errorf("failed to extract embedded subtitle: %v", err)
}
track.Content = content
}
return track, nil
}
// LoadAllSubtitleContent loads the actual content for all detected subtitle tracks
func LoadAllSubtitleContent(videoPath string, subtitles []SubtitleTrack, modtime time.Time) error {
for idx := range subtitles {
subtitle := &subtitles[idx]
// Check if content is already cached
contentKey := fmt.Sprintf("subtitle_content:%s:%d:%s", videoPath, idx, modtime.Format(time.RFC3339))
if cached, ok := utils.MediaCache.Get(contentKey).(string); ok {
subtitle.Content = cached
continue
}
var content string
var err error
if subtitle.IsFile {
// Load external subtitle file content and convert to WebVTT
subtitlePath := filepath.Join(filepath.Dir(videoPath), subtitle.Name)
content, err = LoadAndConvertSubtitleFile(subtitlePath)
if err != nil {
logger.Debug("failed to read/convert subtitle file " + subtitlePath + ": " + err.Error())
continue
}
} else {
// Load embedded subtitle content
if subtitle.Index == nil {
logger.Debug("embedded subtitle has no stream index")
continue
}
content, err = ExtractSubtitleContent(videoPath, *subtitle.Index)
if err != nil {
logger.Debug("failed to extract embedded subtitle: " + err.Error())
continue
}
}
subtitle.Content = content
// Cache the content for future requests
utils.MediaCache.Set(contentKey, content)
}
return nil
}
+147
View File
@@ -0,0 +1,147 @@
package ffmpeg
import (
"bytes"
"context"
"fmt"
"os"
"os/exec"
"strconv"
"strings"
"github.com/gtsteffaniak/go-logger/logger"
)
// VideoService handles video preview operations with ffmpeg
type VideoService struct {
ffmpegPath string
ffprobePath string
debug bool
semaphore chan struct{}
}
// NewVideoService creates a new video service instance
func NewVideoService(ffmpegPath, ffprobePath string, maxConcurrent int, debug bool) *VideoService {
return &VideoService{
ffmpegPath: ffmpegPath,
ffprobePath: ffprobePath,
debug: debug,
semaphore: make(chan struct{}, maxConcurrent),
}
}
func (s *VideoService) acquire(ctx context.Context) error {
select {
case s.semaphore <- struct{}{}:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func (s *VideoService) release() {
<-s.semaphore
}
// GenerateVideoPreview generates a single preview image from a video using ffmpeg.
// videoPath: path to the input video file.
// outputPath: path where the generated preview image will be saved (e.g., "/tmp/preview.jpg").
// seekTime: how many seconds into the video to seek before capturing the frame.
func (s *VideoService) GenerateVideoPreview(videoPath, outputPath string, percentageSeek int) ([]byte, error) {
if err := s.acquire(context.Background()); err != nil {
return nil, err
}
defer s.release()
// Step 1: Get video duration from the container format
probeCmd := exec.Command(
s.ffprobePath,
"-v", "error",
// Use format=duration for better compatibility
"-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1",
videoPath,
)
var probeOut bytes.Buffer
probeCmd.Stdout = &probeOut
if s.debug {
probeCmd.Stderr = os.Stderr
}
if err := probeCmd.Run(); err != nil {
logger.Errorf("ffprobe command failed on file '%v' : %v", videoPath, err)
return nil, fmt.Errorf("ffprobe failed: %w", err)
}
durationStr := strings.TrimSpace(probeOut.String())
if durationStr == "" || durationStr == "N/A" {
logger.Errorf("could not determine video duration for file '%v' using duration info '%v'", videoPath, durationStr)
return nil, fmt.Errorf("could not determine video duration")
}
durationFloat, err := strconv.ParseFloat(durationStr, 64)
if err != nil {
// The original error you saw would be caught here if "N/A" was still the output
return nil, fmt.Errorf("invalid duration: %v", err)
}
if durationFloat <= 0 {
return nil, fmt.Errorf("video duration must be positive")
}
// Step 2: Get the duration of the video in whole seconds
duration := int(durationFloat)
// Step 3: Calculate seek time based on percentageSeek (percentage value)
seekSeconds := duration * percentageSeek / 100
// Step 4: Convert seekSeconds to string for ffmpeg command
seekTime := strconv.Itoa(seekSeconds)
// Step 5: Extract frame at seek time
cmd := exec.Command(
s.ffmpegPath,
"-ss", seekTime,
"-i", videoPath,
"-frames:v", "1",
"-q:v", "10",
"-y", // overwrite output
outputPath,
)
if s.debug {
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
}
err = cmd.Run()
if err != nil {
return nil, fmt.Errorf("ffmpeg command failed on file '%v' : %w", videoPath, err)
}
return os.ReadFile(outputPath)
}
// GetVideoDuration extracts the duration of a video file using ffprobe
func GetVideoDuration(ffprobePath string, videoPath string) (float64, error) {
cmd := exec.Command(ffprobePath,
"-v", "error",
"-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1",
videoPath)
output, err := cmd.Output()
if err != nil {
return 0, fmt.Errorf("ffprobe failed: %w", err)
}
durationStr := strings.TrimSpace(string(output))
if durationStr == "" || durationStr == "N/A" {
return 0, fmt.Errorf("could not determine video duration")
}
duration, err := strconv.ParseFloat(durationStr, 64)
if err != nil {
return 0, fmt.Errorf("invalid duration: %v", err)
}
return duration, nil
}
+73 -58
View File
@@ -5,6 +5,7 @@ go 1.25.0
require (
github.com/asdine/storm/v3 v3.2.1
github.com/coreos/go-oidc/v3 v3.15.0
github.com/dhowden/tag v0.0.0-20240417053706-3d75831295e8
github.com/dsoprea/go-exif/v3 v3.0.1
github.com/gen2brain/go-fitz v1.24.15
github.com/go-playground/validator/v10 v10.27.0
@@ -15,43 +16,47 @@ require (
github.com/gtsteffaniak/go-logger v0.1.2
github.com/kovidgoyal/imaging v1.6.4
github.com/pquerna/otp v1.5.0
github.com/spf13/afero v1.14.0
github.com/stretchr/testify v1.10.0
github.com/spf13/afero v1.15.0
github.com/stretchr/testify v1.11.1
github.com/swaggo/http-swagger v1.3.4
github.com/swaggo/swag v1.16.6
golang.org/x/crypto v0.41.0
golang.org/x/image v0.30.0
golang.org/x/mod v0.27.0
golang.org/x/oauth2 v0.30.0
golang.org/x/sys v0.35.0
golang.org/x/time v0.12.0
golang.org/x/crypto v0.42.0
golang.org/x/image v0.31.0
golang.org/x/mod v0.28.0
golang.org/x/oauth2 v0.31.0
golang.org/x/sys v0.36.0
golang.org/x/time v0.13.0
gopkg.in/yaml.v3 v3.0.1
)
require (
4d63.com/gocheckcompilerdirectives v1.3.0 // indirect
4d63.com/gochecknoglobals v0.2.2 // indirect
codeberg.org/chavacava/garif v0.2.0 // indirect
dario.cat/mergo v1.0.2 // indirect
github.com/4meepo/tagalign v1.4.2 // indirect
github.com/Abirdcfly/dupword v0.1.3 // indirect
dev.gaijin.team/go/exhaustruct/v4 v4.0.0 // indirect
dev.gaijin.team/go/golib v0.6.0 // indirect
github.com/4meepo/tagalign v1.4.3 // indirect
github.com/Abirdcfly/dupword v0.1.6 // indirect
github.com/AlwxSin/noinlineerr v1.0.5 // indirect
github.com/Antonboom/errname v1.1.0 // indirect
github.com/Antonboom/nilnil v1.1.0 // indirect
github.com/Antonboom/testifylint v1.6.1 // indirect
github.com/BurntSushi/toml v1.5.0 // indirect
github.com/Djarvur/go-err113 v0.0.0-20210108212216-aea10b59be24 // indirect
github.com/GaijinEntertainment/go-exhaustruct/v3 v3.3.1 // indirect
github.com/KyleBanks/depth v1.2.1 // indirect
github.com/Masterminds/semver/v3 v3.3.1 // indirect
github.com/OpenPeeDeeP/depguard/v2 v2.2.1 // indirect
github.com/air-verse/air v1.62.0 // indirect
github.com/alecthomas/chroma/v2 v2.17.2 // indirect
github.com/air-verse/air v1.63.0 // indirect
github.com/alecthomas/chroma/v2 v2.20.0 // indirect
github.com/alecthomas/go-check-sumtype v0.3.1 // indirect
github.com/alexkohler/nakedret/v2 v2.0.6 // indirect
github.com/alexkohler/prealloc v1.0.0 // indirect
github.com/alfatraining/structtag v1.0.0 // indirect
github.com/alingse/asasalint v0.0.11 // indirect
github.com/alingse/nilnesserr v0.2.0 // indirect
github.com/ashanbrown/forbidigo v1.6.0 // indirect
github.com/ashanbrown/makezero v1.2.0 // indirect
github.com/ashanbrown/forbidigo/v2 v2.1.0 // indirect
github.com/ashanbrown/makezero/v2 v2.0.1 // indirect
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/bep/godartsass/v2 v2.5.0 // indirect
@@ -59,13 +64,14 @@ require (
github.com/bkielbasa/cyclop v1.2.3 // indirect
github.com/blizzy78/varnamelen v0.8.0 // indirect
github.com/bombsimon/wsl/v4 v4.7.0 // indirect
github.com/bombsimon/wsl/v5 v5.1.1 // indirect
github.com/boombuler/barcode v1.1.0 // indirect
github.com/breml/bidichk v0.3.3 // indirect
github.com/breml/errchkjson v0.4.1 // indirect
github.com/butuzov/ireturn v0.4.0 // indirect
github.com/butuzov/mirror v1.3.0 // indirect
github.com/catenacyber/perfsprint v0.9.1 // indirect
github.com/ccojocar/zxcvbn-go v1.0.2 // indirect
github.com/ccojocar/zxcvbn-go v1.0.4 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/charithe/durationcheck v0.0.10 // indirect
github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect
@@ -73,12 +79,11 @@ require (
github.com/charmbracelet/x/ansi v0.8.0 // indirect
github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd // indirect
github.com/charmbracelet/x/term v0.2.1 // indirect
github.com/chavacava/garif v0.1.0 // indirect
github.com/ckaznocha/intrange v0.3.1 // indirect
github.com/cpuguy83/go-md2man/v2 v2.0.6 // indirect
github.com/creack/pty v1.1.24 // indirect
github.com/curioswitch/go-reassign v0.3.0 // indirect
github.com/daixiang0/gci v0.13.6 // indirect
github.com/daixiang0/gci v0.13.7 // indirect
github.com/dave/dst v0.27.3 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/denis-tingaikin/go-header v0.5.0 // indirect
@@ -92,15 +97,26 @@ require (
github.com/firefart/nonamedreturns v1.0.6 // indirect
github.com/fsnotify/fsnotify v1.9.0 // indirect
github.com/fzipp/gocyclo v0.6.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.9 // indirect
github.com/gabriel-vasile/mimetype v1.4.10 // indirect
github.com/ghostiam/protogetter v0.3.15 // indirect
github.com/go-critic/go-critic v0.13.0 // indirect
github.com/go-errors/errors v1.5.1 // indirect
github.com/go-jose/go-jose/v4 v4.1.2 // indirect
github.com/go-openapi/jsonpointer v0.21.2 // indirect
github.com/go-openapi/jsonreference v0.21.0 // indirect
github.com/go-openapi/jsonpointer v0.22.0 // indirect
github.com/go-openapi/jsonreference v0.21.1 // indirect
github.com/go-openapi/spec v0.21.0 // indirect
github.com/go-openapi/swag v0.23.1 // indirect
github.com/go-openapi/swag v0.24.1 // indirect
github.com/go-openapi/swag/cmdutils v0.24.0 // indirect
github.com/go-openapi/swag/conv v0.24.0 // indirect
github.com/go-openapi/swag/fileutils v0.24.0 // indirect
github.com/go-openapi/swag/jsonname v0.24.0 // indirect
github.com/go-openapi/swag/jsonutils v0.24.0 // indirect
github.com/go-openapi/swag/loading v0.24.0 // indirect
github.com/go-openapi/swag/mangling v0.24.0 // indirect
github.com/go-openapi/swag/netutils v0.24.0 // indirect
github.com/go-openapi/swag/stringutils v0.24.0 // indirect
github.com/go-openapi/swag/typeutils v0.24.0 // indirect
github.com/go-openapi/swag/yamlutils v0.24.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-toolsmith/astcast v1.1.0 // indirect
@@ -110,21 +126,22 @@ require (
github.com/go-toolsmith/astp v1.1.0 // indirect
github.com/go-toolsmith/strparse v1.1.0 // indirect
github.com/go-toolsmith/typep v1.1.0 // indirect
github.com/go-viper/mapstructure/v2 v2.2.1 // indirect
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
github.com/go-xmlfmt/xmlfmt v1.1.3 // indirect
github.com/gobwas/glob v0.2.3 // indirect
github.com/gofrs/flock v0.12.1 // indirect
github.com/gohugoio/hugo v0.147.6 // indirect
github.com/golang/geo v0.0.0-20250821133510-ecfc33a939ac // indirect
github.com/gohugoio/hugo v0.149.1 // indirect
github.com/golang/geo v0.0.0-20250912065020-b504328d3ef3 // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/golangci/dupl v0.0.0-20250308024227-f665c8d69b32 // indirect
github.com/golangci/go-printf-func-name v0.1.0 // indirect
github.com/golangci/gofmt v0.0.0-20250106114630-d62b90e6713d // indirect
github.com/golangci/golangci-lint/v2 v2.1.6 // indirect
github.com/golangci/golangci-lint/v2 v2.4.0 // indirect
github.com/golangci/golines v0.0.0-20250217134842-442fd0091d95 // indirect
github.com/golangci/misspell v0.6.0 // indirect
github.com/golangci/plugin-module-register v0.1.1 // indirect
github.com/golangci/misspell v0.7.0 // indirect
github.com/golangci/plugin-module-register v0.1.2 // indirect
github.com/golangci/revgrep v0.8.0 // indirect
github.com/golangci/swaggoswag v0.0.0-20250504205917-77f2aca3143e // indirect
github.com/golangci/unconvert v0.0.0-20250410112200-a129a6e6413e // indirect
github.com/gordonklaus/ineffassign v0.1.0 // indirect
github.com/gostaticanalysis/analysisutil v0.7.1 // indirect
@@ -137,9 +154,9 @@ require (
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/hexops/gotextdiff v1.0.3 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jgautheron/goconst v1.8.1 // indirect
github.com/jgautheron/goconst v1.8.2 // indirect
github.com/jingyugao/rowserrcheck v1.1.1 // indirect
github.com/jjti/go-spancheck v0.6.4 // indirect
github.com/jjti/go-spancheck v0.6.5 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/julz/importas v0.2.0 // indirect
github.com/jupiterrider/ffi v0.5.1 // indirect
@@ -149,18 +166,19 @@ require (
github.com/kulti/thelper v0.6.3 // indirect
github.com/kunwardeep/paralleltest v1.0.14 // indirect
github.com/lasiar/canonicalheader v1.1.2 // indirect
github.com/ldez/exptostd v0.4.3 // indirect
github.com/ldez/gomoddirectives v0.6.1 // indirect
github.com/ldez/grignotin v0.9.0 // indirect
github.com/ldez/exptostd v0.4.4 // indirect
github.com/ldez/gomoddirectives v0.7.0 // indirect
github.com/ldez/grignotin v0.10.0 // indirect
github.com/ldez/tagliatelle v0.7.1 // indirect
github.com/ldez/usetesting v0.4.3 // indirect
github.com/ldez/usetesting v0.5.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/leonklingele/grouper v1.1.2 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/macabu/inamedparam v0.2.0 // indirect
github.com/magiconair/properties v1.8.6 // indirect
github.com/mailru/easyjson v0.9.0 // indirect
github.com/manuelarte/funcorder v0.2.1 // indirect
github.com/manuelarte/embeddedstructfieldcheck v0.3.0 // indirect
github.com/manuelarte/funcorder v0.5.0 // indirect
github.com/maratori/testableexamples v1.0.0 // indirect
github.com/maratori/testpackage v1.1.1 // indirect
github.com/matoous/godox v1.1.0 // indirect
@@ -168,7 +186,7 @@ require (
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-runewidth v0.0.16 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
github.com/mgechev/revive v1.9.0 // indirect
github.com/mgechev/revive v1.11.0 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/mitchellh/mapstructure v1.5.1-0.20231216201459-8508981c8b6c // indirect
github.com/moricho/tparallel v0.3.2 // indirect
@@ -176,8 +194,7 @@ require (
github.com/nakabonne/nestif v0.3.1 // indirect
github.com/nishanths/exhaustive v0.12.0 // indirect
github.com/nishanths/predeclared v0.2.2 // indirect
github.com/nunnatsa/ginkgolinter v0.19.1 // indirect
github.com/olekukonko/tablewriter v0.0.5 // indirect
github.com/nunnatsa/ginkgolinter v0.20.0 // indirect
github.com/pelletier/go-toml v1.9.5 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
@@ -198,18 +215,18 @@ require (
github.com/ryancurrah/gomodguard v1.4.1 // indirect
github.com/ryanrolds/sqlclosecheck v0.5.1 // indirect
github.com/sanposhiho/wastedassign/v2 v2.1.0 // indirect
github.com/santhosh-tekuri/jsonschema/v6 v6.0.1 // indirect
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 // indirect
github.com/sashamelentyev/interfacebloat v1.1.0 // indirect
github.com/sashamelentyev/usestdlibvars v1.28.0 // indirect
github.com/securego/gosec/v2 v2.22.3 // indirect
github.com/sashamelentyev/usestdlibvars v1.29.0 // indirect
github.com/securego/gosec/v2 v2.22.7 // indirect
github.com/sirupsen/logrus v1.9.3 // indirect
github.com/sivchari/containedctx v1.0.3 // indirect
github.com/sonatard/noctx v0.1.0 // indirect
github.com/sonatard/noctx v0.4.0 // indirect
github.com/sourcegraph/go-diff v0.7.0 // indirect
github.com/spf13/cast v1.8.0 // indirect
github.com/spf13/cast v1.9.2 // indirect
github.com/spf13/cobra v1.9.1 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.6 // indirect
github.com/spf13/pflag v1.0.7 // indirect
github.com/spf13/viper v1.12.0 // indirect
github.com/ssgreg/nlreturn/v2 v2.2.1 // indirect
github.com/stbenjam/no-sprintf-host-port v0.2.0 // indirect
@@ -217,7 +234,7 @@ require (
github.com/subosito/gotenv v1.4.1 // indirect
github.com/swaggo/files v1.0.1 // indirect
github.com/tdakkota/asciicheck v0.4.1 // indirect
github.com/tdewolff/parse/v2 v2.8.1 // indirect
github.com/tdewolff/parse/v2 v2.8.3 // indirect
github.com/tetafro/godot v1.5.1 // indirect
github.com/timakin/bodyclose v0.0.0-20241222091800-1db5c5ca4d67 // indirect
github.com/timonwong/loggercheck v0.11.0 // indirect
@@ -227,7 +244,7 @@ require (
github.com/ultraware/whitespace v0.2.0 // indirect
github.com/urfave/cli/v2 v2.3.0 // indirect
github.com/uudashr/gocognit v1.2.0 // indirect
github.com/uudashr/iface v1.3.1 // indirect
github.com/uudashr/iface v1.4.1 // indirect
github.com/xen0n/gosmopolitan v1.3.0 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
github.com/yagipy/maintidx v1.0.0 // indirect
@@ -235,21 +252,19 @@ require (
github.com/ykadowak/zerologlint v0.1.5 // indirect
gitlab.com/bosi/decorder v0.4.2 // indirect
go-simpler.org/musttag v0.13.1 // indirect
go-simpler.org/sloglint v0.11.0 // indirect
go-simpler.org/sloglint v0.11.1 // indirect
go.augendre.info/arangolint v0.2.0 // indirect
go.augendre.info/fatcontext v0.8.0 // indirect
go.etcd.io/bbolt v1.4.3 // indirect
go.uber.org/atomic v1.7.0 // indirect
go.uber.org/automaxprocs v1.6.0 // indirect
go.uber.org/multierr v1.6.0 // indirect
go.uber.org/zap v1.24.0 // indirect
golang.org/x/exp/typeparams v0.0.0-20250210185358-939b2ce775ac // indirect
golang.org/x/net v0.43.0 // indirect
golang.org/x/sync v0.16.0 // indirect
golang.org/x/text v0.28.0 // indirect
golang.org/x/tools v0.36.0 // indirect
golang.org/x/tools/go/expect v0.1.1-deprecated // indirect
golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated // indirect
google.golang.org/protobuf v1.36.6 // indirect
go.uber.org/multierr v1.10.0 // indirect
go.uber.org/zap v1.27.0 // indirect
golang.org/x/exp/typeparams v0.0.0-20250620022241-b7579e27df2b // indirect
golang.org/x/net v0.44.0 // indirect
golang.org/x/sync v0.17.0 // indirect
golang.org/x/text v0.29.0 // indirect
golang.org/x/tools v0.37.0 // indirect
google.golang.org/protobuf v1.36.8 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
honnef.co/go/tools v0.6.1 // indirect
+191 -160
View File
@@ -34,13 +34,21 @@ cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0Zeo
cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk=
cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs=
cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0=
codeberg.org/chavacava/garif v0.2.0 h1:F0tVjhYbuOCnvNcU3YSpO6b3Waw6Bimy4K0mM8y6MfY=
codeberg.org/chavacava/garif v0.2.0/go.mod h1:P2BPbVbT4QcvLZrORc2T29szK3xEOlnl0GiPTJmEqBQ=
dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=
dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=
dev.gaijin.team/go/exhaustruct/v4 v4.0.0 h1:873r7aNneqoBB3IaFIzhvt2RFYTuHgmMjoKfwODoI1Y=
dev.gaijin.team/go/exhaustruct/v4 v4.0.0/go.mod h1:aZ/k2o4Y05aMJtiux15x8iXaumE88YdiB0Ai4fXOzPI=
dev.gaijin.team/go/golib v0.6.0 h1:v6nnznFTs4bppib/NyU1PQxobwDHwCXXl15P7DV5Zgo=
dev.gaijin.team/go/golib v0.6.0/go.mod h1:uY1mShx8Z/aNHWDyAkZTkX+uCi5PdX7KsG1eDQa2AVE=
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
github.com/4meepo/tagalign v1.4.2 h1:0hcLHPGMjDyM1gHG58cS73aQF8J4TdVR96TZViorO9E=
github.com/4meepo/tagalign v1.4.2/go.mod h1:+p4aMyFM+ra7nb41CnFG6aSDXqRxU/w1VQqScKqDARI=
github.com/Abirdcfly/dupword v0.1.3 h1:9Pa1NuAsZvpFPi9Pqkd93I7LIYRURj+A//dFd5tgBeE=
github.com/Abirdcfly/dupword v0.1.3/go.mod h1:8VbB2t7e10KRNdwTVoxdBaxla6avbhGzb8sCTygUMhw=
github.com/4meepo/tagalign v1.4.3 h1:Bnu7jGWwbfpAie2vyl63Zup5KuRv21olsPIha53BJr8=
github.com/4meepo/tagalign v1.4.3/go.mod h1:00WwRjiuSbrRJnSVeGWPLp2epS5Q/l4UEy0apLLS37c=
github.com/Abirdcfly/dupword v0.1.6 h1:qeL6u0442RPRe3mcaLcbaCi2/Y/hOcdtw6DE9odjz9c=
github.com/Abirdcfly/dupword v0.1.6/go.mod h1:s+BFMuL/I4YSiFv29snqyjwzDp4b65W2Kvy+PKzZ6cw=
github.com/AlwxSin/noinlineerr v1.0.5 h1:RUjt63wk1AYWTXtVXbSqemlbVTb23JOSRiNsshj7TbY=
github.com/AlwxSin/noinlineerr v1.0.5/go.mod h1:+QgkkoYrMH7RHvcdxdlI7vYYEdgeoFOVjU9sUhw/rQc=
github.com/Antonboom/errname v1.1.0 h1:A+ucvdpMwlo/myWrkHEUEBWc/xuXdud23S8tmTb/oAE=
github.com/Antonboom/errname v1.1.0/go.mod h1:O1NMrzgUcVBGIfi3xlVuvX8Q/VP/73sseCaAppfjqZw=
github.com/Antonboom/nilnil v1.1.0 h1:jGxJxjgYS3VUUtOTNk8Z1icwT5ESpLH/426fjmQG+ng=
@@ -57,8 +65,6 @@ github.com/DataDog/zstd v1.4.1 h1:3oxKN3wbHibqx897utPC2LTQU4J+IHWWJO+glkAkpFM=
github.com/DataDog/zstd v1.4.1/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo=
github.com/Djarvur/go-err113 v0.0.0-20210108212216-aea10b59be24 h1:sHglBQTwgx+rWPdisA5ynNEsoARbiCBOyGcJM4/OzsM=
github.com/Djarvur/go-err113 v0.0.0-20210108212216-aea10b59be24/go.mod h1:4UJr5HIiMZrwgkSPdsjy2uOQExX/WEILpIrO9UPGuXs=
github.com/GaijinEntertainment/go-exhaustruct/v3 v3.3.1 h1:Sz1JIXEcSfhz7fUi7xHnhpIE0thVASYjvosApmHuD2k=
github.com/GaijinEntertainment/go-exhaustruct/v3 v3.3.1/go.mod h1:n/LSCXNuIYqVfBlVXyHfMQkZDdp1/mmxfSjADd3z1Zg=
github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc=
github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE=
github.com/Masterminds/semver/v3 v3.3.1 h1:QtNSWtVZ3nBfk8mAOu/B6v7FMJ+NHTIgUPi7rj+4nv4=
@@ -67,16 +73,16 @@ github.com/OpenPeeDeeP/depguard/v2 v2.2.1 h1:vckeWVESWp6Qog7UZSARNqfu/cZqvki8zsu
github.com/OpenPeeDeeP/depguard/v2 v2.2.1/go.mod h1:q4DKzC4UcVaAvcfd41CZh0PWpGgzrVxUYBlgKNGquUo=
github.com/Sereal/Sereal v0.0.0-20190618215532-0b8ac451a863 h1:BRrxwOZBolJN4gIwvZMJY1tzqBvQgpaZiQRuIDD40jM=
github.com/Sereal/Sereal v0.0.0-20190618215532-0b8ac451a863/go.mod h1:D0JMgToj/WdxCgd30Kc1UcA9E+WdZoJqeVOuYW7iTBM=
github.com/air-verse/air v1.62.0 h1:6CoXL4MAX9dc4xAzLfjMcDfbBoGmW5VjuuTV/1+bI+M=
github.com/air-verse/air v1.62.0/go.mod h1:EO+jWuetL10tS9raffwg8WEV0t0KUeucRRaf9ii86dA=
github.com/air-verse/air v1.63.0 h1:fwcdHpwaUe4/+q349PxptzAIn8gVE6Yke8TgW0LsDxQ=
github.com/air-verse/air v1.63.0/go.mod h1:RyCQVx2+3Zz2BzoqkukYiGmWkWXNKMf0x5ubIFcUB8Q=
github.com/alecthomas/assert/v2 v2.11.0 h1:2Q9r3ki8+JYXvGsDyBXwH3LcJ+WK5D0gc5E8vS6K3D0=
github.com/alecthomas/assert/v2 v2.11.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k=
github.com/alecthomas/chroma/v2 v2.17.2 h1:Rm81SCZ2mPoH+Q8ZCc/9YvzPUN/E7HgPiPJD8SLV6GI=
github.com/alecthomas/chroma/v2 v2.17.2/go.mod h1:RVX6AvYm4VfYe/zsk7mjHueLDZor3aWCNE14TFlepBk=
github.com/alecthomas/chroma/v2 v2.20.0 h1:sfIHpxPyR07/Oylvmcai3X/exDlE8+FA820NTz+9sGw=
github.com/alecthomas/chroma/v2 v2.20.0/go.mod h1:e7tViK0xh/Nf4BYHl00ycY6rV7b8iXBksI9E359yNmA=
github.com/alecthomas/go-check-sumtype v0.3.1 h1:u9aUvbGINJxLVXiFvHUlPEaD7VDULsrxJb4Aq31NLkU=
github.com/alecthomas/go-check-sumtype v0.3.1/go.mod h1:A8TSiN3UPRw3laIgWEUOHHLPa6/r9MtoigdlP5h3K/E=
github.com/alecthomas/repr v0.4.0 h1:GhI2A8MACjfegCPVq9f1FLvIBS+DrQ2KQBFZP1iFzXc=
github.com/alecthomas/repr v0.4.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4=
github.com/alecthomas/repr v0.5.1 h1:E3G4t2QbHTSNpPKBgMTln5KLkZHLOcU7r37J4pXBuIg=
github.com/alecthomas/repr v0.5.1/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4=
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
@@ -86,6 +92,8 @@ github.com/alexkohler/nakedret/v2 v2.0.6 h1:ME3Qef1/KIKr3kWX3nti3hhgNxw6aqN5pZmQ
github.com/alexkohler/nakedret/v2 v2.0.6/go.mod h1:l3RKju/IzOMQHmsEvXwkqMDzHHvurNQfAgE1eVmT40Q=
github.com/alexkohler/prealloc v1.0.0 h1:Hbq0/3fJPQhNkN0dR95AVrr6R7tou91y0uHG5pOcUuw=
github.com/alexkohler/prealloc v1.0.0/go.mod h1:VetnK3dIgFBBKmg0YnD9F9x6Icjd+9cvfHR56wJVlKE=
github.com/alfatraining/structtag v1.0.0 h1:2qmcUqNcCoyVJ0up879K614L9PazjBSFruTB0GOFjCc=
github.com/alfatraining/structtag v1.0.0/go.mod h1:p3Xi5SwzTi+Ryj64DqjLWz7XurHxbGsq6y3ubePJPus=
github.com/alingse/asasalint v0.0.11 h1:SFwnQXJ49Kx/1GghOFz1XGqHYKp21Kq1nHad/0WQRnw=
github.com/alingse/asasalint v0.0.11/go.mod h1:nCaoMhw7a9kSJObvQyVzNTPBDbNpdocqrSP7t/cW5+I=
github.com/alingse/nilnesserr v0.2.0 h1:raLem5KG7EFVb4UIDAXgrv3N2JIaffeKNtcEXkEWd/w=
@@ -94,14 +102,14 @@ github.com/armon/go-radix v1.0.1-0.20221118154546-54df44f2176c h1:651/eoCRnQ7YtS
github.com/armon/go-radix v1.0.1-0.20221118154546-54df44f2176c/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=
github.com/asdine/storm/v3 v3.2.1 h1:I5AqhkPK6nBZ/qJXySdI7ot5BlXSZ7qvDY1zAn5ZJac=
github.com/asdine/storm/v3 v3.2.1/go.mod h1:LEpXwGt4pIqrE/XcTvCnZHT5MgZCV6Ub9q7yQzOFWr0=
github.com/ashanbrown/forbidigo v1.6.0 h1:D3aewfM37Yb3pxHujIPSpTf6oQk9sc9WZi8gerOIVIY=
github.com/ashanbrown/forbidigo v1.6.0/go.mod h1:Y8j9jy9ZYAEHXdu723cUlraTqbzjKF1MUyfOKL+AjcU=
github.com/ashanbrown/makezero v1.2.0 h1:/2Lp1bypdmK9wDIq7uWBlDF1iMUpIIS4A+pF6C9IEUU=
github.com/ashanbrown/makezero v1.2.0/go.mod h1:dxlPhHbDMC6N6xICzFBSK+4njQDdK8euNO0qjQMtGY4=
github.com/ashanbrown/forbidigo/v2 v2.1.0 h1:NAxZrWqNUQiDz19FKScQ/xvwzmij6BiOw3S0+QUQ+Hs=
github.com/ashanbrown/forbidigo/v2 v2.1.0/go.mod h1:0zZfdNAuZIL7rSComLGthgc/9/n2FqspBOH90xlCHdA=
github.com/ashanbrown/makezero/v2 v2.0.1 h1:r8GtKetWOgoJ4sLyUx97UTwyt2dO7WkGFHizn/Lo8TY=
github.com/ashanbrown/makezero/v2 v2.0.1/go.mod h1:kKU4IMxmYW1M4fiEHMb2vc5SFoPzXvgbMR9gIp5pjSw=
github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8=
github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=
github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
@@ -110,8 +118,8 @@ github.com/bep/clocks v0.5.0 h1:hhvKVGLPQWRVsBP/UB7ErrHYIO42gINVbvqxvYTPVps=
github.com/bep/clocks v0.5.0/go.mod h1:SUq3q+OOq41y2lRQqH5fsOoxN8GbxSiT6jvoVVLCVhU=
github.com/bep/debounce v1.2.1 h1:v67fRdBA9UQu2NhLFXrSg0Brw7CexQekrBwDMM8bzeY=
github.com/bep/debounce v1.2.1/go.mod h1:H8yggRPQKLUhUoqrJC1bO2xNya7vanpDl7xR3ISbCJ0=
github.com/bep/gitmap v1.6.0 h1:sDuQMm9HoTL0LtlrfxjbjgAg2wHQd4nkMup2FInYzhA=
github.com/bep/gitmap v1.6.0/go.mod h1:n+3W1f/rot2hynsqEGxGMErPRgT41n9CkGuzPvz9cIw=
github.com/bep/gitmap v1.9.0 h1:2pyb1ex+cdwF6c4tsrhEgEKfyNfxE34d5K+s2sa9byc=
github.com/bep/gitmap v1.9.0/go.mod h1:Juq6e1qqCRvc1W7nzgadPGI9IGV13ZncEebg5atj4Vo=
github.com/bep/goat v0.5.0 h1:S8jLXHCVy/EHIoCY+btKkmcxcXFd34a0Q63/0D4TKeA=
github.com/bep/goat v0.5.0/go.mod h1:Md9x7gRxiWKs85yHlVTvHQw9rg86Bm+Y4SuYE8CTH7c=
github.com/bep/godartsass/v2 v2.5.0 h1:tKRvwVdyjCIr48qgtLa4gHEdtRkPF8H1OeEhJAEv7xg=
@@ -122,6 +130,8 @@ github.com/bep/goportabletext v0.1.0 h1:8dqym2So1cEqVZiBa4ZnMM1R9l/DnC1h4ONg4J5k
github.com/bep/goportabletext v0.1.0/go.mod h1:6lzSTsSue75bbcyvVc0zqd1CdApuT+xkZQ6Re5DzZFg=
github.com/bep/gowebp v0.4.0 h1:QihuVnvIKbRoeBNQkN0JPMM8ClLmD6V2jMftTFwSK3Q=
github.com/bep/gowebp v0.4.0/go.mod h1:95gtYkAA8iIn1t3HkAPurRCVGV/6NhgaHJ1urz0iIwc=
github.com/bep/helpers v0.6.0 h1:qtqMCK8XPFNM9hp5Ztu9piPjxNNkk8PIyUVjg6v8Bsw=
github.com/bep/helpers v0.6.0/go.mod h1:IOZlgx5PM/R/2wgyCatfsgg5qQ6rNZJNDpWGXqDR044=
github.com/bep/imagemeta v0.12.0 h1:ARf+igs5B7pf079LrqRnwzQ/wEB8Q9v4NSDRZO1/F5k=
github.com/bep/imagemeta v0.12.0/go.mod h1:23AF6O+4fUi9avjiydpKLStUNtJr5hJB4rarG18JpN8=
github.com/bep/lazycache v0.8.0 h1:lE5frnRjxaOFbkPZ1YL6nijzOPPz6zeXasJq8WpG4L8=
@@ -138,6 +148,8 @@ github.com/blizzy78/varnamelen v0.8.0 h1:oqSblyuQvFsW1hbBHh1zfwrKe3kcSj0rnXkKzsQ
github.com/blizzy78/varnamelen v0.8.0/go.mod h1:V9TzQZ4fLJ1DSrjVDfl89H7aMnTvKkApdHeyESmyR7k=
github.com/bombsimon/wsl/v4 v4.7.0 h1:1Ilm9JBPRczjyUs6hvOPKvd7VL1Q++PL8M0SXBDf+jQ=
github.com/bombsimon/wsl/v4 v4.7.0/go.mod h1:uV/+6BkffuzSAVYD+yGyld1AChO7/EuLrCF/8xTiapg=
github.com/bombsimon/wsl/v5 v5.1.1 h1:cQg5KJf9FlctAH4cpL9vLKnziYknoCMCdqXl0wjl72Q=
github.com/bombsimon/wsl/v5 v5.1.1/go.mod h1:Gp8lD04z27wm3FANIUPZycXp+8huVsn0oxc+n4qfV9I=
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8=
github.com/boombuler/barcode v1.1.0 h1:ChaYjBR63fr4LFyGn8E8nt7dBSt3MiU3zMOZqFvVkHo=
github.com/boombuler/barcode v1.1.0/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8=
@@ -151,8 +163,8 @@ github.com/butuzov/mirror v1.3.0 h1:HdWCXzmwlQHdVhwvsfBb2Au0r3HyINry3bDWLYXiKoc=
github.com/butuzov/mirror v1.3.0/go.mod h1:AEij0Z8YMALaq4yQj9CPPVYOyJQyiexpQEQgihajRfI=
github.com/catenacyber/perfsprint v0.9.1 h1:5LlTp4RwTooQjJCvGEFV6XksZvWE7wCOUvjD2z0vls0=
github.com/catenacyber/perfsprint v0.9.1/go.mod h1:q//VWC2fWbcdSLEY1R3l8n0zQCDPdE4IjZwyY1HMunM=
github.com/ccojocar/zxcvbn-go v1.0.2 h1:na/czXU8RrhXO4EZme6eQJLR4PzcGsahsBOAwU6I3Vg=
github.com/ccojocar/zxcvbn-go v1.0.2/go.mod h1:g1qkXtUSvHP8lhHp5GrSmTz6uWALGRMQdw6Qnz/hi60=
github.com/ccojocar/zxcvbn-go v1.0.4 h1:FWnCIRMXPj43ukfX000kvBZvV6raSxakYr1nzyNrUcc=
github.com/ccojocar/zxcvbn-go v1.0.4/go.mod h1:3GxGX+rHmueTUMvm5ium7irpyjmm7ikxYFOSJB21Das=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
@@ -170,8 +182,6 @@ github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd h1:vy0G
github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs=
github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ=
github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg=
github.com/chavacava/garif v0.1.0 h1:2JHa3hbYf5D9dsgseMKAmc/MZ109otzgNFk5s87H9Pc=
github.com/chavacava/garif v0.1.0/go.mod h1:XMyYCkEL58DF0oyW4qDjjnPWONs2HBqYKI+UIPD+Gww=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
@@ -190,8 +200,8 @@ github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
github.com/curioswitch/go-reassign v0.3.0 h1:dh3kpQHuADL3cobV/sSGETA8DOv457dwl+fbBAhrQPs=
github.com/curioswitch/go-reassign v0.3.0/go.mod h1:nApPCCTtqLJN/s8HfItCcKV0jIPwluBOvZP+dsJGA88=
github.com/daixiang0/gci v0.13.6 h1:RKuEOSkGpSadkGbvZ6hJ4ddItT3cVZ9Vn9Rybk6xjl8=
github.com/daixiang0/gci v0.13.6/go.mod h1:12etP2OniiIdP4q+kjUGrC/rUagga7ODbqsom5Eo5Yk=
github.com/daixiang0/gci v0.13.7 h1:+0bG5eK9vlI08J+J/NWGbWPTNiXPG4WhNLJOkSxWITQ=
github.com/daixiang0/gci v0.13.7/go.mod h1:812WVN6JLFY9S6Tv76twqmNqevN0pa3SX3nih0brVzQ=
github.com/dave/dst v0.27.3 h1:P1HPoMza3cMEquVf9kKy8yXsFirry4zEnWOdYPOoIzY=
github.com/dave/dst v0.27.3/go.mod h1:jHh6EOibnHgcUW3WjKHisiooEkYwqpHLBSX1iOBhEyc=
github.com/dave/jennifer v1.7.1 h1:B4jJJDHelWcDhlRQxWeo0Npa/pYKBLrirAQoTN45txo=
@@ -201,6 +211,8 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/denis-tingaikin/go-header v0.5.0 h1:SRdnP5ZKvcO9KKRP1KJrhFR3RrlGuD+42t4429eC9k8=
github.com/denis-tingaikin/go-header v0.5.0/go.mod h1:mMenU5bWrok6Wl2UsZjy+1okegmwQ3UgWl4V1D8gjlY=
github.com/dhowden/tag v0.0.0-20240417053706-3d75831295e8 h1:OtSeLS5y0Uy01jaKK4mA/WVIYtpzVm63vLVAPzJXigg=
github.com/dhowden/tag v0.0.0-20240417053706-3d75831295e8/go.mod h1:apkPC/CR3s48O2D7Y++n1XWEpgPNNCjXYga3PPbJe2E=
github.com/disintegration/gift v1.2.1 h1:Y005a1X4Z7Uc+0gLpSAsKhWi4qLtsdEcMIbbdvdZ6pc=
github.com/disintegration/gift v1.2.1/go.mod h1:Jh2i7f7Q2BM7Ezno3PhfezbR1xpUg9dUg3/RlKGr4HI=
github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ=
@@ -230,8 +242,8 @@ github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1m
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/ettle/strcase v0.2.0 h1:fGNiVF21fHXpX1niBgk0aROov1LagYsOwV/xqKDKR/Q=
github.com/ettle/strcase v0.2.0/go.mod h1:DajmHElDSaX76ITe3/VHVyMin4LWSJN5Z909Wp+ED1A=
github.com/evanw/esbuild v0.25.3 h1:4JKyUsm/nHDhpxis4IyWXAi8GiyTwG1WdEp6OhGVE8U=
github.com/evanw/esbuild v0.25.3/go.mod h1:D2vIQZqV/vIf/VRHtViaUtViZmG7o+kKmlBfVQuRi48=
github.com/evanw/esbuild v0.25.9 h1:aU7GVC4lxJGC1AyaPwySWjSIaNLAdVEEuq3chD0Khxs=
github.com/evanw/esbuild v0.25.9/go.mod h1:D2vIQZqV/vIf/VRHtViaUtViZmG7o+kKmlBfVQuRi48=
github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
github.com/fatih/structtag v1.2.0 h1:/OdNE99OxoI/PqaW/SuSK9uxxT3f/tcSZgon/ssNSx4=
@@ -245,12 +257,12 @@ github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/fzipp/gocyclo v0.6.0 h1:lsblElZG7d3ALtGMx9fmxeTKZaLLpU8mET09yN4BBLo=
github.com/fzipp/gocyclo v0.6.0/go.mod h1:rXPyn8fnlpa0R2csP/31uerbiVBugk5whMdlyaLkLoA=
github.com/gabriel-vasile/mimetype v1.4.9 h1:5k+WDwEsD9eTLL8Tz3L0VnmVh9QxGjRmjBvAG7U/oYY=
github.com/gabriel-vasile/mimetype v1.4.9/go.mod h1:WnSQhFKJuBlRyLiKohA/2DtIlPFAbguNaG7QCHcyGok=
github.com/gabriel-vasile/mimetype v1.4.10 h1:zyueNbySn/z8mJZHLt6IPw0KoZsiQNszIpU+bX4+ZK0=
github.com/gabriel-vasile/mimetype v1.4.10/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
github.com/gen2brain/go-fitz v1.24.15 h1:sJNB1MOWkqnzzENPHggFpgxTwW0+S5WF/rM5wUBpJWo=
github.com/gen2brain/go-fitz v1.24.15/go.mod h1:SftkiVbTHqF141DuiLwBBM65zP7ig6AVDQpf2WlHamo=
github.com/getkin/kin-openapi v0.132.0 h1:3ISeLMsQzcb5v26yeJrBcdTCEQTag36ZjaGk7MIRUwk=
github.com/getkin/kin-openapi v0.132.0/go.mod h1:3OlG51PCYNsPByuiMB0t4fjnNlIDnaEDsjiKUV8nL58=
github.com/getkin/kin-openapi v0.133.0 h1:pJdmNohVIJ97r4AUFtEXRXwESr8b0bD721u/Tz6k8PQ=
github.com/getkin/kin-openapi v0.133.0/go.mod h1:boAciF6cXk5FhPqe/NQeBTeenbjqU4LhWBf09ILVvWE=
github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
github.com/ghostiam/protogetter v0.3.15 h1:1KF5sXel0HE48zh1/vn0Loiw25A9ApyseLzQuif1mLY=
@@ -274,16 +286,38 @@ github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vb
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A=
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-openapi/jsonpointer v0.21.2 h1:AqQaNADVwq/VnkCmQg6ogE+M3FOsKTytwges0JdwVuA=
github.com/go-openapi/jsonpointer v0.21.2/go.mod h1:50I1STOfbY1ycR8jGz8DaMeLCdXiI6aDteEdRNNzpdk=
github.com/go-openapi/jsonreference v0.21.0 h1:Rs+Y7hSXT83Jacb7kFyjn4ijOuVGSvOdF2+tg1TRrwQ=
github.com/go-openapi/jsonreference v0.21.0/go.mod h1:LmZmgsrTkVg9LG4EaHeY8cBDslNPMo06cago5JNLkm4=
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-openapi/jsonpointer v0.22.0 h1:TmMhghgNef9YXxTu1tOopo+0BGEytxA+okbry0HjZsM=
github.com/go-openapi/jsonpointer v0.22.0/go.mod h1:xt3jV88UtExdIkkL7NloURjRQjbeUgcxFblMjq2iaiU=
github.com/go-openapi/jsonreference v0.21.1 h1:bSKrcl8819zKiOgxkbVNRUBIr6Wwj9KYrDbMjRs0cDA=
github.com/go-openapi/jsonreference v0.21.1/go.mod h1:PWs8rO4xxTUqKGu+lEvvCxD5k2X7QYkKAepJyCmSTT8=
github.com/go-openapi/spec v0.21.0 h1:LTVzPc3p/RzRnkQqLRndbAzjY0d0BCL72A6j3CdL9ZY=
github.com/go-openapi/spec v0.21.0/go.mod h1:78u6VdPw81XU44qEWGhtr982gJ5BWg2c0I5XwVMotYk=
github.com/go-openapi/swag v0.23.1 h1:lpsStH0n2ittzTnbaSloVZLuB5+fvSY/+hnagBjSNZU=
github.com/go-openapi/swag v0.23.1/go.mod h1:STZs8TbRvEQQKUA+JZNAm3EWlgaOBGpyFDqQnDHMef0=
github.com/go-openapi/swag v0.24.1 h1:DPdYTZKo6AQCRqzwr/kGkxJzHhpKxZ9i/oX0zag+MF8=
github.com/go-openapi/swag v0.24.1/go.mod h1:sm8I3lCPlspsBBwUm1t5oZeWZS0s7m/A+Psg0ooRU0A=
github.com/go-openapi/swag/cmdutils v0.24.0 h1:KlRCffHwXFI6E5MV9n8o8zBRElpY4uK4yWyAMWETo9I=
github.com/go-openapi/swag/cmdutils v0.24.0/go.mod h1:uxib2FAeQMByyHomTlsP8h1TtPd54Msu2ZDU/H5Vuf8=
github.com/go-openapi/swag/conv v0.24.0 h1:ejB9+7yogkWly6pnruRX45D1/6J+ZxRu92YFivx54ik=
github.com/go-openapi/swag/conv v0.24.0/go.mod h1:jbn140mZd7EW2g8a8Y5bwm8/Wy1slLySQQ0ND6DPc2c=
github.com/go-openapi/swag/fileutils v0.24.0 h1:U9pCpqp4RUytnD689Ek/N1d2N/a//XCeqoH508H5oak=
github.com/go-openapi/swag/fileutils v0.24.0/go.mod h1:3SCrCSBHyP1/N+3oErQ1gP+OX1GV2QYFSnrTbzwli90=
github.com/go-openapi/swag/jsonname v0.24.0 h1:2wKS9bgRV/xB8c62Qg16w4AUiIrqqiniJFtZGi3dg5k=
github.com/go-openapi/swag/jsonname v0.24.0/go.mod h1:GXqrPzGJe611P7LG4QB9JKPtUZ7flE4DOVechNaDd7Q=
github.com/go-openapi/swag/jsonutils v0.24.0 h1:F1vE1q4pg1xtO3HTyJYRmEuJ4jmIp2iZ30bzW5XgZts=
github.com/go-openapi/swag/jsonutils v0.24.0/go.mod h1:vBowZtF5Z4DDApIoxcIVfR8v0l9oq5PpYRUuteVu6f0=
github.com/go-openapi/swag/loading v0.24.0 h1:ln/fWTwJp2Zkj5DdaX4JPiddFC5CHQpvaBKycOlceYc=
github.com/go-openapi/swag/loading v0.24.0/go.mod h1:gShCN4woKZYIxPxbfbyHgjXAhO61m88tmjy0lp/LkJk=
github.com/go-openapi/swag/mangling v0.24.0 h1:PGOQpViCOUroIeak/Uj/sjGAq9LADS3mOyjznmHy2pk=
github.com/go-openapi/swag/mangling v0.24.0/go.mod h1:Jm5Go9LHkycsz0wfoaBDkdc4CkpuSnIEf62brzyCbhc=
github.com/go-openapi/swag/netutils v0.24.0 h1:Bz02HRjYv8046Ycg/w80q3g9QCWeIqTvlyOjQPDjD8w=
github.com/go-openapi/swag/netutils v0.24.0/go.mod h1:WRgiHcYTnx+IqfMCtu0hy9oOaPR0HnPbmArSRN1SkZM=
github.com/go-openapi/swag/stringutils v0.24.0 h1:i4Z/Jawf9EvXOLUbT97O0HbPUja18VdBxeadyAqS1FM=
github.com/go-openapi/swag/stringutils v0.24.0/go.mod h1:5nUXB4xA0kw2df5PRipZDslPJgJut+NjL7D25zPZ/4w=
github.com/go-openapi/swag/typeutils v0.24.0 h1:d3szEGzGDf4L2y1gYOSSLeK6h46F+zibnEas2Jm/wIw=
github.com/go-openapi/swag/typeutils v0.24.0/go.mod h1:q8C3Kmk/vh2VhpCLaoR2MVWOGP8y7Jc8l82qCTd1DYI=
github.com/go-openapi/swag/yamlutils v0.24.0 h1:bhw4894A7Iw6ne+639hsBNRHg9iZg/ISrOVr+sJGp4c=
github.com/go-openapi/swag/yamlutils v0.24.0/go.mod h1:DpKv5aYuaGm/sULePoeiG8uwMpZSfReo1HR3Ik0yaG8=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
@@ -316,8 +350,8 @@ github.com/go-toolsmith/strparse v1.1.0 h1:GAioeZUK9TGxnLS+qfdqNbA4z0SSm5zVNtCQi
github.com/go-toolsmith/strparse v1.1.0/go.mod h1:7ksGy58fsaQkGQlY8WVoBFNyEPMGuJin1rfoPS4lBSQ=
github.com/go-toolsmith/typep v1.1.0 h1:fIRYDyF+JywLfqzyhdiHzRop/GQDxxNhLGQ6gFUNHus=
github.com/go-toolsmith/typep v1.1.0/go.mod h1:fVIw+7zjdsMxDA3ITWnH1yOiw1rnTQKCsF/sk2H/qig=
github.com/go-viper/mapstructure/v2 v2.2.1 h1:ZAaOCxANMuZx5RCeg0mBdEZk7DZasvvZIxtHqx8aGss=
github.com/go-viper/mapstructure/v2 v2.2.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=
github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/go-xmlfmt/xmlfmt v1.1.3 h1:t8Ey3Uy7jDSEisW2K3somuMKIpzktkWptA0iFCnRUWY=
github.com/go-xmlfmt/xmlfmt v1.1.3/go.mod h1:aUCEOzzezBEjDBbFBoSiya/gduyIiWYRP6CnSFIV8AM=
github.com/gobuffalo/flect v1.0.3 h1:xeWBM2nui+qnVvNM4S3foBhCAL2XgPU+a7FdpelbTq4=
@@ -335,10 +369,10 @@ github.com/gohugoio/hashstructure v0.5.0 h1:G2fjSBU36RdwEJBWJ+919ERvOVqAg9tfcYp4
github.com/gohugoio/hashstructure v0.5.0/go.mod h1:Ser0TniXuu/eauYmrwM4o64EBvySxNzITEOLlm4igec=
github.com/gohugoio/httpcache v0.7.0 h1:ukPnn04Rgvx48JIinZvZetBfHaWE7I01JR2Q2RrQ3Vs=
github.com/gohugoio/httpcache v0.7.0/go.mod h1:fMlPrdY/vVJhAriLZnrF5QpN3BNAcoBClgAyQd+lGFI=
github.com/gohugoio/hugo v0.147.6 h1:rL4rnus/5qzj4+FoA+JMzsVvFJ2YZdVIH6pbuCB2P84=
github.com/gohugoio/hugo v0.147.6/go.mod h1:Sb2COQPDPYG+tRSpePtzKytiuVDqkBivEhgIew1QbNo=
github.com/gohugoio/hugo-goldmark-extensions/extras v0.3.0 h1:gj49kTR5Z4Hnm0ZaQrgPVazL3DUkppw+x6XhHCmh+Wk=
github.com/gohugoio/hugo-goldmark-extensions/extras v0.3.0/go.mod h1:IMMj7xiUbLt1YNJ6m7AM4cnsX4cFnnfkleO/lBHGzUg=
github.com/gohugoio/hugo v0.149.1 h1:uWOc8Ve4h4e48FyYhBquRoHCJviyxA5yGrFJLT48yio=
github.com/gohugoio/hugo v0.149.1/go.mod h1:HS6BP6e8FGxungP4CHC3zeLDvhBLnTJIjHJZWTZjs7o=
github.com/gohugoio/hugo-goldmark-extensions/extras v0.5.0 h1:dco+7YiOryRoPOMXwwaf+kktZSCtlFtreNdiJbETvYE=
github.com/gohugoio/hugo-goldmark-extensions/extras v0.5.0/go.mod h1:CRrxQTKeM3imw+UoS4EHKyrqB7Zp6sAJiqHit+aMGTE=
github.com/gohugoio/hugo-goldmark-extensions/passthrough v0.3.1 h1:nUzXfRTszLliZuN0JTKeunXTRaiFX6ksaWP0puLLYAY=
github.com/gohugoio/hugo-goldmark-extensions/passthrough v0.3.1/go.mod h1:Wy8ThAA8p2/w1DY05vEzq6EIeI2mzDjvHsu7ULBVwog=
github.com/gohugoio/locales v0.14.0 h1:Q0gpsZwfv7ATHMbcTNepFd59H7GoykzWJIxi113XGDc=
@@ -350,8 +384,8 @@ github.com/golang-jwt/jwt/v4 v4.5.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w
github.com/golang/geo v0.0.0-20190916061304-5b978397cfec/go.mod h1:QZ0nwyI2jOfgRAoBvP+ab5aRr7c9x7lhGEJrKvBwjWI=
github.com/golang/geo v0.0.0-20200319012246-673a6f80352d/go.mod h1:QZ0nwyI2jOfgRAoBvP+ab5aRr7c9x7lhGEJrKvBwjWI=
github.com/golang/geo v0.0.0-20210211234256-740aa86cb551/go.mod h1:QZ0nwyI2jOfgRAoBvP+ab5aRr7c9x7lhGEJrKvBwjWI=
github.com/golang/geo v0.0.0-20250821133510-ecfc33a939ac h1:gBtvd74wZT02fkOyoG651Sx2imv5lKdVvDwpUjKPFnw=
github.com/golang/geo v0.0.0-20250821133510-ecfc33a939ac/go.mod h1:AN0OjM34c3PbjAsX+QNma1nYtJtRxl+s9MZNV7S+efw=
github.com/golang/geo v0.0.0-20250912065020-b504328d3ef3 h1:vLpszxHK60Falbg9wHLAFI5LPqXlxnbvQRGxCJJHvLY=
github.com/golang/geo v0.0.0-20250912065020-b504328d3ef3/go.mod h1:AN0OjM34c3PbjAsX+QNma1nYtJtRxl+s9MZNV7S+efw=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
@@ -389,16 +423,19 @@ github.com/golangci/go-printf-func-name v0.1.0 h1:dVokQP+NMTO7jwO4bwsRwLWeudOVUP
github.com/golangci/go-printf-func-name v0.1.0/go.mod h1:wqhWFH5mUdJQhweRnldEywnR5021wTdZSNgwYceV14s=
github.com/golangci/gofmt v0.0.0-20250106114630-d62b90e6713d h1:viFft9sS/dxoYY0aiOTsLKO2aZQAPT4nlQCsimGcSGE=
github.com/golangci/gofmt v0.0.0-20250106114630-d62b90e6713d/go.mod h1:ivJ9QDg0XucIkmwhzCDsqcnxxlDStoTl89jDMIoNxKY=
github.com/golangci/golangci-lint/v2 v2.1.6 h1:LXqShFfAGM5BDzEOWD2SL1IzJAgUOqES/HRBsfKjI+w=
github.com/golangci/golangci-lint/v2 v2.1.6/go.mod h1:EPj+fgv4TeeBq3TcqaKZb3vkiV5dP4hHHKhXhEhzci8=
github.com/golangci/golangci-lint v1.64.8 h1:y5TdeVidMtBGG32zgSC7ZXTFNHrsJkDnpO4ItB3Am+I=
github.com/golangci/golangci-lint/v2 v2.4.0 h1:qz6O6vr7kVzXJqyvHjHSz5fA3D+PM8v96QU5gxZCNWM=
github.com/golangci/golangci-lint/v2 v2.4.0/go.mod h1:Oq7vuAf6L1iNL34uHDcsIF6Mnc0amOPdsT3/GlpHD+I=
github.com/golangci/golines v0.0.0-20250217134842-442fd0091d95 h1:AkK+w9FZBXlU/xUmBtSJN1+tAI4FIvy5WtnUnY8e4p8=
github.com/golangci/golines v0.0.0-20250217134842-442fd0091d95/go.mod h1:k9mmcyWKSTMcPPvQUCfRWWQ9VHJ1U9Dc0R7kaXAgtnQ=
github.com/golangci/misspell v0.6.0 h1:JCle2HUTNWirNlDIAUO44hUsKhOFqGPoC4LZxlaSXDs=
github.com/golangci/misspell v0.6.0/go.mod h1:keMNyY6R9isGaSAu+4Q8NMBwMPkh15Gtc8UCVoDtAWo=
github.com/golangci/plugin-module-register v0.1.1 h1:TCmesur25LnyJkpsVrupv1Cdzo+2f7zX0H6Jkw1Ol6c=
github.com/golangci/plugin-module-register v0.1.1/go.mod h1:TTpqoB6KkwOJMV8u7+NyXMrkwwESJLOkfl9TxR1DGFc=
github.com/golangci/misspell v0.7.0 h1:4GOHr/T1lTW0hhR4tgaaV1WS/lJ+ncvYCoFKmqJsj0c=
github.com/golangci/misspell v0.7.0/go.mod h1:WZyyI2P3hxPY2UVHs3cS8YcllAeyfquQcKfdeE9AFVg=
github.com/golangci/plugin-module-register v0.1.2 h1:e5WM6PO6NIAEcij3B053CohVp3HIYbzSuP53UAYgOpg=
github.com/golangci/plugin-module-register v0.1.2/go.mod h1:1+QGTsKBvAIvPvoY/os+G5eoqxWn70HYDm2uvUyGuVw=
github.com/golangci/revgrep v0.8.0 h1:EZBctwbVd0aMeRnNUsFogoyayvKHyxlV3CdUA46FX2s=
github.com/golangci/revgrep v0.8.0/go.mod h1:U4R/s9dlXZsg8uJmaR1GrloUr14D7qDl8gi2iPXJH8k=
github.com/golangci/swaggoswag v0.0.0-20250504205917-77f2aca3143e h1:ai0EfmVYE2bRA5htgAG9r7s3tHsfjIhN98WshBTJ9jM=
github.com/golangci/swaggoswag v0.0.0-20250504205917-77f2aca3143e/go.mod h1:Vrn4B5oR9qRwM+f54koyeH3yzphlecwERs0el27Fr/s=
github.com/golangci/unconvert v0.0.0-20250410112200-a129a6e6413e h1:gD6P7NEo7Eqtt0ssnqSJNNndxe69DOQ24A5h7+i3KpM=
github.com/golangci/unconvert v0.0.0-20250410112200-a129a6e6413e/go.mod h1:h+wZwLjUTJnm/P2rwlbJdRPZXOzaT36/FwnPnY2inzc=
github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
@@ -413,7 +450,6 @@ github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
@@ -427,13 +463,15 @@ github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hf
github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
github.com/google/pprof v0.0.0-20241210010833-40e02aabc2ad h1:a6HEuzUHeKH6hwfN/ZoQgRgVIWFJljSWa/zetS2WTvg=
github.com/google/pprof v0.0.0-20241210010833-40e02aabc2ad/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144=
github.com/google/pprof v0.0.0-20250607225305-033d6d78b36a h1://KbezygeMJZCSHH+HgUZiTeSoiuFspbMg1ge+eFj18=
github.com/google/pprof v0.0.0-20250607225305-033d6d78b36a/go.mod h1:5hDyRhoBCxViHszMt12TnOpEI4VVi+U8Gm9iphldiMA=
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg=
github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk=
github.com/gordonklaus/ineffassign v0.1.0 h1:y2Gd/9I7MdY1oEIt+n+rowjBNDcLQq3RsH5hwJd0f9s=
github.com/gordonklaus/ineffassign v0.1.0/go.mod h1:Qcp2HIAYhR7mNUVSIxZww3Guk4it82ghYcEXIAk+QT0=
github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8=
github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0=
github.com/gostaticanalysis/analysisutil v0.7.1 h1:ZMCjoue3DtDWQ5WyU16YbjbQEQ3VuzwxALrpYd+HeKk=
github.com/gostaticanalysis/analysisutil v0.7.1/go.mod h1:v21E3hY37WKMGSnbsw2S/ojApNWb6C1//mXO48CXbVc=
github.com/gostaticanalysis/comment v1.4.1/go.mod h1:ih6ZxzTHLdadaiSnF5WY3dxUoXfXAlTaRzuaNDlSado=
@@ -475,12 +513,12 @@ github.com/jdkato/prose v1.2.1 h1:Fp3UnJmLVISmlc57BgKUzdjr0lOtjqTZicL3PaYy6cU=
github.com/jdkato/prose v1.2.1/go.mod h1:AiRHgVagnEx2JbQRQowVBKjG0bcs/vtkGCH1dYAL1rA=
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
github.com/jessevdk/go-flags v1.5.0/go.mod h1:Fw0T6WPc1dYxT4mKEZRfG5kJhaTDP9pj1c2EWnYs/m4=
github.com/jgautheron/goconst v1.8.1 h1:PPqCYp3K/xlOj5JmIe6O1Mj6r1DbkdbLtR3AJuZo414=
github.com/jgautheron/goconst v1.8.1/go.mod h1:A0oxgBCHy55NQn6sYpO7UdnA9p+h7cPtoOZUmvNIako=
github.com/jgautheron/goconst v1.8.2 h1:y0XF7X8CikZ93fSNT6WBTb/NElBu9IjaY7CCYQrCMX4=
github.com/jgautheron/goconst v1.8.2/go.mod h1:A0oxgBCHy55NQn6sYpO7UdnA9p+h7cPtoOZUmvNIako=
github.com/jingyugao/rowserrcheck v1.1.1 h1:zibz55j/MJtLsjP1OF4bSdgXxwL1b+Vn7Tjzq7gFzUs=
github.com/jingyugao/rowserrcheck v1.1.1/go.mod h1:4yvlZSDb3IyDTUZJUmpZfm2Hwok+Dtp+nu2qOq+er9c=
github.com/jjti/go-spancheck v0.6.4 h1:Tl7gQpYf4/TMU7AT84MN83/6PutY21Nb9fuQjFTpRRc=
github.com/jjti/go-spancheck v0.6.4/go.mod h1:yAEYdKJ2lRkDA8g7X+oKUHXOWVAXSBJRv04OhF+QUjk=
github.com/jjti/go-spancheck v0.6.5 h1:lmi7pKxa37oKYIMScialXUK6hP3iY5F1gu+mLBPgYB8=
github.com/jjti/go-spancheck v0.6.5/go.mod h1:aEogkeatBrbYsyW6y5TgDfihCulDYciL1B7rG2vSsrU=
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4=
@@ -523,16 +561,16 @@ github.com/kyokomi/emoji/v2 v2.2.13 h1:GhTfQa67venUUvmleTNFnb+bi7S3aocF7ZCXU9fSO
github.com/kyokomi/emoji/v2 v2.2.13/go.mod h1:JUcn42DTdsXJo1SWanHh4HKDEyPaR5CqkmoirZZP9qE=
github.com/lasiar/canonicalheader v1.1.2 h1:vZ5uqwvDbyJCnMhmFYimgMZnJMjwljN5VGY0VKbMXb4=
github.com/lasiar/canonicalheader v1.1.2/go.mod h1:qJCeLFS0G/QlLQ506T+Fk/fWMa2VmBUiEI2cuMK4djI=
github.com/ldez/exptostd v0.4.3 h1:Ag1aGiq2epGePuRJhez2mzOpZ8sI9Gimcb4Sb3+pk9Y=
github.com/ldez/exptostd v0.4.3/go.mod h1:iZBRYaUmcW5jwCR3KROEZ1KivQQp6PHXbDPk9hqJKCQ=
github.com/ldez/gomoddirectives v0.6.1 h1:Z+PxGAY+217f/bSGjNZr/b2KTXcyYLgiWI6geMBN2Qc=
github.com/ldez/gomoddirectives v0.6.1/go.mod h1:cVBiu3AHR9V31em9u2kwfMKD43ayN5/XDgr+cdaFaKs=
github.com/ldez/grignotin v0.9.0 h1:MgOEmjZIVNn6p5wPaGp/0OKWyvq42KnzAt/DAb8O4Ow=
github.com/ldez/grignotin v0.9.0/go.mod h1:uaVTr0SoZ1KBii33c47O1M8Jp3OP3YDwhZCmzT9GHEk=
github.com/ldez/exptostd v0.4.4 h1:58AtQjnLcT/tI5W/1KU7xE/O7zW9RAWB6c/ScQAnfus=
github.com/ldez/exptostd v0.4.4/go.mod h1:QfdzPw6oHjFVdNV7ILoPu5sw3OZ3OG1JS0I5JN3J4Js=
github.com/ldez/gomoddirectives v0.7.0 h1:EOx8Dd56BZYSez11LVgdj025lKwlP0/E5OLSl9HDwsY=
github.com/ldez/gomoddirectives v0.7.0/go.mod h1:wR4v8MN9J8kcwvrkzrx6sC9xe9Cp68gWYCsda5xvyGc=
github.com/ldez/grignotin v0.10.0 h1:NQPeh1E/Eza4F0exCeC1WkpnLvgUcQDT8MQ1vOLML0E=
github.com/ldez/grignotin v0.10.0/go.mod h1:oR4iCKUP9fwoeO6vCQeD7M5SMxCT6xdVas4vg0h1LaI=
github.com/ldez/tagliatelle v0.7.1 h1:bTgKjjc2sQcsgPiT902+aadvMjCeMHrY7ly2XKFORIk=
github.com/ldez/tagliatelle v0.7.1/go.mod h1:3zjxUpsNB2aEZScWiZTHrAXOl1x25t3cRmzfK1mlo2I=
github.com/ldez/usetesting v0.4.3 h1:pJpN0x3fMupdTf/IapYjnkhiY1nSTN+pox1/GyBRw3k=
github.com/ldez/usetesting v0.4.3/go.mod h1:eEs46T3PpQ+9RgN9VjpY6qWdiw2/QmfiDeWmdZdrjIQ=
github.com/ldez/usetesting v0.5.0 h1:3/QtzZObBKLy1F4F8jLuKJiKBjjVFi1IavpoWbmqLwc=
github.com/ldez/usetesting v0.5.0/go.mod h1:Spnb4Qppf8JTuRgblLrEWb7IE6rDmUpGvxY3iRrzvDQ=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/leonklingele/grouper v1.1.2 h1:o1ARBDLOmmasUaNDesWqWCIFH3u7hoFlM84YrjT3mIY=
@@ -547,8 +585,10 @@ github.com/mailru/easyjson v0.9.0 h1:PrnmzHw7262yW8sTBwxi1PdJA3Iw/EKBa8psRf7d9a4
github.com/mailru/easyjson v0.9.0/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU=
github.com/makeworld-the-better-one/dither/v2 v2.4.0 h1:Az/dYXiTcwcRSe59Hzw4RI1rSnAZns+1msaCXetrMFE=
github.com/makeworld-the-better-one/dither/v2 v2.4.0/go.mod h1:VBtN8DXO7SNtyGmLiGA7IsFeKrBkQPze1/iAeM95arc=
github.com/manuelarte/funcorder v0.2.1 h1:7QJsw3qhljoZ5rH0xapIvjw31EcQeFbF31/7kQ/xS34=
github.com/manuelarte/funcorder v0.2.1/go.mod h1:BQQ0yW57+PF9ZpjpeJDKOffEsQbxDFKW8F8zSMe/Zd0=
github.com/manuelarte/embeddedstructfieldcheck v0.3.0 h1:VhGqK8gANDvFYDxQkjPbv7/gDJtsGU9k6qj/hC2hgso=
github.com/manuelarte/embeddedstructfieldcheck v0.3.0/go.mod h1:LSo/IQpPfx1dXMcX4ibZCYA7Yy6ayZHIaOGM70+1Wy8=
github.com/manuelarte/funcorder v0.5.0 h1:llMuHXXbg7tD0i/LNw8vGnkDTHFpTnWqKPI85Rknc+8=
github.com/manuelarte/funcorder v0.5.0/go.mod h1:Yt3CiUQthSBMBxjShjdXMexmzpP8YGvGLjrxJNkO2hA=
github.com/maratori/testableexamples v1.0.0 h1:dU5alXRrD8WKSjOUnmJZuzdxWOEQ57+7s93SLMxb2vI=
github.com/maratori/testableexamples v1.0.0/go.mod h1:4rhjL1n20TUTT4vdh3RDqSizKLyXp7K2u6HgraZCGzE=
github.com/maratori/testpackage v1.1.1 h1:S58XVV5AD7HADMmD0fNnziNHqKvSdDuEKdPD1rNTU04=
@@ -563,13 +603,14 @@ github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHP
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/mgechev/revive v1.9.0 h1:8LaA62XIKrb8lM6VsBSQ92slt/o92z5+hTw3CmrvSrM=
github.com/mgechev/revive v1.9.0/go.mod h1:LAPq3+MgOf7GcL5PlWIkHb0PT7XH4NuC2LdWymhb9Mo=
github.com/mgechev/revive v1.11.0 h1:b/gLLpBE427o+Xmd8G58gSA+KtBwxWinH/A565Awh0w=
github.com/mgechev/revive v1.11.0/go.mod h1:tI0oLF/2uj+InHCBLrrqfTKfjtFTBCFFfG05auyzgdw=
github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwXFM08ygZfk=
github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA=
github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/mitchellh/mapstructure v1.5.1-0.20231216201459-8508981c8b6c h1:cqn374mizHuIWj+OSJCajGr/phAmuMug9qIX3l9CflE=
@@ -591,24 +632,28 @@ github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRW
github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/nakabonne/nestif v0.3.1 h1:wm28nZjhQY5HyYPx+weN3Q65k6ilSBxDb8v5S81B81U=
github.com/nakabonne/nestif v0.3.1/go.mod h1:9EtoZochLn5iUprVDmDjqGKPofoUEBL8U4Ngq6aY7OE=
github.com/niklasfasching/go-org v1.7.0 h1:vyMdcMWWTe/XmANk19F4k8XGBYg0GQ/gJGMimOjGMek=
github.com/niklasfasching/go-org v1.7.0/go.mod h1:WuVm4d45oePiE0eX25GqTDQIt/qPW1T9DGkRscqLW5o=
github.com/niklasfasching/go-org v1.9.1 h1:/3s4uTPOF06pImGa2Yvlp24yKXZoTYM+nsIlMzfpg/0=
github.com/niklasfasching/go-org v1.9.1/go.mod h1:ZAGFFkWvUQcpazmi/8nHqwvARpr1xpb+Es67oUGX/48=
github.com/nishanths/exhaustive v0.12.0 h1:vIY9sALmw6T/yxiASewa4TQcFsVYZQQRUQJhKRf3Swg=
github.com/nishanths/exhaustive v0.12.0/go.mod h1:mEZ95wPIZW+x8kC4TgC+9YCUgiST7ecevsVDTgc2obs=
github.com/nishanths/predeclared v0.2.2 h1:V2EPdZPliZymNAn79T8RkNApBjMmVKh5XRpLm/w98Vk=
github.com/nishanths/predeclared v0.2.2/go.mod h1:RROzoN6TnGQupbC+lqggsOlcgysk3LMK/HI84Mp280c=
github.com/nunnatsa/ginkgolinter v0.19.1 h1:mjwbOlDQxZi9Cal+KfbEJTCz327OLNfwNvoZ70NJ+c4=
github.com/nunnatsa/ginkgolinter v0.19.1/go.mod h1:jkQ3naZDmxaZMXPWaS9rblH+i+GWXQCaS/JFIWcOH2s=
github.com/nunnatsa/ginkgolinter v0.20.0 h1:OmWLkAFO2HUTYcU6mprnKud1Ey5pVdiVNYGO5HVicx8=
github.com/nunnatsa/ginkgolinter v0.20.0/go.mod h1:dCIuFlTPfQerXgGUju3VygfAFPdC5aE1mdacCDKDJcQ=
github.com/oasdiff/yaml v0.0.0-20250309154309-f31be36b4037 h1:G7ERwszslrBzRxj//JalHPu/3yz+De2J+4aLtSRlHiY=
github.com/oasdiff/yaml v0.0.0-20250309154309-f31be36b4037/go.mod h1:2bpvgLBZEtENV5scfDFEtB/5+1M4hkQhDQrccEJ/qGw=
github.com/oasdiff/yaml3 v0.0.0-20250309153720-d2182401db90 h1:bQx3WeLcUWy+RletIKwUIt4x3t8n2SxavmoclizMb8c=
github.com/oasdiff/yaml3 v0.0.0-20250309153720-d2182401db90/go.mod h1:y5+oSEHCPT/DGrS++Wc/479ERge0zTFxaF8PbGKcg2o=
github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=
github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=
github.com/onsi/ginkgo/v2 v2.23.3 h1:edHxnszytJ4lD9D5Jjc4tiDkPBZ3siDeJJkUZJJVkp0=
github.com/onsi/ginkgo/v2 v2.23.3/go.mod h1:zXTP6xIp3U8aVuXN8ENK9IXRaTjFnpVB9mGmaSRvxnM=
github.com/onsi/gomega v1.36.3 h1:hID7cr8t3Wp26+cYnfcjR6HpJ00fdogN6dqZ1t6IylU=
github.com/onsi/gomega v1.36.3/go.mod h1:8D9+Txp43QWKhM24yyOBEdpkzN8FvJyAwecBgsU4KU0=
github.com/olekukonko/errors v1.1.0 h1:RNuGIh15QdDenh+hNvKrJkmxxjV4hcS50Db478Ou5sM=
github.com/olekukonko/errors v1.1.0/go.mod h1:ppzxA5jBKcO1vIpCXQ9ZqgDh8iwODz6OXIGKU8r5m4Y=
github.com/olekukonko/ll v0.0.9 h1:Y+1YqDfVkqMWuEQMclsF9HUR5+a82+dxJuL1HHSRpxI=
github.com/olekukonko/ll v0.0.9/go.mod h1:En+sEW0JNETl26+K8eZ6/W4UQ7CYSrrgg/EdIYT2H8g=
github.com/olekukonko/tablewriter v1.0.9 h1:XGwRsYLC2bY7bNd93Dk51bcPZksWZmLYuaTHR0FqfL8=
github.com/olekukonko/tablewriter v1.0.9/go.mod h1:5c+EBPeSqvXnLLgkm9isDdzR3wjfBkHR9Nhfp3NWrzo=
github.com/onsi/ginkgo/v2 v2.23.4 h1:ktYTpKJAVZnDT4VjxSbiBenUjmlL/5QkBEocaWXiQus=
github.com/onsi/ginkgo/v2 v2.23.4/go.mod h1:Bt66ApGPBFzHyR+JO10Zbt0Gsp4uWxu5mIOTusL46e8=
github.com/onsi/gomega v1.37.0 h1:CdEG8g0S133B4OswTDC/5XPSzE1OeP29QOioj2PID2Y=
github.com/onsi/gomega v1.37.0/go.mod h1:8D9+Txp43QWKhM24yyOBEdpkzN8FvJyAwecBgsU4KU0=
github.com/otiai10/copy v1.2.0/go.mod h1:rrF5dJ5F0t/EWSYODDu4j9/vEeYHMkc8jt0zJChqQWw=
github.com/otiai10/copy v1.14.0 h1:dCI/t1iTdYGtkvCuBG2BgR6KZa83PTclw4U5n2wAllU=
github.com/otiai10/copy v1.14.0/go.mod h1:ECfuL02W+/FkTWZWgQqXPWZgW9oeKCSQ5qVfSc4qc4w=
@@ -685,14 +730,14 @@ github.com/ryanrolds/sqlclosecheck v0.5.1 h1:dibWW826u0P8jNLsLN+En7+RqWWTYrjCB9f
github.com/ryanrolds/sqlclosecheck v0.5.1/go.mod h1:2g3dUjoS6AL4huFdv6wn55WpLIDjY7ZgUR4J8HOO/XQ=
github.com/sanposhiho/wastedassign/v2 v2.1.0 h1:crurBF7fJKIORrV85u9UUpePDYGWnwvv3+A96WvwXT0=
github.com/sanposhiho/wastedassign/v2 v2.1.0/go.mod h1:+oSmSC+9bQ+VUAxA66nBb0Z7N8CK7mscKTDYC6aIek4=
github.com/santhosh-tekuri/jsonschema/v6 v6.0.1 h1:PKK9DyHxif4LZo+uQSgXNqs0jj5+xZwwfKHgph2lxBw=
github.com/santhosh-tekuri/jsonschema/v6 v6.0.1/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU=
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 h1:KRzFb2m7YtdldCEkzs6KqmJw4nqEVZGK7IN2kJkjTuQ=
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU=
github.com/sashamelentyev/interfacebloat v1.1.0 h1:xdRdJp0irL086OyW1H/RTZTr1h/tMEOsumirXcOJqAw=
github.com/sashamelentyev/interfacebloat v1.1.0/go.mod h1:+Y9yU5YdTkrNvoX0xHc84dxiN1iBi9+G8zZIhPVoNjQ=
github.com/sashamelentyev/usestdlibvars v1.28.0 h1:jZnudE2zKCtYlGzLVreNp5pmCdOxXUzwsMDBkR21cyQ=
github.com/sashamelentyev/usestdlibvars v1.28.0/go.mod h1:9nl0jgOfHKWNFS43Ojw0i7aRoS4j6EBye3YBhmAIRF8=
github.com/securego/gosec/v2 v2.22.3 h1:mRrCNmRF2NgZp4RJ8oJ6yPJ7G4x6OCiAXHd8x4trLRc=
github.com/securego/gosec/v2 v2.22.3/go.mod h1:42M9Xs0v1WseinaB/BmNGO8AVqG8vRfhC2686ACY48k=
github.com/sashamelentyev/usestdlibvars v1.29.0 h1:8J0MoRrw4/NAXtjQqTHrbW9NN+3iMf7Knkq057v4XOQ=
github.com/sashamelentyev/usestdlibvars v1.29.0/go.mod h1:8PpnjHMk5VdeWlVb4wCdrB8PNbLqZ3wBZTZWkrpZZL8=
github.com/securego/gosec/v2 v2.22.7 h1:8/9P+oTYI4yIpAzccQKVsg1/90Po+JzGtAhqoHImDeM=
github.com/securego/gosec/v2 v2.22.7/go.mod h1:510TFNDMrIPytokyHQAVLvPeDr41Yihn2ak8P+XQfNE=
github.com/sergi/go-diff v1.2.0 h1:XU+rvMAioB0UC3q1MFrIQy4Vo5/4VsRDQQXHsEya6xQ=
github.com/sergi/go-diff v1.2.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM=
github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk=
@@ -705,21 +750,22 @@ github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/sivchari/containedctx v1.0.3 h1:x+etemjbsh2fB5ewm5FeLNi5bUjK0V8n0RB+Wwfd0XE=
github.com/sivchari/containedctx v1.0.3/go.mod h1:c1RDvCbnJLtH4lLcYD/GqwiBSSf4F5Qk0xld2rBqzJ4=
github.com/sonatard/noctx v0.1.0 h1:JjqOc2WN16ISWAjAk8M5ej0RfExEXtkEyExl2hLW+OM=
github.com/sonatard/noctx v0.1.0/go.mod h1:0RvBxqY8D4j9cTTTWE8ylt2vqj2EPI8fHmrxHdsaZ2c=
github.com/sonatard/noctx v0.4.0 h1:7MC/5Gg4SQ4lhLYR6mvOP6mQVSxCrdyiExo7atBs27o=
github.com/sonatard/noctx v0.4.0/go.mod h1:64XdbzFb18XL4LporKXp8poqZtPKbCrqQ402CV+kJas=
github.com/sourcegraph/go-diff v0.7.0 h1:9uLlrd5T46OXs5qpp8L/MTltk0zikUGi0sNNyCpA8G0=
github.com/sourcegraph/go-diff v0.7.0/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs=
github.com/spf13/afero v1.14.0 h1:9tH6MapGnn/j0eb0yIXiLjERO8RB6xIVZRDCX7PtqWA=
github.com/spf13/afero v1.14.0/go.mod h1:acJQ8t0ohCGuMN3O+Pv0V0hgMxNYDlvdk+VTfyZmbYo=
github.com/spf13/cast v1.8.0 h1:gEN9K4b8Xws4EX0+a0reLmhq8moKn7ntRlQYgjPeCDk=
github.com/spf13/cast v1.8.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=
github.com/spf13/cast v1.9.2 h1:SsGfm7M8QOFtEzumm7UZrZdLLquNdzFYfIbEXntcFbE=
github.com/spf13/cast v1.9.2/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo=
github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0=
github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk=
github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o=
github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/pflag v1.0.7 h1:vN6T9TfwStFPFM5XzjsvmzZkLuaLX+HS+0SeFLRgU6M=
github.com/spf13/pflag v1.0.7/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.12.0 h1:CZ7eSOd3kZoaYDLbXnmzgQI5RlciuXBMA+18HwHRfZQ=
github.com/spf13/viper v1.12.0/go.mod h1:b6COn30jlNxbm/V2IqWiNWkJ+vZNiMNksliPCiuKtSI=
github.com/ssgreg/nlreturn/v2 v2.2.1 h1:X4XDI7jstt3ySqGU86YGAURbxw3oTDPK9sPEi6YEwQ0=
@@ -728,20 +774,14 @@ github.com/stbenjam/no-sprintf-host-port v0.2.0 h1:i8pxvGrt1+4G0czLr/WnmyH7zbZ8B
github.com/stbenjam/no-sprintf-host-port v0.2.0/go.mod h1:eL0bQ9PasS0hsyTyfTjjG+E80QIyPnBVQbYZyv20Jfk=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/subosito/gotenv v1.4.1 h1:jyEFiXpy21Wm81FBN71l9VoMMV8H8jG+qIK3GCpY6Qs=
github.com/subosito/gotenv v1.4.1/go.mod h1:ayKnFf/c6rvx/2iiLrJUk1e6plDbT3edrFNGqEflhK0=
github.com/swaggo/files v1.0.1 h1:J1bVJ4XHZNq0I46UU90611i9/YzdrF7x92oX1ig5IdE=
@@ -752,10 +792,10 @@ github.com/swaggo/swag v1.16.6 h1:qBNcx53ZaX+M5dxVyTrgQ0PJ/ACK+NzhwcbieTt+9yI=
github.com/swaggo/swag v1.16.6/go.mod h1:ngP2etMK5a0P3QBizic5MEwpRmluJZPHjXcMoj4Xesg=
github.com/tdakkota/asciicheck v0.4.1 h1:bm0tbcmi0jezRA2b5kg4ozmMuGAFotKI3RZfrhfovg8=
github.com/tdakkota/asciicheck v0.4.1/go.mod h1:0k7M3rCfRXb0Z6bwgvkEIMleKH3kXNz9UqJ9Xuqopr8=
github.com/tdewolff/minify/v2 v2.23.5 h1:/P548KcpTkIOUvNg22zN83/GiaYSOIrbqtoue4I7kYM=
github.com/tdewolff/minify/v2 v2.23.5/go.mod h1:2RI9tiIrzJU1Z5EasXEPaI1MqobRyxKHOOgrRkq5oEw=
github.com/tdewolff/parse/v2 v2.8.1 h1:J5GSHru6o3jF1uLlEKVXkDxxcVx6yzOlIVIotK4w2po=
github.com/tdewolff/parse/v2 v2.8.1/go.mod h1:Hwlni2tiVNKyzR1o6nUs4FOF07URA+JLBLd6dlIXYqo=
github.com/tdewolff/minify/v2 v2.24.2 h1:vnY3nTulEAbCAAlxTxPPDkzG24rsq31SOzp63yT+7mo=
github.com/tdewolff/minify/v2 v2.24.2/go.mod h1:1JrCtoZXaDbqioQZfk3Jdmr0GPJKiU7c1Apmb+7tCeE=
github.com/tdewolff/parse/v2 v2.8.3 h1:5VbvtJ83cfb289A1HzRA9sf02iT8YyUwN84ezjkdY1I=
github.com/tdewolff/parse/v2 v2.8.3/go.mod h1:Hwlni2tiVNKyzR1o6nUs4FOF07URA+JLBLd6dlIXYqo=
github.com/tdewolff/test v1.0.11 h1:FdLbwQVHxqG16SlkGveC0JVyrJN62COWTRyUFzfbtBE=
github.com/tdewolff/test v1.0.11/go.mod h1:XPuWBzvdUzhCuxWO1ojpXsyzsA5bFoS3tO/Q3kFuTG8=
github.com/tenntenn/modver v1.0.1 h1:2klLppGhDgzJrScMpkj9Ujy3rXPUspSjAcev9tSEBgA=
@@ -782,10 +822,12 @@ github.com/urfave/cli/v2 v2.3.0 h1:qph92Y649prgesehzOrQjdWyxFOp/QVM+6imKHad91M=
github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI=
github.com/uudashr/gocognit v1.2.0 h1:3BU9aMr1xbhPlvJLSydKwdLN3tEUUrzPSSM8S4hDYRA=
github.com/uudashr/gocognit v1.2.0/go.mod h1:k/DdKPI6XBZO1q7HgoV2juESI2/Ofj9AcHPZhBBdrTU=
github.com/uudashr/iface v1.3.1 h1:bA51vmVx1UIhiIsQFSNq6GZ6VPTk3WNMZgRiCe9R29U=
github.com/uudashr/iface v1.3.1/go.mod h1:4QvspiRd3JLPAEXBQ9AiZpLbJlrWWgRChOKDJEuQTdg=
github.com/uudashr/iface v1.4.1 h1:J16Xl1wyNX9ofhpHmQ9h9gk5rnv2A6lX/2+APLTo0zU=
github.com/uudashr/iface v1.4.1/go.mod h1:pbeBPlbuU2qkNDn0mmfrxP2X+wjPMIQAy+r1MBXSXtg=
github.com/vmihailenco/msgpack v4.0.4+incompatible h1:dSLoQfGFAo3F6OoNhwUmLwVgaUXK79GlxNBwueZn0xI=
github.com/vmihailenco/msgpack v4.0.4+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk=
github.com/woodsbury/decimal128 v1.3.0 h1:8pffMNWIlC0O5vbyHWFZAt5yWvWcrHA+3ovIIjVWss0=
github.com/woodsbury/decimal128 v1.3.0/go.mod h1:C5UTmyTjW3JftjUFzOVhC20BEQa2a4ZKOB5I6Zjb+ds=
github.com/xen0n/gosmopolitan v1.3.0 h1:zAZI1zefvo7gcpbCOrPSHJZJYA9ZgLfJqtKzZ5pHqQM=
github.com/xen0n/gosmopolitan v1.3.0/go.mod h1:rckfr5T6o4lBtM1ga7mLGKZmLxswUoH1zxHgNXOsEt4=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
@@ -803,8 +845,8 @@ github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9dec
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
github.com/yuin/goldmark v1.7.11 h1:ZCxLyDMtz0nT2HFfsYG8WZ47Trip2+JyLysKcMYE5bo=
github.com/yuin/goldmark v1.7.11/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
github.com/yuin/goldmark v1.7.13 h1:GPddIs617DnBLFFVJFgpo1aBfe/4xcvMc3SB5t/D0pA=
github.com/yuin/goldmark v1.7.13/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
github.com/yuin/goldmark-emoji v1.0.6 h1:QWfF2FYaXwL74tfGOW5izeiZepUDroDJfWubQI9HTHs=
github.com/yuin/goldmark-emoji v1.0.6/go.mod h1:ukxJDKFpdFb5x0a5HqbdlcKtebh086iJpI31LTKmWuA=
gitlab.com/bosi/decorder v0.4.2 h1:qbQaV3zgwnBZ4zPMhGLW4KZe7A7NwxEhJx39R3shffo=
@@ -813,8 +855,10 @@ go-simpler.org/assert v0.9.0 h1:PfpmcSvL7yAnWyChSjOz6Sp6m9j5lyK8Ok9pEL31YkQ=
go-simpler.org/assert v0.9.0/go.mod h1:74Eqh5eI6vCK6Y5l3PI8ZYFXG4Sa+tkr70OIPJAUr28=
go-simpler.org/musttag v0.13.1 h1:lw2sJyu7S1X8lc8zWUAdH42y+afdcCnHhWpnkWvd6vU=
go-simpler.org/musttag v0.13.1/go.mod h1:8r450ehpMLQgvpb6sg+hV5Ur47eH6olp/3yEanfG97k=
go-simpler.org/sloglint v0.11.0 h1:JlR1X4jkbeaffiyjLtymeqmGDKBDO1ikC6rjiuFAOco=
go-simpler.org/sloglint v0.11.0/go.mod h1:CFDO8R1i77dlciGfPEPvYke2ZMx4eyGiEIWkyeW2Pvw=
go-simpler.org/sloglint v0.11.1 h1:xRbPepLT/MHPTCA6TS/wNfZrDzkGvCCqUv4Bdwc3H7s=
go-simpler.org/sloglint v0.11.1/go.mod h1:2PowwiCOK8mjiF+0KGifVOT8ZsCNiFzvfyJeJOIt8MQ=
go.augendre.info/arangolint v0.2.0 h1:2NP/XudpPmfBhQKX4rMk+zDYIj//qbt4hfZmSSTcpj8=
go.augendre.info/arangolint v0.2.0/go.mod h1:Vx4KSJwu48tkE+8uxuf0cbBnAPgnt8O1KWiT7bljq7w=
go.augendre.info/fatcontext v0.8.0 h1:2dfk6CQbDGeu1YocF59Za5Pia7ULeAM6friJ3LP7lmk=
go.augendre.info/fatcontext v0.8.0/go.mod h1:oVJfMgwngMsHO+KB2MdgzcO+RvtNdiCEOlWvSFtax/s=
go.etcd.io/bbolt v1.3.4/go.mod h1:G5EMThwa9y8QZGBClrRx5EY+Yw9kAhnjy3bSjsnlVTQ=
@@ -825,16 +869,14 @@ go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8=
go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw=
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/automaxprocs v1.6.0 h1:O3y2/QNTOdbF+e/dpXNNW7Rx2hZ4sTIPyybbxyNqTUs=
go.uber.org/automaxprocs v1.6.0/go.mod h1:ifeIMSnPZuznNm6jmdzmU3/bfk01Fe2fotchwEFJ8r8=
go.uber.org/goleak v1.1.11 h1:wy28qYRKZgnJTxGxvye5/wgWr1EKjmUDGYox5mGlRlI=
go.uber.org/goleak v1.1.11/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ=
go.uber.org/multierr v1.6.0 h1:y6IPFStTAIT5Ytl7/XYmHvzXQ7S3g/IeZW9hyZ5thw4=
go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU=
go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60=
go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ=
go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
@@ -844,8 +886,8 @@ golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPh
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4=
golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc=
golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI=
golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
@@ -856,16 +898,16 @@ golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u0
golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4=
golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM=
golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU=
golang.org/x/exp v0.0.0-20250531010427-b6e5de432a8b h1:QoALfVG9rhQ/M7vYDScfPdWjGL9dlsVVM5VGh7aKoAA=
golang.org/x/exp v0.0.0-20250531010427-b6e5de432a8b/go.mod h1:U6Lno4MTRCDY+Ba7aCcauB9T60gsv5s4ralQzP72ZoQ=
golang.org/x/exp v0.0.0-20250819193227-8b4c13bb791b h1:DXr+pvt3nC887026GRP39Ej11UATqWDmWuS99x26cD0=
golang.org/x/exp v0.0.0-20250819193227-8b4c13bb791b/go.mod h1:4QTo5u+SEIbbKW1RacMZq1YEfOBqeXa19JeshGi+zc4=
golang.org/x/exp/typeparams v0.0.0-20220428152302-39d4317da171/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk=
golang.org/x/exp/typeparams v0.0.0-20230203172020-98cc5a0785f9/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk=
golang.org/x/exp/typeparams v0.0.0-20250210185358-939b2ce775ac h1:TSSpLIG4v+p0rPv1pNOQtl1I8knsO4S9trOxNMOLVP4=
golang.org/x/exp/typeparams v0.0.0-20250210185358-939b2ce775ac/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk=
golang.org/x/exp/typeparams v0.0.0-20250620022241-b7579e27df2b h1:KdrhdYPDUvJTvrDK9gdjfFd6JTk8vA1WJoldYSi0kHo=
golang.org/x/exp/typeparams v0.0.0-20250620022241-b7579e27df2b/go.mod h1:LKZHyeOpPuZcMgxeHjJp4p5yvxrCX1xDvH10zYHhjjQ=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.30.0 h1:jD5RhkmVAnjqaCUXfbGBrn3lpxbknfN9w2UhHHU+5B4=
golang.org/x/image v0.30.0/go.mod h1:SAEUTxCCMWSrJcCy/4HwavEsfZZJlYxeHLc6tTiAe/c=
golang.org/x/image v0.31.0 h1:mLChjE2MV6g1S7oqbXC0/UcKijjm5fnJLUYKIYrLESA=
golang.org/x/image v0.31.0/go.mod h1:R9ec5Lcp96v9FTF+ajwaH3uGxPH4fKfHHAVbUILxghA=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
@@ -888,13 +930,11 @@ golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.9.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.13.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/mod v0.27.0 h1:kb+q2PyFnEADO2IEF935ehFUXlWiNjJWtRNgBLSfbxQ=
golang.org/x/mod v0.27.0/go.mod h1:rWI627Fq0DEoudcK+MBkNkCe0EetEaDSwJJkCcjpazc=
golang.org/x/mod v0.28.0 h1:gQBtGhjxykdjY9YhZpSlZIsbnaE2+PgjfLWUQTnoZ1U=
golang.org/x/mod v0.28.0/go.mod h1:yfB/L0NOf/kmEbXjzCPOx1iK1fRutOydrCMsqRhEBxI=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
@@ -932,23 +972,21 @@ golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qx
golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.0.0-20221002022538-bcab6841153b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk=
golang.org/x/net v0.2.0/go.mod h1:KqCZLdyyvdV855qA2rE3GC2aiw5xGR5TEjj8smXukLY=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
golang.org/x/net v0.16.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=
golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE=
golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg=
golang.org/x/net v0.44.0 h1:evd8IRDyfNBMBTTY5XRF1vaZlD+EmWx6x8PkhR04H/I=
golang.org/x/net v0.44.0/go.mod h1:ECOoLqd5U3Lhyeyo/QDCEVQ4sNgYsqvCZ722XogGieY=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
golang.org/x/oauth2 v0.31.0 h1:8Fq0yVZLh4j4YA47vHKFTa9Ew5XIrCP8LC6UeNZnLxo=
golang.org/x/oauth2 v0.31.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -964,8 +1002,8 @@ golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJ
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
golang.org/x/sync v0.4.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
@@ -1014,19 +1052,16 @@ golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220928140112-f11e5e49a4ec/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k=
golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U=
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U=
@@ -1037,18 +1072,16 @@ golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE=
golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
golang.org/x/time v0.13.0 h1:eUlYslOIt32DgYD6utsuUeHs4d7AsEYLuIAdg7FlYgI=
golang.org/x/time v0.13.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
@@ -1100,13 +1133,11 @@ golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.3.0/go.mod h1:/rWhSS2+zyEVwoJf8YAX6L2f0ntZ7Kn/mGgAWcipA5k=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.7.0/go.mod h1:4pg6aUX35JBAogB10C9AtvVL+qowtN4pT3CGSQex14s=
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
golang.org/x/tools v0.14.0/go.mod h1:uYBEerGOWcJyEORxN+Ek8+TT266gXkNlHdJBwexUsBg=
golang.org/x/tools v0.36.0 h1:kWS0uv/zsvHEle1LbV5LE8QujrxB3wfQyxHfhOk0Qkg=
golang.org/x/tools v0.36.0/go.mod h1:WBDiHKJK8YgLHlcQPYQzNCkUxUypCaa5ZegCVutKm+s=
golang.org/x/tools v0.37.0 h1:DVSRzp7FwePZW356yEAChSdNcQo6Nsp+fex1SUW09lE=
golang.org/x/tools v0.37.0/go.mod h1:MBN5QPQtLMHVdvsbtarmTNukZDdgwdwlO5qGacAzF0w=
golang.org/x/tools/go/expect v0.1.1-deprecated h1:jpBZDwmgPhXsKZC6WhL20P4b/wmnpsEAGHaNy0n/rJM=
golang.org/x/tools/go/expect v0.1.1-deprecated/go.mod h1:eihoPOH+FgIqa3FpoTwguz/bVUSGBlGQU67vpBeOrBY=
golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated h1:1h2MnaIAIXISqTFKdENegdpAgUXz6NrPEsbIeWaBRvM=
@@ -1192,8 +1223,8 @@ google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGj
google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY=
google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
google.golang.org/protobuf v1.36.8 h1:xHScyCOEuuwZEc6UtSOvPbAT4zRh0xcNRYekJwfqyMc=
google.golang.org/protobuf v1.36.8/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+5 -1
View File
@@ -71,7 +71,11 @@ func sseHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int,
return http.StatusInternalServerError, fmt.Errorf("error sending broadcast: %v, user: %s", err, username)
}
case msg := <-sendChan:
case msg, ok := <-sendChan:
if !ok {
logger.Debugf("SSE channel closed for user: %s, SessionId: %s", username, sessionId)
return http.StatusOK, nil
}
if err := msgr.sendEvent(msg.EventType, msg.Message); err != nil {
return http.StatusInternalServerError, fmt.Errorf("error sending targeted message: %v, user: %s", err, username)
}
+23 -73
View File
@@ -15,6 +15,7 @@ import (
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
"github.com/gtsteffaniak/filebrowser/backend/common/version"
"github.com/gtsteffaniak/filebrowser/backend/database/storage/bolt"
"github.com/gtsteffaniak/filebrowser/backend/events"
"github.com/gtsteffaniak/go-logger/logger"
// http-swagger middleware
)
@@ -43,20 +44,9 @@ var (
func StartHttp(ctx context.Context, storage *bolt.BoltStore, shutdownComplete chan struct{}) {
store = storage
config = &settings.Config
// Dev mode enables development features like template hot-reloading
devMode := os.Getenv("FILEBROWSER_DEVMODE") == "true"
_, err := os.Stat("http/dist")
// In dev mode, always use filesystem assets. Otherwise, check if http/dist exists
var embeddedFS bool
if devMode {
embeddedFS = false
} else {
embeddedFS = os.IsNotExist(err)
}
var err error
// --- START: ADD THIS DECRYPTION LOGIC ---
if embeddedFS {
if settings.Config.Server.EmbeddedFs {
// Embedded mode: Serve files from the embedded assets
assetFs, err = fs.Sub(assets, "embed")
if err != nil {
@@ -74,6 +64,8 @@ func StartHttp(ctx context.Context, storage *bolt.BoltStore, shutdownComplete ch
return string(a), err
},
})
devMode := os.Getenv("FILEBROWSER_DEVMODE") == "true"
if !devMode {
templates = template.Must(templates.ParseFS(assetFs, "public/index.html"))
}
@@ -116,6 +108,7 @@ func StartHttp(ctx context.Context, storage *bolt.BoltStore, shutdownComplete ch
api.HandleFunc("PATCH /resources", withUser(resourcePatchHandler))
api.HandleFunc("GET /raw", withUser(rawHandler))
api.HandleFunc("GET /preview", withUser(previewHandler))
api.HandleFunc("GET /media/subtitles", withUser(subtitlesHandler))
if version.Version == "testing" || version.Version == "untracked" {
api.HandleFunc("GET /inspectIndex", inspectIndex)
api.HandleFunc("GET /mockData", mockData)
@@ -127,22 +120,29 @@ func StartHttp(ctx context.Context, storage *bolt.BoltStore, shutdownComplete ch
api.HandleFunc("GET /access/groups", withAdmin(groupGetHandler))
api.HandleFunc("POST /access/group", withAdmin(groupPostHandler))
api.HandleFunc("DELETE /access/group", withAdmin(groupDeleteHandler))
// Share management routes (require permission)
api.HandleFunc("GET /shares", withPermShare(shareListHandler))
api.HandleFunc("GET /share/direct", withPermShare(shareDirectDownloadHandler))
api.HandleFunc("GET /share", withPermShare(shareGetHandler))
api.HandleFunc("POST /share", withPermShare(sharePostHandler))
api.HandleFunc("DELETE /share", withPermShare(shareDeleteHandler))
// Create API sub-router for public API endpoints
publicAPI := http.NewServeMux()
// NEW PUBLIC ROUTES - All publicly accessible endpoints
// Share management routes (require permission but are publicly accessible)
publicRoutes.HandleFunc("GET /shares", withPermShare(shareListHandler))
publicRoutes.HandleFunc("GET /share/direct", withPermShare(shareDirectDownloadHandler))
publicRoutes.HandleFunc("GET /share", withPermShare(shareGetHandler))
publicRoutes.HandleFunc("POST /share", withPermShare(sharePostHandler))
publicRoutes.HandleFunc("DELETE /share", withPermShare(shareDeleteHandler))
// Public API routes (hash-based authentication)
publicAPI.HandleFunc("GET /raw", withHashFile(publicRawHandler))
publicAPI.HandleFunc("GET /preview", withHashFile(publicPreviewHandler))
publicAPI.HandleFunc("GET /resources", withHashFile(publicShareHandler))
publicAPI.HandleFunc("GET /users", withUser(userGetHandler))
publicAPI.HandleFunc("POST /onlyoffice/callback", withHashFile(onlyofficeCallbackHandler))
publicAPI.HandleFunc("GET /onlyoffice/callback", withHashFile(onlyofficeCallbackHandler))
publicAPI.HandleFunc("GET /onlyoffice/config", withHashFile(onlyofficeClientConfigGetHandler))
// Settings routes
api.HandleFunc("GET /settings", withAdmin(settingsGetHandler))
api.HandleFunc("GET /settings/config", withAdmin(settingsConfigHandler))
// Events routes
api.HandleFunc("GET /events", withUser(func(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
@@ -153,63 +153,10 @@ func StartHttp(ctx context.Context, storage *bolt.BoltStore, shutdownComplete ch
api.HandleFunc("GET /jobs/{action}/{target}", withUser(getJobsHandler))
api.HandleFunc("GET /onlyoffice/config", withUser(onlyofficeClientConfigGetHandler))
publicAPI.HandleFunc("GET /onlyoffice/config", withHashFile(onlyofficeClientConfigGetHandler))
api.HandleFunc("POST /onlyoffice/callback", withUser(onlyofficeCallbackHandler))
publicAPI.HandleFunc("POST /onlyoffice/callback", withHashFile(onlyofficeCallbackHandler))
api.HandleFunc("GET /onlyoffice/getToken", withUser(onlyofficeGetTokenHandler))
publicAPI.HandleFunc("GET /onlyoffice/getToken", withHashFile(onlyofficeGetTokenHandler))
api.HandleFunc("GET /onlyoffice/callback", withUser(onlyofficeCallbackHandler))
api.HandleFunc("GET /search", withUser(searchHandler))
// Share routes (DEPRECATED - maintain for backwards compatibility)
// These will redirect to the new /public/shares endpoints
api.HandleFunc("GET /shares", func(w http.ResponseWriter, r *http.Request) {
newURL := config.Server.BaseURL + "public/shares"
if r.URL.RawQuery != "" {
newURL += "?" + r.URL.RawQuery
}
http.Redirect(w, r, newURL, http.StatusMovedPermanently)
})
api.HandleFunc("GET /share", func(w http.ResponseWriter, r *http.Request) {
newURL := config.Server.BaseURL + "public/share"
if r.URL.RawQuery != "" {
newURL += "?" + r.URL.RawQuery
}
http.Redirect(w, r, newURL, http.StatusMovedPermanently)
})
api.HandleFunc("POST /share", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, config.Server.BaseURL+"public/share", http.StatusPermanentRedirect)
})
api.HandleFunc("DELETE /share", func(w http.ResponseWriter, r *http.Request) {
newURL := config.Server.BaseURL + "public/share"
if r.URL.RawQuery != "" {
newURL += "?" + r.URL.RawQuery
}
http.Redirect(w, r, newURL, http.StatusPermanentRedirect)
})
api.HandleFunc("GET /public/raw", func(w http.ResponseWriter, r *http.Request) {
newURL := config.Server.BaseURL + "public/api/raw"
if r.URL.RawQuery != "" {
newURL += "?" + r.URL.RawQuery
}
http.Redirect(w, r, newURL, http.StatusMovedPermanently)
})
api.HandleFunc("GET /public/share", func(w http.ResponseWriter, r *http.Request) {
newURL := config.Server.BaseURL + "public/api/shared"
if r.URL.RawQuery != "" {
newURL += "?" + r.URL.RawQuery
}
http.Redirect(w, r, newURL, http.StatusMovedPermanently)
})
api.HandleFunc("GET /public/preview", func(w http.ResponseWriter, r *http.Request) {
newURL := config.Server.BaseURL + "public/api/preview"
if r.URL.RawQuery != "" {
newURL += "?" + r.URL.RawQuery
}
http.Redirect(w, r, newURL, http.StatusMovedPermanently)
})
// Mount the public API sub-router
publicRoutes.Handle("/api/", http.StripPrefix("/api", publicAPI))
@@ -302,6 +249,9 @@ func StartHttp(ctx context.Context, storage *bolt.BoltStore, shutdownComplete ch
<-ctx.Done()
logger.Info("Shutting down HTTP server...")
// Close all SSE sessions
events.Shutdown()
// Persist in-memory state before shutting down the HTTP server
if store != nil {
if store.Share != nil {
+83
View File
@@ -0,0 +1,83 @@
package http
import (
"bytes"
"fmt"
"net/http"
"net/url"
"path/filepath"
"strconv"
"time"
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
"github.com/gtsteffaniak/filebrowser/backend/ffmpeg"
"github.com/gtsteffaniak/filebrowser/backend/indexing"
)
// subtitlesHandler handles subtitle extraction requests
// @Summary Extract embedded subtitles
// @Description Extracts embedded subtitle content from video files by stream index and returns raw WebVTT content
// @Tags Subtitles
// @Accept json
// @Produce text/vtt
// @Param path query string true "Index path to the video file"
// @Param source query string true "Source name for the desired source"
// @Param index query int false "Stream index for embedded subtitle extraction, defaults to 0"
// @Success 200 {string} string "Raw WebVTT subtitle content"
// @Failure 400 {object} map[string]string "Bad request"
// @Failure 403 {object} map[string]string "Forbidden"
// @Failure 404 {object} map[string]string "Resource not found"
// @Failure 500 {object} map[string]string "Internal server error"
// @Router /api/media/subtitles [get]
func subtitlesHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
encodedPath := r.URL.Query().Get("path")
source := r.URL.Query().Get("source")
indexParam := r.URL.Query().Get("index")
if indexParam == "" {
indexParam = "0" // default to first subtitle stream
}
path, err := url.QueryUnescape(encodedPath)
if err != nil {
return http.StatusBadRequest, fmt.Errorf("invalid path encoding: %v", err)
}
source, err = url.QueryUnescape(source)
if err != nil {
return http.StatusBadRequest, fmt.Errorf("invalid source encoding: %v", err)
}
userscope, err := settings.GetScopeFromSourceName(d.user.Scopes, source)
if err != nil {
return http.StatusForbidden, err
}
idx := indexing.GetIndex(source)
if idx == nil {
return http.StatusNotFound, fmt.Errorf("source %s not found", source)
}
realPath, _, err := idx.GetRealPath(userscope, path)
if err != nil {
return http.StatusNotFound, fmt.Errorf("file not found: %v", err)
}
metadata, exists := idx.GetMetadataInfo(userscope, true)
if !exists {
return http.StatusNotFound, fmt.Errorf("file not found: %v", err)
}
index, err := strconv.Atoi(indexParam)
if err != nil {
return http.StatusBadRequest, fmt.Errorf("invalid index parameter: %v", err)
}
parentDir := filepath.Dir(realPath)
subtitle, err := ffmpeg.ExtractSingleSubtitle(realPath, parentDir, index, metadata.ModTime)
if err != nil {
return http.StatusInternalServerError, fmt.Errorf("failed to extract subtitle: %v", err)
}
w.Header().Set("Content-Type", "text/vtt; charset=utf-8")
w.Header().Set("Content-Disposition", "inline")
w.Header().Set("Cache-Control", "private")
http.ServeContent(w, r, fmt.Sprintf("%s-%d.vtt", subtitle.Name, index),
time.Now(), bytes.NewReader([]byte(subtitle.Content)))
return http.StatusOK, nil
}
+20 -5
View File
@@ -6,6 +6,7 @@ import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"runtime"
"slices"
"strings"
@@ -15,6 +16,7 @@ import (
"github.com/gtsteffaniak/filebrowser/backend/adapters/fs/files"
"github.com/gtsteffaniak/filebrowser/backend/auth"
"github.com/gtsteffaniak/filebrowser/backend/common/errors"
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
"github.com/gtsteffaniak/filebrowser/backend/database/share"
"github.com/gtsteffaniak/filebrowser/backend/database/users"
@@ -47,7 +49,13 @@ type handleFunc func(w http.ResponseWriter, r *http.Request, data *requestContex
func withHashFileHelper(fn handleFunc) handleFunc {
return withOrWithoutUserHelper(func(w http.ResponseWriter, r *http.Request, data *requestContext) (int, error) {
hash := r.URL.Query().Get("hash")
path := r.URL.Query().Get("path")
encodedPath := r.URL.Query().Get("path")
// Decode the URL-encoded path - use PathUnescape to preserve + as literal character
path, err := url.PathUnescape(encodedPath)
if err != nil {
return http.StatusBadRequest, fmt.Errorf("invalid path encoding: %v", err)
}
// Get the file link by hash
link, err := store.Share.GetByHash(hash)
if err != nil {
@@ -80,7 +88,8 @@ func withHashFileHelper(fn handleFunc) handleFunc {
}
// Get file information with options
getContent := r.URL.Query().Get("content") == "true"
if link.DisableFileViewer || link.Downloads >= link.DownloadsLimit {
reachedDownloadsLimit := link.Downloads >= link.DownloadsLimit && link.DownloadsLimit > 0
if link.DisableFileViewer || reachedDownloadsLimit {
getContent = false
}
file, err := FileInfoFasterFunc(iteminfo.FileOptions{
@@ -90,11 +99,16 @@ func withHashFileHelper(fn handleFunc) handleFunc {
Expand: true,
Content: getContent,
})
file.Token = link.Token
if err != nil {
logger.Errorf("error fetching file info for share. hash=%v path=%v error=%v", hash, path, err)
return errToStatus(err), fmt.Errorf("error fetching share from server")
}
file.Token = link.Token
file.Source = ""
file.Hash = link.Hash
if !link.EnableOnlyOffice || !link.DisableFileViewer || reachedDownloadsLimit {
file.OnlyOfficeId = ""
}
if getContent && file.Content != "" {
link.Mu.Lock()
link.Downloads++
@@ -102,7 +116,7 @@ func withHashFileHelper(fn handleFunc) handleFunc {
}
file.Path = "/" + strings.TrimPrefix(strings.TrimPrefix(file.Path, link.Path), "/")
// Set the file info in the `data` object
data.fileInfo = file
data.fileInfo = *file
// Call the next handler with the data
return fn(w, r, data)
})
@@ -180,7 +194,8 @@ func withOrWithoutUserHelper(fn handleFunc) handleFunc {
}
// Only fall back to anonymous if authentication actually failed
if status == http.StatusUnauthorized || status == http.StatusForbidden {
data.user = &users.AnonymousUser
data.user = &users.User{Username: "anonymous"}
settings.ApplyUserDefaults(data.user)
// If user authentication failed, call the handler without user context
// Clear any user data that might have been partially set
data.token = ""
+2 -2
View File
@@ -43,8 +43,8 @@ func mockFileInfoFaster(t *testing.T) {
t.Cleanup(func() { FileInfoFasterFunc = originalFileInfoFaster })
// Mock the function to skip execution
FileInfoFasterFunc = func(opts iteminfo.FileOptions) (iteminfo.ExtendedFileInfo, error) {
return iteminfo.ExtendedFileInfo{
FileInfoFasterFunc = func(opts iteminfo.FileOptions) (*iteminfo.ExtendedFileInfo, error) {
return &iteminfo.ExtendedFileInfo{
FileInfo: iteminfo.FileInfo{
Path: opts.Path,
ItemInfo: iteminfo.ItemInfo{
+353 -101
View File
@@ -1,12 +1,14 @@
package http
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"path/filepath"
"strconv"
"strings"
@@ -34,72 +36,122 @@ type OnlyOfficeCallback struct {
UserData string `json:"userdata,omitempty"`
}
// OnlyOfficeJWTPayload represents the JWT payload structure for OnlyOffice callbacks
type OnlyOfficeJWTPayload struct {
Key string `json:"key"`
Status int `json:"status"`
Users []string `json:"users"`
Actions []struct {
Type int `json:"type"`
UserID string `json:"userid"`
} `json:"actions"`
}
func onlyofficeClientConfigGetHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
if settings.Config.Integrations.OnlyOffice.Url == "" {
return http.StatusInternalServerError, errors.New("only-office integration must be configured in settings")
}
encodedUrl := r.URL.Query().Get("url")
// Decode the URL-encoded path
givenUrl, err := url.QueryUnescape(encodedUrl)
if err != nil {
return http.StatusBadRequest, fmt.Errorf("invalid path encoding: %v", err)
// Extract clean parameters from request
source := r.URL.Query().Get("source")
path := r.URL.Query().Get("path")
// Validate required parameters
if (path == "" || source == "") && d.fileInfo.Hash == "" {
logger.Errorf("OnlyOffice callback missing required parameters: source=%s, path=%s", source, path)
return http.StatusBadRequest, errors.New("missing required parameters: path + source/hash are required")
}
// get path from url
pathParts := strings.Split(givenUrl, "/api/raw?files=")
origPathParts := strings.Split(encodedUrl, "/api/raw?files=")
encodedPath := origPathParts[len(origPathParts)-1]
sourceFile := pathParts[len(pathParts)-1]
sourceSplit := strings.Split(sourceFile, "::")
if len(sourceSplit) != 2 {
return http.StatusBadRequest, fmt.Errorf("invalid url path %v", givenUrl)
themeMode := utils.Ternary(d.user.DarkMode, "dark", "light")
var sourceInfo settings.Source
var ok bool
if d.fileInfo.Hash != "" {
sourceInfo, ok = settings.Config.Server.SourceMap[source]
if !ok {
logger.Error("OnlyOffice: source not found")
return http.StatusInternalServerError, fmt.Errorf("source not found")
}
} else {
sourceInfo, ok = settings.Config.Server.NameToSource[source]
if !ok {
logger.Error("OnlyOffice: source not found")
return http.StatusInternalServerError, fmt.Errorf("source not found")
}
}
source := sourceSplit[0]
path := sourceSplit[1]
urlFirst := pathParts[0]
if settings.Config.Server.InternalUrl != "" {
urlFirst = settings.Config.Server.InternalUrl + settings.Config.Server.BaseURL
whatToReplace := strings.Split(givenUrl, "/api/raw")[0] + "/"
givenUrl = strings.Replace(givenUrl, whatToReplace, urlFirst, 1)
}
userscope, err := settings.GetScopeFromSourceName(d.user.Scopes, source)
if err != nil {
return http.StatusForbidden, err
}
fileInfo, err := files.FileInfoFaster(iteminfo.FileOptions{
Path: utils.JoinPathAsUnix(userscope, path),
Modify: d.user.Permissions.Modify,
Source: source,
Expand: false,
})
if err != nil {
logger.Debugf("onlyofficeClientConfigGetHandler: failed to get file info for file source %v, path %v: %v", source, path, err)
return errToStatus(err), err
}
id, err := getOnlyOfficeId(source, fileInfo.Path)
if err != nil {
logger.Debugf("getOnlyOfficeId failed for file source %v, path %v: %v", source, fileInfo.Path, err)
return http.StatusNotFound, err
}
split := strings.Split(fileInfo.Name, ".")
fileType := split[len(split)-1]
theme := "light"
if d.user.DarkMode {
theme = "dark"
if d.fileInfo.Hash == "" {
// Build file info based on whether this is a share or regular request
// Regular user request - need to resolve scope
userScope, scopeErr := settings.GetScopeFromSourceName(d.user.Scopes, source)
if scopeErr != nil {
logger.Errorf("OnlyOffice: source %s not available for user %s: %v", source, d.user.Username, scopeErr)
return http.StatusForbidden, fmt.Errorf("source %s is not available", source)
}
indexPath := utils.JoinPathAsUnix(userScope, path)
logger.Debugf("OnlyOffice user request: resolved path=%s", indexPath)
fileInfo, err := files.FileInfoFaster(iteminfo.FileOptions{
Path: indexPath,
Modify: d.user.Permissions.Modify,
Source: source,
Expand: false,
})
if err != nil {
logger.Errorf("OnlyOffice: failed to get file info for source=%s, path=%s: %v", source, indexPath, err)
return errToStatus(err), err
}
d.fileInfo = *fileInfo
} else {
source = sourceInfo.Name
// path is index path, so we build from share path
path = utils.JoinPathAsUnix(d.share.Path, path)
if d.share.EnforceDarkLightMode == "dark" {
themeMode = "dark"
}
if d.share.EnforceDarkLightMode == "light" {
themeMode = "light"
}
}
// Determine file type and editing permissions
fileType := strings.TrimPrefix(filepath.Ext(d.fileInfo.Name), ".")
canEdit := iteminfo.CanEditOnlyOffice(d.user.Permissions.Modify, fileType)
mode := "view"
if canEdit {
mode = "edit"
canEditMode := utils.Ternary(canEdit, "edit", "view")
if d.fileInfo.Hash != "" {
if d.share.EnableOnlyOfficeEditing {
canEditMode = "edit"
}
}
callbackURL := fmt.Sprintf("%v/api/onlyoffice/callback?files=%v&auth=%v", strings.TrimSuffix(urlFirst, "/"), encodedPath, d.token)
// For shares, we need to keep track of the original relative path for the callback URL
var callbackPath string
if d.fileInfo.Hash != "" {
// For shares, use the original path parameter (relative to share)
callbackPath = r.URL.Query().Get("path")
} else {
// For regular requests, use the processed path
callbackPath = path
}
// Generate document ID for OnlyOffice
documentId, err := getOnlyOfficeId(d.fileInfo.RealPath)
if err != nil {
logger.Errorf("OnlyOffice: failed to generate document ID for source=%s, path=%s: %v", source, path, err)
return http.StatusNotFound, fmt.Errorf("failed to generate document ID: %v", err)
}
// Build download URL that OnlyOffice server will use
downloadURL := buildOnlyOfficeDownloadURL(source, callbackPath, d.fileInfo.Hash, d.token)
// Build callback URL for OnlyOffice to notify us of changes
callbackURL := buildOnlyOfficeCallbackURL(source, callbackPath, d.fileInfo.Hash, d.token)
// Build OnlyOffice client configuration
clientConfig := map[string]interface{}{
"document": map[string]interface{}{
"fileType": fileType,
"key": id,
"title": fileInfo.Name,
"url": givenUrl + "&auth=" + d.token,
"key": documentId,
"title": d.fileInfo.Name,
"url": downloadURL,
"permissions": map[string]interface{}{
"edit": canEdit,
"edit": utils.Ternary(settings.Config.Integrations.OnlyOffice.ViewOnly, "view", canEditMode),
"download": true,
"print": true,
},
@@ -113,90 +165,248 @@ func onlyofficeClientConfigGetHandler(w http.ResponseWriter, r *http.Request, d
"customization": map[string]interface{}{
"autosave": true,
"forcesave": true,
"uiTheme": theme,
"uiTheme": themeMode,
},
"lang": d.user.Locale,
"mode": mode,
"mode": utils.Ternary(settings.Config.Integrations.OnlyOffice.ViewOnly, "view", canEditMode),
},
}
// Sign configuration with JWT if secret is configured
if settings.Config.Integrations.OnlyOffice.Secret != "" {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims(clientConfig))
signature, err := token.SignedString([]byte(settings.Config.Integrations.OnlyOffice.Secret))
if err != nil {
return http.StatusInternalServerError, fmt.Errorf("failed to sign JWT")
logger.Errorf("OnlyOffice: failed to sign JWT: %v", err)
return http.StatusInternalServerError, fmt.Errorf("failed to sign configuration")
}
clientConfig["token"] = signature
}
return renderJSON(w, r, clientConfig)
}
func onlyofficeCallbackHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
body, err := io.ReadAll(r.Body)
if err != nil {
return http.StatusInternalServerError, err
}
var data OnlyOfficeCallback
err = json.Unmarshal(body, &data)
if err != nil {
return http.StatusInternalServerError, err
// buildOnlyOfficeDownloadURL constructs the download URL that OnlyOffice server will use to fetch the file
func buildOnlyOfficeDownloadURL(source, path, hash, token string) string {
// Determine base URL (internal URL takes priority for OnlyOffice server communication)
baseURL := settings.Config.Server.BaseURL
if settings.Config.Server.InternalUrl != "" {
// Ensure proper URL joining without double slashes
internalURL := strings.TrimSuffix(settings.Config.Server.InternalUrl, "/")
baseURLPath := strings.TrimPrefix(settings.Config.Server.BaseURL, "/")
baseURL = internalURL + "/" + baseURLPath
}
encodedPath := r.URL.Query().Get("files")
pathParts := strings.Split(encodedPath, "::")
if len(pathParts) < 2 {
return http.StatusBadRequest, fmt.Errorf("invalid path encoding: %v", err)
var downloadURL string
if hash != "" {
// Share download URL - don't expose source name, just use the path relative to share
filesParam := url.QueryEscape(path)
downloadURL = fmt.Sprintf("%s/public/api/raw?files=%s&hash=%s&token=%s&auth=%s",
strings.TrimSuffix(baseURL, "/"), filesParam, hash, token, token)
} else {
// Regular download URL - include source for non-share requests
filesParam := url.QueryEscape(source + "::" + path)
downloadURL = fmt.Sprintf("%s/api/raw?files=%s&auth=%s",
strings.TrimSuffix(baseURL, "/"), filesParam, token)
}
source := pathParts[0]
// Decode the URL-encoded path
path, err := url.QueryUnescape(pathParts[1])
if err != nil {
return http.StatusBadRequest, fmt.Errorf("invalid path encoding: %v", err)
return downloadURL
}
// buildOnlyOfficeCallbackURL constructs the callback URL that OnlyOffice server will use to notify us of changes
func buildOnlyOfficeCallbackURL(source, path, hash, token string) string {
baseURL := settings.Config.Server.BaseURL
if settings.Config.Server.InternalUrl != "" {
// Ensure proper URL joining without double slashes
internalURL := strings.TrimSuffix(settings.Config.Server.InternalUrl, "/")
baseURLPath := strings.TrimPrefix(settings.Config.Server.BaseURL, "/")
baseURL = internalURL + "/" + baseURLPath
}
var callbackURL string
if hash != "" {
// Share callback URL - use public API and don't expose source, use path relative to share
params := url.Values{}
params.Set("hash", hash)
params.Set("path", path) // This should be the path relative to the share, not the full filesystem path
params.Set("auth", token)
callbackURL = fmt.Sprintf("%s/public/api/onlyoffice/callback?%s",
strings.TrimSuffix(baseURL, "/"), params.Encode())
} else {
// Regular callback URL - include source for non-share requests
params := url.Values{}
params.Set("source", source)
params.Set("path", path)
params.Set("auth", token)
callbackURL = fmt.Sprintf("%s/api/onlyoffice/callback?%s",
strings.TrimSuffix(baseURL, "/"), params.Encode())
}
return callbackURL
}
// processOnlyOfficeCallback handles the common callback processing logic for both GET and POST requests
func processOnlyOfficeCallback(w http.ResponseWriter, r *http.Request, d *requestContext, data *OnlyOfficeCallback) (int, error) {
// Extract clean parameters from query string
source := r.URL.Query().Get("source")
path := r.URL.Query().Get("path")
// Validate required parameters
if (path == "" || source == "") && d.fileInfo.Hash == "" {
logger.Errorf("OnlyOffice callback missing required parameters: source=%s, path=%s", source, path)
return http.StatusBadRequest, errors.New("missing required parameters: path + source/hash are required")
}
var sourceInfo settings.Source
var ok bool
if d.fileInfo.Hash != "" {
sourceInfo, ok = settings.Config.Server.SourceMap[source]
if !ok {
logger.Error("OnlyOffice: source not found")
return http.StatusInternalServerError, fmt.Errorf("source not found")
}
} else {
sourceInfo, ok = settings.Config.Server.NameToSource[source]
if !ok {
logger.Error("OnlyOffice: source not found")
return http.StatusInternalServerError, fmt.Errorf("source not found")
}
}
if d.fileInfo.Hash == "" {
// Regular user request - need to resolve scope
userScope, scopeErr := settings.GetScopeFromSourceName(d.user.Scopes, source)
if scopeErr != nil {
logger.Errorf("OnlyOffice callback: source %s not available for user %s: %v", source, d.user.Username, scopeErr)
return http.StatusForbidden, fmt.Errorf("source %s is not available", source)
}
path = utils.JoinPathAsUnix(userScope, path)
} else {
source = sourceInfo.Name
// path is index path, so we build from share path
path = utils.JoinPathAsUnix(d.share.Path, path)
}
// Handle document closure - clean up document key cache
if data.Status == onlyOfficeStatusDocumentClosedWithChanges ||
data.Status == onlyOfficeStatusDocumentClosedWithNoChanges {
// Refer to only-office documentation
// Refer to OnlyOffice documentation:
// - https://api.onlyoffice.com/editors/coedit
// - https://api.onlyoffice.com/editors/callback
//
// When the document is fully closed by all editors,
// then the document key should no longer be re-used.
// the document key should no longer be re-used.
deleteOfficeId(source, path)
}
// Handle document save operations
if data.Status == onlyOfficeStatusDocumentClosedWithChanges ||
data.Status == onlyOfficeStatusForceSaveWhileDocumentStillOpen {
// Verify user has modify permissions
if !d.user.Permissions.Modify {
logger.Warningf("OnlyOffice callback: user %s lacks modify permissions for source=%s, path=%s",
d.user.Username, source, path)
return http.StatusForbidden, nil
}
// Download the updated document from OnlyOffice server
doc, err := http.Get(data.URL)
if err != nil {
logger.Errorf("OnlyOffice callback: failed to download updated document: %v", err)
return http.StatusInternalServerError, err
}
defer doc.Body.Close()
// Resolve file path for writing (same logic as in config handler)
var resolvedPath string
if d.fileInfo.Hash == "" {
// Regular user request - need to resolve scope
userScope, scopeErr := settings.GetScopeFromSourceName(d.user.Scopes, source)
if scopeErr != nil {
logger.Errorf("OnlyOffice callback: source %s not available for user %s: %v",
source, d.user.Username, scopeErr)
return http.StatusForbidden, fmt.Errorf("source %s is not available", source)
}
resolvedPath = utils.JoinPathAsUnix(userScope, path)
}
// Write the updated document
fileOpts := iteminfo.FileOptions{
Path: path,
Path: resolvedPath,
Source: source,
}
writeErr := files.WriteFile(fileOpts, doc.Body)
if writeErr != nil {
logger.Errorf("OnlyOffice callback: failed to write updated document: %v", writeErr)
return http.StatusInternalServerError, writeErr
}
}
// Return success response to OnlyOffice server
resp := map[string]int{
"error": 0,
}
return renderJSON(w, r, resp)
}
func getOnlyOfficeId(source, path string) (string, error) {
idx := indexing.GetIndex(source)
if idx == nil {
return "", fmt.Errorf("source not found")
func onlyofficeCallbackHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
// Parse callback data based on request method
var callbackData *OnlyOfficeCallback
var err error
if r.Method == "GET" {
// OnlyOffice sends callback data in Authorization header as JWT
callbackData, err = parseOnlyOfficeCallbackFromJWT(r)
} else if r.Method == "POST" {
// OnlyOffice sends callback data in request body as JSON
callbackData, err = parseOnlyOfficeCallbackFromJSON(r)
} else {
return http.StatusMethodNotAllowed, fmt.Errorf("unsupported method: %s", r.Method)
}
realpath, _, _ := idx.GetRealPath(path)
if err != nil {
logger.Errorf("OnlyOffice callback: failed to parse callback data: %v", err)
return http.StatusBadRequest, err
}
// Process the callback data using shared logic
return processOnlyOfficeCallback(w, r, d, callbackData)
}
// parseOnlyOfficeCallbackFromJWT extracts callback data from JWT in Authorization header
func parseOnlyOfficeCallbackFromJWT(r *http.Request) (*OnlyOfficeCallback, error) {
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
return nil, errors.New("missing Authorization header")
}
if !strings.HasPrefix(authHeader, "Bearer ") {
return nil, errors.New("invalid Authorization header format")
}
jwtToken := strings.TrimPrefix(authHeader, "Bearer ")
return parseOnlyOfficeJWT(jwtToken)
}
// parseOnlyOfficeCallbackFromJSON extracts callback data from JSON request body
func parseOnlyOfficeCallbackFromJSON(r *http.Request) (*OnlyOfficeCallback, error) {
body, err := io.ReadAll(r.Body)
if err != nil {
return nil, fmt.Errorf("failed to read request body: %v", err)
}
var data OnlyOfficeCallback
err = json.Unmarshal(body, &data)
if err != nil {
return nil, fmt.Errorf("failed to parse JSON: %v", err)
}
return &data, nil
}
func getOnlyOfficeId(realpath string) (string, error) {
// error is intentionally ignored in order treat errors
// the same as a cache-miss
cachedDocumentKey, ok := utils.OnlyOfficeCache.Get(realpath).(string)
@@ -216,28 +426,70 @@ func deleteOfficeId(source, path string) {
utils.OnlyOfficeCache.Delete(realpath)
}
func onlyofficeGetTokenHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
// get config from body
body, err := io.ReadAll(r.Body)
if err != nil {
return http.StatusInternalServerError, err
}
defer r.Body.Close()
var payload map[string]interface{}
// marshall to struct
err = json.Unmarshal(body, &payload)
if err != nil {
return http.StatusInternalServerError, err
// parseOnlyOfficeJWT parses the JWT token from OnlyOffice callback
func parseOnlyOfficeJWT(tokenString string) (*OnlyOfficeCallback, error) {
// Parse the JWT token without signature verification since OnlyOffice uses different signing
// We'll parse it manually to avoid signature validation issues
parts := strings.Split(tokenString, ".")
if len(parts) != 3 {
return nil, fmt.Errorf("invalid JWT format")
}
if settings.Config.Integrations.OnlyOffice.Secret != "" {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims(payload))
ss, err := token.SignedString([]byte(settings.Config.Integrations.OnlyOffice.Secret))
// Decode the payload (second part) with fallback to standard base64
payloadBytes, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
// Fallback to standard base64 decoding
payloadBytes, err = base64.StdEncoding.DecodeString(parts[1])
if err != nil {
return 500, errors.New("could not generate a new jwt")
return nil, fmt.Errorf("failed to decode JWT payload: %v", err)
}
return renderJSON(w, r, map[string]string{"token": ss})
}
return 400, fmt.Errorf("bad request")
var claims jwt.MapClaims
err = json.Unmarshal(payloadBytes, &claims)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal JWT claims: %v", err)
}
// Extract payload from claims with fallback
payload, ok := claims["payload"].(map[string]interface{})
if !ok {
// Fallback: try to use claims directly if no payload wrapper
payload = map[string]interface{}(claims)
}
// Convert to OnlyOfficeCallback struct with safe type assertions
callback := &OnlyOfficeCallback{}
// Extract key with validation
if key, ok := payload["key"].(string); ok && key != "" {
callback.Key = key
} else {
logger.Warningf("OnlyOffice callback: missing or empty key in JWT payload")
}
// Extract status with validation
if status, ok := payload["status"].(float64); ok {
callback.Status = int(status)
} else {
logger.Warningf("OnlyOffice callback: missing or invalid status in JWT payload")
callback.Status = 0 // Default to unknown status
}
// Extract users with safe array handling
if users, ok := payload["users"].([]interface{}); ok {
callback.Users = make([]string, 0, len(users))
for _, user := range users {
if userStr, ok := user.(string); ok && userStr != "" {
callback.Users = append(callback.Users, userStr)
}
}
}
// Validate essential fields
if callback.Key == "" {
return nil, fmt.Errorf("missing document key in JWT payload")
}
return callback, nil
}
+39 -13
View File
@@ -7,6 +7,7 @@ import (
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
@@ -48,7 +49,7 @@ func previewHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (
source := r.URL.Query().Get("source")
var err error
// decode url encoded source name
source, err = url.QueryUnescape(source)
source, err = url.PathUnescape(source)
if err != nil {
return http.StatusBadRequest, fmt.Errorf("invalid source encoding: %v", err)
}
@@ -63,14 +64,13 @@ func previewHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (
Access: store.Access,
Username: d.user.Username,
Path: utils.JoinPathAsUnix(userscope, path),
Modify: d.user.Permissions.Modify,
Source: source,
Expand: true,
Content: true,
})
if err != nil {
return errToStatus(err), err
}
d.fileInfo = fileInfo
d.fileInfo = *fileInfo
return previewHelperFunc(w, r, d)
}
@@ -98,20 +98,46 @@ func previewHelperFunc(w http.ResponseWriter, r *http.Request, d *requestContext
if !(previewSize == "large" || previewSize == "original") {
previewSize = "small"
}
if d.fileInfo.Type == "directory" {
return http.StatusBadRequest, fmt.Errorf("can't create preview for directory")
if !d.fileInfo.HasPreview {
return http.StatusBadRequest, fmt.Errorf("this item does not have a preview")
}
if d.fileInfo.Type == "directory" {
// get extended file info of first previewable item in directory
for _, item := range d.fileInfo.Files {
if item.HasPreview {
source := d.fileInfo.Source
path := utils.JoinPathAsUnix(d.fileInfo.Path, item.Name)
if d.share != nil {
// Get the actual source name from the share's source mapping
sourceInfo, ok := settings.Config.Server.SourceMap[d.share.Source]
if !ok {
return http.StatusInternalServerError, fmt.Errorf("source not found for share")
}
source = sourceInfo.Name
path = utils.JoinPathAsUnix(d.share.Path, path)
}
fileInfo, err := files.FileInfoFaster(
iteminfo.FileOptions{
Path: path,
Source: source,
Content: true,
})
if err != nil {
return http.StatusInternalServerError, err
}
d.fileInfo = *fileInfo
break
}
}
}
setContentDisposition(w, r, d.fileInfo.Name)
isImage := strings.HasPrefix(d.fileInfo.Type, "image")
if config.Server.DisableResize && isImage {
ext := strings.ToLower(filepath.Ext(d.fileInfo.Name))
resizable := iteminfo.ResizableImageTypes[ext]
if (!resizable || config.Server.DisableResize) && isImage {
return rawFileHandler(w, r, d.fileInfo)
}
if !preview.AvailablePreview(d.fileInfo) {
if isImage {
return rawFileHandler(w, r, d.fileInfo)
}
return http.StatusNotImplemented, fmt.Errorf("can't create preview for %s type", d.fileInfo.Type)
}
seekPercentage := 0
percentage := r.URL.Query().Get("atPercentage")
if percentage != "" {
+13 -7
View File
@@ -7,6 +7,7 @@ import (
"net/url"
"strings"
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
"github.com/gtsteffaniak/go-logger/logger"
@@ -37,12 +38,19 @@ func publicRawHandler(w http.ResponseWriter, r *http.Request, d *requestContext)
d.share.Mu.Unlock()
encodedFiles := r.URL.Query().Get("files")
// Decode the URL-encoded path
f, err := url.QueryUnescape(encodedFiles)
// Decode the URL-encoded path - use PathUnescape to preserve + as literal character
f, err := url.PathUnescape(encodedFiles)
if err != nil {
return http.StatusBadRequest, fmt.Errorf("invalid path encoding: %v", err)
}
// Get the actual source name from the share's source mapping
sourceInfo, ok := settings.Config.Server.SourceMap[d.share.Source]
if !ok {
return http.StatusInternalServerError, fmt.Errorf("source not found for share")
}
actualSourceName := sourceInfo.Name
fileList := []string{}
for _, file := range strings.Split(f, "||") {
// Check if file already contains source prefix (source::path format)
@@ -57,12 +65,12 @@ func publicRawHandler(w http.ResponseWriter, r *http.Request, d *requestContext)
} else {
// Fallback: treat as plain path
filePath := utils.JoinPathAsUnix(d.share.Path, file)
fileList = append(fileList, d.fileInfo.Source+"::"+filePath)
fileList = append(fileList, actualSourceName+"::"+filePath)
}
} else {
// Plain path without source prefix
// Plain path without source prefix - use the actual source name from share
filePath := utils.JoinPathAsUnix(d.share.Path, file)
fileList = append(fileList, d.fileInfo.Source+"::"+filePath)
fileList = append(fileList, actualSourceName+"::"+filePath)
}
}
@@ -76,8 +84,6 @@ func publicRawHandler(w http.ResponseWriter, r *http.Request, d *requestContext)
}
func publicShareHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
// disable onlyoffice for public share
d.fileInfo.OnlyOfficeId = ""
return renderJSON(w, r, d.fileInfo)
}
+2 -1
View File
@@ -15,6 +15,7 @@ import (
"strings"
"github.com/gtsteffaniak/filebrowser/backend/adapters/fs/files"
"github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils"
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
"github.com/gtsteffaniak/filebrowser/backend/indexing"
@@ -160,7 +161,7 @@ func addFile(path string, d *requestContext, tarWriter *tar.Writer, zipWriter *z
if tarWriter != nil {
header := &tar.Header{
Name: relPath + "/",
Mode: 0755,
Mode: fileutils.PermDir,
Typeflag: tar.TypeDir,
ModTime: fileInfo.ModTime(),
}
+10 -10
View File
@@ -116,13 +116,13 @@ func resourceGetHandler(w http.ResponseWriter, r *http.Request, d *requestContex
return http.StatusNotFound, fmt.Errorf("source %s not found", source)
}
realPath, _, _ := idx.GetRealPath(userscope, path)
checksums, err := files.GetChecksum(realPath, algo)
checksum, err := utils.GetChecksum(realPath, algo)
if err == errors.ErrInvalidOption {
return http.StatusBadRequest, nil
} else if err != nil {
return http.StatusInternalServerError, err
}
fileInfo.Checksums = checksums
fileInfo.Checksums[algo] = checksum
}
return renderJSON(w, r, fileInfo)
@@ -176,7 +176,7 @@ func resourceDeleteHandler(w http.ResponseWriter, r *http.Request, d *requestCon
}
// delete thumbnails
preview.DelThumbs(r.Context(), fileInfo)
preview.DelThumbs(r.Context(), *fileInfo)
err = files.DeleteFiles(source, fileInfo.RealPath, filepath.Dir(fileInfo.RealPath))
if err != nil {
@@ -269,7 +269,7 @@ func resourcePostHandler(w http.ResponseWriter, r *http.Request, d *requestConte
}
// On the first chunk, check for conflicts or handle override
if offset == 0 {
var fileInfo iteminfo.ExtendedFileInfo
var fileInfo *iteminfo.ExtendedFileInfo
fileInfo, err = files.FileInfoFaster(fileOpts)
if err == nil { // File exists
if r.URL.Query().Get("override") != "true" {
@@ -278,18 +278,18 @@ func resourcePostHandler(w http.ResponseWriter, r *http.Request, d *requestConte
return http.StatusConflict, nil
}
// If overriding, delete existing thumbnails
preview.DelThumbs(r.Context(), fileInfo)
preview.DelThumbs(r.Context(), *fileInfo)
}
}
// Use a temporary file in the cache directory for chunks.
// Create a unique name for the temporary file to avoid collisions.
hasher := md5.New() //nolint:gosec
hasher := md5.New()
hasher.Write([]byte(realPath))
uploadID := hex.EncodeToString(hasher.Sum(nil))
tempFilePath := filepath.Join(settings.Config.Server.CacheDir, "uploads", uploadID)
if err = os.MkdirAll(filepath.Dir(tempFilePath), 0755); err != nil {
if err = os.MkdirAll(filepath.Dir(tempFilePath), fileutils.PermDir); err != nil {
logger.Debugf("could not create temp dir: %v", err)
return http.StatusInternalServerError, fmt.Errorf("could not create temp dir: %v", err)
}
@@ -326,7 +326,7 @@ func resourcePostHandler(w http.ResponseWriter, r *http.Request, d *requestConte
logger.Debugf("could not move temp file to destination: %v", err)
return http.StatusInternalServerError, fmt.Errorf("could not move temp file to destination: %v", err)
}
go files.RefreshIndex(source, realPath, false) //nolint:errcheck
go files.RefreshIndex(source, realPath, false, false) //nolint:errcheck
}
return http.StatusOK, nil
@@ -341,7 +341,7 @@ func resourcePostHandler(w http.ResponseWriter, r *http.Request, d *requestConte
return http.StatusConflict, nil
}
preview.DelThumbs(r.Context(), fileInfo)
preview.DelThumbs(r.Context(), *fileInfo)
}
err = files.WriteFile(fileOpts, r.Body)
if err != nil {
@@ -571,7 +571,7 @@ func patchAction(ctx context.Context, params patchActionParams) error {
}
// delete thumbnails
preview.DelThumbs(ctx, fileInfo)
preview.DelThumbs(ctx, *fileInfo)
return files.MoveResource(params.isSrcDir, params.isDstDir, params.srcIndex, params.dstIndex, params.src, params.dst, store.Share)
default:
return fmt.Errorf("unsupported action %s: %w", params.action, errors.ErrInvalidRequestParams)
+3
View File
@@ -64,6 +64,9 @@ func searchHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (i
if err != nil {
return http.StatusBadRequest, fmt.Errorf("invalid path encoding: %v", err)
}
if len(query) < settings.Config.Server.MinSearchLength {
return http.StatusBadRequest, fmt.Errorf("query is too short, minimum length is %d", settings.Config.Server.MinSearchLength)
}
searchScope := strings.TrimPrefix(unencodedScope, ".")
// Retrieve the User-Agent and X-Auth headers from the request
sessionId := r.Header.Get("SessionId")
+47
View File
@@ -1,7 +1,10 @@
package http
import (
"fmt"
"net/http"
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
)
// settingsGetHandler retrieves the current system settings.
@@ -34,3 +37,47 @@ func settingsGetHandler(w http.ResponseWriter, r *http.Request, d *requestContex
}
return renderJSON(w, r, config)
}
// settingsConfigHandler returns the current system settings as YAML.
// @Summary Get system settings as YAML
// @Description Returns the current running configuration settings as YAML format with optional comments and filtering.
// @Tags Settings
// @Accept json
// @Produce text/plain
// @Param full query boolean false "Show all values (true) or only non-default values (false, default)"
// @Param comments query boolean false "Include comments in YAML (true) or plain YAML (false, default)"
// @Success 200 {string} string "System settings in YAML format"
// @Router /api/settings/config [get]
func settingsConfigHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
// Parse query parameters
fullParam := r.URL.Query().Get("full")
commentsParam := r.URL.Query().Get("comments")
showFull := fullParam == "true"
showComments := commentsParam == "true"
var err error
var yamlConfig string
if config.Server.EmbeddedFs {
embeddedYaml, readErr := assets.ReadFile("embed/config.generated.yaml")
if readErr != nil {
return http.StatusInternalServerError, fmt.Errorf("error reading embedded YAML: %v", readErr)
}
yamlConfig, err = settings.GenerateConfigYamlWithEmbedded(config, showComments, showFull, false, string(embeddedYaml))
if err != nil {
return http.StatusInternalServerError, fmt.Errorf("error generating YAML: %v", err)
}
} else {
yamlConfig, err = settings.GenerateConfigYaml(config, showComments, showFull, false)
if err != nil {
return http.StatusInternalServerError, fmt.Errorf("error generating YAML: %v", err)
}
}
// Set content type and write response
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
if _, err := w.Write([]byte(yamlConfig)); err != nil {
return http.StatusInternalServerError, err
}
return http.StatusOK, nil
}
+4 -4
View File
@@ -89,7 +89,7 @@ func shareGetHandler(w http.ResponseWriter, r *http.Request, d *requestContext)
encodedPath := r.URL.Query().Get("path")
sourceName := r.URL.Query().Get("source")
// Decode the URL-encoded path
path, err := url.QueryUnescape(encodedPath)
path, err := url.PathUnescape(encodedPath)
if err != nil {
return http.StatusBadRequest, fmt.Errorf("invalid path encoding: %v", err)
}
@@ -176,8 +176,8 @@ func sharePostHandler(w http.ResponseWriter, r *http.Request, d *requestContext)
var expire int64 = 0
if body.Expires != "" {
//nolint:govet
num, err := strconv.Atoi(body.Expires)
var num int
num, err = strconv.Atoi(body.Expires)
if err != nil {
return http.StatusInternalServerError, err
}
@@ -204,7 +204,7 @@ func sharePostHandler(w http.ResponseWriter, r *http.Request, d *requestContext)
stringHash := ""
var token string
if len(hash) > 0 {
tokenBuffer := make([]byte, 24) //nolint:gomnd
tokenBuffer := make([]byte, 24)
if _, err = rand.Read(tokenBuffer); err != nil {
return http.StatusInternalServerError, err
}
+69 -25
View File
@@ -48,29 +48,27 @@ func handleWithStaticData(w http.ResponseWriter, r *http.Request, d *requestCont
}
userSelectedTheme := ""
if d.user != nil {
theme, ok := config.Frontend.Styling.CustomThemes[d.user.CustomTheme]
theme, ok := config.Frontend.Styling.CustomThemeOptions[d.user.CustomTheme]
if ok {
userSelectedTheme = theme.CSS
userSelectedTheme = theme.CssRaw
}
}
defaultThemeColor := "#455a64"
staticURL := config.Server.BaseURL + "static"
publicStaticURL := config.Server.BaseURL + "public/static"
data := map[string]interface{}{
"title": config.Frontend.Name,
"customCSS": config.Frontend.Styling.CustomCSS,
"userSelectedTheme": userSelectedTheme,
"lightBackground": config.Frontend.Styling.LightBackground,
"darkBackground": config.Frontend.Styling.DarkBackground,
"staticURL": staticURL,
"baseURL": config.Server.BaseURL,
"favicon": staticURL + "/img/icons/favicon-256x256.png",
"color": defaultThemeColor,
"winIcon": staticURL + "/img/icons/mstile-144x144.png",
"appIcon": staticURL + "/img/icons/android-chrome-256x256.png",
"description": "FileBrowser Quantum is a file manager for the web which can be used to manage files on your server",
if d.share != nil {
staticURL = config.Server.BaseURL + "public/static"
}
// Use custom favicon if configured and validated, otherwise fall back to default
var favicon string
if config.Frontend.Favicon != "" {
favicon = staticURL + "/favicon"
} else {
// Default favicon
favicon = staticURL + "/img/icons/favicon-256x256.png"
}
data := make(map[string]interface{})
shareProps := map[string]interface{}{
"isShare": false,
"isValid": false,
@@ -94,6 +92,7 @@ func handleWithStaticData(w http.ResponseWriter, r *http.Request, d *requestCont
shareProps["hash"] = d.share.Hash
if d.shareValid {
shareProps["singleFileShare"] = d.share.IsSingleFileShare()
disableNavButtons = disableNavButtons || d.share.HideNavButtons
shareProps["viewMode"] = d.share.ViewMode
shareProps["banner"] = d.share.Banner
@@ -107,11 +106,21 @@ func handleWithStaticData(w http.ResponseWriter, r *http.Request, d *requestCont
shareProps["disableSidebar"] = d.share.DisableSidebar
shareProps["isPasswordProtected"] = d.share.PasswordHash != ""
shareProps["downloadURL"] = getDownloadURL(r, d.share.Hash)
shareProps["enforceDarkLightMode"] = d.share.EnforceDarkLightMode
shareProps["viewMode"] = d.share.ViewMode
shareProps["enableOnlyOffice"] = d.share.EnableOnlyOffice
shareProps["enableOnlyOfficeEditing"] = d.share.EnableOnlyOfficeEditing
// Additional computed properties from extended.go
shareProps["hasPassword"] = d.share.HasPassword()
shareProps["isPermanent"] = d.share.IsPermanent()
shareProps["fileExtension"] = d.share.GetFileExtension()
shareProps["fileName"] = d.share.GetFileName()
if d.share.Favicon != "" {
if strings.HasPrefix(d.share.Favicon, "http") {
data["favicon"] = d.share.Favicon
} else {
data["favicon"] = publicStaticURL + "/" + d.share.Favicon
data["favicon"] = staticURL + "/" + d.share.Favicon
}
}
if d.share.Description != "" {
@@ -123,14 +132,34 @@ func handleWithStaticData(w http.ResponseWriter, r *http.Request, d *requestCont
}
// base url could be different for routes behind proxy
data["staticURL"] = publicStaticURL
data["favicon"] = publicStaticURL + "/img/icons/favicon-256x256.png"
data["winIcon"] = publicStaticURL + "/img/icons/mstile-144x144.png"
data["appIcon"] = publicStaticURL + "/img/icons/android-chrome-256x256.png"
data["staticURL"] = staticURL
// Use custom favicon for shares too if configured
if config.Frontend.Favicon != "" {
data["favicon"] = staticURL + "/favicon"
} else {
data["favicon"] = staticURL + "/img/icons/favicon-256x256.png"
}
data["winIcon"] = staticURL + "/img/icons/mstile-144x144.png"
data["appIcon"] = staticURL + "/img/icons/android-chrome-256x256.png"
}
data["htmlVars"] = map[string]interface{}{
"title": config.Frontend.Name,
"customCSS": config.Frontend.Styling.CustomCSSRaw,
"userSelectedTheme": userSelectedTheme,
"lightBackground": config.Frontend.Styling.LightBackground,
"darkBackground": config.Frontend.Styling.DarkBackground,
"staticURL": staticURL,
"baseURL": config.Server.BaseURL,
"favicon": favicon,
"color": defaultThemeColor,
"winIcon": staticURL + "/img/icons/mstile-144x144.png",
"appIcon": staticURL + "/img/icons/android-chrome-256x256.png",
"description": config.Frontend.Description,
}
// variables consumed by frontend as json
data["globalVars"] = map[string]interface{}{
"name": config.Frontend.Name,
"minSearchLength": config.Server.MinSearchLength,
"disableExternal": config.Frontend.DisableDefaultLinks,
"darkMode": settings.Config.UserDefaults.DarkMode,
"baseURL": config.Server.BaseURL,
@@ -151,13 +180,22 @@ func handleWithStaticData(w http.ResponseWriter, r *http.Request, d *requestCont
"updateAvailable": utils.GetUpdateAvailableUrl(),
"disableNavButtons": disableNavButtons,
"userSelectableThemes": config.Frontend.Styling.CustomThemeOptions,
"share": shareProps,
"enableHeicConversion": config.Integrations.Media.Convert.ImagePreview[settings.HEICImagePreview],
}
jsonVars, err := json.Marshal(data["globalVars"])
// Marshal each variable to JSON strings for direct template usage
globalVarsJSON, err := json.Marshal(data["globalVars"])
if err != nil {
return http.StatusInternalServerError, err
return http.StatusInternalServerError, fmt.Errorf("error marshaling globalVars: %w", err)
}
data["globalVars"] = strings.ReplaceAll(string(jsonVars), `'`, `\'`)
shareVarsJSON, err := json.Marshal(shareProps)
if err != nil {
return http.StatusInternalServerError, fmt.Errorf("error marshaling shareVars: %w", err)
}
// Replace with JSON strings for direct template usage
data["globalVars"] = string(globalVarsJSON)
data["shareVars"] = string(shareVarsJSON)
// Render the template with global variables
if err := templateRenderer.Render(w, file, data); err != nil {
@@ -171,6 +209,12 @@ func staticFilesHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%v", maxAge))
w.Header().Set("Content-Security-Policy", `default-src 'self'; style-src 'unsafe-inline';`)
// Handle custom favicon if configured and requested
if r.URL.Path == "favicon" && config.Frontend.Favicon != "" {
http.ServeFile(w, r, config.Frontend.Favicon)
return
}
adjustedCompressed := r.URL.Path + ".gz"
if strings.HasSuffix(r.URL.Path, ".js") {
w.Header().Set("Content-Type", "application/javascript; charset=utf-8") // Set the correct MIME type for JavaScript files
+137 -32
View File
@@ -20,6 +20,20 @@ import (
var RealPathCache = cache.NewCache(48*time.Hour, 72*time.Hour)
// actionConfig holds all configuration options for indexing operations
type actionConfig struct {
Quick bool // whether to perform a quick scan (skip unchanged directories)
Recursive bool // whether to recursively index subdirectories
}
// NewactionConfig creates a new actionConfig with common presets
func NewactionConfig() *actionConfig {
return &actionConfig{
Quick: false,
Recursive: true,
}
}
// reduced index is json exposed to the client
type ReducedIndex struct {
IdxName string `json:"name"`
@@ -65,6 +79,9 @@ const (
UNAVAILABLE IndexStatus = "unavailable"
)
// omitList contains directory names to skip during indexing
var omitList = []string{"$RECYCLE.BIN", "System Volume Information", "@eaDir"}
func init() {
indexes = make(map[string]*Index)
}
@@ -97,8 +114,13 @@ func Initialize(source settings.Source, mock bool) {
}
}
// indexDirectoryWithOptions wraps indexDirectory with actionConfig
func (idx *Index) indexDirectoryWithOptions(adjustedPath string, config *actionConfig) error {
return idx.indexDirectory(adjustedPath, config)
}
// Define a function to recursively index files and directories
func (idx *Index) indexDirectory(adjustedPath string, quick, recursive bool) error {
func (idx *Index) indexDirectory(adjustedPath string, config *actionConfig) error {
realPath := strings.TrimRight(idx.Path, "/") + adjustedPath
// Open the directory
dir, err := os.Open(realPath)
@@ -120,7 +142,7 @@ func (idx *Index) indexDirectory(adjustedPath string, quick, recursive bool) err
}
// if indexing, mark the directory as valid and indexed.
if recursive {
if config.Recursive {
// Prevent race conditions if scanning becomes concurrent in the future.
idx.mu.Lock()
idx.DirectoriesLedger[adjustedPath] = struct{}{}
@@ -143,14 +165,18 @@ func (idx *Index) indexDirectory(adjustedPath string, quick, recursive bool) err
// If the directory has not been modified since the last index, skip expensive readdir
// recursively check cached dirs for mod time changes as well
if recursive {
if config.Recursive {
if modChange {
idx.mu.Lock()
idx.FilesChangedDuringIndexing = true
idx.mu.Unlock()
} else if quick {
} else if config.Quick {
for _, item := range cacheDirItems {
err = idx.indexDirectory(combinedPath+item.Name, quick, true)
subConfig := &actionConfig{
Quick: config.Quick,
Recursive: true,
}
err = idx.indexDirectory(combinedPath+item.Name, subConfig)
if err != nil && err != errors.ErrNotIndexed {
logger.Errorf("error indexing directory %v : %v", combinedPath+item.Name, err)
}
@@ -158,7 +184,7 @@ func (idx *Index) indexDirectory(adjustedPath string, quick, recursive bool) err
return nil
}
}
dirFileInfo, err2 := idx.GetDirInfo(dir, dirInfo, realPath, adjustedPath, combinedPath, quick, recursive, true)
dirFileInfo, err2 := idx.GetDirInfo(dir, dirInfo, realPath, adjustedPath, combinedPath, config)
if err2 != nil {
return err2
}
@@ -194,7 +220,7 @@ func (idx *Index) GetFsDirInfo(adjustedPath string) (*iteminfo.FileInfo, error)
ModTime: dirInfo.ModTime(),
},
}
fileInfo.DetectType(adjustedPath, false)
fileInfo.DetectType(realPath, false)
return &fileInfo, nil
}
combinedPath := adjustedPath + "/"
@@ -202,7 +228,10 @@ func (idx *Index) GetFsDirInfo(adjustedPath string) (*iteminfo.FileInfo, error)
combinedPath = "/"
}
var response *iteminfo.FileInfo
response, err = idx.GetDirInfo(dir, dirInfo, realPath, adjustedPath, combinedPath, false, false, false)
response, err = idx.GetDirInfo(dir, dirInfo, realPath, adjustedPath, combinedPath, &actionConfig{
Quick: false,
Recursive: false,
})
if err != nil {
return nil, err
}
@@ -229,7 +258,7 @@ func (idx *Index) GetFsDirInfo(adjustedPath string) (*iteminfo.FileInfo, error)
}
func (idx *Index) GetDirInfo(dirInfo *os.File, stat os.FileInfo, realPath, adjustedPath, combinedPath string, quick, recursive, checkSkip bool) (*iteminfo.FileInfo, error) {
func (idx *Index) GetDirInfo(dirInfo *os.File, stat os.FileInfo, realPath, adjustedPath, combinedPath string, config *actionConfig) (*iteminfo.FileInfo, error) {
// Read directory contents
files, err := dirInfo.Readdir(-1)
if err != nil {
@@ -238,6 +267,13 @@ func (idx *Index) GetDirInfo(dirInfo *os.File, stat os.FileInfo, realPath, adjus
var totalSize int64
fileInfos := []iteminfo.ItemInfo{}
dirInfos := []iteminfo.ItemInfo{}
hasPreview := false
if !config.Recursive {
realDirInfo, exists := idx.GetMetadataInfo(adjustedPath, true)
if exists {
hasPreview = realDirInfo.HasPreview
}
}
// Process each file and directory in the current directory
for _, file := range files {
@@ -250,7 +286,7 @@ func (idx *Index) GetDirInfo(dirInfo *os.File, stat os.FileInfo, realPath, adjus
continue
}
}
if checkSkip && idx.shouldSkip(isDir, hidden, fullCombined, baseName) {
if idx.shouldSkip(isDir, hidden, fullCombined, baseName) {
continue
}
itemInfo := &iteminfo.ItemInfo{
@@ -261,7 +297,7 @@ func (idx *Index) GetDirInfo(dirInfo *os.File, stat os.FileInfo, realPath, adjus
if isDir {
dirPath := combinedPath + file.Name()
if idx.hasIndex && recursive && len(idx.Config.NeverWatchPaths) > 0 {
if idx.hasIndex && config.Recursive && len(idx.Config.NeverWatchPaths) > 0 {
if slices.Contains(idx.Config.NeverWatchPaths, fullCombined) {
realDirInfo, exists := idx.GetMetadataInfo(dirPath, true)
if exists {
@@ -271,15 +307,15 @@ func (idx *Index) GetDirInfo(dirInfo *os.File, stat os.FileInfo, realPath, adjus
}
}
// skip non-indexable dirs.
if file.Name() == "$RECYCLE.BIN" || file.Name() == "System Volume Information" {
if slices.Contains(omitList, file.Name()) {
continue
}
if recursive {
if config.Recursive {
// clear for garbage collection
file = nil
// Recursively index the subdirectory
err = idx.indexDirectory(dirPath, quick, recursive)
err = idx.indexDirectory(dirPath, config)
if err != nil {
logger.Errorf("Failed to index directory %s: %v", dirPath, err)
continue
@@ -288,24 +324,74 @@ func (idx *Index) GetDirInfo(dirInfo *os.File, stat os.FileInfo, realPath, adjus
realDirInfo, exists := idx.GetMetadataInfo(dirPath, true)
if exists {
itemInfo.Size = realDirInfo.Size
itemInfo.HasPreview = realDirInfo.HasPreview
}
totalSize += itemInfo.Size
itemInfo.Type = "directory"
dirInfos = append(dirInfos, *itemInfo)
if recursive {
if config.Recursive {
idx.NumDirs++
}
} else {
size, shouldCountSize := idx.handleFile(file, fullCombined)
itemInfo.DetectType(fullCombined, false)
itemInfo.DetectType(realPath+"/"+file.Name(), false)
simpleType := strings.Split(itemInfo.Type, "/")[0]
if simpleType == "audio" {
// Check if this file is new or changed by comparing with previous metadata
shouldCheckAlbumArt := false
previousInfo, exists := idx.GetReducedMetadata(fullCombined, false)
if !exists {
// File is new - check album art
shouldCheckAlbumArt = true
} else if previousInfo.ModTime != file.ModTime() {
// File has been modified - check album art
shouldCheckAlbumArt = true
} else {
// File unchanged - use cached album art info
itemInfo.HasPreview = previousInfo.HasPreview
}
if shouldCheckAlbumArt {
itemInfo.HasPreview = iteminfo.HasAlbumArt(realPath+"/"+file.Name(), filepath.Ext(file.Name()))
}
}
ext := strings.ToLower(filepath.Ext(file.Name()))
switch ext {
case ".jpg", ".jpeg", ".png", ".bmp", ".tiff":
itemInfo.HasPreview = true
case ".heic", ".heif":
if settings.Config.Integrations.Media.FfmpegPath != "" {
itemInfo.HasPreview = true
}
}
if simpleType == "image" {
itemInfo.HasPreview = true
}
if settings.Config.Integrations.Media.FfmpegPath != "" && simpleType == "video" {
itemInfo.HasPreview = true
}
itemInfo.Size = int64(size)
// Set HasPreview before appending to fileInfos
// these don't create preview for parent folders
if settings.Config.Integrations.OnlyOffice.Secret != "" && iteminfo.IsOnlyOffice(file.Name()) {
itemInfo.HasPreview = true
}
if iteminfo.HasDocConvertableExtension(itemInfo.Name, itemInfo.Type) {
itemInfo.HasPreview = true
}
fileInfos = append(fileInfos, *itemInfo)
if shouldCountSize {
totalSize += itemInfo.Size
}
if recursive {
if config.Recursive {
idx.NumFiles++
}
if itemInfo.HasPreview {
hasPreview = true
}
}
}
@@ -326,12 +412,14 @@ func (idx *Index) GetDirInfo(dirInfo *os.File, stat os.FileInfo, realPath, adjus
Folders: dirInfos,
}
dirFileInfo.ItemInfo = iteminfo.ItemInfo{
Name: filepath.Base(dirInfo.Name()),
Type: "directory",
Size: totalSize,
ModTime: stat.ModTime(),
Name: filepath.Base(dirInfo.Name()),
Type: "directory",
Size: totalSize,
ModTime: stat.ModTime(),
HasPreview: hasPreview,
}
dirFileInfo.SortItems()
return dirFileInfo, nil
}
@@ -391,29 +479,32 @@ func (idx *Index) GetRealPath(relativePath ...string) (string, bool, error) {
}
func (idx *Index) RefreshFileInfo(opts iteminfo.FileOptions) error {
refreshOptions := iteminfo.FileOptions{
Path: opts.Path,
IsDir: opts.IsDir,
config := &actionConfig{
Quick: false,
Recursive: opts.Recursive,
}
if !refreshOptions.IsDir {
refreshOptions.Path = idx.MakeIndexPath(filepath.Dir(refreshOptions.Path))
refreshOptions.IsDir = true
targetPath := opts.Path
if !opts.IsDir {
targetPath = idx.MakeIndexPath(filepath.Dir(targetPath))
}
err := idx.indexDirectory(refreshOptions.Path, false, false)
// Use the recursive flag from options - false for quick scan, true for recursive
err := idx.indexDirectoryWithOptions(targetPath, config)
if err != nil {
return err
}
file, exists := idx.GetMetadataInfo(refreshOptions.Path, true)
file, exists := idx.GetMetadataInfo(targetPath, true)
if !exists {
return fmt.Errorf("file/folder does not exist in metadata: %s", refreshOptions.Path)
return fmt.Errorf("file/folder does not exist in metadata: %s", targetPath)
}
current, firstExisted := idx.GetMetadataInfo(refreshOptions.Path, true)
current, firstExisted := idx.GetMetadataInfo(targetPath, true)
refreshParentInfo := firstExisted && current.Size != file.Size
//utils.PrintStructFields(*file)
result := idx.UpdateMetadata(file)
if !result {
return fmt.Errorf("file/folder does not exist in metadata: %s", refreshOptions.Path)
return fmt.Errorf("file/folder does not exist in metadata: %s", targetPath)
}
if !exists {
return nil
@@ -488,6 +579,13 @@ func (idx *Index) shouldSkip(isDir bool, isHidden bool, fullCombined, baseName s
}
}
}
if len(rules.FolderStartsWith) > 0 {
for _, start := range rules.FolderStartsWith {
if strings.HasPrefix(baseName, start) {
return true
}
}
}
} else {
if len(rules.FilePaths) > 0 {
for _, p := range rules.FilePaths {
@@ -506,6 +604,13 @@ func (idx *Index) shouldSkip(isDir bool, isHidden bool, fullCombined, baseName s
}
}
}
if len(rules.FileStartsWith) > 0 {
for _, start := range rules.FileStartsWith {
if strings.HasPrefix(baseName, start) {
return true
}
}
}
// Exclude if parent directory matches FolderPaths
if len(rules.FolderPaths) > 0 {
parent := filepath.Dir(fullCombined)
+6 -1
View File
@@ -131,6 +131,7 @@ func (idx *Index) RunIndexing(origin string, quick bool) {
return
}
idx.PreScan()
prevNumDirs := idx.NumDirs
prevNumFiles := idx.NumFiles
if quick {
@@ -147,7 +148,11 @@ func (idx *Index) RunIndexing(origin string, quick bool) {
startTime := time.Now()
idx.FilesChangedDuringIndexing = false
// Perform the indexing operation
err := idx.indexDirectory("/", quick, true)
config := &actionConfig{
Quick: quick,
Recursive: true,
}
err := idx.indexDirectory("/", config)
if err != nil {
logger.Errorf("Error during indexing: %v", err)
}
+197 -22
View File
@@ -1,6 +1,10 @@
package iteminfo
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"mime"
"net/http"
"os"
@@ -32,21 +36,30 @@ var SubtitleExts = []string{
".smi",
}
var MuPdfConvertable = []string{
".pdf", // PDF
".xps", // XPS
".epub", // EPUB
".mobi", // MOBI
".fb2", // FB2
".cbz", // CBZ
".svg", // SVG
".txt", // TXT
".docx", // DOCX
".pptx", // PPTX
".xlsx", // XLSX
".hwp", // HWP
".hwp", // HWPX
".md", // Markdown
var MuPdfConvertable = map[string]bool{
".pdf": true, // PDF
".xps": true, // XPS
".epub": true, // EPUB
".mobi": true, // MOBI
".fb2": true, // FB2
".cbz": true, // CBZ
".svg": true, // SVG
".txt": true, // TXT
".docx": true, // DOCX
".pptx": true, // PPTX
".xlsx": true, // XLSX
".hwp": true, // HWP
".hwpx": true, // HWPX
".md": true, // Markdown
}
var ResizableImageTypes = map[string]bool{
".jpg": true,
".jpeg": true,
".png": true,
".gif": true,
".bmp": true,
".other": false,
}
// Known bundle-style extensions that are technically directories but treated as files
@@ -184,6 +197,26 @@ var compressedFile = []string{
".zstd",
}
var audioMetadataTypes = []string{
".mp3",
".flac",
".ogg",
".m4a",
".mp4",
".wav",
".ape",
".wv",
}
func CouldHaveAlbumArt(extension string) bool {
for _, typefile := range audioMetadataTypes {
if extension == typefile {
return true
}
}
return false
}
func ExtendedMimeTypeCheck(extension string) string {
if IsDoc(extension) {
return "application/document"
@@ -267,14 +300,19 @@ func IsMatchingType(extension string, matchType string) bool {
// DetectType detects the MIME type of a file and updates the ItemInfo struct.
func (i *ItemInfo) DetectType(realPath string, saveContent bool) {
name := i.Name
ext := filepath.Ext(name)
ext := strings.ToLower(filepath.Ext(name))
// Attempt MIME detection by file extension
if ext == ".md" {
switch ext {
case ".md":
i.Type = "text/markdown"
return
case ".heic", ".heif":
i.Type = "image/heic"
return
}
i.Type = strings.Split(mime.TypeByExtension(ext), ";")[0]
if i.Type == "" {
i.Type = ExtendedMimeTypeCheck(ext)
}
@@ -285,10 +323,148 @@ func (i *ItemInfo) DetectType(realPath string, saveContent bool) {
i.Type = DetectTypeByHeader(realPath)
return
}
if i.Type == "blob" {
if i.Type == "blob" || i.Type == "" {
i.Type = DetectTypeByHeader(realPath)
}
}
if i.Type == "" || i.Type == "application/octet-stream" {
i.Type = "blob"
}
}
// hasAlbumArtLowLevel efficiently checks for album art in audio files.
// It handles ID3v2 tags (MP3) and Vorbis comments (FLAC, OGG) with low-level parsing.
func hasAlbumArtLowLevel(filePath string, extension string) (bool, error) {
file, err := os.Open(filePath)
if err != nil {
return false, fmt.Errorf("failed to open file: %w", err)
}
defer file.Close()
// Handle different audio formats
switch extension {
case ".mp3":
return hasAlbumArtMP3(file)
case ".flac", ".ogg":
return hasAlbumArtVorbis(file)
case ".m4a", ".mp4":
return hasAlbumArtM4A(file)
default:
// For other formats, return false (no album art detection)
return false, nil
}
}
// hasAlbumArtMP3 checks for APIC frames in ID3v2 tags
func hasAlbumArtMP3(file *os.File) (bool, error) {
// 1. Read the 10-byte ID3v2 header.
header := make([]byte, 10)
if _, err := io.ReadFull(file, header); err != nil {
return false, nil // No ID3v2 tag found
}
// 2. Check for the "ID3" identifier.
if string(header[0:3]) != "ID3" {
return false, nil // No ID3v2 tag found
}
// 3. Decode the tag size. It's a "synchsafe" integer.
tagSize := (int(header[6]) << 21) | (int(header[7]) << 14) | (int(header[8]) << 7) | int(header[9])
// 4. Read the entire tag content into a buffer.
tagData := make([]byte, tagSize)
if _, err := io.ReadFull(file, tagData); err != nil {
return false, fmt.Errorf("failed to read tag data: %w", err)
}
position := 0
// 5. Loop through the frames within the tag data.
for position < tagSize {
if position+10 > tagSize {
break
}
frameHeader := tagData[position : position+10]
frameID := string(frameHeader[0:4])
// We found it! The APIC frame contains the album art.
if frameID == "APIC" {
return true, nil
}
// If it's not APIC, find the frame's size to skip over it.
var frameSize uint32
if err := binary.Read(bytes.NewReader(frameHeader[4:8]), binary.BigEndian, &frameSize); err != nil {
return false, fmt.Errorf("corrupt frame header: %w", err)
}
// Move position to the next frame header.
position += 10 + int(frameSize)
// Break if the next frame would start with padding (null bytes).
if position >= tagSize || tagData[position] == 0 {
break
}
}
return false, nil
}
// hasAlbumArtVorbis checks for METADATA_BLOCK_PICTURE in Vorbis comments (FLAC, OGG)
func hasAlbumArtVorbis(file *os.File) (bool, error) {
// For FLAC files, look for METADATA_BLOCK_PICTURE in Vorbis comments
// This is a simplified check - in practice, you'd need to parse the FLAC structure
// For now, we'll do a basic search for common picture-related strings
buffer := make([]byte, 8192) // Read first 8KB
n, err := file.Read(buffer)
if err != nil && err != io.EOF {
return false, err
}
// Look for METADATA_BLOCK_PICTURE or COVERART in the buffer
content := string(buffer[:n])
if strings.Contains(content, "METADATA_BLOCK_PICTURE") ||
strings.Contains(content, "COVERART") ||
strings.Contains(content, "COVER_ART") {
return true, nil
}
return false, nil
}
// hasAlbumArtM4A checks for embedded artwork in M4A/MP4 files
func hasAlbumArtM4A(file *os.File) (bool, error) {
// For M4A files, look for 'covr' atom which contains artwork
// This is a simplified check - in practice, you'd need to parse the MP4 structure
buffer := make([]byte, 8192) // Read first 8KB
n, err := file.Read(buffer)
if err != nil && err != io.EOF {
return false, err
}
// Look for 'covr' atom in the buffer
content := string(buffer[:n])
if strings.Contains(content, "covr") {
return true, nil
}
return false, nil
}
func HasAlbumArt(filePath string, extension string) bool {
if !CouldHaveAlbumArt(extension) {
return false
}
// Use low-level detection for all audio formats
hasArt, err := hasAlbumArtLowLevel(filePath, extension)
if err != nil {
// If there's an error with low-level detection, return false
// This is safer than potentially crashing the indexing process
return false
}
return hasArt
}
// DetectTypeByHeader detects the MIME type of a file based on its header.
@@ -406,10 +582,9 @@ func HasDocConvertableExtension(name, mimetype string) bool {
return true
}
ext := strings.ToLower(filepath.Ext(name))
for _, e := range MuPdfConvertable {
if ext == e {
return true
}
val, ok := MuPdfConvertable[ext]
if ok {
return val
}
return false
}
+29 -12
View File
@@ -5,14 +5,16 @@ import (
"time"
"github.com/gtsteffaniak/filebrowser/backend/database/access"
"github.com/gtsteffaniak/filebrowser/backend/ffmpeg"
)
type ItemInfo struct {
Name string `json:"name"` // name of the file
Size int64 `json:"size"` // length in bytes for regular files
ModTime time.Time `json:"modified"` // modification time
Type string `json:"type"` // type of the file, either "directory" or a file mimetype
Hidden bool `json:"hidden"` // whether the file is hidden
Name string `json:"name"` // name of the file
Size int64 `json:"size"` // length in bytes for regular files
ModTime time.Time `json:"modified"` // modification time
Type string `json:"type"` // type of the file, either "directory" or a file mimetype
Hidden bool `json:"hidden"` // whether the file is hidden
HasPreview bool `json:"hasPreview"` // whether the file has a thumbnail preview
}
// FileInfo describes a file.
@@ -24,17 +26,31 @@ type FileInfo struct {
Path string `json:"path"` // path scoped to the associated index
}
// AudioMetadata contains metadata extracted from audio files
type AudioMetadata struct {
Title string `json:"title,omitempty"` // track title
Artist string `json:"artist,omitempty"` // track artist
Album string `json:"album,omitempty"` // album name
Year int `json:"year,omitempty"` // release year
Genre string `json:"genre,omitempty"` // music genre
Track int `json:"track,omitempty"` // track number
Duration int `json:"duration,omitempty"` // duration in seconds
AlbumArt string `json:"albumArt,omitempty"` // base64 encoded album art
}
// for efficiency, a response will be a pointer to the data
// extra calculated fields can be added here
type ExtendedFileInfo struct {
FileInfo
Content string `json:"content,omitempty"` // text content of a file, if requested
Subtitles []string `json:"subtitles,omitempty"` // subtitles for video files
Checksums map[string]string `json:"checksums,omitempty"` // checksums for the file
Token string `json:"token,omitempty"` // token for the file -- used for sharing
OnlyOfficeId string `json:"onlyOfficeId,omitempty"` // id for onlyoffice files
Source string `json:"source"` // associated index source for the file
RealPath string `json:"-"`
Content string `json:"content,omitempty"` // text content of a file, if requested
Subtitles []ffmpeg.SubtitleTrack `json:"subtitles,omitempty"` // subtitles for video files
AudioMeta *AudioMetadata `json:"audioMeta,omitempty"` // audio metadata for audio files
Checksums map[string]string `json:"checksums,omitempty"` // checksums for the file
Token string `json:"token,omitempty"` // token for the file -- used for sharing
OnlyOfficeId string `json:"onlyOfficeId,omitempty"` // id for onlyoffice files
Source string `json:"source,omitempty"` // associated index source for the file
Hash string `json:"hash,omitempty"` // hash for the file -- used for sharing
RealPath string `json:"-"`
}
// FileOptions are the options when getting a file info.
@@ -48,6 +64,7 @@ type FileOptions struct {
Expand bool
ReadHeader bool
Content bool
Recursive bool // whether to recursively index directories
}
func (f FileOptions) Components() (string, string) {
+27 -13
View File
@@ -8,29 +8,43 @@ import (
"strconv"
"strings"
"github.com/gtsteffaniak/filebrowser/backend/ffmpeg"
"github.com/gtsteffaniak/go-logger/logger"
)
type SubtitleTrack struct {
Name string `json:"name"` // filename for external, or descriptive name for embedded
Language string `json:"language,omitempty"` // language code
Title string `json:"title,omitempty"` // title/description
Index *int `json:"index,omitempty"` // stream index for embedded subtitles (nil for external)
Codec string `json:"codec,omitempty"` // codec name for embedded subtitles
IsFile bool `json:"isFile"` // true for external files, false for embedded
}
type FFProbeOutput struct {
Streams []struct {
Index int `json:"index"`
CodecType string `json:"codec_type"`
CodecName string `json:"codec_name"`
Tags map[string]string `json:"tags,omitempty"`
Disposition map[string]int `json:"disposition,omitempty"`
} `json:"streams"`
}
// detects subtitles for video files.
func (i *ExtendedFileInfo) DetectSubtitles(parentInfo *FileInfo) {
if !strings.HasPrefix(i.Type, "video") {
logger.Debug("subtitles are not supported for this file : " + i.Name)
return
}
ext := filepath.Ext(i.Name)
baseWithoutExt := strings.TrimSuffix(i.Name, ext)
for _, f := range parentInfo.Files {
baseName := strings.TrimSuffix(i.Name, ext)
if baseName != baseWithoutExt {
continue
}
// Use unified subtitle detection that finds both embedded and external
parentDir := filepath.Dir(i.RealPath)
i.Subtitles = ffmpeg.DetectAllSubtitles(i.RealPath, parentDir, i.ModTime)
}
for _, subtitleExt := range SubtitleExts {
if strings.HasSuffix(f.Name, subtitleExt) {
i.Subtitles = append(i.Subtitles, f.Name)
}
}
}
// LoadSubtitleContent loads the actual content for all detected subtitle tracks
func (i *ExtendedFileInfo) LoadSubtitleContent() error {
return ffmpeg.LoadAllSubtitleContent(i.RealPath, i.Subtitles, i.ModTime)
}
func (info *FileInfo) SortItems() {
+61
View File
@@ -18,6 +18,67 @@ func (idx *Index) UpdateMetadata(info *iteminfo.FileInfo) bool {
return true
}
// DeleteMetadata removes the specified path from the index.
// If recursive is true and the path is a directory, it will also remove all subdirectories.
func (idx *Index) DeleteMetadata(path string, isDir bool, recursive bool) bool {
idx.mu.Lock()
defer idx.mu.Unlock()
indexPath := idx.MakeIndexPath(path)
if !isDir {
// For files, remove from parent directory's Files slice
parentPath := idx.MakeIndexPath(filepath.Dir(path))
if parentDir, exists := idx.Directories[parentPath]; exists {
fileName := filepath.Base(path)
for i, file := range parentDir.Files {
if file.Name == fileName {
// Remove file from slice
parentDir.Files = append(parentDir.Files[:i], parentDir.Files[i+1:]...)
break
}
}
}
return true
}
// For directories
if recursive {
// Remove all subdirectories that start with this path
toDelete := []string{}
for dirPath := range idx.Directories {
if dirPath == indexPath || (len(dirPath) > len(indexPath) &&
dirPath[:len(indexPath)] == indexPath &&
(indexPath == "/" || dirPath[len(indexPath)] == '/')) {
toDelete = append(toDelete, dirPath)
}
}
for _, dirPath := range toDelete {
delete(idx.Directories, dirPath)
}
} else {
// Just remove this specific directory
delete(idx.Directories, indexPath)
}
// Remove from parent directory's Folders slice
if indexPath != "/" {
parentPath := idx.MakeIndexPath(filepath.Dir(path))
if parentDir, exists := idx.Directories[parentPath]; exists {
dirName := filepath.Base(path)
for i, folder := range parentDir.Folders {
if folder.Name == dirName {
// Remove folder from slice
parentDir.Folders = append(parentDir.Folders[:i], parentDir.Folders[i+1:]...)
break
}
}
}
}
return true
}
// GetMetadataInfo retrieves the FileInfo from the specified file or directory in the index.
func (idx *Index) GetReducedMetadata(target string, isDir bool) (*iteminfo.FileInfo, bool) {
idx.mu.RLock()
+36
View File
@@ -0,0 +1,36 @@
package preview
import (
"path/filepath"
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
"github.com/gtsteffaniak/filebrowser/backend/ffmpeg"
)
// convertHEICToJPEGWithFFmpeg converts a HEIC file to JPEG format using FFmpeg
// This function handles all FFmpeg-related logic and parameters
func (s *Service) convertHEICToJPEGWithFFmpeg(filePath string, previewSize string) ([]byte, error) {
// Create FFmpeg image service
imageService := ffmpeg.NewImageService(s.ffmpegPath, s.ffprobePath, s.debug, filepath.Join(settings.Config.Server.CacheDir, "heic", filepath.Base(filePath)))
// Determine target dimensions and quality based on preview size
var width, height int
var quality string
switch previewSize {
case "large":
width, height = 640, 640
quality = "2" // High quality for FFmpeg -q:v
case "original":
// For original size - no scaling, maximum quality
width, height = 0, 0 // Signal to not apply scaling
quality = "1" // Maximum quality for original
default:
width, height = 256, 256
quality = "5" // Medium quality
}
// Use tile-based conversion for correct full-resolution image reconstruction
result, err := imageService.ConvertHEICToJPEG(filePath, width, height, quality)
if err != nil {
return nil, err
}
return result, nil
}
+23 -4
View File
@@ -1,4 +1,3 @@
//go:generate go-enum --sql --marshal --file $GOFILE
package preview
import (
@@ -8,9 +7,9 @@ import (
"image"
"io"
"github.com/kovidgoyal/imaging"
exif "github.com/dsoprea/go-exif/v3"
exifcommon "github.com/dsoprea/go-exif/v3/common"
"github.com/kovidgoyal/imaging"
)
// Format is an image file format.
@@ -21,6 +20,7 @@ png
gif
tiff
bmp
heic
)
*/
type Format int
@@ -37,6 +37,8 @@ func (x Format) toImaging() imaging.Format {
return imaging.TIFF
case FormatBmp:
return imaging.BMP
case FormatHeic:
return imaging.JPEG
default:
return imaging.JPEG
}
@@ -73,6 +75,12 @@ fill
type ResizeMode int
func (s *Service) FormatFromExtension(ext string) (Format, error) {
// heic is not supported by imaging, so we return FormatHeic
switch ext {
case ".heic", ".heif":
return FormatHeic, nil
}
format, err := imaging.FormatFromExtension(ext)
if err != nil {
return -1, ErrUnsupportedFormat
@@ -139,6 +147,10 @@ func (s *Service) Resize(in io.Reader, width, height int, out io.Writer, options
option(&config)
}
if format == FormatHeic {
config.format = FormatJpeg
}
if config.quality == QualityLow && format == FormatJpeg {
thm, newWrappedReader, errThm := getEmbeddedThumbnail(wrappedReader)
wrappedReader = newWrappedReader
@@ -150,16 +162,19 @@ func (s *Service) Resize(in io.Reader, width, height int, out io.Writer, options
}
}
img, err := imaging.Decode(wrappedReader, imaging.AutoOrientation(true))
// For HEIC files, try without AutoOrientation first since it might not work properly
img, err := imaging.Decode(wrappedReader)
if err != nil {
return err
}
// Note: For HEIC files processed via FFmpeg, orientation is handled automatically
switch config.resizeMode {
case ResizeModeFill:
img = imaging.Fill(img, width, height, imaging.Center, config.quality.resampleFilter())
case ResizeModeFit:
fallthrough
img = imaging.Fit(img, width, height, config.quality.resampleFilter())
default:
img = imaging.Fit(img, width, height, config.quality.resampleFilter())
}
@@ -176,6 +191,10 @@ func (s *Service) detectFormat(in io.Reader) (Format, io.Reader, error) {
return 0, nil, fmt.Errorf("%s: %w", err.Error(), ErrUnsupportedFormat)
}
if imgFormat == "heif" {
imgFormat = "heic"
}
format, err := ParseFormat(imgFormat)
if err != nil {
return 0, nil, ErrUnsupportedFormat
+15 -11
View File
@@ -19,16 +19,19 @@ const (
FormatTiff
// FormatBmp is a Format of type Bmp
FormatBmp
// FormatHeic is a Format of type Heic
FormatHeic
)
const _FormatName = "jpegpnggiftiffbmp"
const _FormatName = "jpegpnggiftiffbmpheic"
var _FormatMap = map[Format]string{
0: _FormatName[0:4],
1: _FormatName[4:7],
2: _FormatName[7:10],
3: _FormatName[10:14],
4: _FormatName[14:17],
0: _FormatName[0:4], // jpeg
1: _FormatName[4:7], // png
2: _FormatName[7:10], // gif
3: _FormatName[10:14], // tiff
4: _FormatName[14:17], // bmp
5: _FormatName[17:21], // heic
}
// String implements the Stringer interface.
@@ -40,11 +43,12 @@ func (x Format) String() string {
}
var _FormatValue = map[string]Format{
_FormatName[0:4]: 0,
_FormatName[4:7]: 1,
_FormatName[7:10]: 2,
_FormatName[10:14]: 3,
_FormatName[14:17]: 4,
_FormatName[0:4]: 0, // jpeg
_FormatName[4:7]: 1, // png
_FormatName[7:10]: 2, // gif
_FormatName[10:14]: 3, // tiff
_FormatName[14:17]: 4, // bmp
_FormatName[17:21]: 5, // heic
}
// ParseFormat attempts to convert a string to a Format
+67 -34
View File
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"crypto/md5"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
@@ -13,10 +14,11 @@ import (
"runtime"
"strings"
"sync"
"time"
"github.com/gtsteffaniak/filebrowser/backend/adapters/fs/diskcache"
"github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils"
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
"github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo"
"github.com/gtsteffaniak/go-logger/logger"
)
@@ -52,12 +54,16 @@ func NewPreviewGenerator(concurrencyLimit int, ffmpegPath string, cacheDir strin
// No-op cache if no cacheDir is specified
fileCache = diskcache.NewNoOp()
}
// Create directories recursively with 0755 permissions
err := os.MkdirAll(filepath.Join(settings.Config.Server.CacheDir, "thumbnails", "docs"), 0755)
// Create directories recursively
err := os.MkdirAll(filepath.Join(settings.Config.Server.CacheDir, "thumbnails", "docs"), fileutils.PermDir)
if err != nil {
logger.Error(err)
}
err = os.MkdirAll(filepath.Join(settings.Config.Server.CacheDir, "thumbnails", "videos"), 0755)
err = os.MkdirAll(filepath.Join(settings.Config.Server.CacheDir, "thumbnails", "videos"), fileutils.PermDir)
if err != nil {
logger.Error(err)
}
err = os.MkdirAll(filepath.Join(settings.Config.Server.CacheDir, "heic"), fileutils.PermDir)
if err != nil {
logger.Error(err)
}
@@ -70,11 +76,11 @@ func NewPreviewGenerator(concurrencyLimit int, ffmpegPath string, cacheDir strin
logger.Fatalf("the configured ffmpeg path is not a valid ffprobe binary %s, err: %v", ffmpegPath, err)
}
if errprobe == nil && err == nil {
logger.Infof("Media Enabled : %v", errprobe == nil)
settings.Config.Integrations.Media.FfmpegPath = filepath.Base(ffmpegMainPath)
}
logger.Debugf("Media Enabled : %v", ffmpegMainPath != "" && ffprobePath != "")
settings.Config.Server.MuPdfAvailable = docEnabled()
logger.Infof("MuPDF Enabled : %v", settings.Config.Server.MuPdfAvailable)
logger.Debugf("MuPDF Enabled : %v", settings.Config.Server.MuPdfAvailable)
return &Service{
sem: make(chan struct{}, concurrencyLimit),
ffmpegPath: ffmpegMainPath,
@@ -90,16 +96,36 @@ func StartPreviewGenerator(concurrencyLimit int, ffmpegPath, cacheDir string) er
}
func GetPreviewForFile(file iteminfo.ExtendedFileInfo, previewSize, url string, seekPercentage int) ([]byte, error) {
if !AvailablePreview(file) {
if !file.HasPreview {
return nil, ErrUnsupportedMedia
}
cacheKey := CacheKey(file.RealPath, previewSize, file.ModTime, seekPercentage)
var thisMd5 string
if file.AudioMeta != nil && file.AudioMeta.AlbumArt != "" {
// md5 is based on album art
// md5 file.AlbumArt
hasher := md5.New()
_, _ = hasher.Write([]byte(file.AudioMeta.AlbumArt))
thisMd5 = hex.EncodeToString(hasher.Sum(nil))
file.Checksums = make(map[string]string)
file.Checksums["md5"] = thisMd5
} else {
var err error
thisMd5, err = utils.GetChecksum(file.RealPath, "md5")
if err != nil {
return nil, fmt.Errorf("failed to get checksum: %w", err)
}
// Ensure the file.Checksums map is initialized and MD5 is set
if file.Checksums == nil {
file.Checksums = make(map[string]string)
}
file.Checksums["md5"] = thisMd5
}
cacheKey := CacheKey(thisMd5, previewSize, seekPercentage)
if data, found, err := service.fileCache.Load(context.Background(), cacheKey); err != nil {
return nil, fmt.Errorf("failed to load from cache: %w", err)
} else if found {
return data, nil
}
return GeneratePreview(file, previewSize, url, seekPercentage)
}
@@ -109,9 +135,10 @@ func GeneratePreview(file iteminfo.ExtendedFileInfo, previewSize, officeUrl stri
err error
imageBytes []byte
)
// Generate thumbnail image from video
hasher := md5.New() //nolint:gosec
_, _ = hasher.Write([]byte(CacheKey(file.RealPath, previewSize, file.ModTime, seekPercentage)))
hasher := md5.New()
_, _ = hasher.Write([]byte(CacheKey(file.Checksums["md5"], previewSize, seekPercentage)))
hash := hex.EncodeToString(hasher.Sum(nil))
// Generate an image from office document
if iteminfo.HasDocConvertableExtension(file.Name, file.Type) {
@@ -125,8 +152,19 @@ func GeneratePreview(file iteminfo.ExtendedFileInfo, previewSize, officeUrl stri
if err != nil {
return nil, fmt.Errorf("failed to create image for office file: %w", err)
}
} else if strings.HasPrefix(file.Type, "image/heic") {
// HEIC files need FFmpeg conversion to JPEG with proper size/quality handling
imageBytes, err = service.convertHEICToJPEGWithFFmpeg(file.RealPath, previewSize)
if err != nil {
return nil, fmt.Errorf("failed to process HEIC image file: %w", err)
}
// For HEIC files, we've already done the resize/conversion, so cache and return directly
cacheKey := CacheKey(file.Checksums["md5"], previewSize, seekPercentage)
if err = service.fileCache.Store(context.Background(), cacheKey, imageBytes); err != nil {
logger.Errorf("failed to cache HEIC image: %v", err)
}
return imageBytes, nil
} else if strings.HasPrefix(file.Type, "image") {
// get image bytes from file
imageBytes, err = os.ReadFile(file.RealPath)
if err != nil {
return nil, fmt.Errorf("failed to read image file: %w", err)
@@ -141,6 +179,16 @@ func GeneratePreview(file iteminfo.ExtendedFileInfo, previewSize, officeUrl stri
if err != nil {
return nil, fmt.Errorf("failed to create image for video file: %w", err)
}
} else if strings.HasPrefix(file.Type, "audio") {
// Extract album artwork from audio files
if file.AudioMeta != nil && file.AudioMeta.AlbumArt != "" {
imageBytes, err = base64.StdEncoding.DecodeString(file.AudioMeta.AlbumArt)
if err != nil {
return nil, fmt.Errorf("failed to decode album artwork: %w", err)
}
} else {
return nil, fmt.Errorf("no album artwork available for audio file: %s", file.Name)
}
} else {
return nil, fmt.Errorf("unsupported media type: %s", ext)
}
@@ -155,15 +203,15 @@ func GeneratePreview(file iteminfo.ExtendedFileInfo, previewSize, officeUrl stri
return nil, fmt.Errorf("failed to resize preview image: %w", err)
}
// Cache and return
cacheKey := CacheKey(file.RealPath, previewSize, file.ModTime, seekPercentage)
cacheKey := CacheKey(file.Checksums["md5"], previewSize, seekPercentage)
if err := service.fileCache.Store(context.Background(), cacheKey, resizedBytes); err != nil {
logger.Errorf("failed to cache resized image: %v", err)
}
return resizedBytes, nil
} else {
cacheKey := CacheKey(file.RealPath, previewSize, file.ModTime, seekPercentage)
cacheKey := CacheKey(file.Checksums["md5"], previewSize, seekPercentage)
if err := service.fileCache.Store(context.Background(), cacheKey, imageBytes); err != nil {
logger.Errorf("failed to cache resized image: %v", err)
logger.Errorf("failed to cache original image: %v", err)
}
return imageBytes, nil
}
@@ -198,35 +246,20 @@ func (s *Service) CreatePreview(data []byte, previewSize string) ([]byte, error)
return output.Bytes(), nil
}
func CacheKey(realPath, previewSize string, modTime time.Time, percentage int) string {
return fmt.Sprintf("%x%x%x%x", realPath, modTime.Unix(), previewSize, percentage)
func CacheKey(md5, previewSize string, percentage int) string {
return fmt.Sprintf("%x%x%x", md5, previewSize, percentage)
}
func DelThumbs(ctx context.Context, file iteminfo.ExtendedFileInfo) {
errSmall := service.fileCache.Delete(ctx, CacheKey(file.RealPath, "small", file.ModTime, 0))
errSmall := service.fileCache.Delete(ctx, CacheKey(file.Checksums["md5"], "small", 0))
if errSmall != nil {
errLarge := service.fileCache.Delete(ctx, CacheKey(file.RealPath, "large", file.ModTime, 0))
errLarge := service.fileCache.Delete(ctx, CacheKey(file.Checksums["md5"], "large", 0))
if errLarge != nil {
logger.Debugf("Could not delete thumbnail: %v", file.Name)
}
}
}
func AvailablePreview(file iteminfo.ExtendedFileInfo) bool {
if strings.HasPrefix(file.Type, "video") && service.ffmpegPath != "" {
return true
}
if iteminfo.HasDocConvertableExtension(file.Name, file.Type) {
return true
}
ext := strings.ToLower(filepath.Ext(file.Name))
switch ext {
case ".jpg", ".jpeg", ".png", ".bmp", ".tiff":
return true
}
return file.OnlyOfficeId != ""
}
// CheckValidFFmpeg checks for a valid ffmpeg executable.
// If a path is provided, it looks there. Otherwise, it searches the system's PATH.
func CheckValidFFmpeg(path string) (string, error) {
+4 -71
View File
@@ -1,15 +1,9 @@
package preview
import (
"bytes"
"context"
"fmt"
"os"
"os/exec"
"strconv"
"strings"
"github.com/gtsteffaniak/go-logger/logger"
"github.com/gtsteffaniak/filebrowser/backend/ffmpeg"
)
// GenerateVideoPreview generates a single preview image from a video using ffmpeg.
@@ -21,69 +15,8 @@ func (s *Service) GenerateVideoPreview(videoPath, outputPath string, percentageS
return nil, err
}
defer s.release()
// Step 1: Get video duration from the container format
probeCmd := exec.Command(
s.ffprobePath,
"-v", "error",
// Use format=duration for better compatibility
"-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1",
videoPath,
)
var probeOut bytes.Buffer
probeCmd.Stdout = &probeOut
if s.debug {
probeCmd.Stderr = os.Stderr
}
if err := probeCmd.Run(); err != nil {
logger.Errorf("ffprobe command failed on file '%v' : %v", videoPath, err)
return nil, fmt.Errorf("ffprobe failed: %w", err)
}
durationStr := strings.TrimSpace(probeOut.String())
if durationStr == "" || durationStr == "N/A" {
logger.Errorf("could not determine video duration for file '%v' using duration info '%v'", videoPath, durationStr)
return nil, fmt.Errorf("could not determine video duration")
}
durationFloat, err := strconv.ParseFloat(durationStr, 64)
if err != nil {
// The original error you saw would be caught here if "N/A" was still the output
return nil, fmt.Errorf("invalid duration: %v", err)
}
if durationFloat <= 0 {
return nil, fmt.Errorf("video duration must be positive")
}
// The rest of your function remains the same...
// Step 2: Get the duration of the video in whole seconds
duration := int(durationFloat)
// Step 3: Calculate seek time based on percentageSeek (percentage value)
seekSeconds := duration * percentageSeek / 100
// Step 4: Convert seekSeconds to string for ffmpeg command
seekTime := strconv.Itoa(seekSeconds)
// Step 5: Extract frame at seek time
cmd := exec.Command(
s.ffmpegPath,
"-ss", seekTime,
"-i", videoPath,
"-frames:v", "1",
"-q:v", "10",
"-y", // overwrite output
outputPath,
)
if s.debug {
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
}
err = cmd.Run()
if err != nil {
return nil, fmt.Errorf("ffmpeg command failed on file '%v' : %w", videoPath, err)
}
return os.ReadFile(outputPath)
// Create a temporary video service for this operation
videoSvc := ffmpeg.NewVideoService(s.ffmpegPath, s.ffprobePath, 1, s.debug)
return videoSvc.GenerateVideoPreview(videoPath, outputPath, percentageSeek)
}
+243 -17
View File
@@ -854,6 +854,87 @@ const docTemplate = `{
}
}
},
"/api/media/subtitles": {
"get": {
"description": "Extracts embedded subtitle content from video files by stream index and returns raw WebVTT content",
"consumes": [
"application/json"
],
"produces": [
"text/vtt"
],
"tags": [
"Subtitles"
],
"summary": "Extract embedded subtitles",
"parameters": [
{
"type": "string",
"description": "Index path to the video file",
"name": "path",
"in": "query",
"required": true
},
{
"type": "string",
"description": "Source name for the desired source",
"name": "source",
"in": "query",
"required": true
},
{
"type": "integer",
"description": "Stream index for embedded subtitle extraction, defaults to 0",
"name": "index",
"in": "query"
}
],
"responses": {
"200": {
"description": "Raw WebVTT subtitle content",
"schema": {
"type": "string"
}
},
"400": {
"description": "Bad request",
"schema": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
},
"403": {
"description": "Forbidden",
"schema": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
},
"404": {
"description": "Resource not found",
"schema": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
},
"500": {
"description": "Internal server error",
"schema": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
}
}
}
},
"/api/preview": {
"get": {
"description": "Returns a preview image based on the requested path and size.",
@@ -1616,6 +1697,43 @@ const docTemplate = `{
}
}
},
"/api/settings/config": {
"get": {
"description": "Returns the current running configuration settings as YAML format with optional comments and filtering.",
"consumes": [
"application/json"
],
"produces": [
"text/plain"
],
"tags": [
"Settings"
],
"summary": "Get system settings as YAML",
"parameters": [
{
"type": "boolean",
"description": "Show all values (true) or only non-default values (false, default)",
"name": "full",
"in": "query"
},
{
"type": "boolean",
"description": "Include comments in YAML (true) or plain YAML (false, default)",
"name": "comments",
"in": "query"
}
],
"responses": {
"200": {
"description": "System settings in YAML format",
"schema": {
"type": "string"
}
}
}
}
},
"/api/share": {
"get": {
"description": "Retrieves all share links associated with a specific resource path for the current user.",
@@ -2431,6 +2549,10 @@ const docTemplate = `{
"$ref": "#/definitions/iteminfo.ItemInfo"
}
},
"hasPreview": {
"description": "whether the file has a thumbnail preview",
"type": "boolean"
},
"hidden": {
"description": "whether the file is hidden",
"type": "boolean"
@@ -2460,6 +2582,10 @@ const docTemplate = `{
"iteminfo.ItemInfo": {
"type": "object",
"properties": {
"hasPreview": {
"description": "whether the file has a thumbnail preview",
"type": "boolean"
},
"hidden": {
"description": "whether the file is hidden",
"type": "boolean"
@@ -2486,26 +2612,26 @@ const docTemplate = `{
"type": "object",
"properties": {
"adminPassword": {
"description": "the password of the admin user. If not set, the default is \"admin\".",
"description": "secret: the password of the admin user. If not set, the default is \"admin\".",
"type": "string"
},
"adminUsername": {
"description": "the username of the admin user. If not set, the default is \"admin\".",
"description": "secret: the username of the admin user. If not set, the default is \"admin\".",
"type": "string"
},
"key": {
"description": "the key used to sign the JWT tokens. If not set, a random key will be generated.",
"description": "secret: the key used to sign the JWT tokens. If not set, a random key will be generated.",
"type": "string"
},
"methods": {
"$ref": "#/definitions/settings.LoginMethods"
},
"tokenExpirationHours": {
"description": "the number of hours until the token expires. Default is 2 hours.",
"description": "time in hours each web UI session token is valid for. Default is 2 hours.",
"type": "integer"
},
"totpSecret": {
"description": "secret used to encrypt TOTP secrets",
"description": "secret: secret used to encrypt TOTP secrets",
"type": "string"
}
}
@@ -2547,6 +2673,13 @@ const docTemplate = `{
"type": "string"
}
},
"fileStartsWith": {
"description": "(global) exclude files that start with these prefixes. Eg. \"archive-\" or \"backup-\"",
"type": "array",
"items": {
"type": "string"
}
},
"folderEndsWith": {
"description": "(global) exclude folders that end with these suffixes. Eg. \".thumbnails\" or \".git\"",
"type": "array",
@@ -2568,6 +2701,13 @@ const docTemplate = `{
"type": "string"
}
},
"folderStartsWith": {
"description": "(global) exclude folders that start with these prefixes. Eg. \"archive-\" or \"backup-\"",
"type": "array",
"items": {
"type": "string"
}
},
"hidden": {
"description": "exclude hidden files and folders.",
"type": "boolean"
@@ -2599,9 +2739,25 @@ const docTemplate = `{
}
}
},
"settings.FfmpegConvert": {
"type": "object",
"properties": {
"imagePreview": {
"description": "supported image preview formats. default is heic",
"type": "object",
"additionalProperties": {
"type": "boolean"
}
}
}
},
"settings.Frontend": {
"type": "object",
"properties": {
"description": {
"description": "description that shows up in html head meta description",
"type": "string"
},
"disableDefaultLinks": {
"description": "disable default links in the sidebar",
"type": "boolean"
@@ -2620,6 +2776,10 @@ const docTemplate = `{
"$ref": "#/definitions/settings.ExternalLink"
}
},
"favicon": {
"description": "path to a favicon to use for the frontend",
"type": "string"
},
"name": {
"description": "display name",
"type": "string"
@@ -2709,6 +2869,14 @@ const docTemplate = `{
"settings.Media": {
"type": "object",
"properties": {
"convert": {
"description": "config for ffmpeg conversion settings",
"allOf": [
{
"$ref": "#/definitions/settings.FfmpegConvert"
}
]
},
"ffmpegPath": {
"description": "path to ffmpeg directory with ffmpeg and ffprobe (eg. /usr/local/bin)",
"type": "string"
@@ -2723,11 +2891,11 @@ const docTemplate = `{
"type": "string"
},
"clientId": {
"description": "client id of the OIDC application",
"description": "secret: client id of the OIDC application",
"type": "string"
},
"clientSecret": {
"description": "client secret of the OIDC application",
"description": "secret: client secret of the OIDC application",
"type": "string"
},
"createUser": {
@@ -2776,11 +2944,16 @@ const docTemplate = `{
"type": "string"
},
"secret": {
"description": "secret: authentication key for OnlyOffice integration",
"type": "string"
},
"url": {
"description": "The URL to the OnlyOffice Document Server, needs to be accessible to the user.",
"type": "string"
},
"viewOnly": {
"description": "view only mode for OnlyOffice",
"type": "boolean"
}
}
},
@@ -2885,6 +3058,10 @@ const docTemplate = `{
"description": "disable type detection by header, useful if filesystem is slow.",
"type": "boolean"
},
"disableUpdateCheck": {
"description": "disables backend update check service",
"type": "boolean"
},
"externalUrl": {
"description": "used by share links if set (eg. http://mydomain.com)",
"type": "string"
@@ -2903,6 +3080,10 @@ const docTemplate = `{
"description": "max pre-archive combined size of files/folder that are allowed to be archived (in GB)",
"type": "integer"
},
"minSearchLength": {
"description": "minimum length of search query to begin searching (default: 3)",
"type": "integer"
},
"numImageProcessors": {
"description": "number of concurrent image processing jobs used to create previews, default is number of cpu cores available.",
"type": "integer"
@@ -3013,6 +3194,10 @@ const docTemplate = `{
}
]
},
"indexAlbumArt": {
"description": "deprecated: always enabled since 0.8.6",
"type": "boolean"
},
"indexingIntervalMinutes": {
"description": "optional manual overide interval in minutes to re-index the source",
"type": "integer"
@@ -3073,6 +3258,10 @@ const docTemplate = `{
"description": "when false, the date is relative, when true, the date is an exact timestamp",
"type": "boolean"
},
"debugOffice": {
"description": "debug onlyoffice editor",
"type": "boolean"
},
"deleteWithoutConfirming": {
"description": "delete files without confirmation",
"type": "boolean"
@@ -3086,7 +3275,7 @@ const docTemplate = `{
"type": "string"
},
"disablePreviewExt": {
"description": "comma separated list of file extensions to disable preview for",
"description": "space separated list of file extensions to disable preview for",
"type": "string"
},
"disableQuickToggles": {
@@ -3106,7 +3295,7 @@ const docTemplate = `{
"type": "boolean"
},
"disableViewingExt": {
"description": "comma separated list of file extensions to disable viewing for",
"description": "space separated list of file extensions to disable viewing for",
"type": "string"
},
"editorQuickSave": {
@@ -3217,6 +3406,16 @@ const docTemplate = `{
"downloadsLimit": {
"type": "integer"
},
"enableOnlyOffice": {
"type": "boolean"
},
"enableOnlyOfficeEditing": {
"type": "boolean"
},
"enforceDarkLightMode": {
"description": "\"dark\" or \"light\"",
"type": "string"
},
"expires": {
"type": "string"
},
@@ -3261,6 +3460,7 @@ const docTemplate = `{
"type": "string"
},
"viewMode": {
"description": "default view mode for anonymous users: \"list\", \"compact\", \"normal\", \"gallery\"",
"type": "string"
}
}
@@ -3308,6 +3508,16 @@ const docTemplate = `{
"downloadsLimit": {
"type": "integer"
},
"enableOnlyOffice": {
"type": "boolean"
},
"enableOnlyOfficeEditing": {
"type": "boolean"
},
"enforceDarkLightMode": {
"description": "\"dark\" or \"light\"",
"type": "string"
},
"expire": {
"type": "integer"
},
@@ -3356,6 +3566,7 @@ const docTemplate = `{
"type": "integer"
},
"viewMode": {
"description": "default view mode for anonymous users: \"list\", \"compact\", \"normal\", \"gallery\"",
"type": "string"
}
}
@@ -3386,6 +3597,9 @@ const docTemplate = `{
"users.FileLoading": {
"type": "object",
"properties": {
"clearAll": {
"type": "boolean"
},
"maxConcurrentUpload": {
"type": "integer"
},
@@ -3434,32 +3648,40 @@ const docTemplate = `{
"description": "autoplay media files in preview",
"type": "boolean"
},
"defaultMediaPlayer": {
"description": "disable html5 media player and use the default media player",
"type": "boolean"
},
"disableHideSidebar": {
"description": "disable the hide sidebar preview for previews and editors",
"type": "boolean"
},
"folder": {
"description": "show thumbnail preview image for folder files",
"type": "boolean"
},
"highQuality": {
"description": "generate high quality preview images",
"description": "generate high quality thumbnail preview images",
"type": "boolean"
},
"image": {
"description": "show real image as icon instead of generic photo icon",
"description": "show thumbnail preview image for image files",
"type": "boolean"
},
"motionVideoPreview": {
"description": "show multiple frames for videos in preview when hovering",
"description": "show multiple frames for videos in thumbnail preview when hovering",
"type": "boolean"
},
"office": {
"description": "show preview image for office files",
"description": "show thumbnail preview image for office files",
"type": "boolean"
},
"popup": {
"description": "show larger popup preview when hovering",
"description": "show larger popup preview when hovering over thumbnail",
"type": "boolean"
},
"video": {
"description": "show preview image for video files",
"description": "show thumbnail preview image for video files",
"type": "boolean"
}
}
@@ -3507,6 +3729,10 @@ const docTemplate = `{
"description": "when false, the date is relative, when true, the date is an exact timestamp",
"type": "boolean"
},
"debugOffice": {
"description": "debug onlyoffice editor",
"type": "boolean"
},
"deleteWithoutConfirming": {
"description": "delete files without confirmation",
"type": "boolean"
@@ -3520,7 +3746,7 @@ const docTemplate = `{
"type": "string"
},
"disablePreviewExt": {
"description": "comma separated list of file extensions to disable preview for",
"description": "space separated list of file extensions to disable preview for",
"type": "string"
},
"disableQuickToggles": {
@@ -3539,7 +3765,7 @@ const docTemplate = `{
"type": "boolean"
},
"disableViewingExt": {
"description": "comma separated list of file extensions to disable viewing for",
"description": "space separated list of file extensions to disable viewing for",
"type": "string"
},
"editorQuickSave": {
+243 -17
View File
@@ -843,6 +843,87 @@
}
}
},
"/api/media/subtitles": {
"get": {
"description": "Extracts embedded subtitle content from video files by stream index and returns raw WebVTT content",
"consumes": [
"application/json"
],
"produces": [
"text/vtt"
],
"tags": [
"Subtitles"
],
"summary": "Extract embedded subtitles",
"parameters": [
{
"type": "string",
"description": "Index path to the video file",
"name": "path",
"in": "query",
"required": true
},
{
"type": "string",
"description": "Source name for the desired source",
"name": "source",
"in": "query",
"required": true
},
{
"type": "integer",
"description": "Stream index for embedded subtitle extraction, defaults to 0",
"name": "index",
"in": "query"
}
],
"responses": {
"200": {
"description": "Raw WebVTT subtitle content",
"schema": {
"type": "string"
}
},
"400": {
"description": "Bad request",
"schema": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
},
"403": {
"description": "Forbidden",
"schema": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
},
"404": {
"description": "Resource not found",
"schema": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
},
"500": {
"description": "Internal server error",
"schema": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
}
}
}
},
"/api/preview": {
"get": {
"description": "Returns a preview image based on the requested path and size.",
@@ -1605,6 +1686,43 @@
}
}
},
"/api/settings/config": {
"get": {
"description": "Returns the current running configuration settings as YAML format with optional comments and filtering.",
"consumes": [
"application/json"
],
"produces": [
"text/plain"
],
"tags": [
"Settings"
],
"summary": "Get system settings as YAML",
"parameters": [
{
"type": "boolean",
"description": "Show all values (true) or only non-default values (false, default)",
"name": "full",
"in": "query"
},
{
"type": "boolean",
"description": "Include comments in YAML (true) or plain YAML (false, default)",
"name": "comments",
"in": "query"
}
],
"responses": {
"200": {
"description": "System settings in YAML format",
"schema": {
"type": "string"
}
}
}
}
},
"/api/share": {
"get": {
"description": "Retrieves all share links associated with a specific resource path for the current user.",
@@ -2420,6 +2538,10 @@
"$ref": "#/definitions/iteminfo.ItemInfo"
}
},
"hasPreview": {
"description": "whether the file has a thumbnail preview",
"type": "boolean"
},
"hidden": {
"description": "whether the file is hidden",
"type": "boolean"
@@ -2449,6 +2571,10 @@
"iteminfo.ItemInfo": {
"type": "object",
"properties": {
"hasPreview": {
"description": "whether the file has a thumbnail preview",
"type": "boolean"
},
"hidden": {
"description": "whether the file is hidden",
"type": "boolean"
@@ -2475,26 +2601,26 @@
"type": "object",
"properties": {
"adminPassword": {
"description": "the password of the admin user. If not set, the default is \"admin\".",
"description": "secret: the password of the admin user. If not set, the default is \"admin\".",
"type": "string"
},
"adminUsername": {
"description": "the username of the admin user. If not set, the default is \"admin\".",
"description": "secret: the username of the admin user. If not set, the default is \"admin\".",
"type": "string"
},
"key": {
"description": "the key used to sign the JWT tokens. If not set, a random key will be generated.",
"description": "secret: the key used to sign the JWT tokens. If not set, a random key will be generated.",
"type": "string"
},
"methods": {
"$ref": "#/definitions/settings.LoginMethods"
},
"tokenExpirationHours": {
"description": "the number of hours until the token expires. Default is 2 hours.",
"description": "time in hours each web UI session token is valid for. Default is 2 hours.",
"type": "integer"
},
"totpSecret": {
"description": "secret used to encrypt TOTP secrets",
"description": "secret: secret used to encrypt TOTP secrets",
"type": "string"
}
}
@@ -2536,6 +2662,13 @@
"type": "string"
}
},
"fileStartsWith": {
"description": "(global) exclude files that start with these prefixes. Eg. \"archive-\" or \"backup-\"",
"type": "array",
"items": {
"type": "string"
}
},
"folderEndsWith": {
"description": "(global) exclude folders that end with these suffixes. Eg. \".thumbnails\" or \".git\"",
"type": "array",
@@ -2557,6 +2690,13 @@
"type": "string"
}
},
"folderStartsWith": {
"description": "(global) exclude folders that start with these prefixes. Eg. \"archive-\" or \"backup-\"",
"type": "array",
"items": {
"type": "string"
}
},
"hidden": {
"description": "exclude hidden files and folders.",
"type": "boolean"
@@ -2588,9 +2728,25 @@
}
}
},
"settings.FfmpegConvert": {
"type": "object",
"properties": {
"imagePreview": {
"description": "supported image preview formats. default is heic",
"type": "object",
"additionalProperties": {
"type": "boolean"
}
}
}
},
"settings.Frontend": {
"type": "object",
"properties": {
"description": {
"description": "description that shows up in html head meta description",
"type": "string"
},
"disableDefaultLinks": {
"description": "disable default links in the sidebar",
"type": "boolean"
@@ -2609,6 +2765,10 @@
"$ref": "#/definitions/settings.ExternalLink"
}
},
"favicon": {
"description": "path to a favicon to use for the frontend",
"type": "string"
},
"name": {
"description": "display name",
"type": "string"
@@ -2698,6 +2858,14 @@
"settings.Media": {
"type": "object",
"properties": {
"convert": {
"description": "config for ffmpeg conversion settings",
"allOf": [
{
"$ref": "#/definitions/settings.FfmpegConvert"
}
]
},
"ffmpegPath": {
"description": "path to ffmpeg directory with ffmpeg and ffprobe (eg. /usr/local/bin)",
"type": "string"
@@ -2712,11 +2880,11 @@
"type": "string"
},
"clientId": {
"description": "client id of the OIDC application",
"description": "secret: client id of the OIDC application",
"type": "string"
},
"clientSecret": {
"description": "client secret of the OIDC application",
"description": "secret: client secret of the OIDC application",
"type": "string"
},
"createUser": {
@@ -2765,11 +2933,16 @@
"type": "string"
},
"secret": {
"description": "secret: authentication key for OnlyOffice integration",
"type": "string"
},
"url": {
"description": "The URL to the OnlyOffice Document Server, needs to be accessible to the user.",
"type": "string"
},
"viewOnly": {
"description": "view only mode for OnlyOffice",
"type": "boolean"
}
}
},
@@ -2874,6 +3047,10 @@
"description": "disable type detection by header, useful if filesystem is slow.",
"type": "boolean"
},
"disableUpdateCheck": {
"description": "disables backend update check service",
"type": "boolean"
},
"externalUrl": {
"description": "used by share links if set (eg. http://mydomain.com)",
"type": "string"
@@ -2892,6 +3069,10 @@
"description": "max pre-archive combined size of files/folder that are allowed to be archived (in GB)",
"type": "integer"
},
"minSearchLength": {
"description": "minimum length of search query to begin searching (default: 3)",
"type": "integer"
},
"numImageProcessors": {
"description": "number of concurrent image processing jobs used to create previews, default is number of cpu cores available.",
"type": "integer"
@@ -3002,6 +3183,10 @@
}
]
},
"indexAlbumArt": {
"description": "deprecated: always enabled since 0.8.6",
"type": "boolean"
},
"indexingIntervalMinutes": {
"description": "optional manual overide interval in minutes to re-index the source",
"type": "integer"
@@ -3062,6 +3247,10 @@
"description": "when false, the date is relative, when true, the date is an exact timestamp",
"type": "boolean"
},
"debugOffice": {
"description": "debug onlyoffice editor",
"type": "boolean"
},
"deleteWithoutConfirming": {
"description": "delete files without confirmation",
"type": "boolean"
@@ -3075,7 +3264,7 @@
"type": "string"
},
"disablePreviewExt": {
"description": "comma separated list of file extensions to disable preview for",
"description": "space separated list of file extensions to disable preview for",
"type": "string"
},
"disableQuickToggles": {
@@ -3095,7 +3284,7 @@
"type": "boolean"
},
"disableViewingExt": {
"description": "comma separated list of file extensions to disable viewing for",
"description": "space separated list of file extensions to disable viewing for",
"type": "string"
},
"editorQuickSave": {
@@ -3206,6 +3395,16 @@
"downloadsLimit": {
"type": "integer"
},
"enableOnlyOffice": {
"type": "boolean"
},
"enableOnlyOfficeEditing": {
"type": "boolean"
},
"enforceDarkLightMode": {
"description": "\"dark\" or \"light\"",
"type": "string"
},
"expires": {
"type": "string"
},
@@ -3250,6 +3449,7 @@
"type": "string"
},
"viewMode": {
"description": "default view mode for anonymous users: \"list\", \"compact\", \"normal\", \"gallery\"",
"type": "string"
}
}
@@ -3297,6 +3497,16 @@
"downloadsLimit": {
"type": "integer"
},
"enableOnlyOffice": {
"type": "boolean"
},
"enableOnlyOfficeEditing": {
"type": "boolean"
},
"enforceDarkLightMode": {
"description": "\"dark\" or \"light\"",
"type": "string"
},
"expire": {
"type": "integer"
},
@@ -3345,6 +3555,7 @@
"type": "integer"
},
"viewMode": {
"description": "default view mode for anonymous users: \"list\", \"compact\", \"normal\", \"gallery\"",
"type": "string"
}
}
@@ -3375,6 +3586,9 @@
"users.FileLoading": {
"type": "object",
"properties": {
"clearAll": {
"type": "boolean"
},
"maxConcurrentUpload": {
"type": "integer"
},
@@ -3423,32 +3637,40 @@
"description": "autoplay media files in preview",
"type": "boolean"
},
"defaultMediaPlayer": {
"description": "disable html5 media player and use the default media player",
"type": "boolean"
},
"disableHideSidebar": {
"description": "disable the hide sidebar preview for previews and editors",
"type": "boolean"
},
"folder": {
"description": "show thumbnail preview image for folder files",
"type": "boolean"
},
"highQuality": {
"description": "generate high quality preview images",
"description": "generate high quality thumbnail preview images",
"type": "boolean"
},
"image": {
"description": "show real image as icon instead of generic photo icon",
"description": "show thumbnail preview image for image files",
"type": "boolean"
},
"motionVideoPreview": {
"description": "show multiple frames for videos in preview when hovering",
"description": "show multiple frames for videos in thumbnail preview when hovering",
"type": "boolean"
},
"office": {
"description": "show preview image for office files",
"description": "show thumbnail preview image for office files",
"type": "boolean"
},
"popup": {
"description": "show larger popup preview when hovering",
"description": "show larger popup preview when hovering over thumbnail",
"type": "boolean"
},
"video": {
"description": "show preview image for video files",
"description": "show thumbnail preview image for video files",
"type": "boolean"
}
}
@@ -3496,6 +3718,10 @@
"description": "when false, the date is relative, when true, the date is an exact timestamp",
"type": "boolean"
},
"debugOffice": {
"description": "debug onlyoffice editor",
"type": "boolean"
},
"deleteWithoutConfirming": {
"description": "delete files without confirmation",
"type": "boolean"
@@ -3509,7 +3735,7 @@
"type": "string"
},
"disablePreviewExt": {
"description": "comma separated list of file extensions to disable preview for",
"description": "space separated list of file extensions to disable preview for",
"type": "string"
},
"disableQuickToggles": {
@@ -3528,7 +3754,7 @@
"type": "boolean"
},
"disableViewingExt": {
"description": "comma separated list of file extensions to disable viewing for",
"description": "space separated list of file extensions to disable viewing for",
"type": "string"
},
"editorQuickSave": {
+183 -18
View File
@@ -100,6 +100,9 @@ definitions:
items:
$ref: '#/definitions/iteminfo.ItemInfo'
type: array
hasPreview:
description: whether the file has a thumbnail preview
type: boolean
hidden:
description: whether the file is hidden
type: boolean
@@ -121,6 +124,9 @@ definitions:
type: object
iteminfo.ItemInfo:
properties:
hasPreview:
description: whether the file has a thumbnail preview
type: boolean
hidden:
description: whether the file is hidden
type: boolean
@@ -140,22 +146,25 @@ definitions:
settings.Auth:
properties:
adminPassword:
description: the password of the admin user. If not set, the default is "admin".
description: 'secret: the password of the admin user. If not set, the default
is "admin".'
type: string
adminUsername:
description: the username of the admin user. If not set, the default is "admin".
description: 'secret: the username of the admin user. If not set, the default
is "admin".'
type: string
key:
description: the key used to sign the JWT tokens. If not set, a random key
will be generated.
description: 'secret: the key used to sign the JWT tokens. If not set, a random
key will be generated.'
type: string
methods:
$ref: '#/definitions/settings.LoginMethods'
tokenExpirationHours:
description: the number of hours until the token expires. Default is 2 hours.
description: time in hours each web UI session token is valid for. Default
is 2 hours.
type: integer
totpSecret:
description: secret used to encrypt TOTP secrets
description: 'secret: secret used to encrypt TOTP secrets'
type: string
type: object
settings.CustomTheme:
@@ -186,6 +195,12 @@ definitions:
items:
type: string
type: array
fileStartsWith:
description: (global) exclude files that start with these prefixes. Eg. "archive-"
or "backup-"
items:
type: string
type: array
folderEndsWith:
description: (global) exclude folders that end with these suffixes. Eg. ".thumbnails"
or ".git"
@@ -205,6 +220,12 @@ definitions:
items:
type: string
type: array
folderStartsWith:
description: (global) exclude folders that start with these prefixes. Eg.
"archive-" or "backup-"
items:
type: string
type: array
hidden:
description: exclude hidden files and folders.
type: boolean
@@ -227,8 +248,19 @@ definitions:
- text
- url
type: object
settings.FfmpegConvert:
properties:
imagePreview:
additionalProperties:
type: boolean
description: supported image preview formats. default is heic
type: object
type: object
settings.Frontend:
properties:
description:
description: description that shows up in html head meta description
type: string
disableDefaultLinks:
description: disable default links in the sidebar
type: boolean
@@ -242,6 +274,9 @@ definitions:
items:
$ref: '#/definitions/settings.ExternalLink'
type: array
favicon:
description: path to a favicon to use for the frontend
type: string
name:
description: display name
type: string
@@ -306,6 +341,10 @@ definitions:
type: object
settings.Media:
properties:
convert:
allOf:
- $ref: '#/definitions/settings.FfmpegConvert'
description: config for ffmpeg conversion settings
ffmpegPath:
description: path to ffmpeg directory with ffmpeg and ffprobe (eg. /usr/local/bin)
type: string
@@ -316,10 +355,10 @@ definitions:
description: if set, users in this group will be granted admin privileges.
type: string
clientId:
description: client id of the OIDC application
description: 'secret: client id of the OIDC application'
type: string
clientSecret:
description: client secret of the OIDC application
description: 'secret: client secret of the OIDC application'
type: string
createUser:
description: create user if not exists
@@ -357,11 +396,15 @@ definitions:
to bypass proxy.
type: string
secret:
description: 'secret: authentication key for OnlyOffice integration'
type: string
url:
description: The URL to the OnlyOffice Document Server, needs to be accessible
to the user.
type: string
viewOnly:
description: view only mode for OnlyOffice
type: boolean
required:
- secret
- url
@@ -440,6 +483,9 @@ definitions:
disableTypeDetectionByHeader:
description: disable type detection by header, useful if filesystem is slow.
type: boolean
disableUpdateCheck:
description: disables backend update check service
type: boolean
externalUrl:
description: used by share links if set (eg. http://mydomain.com)
type: string
@@ -455,6 +501,10 @@ definitions:
description: max pre-archive combined size of files/folder that are allowed
to be archived (in GB)
type: integer
minSearchLength:
description: 'minimum length of search query to begin searching (default:
3)'
type: integer
numImageProcessors:
description: number of concurrent image processing jobs used to create previews,
default is number of cpu cores available.
@@ -533,6 +583,9 @@ definitions:
allOf:
- $ref: '#/definitions/settings.IncludeIndexFilter'
description: include files and folders from indexing, if exclude is not set
indexAlbumArt:
description: 'deprecated: always enabled since 0.8.6'
type: boolean
indexingIntervalMinutes:
description: optional manual overide interval in minutes to re-index the source
type: integer
@@ -585,6 +638,9 @@ definitions:
description: when false, the date is relative, when true, the date is an exact
timestamp
type: boolean
debugOffice:
description: debug onlyoffice editor
type: boolean
deleteWithoutConfirming:
description: delete files without confirmation
type: boolean
@@ -595,7 +651,7 @@ definitions:
description: list of file extensions to disable onlyoffice editor for
type: string
disablePreviewExt:
description: comma separated list of file extensions to disable preview for
description: space separated list of file extensions to disable preview for
type: string
disableQuickToggles:
description: disable the quick toggles in the sidebar
@@ -610,7 +666,7 @@ definitions:
description: disable update notifications banner for admin users
type: boolean
disableViewingExt:
description: comma separated list of file extensions to disable viewing for
description: space separated list of file extensions to disable viewing for
type: string
editorQuickSave:
description: show quick save button in editor
@@ -690,6 +746,13 @@ definitions:
type: string
downloadsLimit:
type: integer
enableOnlyOffice:
type: boolean
enableOnlyOfficeEditing:
type: boolean
enforceDarkLightMode:
description: '"dark" or "light"'
type: string
expires:
type: string
favicon:
@@ -720,6 +783,8 @@ definitions:
unit:
type: string
viewMode:
description: 'default view mode for anonymous users: "list", "compact", "normal",
"gallery"'
type: string
type: object
share.Link:
@@ -751,6 +816,13 @@ definitions:
type: integer
downloadsLimit:
type: integer
enableOnlyOffice:
type: boolean
enableOnlyOfficeEditing:
type: boolean
enforceDarkLightMode:
description: '"dark" or "light"'
type: string
expire:
type: integer
favicon:
@@ -787,6 +859,8 @@ definitions:
userID:
type: integer
viewMode:
description: 'default view mode for anonymous users: "list", "compact", "normal",
"gallery"'
type: string
type: object
users.AuthToken:
@@ -806,6 +880,8 @@ definitions:
type: object
users.FileLoading:
properties:
clearAll:
type: boolean
maxConcurrentUpload:
type: integer
uploadChunkSizeMb:
@@ -839,26 +915,32 @@ definitions:
autoplayMedia:
description: autoplay media files in preview
type: boolean
defaultMediaPlayer:
description: disable html5 media player and use the default media player
type: boolean
disableHideSidebar:
description: disable the hide sidebar preview for previews and editors
type: boolean
folder:
description: show thumbnail preview image for folder files
type: boolean
highQuality:
description: generate high quality preview images
description: generate high quality thumbnail preview images
type: boolean
image:
description: show real image as icon instead of generic photo icon
description: show thumbnail preview image for image files
type: boolean
motionVideoPreview:
description: show multiple frames for videos in preview when hovering
description: show multiple frames for videos in thumbnail preview when hovering
type: boolean
office:
description: show preview image for office files
description: show thumbnail preview image for office files
type: boolean
popup:
description: show larger popup preview when hovering
description: show larger popup preview when hovering over thumbnail
type: boolean
video:
description: show preview image for video files
description: show thumbnail preview image for video files
type: boolean
type: object
users.Sorting:
@@ -891,6 +973,9 @@ definitions:
description: when false, the date is relative, when true, the date is an exact
timestamp
type: boolean
debugOffice:
description: debug onlyoffice editor
type: boolean
deleteWithoutConfirming:
description: delete files without confirmation
type: boolean
@@ -901,7 +986,7 @@ definitions:
description: deprecated
type: string
disablePreviewExt:
description: comma separated list of file extensions to disable preview for
description: space separated list of file extensions to disable preview for
type: string
disableQuickToggles:
description: disable the quick toggles in the sidebar
@@ -915,7 +1000,7 @@ definitions:
description: disable update notifications
type: boolean
disableViewingExt:
description: comma separated list of file extensions to disable viewing for
description: space separated list of file extensions to disable viewing for
type: string
editorQuickSave:
description: show quick save button in editor
@@ -1554,6 +1639,61 @@ paths:
summary: User login
tags:
- Auth
/api/media/subtitles:
get:
consumes:
- application/json
description: Extracts embedded subtitle content from video files by stream index
and returns raw WebVTT content
parameters:
- description: Index path to the video file
in: query
name: path
required: true
type: string
- description: Source name for the desired source
in: query
name: source
required: true
type: string
- description: Stream index for embedded subtitle extraction, defaults to 0
in: query
name: index
type: integer
produces:
- text/vtt
responses:
"200":
description: Raw WebVTT subtitle content
schema:
type: string
"400":
description: Bad request
schema:
additionalProperties:
type: string
type: object
"403":
description: Forbidden
schema:
additionalProperties:
type: string
type: object
"404":
description: Resource not found
schema:
additionalProperties:
type: string
type: object
"500":
description: Internal server error
schema:
additionalProperties:
type: string
type: object
summary: Extract embedded subtitles
tags:
- Subtitles
/api/preview:
get:
consumes:
@@ -2077,6 +2217,31 @@ paths:
summary: Get system settings
tags:
- Settings
/api/settings/config:
get:
consumes:
- application/json
description: Returns the current running configuration settings as YAML format
with optional comments and filtering.
parameters:
- description: Show all values (true) or only non-default values (false, default)
in: query
name: full
type: boolean
- description: Include comments in YAML (true) or plain YAML (false, default)
in: query
name: comments
type: boolean
produces:
- text/plain
responses:
"200":
description: System settings in YAML format
schema:
type: string
summary: Get system settings as YAML
tags:
- Settings
/api/share:
get:
consumes:
-740
View File
@@ -1,740 +0,0 @@
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 92478a24..5085e058 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,17 +11,16 @@ All notable changes to this project will be documented in this file. For commit
**New Features**:
- New access control system that works like shares. You can add new allow / deny rules for users/groups for specific paths on specific sources.
- #- The concept of 'groups', either automatically from OIDC groups claim or defined https://github.com/gtsteffaniak/filebrowser/issues/545
+ - The concept of 'groups', either automatically from OIDC groups claim or defined https://github.com/gtsteffaniak/filebrowser/issues/545
- share view changes -- now aligns with the standard listing view. This means files can be viewed and edited (if permission allows) just like a normal listing.
- many share links customization enhancements
- #- only share to certain authenticated users https://github.com/gtsteffaniak/filebrowser/issues/656 https://github.com/gtsteffaniak/filebrowser/issues/985
- #- one-time download links
- #- customize share theme, banner image, and icons https://github.com/gtsteffaniak/filebrowser/issues/827 https://github.com/gtsteffaniak/filebrowser/issues/1029
- #- share link info customization https://github.com/gtsteffaniak/filebrowser/issues/792 https://github.com/gtsteffaniak/filebrowser/issues/841 https://github.com/gtsteffaniak/filebrowser/issues/520
- #- "shared with me" and "share history" https://github.com/gtsteffaniak/filebrowser/issues/943
+ - only share to certain authenticated users https://github.com/gtsteffaniak/filebrowser/issues/656 https://github.com/gtsteffaniak/filebrowser/issues/985
+ - one-time download links
+ - customize share theme, banner image, and icons https://github.com/gtsteffaniak/filebrowser/issues/827 https://github.com/gtsteffaniak/filebrowser/issues/1029
+ - share link info customization https://github.com/gtsteffaniak/filebrowser/issues/792 https://github.com/gtsteffaniak/filebrowser/issues/841 https://github.com/gtsteffaniak/filebrowser/issues/520
+ - "shared with me" and "share history" https://github.com/gtsteffaniak/filebrowser/issues/943
- upload to share links https://github.com/gtsteffaniak/filebrowser/issues/661
- share link public changes https://github.com/gtsteffaniak/filebrowser/issues/473
- -
- public/private folder logic https://github.com/gtsteffaniak/filebrowser/issues/505
**BugFixes**:
diff --git a/backend/http/middleware.go b/backend/http/middleware.go
index 5ba397fe..595f00e1 100644
--- a/backend/http/middleware.go
+++ b/backend/http/middleware.go
@@ -6,7 +6,6 @@ import (
"encoding/json"
"fmt"
"net/http"
- "net/url"
"runtime"
"strings"
"time"
@@ -44,14 +43,8 @@ type handleFunc func(w http.ResponseWriter, r *http.Request, data *requestContex
// Middleware to handle file requests by hash and pass it to the handler
func withHashFileHelper(fn handleFunc) handleFunc {
return withOrWithoutUserHelper(func(w http.ResponseWriter, r *http.Request, data *requestContext) (int, error) {
+ path := r.URL.Query().Get("path")
hash := r.URL.Query().Get("hash")
- encodedPath := r.URL.Query().Get("path")
- // Decode the URL-encoded path
- path, err := url.QueryUnescape(encodedPath)
- if err != nil {
- return http.StatusBadRequest, fmt.Errorf("invalid path encoding: %v", err)
- }
- data.path = path
// Get the file link by hash
link, err := store.Share.GetByHash(hash)
if err != nil {
@@ -71,6 +64,11 @@ func withHashFileHelper(fn handleFunc) handleFunc {
return status, fmt.Errorf("could not authenticate share request")
}
}
+ data.path = strings.TrimSuffix(link.Path, "/") + "/" + strings.TrimPrefix(path, "/")
+ if path == "" || path == "/" {
+ data.path = link.Path
+ }
+
source, ok := config.Server.SourceMap[link.Source]
if !ok {
return http.StatusNotFound, fmt.Errorf("source not found")
diff --git a/backend/http/middleware_test.go b/backend/http/middleware_test.go
index ff7c173e..eb257951 100644
--- a/backend/http/middleware_test.go
+++ b/backend/http/middleware_test.go
@@ -155,20 +155,6 @@ func TestPublicShareHandlerAuthentication(t *testing.T) {
},
expectedStatusCode: 0, // zero means 200 on helpers
},
- {
- name: "Private share, valid password when token exists",
- share: &share.Link{
- Hash: "pw_and_token_hash",
- UserID: 1,
- PasswordHash: passwordBcrypt,
- Token: "some_random_token",
- Source: "/srv",
- },
- extraHeaders: map[string]string{
- "X-SHARE-PASSWORD": "password",
- },
- expectedStatusCode: 0, // zero means 200 on helpers
- },
{
name: "Private share, no auth provided",
share: &share.Link{
diff --git a/backend/http/public.go b/backend/http/public.go
index ef65dfa6..0e641fbd 100644
--- a/backend/http/public.go
+++ b/backend/http/public.go
@@ -7,6 +7,9 @@ import (
"net/url"
"strings"
+ "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/files"
+ "github.com/gtsteffaniak/filebrowser/backend/common/utils"
+ "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo"
"github.com/gtsteffaniak/go-logger/logger"
_ "github.com/gtsteffaniak/filebrowser/backend/swagger/docs"
@@ -49,7 +52,7 @@ func publicRawHandler(w http.ResponseWriter, r *http.Request, d *requestContext)
}
func publicShareHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
- d.fileInfo.Path = "/" + strings.TrimPrefix(d.fileInfo.Path, d.share.Path)
+ d.fileInfo.Path = strings.TrimPrefix(d.fileInfo.Path, d.share.Path)
return renderJSON(w, r, d.fileInfo)
}
@@ -91,5 +94,24 @@ func publicPreviewHandler(w http.ResponseWriter, r *http.Request, d *requestCont
if config.Server.DisablePreviews {
return http.StatusNotImplemented, fmt.Errorf("preview is disabled")
}
+ path := r.URL.Query().Get("path")
+ var err error
+ if path == "" {
+ return http.StatusBadRequest, fmt.Errorf("invalid request path")
+ }
+ fileInfo, err := files.FileInfoFaster(iteminfo.FileOptions{
+ Path: utils.JoinPathAsUnix(d.share.Path, path),
+ Modify: false, // TODO make this configurable
+ Source: d.fileInfo.Source,
+ Expand: true,
+ })
+ if err != nil {
+ logger.Debugf("public preview handler: error getting file info: %v", err)
+ return 400, fmt.Errorf("file not found")
+ }
+ if fileInfo.Type == "directory" {
+ return http.StatusBadRequest, fmt.Errorf("can't create preview for directory")
+ }
+ d.fileInfo = fileInfo
return previewHelperFunc(w, r, d)
}
diff --git a/frontend/src/api/index.js b/frontend/src/api/index.js
index 9399a292..2ef5f38e 100644
--- a/frontend/src/api/index.js
+++ b/frontend/src/api/index.js
@@ -7,3 +7,6 @@ import search from "./search";
// Note: shareApi has been consolidated into publicApi
export { filesApi, publicApi, usersApi, settingsApi, search, accessApi };
+
+// For backward compatibility, export publicApi as shareApi as well
+export { publicApi as shareApi };
diff --git a/frontend/src/api/public.js b/frontend/src/api/public.js
index 1dcb4125..d94713c5 100644
--- a/frontend/src/api/public.js
+++ b/frontend/src/api/public.js
@@ -2,7 +2,6 @@ import { fetchURL, fetchJSON, adjustedData } from "./utils";
import { notify } from "@/notify";
import { getApiPath, removePrefix } from "@/utils/url.js";
import { externalUrl, baseURL } from "@/utils/constants";
-import { state } from "@/store";
// ============================================================================
// PUBLIC API ENDPOINTS (hash-based authentication)
@@ -13,8 +12,7 @@ export async function fetchPub(path, hash, password = "", content = false) {
const params = {
path,
hash,
- ...(content && { content: 'true' }),
- ...(state.share.token && { token: state.share.token })
+ ...(content && { content: 'true' })
}
const apiPath = getApiPath("public/api/shared", params);
const response = await fetch(apiPath, {
@@ -24,17 +22,7 @@ export async function fetchPub(path, hash, password = "", content = false) {
});
if (!response.ok) {
- const error = new Error(response.statusText);
- // attempt to marshal json response
- let data = null;
- try {
- data = await response.json()
- } catch (e) {
- // ignore
- }
- if (data) {
- error.message = data.message;
- }
+ const error = new Error("Failed to connect to the server.");
error.status = response.status;
throw error;
}
@@ -57,14 +45,13 @@ export function getDownloadURL(share, files) {
}
// Generate a preview URL for public shares
-export function getPreviewURL(path) {
+export function getPreviewURL(hash, path) {
try {
const params = {
path: encodeURIComponent(path),
size: 'small',
- hash: state.share.hash,
- inline: 'true',
- ...(state.share.token && { token: state.share.token })
+ hash: hash,
+ inline: 'true'
}
const apiPath = getApiPath('public/api/preview', params)
return window.origin + apiPath
diff --git a/frontend/src/api/share.js b/frontend/src/api/share.js
new file mode 100644
index 00000000..729b7599
--- /dev/null
+++ b/frontend/src/api/share.js
@@ -0,0 +1,66 @@
+import { fetchURL, fetchJSON, adjustedData } from "./utils";
+import { notify } from "@/notify";
+import { getApiPath } from "@/utils/url.js";
+import { externalUrl } from "@/utils/constants";
+
+export async function list() {
+ const apiPath = getApiPath("api/shares");
+ return fetchJSON(apiPath);
+}
+
+export async function get(path, source) {
+ try {
+ const params = { path: encodeURIComponent(path), source: encodeURIComponent(source) };
+ const apiPath = getApiPath("api/share",params);
+ let data = fetchJSON(apiPath);
+ return adjustedData(data, path);
+ } catch (err) {
+ notify.showError(err.message || "Error fetching data");
+ throw err;
+ }
+}
+
+export async function remove(hash) {
+ const params = { hash };
+ const apiPath = getApiPath("api/share",params);
+ await fetchURL(apiPath, {
+ method: "DELETE",
+ });
+}
+
+export async function create(path, source, password = "", expires = "", unit = "hours") {
+ const params = { path: encodeURIComponent(path), source: encodeURIComponent(source) };
+ const apiPath = getApiPath("api/share",params);
+ let body = "{}";
+ if (password != "" || expires !== "" || unit !== "hours") {
+ body = JSON.stringify({ password: password, expires: expires, unit: unit });
+ }
+ return fetchJSON(apiPath, {
+ method: "POST",
+ body: body,
+ });
+}
+
+export function getShareURL(share) {
+ if (externalUrl) {
+ const apiPath = getApiPath(`share/${share.hash}`)
+ return externalUrl + apiPath
+ }
+ return window.origin+getApiPath(`share/${share.hash}`);
+}
+
+export function getPreviewURL(hash, path) {
+ try {
+ const params = {
+ path: encodeURIComponent(path),
+ size: 'small',
+ hash: hash,
+ inline: 'true'
+ }
+ const apiPath = getApiPath('api/public/preview', params)
+ return window.origin + apiPath
+ } catch (err) {
+ notify.showError(err.message || 'Error getting preview URL')
+ throw err
+ }
+}
diff --git a/frontend/src/components/files/ListingItem.vue b/frontend/src/components/files/ListingItem.vue
index 29c2749f..93848c1c 100644
--- a/frontend/src/components/files/ListingItem.vue
+++ b/frontend/src/components/files/ListingItem.vue
@@ -67,7 +67,7 @@ import { enableThumbs } from "@/utils/constants";
import downloadFiles from "@/utils/download";
import { getHumanReadableFilesize } from "@/utils/filesizes";
-import { filesApi,publicApi } from "@/api";
+import { filesApi, shareApi } from "@/api";
import * as upload from "@/utils/upload";
import { state, getters, mutations } from "@/store"; // Import your custom store
import { url } from "@/utils";
@@ -162,8 +162,8 @@ export default {
// @ts-ignore
let path = url.removeTrailingSlash(state.req.path) + "/" + this.name;
if (getters.isShare()) {
- let urlPath = getters.getSharePath(this.name) ;
- return publicApi.getPreviewURL(urlPath);
+ let urlPath = getters.getSharePath() + "/" + this.name;
+ return shareApi.getPreviewURL(state.share.hash, urlPath, state.req.modified);
}
// @ts-ignore
return filesApi.getPreviewURL(state.req.source, path, this.modified);
@@ -226,7 +226,7 @@ export default {
},
getUrl() {
if (this.hash) {
- return baseURL + "public/share/" + this.hash + "/" + url.encodedPath(this.path);
+ return baseURL + "share/" + this.hash + url.encodedPath(this.path);
}
if (serverHasMultipleSources) {
return baseURL + "files/" + encodeURIComponent(this.source) + url.encodedPath(this.path);
diff --git a/frontend/src/components/prompts/ActionApi.vue b/frontend/src/components/prompts/ActionApi.vue
index f2ebaa3f..1a381565 100644
--- a/frontend/src/components/prompts/ActionApi.vue
+++ b/frontend/src/components/prompts/ActionApi.vue
@@ -90,3 +90,20 @@ export default {
},
};
</script>
+
+<style>
+/* Basic styling for the prompt */
+.card.floating {
+ padding: 20px;
+}
+.card-content {
+ margin-bottom: 16px;
+}
+.card-action {
+ display: flex;
+ justify-content: flex-end;
+}
+.card-action .button {
+ margin-left: 8px;
+}
+</style>
diff --git a/frontend/src/components/prompts/Share.vue b/frontend/src/components/prompts/Share.vue
index be1ad5ad..8689100d 100644
--- a/frontend/src/components/prompts/Share.vue
+++ b/frontend/src/components/prompts/Share.vue
@@ -2,11 +2,10 @@
<div class="card-title">
<h2>{{ $t("buttons.share") }}</h2>
</div>
- <div class="card-content">
- <div aria-label="share-path" class="searchContext"> {{ $t('search.path') }} {{ subpath }}</div>
- <p> {{ $t('share.notice') }} </p>
-
- <div v-if="listing">
+ <div aria-label="share-path" class="searchContext"> {{ $t('search.path') }} {{ subpath }}</div>
+ <p> {{ $t('share.notice') }} </p>
+ <template v-if="listing">
+ <div class="card-content">
<table>
<tbody>
<tr>
@@ -46,7 +45,20 @@
</table>
</div>
- <div v-else>
+ <div class="card-action">
+ <button class="button button--flat button--grey" @click="closeHovers" :aria-label="$t('buttons.close')"
+ :title="$t('buttons.close')">
+ {{ $t("buttons.close") }}
+ </button>
+ <button class="button button--flat button--blue" @click="() => switchListing()" :aria-label="$t('buttons.new')"
+ :title="$t('buttons.new')">
+ {{ $t("buttons.new") }}
+ </button>
+ </div>
+ </template>
+
+ <template v-else>
+ <div class="card-content">
<p>{{ $t("settings.shareDuration") }}</p>
<div class="form-flex-group">
<input class="form-grow input flat-right" v-focus type="number" max="2147483647" min="1" @keyup.enter="submit" v-model.trim="time" />
@@ -58,7 +70,7 @@
</select>
</div>
<p>{{ $t("prompts.optionalPassword") }}</p>
- <input class="input" type="password" autocomplete="off" v-model.trim="password" />
+ <input class="input" type="password" v-model.trim="password" />
<div class="settings-items">
<ToggleSwitch class="item" v-model="readOnly" :name="'Read-only access'" />
@@ -80,32 +92,23 @@
</select>
</div>
</div>
- </div>
- <div class="card-action">
- <button v-if="listing" class="button button--flat button--grey" @click="closeHovers" :aria-label="$t('buttons.close')"
- :title="$t('buttons.close')">
- {{ $t("buttons.close") }}
- </button>
- <button v-if="listing" class="button button--flat button--blue" @click="() => switchListing()" :aria-label="$t('buttons.new')"
- :title="$t('buttons.new')">
- {{ $t("buttons.new") }}
- </button>
-
- <button v-if="!listing" class="button button--flat button--grey" @click="() => switchListing()" :aria-label="$t('buttons.cancel')"
- :title="$t('buttons.cancel')">
- {{ $t("buttons.cancel") }}
- </button>
- <button v-if="!listing" class="button button--flat button--blue" @click="submit" aria-label="Share-Confirm"
- :title="$t('buttons.share')">
- {{ $t("buttons.share") }}
- </button>
- </div>
+ <div class="card-action">
+ <button class="button button--flat button--grey" @click="() => switchListing()" :aria-label="$t('buttons.cancel')"
+ :title="$t('buttons.cancel')">
+ {{ $t("buttons.cancel") }}
+ </button>
+ <button class="button button--flat button--blue" @click="submit" aria-label="Share-Confirm"
+ :title="$t('buttons.share')">
+ {{ $t("buttons.share") }}
+ </button>
+ </div>
+ </template>
</template>
<script>
import { notify } from "@/notify";
import { state, getters, mutations } from "@/store";
-import { publicApi } from "@/api";
+import { shareApi, publicApi } from "@/api";
import Clipboard from "clipboard";
import { fromNow } from "@/utils/moment";
import { buildItemUrl } from "@/utils/url";
@@ -188,7 +191,7 @@ export default {
try {
// get last element of the path
- const links = await publicApi.get(this.subpath, this.source);
+ const links = await shareApi.get(this.subpath, this.source);
this.links = links;
} catch (err) {
notify.showError(err);
@@ -215,9 +218,9 @@ export default {
let isPermanent = !this.time || this.time == 0;
let res = null;
if (isPermanent) {
- res = await publicApi.create(this.subpath, this.source, this.password);
+ res = await shareApi.create(this.subpath, this.source, this.password);
} else {
- res = await publicApi.create(
+ res = await shareApi.create(
this.subpath,
this.source,
this.password,
@@ -241,7 +244,7 @@ export default {
async deleteLink(event, link) {
event.preventDefault();
try {
- await publicApi.remove(link.hash);
+ await shareApi.remove(link.hash);
this.links = this.links.filter((item) => item.hash !== link.hash);
if (this.links.length === 0) {
this.listing = false;
@@ -254,7 +257,7 @@ export default {
return fromNow(time, state.user.locale)
},
buildLink(share) {
- return publicApi.getShareURL(share);
+ return shareApi.getShareURL(share);
},
hasDownloadLink() {
if (state.isSearchActive) {
diff --git a/frontend/src/components/sidebar/General.vue b/frontend/src/components/sidebar/General.vue
index 58f02c10..0e030aeb 100644
--- a/frontend/src/components/sidebar/General.vue
+++ b/frontend/src/components/sidebar/General.vue
@@ -159,7 +159,7 @@ export default {
isStickySidebar: () => getters.isStickySidebar(),
isMobile: () => getters.isMobile(),
isListingView: () => getters.currentView() == "listingView",
- user: () => (state.user),
+ user: () => (console.log(state.user), state.user),
isDarkMode: () => getters.isDarkMode(),
showSources: () => !getters.isShare(),
currentPrompt: () => getters.currentPrompt(),
diff --git a/frontend/src/css/dashboard.css b/frontend/src/css/dashboard.css
index 2e1fbc8f..77da5938 100644
--- a/frontend/src/css/dashboard.css
+++ b/frontend/src/css/dashboard.css
@@ -226,10 +226,6 @@ body.rtl .card-title>*:first-child {
overflow: auto;
}
-.card-content h3 {
- text-align: center;
-}
-
.card h2 {
font-weight: 500;
}
diff --git a/frontend/src/store/getters.js b/frontend/src/store/getters.js
index cb062702..d97e7eed 100644
--- a/frontend/src/store/getters.js
+++ b/frontend/src/store/getters.js
@@ -201,9 +201,10 @@ export const getters = {
sharePathBase: () => {
return '/public/share/' + getters.shareHash() + '/'
},
- getSharePath: (subPath = "") => {
+ getSharePath: () => {
let urlPath = getters.routePath('public/share')
- return "/" + removeLeadingSlash(urlPath.split(state.share.hash)[1]) + "/" + subPath
+ let parts = urlPath.split('/')
+ return "/" + removeLeadingSlash(parts.slice(2).join('/'))
},
currentView: () => {
let listingView = ''
@@ -288,6 +289,7 @@ export const getters = {
},
currentPromptName: () => {
+ console.log("currentPromptName", state.prompts);
// Ensure state.prompts is an array
if (!Array.isArray(state.prompts) || state.prompts.length === 0) {
return ""
diff --git a/frontend/src/store/mutations.js b/frontend/src/store/mutations.js
index 8dc0b19f..b2b13461 100644
--- a/frontend/src/store/mutations.js
+++ b/frontend/src/store/mutations.js
@@ -191,6 +191,7 @@ export const mutations = {
emitStateChanged();
},
showHover: (value) => {
+ console.log("showHover", value);
if (typeof value === "object") {
state.prompts.push({
name: value?.name,
@@ -206,6 +207,7 @@ export const mutations = {
props: value?.props,
});
}
+ console.log("showHover", state.prompts);
emitStateChanged();
},
setLoading: (loadType, status) => {
@@ -221,6 +223,7 @@ export const mutations = {
emitStateChanged();
},
setCurrentUser: (value) => {
+ console.log('setCurrentUser', value);
try {
// If value is null or undefined, emit state change and exit early
if (!value) {
@@ -243,6 +246,7 @@ export const mutations = {
} catch (error) {
console.log(error);
}
+ console.log('setCurrentUser', state.user);
emitStateChanged();
},
setJWT: (value) => {
@@ -303,6 +307,7 @@ export const mutations = {
if (!state.user) {
state.user = {};
}
+ console.log('updateCurrentUser', value);
// Store previous state for comparison
const previousUser = { ...state.user };
@@ -315,12 +320,14 @@ export const mutations = {
i18n.default.locale = state.user.locale;
localStorage.setItem("userLocale", state.user.locale);
}
+ console.log('updateCurrentUser2', state.user);
// Update localStorage if stickySidebar exists
if (state.user.stickySidebar && getters.currentView() == "listingView") {
state.multiButtonState = "menu";
} else if (state.showSidebar) {
state.multiButtonState = "back";
}
+ console.log('updateCurrentUser3', state.user);
// Update users if there's any change in state.user
if (JSON.stringify(state.user) !== JSON.stringify(previousUser)) {
// Only update the properties that were actually provided in the input
diff --git a/frontend/src/views/Files.vue b/frontend/src/views/Files.vue
index 4c69ecd7..6f8b892b 100644
--- a/frontend/src/views/Files.vue
+++ b/frontend/src/views/Files.vue
@@ -9,9 +9,8 @@
<div class="card-title">
<h2>{{ $t("general.password") }}</h2>
</div>
- <div class="card-content form-flex-group">
+ <div class="card-content">
<input
- class="input share-password"
v-focus
type="password"
:placeholder="$t('general.password')"
@@ -149,10 +148,8 @@ export default {
});
// Add glow effect
element.classList.add('scroll-glow');
- console.log("scrollToHash", element)
// Remove glow effect after animation completes
setTimeout(() => {
- console.log("scrollToHash remove glow", element)
element.classList.remove('scroll-glow');
}, 1000);
}
@@ -211,15 +208,19 @@ export default {
this.shareHash = parts[1]
this.shareSubPath = "/" + parts.slice(2).join("/");
+ // Store share data in state for use by components
+ mutations.setShareData({
+ hash: this.shareHash,
+ token: this.shareToken,
+ subPath: this.shareSubPath,
+ });
+
// Handle password
- if (this.sharePassword === "") {
+ if (this.sharePassword === "" || this.sharePassword === null) {
this.sharePassword = localStorage.getItem("sharepass:" + this.shareHash);
} else {
localStorage.setItem("sharepass:" + this.shareHash, this.sharePassword);
}
- if (this.sharePassword === null) {
- this.sharePassword = "";
- }
mutations.resetSelected();
mutations.setMultiple(false);
@@ -229,15 +230,11 @@ export default {
let file = await publicApi.fetchPub(this.shareSubPath, this.shareHash, this.sharePassword);
file.hash = this.shareHash;
this.shareToken = file.token;
- // Store share data in state for use by components
- mutations.setShareData({
- hash: this.shareHash,
- token: this.shareToken,
- subPath: this.shareSubPath,
- });
+
// If not a directory, fetch content for preview components
if (file.type != "directory") {
const content = !getters.fileViewingDisabled(file.name);
+
file = await publicApi.fetchPub(this.shareSubPath, this.shareHash, this.sharePassword, content);
file.hash = this.shareHash;
this.shareToken = file.token;
@@ -324,7 +321,7 @@ export default {
};
</script>
-<style>
+<style scoped>
.share__wrong__password {
color: #ff4757;
text-align: center;
@@ -351,8 +348,4 @@ export default {
color: inherit;
}
}
-
-.share-password {
- width: 100%;
-}
</style>
diff --git a/frontend/src/views/Settings.vue b/frontend/src/views/Settings.vue
index 4547e3d2..38d75dc1 100644
--- a/frontend/src/views/Settings.vue
+++ b/frontend/src/views/Settings.vue
@@ -122,4 +122,7 @@ export default {
background-color: var(--surfaceSecondary);
}
+.card-content {
+ padding: 1em;
+}
</style>
diff --git a/frontend/src/views/settings/Profile.vue b/frontend/src/views/settings/Profile.vue
index f65fe30f..e34e405a 100644
--- a/frontend/src/views/settings/Profile.vue
+++ b/frontend/src/views/settings/Profile.vue
@@ -428,6 +428,9 @@ export default {
</script>
<style scoped>
+.card-content h3 {
+ text-align: center;
+}
#disablePreviews,
#disableViewing,
diff --git a/frontend/src/views/settings/Shares.vue b/frontend/src/views/settings/Shares.vue
index cd28af70..6d39166e 100644
--- a/frontend/src/views/settings/Shares.vue
+++ b/frontend/src/views/settings/Shares.vue
@@ -49,7 +49,7 @@
<script>
import { notify } from "@/notify";
-import { publicApi } from "@/api";
+import { shareApi } from "@/api";
import { state, mutations, getters } from "@/store";
import Clipboard from "clipboard";
import Errors from "@/views/Errors.vue";
@@ -70,7 +70,7 @@ export default {
async created() {
mutations.setLoading("shares", true);
try {
- let links = await publicApi.list();
+ let links = await shareApi.list();
if (links.length === 0) {
this.links = [];
return;
@@ -115,7 +115,7 @@ export default {
mutations.closeHovers();
try {
- publicApi.remove(link.hash);
+ shareApi.remove(link.hash);
this.links = this.links.filter((item) => item.hash !== link.hash);
notify.showSuccess(this.$t("settings.shareDeleted"));
} catch (e) {
@@ -128,7 +128,7 @@ export default {
return fromNow(time);
},
buildLink(share) {
- return publicApi.getShareURL(share);
+ return shareApi.getShareURL(share);
},
},
};
-2
View File
@@ -55,8 +55,6 @@
"shallowOnly": true
}
]
// no-undef is already included in
// @vue/eslint-config-typescript
},
"parserOptions": {
"ecmaVersion": "latest",
+2
View File
@@ -21,6 +21,7 @@
},
"dependencies": {
"@onlyoffice/document-editor-vue": "^1.4.0",
"@skjnldsv/vue-plyr": "^7.5.0",
"ace-builds": "^1.24.2",
"axios": "^1.7.9",
"clipboard": "^2.0.4",
@@ -54,6 +55,7 @@
"fs-extra": "^11.3.0",
"jsdom": "^25.0.1",
"vite": "^6.2.0",
"vite-plugin-checker": "^0.10.3",
"vite-plugin-compression2": "^1.0.0",
"vitest": "^3.0.7",
"vue-tsc": "^2.0.7"
+30 -17
View File
@@ -1,4 +1,6 @@
server:
minSearchLength: 3 # minimum length of search query to begin searching (default: 3)
disableUpdateCheck: false # disables backend update check service
numImageProcessors: 4 # number of concurrent image processing jobs used to create previews, default is number of cpu cores available.
socket: "" # socket to listen on
tlsKey: "" # path to TLS key
@@ -37,6 +39,8 @@ server:
folderNames: []
fileEndsWith: []
folderEndsWith: []
fileStartsWith: []
folderStartsWith: []
include: # include files and folders from indexing, if exclude is not set
rootFolders: []
rootFiles: []
@@ -48,7 +52,7 @@ server:
cacheDir: "tmp" # path to the cache directory, used for thumbnails and other cached files
maxArchiveSize: 50 # max pre-archive combined size of files/folder that are allowed to be archived (in GB)
auth:
tokenExpirationHours: 2 # the number of hours until the token expires. Default is 2 hours.
tokenExpirationHours: 2 # time in hours each web UI session token is valid for. Default is 2 hours.
methods:
proxy: # validate:omitempty
enabled: false
@@ -67,8 +71,8 @@ auth:
enforcedOtp: false # if set to true, TOTP is enforced for all password users users. Otherwise, users can choose to enable TOTP.
oidc: # validate:omitempty
enabled: false # whether to enable OIDC authentication
clientId: "" # client id of the OIDC application
clientSecret: "" # client secret of the OIDC application
clientId: "**hidden**" # secret: client id of the OIDC application
clientSecret: "**hidden**" # secret: client secret of the OIDC application
issuerUrl: "" # authorization URL of the OIDC provider
scopes: "openid email profile" # scopes to request from the OIDC provider
userIdentifier: "preferred_username" # the field value to use as the username. Default is "preferred_username", can also be "email" or "username", or "phone"
@@ -77,10 +81,10 @@ auth:
createUser: false # create user if not exists
adminGroup: "" # if set, users in this group will be granted admin privileges.
groupsClaim: "groups" # the JSON field name to read groups from. Default is "groups"
key: "" # the key used to sign the JWT tokens. If not set, a random key will be generated.
adminUsername: "admin" # the username of the admin user. If not set, the default is "admin".
adminPassword: "admin" # the password of the admin user. If not set, the default is "admin".
totpSecret: "" # secret used to encrypt TOTP secrets
key: "**hidden**" # secret: the key used to sign the JWT tokens. If not set, a random key will be generated.
adminUsername: "**hidden**" # secret: the username of the admin user. If not set, the default is "admin".
adminPassword: "**hidden**" # secret: the password of the admin user. If not set, the default is "admin".
totpSecret: "**hidden**" # secret: secret used to encrypt TOTP secrets
frontend:
name: "FileBrowser Quantum" # display name
disableDefaultLinks: false # disable default links in the sidebar
@@ -91,19 +95,21 @@ frontend:
url: "https://github.com/gtsteffaniak/filebrowser/releases/" # the url to link to validate:required
- text: "Help" # the text to display on the link validate:required
title: "" # the title to display on hover
url: "https://github.com/gtsteffaniak/filebrowser/wiki" # the url to link to validate:required
url: "help prompt" # the url to link to validate:required
disableNavButtons: false # disable the nav buttons in the sidebar
styling:
customCSS: "" # if a valid path to a css file is provided, it will be applied for all users. (eg. "reduce-rounded-corners.css")
lightBackground: "#f5f5f5" # specify a valid CSS color property value to use as the background color in light mode
darkBackground: "#141D24" # Specify a valid CSS color property value to use as the background color in dark mode
customThemes: # A list of custom css files that each user can select to override the default styling. if "default" is key name then it will be the default option.
alternative:
description: Reduce rounded corners
css: reduce-rounded-corners.css
default:
description: The default theme
css: ""
description: "The default theme" # The description of the theme to display in the UI.
css: "" # The css file path and filename to use for the theme.
alternative:
description: "Reduce rounded corners" # The description of the theme to display in the UI.
css: "reduce-rounded-corners.css" # The css file path and filename to use for the theme.
favicon: "" # path to a favicon to use for the frontend
description: "FileBrowser Quantum is a file manager for the web which can be used to manage files on your server" # description that shows up in html head meta description
userDefaults:
editorQuickSave: false # show quick save button in editor
hideSidebarFileActions: false # hide the file actions in the sidebar
@@ -119,8 +125,8 @@ userDefaults:
gallerySize: 3 # 0-9 - the size of the gallery thumbnails
themeColor: "var(--blue)" # theme color to use: eg. #ff0000, or var(--red), var(--purple), etc
quickDownload: false # show icon to download in one click
disablePreviewExt: "" # comma separated list of file extensions to disable preview for
disableViewingExt: "" # comma separated list of file extensions to disable viewing for
disablePreviewExt: "" # space separated list of file extensions to disable preview for
disableViewingExt: "" # space separated list of file extensions to disable viewing for
lockPassword: false # disable the user from changing their password
disableSettings: false # disable the user from viewing the settings page
preview:
@@ -132,6 +138,8 @@ userDefaults:
office: false
popup: false
autoplayMedia: false
defaultMediaPlayer: false
folder: false
permissions:
api: false
admin: false
@@ -144,14 +152,19 @@ userDefaults:
fileLoading: # upload and download settings
maxConcurrentUpload: 10
uploadChunkSizeMb: 10
disableOfficePreviewExt: "" # deprecated: use disablePreviewExt instead
clearAll: false
disableOnlyOfficeExt: "" # list of file extensions to disable onlyoffice editor for
customTheme: "" # Name of theme to use chosen from custom themes config.
showSelectMultiple: false # show select multiple files on desktop
debugOffice: false # debug onlyoffice editor
integrations:
office: # validate:omitempty
url: "" # The URL to the OnlyOffice Document Server, needs to be accessible to the user. validate:required
internalUrl: "" # An optional internal address that the filebrowser server can use to communicate with the OnlyOffice Document Server, could be useful to bypass proxy.
secret: "" # validate:required
secret: "**hidden**" # secret: authentication key for OnlyOffice integration validate:required
viewOnly: false # view only mode for OnlyOffice
media: # validate:omitempty
ffmpegPath: "" # path to ffmpeg directory with ffmpeg and ffprobe (eg. /usr/local/bin)
convert: # config for ffmpeg conversion settings
imagePreview: # supported image preview formats. default is heic
heic: false
+18 -17
View File
@@ -7,49 +7,50 @@
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<title>{{ .title }}</title>
<link rel="icon" type="image/png" sizes="256x256" href="{{ .favicon }}">
<link rel="icon" type="image/png" sizes="256x256" href="{{ .htmlVars.favicon }}">
<!--<link href="https://fonts.googleapis.com/css?family=Material+Icons|Material+Symbols+Outlined" rel="stylesheet">-->
<!-- Add to home screen for Android and modern mobile browsers -->
<link rel="manifest" id="manifestPlaceholder" crossorigin="use-credentials">
<meta name="theme-color" content="{{ .color }}">
<meta name="theme-color" content="{{ .htmlVars.color }}">
<!-- Add to home screen for Safari on iOS/iPadOS -->
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="assets">
<link rel="apple-touch-icon" sizes="180x180" href="{{ .appIcon }}">
<link rel="apple-touch-icon" sizes="180x180" href="{{ .htmlVars.appIcon }}">
<!-- Add to home screen for Windows -->
<meta name="msapplication-TileImage" content="{{ .winIcon }}">
<meta name="msapplication-TileColor" content="{{ .color }}">
<meta name="msapplication-TileImage" content="{{ .htmlVars.winIcon }}">
<meta name="msapplication-TileColor" content="{{ .htmlVars.color }}">
<meta name="description" content="{{ .description }}">
<meta name="description" content="{{ .htmlVars.description }}">
<link rel="canonical" href="https://github.com/gtsteffaniak/filebrowser">
<link rel="canonical" href="https://github.com/gtsteffaniak">
<link rel="canonical" href="https://github.com/quantumx-apps">
<!-- Inject Some Variables and generate the manifest json -->
<script>
window.filebrowser = JSON.parse('{{ .globalVars }}');
window.globalVars = {{ .globalVars }};
window.shareVars = {{ .shareVars }};
var dynamicManifest = {
"name": window.filebrowser.name || 'FileBrowser Quantum',
"name": window.globalVars.name || 'FileBrowser Quantum',
"icons": [
{
"src": window.location.origin + "{{ .staticURL }}/img/icons/android-chrome-256x256.png",
"src": window.location.origin + "{{ .htmlVars.staticURL }}/img/icons/android-chrome-256x256.png",
"sizes": "512x512",
"type": "image/png"
},
{
"src": window.location.origin + "{{ .staticURL }}/img/icons/android-chrome-192x192.png",
"src": window.location.origin + "{{ .htmlVars.staticURL }}/img/icons/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
],
"start_url": window.location.origin + "{{ .baseURL }}",
"start_url": window.location.origin + "{{ .htmlVars.baseURL }}",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "{{ .color }}"
"theme_color": "{{ .htmlVars.color }}"
}
const stringManifest = JSON.stringify(dynamicManifest);
@@ -61,7 +62,7 @@
<style>
/* Basic Styles */
:root {
--background: {{ .lightBackground }};
--background: {{ .htmlVars.lightBackground }};
--alt-background: #ddd;
--surfacePrimary: gray;
--surfaceSecondary: lightgray;
@@ -71,7 +72,7 @@
--activeWhiteIcon: gray;
}
.dark-mode {
--background: {{ .darkBackground }};
--background: {{ .htmlVars.darkBackground }};
--alt-background: #283136;
--surfacePrimary: #20292F;
--surfaceSecondary: #3A4147;
@@ -155,15 +156,15 @@
transform: scale(1.0);
}
}
{{ .customCSS }}
{{ .userSelectedTheme }}
{{ .htmlVars.customCSS }}
{{ .htmlVars.userSelectedTheme }}
</style>
</head>
<body>
<div id="app"></div>
{{ if .darkMode -}}
{{ if .htmlVars.darkMode -}}
<div id="loading" class="dark-mode">
<div class="spinner">
<div class="bounce1"></div>
+18 -5
View File
@@ -50,9 +50,15 @@ async function translateText(text, targetLanguage, keyPath = '') {
return text;
}
if (/\{[^}]+\}/.test(text)) {
console.log(`Skipping translation for placeholder string: "${text}"`);
return text;
const hasPlaceholders = /\{[^}]+\}/.test(text);
let textToTranslate = text;
const options = {};
if (hasPlaceholders) {
console.log(`Found placeholder in: "${text}". Wrapping for translation.`);
textToTranslate = text.replace(/(\{[^}]+\})/g, '<ph>$1</ph>');
options.tagHandling = 'xml';
options.ignoreTags = ['ph'];
}
try {
@@ -60,12 +66,19 @@ async function translateText(text, targetLanguage, keyPath = '') {
let deeplTargetLang = deeplLangMap[targetLanguage.toLowerCase()] || targetLanguage.toUpperCase();
const result = await translator.translateText(text, masterLanguageCode, deeplTargetLang);
const result = await translator.translateText(textToTranslate, masterLanguageCode, deeplTargetLang, options);
// Delay to avoid rate-limiting
await new Promise(resolve => setTimeout(resolve, 100));
return result.text;
let translatedText = result.text;
if (hasPlaceholders) {
// Unwrap the placeholders. The translator might add spaces around tags.
translatedText = translatedText.replace(/<ph>\s*(\{[^}]+\})\s*<\/ph>/g, '$1');
}
return translatedText;
} catch (err) {
console.error(`⚠️ Translation failed for "${text}" (${keyPath}):`, err?.message || err);
+2 -2
View File
@@ -1,10 +1,10 @@
import { baseURL } from "@/utils/constants";
import { globalVars } from "@/utils/constants";
const ssl = window.location.protocol === "https:";
const protocol = ssl ? "wss:" : "ws:";
export default function command(url, command, onmessage, onclose) {
url = `${protocol}//${window.location.host}${baseURL}api/command${url}`;
url = `${protocol}//${window.location.host}${globalVars.baseURL}api/command${url}`;
let conn = new window.WebSocket(url);
conn.onopen = () => conn.send(command);
conn.onmessage = onmessage;
+18 -4
View File
@@ -1,8 +1,8 @@
import { fetchURL, adjustedData } from './utils'
import { getApiPath, doubleEncode } from '@/utils/url.js'
import { getApiPath, doubleEncode, getPublicApiPath } from '@/utils/url.js'
import { mutations } from '@/store'
import { notify } from '@/notify'
import { externalUrl } from '@/utils/constants'
import { globalVars } from '@/utils/constants'
// Notify if errors occur
export async function fetchFiles(source, path, content = false) {
@@ -229,8 +229,8 @@ export function getDownloadURL(source, path, inline, useExternal) {
...(inline && { inline: 'true' })
}
const apiPath = getApiPath('api/raw', params)
if (externalUrl && useExternal) {
return externalUrl + apiPath
if (globalVars.externalUrl && useExternal) {
return globalVars.externalUrl + apiPath
}
return window.origin + apiPath
} catch (err) {
@@ -265,3 +265,17 @@ export async function sources() {
throw err
}
}
export async function GetOfficeConfig(req) {
const params = {
path: encodeURIComponent(req.path),
...(req.hash && { hash: encodeURIComponent(req.hash) }),
...(req.source && { source: encodeURIComponent(req.source) })
}
let apiPath = getApiPath('api/onlyoffice/config', params)
if (req.hash) {
apiPath = getPublicApiPath('onlyoffice/config', params)
}
const res = await fetchURL(apiPath)
return await res.json()
}
+2 -1
View File
@@ -3,7 +3,8 @@ import * as publicApi from "./public";
import * as usersApi from "./users";
import * as settingsApi from "./settings";
import * as accessApi from "./access";
import * as shareApi from "./share";
import search from "./search";
// Note: shareApi has been consolidated into publicApi
export { filesApi, publicApi, usersApi, settingsApi, search, accessApi };
export { filesApi, publicApi, usersApi, settingsApi, shareApi, search, accessApi };
+10 -79
View File
@@ -1,7 +1,7 @@
import { fetchURL, fetchJSON, adjustedData } from "./utils";
import { adjustedData } from "./utils";
import { notify } from "@/notify";
import { getApiPath, getPublicApiPath } from "@/utils/url.js";
import { externalUrl } from "@/utils/constants";
import { getApiPath, getPublicApiPath, encodedPath } from "@/utils/url.js";
import { globalVars } from "@/utils/constants";
import { state } from "@/store";
// ============================================================================
@@ -17,8 +17,9 @@ import { state } from "@/store";
* @returns {Promise<any>}
*/
export async function fetchPub(path, hash, password = "", content = false) {
path = encodedPath(path);
const params = {
path,
path: path,
hash,
...(content && { content: 'true' }),
...(state.share.token && { token: state.share.token })
@@ -57,8 +58,10 @@ export async function fetchPub(path, hash, password = "", content = false) {
* @returns {string}
*/
export function getDownloadURL(share, files, inline=false) {
// Join files array with || delimiter and then URL encode
const filesParam = Array.isArray(files) ? files.join('||') : files;
const params = {
files: files,
files: encodeURIComponent(filesParam),
hash: share.hash,
token: share.token,
...(inline && { inline: 'true' })
@@ -89,87 +92,15 @@ export function getPreviewURL(path,size="small") {
}
}
// ============================================================================
// SHARE MANAGEMENT API (permission-based authentication)
// ============================================================================
// List all shares
export async function list() {
const apiPath = getApiPath("public/shares");
return fetchJSON(apiPath);
}
// Get share information
/**
* @param {string} path
* @param {string} source
* @returns {Promise<any>}
*/
export async function get(path, source) {
try {
const params = { path: encodeURIComponent(path), source: encodeURIComponent(source) };
const apiPath = getApiPath("public/share", params);
let data = await fetchJSON(apiPath);
return adjustedData(data);
} catch (/** @type {any} */ err) {
notify.showError(err.message || "Error fetching data");
throw err;
}
}
// Remove/delete a share
/**
* @param {string} hash
* @returns {Promise<void>}
*/
export async function remove(hash) {
const params = { hash };
const apiPath = getApiPath("public/share", params);
await fetchURL(apiPath, {
method: "DELETE",
});
}
// Create a new share
/**
* @param {Record<string, any>} bodyObj
* @returns {Promise<Share>}
*/
export async function create(bodyObj = {}) {
const apiPath = getApiPath("public/share");
return fetchJSON(apiPath, {
method: "POST",
body: JSON.stringify(bodyObj || {}),
});
}
// Get the shareable URL for a share
/**
* @param {{ hash: string }} share
* @returns {string}
*/
export function getShareURL(share) {
if (externalUrl) {
if (globalVars.externalUrl) {
const apiPath = getApiPath(`public/share/${share.hash}`)
return externalUrl + apiPath;
return globalVars.externalUrl + apiPath;
}
return window.origin + getApiPath(`public/share/${share.hash}`);
}
/**
* @typedef {object} Share
* @property {string} hash
* @property {string} path
* @property {string} source
* @property {number} expire
* @property {number} downloadsLimit
* @property {number} maxBandwidth
* @property {string} shareTheme
* @property {boolean} disableAnonymous
* @property {boolean} disableThumbnails
* @property {boolean} keepAfterExpiration
* @property {string[]} allowedUsernames
* @property {string} viewMode
* @property {string} token
* @property {boolean} inline
*/
+8
View File
@@ -13,3 +13,11 @@ export async function update(settings) {
body: JSON.stringify(settings),
});
}
export function getConfig(showFull = false, showComments = false) {
const params = {};
if (showFull) params.full = "true";
if (showComments) params.comments = "true";
const path = getApiPath("api/settings/config", params);
return fetchURL(path);
}
+76
View File
@@ -0,0 +1,76 @@
import { fetchURL, fetchJSON, adjustedData } from "./utils";
import { notify } from "@/notify";
import { getApiPath } from "@/utils/url.js";
// ============================================================================
// SHARE MANAGEMENT API (permission-based authentication)
// ============================================================================
// List all shares
export async function list() {
const apiPath = getApiPath("api/shares");
return fetchJSON(apiPath);
}
// Get share information
/**
* @param {string} path
* @param {string} source
* @returns {Promise<any>}
*/
export async function get(path, source) {
try {
const params = { path: encodeURIComponent(path), source: encodeURIComponent(source) };
const apiPath = getApiPath("api/share", params);
let data = await fetchJSON(apiPath);
return adjustedData(data);
} catch (/** @type {any} */ err) {
notify.showError(err.message || "Error fetching data");
throw err;
}
}
// Remove/delete a share
/**
* @param {string} hash
* @returns {Promise<void>}
*/
export async function remove(hash) {
const params = { hash };
const apiPath = getApiPath("api/share", params);
await fetchURL(apiPath, {
method: "DELETE",
});
}
// Create a new share
/**
* @param {Record<string, any>} bodyObj
* @returns {Promise<Share>}
*/
export async function create(bodyObj = {}) {
const apiPath = getApiPath("api/share");
return fetchJSON(apiPath, {
method: "POST",
body: JSON.stringify(bodyObj || {}),
});
}
/**
* @typedef {object} Share
* @property {string} hash
* @property {string} path
* @property {string} source
* @property {number} expire
* @property {number} downloadsLimit
* @property {number} maxBandwidth
* @property {string} shareTheme
* @property {boolean} disableAnonymous
* @property {boolean} disableThumbnails
* @property {boolean} keepAfterExpiration
* @property {string[]} allowedUsernames
* @property {string} viewMode
* @property {string} token
* @property {boolean} inline
*/
+43 -5
View File
@@ -1,12 +1,50 @@
import { describe, it, expect, vi } from 'vitest';
vi.mock('@/utils/constants', () => {
return {
globalVars: {
baseURL: "unit-testing",
name: "Test App",
mediaAvailable: true,
muPdfAvailable: true,
onlyOfficeUrl: "",
recaptcha: false,
recaptchaKey: "",
darkMode: false,
oidcAvailable: false,
passwordAvailable: true,
externalUrl: "",
minSearchLength: 1,
disableNavButtons: false,
userSelectableThemes: {},
enableThumbs: true,
noAuth: false,
loginPage: true,
signup: false,
version: "test",
commitSHA: "test",
disableExternal: false,
externalLinks: [],
updateAvailable: "",
},
shareInfo: {
isShare: false,
disableThumbnails: false,
hash: "",
enforceDarkLightMode: "",
disableSidebar: false,
isValid: true,
},
serverHasMultipleSources: false,
logoURL: "test-logo.png",
origin: "http://localhost",
settings: [],
};
});
import { adjustedData } from './utils.js';
describe('adjustedData', () => {
vi.doMock('@/utils/constants', () => {
return {
baseURL: "unit-testing",
};
});
it('should append the URL and process directory data correctly', () => {
const input = {
type: "directory",
+45 -21
View File
@@ -14,15 +14,25 @@
:class="{ 'dark-mode': isDarkMode, 'centered': centered }"
:key="showCreate ? 'create-mode' : 'normal-mode'"
>
<div v-if="selectedCount > 0" class="button selected-count-header">
<span>{{ selectedCount }} {{ $t("prompts.selected") }} </span>
<div class="context-menu-header">
<div
class="action button clickable"
v-if="!isSearchActive && userPerms.modify && !isShare"
@click="toggleShowCreate"
>
<i v-if="!showCreate" class="material-icons">add</i>
<i v-if="showCreate" class="material-icons">arrow_back</i>
</div>
<div
v-if="selectedCount > 0"
@mouseleave="hideTooltip"
@mouseenter="showTooltip($event, $t('buttons.selectedCount'))"
class="button selected-count-header"
>
<span>{{ selectedCount }}</span>
</div>
</div>
<action
v-if="!showCreate && !isSearchActive && userPerms.modify && !isShare"
icon="add"
:label="$t('buttons.new')"
@action="startShowCreate"
/>
<hr class="divider">
<action
v-if="showCreate && !isSearchActive && userPerms.modify"
icon="create_new_folder"
@@ -77,7 +87,7 @@
v-if="!showCreate && selectedCount == 1 && isSearchActive"
icon="folder"
:label="$t('buttons.openParentFolder')"
@action="openParentFolder"
@action="openParentFolder"
/>
<action
v-if="!showCreate && selectedCount > 0 && userPerms.modify"
@@ -124,7 +134,7 @@
>
<action v-if="showGoToRaw" icon="open_in_new" :label="$t('buttons.openFile')" @action="goToRaw()" />
<action v-if="shouldShowParentFolder()" icon="folder" :label="$t('buttons.openParentFolder')" @action="openParentFolder" />
<action v-if="isPreview" icon="file_download" :label="$t('buttons.download')" @action="startDownload" />
<action v-if="hasDownload" icon="file_download" :label="$t('buttons.download')" @action="startDownload" />
<action v-if="showEdit" icon="edit" :label="$t('buttons.edit')" @action="edit()" />
<action v-if="showSave" icon="save" :label="$t('buttons.save')" @action="save()" />
<action v-if="showDelete" icon="delete" :label="$t('buttons.delete')" show="delete" />
@@ -136,7 +146,7 @@
import downloadFiles from "@/utils/download";
import { state, getters, mutations } from "@/store";
import Action from "@/components/Action.vue";
import { onlyOfficeUrl } from "@/utils/constants.js";
import { globalVars } from "@/utils/constants.js";
import buttons from "@/utils/buttons";
import { notify } from "@/notify";
import { eventBus } from "@/store/eventBus";
@@ -179,7 +189,7 @@ export default {
return false
},
hasOverflowItems() {
return this.showEdit || this.showDelete || this.showSave || this.showGoToRaw;
return this.showEdit || this.showDelete || this.showSave || this.showGoToRaw || this.hasDownload;
},
showGoToRaw() {
const cv = getters.currentView();
@@ -202,6 +212,9 @@ export default {
const showDelete = cv != "settings" && !this.showCreate && this.selectedCount > 0 && !this.isSearchActive;
return showDelete;
},
hasDownload() {
return this.selectedCount > 0;
},
isPreview() {
const cv = getters.currentView();
return (
@@ -236,7 +249,7 @@ export default {
return getters.currentPromptName() == "ContextMenu";
},
onlyofficeEnabled() {
return onlyOfficeUrl !== "";
return globalVars.onlyOfficeUrl !== "";
},
isSearchActive() {
return state.isSearchActive;
@@ -271,14 +284,6 @@ export default {
},
},
watch: {
currentPrompt: {
handler(prompt) {
if (prompt && prompt.name === "ContextMenu") {
this.setPositions();
}
},
deep: true,
},
hasOverflowItems: {
handler(hasItems) {
mutations.setContextMenuHasItems(hasItems);
@@ -306,6 +311,19 @@ export default {
}
},
methods: {
hideTooltip() {
mutations.hideTooltip();
},
showTooltip(event, text) {
mutations.showTooltip({
content: text,
x: event.clientX,
y: event.clientY,
});
},
toggleShowCreate() {
this.showCreate = !this.showCreate;
},
shouldShowParentFolder() {
return this.isPreview && state.req.path != "/";
},
@@ -538,4 +556,10 @@ export default {
height: 0 !important;
opacity: 0;
}
.context-menu-header {
display: flex;
align-items: center;
justify-content: space-between;
}
</style>
+39
View File
@@ -18,12 +18,21 @@ https://raw.githubusercontent.com/dzwillia/vue-simple-progress/master/src/compon
v-if="textPosition == 'inside'"
>
{{ displayed_text }}
<i
v-if="helpText && status === 'error'"
class="no-select material-symbols-outlined tooltip-info-icon"
@mouseenter="showTooltip"
@mouseleave="hideTooltip"
>
help
</i>
</div>
</div>
</template>
<script>
import { getHumanReadableFilesize } from "@/utils/filesizes.js";
import { mutations } from "@/store";
// We're leaving this untouched as you can read in the beginning
var isNumber = function (n) {
@@ -92,6 +101,10 @@ export default {
type: String,
default: 'default',
},
"help-text": {
type: String,
default: "",
},
},
computed: {
isValNumeric() {
@@ -244,6 +257,20 @@ export default {
return style;
},
},
methods: {
showTooltip(event) {
if (this.helpText) {
mutations.showTooltip({
content: this.helpText,
x: event.clientX,
y: event.clientY,
});
}
},
hideTooltip() {
mutations.hideTooltip();
},
},
};
</script>
@@ -263,4 +290,16 @@ export default {
.vue-simple-progress-text {
color: black;
}
.tooltip-info-icon {
font-size: 1rem;
cursor: pointer;
margin-left: 0.3em;
vertical-align: middle;
opacity: 0.7;
}
.tooltip-info-icon:hover {
opacity: 1;
}
</style>
+19 -26
View File
@@ -50,7 +50,7 @@
</select>
<!-- Formatted display of selected value -->
<div class="searchContext">{{ contextText }}</div>
<div class="searchContext">{{ $t("search.searchContext", { context: getContext }) }}</div>
</div>
<div id="result-list">
@@ -87,7 +87,7 @@
v-model="smallerThan"
type="number"
min="0"
placeholder="number"
:placeholder="$t('search.number')"
/><p>MB</p> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</div>
<div class="sizeInputWrapper">
@@ -96,7 +96,7 @@
class="sizeInput"
v-model="largerThan"
type="number"
placeholder="number"
:placeholder="$t('search.number')"
/><p>MB</p> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</div>
</div>
@@ -146,9 +146,8 @@ import { search } from "@/api";
import { getters, mutations, state } from "@/store";
import { getHumanReadableFilesize } from "@/utils/filesizes";
import { url } from "@/utils/";
import Icon from "@/components/files/Icon.vue";
import { serverHasMultipleSources, baseURL } from "@/utils/constants";
import { globalVars, serverHasMultipleSources } from "@/utils/constants";
var boxes = {
folder: { label: "folders", icon: "folder" },
@@ -170,22 +169,22 @@ export default {
return {
largerThan: "",
smallerThan: "",
noneMessage: "Start typing 3 or more characters to begin searching.",
noneMessage: this.$t("search.typeToSearch", { minSearchLength: globalVars.minSearchLength }),
searchTypes: "",
isTypeSelectDisabled: false,
showHelp: false,
folderSelect: [
{ label: "Only Folders", value: "type:folder" },
{ label: "Only Files", value: "type:file" },
{ label: this.$t("search.onlyFolders"), value: "type:folder" },
{ label: this.$t("search.onlyFiles"), value: "type:file" },
],
typeSelect: [
{ label: "Photos", value: "type:image" },
{ label: "Audio", value: "type:audio" },
{ label: "Videos", value: "type:video" },
{ label: "Documents", value: "type:doc" },
{ label: "Archives", value: "type:archive" },
{ label: this.$t("search.photos"), value: "type:image" },
{ label: this.$t("search.audio"), value: "type:audio" },
{ label: this.$t("search.videos"), value: "type:video" },
{ label: this.$t("search.documents"), value: "type:doc" },
{ label: this.$t("search.archives"), value: "type:archive" },
],
toggleOptionButton: [{ label: "Show Options" }],
toggleOptionButton: [{ label: this.$t("search.showOptions") }],
value: "",
ongoing: false,
results: [],
@@ -295,9 +294,7 @@ export default {
if (this.ongoing) {
return "";
}
return this.value === ""
? this.$t("search.typeToSearch")
: this.$t("search.pressToSearch");
return this.$t("search.typeToSearch", { minSearchLength: globalVars.minSearchLength })
},
isRunning() {
return this.ongoing;
@@ -330,9 +327,6 @@ export default {
return "/"; // if searching on non-current source, search the whole thing
}
},
contextText() {
return `Search Context: ${this.getContext}`; // FIX: Use `this.getContext` as a property, not a function call
},
},
methods: {
openContext(event) {
@@ -401,9 +395,9 @@ export default {
const encodedPath = encodeURIComponent(context + "/" + path).replaceAll("%2F", "/");
let fullpath = encodedPath;
if (serverHasMultipleSources) {
fullpath = baseURL+"files/" + this.selectedSource + encodedPath;
fullpath = globalVars.baseURL+"files/" + this.selectedSource + encodedPath;
} else {
fullpath = baseURL+"files" + encodedPath;
fullpath = globalVars.baseURL+"files" + encodedPath;
}
return fullpath;
},
@@ -489,9 +483,8 @@ export default {
if (event != undefined) {
event.preventDefault();
}
if (this.value === "" || this.value.length < 3) {
this.ongoing = false;
this.noneMessage = "Not enough characters to search (min 3)";
if (this.value === "" || this.value.length < globalVars.minSearchLength) {
this.ongoing = false; this.noneMessage = this.$t("search.notEnoughCharacters", { minSearchLength: globalVars.minSearchLength });
return;
}
let searchTypesFull = this.searchTypes;
@@ -510,7 +503,7 @@ export default {
this.ongoing = false;
if (this.results.length == 0) {
this.noneMessage = "No results found in indexed search.";
this.noneMessage = this.$t("search.noResults");
}
},
toggleHelp() {
+32 -4
View File
@@ -3,14 +3,14 @@
ref="tooltipRef"
v-show="tooltip.show"
class="floating-tooltip fb-shadow"
:class="{ 'dark-mode': isDarkMode }"
:class="{ 'dark-mode': isDarkMode, 'pointer-enabled': tooltip.pointerEvents }"
:style="tooltipStyle"
v-html="tooltip.content"
></div>
</template>
<script>
import { state } from "@/store";
import { state,getters } from "@/store";
export default {
name: "Tooltip",
@@ -26,13 +26,27 @@ export default {
return state.tooltip;
},
isDarkMode() {
return state.user.darkMode;
return getters.isDarkMode();
},
tooltipStyle() {
return {
const style = {
top: `${this.adjustedY}px`,
left: `${this.adjustedX}px`,
};
// Add custom width if specified
if (this.tooltip.width) {
style.maxWidth = this.tooltip.width;
style.width = this.tooltip.width;
}
// Add max height and scrolling for viewport overflow
if (this.tooltip.width || this.tooltip.pointerEvents) {
style.maxHeight = '80vh';
style.overflowY = 'auto';
}
return style;
},
},
watch: {
@@ -53,6 +67,10 @@ export default {
},
},
methods: {
/**
* @param {number} x - X coordinate
* @param {number} y - Y coordinate
*/
updatePosition(x, y) {
this.$nextTick(() => {
const tooltipEl = this.$refs.tooltipRef;
@@ -101,6 +119,16 @@ export default {
white-space: normal;
overflow-wrap: break-word;
}
.floating-tooltip.pointer-enabled {
pointer-events: auto;
cursor: auto;
}
.floating-tooltip.pointer-enabled a {
pointer-events: auto;
cursor: pointer;
}
.tooltip-info-icon {
font-size: 1em !important;
padding: 0.1em !important;
+24 -48
View File
@@ -24,19 +24,13 @@
</template>
<script>
import {
onlyOfficeUrl,
mediaAvailable,
muPdfAvailable,
baseURL,
} from "@/utils/constants";
import { globalVars, shareInfo } from "@/utils/constants";
import { getTypeInfo } from "@/utils/mimetype";
import { mutations, state } from "@/store";
import { shareInfo } from "@/utils/constants";
import { mutations, state, getters } from "@/store";
// NEW: Define placeholder and error image URLs for easy configuration
const PLACEHOLDER_URL = baseURL + "static/img/placeholder.png"; // A generic loading placeholder
const ERROR_URL = baseURL + "static/img/placeholder.png";
const PLACEHOLDER_URL = globalVars.baseURL + "static/img/placeholder.png"; // A generic loading placeholder
const ERROR_URL = globalVars.baseURL + "static/img/placeholder.png";
export default {
name: "Icon",
@@ -49,6 +43,10 @@ export default {
type: String,
required: true,
},
hasPreview: {
type: Boolean,
default: false,
},
active: {
type: Boolean,
},
@@ -79,7 +77,16 @@ export default {
if (shareInfo.disableThumbnails) {
return false;
}
return this.isPreviewImg && this.imageState !== 'error' && !this.disablePreviewExt && !this.officeFileDisabled
if (this.thumbnailUrl == "") {
return false;
}
if (!this.hasPreview) {
return false;
}
if (!state.user.preview.folder && this.mimetype == "directory") {
return false;
}
return this.imageState !== 'error' && !this.disablePreviewExt && !this.officeFileDisabled
},
disablePreviewExt() {
const ext = "." + (this.filename.split(".").pop() || "").toLowerCase(); // Ensure lowercase and dot
@@ -92,7 +99,7 @@ export default {
return state.user?.disablePreviewExt?.includes(ext);
},
pdfConvertable() {
if (!muPdfAvailable) {
if (!globalVars.muPdfAvailable) {
return false; // If muPDF is not available
}
const ext = "." + (this.filename.split(".").pop() || "").toLowerCase(); // Ensure lowercase and dot
@@ -126,16 +133,16 @@ export default {
return this.imageTargetSrc;
},
showLargeIcon() {
return state.user.viewMode === "gallery" && state.user.preview.highQuality;
return getters.viewMode() === "gallery" && state.user.preview.highQuality;
},
showLarger() {
return state.user.viewMode === "gallery" || state.user.viewMode === "normal";
return getters.viewMode() === "gallery" || getters.viewMode() === "normal";
},
hasMotion() {
return (
this.getIconForType().simpleType === "video" &&
state.user.preview?.video &&
mediaAvailable &&
globalVars.mediaAvailable &&
// @ts-ignore
state.user.preview.motionVideoPreview
);
@@ -143,37 +150,6 @@ export default {
isMaterialIcon() {
return this.materialIcon !== "";
},
isPreviewImg() {
if (this.thumbnailUrl == "") {
return false;
}
if (this.mimetype == "text/csv") {
return false;
}
// @ts-ignore
if (this.pdfConvertable && state.user.preview?.office) {
return true;
}
if (this.getIconForType().simpleType === "image" && state.user.preview?.image) {
return true;
}
if (
this.getIconForType().simpleType === "video" &&
state.user.preview?.video &&
mediaAvailable
) {
return true;
}
if (
this.getIconForType().simpleType === "document" &&
// @ts-ignore
state.user.preview?.office &&
onlyOfficeUrl != ""
) {
return true;
}
return false;
},
},
methods: {
// NEW: Centralized method to load any image and handle its state
@@ -276,11 +252,11 @@ export default {
showLargeIcon() {
this.updateImageTargetSrc();
},
// UPDATED: Added a check for isPreviewImg
// UPDATED: Added a check for hasPreviewImage
imageTargetSrc: {
handler(newSrc) {
// ONLY trigger the image loader if the component is meant to show a preview.
if (this.isPreviewImg) {
if (this.hasPreviewImage) {
this.loadImage(newSrc);
}
},
+16 -17
View File
@@ -34,6 +34,7 @@
:active="isSelected"
:thumbnailUrl="isThumbnailInView ? thumbnailUrl : ''"
:filename="name"
:hasPreview="hasPreview"
/>
</div>
@@ -54,6 +55,7 @@
@click.stop="downloadFile"
v-if="quickDownloadEnabled"
:filename="name"
:hasPreview="hasPreview"
mimetype="file_download"
style="padding-right: 0.5em"
class="download-icon"
@@ -66,7 +68,7 @@
</template>
<script>
import { enableThumbs } from "@/utils/constants";
import { globalVars, serverHasMultipleSources, shareInfo } from "@/utils/constants";
import downloadFiles from "@/utils/download";
import { getHumanReadableFilesize } from "@/utils/filesizes";
@@ -75,7 +77,6 @@ import * as upload from "@/utils/upload";
import { state, getters, mutations } from "@/store"; // Import your custom store
import { url } from "@/utils";
import Icon from "@/components/files/Icon.vue";
import { baseURL, serverHasMultipleSources, shareInfo } from "@/utils/constants";
export default {
name: "item",
@@ -106,10 +107,11 @@ export default {
"path",
"reducedOpacity",
"hash",
"hasPreview",
],
computed: {
galleryView() {
return state.user.viewMode === "gallery";
return getters.viewMode() === "gallery";
},
quickDownloadEnabled() {
// @ts-ignore
@@ -164,7 +166,7 @@ export default {
return true;
},
thumbnailUrl() {
if (!enableThumbs) {
if (!globalVars.enableThumbs) {
return "";
}
const previewPath = url.removeTrailingSlash(state.req.path) + "/" + this.name;
@@ -175,7 +177,7 @@ export default {
return filesApi.getPreviewURL(state.req.source, previewPath, this.modified);
},
isThumbsEnabled() {
return enableThumbs;
return globalVars.enableThumbs;
},
},
mounted() {
@@ -232,12 +234,12 @@ export default {
},
getUrl() {
if (this.hash) {
return baseURL + "public/share/" + this.hash + "/" + url.encodedPath(this.path);
return globalVars.baseURL + "public/share/" + this.hash + "/" + url.encodedPath(this.path);
}
if (serverHasMultipleSources) {
return baseURL + "files/" + encodeURIComponent(this.source) + url.encodedPath(this.path);
return globalVars.baseURL + "files/" + encodeURIComponent(this.source) + url.encodedPath(this.path);
}
return baseURL + "files" + url.encodedPath(this.path);
return globalVars.baseURL + "files" + url.encodedPath(this.path);
},
/** @param {MouseEvent} event */
onRightClick(event) {
@@ -465,19 +467,16 @@ export default {
) {
mutations.resetSelected();
}
// @ts-ignore
mutations.addSelected(this.index);
mutations.setLastSelectedIndex(this.index);
},
open() {
if (this.hash) {
const shareHash = this.hash;
url.goToItem(this.source, this.path, "", shareHash);
return;
}
// @ts-ignore
const previousHash = state.req.items[this.index].name;
url.goToItem(this.source, this.path, previousHash);
const previousHistoryItem = {
name: state.req.items[this.index].name,
source: state.req.source,
path: state.req.path,
};
url.goToItem(this.source, this.path, previousHistoryItem);
},
},
};
+22 -13
View File
@@ -10,21 +10,25 @@
<div v-if="shareInfo.description" class="share__box__element">
<p>{{ shareInfo.description }}</p>
</div>
<hr v-if="shareInfo.banner || shareInfo.title || shareInfo.description" />
<div class="share__box__element">
<strong>{{ $t("prompts.displayName") }}</strong> {{ req.name }}
</div>
<div class="share__box__element" :title="modTime">
<strong>{{ $t("prompts.lastModified") }}:</strong> {{ humanTime }} <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</div>
<div class="share__box__element">
<strong>{{ $t("prompts.size") }}:</strong> {{ humanSize }} <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</div>
<div class="share__box__element share__box__center">
<button class="button button--flat clickable" @click="goToLink()"> {{ $t("buttons.download") }} </button>
</div>
<div v-if="accessible">
<hr v-if="shareInfo.banner || shareInfo.title || shareInfo.description" />
<div class="share__box__element">
<strong>{{ $t("prompts.displayName") }}</strong> {{ req.name }}
</div>
<div class="share__box__element" :title="modTime">
<strong>{{ $t("prompts.lastModified", {suffix: ":"}) }}</strong> {{ humanTime }}
<!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</div>
<div class="share__box__element">
<strong>{{ $t("prompts.size", {suffix: ":"}) }}</strong> {{ humanSize }}
<!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</div>
<div class="share__box__element share__box__center">
<button class="button button--flat clickable" @click="goToLink()"> {{ $t("buttons.download") }} </button>
</div>
</div>
<div v-if="req.type" class="share__box__element share__box__center">
<qrcode-vue class="qrcode" :value="getLink(false)" size="200" level="M"></qrcode-vue>
</div>
@@ -60,6 +64,9 @@ export default {
},
},
computed: {
accessible() {
return shareInfo.isPasswordProtected && state.share.passwordValid;
},
getShareBanner() {
if (this.shareInfo.banner.startsWith("http")) {
return this.shareInfo.banner;
@@ -122,6 +129,7 @@ export default {
.banner img {
width: 100%;
}
.share {
display: flex;
}
@@ -146,6 +154,7 @@ export default {
.share__box__element canvas {
border-style: solid;
}
.share__box__center {
text-align: center;
}
@@ -0,0 +1,882 @@
<template>
<!-- Left edge detection zone -->
<div
v-if="enabled && hasPrevious"
class="nav-zone nav-zone-left"
:class="{ moveWithSidebar: moveWithSidebar }"
@mousemove="toggleNavigation"
@touchstart="(e) => { handleTouchStart(e); toggleNavigation(e); }"
@touchmove="handleTouchMove"
@click="handleClick"
></div>
<!-- Right edge detection zone -->
<div
v-if="enabled && hasNext"
class="nav-zone nav-zone-right"
@mousemove="toggleNavigation"
@touchstart="(e) => { handleTouchStart(e); toggleNavigation(e); }"
@touchmove="handleTouchMove"
@click="handleClick"
></div>
<!-- Previous button -->
<button
v-if="enabled && hasPrevious"
@click.stop="handlePrevClick"
@mousedown="startDrag($event, 'previous')"
@touchstart="handleTouchStart($event, 'previous')"
@touchmove="handleButtonTouchMove"
@touchend="handleTouchEnd"
@mouseover="setHoverNav(true)"
@mouseleave="setHoverNav(false)"
class="nav-button nav-previous"
:class="{
moveWithSidebar: moveWithSidebar,
hidden: !showNav,
disabled: !hasPrevious,
dragging: dragState.type === 'previous',
active: dragState.atFullExtent && dragState.type === 'previous',
'dark-mode': isDarkMode,
}"
:style="dragState.type === 'previous' ? { transform: `translateY(-50%) translate(${dragState.deltaX}px, 0)` } : {}"
:aria-label="$t('buttons.previous')"
:title="$t('buttons.previous')"
>
<i class="material-icons">
{{ dragState.type === 'previous' && dragState.atFullExtent ? 'list_alt' : 'chevron_left' }} <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</i>
</button>
<!-- Next button -->
<button
v-if="enabled && hasNext"
@click.stop="handleNextClick"
@mousedown="startDrag($event, 'next')"
@touchstart="handleTouchStart($event, 'next')"
@touchmove="handleButtonTouchMove"
@touchend="handleTouchEnd"
@mouseover="setHoverNav(true)"
@mouseleave="setHoverNav(false)"
class="nav-button nav-next"
:class="{ hidden: !showNav, dragging: dragState.type === 'next', active: dragState.atFullExtent && dragState.type === 'next','dark-mode': isDarkMode}"
:style="dragState.type === 'next' ? { transform: `translateY(-50%) translate(${dragState.deltaX}px, 0)` } : {}"
:aria-label="$t('buttons.next')"
:title="$t('buttons.next')"
>
<i class="material-icons">
{{ dragState.type === 'next' && dragState.atFullExtent ? 'list_alt' : 'chevron_right' }} <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</i>
</button>
<!-- Prefetch links for better performance -->
<link v-if="previousRaw" rel="prefetch" :href="previousRaw" />
<link v-if="nextRaw" rel="prefetch" :href="nextRaw" />
</template>
<script>
import { state, getters, mutations } from "@/store";
import throttle from "@/utils/throttle";
import { previewViews } from "@/utils/constants";
import { url } from "@/utils";
import { filesApi, publicApi } from "@/api";
export default {
name: "NextPrevious",
data() {
return {
hoverNav: false,
dragState: {
isDragging: false,
type: null, // 'previous' or 'next'
startX: 0,
startY: 0,
deltaX: 0,
deltaY: 0,
threshold: 0, // Will be calculated as 10em in pixels
atFullExtent: false,
triggered: false,
},
// State tracking
navigationTimeout: null,
isSwipe: false,
touchStartX: 0,
touchStartY: 0,
// Button touch handling
touchState: {
isButtonTouch: false,
buttonType: null,
startTime: 0,
hasMoved: false,
tapTimeout: null,
triggered: false
},
};
},
computed: {
isDarkMode() { return getters.isDarkMode(); },
moveWithSidebar() {
return getters.isSidebarVisible() && getters.isStickySidebar();
},
enabled() {
return state.navigation.enabled;
},
showNav() {
const shouldShow = state.navigation.show || this.hoverNav;
return shouldShow;
},
hasPrevious() {
const has = state.navigation.previousLink !== "";
return has;
},
hasNext() {
const has = state.navigation.nextLink !== "";
return has;
},
previousRaw() {
return state.navigation.previousRaw;
},
nextRaw() {
return state.navigation.nextRaw;
},
currentView() {
const view = getters.currentView();
return view;
}
},
watch: {
currentView() {
this.updateNavigationEnabled();
// Also trigger navigation setup if we're now in a preview view
this.$nextTick(() => {
if (this.enabled && state.req) {
this.setupNavigationForCurrentItem();
}
});
},
'state.req': {
handler() {
this.updateNavigationEnabled();
// Auto-setup navigation when request changes and we're enabled
if (this.enabled) {
this.$nextTick(() => {
this.setupNavigationForCurrentItem();
});
}
},
deep: true,
immediate: false
},
enabled(newEnabled) {
if (newEnabled && state.req) {
this.$nextTick(() => {
this.setupNavigationForCurrentItem();
});
}
},
'$route'() {
// Give time for state.req to be updated, then setup navigation
setTimeout(() => {
this.$nextTick(() => {
if (this.enabled && state.req) {
this.setupNavigationForCurrentItem();
}
});
}, 100);
},
// Watch for when navigation links are set up
'state.navigation.previousLink'() {
this.showInitialNavigation();
},
'state.navigation.nextLink'() {
this.showInitialNavigation();
},
},
mounted() {
window.addEventListener("keydown", this.keyEvent);
window.addEventListener("mousemove", this.handleDrag);
window.addEventListener("mouseup", this.endDrag);
window.addEventListener("touchmove", this.handleDrag, { passive: false });
window.addEventListener("touchend", this.endDrag);
// Calculate 10em threshold in pixels
const emSize = parseFloat(getComputedStyle(document.documentElement).fontSize);
this.dragState.threshold = 10 * emSize;
this.updateNavigationEnabled();
// Setup navigation if enabled and we have a current item
if (this.enabled && state.req) {
this.$nextTick(() => {
this.setupNavigationForCurrentItem();
});
} else {
this.$nextTick(() => {
this.showInitialNavigation();
});
}
},
beforeUnmount() {
window.removeEventListener("keydown", this.keyEvent);
window.removeEventListener("mousemove", this.handleDrag);
window.removeEventListener("mouseup", this.endDrag);
window.removeEventListener("touchmove", this.handleDrag);
window.removeEventListener("touchend", this.endDrag);
// Clear our local timeout
if (this.navigationTimeout) {
clearTimeout(this.navigationTimeout);
this.navigationTimeout = null;
}
// Clean up touch state
this.resetTouchState();
mutations.clearNavigation();
},
methods: {
updateNavigationEnabled() {
const shouldEnable = previewViews.includes(this.currentView);
mutations.setNavigationEnabled(shouldEnable);
},
async setupNavigationForCurrentItem() {
if (!this.enabled || !state.req || state.req.type === 'directory') {
// Clear navigation when not applicable
mutations.clearNavigation();
return;
}
const directoryPath = url.removeLastDir(state.req.path);
let listing = null;
// Try to get listing from current request first
if (state.req.items) {
listing = state.req.items;
} else {
// Fetch the directory listing
try {
let res;
if (getters.isShare()) {
res = await publicApi.fetchPub(directoryPath, state.share.hash);
} else {
res = await filesApi.fetchFiles(state.req.source, directoryPath);
}
listing = res.items;
} catch (error) {
listing = [state.req]; // Fallback to current item only
}
}
mutations.setupNavigation({
listing: listing,
currentItem: state.req,
directoryPath: directoryPath
});
},
showInitialNavigation() {
// Show navigation initially for 3 seconds when navigation is set up
if (this.enabled && (this.hasPrevious || this.hasNext)) {
mutations.setNavigationShow(true);
// Clear any existing timeout
if (this.navigationTimeout) {
clearTimeout(this.navigationTimeout);
this.navigationTimeout = null;
}
this.navigationTimeout = setTimeout(() => {
if (!this.hoverNav) {
mutations.setNavigationShow(false);
}
this.navigationTimeout = null;
}, 3000);
}
},
prev() {
if (this.hasPrevious) {
this.hoverNav = false;
this.$router.replace({ path: state.navigation.previousLink });
}
},
next() {
if (this.hasNext) {
this.hoverNav = false;
this.$router.replace({ path: state.navigation.nextLink });
}
},
keyEvent(event) {
// Only handle navigation if enabled and no prompt is active
if (!this.enabled || state.prompts.length > 0) {
return;
}
const { key } = event;
switch (key) {
case "ArrowRight":
if (this.hasNext) {
event.preventDefault();
this.next();
}
break;
case "ArrowLeft":
if (this.hasPrevious) {
event.preventDefault();
this.prev();
}
break;
}
},
handleClick() {
// Don't show navigation if this is part of a swipe gesture
if (this.isSwipe) {
return;
}
// Simplified: clicking anywhere in the CSS zones shows navigation
if (!this.enabled || (!this.hasPrevious && !this.hasNext)) {
return;
}
this.showNavigation();
},
showNavigation() {
mutations.setNavigationShow(true);
mutations.clearNavigationTimeout();
// Clear our local timeout too
if (this.navigationTimeout) {
clearTimeout(this.navigationTimeout);
this.navigationTimeout = null;
}
this.navigationTimeout = setTimeout(() => {
if (!this.hoverNav) {
mutations.setNavigationShow(false);
}
mutations.clearNavigationTimeout();
this.navigationTimeout = null;
}, 3000); // Show for 3 seconds
mutations.setNavigationTimeout(this.navigationTimeout);
},
toggleNavigation: throttle(function () {
if (!this.enabled) {
return;
}
if (this.isSwipe) {
return;
}
this.showNavigation();
}, 100),
setHoverNav(value) {
this.hoverNav = value;
mutations.setNavigationHover(value);
},
// Touch handling and swipe detection (similar to ListingItem.vue)
handleTouchStart(event, buttonType = null) {
if (event.touches && event.touches.length > 0) {
const touch = event.touches[0];
this.touchStartX = touch.clientX;
this.touchStartY = touch.clientY;
this.isSwipe = false;
// Handle button-specific touch
if (buttonType) {
this.touchState = {
isButtonTouch: true,
buttonType: buttonType,
startTime: Date.now(),
hasMoved: false,
tapTimeout: null,
triggered: false
};
// Set a longer timeout to allow for drag intent detection
this.touchState.tapTimeout = setTimeout(() => {
// If we haven't moved significantly and not dragging, treat as tap
if (!this.touchState.hasMoved && !this.dragState.isDragging) {
this.handleButtonTap(buttonType);
}
}, 300); // Increased to 300ms to allow for drag detection
}
}
},
handleTouchMove(event) {
if (!event.touches || event.touches.length === 0) return;
const touch = event.touches[0];
const deltaX = Math.abs(touch.clientX - this.touchStartX);
const deltaY = Math.abs(touch.clientY - this.touchStartY);
const movementThreshold = 10;
if (deltaX > movementThreshold || deltaY > movementThreshold) {
this.isSwipe = true;
this.cancelNavigationTimeout();
}
},
// Handle touch movement specifically for navigation buttons
handleButtonTouchMove(event) {
if (!event.touches || event.touches.length === 0) return;
if (!this.touchState.isButtonTouch) return;
event.preventDefault(); // Prevent scrolling while dragging
const touch = event.touches[0];
const deltaX = Math.abs(touch.clientX - this.touchStartX);
const deltaY = Math.abs(touch.clientY - this.touchStartY);
const movementThreshold = 10;
// Check if user has moved enough to start dragging
if (deltaX > movementThreshold || deltaY > movementThreshold) {
this.touchState.hasMoved = true;
// Cancel tap timeout since user is dragging
if (this.touchState.tapTimeout) {
clearTimeout(this.touchState.tapTimeout);
this.touchState.tapTimeout = null;
}
// Initialize drag state if not already dragging
if (!this.dragState.isDragging) {
// Calculate 10em threshold in pixels if not set
if (!this.dragState.threshold) {
const emSize = parseFloat(getComputedStyle(document.documentElement).fontSize);
this.dragState.threshold = 10 * emSize;
}
this.dragState = {
isDragging: true,
type: this.touchState.buttonType,
startX: this.touchStartX,
startY: this.touchStartY,
deltaX: 0,
deltaY: 0,
threshold: this.dragState.threshold,
atFullExtent: false,
triggered: false,
};
}
// Update drag position - implement drag logic directly
if (this.dragState.isDragging) {
let dragDeltaX = touch.clientX - this.dragState.startX;
const maxDrag = this.dragState.threshold; // 10em
// Constrain drag to correct direction and max distance
if (this.dragState.type === 'previous') {
// Left button: only allow rightward drag (positive deltaX)
dragDeltaX = Math.max(0, Math.min(maxDrag, dragDeltaX));
} else if (this.dragState.type === 'next') {
// Right button: only allow leftward drag (negative deltaX)
dragDeltaX = Math.min(0, Math.max(-maxDrag, dragDeltaX));
}
this.dragState.deltaX = dragDeltaX;
// Check if we've reached the full extent
const atFullExtent = Math.abs(dragDeltaX) >= maxDrag;
this.dragState.atFullExtent = atFullExtent;
}
}
},
handleTouchEnd() {
// Handle touch end for buttons
if (this.touchState.isButtonTouch) {
const touchDuration = Date.now() - this.touchState.startTime;
// If it was a short touch without movement, and we haven't already navigated, treat as tap
if (!this.touchState.hasMoved && touchDuration < 300 && this.touchState.tapTimeout) {
clearTimeout(this.touchState.tapTimeout);
this.touchState.tapTimeout = null;
this.handleButtonTap(this.touchState.buttonType);
}
// Reset touch state
this.resetTouchState();
}
// Reset navigation swipe state
this.isSwipe = false;
// Let endDrag handle the drag cleanup
if (this.dragState.isDragging) {
this.endDrag();
}
},
cancelNavigationTimeout() {
if (this.navigationTimeout) {
clearTimeout(this.navigationTimeout);
this.navigationTimeout = null;
}
},
// Handle immediate button tap (mobile-friendly)
handleButtonTap(buttonType) {
// Prevent double navigation if already triggered
if (this.touchState.triggered) {
return;
}
// Clear any pending timeouts
if (this.touchState.tapTimeout) {
clearTimeout(this.touchState.tapTimeout);
this.touchState.tapTimeout = null;
}
// Mark as triggered to prevent double navigation
this.touchState.triggered = true;
// Navigate immediately on tap
if (buttonType === 'previous' && this.hasPrevious) {
this.prev();
} else if (buttonType === 'next' && this.hasNext) {
this.next();
}
// Reset touch state
this.resetTouchState();
},
resetTouchState() {
if (this.touchState.tapTimeout) {
clearTimeout(this.touchState.tapTimeout);
}
this.touchState = {
isButtonTouch: false,
buttonType: null,
startTime: 0,
hasMoved: false,
tapTimeout: null,
triggered: false
};
},
// Drag functionality for navigation buttons
startDrag(event, type) {
event.preventDefault();
const clientX = event.touches ? event.touches[0].clientX : event.clientX;
const clientY = event.touches ? event.touches[0].clientY : event.clientY;
this.dragState = {
isDragging: true,
type: type,
startX: clientX,
startY: clientY,
deltaX: 0,
deltaY: 0,
threshold: this.dragState.threshold,
atFullExtent: false,
triggered: false,
};
},
handleDrag(event) {
if (!this.dragState.isDragging) return;
const clientX = event.touches ? event.touches[0].clientX : event.clientX;
let deltaX = clientX - this.dragState.startX;
// Constrain drag to correct direction and max distance
const maxDrag = this.dragState.threshold; // 10em
if (this.dragState.type === 'previous') {
// Left button: only allow rightward drag (positive deltaX)
deltaX = Math.max(0, Math.min(maxDrag, deltaX));
} else if (this.dragState.type === 'next') {
// Right button: only allow leftward drag (negative deltaX)
deltaX = Math.min(0, Math.max(-maxDrag, deltaX));
}
this.dragState.deltaX = deltaX;
// Check if we've reached the full extent
const atFullExtent = Math.abs(deltaX) >= maxDrag;
this.dragState.atFullExtent = atFullExtent;
// Prevent default to avoid text selection during drag
event.preventDefault();
},
endDrag() {
if (!this.dragState.isDragging && !this.touchState.isButtonTouch) return;
// Only show file list if user released at full extent
if (this.dragState.atFullExtent) {
this.showFileList(this.dragState.type);
}
this.resetDragState();
this.resetTouchState();
},
resetDragState() {
this.dragState = {
isDragging: false,
type: null,
startX: 0,
startY: 0,
deltaX: 0,
deltaY: 0,
threshold: this.dragState.threshold,
atFullExtent: false,
triggered: false,
};
},
handlePrevClick() {
// Only navigate if this wasn't a drag
if (!this.dragState.triggered) {
this.prev();
}
this.resetDragState();
},
handleNextClick() {
// Only navigate if this wasn't a drag
if (!this.dragState.triggered) {
this.next();
}
this.resetDragState();
},
showFileList(type) {
// Hide navigation buttons when showing file list
mutations.setNavigationShow(false);
// Determine what list to show based on drag type
if (type === 'previous') {
// Show parent directories for navigating up
this.showParentDirectories();
} else if (type === 'next') {
// Show current listing items for quick jumping
this.showCurrentListing();
}
},
showParentDirectories() {
// Show files in the current directory (same directory as the previewed file)
const currentItems = this.getCurrentListingItems();
mutations.showHover({
name: "file-list",
props: {
fileList: currentItems,
mode: "navigate-siblings",
title: this.$t("prompts.quickJump")
}
});
},
showCurrentListing() {
const currentItems = this.getCurrentListingItems();
mutations.showHover({
name: "file-list",
props: {
fileList: currentItems,
mode: "quick-jump",
title: this.$t("prompts.quickJump")
}
});
},
getParentDirectories() {
// Build array of parent directories from current path
const currentPath = state.req.path || "/";
const pathParts = currentPath.split("/").filter(part => part);
const parentDirs = [];
// Add root
parentDirs.push({
name: "/",
path: "/",
source: state.req.source,
isDirectory: true
});
// Add each level up to current
let buildPath = "";
for (let i = 0; i < pathParts.length; i++) {
buildPath += "/" + pathParts[i];
parentDirs.push({
name: pathParts[i],
path: buildPath,
source: state.req.source,
isDirectory: true
});
}
return parentDirs.reverse(); // Show deepest first
},
getCurrentListingItems() {
// Get items from the current navigation listing (files in same directory)
const listing = state.navigation.listing || [];
return listing.map(item => ({
name: item.name, // Keep original names without emojis
path: item.path,
source: item.source || state.req.source,
type: item.type,
isDirectory: item.type === 'directory',
originalItem: item
}));
}
},
};
</script>
<style scoped>
/* Thin edge detection zones - minimal interference with content */
.nav-zone {
position: fixed;
top: 25%; /* Start at 25% from top */
bottom: 25%; /* End at 25% from bottom (so middle 50%) */
width: 3em; /* Reduced width to minimize content interference */
pointer-events: auto;
z-index: 5; /* Lower z-index so content can appear above */
background: transparent; /* Invisible zones for mouse/touch detection */
}
.nav-zone-left {
left: 0;
}
.nav-zone-right {
right: 0;
}
/* Removed navigation-buttons container to prevent content interaction blocking */
.nav-button {
position: fixed;
top: 50%;
transform: translateY(-50%);
width: 50px;
height: 50px;
border: none;
border-radius: 50%;
background: var(--background);
color: var(--textPrimary);
cursor: pointer;
transition: opacity 0.4s ease, transform 0.3s ease, background-color 0.3s ease, box-shadow 0.3s ease;
pointer-events: auto;
z-index: 1001;
display: flex;
align-items: center;
justify-content: center;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
opacity: 1;
}
.nav-button.dark-mode {
background: var(--surfacePrimary);
color: var(--textPrimary);
}
.nav-button:hover,
.nav-button.active {
background: var(--primaryColor);
transform: translateY(-50%) scale(1.1);
box-shadow:
inset 0 -3em 3em rgba(217, 217, 217, 0.211),
0 0 0 2px var(--alt-background),
0 4px 20px rgba(0, 0, 0, 0.4);
color: white;
opacity: 1;
}
.nav-previous {
left: 20px;
}
.nav-next {
right: 20px;
}
.nav-button.hidden {
opacity: 0;
transform: translateY(-50%) scale(0.9);
pointer-events: none !important; /* Ensure no interaction when hidden */
z-index: -1; /* Move behind content when hidden */
}
/* Smooth show animation for better UX */
.nav-button:not(.hidden) {
animation: nav-button-show 0.4s ease-out;
}
@keyframes nav-button-show {
0% {
opacity: 0;
transform: translateY(-50%) scale(0.8);
}
100% {
opacity: 1;
transform: translateY(-50%) scale(1);
}
}
.nav-button.dragging {
z-index: 1002;
cursor: grabbing;
transition: none; /* Disable transitions during drag for immediate response */
}
.nav-button i.material-icons {
font-size: 24px;
line-height: 1;
transition: transform 0.2s ease;
}
.nav-button:hover i.material-icons,
.nav-button.active i.material-icons {
transform: scale(1.1);
}
/* Mobile styles */
@media (max-width: 768px) {
.nav-button {
width: 44px;
height: 44px;
}
.nav-previous {
left: 10px;
}
.nav-next {
right: 10px;
}
.nav-button i.material-icons {
font-size: 20px;
}
/* Reduce animation intensity on mobile for better performance */
.nav-button:not(.hidden) {
animation-duration: 0.3s;
}
}
/* Ensure buttons don't interfere with scrollbars */
@media (max-width: 480px) {
.nav-previous {
left: 8px;
}
.nav-next {
right: 8px;
}
}
.moveWithSidebar {
margin-left: 20em;
}
</style>
+13 -12
View File
@@ -5,14 +5,6 @@
<div class="card-content">
<div v-if="isEditingPath">
<file-list @update:selected="updateTempPath" :browse-source="sourceName"></file-list>
<div style="margin-top: 1em; text-align: right;">
<button class="button button--flat" @click="cancelPathChange">
{{ $t("buttons.cancel") }}
</button>
<button class="button button--flat" @click="confirmPathChange">
{{ $t("buttons.ok") }}
</button>
</div>
</div>
<div v-else>
<p>{{ $t("prompts.source", { suffix: ":" }) }} {{ currentSource }}</p>
@@ -77,10 +69,19 @@
</div>
</div>
<div class="card-action">
<button v-if="!isEditingPath" @click="closeHovers" class="button button--flat button--grey"
:aria-label="$t('buttons.close')" :title="$t('buttons.close')">
{{ $t("buttons.close") }}
</button>
<template v-if="isEditingPath">
<button class="button button--flat" @click="cancelPathChange" :aria-label="$t('buttons.cancel')" :title="$t('buttons.cancel')">
{{ $t("buttons.cancel") }}
</button>
<button class="button button--flat" @click="confirmPathChange" :aria-label="$t('buttons.ok')" :title="$t('buttons.ok')">
{{ $t("buttons.ok") }}
</button>
</template>
<template v-else>
<button @click="closeHovers" class="button button--flat button--grey" :aria-label="$t('buttons.close')" :title="$t('buttons.close')">
{{ $t("buttons.close") }}
</button>
</template>
</div>
</template>
+149 -34
View File
@@ -1,51 +1,74 @@
<template>
<div>
<!-- Source Selection Dropdown (only show if multiple sources available) -->
<div v-if="availableSources.length > 1" class="source-selector" style="margin-bottom: 1rem;">
<div v-if="isDisplayMode" class="card-title">
<h2>{{ effectiveTitle }}</h2>
</div>
<div class="card-content">
<!-- Source Selection Dropdown (only show if multiple sources available and not in display mode) -->
<div v-if="availableSources.length > 1 && !isDisplayMode" class="source-selector" style="margin-bottom: 1rem;">
<label for="destinationSource" style="display: block; margin-bottom: 0.5rem; font-weight: bold;">
{{ $t("prompts.destinationSource") }}
</label>
<select id="destinationSource" v-model="currentSource" @change="onSourceChange"
class="input">
<select id="destinationSource" v-model="currentSource" @change="onSourceChange" class="input">
<option v-for="source in availableSources" :key="source" :value="source">
{{ source }}
</option>
</select>
</div>
<div>Source: {{ sourcePath.source }} </div> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<div aria-label="filelist-path" class="searchContext button clickable">{{$t('search.path')}} {{ sourcePath.path }}</div>
<div v-if="!isDisplayMode" aria-label="filelist-path" class="searchContext button clickable">{{ $t('search.path') }}
{{ sourcePath.path }}</div>
<ul class="file-list">
<li
@click="itemClick"
@touchstart="touchstart"
@dblclick="next"
role="button"
tabindex="0"
:aria-label="item.name"
:aria-selected="selected == item.path"
:key="item.name"
v-for="item in items"
:data-path="item.path"
>
{{ item.name }}
<li @click="itemClick" @touchstart="touchstart" @dblclick="next" role="button" tabindex="0"
:aria-label="item.name" :aria-selected="selected == item.path" :key="item.name" v-for="item in items"
:data-path="item.path" class="file-item">
<Icon v-if="isDisplayMode" :filename="item.name"
:mimetype="item.originalItem?.type || 'application/octet-stream'" :active="selected == item.path"
class="file-icon" />
<span class="file-name">{{ item.name }}</span>
</li>
</ul>
</div>
<!-- Cancel/Close button for display mode -->
<div v-if="isDisplayMode" class="card-action">
<button @click="closeModal" class="button button--flat" :aria-label="$t('buttons.cancel')"
:title="$t('buttons.cancel')">
{{ $t('buttons.cancel') }}
</button>
</div>
</template>
<script>
import { state, mutations } from "@/store";
import { url } from "@/utils";
import { filesApi } from "@/api";
import Icon from "@/components/files/Icon.vue";
export default {
name: "file-list",
components: {
Icon,
},
props: {
browseSource: {
type: String,
default: null,
},
fileList: {
type: Array,
default: null,
},
mode: {
type: String,
default: "browse", // 'browse', 'navigate-up', 'quick-jump'
},
title: {
type: String,
default: null,
},
},
data: function () {
const initialSource = this.browseSource || state.req.source;
@@ -66,6 +89,9 @@ export default {
};
},
computed: {
effectiveTitle() {
return this.title || this.$t("files.files");
},
sourcePath() {
return { source: this.source, path: this.path };
},
@@ -76,6 +102,10 @@ export default {
// Get all available sources from state.sources.info
return state.sources && state.sources.info ? Object.keys(state.sources.info) : [state.req.source];
},
isDisplayMode() {
// Display mode when fileList prop is provided (drag-triggered navigation)
return this.fileList !== null;
},
},
watch: {
browseSource(newSource) {
@@ -91,19 +121,24 @@ export default {
},
},
mounted() {
// Use currentSource if provided, otherwise use state.req
const sourceToUse = this.currentSource;
const pathToUse = this.currentSource !== state.req.source ? "/" : state.req.path;
const initialReq = {
...state.req,
source: sourceToUse,
path: pathToUse,
};
// Fetch the initial data for the source
if (this.currentSource !== state.req.source) {
filesApi.fetchFiles(sourceToUse, pathToUse).then(this.fillOptions);
if (this.isDisplayMode) {
// Display mode: use provided fileList
this.fillOptionsFromList();
} else {
this.fillOptions(initialReq);
// Normal browse mode: fetch files
const sourceToUse = this.currentSource;
const pathToUse = this.currentSource !== state.req.source ? "/" : state.req.path;
const initialReq = {
...state.req,
source: sourceToUse,
path: pathToUse,
};
// Fetch the initial data for the source
if (this.currentSource !== state.req.source) {
filesApi.fetchFiles(sourceToUse, pathToUse).then(this.fillOptions);
} else {
this.fillOptions(initialReq);
}
}
},
methods: {
@@ -193,8 +228,14 @@ export default {
}
},
itemClick: function (event) {
if (state.user.singleClick) this.next(event);
else this.select(event);
if (this.isDisplayMode) {
// In display mode, navigate directly to the item
this.navigateToItem(event);
} else if (state.user.singleClick) {
this.next(event);
} else {
this.select(event);
}
},
select: function (event) {
let path = event.currentTarget.dataset.path;
@@ -232,6 +273,80 @@ export default {
onSourceChange() {
this.resetToSource(this.currentSource);
},
// Display mode methods (for drag-triggered navigation)
fillOptionsFromList() {
// Use the provided fileList, filtering out directories to show only files
const allItems = this.fileList || [];
this.items = allItems.filter(item => !item.isDirectory && item.type !== 'directory');
this.current = this.title || "Navigation";
this.source = state.req.source;
// Emit the current info
this.$emit("update:selected", {
path: this.current,
source: this.source
});
},
navigateToItem(event) {
const path = event.currentTarget.dataset.path;
const item = this.items.find(item => item.path === path);
if (!item) return;
// Close the file list modal
mutations.closeHovers();
// Navigate to the item's URL
const itemUrl = url.buildItemUrl(item.source || state.req.source, item.path);
// Use router to navigate
this.$router.replace({ path: itemUrl });
},
closeModal() {
// Close the file list modal
mutations.closeHovers();
},
},
};
</script>
<style scoped>
.file-item {
display: flex;
align-items: center;
padding: 0.5rem;
cursor: pointer;
}
.file-item:hover {
background-color: var(--surfaceSecondary, rgba(0, 0, 0, 0.05));
}
.file-icon {
margin-right: 0.75rem;
flex-shrink: 0;
}
.file-name {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.file-list {
padding: 0;
margin: 0;
}
.file-list li[aria-selected=true] {
background: var(--primaryColor) !important;
color: #fff !important;
transition: .1s ease all;
}
</style>
+2 -3
View File
@@ -4,16 +4,15 @@
</div>
<div class="card-content">
<p>{{ $t("help.description") }} <a class="link" href="https://github.com/gtsteffaniak/filebrowser/wiki" target="_blank">{{ $t("help.wiki") }}</a></p>
<ul>
<li><strong>F1</strong> - {{ $t("help.f1") }}</li> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<li><strong>F2</strong> - {{ $t("help.f2") }}</li> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<li><strong>DEL</strong> - {{ $t("help.del") }}</li> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<li><strong>ESC</strong> - {{ $t("help.esc") }}</li> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<li><strong>CTRL + S</strong> - {{ $t("help.ctrl.s") }}</li> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<li><strong>CTRL + F</strong> - {{ $t("help.ctrl.f") }}</li> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<li><strong>CTRL + Click</strong> - {{ $t("help.ctrl.click") }}</li> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<li><strong>Click</strong> - {{ $t("help.click") }}</li> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<li><strong>Double click</strong> - {{ $t("help.doubleClick") }}</li> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<li><strong>CTRL + D</strong> - {{ $t("help.ctrl.d") }}</li> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</ul>
</div>
+3 -3
View File
@@ -56,9 +56,9 @@
</div>
<div class="card-action">
<button type="submit" @click="closeHovers" class="button button--flat" :aria-label="$t('buttons.ok')"
:title="$t('buttons.ok')">
{{ $t("buttons.ok") }}
<button type="submit" @click="closeHovers" class="button button--flat" :aria-label="$t('buttons.close')"
:title="$t('buttons.close')">
{{ $t("buttons.close") }}
</button>
</div>
</template>
+10 -2
View File
@@ -38,7 +38,7 @@ import buttons from "@/utils/buttons";
import * as upload from "@/utils/upload";
import { url } from "@/utils";
import { notify } from "@/notify";
import { removeLastDir } from "@/utils/url";
import { removeLastDir, goToItem } from "@/utils/url";
export default {
name: "move-copy",
@@ -171,7 +171,15 @@ export default {
}
mutations.closeHovers();
mutations.setSearch(false);
notify.showSuccess(`Server is ${this.operation === "copy" ? "copying" : "moving"} files...`);
if (this.operation === "move") {
notify.showSuccess(this.$t(`prompts.moveSuccess`));
} else {
notify.showSuccess(this.$t(`prompts.copySuccess`));
}
// Navigate to the destination folder after successful operation
if (this.destSource && this.destPath) {
goToItem(this.destSource, this.destPath);
}
} catch (error) {
notify.showError(error);
}
@@ -31,6 +31,7 @@ import buttons from "@/utils/buttons";
import Totp from "./Totp.vue";
import Access from "./Access.vue";
import Password from "./Password.vue";
import FileList from "./FileList.vue";
import { state, getters, mutations } from "@/store"; // Import your custom store
export default {
@@ -58,6 +59,7 @@ export default {
ActionApi,
Access,
Password,
"file-list": FileList,
},
data() {
return {
+50 -15
View File
@@ -4,11 +4,16 @@
</div>
<div class="card-content">
<p>{{ $t("prompts.renameMessage", { filename: oldName }) }}</p>
<input class="input" :class="{ 'form-invalid': !validateFileName(name) }" v-focus type="text"
@keyup.enter="submit" v-model.trim="name" />
<p v-if="!validateFileName(name) && name.length > 0" class="validation-error">
{{ $t("prompts.invalidName") }}
<p>{{ $t("prompts.renameMessage") }}</p>
<input class="input" :class="{ 'form-invalid': !validation.valid }" v-focus type="text" @keyup.enter="submit"
v-model.trim="name" />
<p v-if="!validation.valid && name.length > 0" class="validation-error">
<span v-if="validation.reason === 'conflict'">
{{ $t("prompts.renameMessageConflict", { filename: name }) }}
</span>
<span v-else>
{{ $t("prompts.renameMessageInvalid") }}
</span>
</p>
</div>
@@ -17,7 +22,7 @@
:title="$t('buttons.cancel')">
{{ $t("buttons.cancel") }}
</button>
<button @click="submit" class="button button--flat" :disabled="!validateFileName(name) || name.length === 0"
<button @click="submit" class="button button--flat" :disabled="!validation.valid || name.length === 0"
type="submit" :aria-label="$t('buttons.rename')" :title="$t('buttons.rename')">
{{ $t("buttons.rename") }}
</button>
@@ -25,7 +30,7 @@
</template>
<script>
import { filesApi } from "@/api";
import { mutations } from "@/store";
import { mutations, state } from "@/store";
import { notify } from "@/notify";
export default {
@@ -49,6 +54,9 @@ export default {
oldName() {
return this.item?.name || "";
},
validation() {
return this.validateFileName(this.name);
}
},
methods: {
/**
@@ -56,24 +64,51 @@ export default {
*/
validateFileName(value) {
if (value === "") {
return false;
return { valid: true };
}
// Check for forbidden characters: forward slash and backslash
const forbiddenChars = /[/\\]/;
return !forbiddenChars.test(value);
const isFolder = this.item.type === "directory";
// Check for forbidden characters in file names
if (!isFolder) {
const forbiddenChars = /[/\\]/;
if (forbiddenChars.test(value)) {
return { valid: false, reason: 'invalidChar' };
}
}
// Check if the item already exists
for (const item of state.req.items) {
if (item.name.toLowerCase() === value.toLowerCase()) {
if (isFolder === (item.type === "directory")) {
return { valid: false, reason: 'conflict' };
}
}
}
return { valid: true };
},
async submit() {
// Validate before submitting
if (!this.validateFileName(this.name) || this.name.length === 0) {
notify.showError(this.$t("prompts.invalidName"));
// remove trailing slashes
if (this.name.endsWith("/") || this.name.endsWith("\\")) {
this.name = this.name.substring(0, this.name.length - 1);
}
if (!this.validation.valid) {
return;
}
let newPath = this.item.path.substring(0, this.item.path.lastIndexOf("/"));
newPath = `${newPath}/${this.name}`;
try {
if (this.name === this.item.name) {
mutations.closeHovers();
return;
}
const items = [{
from: this.item.path,
fromSource: this.item.source,
to: this.item.path.replace(/[^/]+$/, this.name),
to: newPath,
toSource: this.item.source,
}];
+68 -83
View File
@@ -89,6 +89,25 @@
/>
<ToggleSwitch class="item" v-model="disableAnonymous" :name="$t('share.disableAnonymous')" :description="$t('share.disableAnonymousDescription')" />
<ToggleSwitch class="item" v-model="enableAllowedUsernames" :name="$t('share.enableAllowedUsernames')" :description="$t('share.enableAllowedUsernamesDescription')" />
<ToggleSwitch v-if="onlyOfficeAvailable" class="item" v-model="enableOnlyOffice" :name="$t('share.enableOnlyOffice')" :description="$t('share.enableOnlyOfficeDescription')" />
<ToggleSwitch v-if="onlyOfficeAvailable" class="item" v-model="enableOnlyOfficeEditing" :name="$t('share.enableOnlyOfficeEditing')" :description="$t('share.enableOnlyOfficeEditingDescription')" />
<p>
{{ $t("share.enforceDarkLightMode") }}
<i
class="no-select material-symbols-outlined tooltip-info-icon"
@mouseenter="showTooltip($event, $t('share.enforceDarkLightModeDescription'))"
@mouseleave="hideTooltip"
>
help
</i>
</p>
<select class="input" v-model="enforceDarkLightMode">
<option value="default">{{ $t("share.default") }}</option>
<option value="dark">{{ $t("share.dark") }}</option>
<option value="light">{{ $t("share.light") }}</option>
</select>
<div v-if="enableAllowedUsernames" class="item">
<input class="input" type="text" v-model.trim="allowedUsernames" :placeholder="$t('share.allowedUsernamesPlaceholder')" />
</div>
@@ -111,26 +130,23 @@
</option>
</select>
</div>
<div class="advanced-toggle">
<button
class="button button--flat button--block"
@click="showAdvanced = !showAdvanced"
:aria-expanded="showAdvanced ? 'true' : 'false'"
aria-controls="advanced-settings"
:aria-label="showAdvanced ? $t('buttons.showLess') : $t('buttons.showMore')"
:title="showAdvanced ? $t('buttons.showLess') : $t('buttons.showMore')"
>
{{ showAdvanced ? $t('buttons.showLess') : $t('buttons.showMore') }}
</button>
</div>
<transition
name="expand"
@before-enter="beforeEnter"
@enter="enter"
@leave="leave"
>
<div id="advanced-settings" v-show="showAdvanced">
<p>
{{ $t("share.defaultViewMode") }}
<i
class="no-select material-symbols-outlined tooltip-info-icon"
@mouseenter="showTooltip($event, $t('share.defaultViewModeDescription'))"
@mouseleave="hideTooltip"
>
help
</i>
</p>
<select class="input" v-model="viewMode">
<option value="normal">{{ $t("buttons.normalView") }}</option>
<option value="list">{{ $t("buttons.listView") }}</option>
<option value="compact">{{ $t("buttons.compactView") }}</option>
<option value="gallery">{{ $t("buttons.galleryView") }}</option>
</select>
<SettingsItem :title="$t('buttons.showMore')" :collapsable="true" :start-collapsed="true">
<div class="settings-items">
<ToggleSwitch class="item" v-model="keepAfterExpiration" :name="$t('share.keepAfterExpiration')" :description="$t('share.keepAfterExpirationDescription')" />
<ToggleSwitch class="item" v-model="disableThumbnails" :name="$t('share.disableThumbnails')" :description="$t('share.disableThumbnailsDescription')" />
@@ -222,8 +238,7 @@
</i>
</p>
<input class="input" type="text" v-model.trim="favicon" />
</div>
</transition>
</SettingsItem>
</div>
</div>
@@ -250,12 +265,13 @@
<script>
import { notify } from "@/notify";
import { state, getters, mutations } from "@/store";
import { publicApi } from "@/api";
import { publicApi, shareApi } from "@/api";
import Clipboard from "clipboard";
import { fromNow } from "@/utils/moment";
import { buildItemUrl, fixDownloadURL } from "@/utils/url";
import ToggleSwitch from "@/components/settings/ToggleSwitch.vue";
import { userSelectableThemes, externalUrl } from "@/utils/constants";
import SettingsItem from "@/components/settings/SettingsItem.vue";
import { globalVars } from "@/utils/constants";
import { eventBus } from "@/store/eventBus";
//import ViewMode from "@/components/settings/ViewMode.vue";
@@ -263,6 +279,7 @@ export default {
name: "share",
components: {
ToggleSwitch,
SettingsItem,
//ViewMode,
},
props: {
@@ -310,17 +327,23 @@ export default {
title: "",
description: "",
favicon: "",
showAdvanced: false,
quickDownload: false,
disableNavButtons: false,
disableShareCard: false,
disableSidebar: false,
enforceDarkLightMode: "default",
viewMode: "normal",
enableOnlyOffice: false,
enableOnlyOfficeEditing: false,
//viewMode: "normal",
};
},
computed: {
onlyOfficeAvailable() {
return globalVars.onlyOfficeUrl !== "";
},
availableThemes() {
return userSelectableThemes || {};
return globalVars.userSelectableThemes || {};
},
closeHovers() {
return mutations.closeHovers;
@@ -390,6 +413,10 @@ export default {
this.disableNavButtons = this.link.hideNavButtons || false;
this.disableShareCard = this.link.disableShareCard || false;
this.disableSidebar = this.link.disableSidebar || false;
this.enforceDarkLightMode = this.link.enforceDarkLightMode || "default";
this.viewMode = this.link.viewMode || "normal";
this.enableOnlyOffice = this.link.enableOnlyOffice || false;
this.enableOnlyOfficeEditing = this.link.enableOnlyOfficeEditing || false;
//this.viewMode = this.link.viewMode || "normal";
}
},
@@ -401,7 +428,7 @@ export default {
}
try {
// get last element of the path
const links = await publicApi.get(this.item.path, this.item.source);
const links = await shareApi.get(this.item.path, this.item.source);
this.links = links;
} catch (err) {
notify.showError(err);
@@ -420,45 +447,6 @@ export default {
});
},
methods: {
/**
* @param {Element} el
*/
beforeEnter(el) {
const element = /** @type {HTMLElement} */ (el);
element.style.height = '0';
element.style.opacity = '0';
},
/**
* @param {Element} el
* @param {() => void} done
*/
enter(el, done) {
const element = /** @type {HTMLElement} */ (el);
element.style.transition = '';
element.style.height = '0';
element.style.opacity = '0';
void element.offsetHeight;
element.style.transition = 'height 0.3s, opacity 0.3s';
element.style.height = element.scrollHeight + 'px';
element.style.opacity = '1';
setTimeout(() => {
element.style.height = 'auto';
done();
}, 300);
},
/**
* @param {Element} el
* @param {() => void} done
*/
leave(el, done) {
const element = /** @type {HTMLElement} */ (el);
element.style.transition = 'height 0.3s, opacity 0.3s';
element.style.height = element.scrollHeight + 'px';
void element.offsetHeight;
element.style.height = '0';
element.style.opacity = '0';
setTimeout(done, 300);
},
/**
* @param {MouseEvent} event
* @param {string} text
@@ -507,12 +495,16 @@ export default {
hideNavButtons: this.disableNavButtons,
disableShareCard: this.disableShareCard,
disableSidebar: this.disableSidebar,
enforceDarkLightMode: this.enforceDarkLightMode,
viewMode: this.viewMode,
enableOnlyOffice: this.enableOnlyOffice,
enableOnlyOfficeEditing: this.enableOnlyOfficeEditing,
};
if (this.isEditMode) {
payload.hash = this.link.hash;
}
const res = await publicApi.create(payload);
const res = await shareApi.create(payload);
if (!this.isEditMode) {
this.links.push(res);
@@ -539,7 +531,7 @@ export default {
async deleteLink(event, link) {
event.preventDefault();
try {
await publicApi.remove(link.hash);
await shareApi.remove(link.hash);
this.links = this.links.filter((item) => item.hash !== link.hash);
// emit event to reload shares in settings view
eventBus.emit('sharesChanged');
@@ -570,7 +562,14 @@ export default {
* @param {Share} share
*/
buildDownloadLink(share) {
if (share.downloadURL && externalUrl == "") {
if (share.downloadURL) {
// Only fix the URL if it doesn't already have the correct external domain
if (globalVars.externalUrl) {
// URL already has the correct external domain, use as-is
return share.downloadURL;
}
// URL needs fixing (internal domain or no externalUrl set)
return this.fixDownloadURL(share.downloadURL);
}
return publicApi.getDownloadURL(share, [this.item.name]);
@@ -599,9 +598,6 @@ export default {
<style scoped>
.advanced-toggle {
margin-top: 1em;
}
.setting-item {
display: flex;
justify-content: space-between;
@@ -619,15 +615,4 @@ export default {
.input {
height: auto;
}
.expand-enter-active,
.expand-leave-active {
transition: height 0.3s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.3s cubic-bezier(0.4, 0, 0.2, 1);
overflow: hidden;
}
.expand-enter,
.expand-leave-to {
height: 0 !important;
opacity: 0;
}
</style>
+21 -4
View File
@@ -48,7 +48,8 @@
? $t('prompts.conflictsDetected')
: (file.progress / 100) * file.size
" :unit="file.status === 'completed' || file.status === 'error' ? '' : 'bytes'" :max="file.size"
:status="file.status" text-position="inside" size="20">
:status="file.status" text-position="inside" size="20"
:help-text="file.status === 'error' && file.errorDetails ? file.errorDetails : ''">
</progress-bar>
<div v-else class="status-label">
<span>{{ $t(`prompts.${file.status}`) }}</span>
@@ -94,7 +95,7 @@
:aria-label="$t('buttons.resumeAll')" :title="$t('buttons.resumeAll')">
{{ $t("buttons.resumeAll") }}
</button>
<button @click="clearCompleted" class="button button--flat" :disabled="!hasCompleted"
<button @click="clearCompleted" class="button button--flat" :disabled="!hasClearable"
:aria-label="$t('buttons.clearCompleted')" :title="$t('buttons.clearCompleted')">
{{ $t("buttons.clearCompleted") }}
</button>
@@ -184,7 +185,7 @@ export default {
console.error("No conflicting folder found for rename");
return;
}
mutations.showHover({
name: "rename",
confirm: (newName) => {
@@ -205,7 +206,7 @@ export default {
// Update upload manager with the new folder name
await uploadManager.renameFolder(oldName, newName);
// Resolve the conflict and continue upload
if (conflictResolver) {
conflictResolver({ rename: newName });
@@ -256,6 +257,21 @@ export default {
files.value.some((file) => file.status === "completed")
);
const hasClearable = computed(() => {
if (state.user.fileLoading?.clearAll) {
// For "clear all" mode: check for completed, error, conflict, or paused uploads
return files.value.some((file) =>
file.status === "completed" ||
file.status === "error" ||
file.status === "conflict" ||
file.status === "paused"
);
} else {
// For "clear completed" mode: only check for completed uploads
return files.value.some((file) => file.status === "completed");
}
});
const canPauseAll = computed(() =>
files.value.some((file) => file.status === "uploading")
);
@@ -447,6 +463,7 @@ export default {
close,
clearCompleted,
hasCompleted,
hasClearable,
showConflictPrompt,
resolveConflict,
showRenamePrompt,
+350 -34
View File
@@ -1,42 +1,228 @@
<template>
<errors v-if="error" :errorCode="error.status" />
<form @submit.prevent="save" v-if="loaded">
<div class="card-title">
<h2 v-if="isNew">{{ $t("settings.newUser") }}</h2>
<h2 v-else-if="actor.id == user.id">
{{ $t("settings.modifyCurrentUser") }} {{ user.username }}
</h2>
<h2 v-else>{{ $t("settings.modifyOtherUser") }} {{ user.username }}</h2>
<div class="card-title">
<h2 v-if="isNew">{{ $t("settings.newUser") }}</h2>
<h2 v-else-if="actor.id == user.id">
{{ $t("settings.modifyCurrentUser") }} {{ user.username }}
</h2>
<h2 v-else>{{ $t("settings.modifyOtherUser") }} {{ user.username }}</h2>
</div>
<div class="card-content">
<errors v-if="error" :errorCode="error.status" />
<h2
class="message"
v-if="user.loginMethod != 'password' && !stateUser.permissions.admin"
>
<i class="material-icons">sentiment_dissatisfied</i>
<span>{{ $t("files.lonely") }}</span>
</h2>
<div v-if="user.loginMethod == 'password' && globalVars.passwordAvailable && !isNew">
<label for="password">{{ $t("settings.password") }}</label>
<div class="form-flex-group">
<input
class="input form-form"
:class="{ 'form-invalid': invalidPassword }"
aria-label="Password1"
type="password"
autocomplete="new-password"
:placeholder="$t('settings.enterPassword')"
v-model="passwordRef"
/>
</div>
<div class="form-flex-group">
<input
class="input form-form"
:class="{ 'flat-right': !isNew, 'form-invalid': invalidPassword }"
aria-label="Password2"
type="password"
autocomplete="new-password"
:placeholder="$t('settings.enterPasswordAgain')"
v-model="user.password"
id="password"
/>
<button
v-if="!isNew"
type="button"
class="button form-button flat-left"
@click="submitUpdatePassword"
>
{{ $t("buttons.update") }}
</button>
</div>
<div
style="display: flex; flex-direction: column"
>
<div class="settings-items">
<ToggleSwitch class="item" v-model="user.otpEnabled" :name="$t('otp.name')" />
</div>
<button class="button" type="button" v-if="user.otpEnabled" @click="newOTP" aria-label="Generate Code">
{{ $t("buttons.generateNewOtp") }}
</button>
</div>
<hr />
</div>
<div class="card-content minimal-card">
<user-form v-model:user="user" :createUserDir="createUserDir" :isNew="isNew"
@update:createUserDir="(updatedDir) => (createUserDir = updatedDir)" />
</div>
<div v-if="actor.permissions.admin" class="card-action">
<button class="button button--flat button--grey" @click="closeHovers" :aria-label="$t('buttons.cancel')"
:title="$t('buttons.cancel')">
{{ $t("buttons.cancel") }}
<div v-if="stateUser.permissions.admin">
<p v-if="isNew">
<label for="username">{{ $t("settings.username") }}</label>
<input
class="input"
type="text"
v-model="user.username"
id="username"
@input="emitUpdate"
/>
</p>
<div v-if="user.loginMethod == 'password' && globalVars.passwordAvailable && isNew">
<label for="password">{{ $t("settings.password") }}</label>
<div class="form-flex-group">
<input
class="input form-form"
:class="{ 'form-invalid': invalidPassword }"
aria-label="Password1"
type="password"
:placeholder="$t('settings.enterPassword')"
v-model="passwordRef"
/>
</div>
<div class="form-flex-group">
<input
class="input form-form"
:class="{ 'flat-right': !isNew, 'form-invalid': invalidPassword }"
type="password"
:placeholder="$t('settings.enterPasswordAgain')"
aria-label="Password2"
v-model="user.password"
autocomplete="new-password"
id="password"
/>
<button
v-if="!isNew"
type="button"
class="button form-button flat-left"
@click="submitUpdatePassword"
>
{{ $t("buttons.update") }}
</button>
</div>
</div>
<div
v-if="user.loginMethod == 'password' && globalVars.passwordAvailable"
class="settings-items"
>
<ToggleSwitch
v-if="user.loginMethod === 'password' && stateUser.permissions?.admin"
class="item"
:modelValue="user.lockPassword"
@update:modelValue="(val) => updateUserField('lockPassword', val)"
:name="$t('settings.lockPassword')"
/>
</div>
<div style="padding-bottom: 1em" v-if="stateUser.permissions.admin">
<label for="scopes">{{ $t("settings.scopes") }}</label>
<div
class="scope-list"
:class="{ 'form-invalid': duplicateSources.includes(source.name) }"
v-for="(source, index) in selectedSources"
:key="index"
>
<select
@change="handleSourceChange(source, $event, source.name)"
class="input flat-right"
v-model="source.name"
>
<option v-for="s in sourceList" :key="s.name" :value="s.name">
{{ s.name }}
</option>
</select>
<input
class="input flat-left scope-input"
placeholder="scope eg. '/subfolder', leave blank for default path"
@input="updateParent({ source: source, input: $event })"
:value="source.scope"
:class="{ 'flat-right': selectedSources.length > 1 }"
/>
<button
v-if="selectedSources.length > 1"
class="button flat-left no-height"
@click="removeScope(index)"
>
<i class="material-icons material-size">delete</i>
</button>
</div>
</div>
<button v-if="hasMoreSources" @click="addNewScopeSource" class="button no-height">
<i class="material-icons material-size">add</i>
</button>
<button v-if="!isNew" @click.prevent="deletePrompt" type="button" class="button button--flat button--red"
aria-label="Delete User" :title="$t('buttons.delete')">
{{ $t("buttons.delete") }}
</button>
<input aria-label="Save User" class="save-button button button--flat" type="submit" :value="$t('buttons.save')" />
<div class="settings-items">
<ToggleSwitch
v-if="displayHomeDirectoryCheckbox"
class="item"
v-model="createUserDir"
:name="$t('settings.createUserHomeDirectory')"
/>
</div>
<p v-if="stateUser.username !== user.username">
<label for="locale">{{ $t("settings.language") }}</label>
<languages
class="input"
id="locale"
v-model:locale="user.locale"
@input="emitUpdate"
></languages>
</p>
<div v-if="stateUser.permissions.admin">
<label for="loginMethod">{{ $t("settings.loginMethodDescription") }}</label>
<select v-model="user.loginMethod" class="input" id="loginMethod">
<option value="password">Password</option> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<option value="oidc">OIDC</option> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<option value="proxy">Proxy</option> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</select>
</div>
<permissions v-if="stateUser.permissions.admin" :permissions="user.permissions" />
</div>
</form>
</div>
<div class="card-action">
<button class="button button--flat button--grey" @click="closeHovers" :aria-label="$t('buttons.cancel')"
:title="$t('buttons.cancel')">
{{ $t("buttons.cancel") }}
</button>
<button v-if="!isNew" @click.prevent="deletePrompt" type="button" class="button button--flat button--red"
aria-label="Delete User" :title="$t('buttons.delete')">
{{ $t("buttons.delete") }}
</button>
<button @click="save" class="button button--flat" :aria-label="$t('buttons.save')" :title="$t('buttons.save')">
{{ $t("buttons.save") }}
</button>
</div>
</template>
<script>
import { mutations, state } from "@/store";
import { usersApi, settingsApi } from "@/api";
import UserForm from "@/components/settings/UserForm.vue";
import Languages from "@/components/settings/Languages.vue";
import Permissions from "@/components/settings/Permissions.vue";
import ToggleSwitch from "@/components/settings/ToggleSwitch.vue";
import Errors from "@/views/Errors.vue";
import { notify } from "@/notify";
import { globalVars } from "@/utils/constants";
export default {
name: "user-edit",
components: {
UserForm,
Languages,
Permissions,
ToggleSwitch,
Errors,
},
props: {
@@ -59,10 +245,16 @@ export default {
showDelete: false,
createUserDir: false,
loaded: false,
originalUserScope: ".",
sourceList: [],
availableSources: [],
selectedSources: [],
passwordRef: "",
};
},
created() {
this.fetchData();
async created() {
await this.fetchData();
await this.initializeForm();
},
computed: {
actor() {
@@ -74,6 +266,39 @@ export default {
isNew() {
return !this.userId;
},
stateUser() {
return state.user;
},
invalidPassword() {
const matching =
this.user.password != this.passwordRef && this.user.password.length > 0;
return matching;
},
passwordAvailable: () => globalVars.passwordAvailable,
globalVars: () => globalVars,
duplicateSources() {
const names = this.selectedSources.map((s) => s.name);
return names.filter((name, idx) => names.indexOf(name) !== idx);
},
hasMoreSources() {
return this.selectedSources.length < this.sourceList.length;
},
passwordPlaceholder() {
return this.isNew ? "" : this.$t("settings.avoidChanges");
},
displayHomeDirectoryCheckbox() {
return this.isNew && this.createUserDir;
},
},
watch: {
createUserDir(newVal) {
this.user.scopes = newVal ? { default: "" } : this.originalUserScope;
this.emitUserUpdate();
},
stateUser() {
this.user.otpEnabled = state.user.otpEnabled;
this.emitUserUpdate();
},
},
methods: {
closeHovers() {
@@ -102,6 +327,27 @@ export default {
this.loaded = true;
}
},
async initializeForm() {
if (!this.stateUser.permissions.admin) {
this.sourceList = this.user.scopes || [];
} else {
this.sourceList = await settingsApi.get("sources");
}
this.user.password = this.user.password || "";
this.selectedSources = this.user.scopes || [];
this.availableSources = this.sourceList.filter(
(s) => !this.selectedSources.some((sel) => sel.name === s.name)
);
if (this.isNew && this.availableSources.length) {
const newSource = this.availableSources.shift();
if (newSource) {
this.selectedSources.push(newSource);
this.emitUserUpdate();
}
}
},
deletePrompt() {
mutations.showHover({ name: "deleteUser", props: { user: this.user } });
},
@@ -114,10 +360,10 @@ export default {
return;
}
if (this.isNew) {
await usersApi.create(this.user); // Use the computed property
await usersApi.create({ ...this.user, scopes: this.selectedSources });
this.$router.push({ path: "/settings", hash: "#users-main" });
} else {
await usersApi.update(this.user, fields);
await usersApi.update({ ...this.user, scopes: this.selectedSources }, fields);
notify.showSuccess(this.$t("settings.userUpdated"));
}
window.location.reload();
@@ -125,18 +371,88 @@ export default {
notify.showError(e);
}
},
newOTP() {
mutations.showHover({
name: "totp",
props: {
generate: true,
},
});
},
async submitUpdatePassword() {
event.preventDefault();
if (this.invalidPassword) {
notify.showError(this.$t("settings.passwordsDoNotMatch"));
return;
}
try {
await usersApi.update(this.user, ["password"]);
notify.showSuccess(this.$t("settings.userUpdated"));
} catch (e) {
notify.showError(e);
}
},
emitUserUpdate() {
// Update the user object with current scopes
this.user = { ...this.user, scopes: this.selectedSources };
},
emitUpdate() {
// Update the user object
this.user = { ...this.user };
},
setUpdatePassword() {
// This method is kept for compatibility but not used in the new structure
},
updateParent(input) {
const updatedScopes = this.selectedSources.map((source) =>
source.name === input.source.name
? { ...source, scope: input.input.target.value }
: source
);
this.selectedSources = updatedScopes;
this.emitUserUpdate();
},
addNewScopeSource(event) {
event.preventDefault();
if (this.hasMoreSources) {
this.selectedSources.push({ name: "", scope: "" });
this.emitUserUpdate();
}
},
removeScope(index) {
const removed = this.selectedSources.splice(index, 1)[0];
this.availableSources.push({ name: removed.name });
this.emitUserUpdate();
},
handleSourceChange(source, event, oldName) {
const newName = event.target.value;
this.availableSources = this.availableSources.filter((s) => s.name !== newName);
if (oldName && !this.availableSources.find((s) => s.name === oldName)) {
this.availableSources.push({ name: oldName });
}
source.name = newName;
this.emitUserUpdate();
},
updateUserField(field, value) {
this.user[field] = value;
this.emitUserUpdate();
},
},
};
</script>
<style scoped>
.minimal-card {
/* margin-bottom: 16px; */
padding-top: 0 !important;
padding-bottom: 0 !important;
.scope-list {
display: flex;
}
.save-button {
width: 33%;
.scope-input {
width: 100%;
}
.no-height {
height: unset;
}
.material-size {
font-size: 1em !important;
}
</style>
@@ -0,0 +1,166 @@
<template>
<div class="settings-group">
<div class="settings-group-title button" :class="{ 'unclickable': !collapsable }"
@click="collapsable ? toggleCollapse() : null">
<h3>{{ title }}</h3>
<i v-if="collapsable" class="material-symbols-outlined collapse-icon" :class="{ 'rotated': !actuallyCollapsed }">
expand_more
</i>
</div>
<transition name="expand" @before-enter="beforeEnter" @enter="enter" @leave="leave">
<div v-show="!actuallyCollapsed" class="settings-content">
<slot></slot>
</div>
</transition>
</div>
</template>
<script>
export default {
name: 'SettingsItem',
props: {
title: {
type: String,
required: true
},
collapsable: {
type: Boolean,
default: false
},
startCollapsed: {
type: Boolean,
default: false
},
forceCollapsed: {
type: Boolean,
default: null
}
},
data() {
return {
isCollapsed: this.startCollapsed
}
},
computed: {
actuallyCollapsed() {
// If forceCollapsed is explicitly set, use that, otherwise use internal state
return this.forceCollapsed !== null ? this.forceCollapsed : this.isCollapsed;
}
},
watch: {
forceCollapsed(newVal) {
if (newVal !== null) {
this.isCollapsed = newVal;
}
}
},
methods: {
toggleCollapse() {
if (this.forceCollapsed !== null) {
// Emit event for parent to handle accordion logic
this.$emit('toggle', this.title);
} else {
// Handle internally as before
this.isCollapsed = !this.isCollapsed;
}
},
/**
* @param {Element} el
*/
beforeEnter(el) {
const element = /** @type {HTMLElement} */ (el);
element.style.height = '0';
element.style.opacity = '0';
},
/**
* @param {Element} el
* @param {() => void} done
*/
enter(el, done) {
const element = /** @type {HTMLElement} */ (el);
element.style.transition = '';
element.style.height = '0';
element.style.opacity = '0';
void element.offsetHeight;
element.style.transition = 'height 0.3s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.3s cubic-bezier(0.4, 0, 0.2, 1)';
element.style.height = element.scrollHeight + 'px';
element.style.opacity = '1';
setTimeout(() => {
element.style.height = 'auto';
done();
}, 300);
},
/**
* @param {Element} el
* @param {() => void} done
*/
leave(el, done) {
const element = /** @type {HTMLElement} */ (el);
element.style.transition = 'height 0.3s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.3s cubic-bezier(0.4, 0, 0.2, 1)';
element.style.height = element.scrollHeight + 'px';
void element.offsetHeight;
element.style.height = '0';
element.style.opacity = '0';
setTimeout(done, 300);
},
}
}
</script>
<style scoped>
.settings-group-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 1em;
background: var(--alt-background) !important;
color: var(--textPrimary) !important;
padding: 0.5em;
}
.settings-group-title h3 {
margin: 0;
flex: 1;
}
.collapse-icon {
transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
color: var(--textSecondary);
}
.collapse-icon.rotated {
transform: rotate(180deg);
}
.settings-content {
overflow: hidden;
margin-top: 0.5em;
}
.expand-enter-active,
.expand-leave-active {
transition: height 0.3s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.3s cubic-bezier(0.4, 0, 0.2, 1);
overflow: hidden;
}
.expand-enter,
.expand-leave-to {
height: 0 !important;
opacity: 0;
}
.settings-group-title.unclickable {
cursor: default;
user-select: none;
transition: opacity 0.2s ease;
}
/* Prevent content height issues during animation */
.settings-content .input,
.settings-content .settings-items {
height: auto;
}
</style>
@@ -1,350 +0,0 @@
<template>
<h2
class="message"
v-if="user.loginMethod != 'password' && !stateUser.permissions.admin"
>
<i class="material-icons">sentiment_dissatisfied</i>
<span>{{ $t("files.lonely") }}</span>
</h2>
<div v-if="user.loginMethod == 'password' && passwordAvailable && !isNew">
<label for="password">{{ $t("settings.password") }}</label>
<div class="form-flex-group">
<input
class="input form-form"
:class="{ 'form-invalid': invalidPassword }"
aria-label="Password1"
type="password"
autocomplete="new-password"
:placeholder="$t('settings.enterPassword')"
v-model="passwordRef"
/>
</div>
<div class="form-flex-group">
<input
class="input form-form"
:class="{ 'flat-right': !isNew, 'form-invalid': invalidPassword }"
aria-label="Password2"
type="password"
autocomplete="new-password"
:placeholder="$t('settings.enterPasswordAgain')"
v-model="user.password"
id="password"
/>
<button
v-if="!isNew"
type="button"
class="button form-button flat-left"
@click="submitUpdatePassword"
>
{{ $t("buttons.update") }}
</button>
</div>
<div
style="display: flex; flex-direction: column"
>
<div class="settings-items">
<ToggleSwitch class="item" v-model="user.otpEnabled" :name="$t('otp.name')" />
</div>
<button class="button" type="button" v-if="user.otpEnabled" :onclick="newOTP" aria-label="Generate Code">
{{ $t("buttons.generateNewOtp") }}
</button>
</div>
<hr />
</div>
<div v-if="stateUser.permissions.admin">
<p v-if="isNew">
<label for="username">{{ $t("settings.username") }}</label>
<input
class="input"
type="text"
v-model="user.username"
id="username"
@input="emitUpdate"
/>
</p>
<div v-if="user.loginMethod == 'password' && passwordAvailable && isNew">
<label for="password">{{ $t("settings.password") }}</label>
<div class="form-flex-group">
<input
class="input form-form"
:class="{ 'form-invalid': invalidPassword }"
aria-label="Password1"
type="password"
:placeholder="$t('settings.enterPassword')"
v-model="passwordRef"
/>
</div>
<div class="form-flex-group">
<input
class="input form-form"
:class="{ 'flat-right': !isNew, 'form-invalid': invalidPassword }"
type="password"
:placeholder="$t('settings.enterPasswordAgain')"
aria-label="Password2"
v-model="user.password"
autocomplete="new-password"
id="password"
/>
<button
v-if="!isNew"
type="button"
class="button form-button flat-left"
@click="submitUpdatePassword"
>
{{ $t("buttons.update") }}
</button>
</div>
</div>
<div
v-if="user.loginMethod == 'password' && passwordAvailable"
class="settings-items"
>
<ToggleSwitch
v-if="user.loginMethod === 'password' && stateUser.permissions?.admin"
class="item"
:modelValue="user.lockPassword"
@update:modelValue="(val) => updateUserField('lockPassword', val)"
:name="$t('settings.lockPassword')"
/>
</div>
<div style="padding-bottom: 1em" v-if="stateUser.permissions.admin">
<label for="scopes">{{ $t("settings.scopes") }}</label>
<div
class="scope-list"
:class="{ 'form-invalid': duplicateSources.includes(source.name) }"
v-for="(source, index) in selectedSources"
:key="index"
>
<select
@change="handleSourceChange(source, $event, source.name)"
class="input flat-right"
v-model="source.name"
>
<option v-for="s in sourceList" :key="s.name" :value="s.name">
{{ s.name }}
</option>
</select>
<input
class="input flat-left scope-input"
placeholder="scope eg. '/subfolder', leave blank for default path"
@input="updateParent({ source: source, input: $event })"
:value="source.scope"
:class="{ 'flat-right': selectedSources.length > 1 }"
/>
<button
v-if="selectedSources.length > 1"
class="button flat-left no-height"
@click="removeScope(index)"
>
<i class="material-icons material-size">delete</i>
</button>
</div>
</div>
<button v-if="hasMoreSources" @click="addNewScopeSource" class="button no-height">
<i class="material-icons material-size">add</i>
</button>
<div class="settings-items">
<ToggleSwitch
v-if="displayHomeDirectoryCheckbox"
class="item"
v-model="createUserDir"
:name="$t('settings.createUserHomeDirectory')"
/>
</div>
<p v-if="stateUser.username !== user.username">
<label for="locale">{{ $t("settings.language") }}</label>
<languages
class="input"
id="locale"
v-model:locale="user.locale"
@input="emitUpdate"
></languages>
</p>
<div v-if="stateUser.permissions.admin">
<label for="loginMethod">{{ $t("settings.loginMethodDescription") }}</label>
<select v-model="user.loginMethod" class="input" id="loginMethod">
<option value="password">Password</option> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<option value="oidc">OIDC</option> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<option value="proxy">Proxy</option> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</select>
</div>
<permissions v-if="stateUser.permissions.admin" :permissions="user.permissions" />
</div>
</template>
<script>
import Languages from "./Languages.vue";
import Permissions from "./Permissions.vue";
import { mutations, state } from "@/store";
import ToggleSwitch from "@/components/settings/ToggleSwitch.vue";
import { notify } from "@/notify";
import { usersApi, settingsApi } from "@/api";
import { passwordAvailable } from "@/utils/constants";
export default {
name: "UserForm",
components: {
Permissions,
Languages,
ToggleSwitch,
},
props: {
user: Object,
isNew: Boolean,
},
data() {
return {
createUserDir: false,
originalUserScope: ".",
sourceList: [],
availableSources: [],
selectedSources: [],
passwordRef: "",
};
},
async mounted() {
if (!this.stateUser.permissions.admin) {
this.sourceList = this.user.scopes || [];
} else {
this.sourceList = await settingsApi.get("sources");
}
this.user.password = this.user.password || "";
this.selectedSources = this.user.scopes || [];
this.availableSources = this.sourceList.filter(
(s) => !this.selectedSources.some((sel) => sel.name === s.name)
);
if (this.isNew && this.availableSources.length) {
const newSource = this.availableSources.shift();
if (newSource) {
this.selectedSources.push(newSource);
this.emitUserUpdate();
}
}
},
watch: {
createUserDir(newVal) {
this.user.scopes = newVal ? { default: "" } : this.originalUserScope;
this.emitUserUpdate();
},
stateUser() {
this.user.otpEnabled = state.user.otpEnabled;
this.emitUserUpdate();
},
},
computed: {
invalidPassword() {
const matching =
this.user.password != this.passwordRef && this.user.password.length > 0;
return matching;
},
passwordAvailable: () => passwordAvailable,
duplicateSources() {
const names = this.selectedSources.map((s) => s.name);
return names.filter((name, idx) => names.indexOf(name) !== idx);
},
hasMoreSources() {
return this.selectedSources.length < this.sourceList.length;
},
stateUser() {
return state.user;
},
passwordPlaceholder() {
return this.isNew ? "" : this.$t("settings.avoidChanges");
},
displayHomeDirectoryCheckbox() {
return this.isNew && this.createUserDir;
},
},
methods: {
newOTP() {
mutations.showHover({
name: "totp",
props: {
generate: true,
},
});
},
async submitUpdatePassword() {
event.preventDefault();
if (this.invalidPassword) {
notify.showError(this.$t("settings.passwordsDoNotMatch"));
return;
}
try {
await usersApi.update(this.user, ["password"]);
notify.showSuccess(this.$t("settings.userUpdated"));
} catch (e) {
notify.showError(e);
}
},
emitUserUpdate() {
this.$emit("update:user", { ...this.user, scopes: this.selectedSources });
},
emitUpdate() {
this.$emit("update:user", { ...this.user });
},
setUpdatePassword() {
this.$emit("update:updatePassword", true);
},
updateParent(input) {
const updatedScopes = this.selectedSources.map((source) =>
source.name === input.source.name
? { ...source, scope: input.input.target.value }
: source
);
this.selectedSources = updatedScopes;
this.emitUserUpdate();
},
addNewScopeSource(event) {
event.preventDefault();
if (this.hasMoreSources) {
this.selectedSources.push({ name: "", scope: "" });
this.emitUserUpdate();
}
},
removeScope(index) {
const removed = this.selectedSources.splice(index, 1)[0];
this.availableSources.push({ name: removed.name });
this.emitUserUpdate();
},
handleSourceChange(source, event, oldName) {
const newName = event.target.value;
this.availableSources = this.availableSources.filter((s) => s.name !== newName);
if (oldName && !this.availableSources.find((s) => s.name === oldName)) {
this.availableSources.push({ name: oldName });
}
source.name = newName;
this.emitUserUpdate();
},
updateUserField(field, value) {
this.user[field] = value;
this.emitUserUpdate();
},
},
};
</script>
<style>
.scope-list {
display: flex;
}
.scope-input {
width: 100%;
}
.no-height {
height: unset;
}
.material-size {
font-size: 1em !important;
}
</style>
+18 -19
View File
@@ -3,7 +3,7 @@
<div class="card-wrapper user-card">
<div
v-if="settingsAllowed && user.username !== 'anonymous'"
@click="navigateTo('/settings#profile-main')"
@click="navigateTo('/settings','#profile-main')"
class="inner-card"
>
<button
@@ -53,6 +53,7 @@
<i class="material-icons">ads_click</i>
</div>
<div
v-if="darkModeTogglePossible"
class="clickable"
:class="{ active: user?.darkMode }"
@click="toggleDarkMode"
@@ -140,7 +141,7 @@
<script>
import * as auth from "@/utils/auth";
import { signup, disableExternal, noAuth, loginPage, shareInfo } from "@/utils/constants";
import { globalVars, shareInfo } from "@/utils/constants";
import ProgressBar from "@/components/ProgressBar.vue";
import { state, getters, mutations } from "@/store"; // Import your custom store
import { getHumanReadableFilesize } from "@/utils/filesizes.js";
@@ -169,22 +170,23 @@ export default {
showSources: () => !getters.isShare(),
currentPrompt: () => getters.currentPrompt(),
active: () => getters.isSidebarVisible(),
signup: () => signup,
version: () => version,
commitSHA: () => commitSHA,
disableExternal: () => disableExternal,
canLogout: () => !noAuth && loginPage,
signup: () => globalVars.signup,
version: () => globalVars.version,
commitSHA: () => globalVars.commitSHA,
disableExternal: () => globalVars.disableExternal,
canLogout: () => !globalVars.noAuth && globalVars.loginPage,
route: () => state.route,
sourceInfo: () => state.sources.info,
activeSource: () => state.sources.current,
realtimeActive: () => state.realtimeActive,
darkModeTogglePossible: () => shareInfo.enforceDarkLightMode != "dark" && shareInfo.enforceDarkLightMode != "light",
},
watch: {
route() {
if (!getters.isLoggedIn()) {
return;
}
if (!this.isStickySidebar) {
if (!this.isStickySidebar && !shareInfo.singleFileShare) {
mutations.closeSidebar();
}
},
@@ -218,17 +220,13 @@ export default {
}
mutations.updateCurrentUser({ stickySidebar: !state.user.stickySidebar });
},
navigateTo(path) {
const hashIndex = path.indexOf("#");
if (hashIndex !== -1) {
// Extract the hash
const hash = path.substring(hashIndex);
// Remove the hash from the path
const cleanPath = path.substring(0, hashIndex);
this.$router.push({ path: cleanPath, hash: hash }, () => {});
} else {
this.$router.push({ path: path }, () => {});
}
navigateTo(path,hash) {
mutations.setPreviousHistoryItem({
name: state.req.name,
source: state.req.source,
path: state.req.path,
});
this.$router.push({ path: path, hash: hash });
mutations.closeHovers();
},
navigateToLogin() {
@@ -406,6 +404,7 @@ button.action {
.quick-toggles .active {
background-color: var(--primaryColor) !important;
border-radius: 10em;
color: white;
}
.inner-card {
Loaded 100 of 175 files, more files were not shown because too many files have changed in this diff. Show more